Optionally determine MIME types using libmagic

This commit is contained in:
Thomas Kolb 2013-01-17 23:17:38 +01:00
parent b77e4dcc8b
commit 9a9a49ff3a
2 changed files with 41 additions and 3 deletions

View File

@ -1,8 +1,11 @@
MAGIC_CFLAGS=-DHAVE_MAGIC
MAGIC_LIBS=-lmagic
CC=gcc
#CFLAGS+=-O2 -Wall -march=native -pedantic -std=c99 -D_POSIX_C_SOURCE=20120607L -D_XOPEN_SOURCE $(LUA_CFLAGS)
#CFLAGS+=-O2 -Wall -march=native -pedantic -std=c99 -D_POSIX_C_SOURCE=20120607L
CFLAGS+=-g -Wall -pedantic -std=c99 -D_POSIX_C_SOURCE=20120607L
LIBS=-lmicrohttpd
CFLAGS+=-g -Wall -pedantic -std=c99 -D_POSIX_C_SOURCE=20120607L $(MAGIC_CFLAGS)
LIBS=-lmicrohttpd $(MAGIC_LIBS)
TARGET=fileshare
SOURCE=main.c logger.c dirlisting.c util.c

37
main.c
View File

@ -13,6 +13,10 @@
#include <microhttpd.h>
#ifdef HAVE_MAGIC
#include <magic.h>
#endif
#include "logger.h"
#include "templates.h"
#include "dirlisting.h"
@ -31,6 +35,10 @@ struct MHD_Response *error403Response;
struct MHD_Response *error404Response;
struct MHD_Response *error500Response;
#ifdef HAVE_MAGIC
magic_t magicCookie;
#endif
int running = 1;
void request_completed(void *cls,
@ -101,7 +109,6 @@ static int connection_handler(void * cls,
return MHD_queue_response(connection, MHD_HTTP_FORBIDDEN, error403Response);
}
// check properties of the target file/dir
if(stat(connstate->localFileName, &(connstate->targetStat)) == -1) {
LOG(LVL_ERR, "Cannot stat %s: %s",
@ -128,6 +135,13 @@ static int connection_handler(void * cls,
connstate->targetStat.st_size,
fd);
#ifdef HAVE_MAGIC
// if libmagic is available, determine the correct MIME type for the file
const char *mimeType = magic_file(magicCookie, connstate->localFileName);
LOG(LVL_DEBUG, "MIME type for %s: %s", connstate->localFileName, mimeType);
MHD_add_response_header(response, MHD_HTTP_HEADER_CONTENT_TYPE, mimeType);
#endif
ret = MHD_queue_response(connection, MHD_HTTP_OK, response);
MHD_destroy_response(response);
return ret;
@ -209,6 +223,23 @@ int main(int argc, char ** argv) {
port = DEFAULT_PORT;
}
#ifdef HAVE_MAGIC
// initialize libmagic
magicCookie = magic_open(MAGIC_SYMLINK | MAGIC_MIME_TYPE);
if(!magicCookie) {
LOG(LVL_ERR, "Cannot allocate magic cookie");
} else {
// load the default database
if(magic_load(magicCookie, NULL) == -1) {
LOG(LVL_ERR, "Cannot load default magic database: %s", magic_error(magicCookie));
magic_close(magicCookie);
magicCookie = 0;
} else {
LOG(LVL_INFO, "libmagic initialized successfully.");
}
}
#endif
// create the static response for error pages
error403Response = MHD_create_response_from_data(
strlen(ERROR_403),
@ -258,6 +289,10 @@ int main(int argc, char ** argv) {
MHD_destroy_response(error404Response);
MHD_destroy_response(error500Response);
#ifdef HAVE_MAGIC
magic_close(magicCookie);
#endif
logger_shutdown();
return EXIT_SUCCESS;
}