Skip to main content

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index] [List Home]
[mosquitto-dev] http_dir & mimetype

Hello everyone,

I'm using mosquitto in a semi embedded project. It's basically a
javascript driven website, that uses a websockets connection to
mosquitto so the 'http_dir' feature comes in very handy as an additional
webserver can be omitted.

The website also uses stylesheets, but: »Starting with IE9 Standards
mode, style sheets will be ignored (not applied) unless they are
delivered with a "text/css" MIME type.« [ie]

libwebsockets already has a convenient function for this:
[lws_get_mimetype], so I've hacked together the attached patch.

As I'm by far not a competent c-programmer, I've also looked up how
lws is using the lws_get_mimetype function and found some utility
functions that support HTTP1 and HTTP2 in [test-server-http.c].
It seems like mosquitto supports older versions of libwebsockets, so
these utility functions are not always available?

I could try to adapt the functions of [test-server-http.c] to
websockets.c, but I'm not sure if it's a great help if a c greenhorn
hacks these functions together.

If the attached patch is of any use, please feel free to use it.

Greetings,
Benedikt

[ie]
https://msdn.microsoft.com/en-us/library/gg622939%28v=vs.85%29.aspx

[lws_get_mimetype]
https://libwebsockets.org/lws-api-doc-master/html/group__httpft.html#gab4da87a4800413f15e7aba649fb1d77c

[test-server-http.c]
https://github.com/warmcat/libwebsockets/blob/master/test-server/test-server-http.c#L309-L312
diff --git a/src/websockets.c b/src/websockets.c
index b44943d..3d93aaa 100644
--- a/src/websockets.c
+++ b/src/websockets.c
@@ -410,6 +410,8 @@ static int callback_http(struct libwebsocket_context *context,
 	size_t wlen;
 #endif
 	char *filename, *filename_canonical;
+	const char *mimetype;
+	unsigned char mimetype_header[1024];
 	unsigned char buf[4096];
 	struct stat filestat;
 
@@ -496,6 +498,7 @@ static int callback_http(struct libwebsocket_context *context,
 
 			_mosquitto_log_printf(NULL, MOSQ_LOG_DEBUG, "http serving file \"%s\".", filename);
 			u->fptr = fopen(filename, "rb");
+			mimetype = lws_get_mimetype(filename, NULL);
 			_mosquitto_free(filename);
 			if(!u->fptr){
 				libwebsockets_return_http_status(context, wsi, HTTP_STATUS_NOT_FOUND, NULL);
@@ -518,9 +521,15 @@ static int callback_http(struct libwebsocket_context *context,
 				return -1;
 			}
 
+			mimetype_header[0] = '\0';
+			if (mimetype && mimetype[0]) {
+				snprintf((char *)mimetype_header, 1024, "Content-Type: %s\r\n", mimetype);
+			}
+
 			buflen = snprintf((char *)buf, 4096, "HTTP/1.0 200 OK\r\n"
-												"Server: mosquitto\r\n"
+												"Server: mosquitto\r\n%s"
 												"Content-Length: %u\r\n\r\n",
+												mimetype_header,
 												(unsigned int)filestat.st_size);
             if(libwebsocket_write(wsi, buf, buflen, LWS_WRITE_HTTP) < 0){
 				fclose(u->fptr);

Back to the top