Browse files

whitespace five-oh paid a visit: wsclean -e -x -U -v $(find . -type f…

… -name '*.[ch]' )
  • Loading branch information...
1 parent 9209768 commit 00db6b8727d3c9939f36ae3c14ce80a3b7b79fc0 @GerHobbelt committed Jun 4, 2012
Showing with 1,400 additions and 1,404 deletions.
  1. +61 −61 examples/authentication.c
  2. +93 −93 examples/chat.c
  3. +2 −2 examples/hello.c
  4. +392 −392 examples/virtualhosting.c
  5. +82 −82 main.c
  6. +212 −217 mongoose.c
  7. +55 −54 mongoose.h
  8. +169 −169 mongoose_ex.c
  9. +8 −8 mongoose_ex.h
  10. +18 −18 mongoose_sys_porting.h
  11. +1 −1 selectable-socketpair
  12. +8 −8 test/embed.c
  13. +250 −250 test/unit_test.c
  14. +20 −20 testclient/testclient.c
  15. +1 −1 upskirt
  16. +28 −28 win32/resource.h
View
122 examples/authentication.c
@@ -27,10 +27,10 @@ static int
login_page(struct mg_connection *conn)
{
char name[100], pass[100], uri[100];
- const char *cookies[20];
- struct mg_request_info *ri = mg_get_request_info(conn);
- const char *qs = ri->query_string;
- size_t qslen = strlen(qs == NULL ? "" : qs);
+ const char *cookies[20];
+ struct mg_request_info *ri = mg_get_request_info(conn);
+ const char *qs = ri->query_string;
+ size_t qslen = strlen(qs == NULL ? "" : qs);
mg_get_var(qs, qslen, "name", name, ARRAY_SIZE(name));
mg_get_var(qs, qslen, "pass", pass, ARRAY_SIZE(pass));
@@ -44,15 +44,15 @@ login_page(struct mg_connection *conn)
* redirect back to the page where we have been redirected to login.
*/
if (strcmp(name, "admin") == 0 && strcmp(pass, "admin") == 0) {
- const char **cookie;
- for (cookie = &cookies[0]; *cookie; cookie++)
- {
- if (*cookie == NULL || sscanf(*cookie, "uri=%99s", uri) != 1)
- {
- (void) strcpy(uri, "/");
- break;
- }
- }
+ const char **cookie;
+ for (cookie = &cookies[0]; *cookie; cookie++)
+ {
+ if (*cookie == NULL || sscanf(*cookie, "uri=%99s", uri) != 1)
+ {
+ (void) strcpy(uri, "/");
+ break;
+ }
+ }
/* Set allow=yes cookie, which is expected by authorize() */
mg_printf(conn, "HTTP/1.1 301 Moved Permanently\r\n"
"Location: %s\r\n"
@@ -61,7 +61,7 @@ login_page(struct mg_connection *conn)
} else {
/* Print login page */
mg_printf(conn, "HTTP/1.1 200 OK\r\n"
- "Set-Cookie: allow=no; Path=/; Expires=Thu, 01 Jan 1970 00:00:01 GMT;\r\n" /* destroy cookie if it exists already */
+ "Set-Cookie: allow=no; Path=/; Expires=Thu, 01 Jan 1970 00:00:01 GMT;\r\n" /* destroy cookie if it exists already */
"content-Type: text/html\r\n\r\n");
mg_mark_end_of_header_transmission(conn);
mg_printf(conn, ""
@@ -72,26 +72,26 @@ login_page(struct mg_connection *conn)
"<input type=submit value=Login></input>"
"</form>");
}
- return 1;
+ return 1;
}
static int
authorize(struct mg_connection *conn)
{
const char *cookies[20];
- const char *cookie = NULL;
- int i;
- const struct mg_request_info *ri = mg_get_request_info(conn);
+ const char *cookie = NULL;
+ int i;
+ const struct mg_request_info *ri = mg_get_request_info(conn);
- mg_get_headers(cookies, ARRAY_SIZE(cookies), conn, "Cookie");
- for (i = 0; cookies[i]; i++)
- {
- if (strstr(cookies[i], "allow=") != NULL)
- {
- cookie = cookies[i];
- break;
- }
- }
+ mg_get_headers(cookies, ARRAY_SIZE(cookies), conn, "Cookie");
+ for (i = 0; cookies[i]; i++)
+ {
+ if (strstr(cookies[i], "allow=") != NULL)
+ {
+ cookie = cookies[i];
+ break;
+ }
+ }
if (!strcmp(ri->uri, "/login")) {
/* Always authorize accesses to the login page */
@@ -106,57 +106,57 @@ authorize(struct mg_connection *conn)
"Location: /login\r\n\r\n", ri->uri);
mg_mark_end_of_header_transmission(conn);
}
- return 1;
+ return 1;
}
static const struct srv_pages_config {
- enum mg_event event;
- const char *uri;
- int (*func)(struct mg_connection *conn);
+ enum mg_event event;
+ const char *uri;
+ int (*func)(struct mg_connection *conn);
} srv_pages_config[] = {
- {MG_NEW_REQUEST, "/login$", &login_page},
- {MG_NEW_REQUEST, "/**", &authorize},
- {0, NULL, NULL}
+ {MG_NEW_REQUEST, "/login$", &login_page},
+ {MG_NEW_REQUEST, "/**", &authorize},
+ {0, NULL, NULL}
};
static void *callback(enum mg_event event,
- struct mg_connection *conn)
+ struct mg_connection *conn)
{
- int i;
- const struct mg_request_info *ri = mg_get_request_info(conn);
+ int i;
+ const struct mg_request_info *ri = mg_get_request_info(conn);
- for (i = 0; srv_pages_config[i].uri != NULL; i++)
- {
- if (event == srv_pages_config[i].event &&
- (event == MG_HTTP_ERROR ||
- -1 < mg_match_prefix(srv_pages_config[i].uri, strlen(srv_pages_config[i].uri), ri->uri)))
- {
- if (srv_pages_config[i].func(conn) != 0)
- return "processed";
- }
- }
+ for (i = 0; srv_pages_config[i].uri != NULL; i++)
+ {
+ if (event == srv_pages_config[i].event &&
+ (event == MG_HTTP_ERROR ||
+ -1 < mg_match_prefix(srv_pages_config[i].uri, strlen(srv_pages_config[i].uri), ri->uri)))
+ {
+ if (srv_pages_config[i].func(conn) != 0)
+ return "processed";
+ }
+ }
- return NULL;
+ return NULL;
}
int
main(void)
{
- struct mg_context *ctx;
- const char *options[] = {"listening_ports", "8080"};
- const struct mg_user_class_t ucb = {
- callback, // User-defined callback function
- NULL // Arbitrary user-defined data
- };
+ struct mg_context *ctx;
+ const char *options[] = {"listening_ports", "8080"};
+ const struct mg_user_class_t ucb = {
+ callback, // User-defined callback function
+ NULL // Arbitrary user-defined data
+ };
- ctx = mg_start(&ucb, options);
+ ctx = mg_start(&ucb, options);
#if !defined(WIN32)
- pause();
+ pause();
#else
- while (!mg_get_stop_flag(ctx)) {
- mg_sleep(10);
- }
- mg_stop(ctx);
+ while (!mg_get_stop_flag(ctx)) {
+ mg_sleep(10);
+ }
+ mg_stop(ctx);
#endif
- return 0;
+ return 0;
}
View
186 examples/chat.c
@@ -96,10 +96,10 @@ static char *messages_to_json(long last_id) {
if (last_message_id - last_id > max_msgs) {
last_id = last_message_id - max_msgs;
}
- // If client is way up ahead, there's gone something terribly wrong!
+ // If client is way up ahead, there's gone something terribly wrong!
if (last_message_id - last_id < 0) {
len += mg_snq0printf(NULL, buf + len, sizeof(buf) - len,
- "{user: \x01ServerBot\x02, text: \x01We're pooped; you're at #%lu while I don't know about anything beyond #%lu; picking up from there...\x02, timestamp: %lu, id: %lu, force_id: %lu},",
+ "{user: \x01ServerBot\x02, text: \x01We're pooped; you're at #%lu while I don't know about anything beyond #%lu; picking up from there...\x02, timestamp: %lu, id: %lu, force_id: %lu},",
last_id, last_message_id, (unsigned long)time(NULL), last_message_id, last_message_id - max_msgs);
}
for (; last_id < last_message_id; last_id++) {
@@ -119,98 +119,98 @@ static char *messages_to_json(long last_id) {
pthread_rwlock_unlock(&rwlock);
if (len > 0)
{
- char *d;
- int i, j, in_string;
-
- // strip off trailing ',' --> output is '{...}' instead of '{...},'
- if (buf[len - 1] == ',')
- buf[--len] = 0;
- /*
- now encode the json output as embedded quotes and stuff would
- otherwise break the generated output.
-
- That's why we use the 'magicky' \x01 and \x02 as 'string delimiters'
- in that snprintf() up there... (we use mg_vsnq0printf() as we don't
- want any yammering to the server console when the buffer overflows)
- */
- d = malloc(len * 4); // not strdup! allow space for encoding
- for (j = i = in_string = 0; i < len; i++)
- {
- switch (buf[i])
- {
- case '\x01':
- // start of string:
- if (!in_string) {
- in_string = 1;
- d[j++] = '\'';
- continue;
- }
- goto encode_hex;
-
- case '\x02':
- // end of string:
- if (in_string) {
- in_string = 0;
- d[j++] = '\'';
- continue;
- }
- goto encode_hex;
-
- case '\'':
- case '"':
- // encode quotes in string
- assert(in_string);
- d[j++] = '\\';
- d[j++] = buf[i];
- continue;
-
- case '\n':
- if (in_string) {
- d[j++] = '\\';
- d[j++] = 'n';
- }
- else {
- d[j++] = buf[i];
- }
- continue;
-
- case '\r':
- if (in_string) {
- d[j++] = '\\';
- d[j++] = 'r';
- }
- else {
- d[j++] = buf[i];
- }
- continue;
-
- case '\t':
- if (in_string) {
- d[j++] = '\\';
- d[j++] = 't';
- }
- else {
- d[j++] = buf[i];
- }
- continue;
-
- default:
- if (buf[i] >= 32 && buf[i] < 127) {
- d[j++] = buf[i];
- continue;
- }
+ char *d;
+ int i, j, in_string;
+
+ // strip off trailing ',' --> output is '{...}' instead of '{...},'
+ if (buf[len - 1] == ',')
+ buf[--len] = 0;
+ /*
+ now encode the json output as embedded quotes and stuff would
+ otherwise break the generated output.
+
+ That's why we use the 'magicky' \x01 and \x02 as 'string delimiters'
+ in that snprintf() up there... (we use mg_vsnq0printf() as we don't
+ want any yammering to the server console when the buffer overflows)
+ */
+ d = malloc(len * 4); // not strdup! allow space for encoding
+ for (j = i = in_string = 0; i < len; i++)
+ {
+ switch (buf[i])
+ {
+ case '\x01':
+ // start of string:
+ if (!in_string) {
+ in_string = 1;
+ d[j++] = '\'';
+ continue;
+ }
+ goto encode_hex;
+
+ case '\x02':
+ // end of string:
+ if (in_string) {
+ in_string = 0;
+ d[j++] = '\'';
+ continue;
+ }
+ goto encode_hex;
+
+ case '\'':
+ case '"':
+ // encode quotes in string
+ assert(in_string);
+ d[j++] = '\\';
+ d[j++] = buf[i];
+ continue;
+
+ case '\n':
+ if (in_string) {
+ d[j++] = '\\';
+ d[j++] = 'n';
+ }
+ else {
+ d[j++] = buf[i];
+ }
+ continue;
+
+ case '\r':
+ if (in_string) {
+ d[j++] = '\\';
+ d[j++] = 'r';
+ }
+ else {
+ d[j++] = buf[i];
+ }
+ continue;
+
+ case '\t':
+ if (in_string) {
+ d[j++] = '\\';
+ d[j++] = 't';
+ }
+ else {
+ d[j++] = buf[i];
+ }
+ continue;
+
+ default:
+ if (buf[i] >= 32 && buf[i] < 127) {
+ d[j++] = buf[i];
+ continue;
+ }
encode_hex:
- j += mg_snq0printf(NULL, d + j, 5, "\\x%02x", buf[i] & 0xFF);
- continue;
-
- case 0:
- assert(!"Should never get here");
- break;
- }
- }
- d[j] = 0;
- len = j;
- return d;
+ j += mg_snq0printf(NULL, d + j, 5, "\\x%02x", buf[i] & 0xFF);
+ continue;
+
+ case 0:
+ assert(!"Should never get here");
+ break;
+ }
+ }
+ d[j] = 0;
+ len = j;
+ return d;
}
return NULL;
View
4 examples/hello.c
@@ -9,9 +9,9 @@ static void *callback(enum mg_event event,
if (event == MG_NEW_REQUEST) {
// Echo requested URI back to the client
mg_printf(conn, "HTTP/1.1 200 OK\r\n"
- "Content-Length: %u\r\n"
+ "Content-Length: %u\r\n"
"Content-Type: text/plain\r\n\r\n",
- (unsigned int)strlen(ri->uri));
+ (unsigned int)strlen(ri->uri));
mg_mark_end_of_header_transmission(conn);
mg_printf(conn, "%s", ri->uri);
return ""; // Mark as processed
View
784 examples/virtualhosting.c
@@ -49,19 +49,19 @@ static void WINCDECL signal_handler(int sig_num) {
}
static const char *default_options[] = {
- "document_root", "./test",
- "listening_ports", "8081", // "8081,8082s"
- //"ssl_certificate", "ssl_cert.pem",
- "num_threads", "5",
- "error_log_file", "./log/%Y/%m/tws_ib_if_srv-%Y%m%d.%H-IP-%[s]-%[p]-error.log",
- "access_log_file", "./log/%Y/%m/tws_ib_if_srv-%Y%m%d.%H-IP-%[s]-%[p]-access.log",
- "index_files", "default.html",
- "ssi_pattern", "**.html$|**.htm|**.shtml$|**.shtm$",
- "enable_keep_alive", "yes",
- //"ssi_marker", "{!--#,}",
- "keep_alive_timeout", "5",
-
- NULL
+ "document_root", "./test",
+ "listening_ports", "8081", // "8081,8082s"
+ //"ssl_certificate", "ssl_cert.pem",
+ "num_threads", "5",
+ "error_log_file", "./log/%Y/%m/tws_ib_if_srv-%Y%m%d.%H-IP-%[s]-%[p]-error.log",
+ "access_log_file", "./log/%Y/%m/tws_ib_if_srv-%Y%m%d.%H-IP-%[s]-%[p]-access.log",
+ "index_files", "default.html",
+ "ssi_pattern", "**.html$|**.htm|**.shtml$|**.shtm$",
+ "enable_keep_alive", "yes",
+ //"ssi_marker", "{!--#,}",
+ "keep_alive_timeout", "5",
+
+ NULL
};
#if defined(_WIN32)
@@ -79,8 +79,8 @@ void die(const char *fmt, ...) {
#if defined(_WIN32)
if (!error_dialog_shown_previously)
{
- MessageBoxA(NULL, msg, "Error", MB_OK);
- error_dialog_shown_previously = 1;
+ MessageBoxA(NULL, msg, "Error", MB_OK);
+ error_dialog_shown_previously = 1;
}
#else
fprintf(stderr, "%s\n", msg);
@@ -90,8 +90,8 @@ void die(const char *fmt, ...) {
}
static void show_usage_and_exit(const struct mg_context *ctx) {
- const char **names;
- int i;
+ const char **names;
+ int i;
fprintf(stderr, "Mongoose version %s (c) Sergey Lyubka\n", mg_version());
fprintf(stderr, "Usage:\n");
@@ -115,34 +115,34 @@ static void show_usage_and_exit(const struct mg_context *ctx) {
static void verify_document_root(const char *root) {
struct mgstat st;
- if (mg_stat(root, &st) != 0 || !st.is_directory) {
- die("Invalid root directory: [%s]: %s", root, mg_strerror(errno));
- }
+ if (mg_stat(root, &st) != 0 || !st.is_directory) {
+ die("Invalid root directory: [%s]: %s", root, mg_strerror(errno));
+ }
}
static void set_option(char **options, const char *name, const char *value) {
int i;
if (mg_get_option_long_name(name))
- name = mg_get_option_long_name(name);
+ name = mg_get_option_long_name(name);
- for (i = 0; i < MAX_OPTIONS * 2; i += 2) {
- // replace option value when it was set before: command line overrules config file, which overrules global defaults.
- if (options[i] == NULL) {
- options[i] = mg_strdup(name);
- options[i + 1] = mg_strdup(value);
- break;
- } else if (strcmp(options[i], name) == 0) {
- free(options[i + 1]);
- options[i + 1] = mg_strdup(value);
- break;
- }
+ for (i = 0; i < MAX_OPTIONS * 2; i += 2) {
+ // replace option value when it was set before: command line overrules config file, which overrules global defaults.
+ if (options[i] == NULL) {
+ options[i] = mg_strdup(name);
+ options[i + 1] = mg_strdup(value);
+ break;
+ } else if (strcmp(options[i], name) == 0) {
+ free(options[i + 1]);
+ options[i + 1] = mg_strdup(value);
+ break;
}
+ }
- if (i > MAX_OPTIONS * 2 - 2) {
- die("Too many options specified");
- }
+ if (i > MAX_OPTIONS * 2 - 2) {
+ die("Too many options specified");
+ }
}
static void process_command_line_arguments(char *argv[], char **options) {
@@ -166,15 +166,15 @@ static void process_command_line_arguments(char *argv[], char **options) {
fp = mg_fopen(config_file, "r");
- // If config file was set in command line and open failed, exit
- if (argv[1] != NULL && argv[2] == NULL && fp == NULL) {
- die("Cannot open config file %s: %s", config_file, mg_strerror(errno));
- }
+ // If config file was set in command line and open failed, exit
+ if (argv[1] != NULL && argv[2] == NULL && fp == NULL) {
+ die("Cannot open config file %s: %s", config_file, mg_strerror(errno));
+ }
- // use the default values for starters (so that all options have a known reasonable value):
- for (i = 0; default_options[i]; i += 2) {
- set_option(options, default_options[i], default_options[i+1]);
- }
+ // use the default values for starters (so that all options have a known reasonable value):
+ for (i = 0; default_options[i]; i += 2) {
+ set_option(options, default_options[i], default_options[i+1]);
+ }
// Load config file settings first
if (fp != NULL) {
@@ -247,7 +247,7 @@ struct t_user_arg {
unsigned short crc16(const void * data, unsigned long bitCount) {
unsigned short r = 0xFFFFu;
- unsigned long i;
+ unsigned long i;
for (i=0;i<bitCount;i++) {
unsigned short b = ((unsigned char*)data)[i>>3];
b >>= i & 0x7ul;
@@ -259,22 +259,22 @@ unsigned short crc16(const void * data, unsigned long bitCount) {
static int report_markdown_failure(struct mg_connection *conn, int is_inline_production, int response_code, const char *fmt, ...)
{
- va_list args;
-
- if (is_inline_production)
- {
- mg_printf(conn, "<h1 style=\"color: red;\">Error: %d - %s</h1>\n", response_code, mg_get_response_code_text(response_code));
- va_start(args, fmt);
- mg_vprintf(conn, fmt, args);
- va_end(args);
- }
- else
- {
- va_start(args, fmt);
- mg_vsend_http_error(conn, response_code, NULL, fmt, args);
- va_end(args);
- }
- return -1;
+ va_list args;
+
+ if (is_inline_production)
+ {
+ mg_printf(conn, "<h1 style=\"color: red;\">Error: %d - %s</h1>\n", response_code, mg_get_response_code_text(response_code));
+ va_start(args, fmt);
+ mg_vprintf(conn, fmt, args);
+ va_end(args);
+ }
+ else
+ {
+ va_start(args, fmt);
+ mg_vsend_http_error(conn, response_code, NULL, fmt, args);
+ va_end(args);
+ }
+ return -1;
}
@@ -283,137 +283,137 @@ int serve_a_markdown_page(struct mg_connection *conn, const struct mgstat *st, i
#define SD_READ_UNIT 1024
#define SD_OUTPUT_UNIT 64
- struct mg_request_info *ri = mg_get_request_info(conn);
- struct sd_buf *ib, *ob;
- int ret;
- unsigned int enabled_extensions = MKDEXT_TABLES | MKDEXT_FENCED_CODE | MKDEXT_EMAIL_FRIENDLY;
- unsigned int render_flags = 0; // HTML_SKIP_HTML | HTML_SKIP_STYLE | HTML_HARD_WRAP;
-
- struct sd_callbacks callbacks;
- struct html_renderopt options;
- struct sd_markdown *markdown;
-
- /* opening the file */
- FILE *in;
-
- assert(ri->phys_path);
- /* opening the file */
- in = mg_fopen(ri->phys_path, "r");
- if (!in)
- {
- return report_markdown_failure(conn, is_inline_production, 404, "Unable to open input file: [%s] %s", ri->uri, mg_strerror(errno));
- }
-
- /* reading everything */
- ib = sd_bufnew(SD_READ_UNIT);
- if (SD_BUF_OK != sd_bufgrow(ib, (size_t)st->size))
- {
- mg_fclose(in);
- sd_bufrelease(ib);
- return report_markdown_failure(conn, is_inline_production, 500, "Out of memory while loading Markdown input file: [%s]", ri->uri);
- }
- ret = fread(ib->data, 1, ib->asize, in);
- if (ret > 0)
- {
- ib->size += ret;
- mg_fclose(in);
- }
- else
- {
- mg_fclose(in);
- sd_bufrelease(ib);
- return report_markdown_failure(conn, is_inline_production, 500, "Cannot read from input file: [%s] %s", ri->uri, mg_strerror(errno));
- }
-
- /* performing markdown parsing */
- ob = sd_bufnew(SD_OUTPUT_UNIT);
-
- sdhtml_renderer(&callbacks, &options, render_flags);
- markdown = sd_markdown_new(enabled_extensions, 16, &callbacks, &options);
- if (!markdown)
- {
- sd_bufrelease(ib);
- sd_bufrelease(ob);
- return report_markdown_failure(conn, is_inline_production, 500, "Out of memory while processing Markdown input file: [%s]", ri->uri);
- }
- sd_markdown_render(ob, ib->data, ib->size, markdown);
- sd_markdown_free(markdown);
-
- if (!is_inline_production)
- {
- /* write the appropriate headers */
- char date[64], lm[64], etag[64], range[64];
- time_t curtime = time(NULL);
- const char *hdr;
- int64_t cl, r1, r2;
- int n;
-
- ri->status_code = 200;
-
- cl = ob->size;
-
- range[0] = '\0';
+ struct mg_request_info *ri = mg_get_request_info(conn);
+ struct sd_buf *ib, *ob;
+ int ret;
+ unsigned int enabled_extensions = MKDEXT_TABLES | MKDEXT_FENCED_CODE | MKDEXT_EMAIL_FRIENDLY;
+ unsigned int render_flags = 0; // HTML_SKIP_HTML | HTML_SKIP_STYLE | HTML_HARD_WRAP;
+
+ struct sd_callbacks callbacks;
+ struct html_renderopt options;
+ struct sd_markdown *markdown;
+
+ /* opening the file */
+ FILE *in;
+
+ assert(ri->phys_path);
+ /* opening the file */
+ in = mg_fopen(ri->phys_path, "r");
+ if (!in)
+ {
+ return report_markdown_failure(conn, is_inline_production, 404, "Unable to open input file: [%s] %s", ri->uri, mg_strerror(errno));
+ }
+
+ /* reading everything */
+ ib = sd_bufnew(SD_READ_UNIT);
+ if (SD_BUF_OK != sd_bufgrow(ib, (size_t)st->size))
+ {
+ mg_fclose(in);
+ sd_bufrelease(ib);
+ return report_markdown_failure(conn, is_inline_production, 500, "Out of memory while loading Markdown input file: [%s]", ri->uri);
+ }
+ ret = fread(ib->data, 1, ib->asize, in);
+ if (ret > 0)
+ {
+ ib->size += ret;
+ mg_fclose(in);
+ }
+ else
+ {
+ mg_fclose(in);
+ sd_bufrelease(ib);
+ return report_markdown_failure(conn, is_inline_production, 500, "Cannot read from input file: [%s] %s", ri->uri, mg_strerror(errno));
+ }
+
+ /* performing markdown parsing */
+ ob = sd_bufnew(SD_OUTPUT_UNIT);
+
+ sdhtml_renderer(&callbacks, &options, render_flags);
+ markdown = sd_markdown_new(enabled_extensions, 16, &callbacks, &options);
+ if (!markdown)
+ {
+ sd_bufrelease(ib);
+ sd_bufrelease(ob);
+ return report_markdown_failure(conn, is_inline_production, 500, "Out of memory while processing Markdown input file: [%s]", ri->uri);
+ }
+ sd_markdown_render(ob, ib->data, ib->size, markdown);
+ sd_markdown_free(markdown);
+
+ if (!is_inline_production)
+ {
+ /* write the appropriate headers */
+ char date[64], lm[64], etag[64], range[64];
+ time_t curtime = time(NULL);
+ const char *hdr;
+ int64_t cl, r1, r2;
+ int n;
+
+ ri->status_code = 200;
+
+ cl = ob->size;
+
+ range[0] = '\0';
#if 0
- // If Range: header specified, act accordingly
- r1 = r2 = 0;
- hdr = mg_get_header(conn, "Range");
- if (hdr != NULL && (n = parse_range_header(hdr, &r1, &r2)) > 0) {
- conn->request_info.status_code = 206;
- (void) fseeko(fp, (off_t) r1, SEEK_SET);
- cl = n == 2 ? r2 - r1 + 1: cl - r1;
- (void) mg_snprintf(conn, range, sizeof(range),
- "Content-Range: bytes "
- "%" INT64_FMT "-%"
- INT64_FMT "/%" INT64_FMT "\r\n",
- r1, r1 + cl - 1, stp->size);
- }
+ // If Range: header specified, act accordingly
+ r1 = r2 = 0;
+ hdr = mg_get_header(conn, "Range");
+ if (hdr != NULL && (n = parse_range_header(hdr, &r1, &r2)) > 0) {
+ conn->request_info.status_code = 206;
+ (void) fseeko(fp, (off_t) r1, SEEK_SET);
+ cl = n == 2 ? r2 - r1 + 1: cl - r1;
+ (void) mg_snprintf(conn, range, sizeof(range),
+ "Content-Range: bytes "
+ "%" INT64_FMT "-%"
+ INT64_FMT "/%" INT64_FMT "\r\n",
+ r1, r1 + cl - 1, stp->size);
+ }
#endif
- // Prepare Etag, Date, Last-Modified headers. Must be in UTC, according to
- // http://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.3
- mg_gmt_time_string(date, sizeof(date), &curtime);
- mg_gmt_time_string(lm, sizeof(lm), &st->mtime);
- (void) mg_snprintf(conn, etag, sizeof(etag), "%lx.%lx", (unsigned long) st->mtime, (unsigned long) st->size);
-
- (void) mg_printf(conn,
- "HTTP/1.1 %d %s\r\n"
- "Date: %s\r\n"
- "Last-Modified: %s\r\n"
- "Etag: \"%s\"\r\n"
- "Content-Type: text/html\r\n"
- "Content-Length: %" INT64_FMT "\r\n"
- "Connection: %s\r\n"
- // "Accept-Ranges: bytes\r\n"
- "%s\r\n"
- , ri->status_code, mg_get_response_code_text(ri->status_code)
- , date, lm, etag
- , cl
- , mg_suggest_connection_header(conn)
- , range
- );
- mg_mark_end_of_header_transmission(conn);
-
- ret = (int)cl;
- if (strcmp(ri->request_method, "HEAD") != 0) {
- ret = mg_write(conn, ob->data, (size_t)cl);
- }
- }
- else
- {
- ret = mg_write(conn, ob->data, ob->size);
- }
-
- /* cleanup */
- sd_bufrelease(ib);
- sd_bufrelease(ob);
-
- return ret;
+ // Prepare Etag, Date, Last-Modified headers. Must be in UTC, according to
+ // http://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.3
+ mg_gmt_time_string(date, sizeof(date), &curtime);
+ mg_gmt_time_string(lm, sizeof(lm), &st->mtime);
+ (void) mg_snprintf(conn, etag, sizeof(etag), "%lx.%lx", (unsigned long) st->mtime, (unsigned long) st->size);
+
+ (void) mg_printf(conn,
+ "HTTP/1.1 %d %s\r\n"
+ "Date: %s\r\n"
+ "Last-Modified: %s\r\n"
+ "Etag: \"%s\"\r\n"
+ "Content-Type: text/html\r\n"
+ "Content-Length: %" INT64_FMT "\r\n"
+ "Connection: %s\r\n"
+ // "Accept-Ranges: bytes\r\n"
+ "%s\r\n"
+ , ri->status_code, mg_get_response_code_text(ri->status_code)
+ , date, lm, etag
+ , cl
+ , mg_suggest_connection_header(conn)
+ , range
+ );
+ mg_mark_end_of_header_transmission(conn);
+
+ ret = (int)cl;
+ if (strcmp(ri->request_method, "HEAD") != 0) {
+ ret = mg_write(conn, ob->data, (size_t)cl);
+ }
+ }
+ else
+ {
+ ret = mg_write(conn, ob->data, ob->size);
+ }
+
+ /* cleanup */
+ sd_bufrelease(ib);
+ sd_bufrelease(ob);
+
+ return ret;
}
/*
-Ths bit of code shows how one can go about providing something very much like
+Ths bit of code shows how one can go about providing something very much like
IP-based and/or Name-based Virtual Hosting.
When you have your local DNS (or hosts file for that matter) configured to
@@ -422,7 +422,7 @@ mongoose on your localhost and visit
http://127.0.0.2/
for an example of IP-based Virtual Hosting, or
http://localhost-9.lan/
-for an example of Host-based Virtual Hosting, you will see another website
+for an example of Host-based Virtual Hosting, you will see another website
located in ./documentation: the mongoose documentation pages.
If you visit
http://127.0.0.1/
@@ -434,38 +434,38 @@ instead you will visit the website located in ./test/
Off Topic: one can override other options on a per-connection / request basis
as well. This applies to all options which' values are fetched by
- mongoose through the internal get_conn_option() call - grep
- mongoose.c for that one if you like.
+ mongoose through the internal get_conn_option() call - grep
+ mongoose.c for that one if you like.
*/
// typedef const char * (*mg_option_get_callback_t)(struct mg_context *ctx, struct mg_connection *conn, const char *name);
static const char *option_get_callback(struct mg_context *ctx, struct mg_connection *conn, const char *name)
{
- // check local IP for IP-based Virtual Hosting & switch DocumentRoot for the connection accordingly:
- if (conn && !strcmp("document_root", name))
- {
- struct mg_request_info *request_info = mg_get_request_info(conn);
-
- if (/* IP-based Virtual Hosting */
- (!request_info->local_ip.is_ip6 &&
- request_info->local_ip.ip_addr.v4[0] == 127 &&
- request_info->local_ip.ip_addr.v4[1] == 0 &&
- request_info->local_ip.ip_addr.v4[2] == 0 &&
- request_info->local_ip.ip_addr.v4[3] == 2 /* 127.0.0.x where x == 2 */) ||
- /* Name-based Virtual Hosting */
- 0 < mg_match_prefix("localhost-9.lan*|fifi.lan*", -1, mg_get_header(conn, "Host")) /* e.g. 'localhost-9.lan:8081' or 'fifi.lan:8081' */)
- {
- static char docu_site_docroot[PATH_MAX] = "";
-
- if (!*docu_site_docroot)
- {
- // use the CTX-based get-option call so our recursive invocation
- // skips this bit of code as 'conn == NULL' then:
- mg_snprintf(NULL, docu_site_docroot, sizeof(docu_site_docroot), "%s/../documentation", mg_get_option(ctx, name));
- }
- return docu_site_docroot;
- }
- }
- return NULL; // let mongoose handle it by himself
+ // check local IP for IP-based Virtual Hosting & switch DocumentRoot for the connection accordingly:
+ if (conn && !strcmp("document_root", name))
+ {
+ struct mg_request_info *request_info = mg_get_request_info(conn);
+
+ if (/* IP-based Virtual Hosting */
+ (!request_info->local_ip.is_ip6 &&
+ request_info->local_ip.ip_addr.v4[0] == 127 &&
+ request_info->local_ip.ip_addr.v4[1] == 0 &&
+ request_info->local_ip.ip_addr.v4[2] == 0 &&
+ request_info->local_ip.ip_addr.v4[3] == 2 /* 127.0.0.x where x == 2 */) ||
+ /* Name-based Virtual Hosting */
+ 0 < mg_match_prefix("localhost-9.lan*|fifi.lan*", -1, mg_get_header(conn, "Host")) /* e.g. 'localhost-9.lan:8081' or 'fifi.lan:8081' */)
+ {
+ static char docu_site_docroot[PATH_MAX] = "";
+
+ if (!*docu_site_docroot)
+ {
+ // use the CTX-based get-option call so our recursive invocation
+ // skips this bit of code as 'conn == NULL' then:
+ mg_snprintf(NULL, docu_site_docroot, sizeof(docu_site_docroot), "%s/../documentation", mg_get_option(ctx, name));
+ }
+ return docu_site_docroot;
+ }
+ }
+ return NULL; // let mongoose handle it by himself
}
@@ -481,45 +481,45 @@ static void *event_callback(enum mg_event event, struct mg_connection *conn) {
if (event == MG_INIT0)
{
- verify_document_root(mg_get_conn_option(conn, "document_root"));
- return (void *)1;
+ verify_document_root(mg_get_conn_option(conn, "document_root"));
+ return (void *)1;
}
#if defined(_WIN32)
- if (event == MG_EVENT_LOG &&
- strstr(request_info->log_message, "cannot bind to") &&
- !strcmp(request_info->log_severity, "error"))
+ if (event == MG_EVENT_LOG &&
+ strstr(request_info->log_message, "cannot bind to") &&
+ !strcmp(request_info->log_severity, "error"))
{
- if (!error_dialog_shown_previously)
- {
- MessageBoxA(NULL, request_info->log_message, "Error", MB_OK);
- error_dialog_shown_previously = 1;
- }
- return 0;
+ if (!error_dialog_shown_previously)
+ {
+ MessageBoxA(NULL, request_info->log_message, "Error", MB_OK);
+ error_dialog_shown_previously = 1;
+ }
+ return 0;
}
#endif
#if 0
if (event == MG_EXIT_CLIENT_CONN && !request_info->request_method && !request_info->uri)
{
- printf("Boom?\n");
+ printf("Boom?\n");
}
#endif
if (event == MG_SSI_INCLUDE_REQUEST || event == MG_NEW_REQUEST) {
- struct mgstat st;
- int file_found;
+ struct mgstat st;
+ int file_found;
- assert(request_info->phys_path);
- file_found = (0 == mg_stat(request_info->phys_path, &st) && !st.is_directory);
- if (file_found) {
- // are we looking for HTML output of MarkDown file?
+ assert(request_info->phys_path);
+ file_found = (0 == mg_stat(request_info->phys_path, &st) && !st.is_directory);
+ if (file_found) {
+ // are we looking for HTML output of MarkDown file?
if (mg_match_prefix("**.md$|**.wiki$", -1, request_info->phys_path) > 0) {
- serve_a_markdown_page(conn, &st, (event == MG_SSI_INCLUDE_REQUEST));
- return "";
- }
- return NULL; // let mongoose handle the default of 'file exists'...
- }
+ serve_a_markdown_page(conn, &st, (event == MG_SSI_INCLUDE_REQUEST));
+ return "";
+ }
+ return NULL; // let mongoose handle the default of 'file exists'...
+ }
}
if (event != MG_NEW_REQUEST) {
@@ -608,120 +608,120 @@ static void *event_callback(enum mg_event event, struct mg_connection *conn) {
"Content-Type: text/plain; charset=utf-8\r\n\r\n");
mg_mark_end_of_header_transmission(conn);
- mg_printf(conn, "Received headers:\r\n");
- for (i = 0; i < request_info->num_headers; i++)
- {
- mg_printf(conn, "Header[%d]: '%s' = '%s'\r\n",
- i, request_info->http_headers[i].name, request_info->http_headers[i].value);
- }
- mg_printf(conn, "----- info bits ------\r\n");
- mg_printf(conn, "URL: [%s]\r\n", request_info->uri);
- mg_printf(conn, "Query: [%s]\r\n", request_info->query_string);
- mg_printf(conn, "Phys.Path: [%s]\r\n", request_info->phys_path);
- mg_printf(conn, "----- data? ------\r\n");
+ mg_printf(conn, "Received headers:\r\n");
+ for (i = 0; i < request_info->num_headers; i++)
+ {
+ mg_printf(conn, "Header[%d]: '%s' = '%s'\r\n",
+ i, request_info->http_headers[i].name, request_info->http_headers[i].value);
+ }
+ mg_printf(conn, "----- info bits ------\r\n");
+ mg_printf(conn, "URL: [%s]\r\n", request_info->uri);
+ mg_printf(conn, "Query: [%s]\r\n", request_info->query_string);
+ mg_printf(conn, "Phys.Path: [%s]\r\n", request_info->phys_path);
+ mg_printf(conn, "----- data? ------\r\n");
if (!strcmp(request_info->request_method, "POST")) {
long int dataSize = atol(contentLength);
#if 0
- int bufferSize = (dataSize > 1024 * 1024 ? 1024 * 1024 : (int)dataSize);
+ int bufferSize = (dataSize > 1024 * 1024 ? 1024 * 1024 : (int)dataSize);
#else
- int bufferSize = (int)dataSize;
+ int bufferSize = (int)dataSize;
#endif
- long int gotSize = 0;
- int bufferFill = 0;
+ long int gotSize = 0;
+ int bufferFill = 0;
char * data = (char*) ((dataSize>0) ? malloc(bufferSize) : 0);
if (data) {
- mg_set_non_blocking_mode(mg_get_socket(conn), 1);
- {
- const int tcpbuflen = 1 * 1024 * 1024;
+ mg_set_non_blocking_mode(mg_get_socket(conn), 1);
+ {
+ const int tcpbuflen = 1 * 1024 * 1024;
- mg_setsockopt(mg_get_socket(conn), SOL_SOCKET, SO_RCVBUF, (const void *)&tcpbuflen, sizeof(tcpbuflen));
- mg_setsockopt(mg_get_socket(conn), SOL_SOCKET, SO_SNDBUF, (const void *)&tcpbuflen, sizeof(tcpbuflen));
- }
+ mg_setsockopt(mg_get_socket(conn), SOL_SOCKET, SO_RCVBUF, (const void *)&tcpbuflen, sizeof(tcpbuflen));
+ mg_setsockopt(mg_get_socket(conn), SOL_SOCKET, SO_SNDBUF, (const void *)&tcpbuflen, sizeof(tcpbuflen));
+ }
while (gotSize < dataSize && !mg_get_stop_flag(ctx)) {
- int gotNow = 0;
- // check whether there's anything available:
- fd_set read_set;
- struct timeval tv;
- int max_fd;
-
- FD_ZERO(&read_set);
- max_fd = -1;
-
- tv.tv_sec = 1;
- tv.tv_usec = 0;
-
- while (mg_get_stop_flag(ctx) == 0)
- {
- struct timeval tv2 = tv;
-
- FD_ZERO(&read_set);
- max_fd = -1;
-
- // Add listening sockets to the read set
- mg_FD_SET(mg_get_socket(conn), &read_set, &max_fd);
- if (select(max_fd + 1, &read_set, NULL, NULL, &tv2) < 0)
- {
- // signal a fatal failure:
- // clear the handles sets to prevent 'surprises' from processing these a second time (below):
- FD_ZERO(&read_set);
- max_fd = -1;
- assert(!"Should never get here");
- mg_send_http_error(conn, 579, NULL, "select() failure"); // internal error in our custom handler
- break;
- }
- else
- {
- if (mg_FD_ISSET(mg_get_socket(conn), &read_set))
- {
- break;
- }
- max_fd = -1;
- }
- }
-
- if (max_fd >= 0)
- {
- // use mg_pull() instead when you're accessing custom protocol sockets
- long int len = dataSize - gotSize;
- unsigned long int readLen = 0;
- if (len > bufferSize - bufferFill)
- len = bufferSize - bufferFill;
- gotNow = mg_read(conn, data + bufferFill, len);
- if (gotNow > 0)
- {
- bufferFill += gotNow;
- if (bufferFill == bufferSize && bufferSize != dataSize)
- {
- bufferFill = mg_write(conn, data, bufferSize);
- if (bufferFill < 0)
- {
- mg_send_http_error(conn, 579, NULL, "POST /_echo: write error at dataSize=%lu, gotNow=%u, gotSize=%lu\n", dataSize, gotNow, gotSize);
- break;
- }
- bufferFill = bufferSize - bufferFill;
- }
- }
- }
-
- if (gotNow == 0)
- {
- DEBUG_TRACE(("POST /_echo: ***CLOSE*** at dataSize=%lu, gotNow=%u, gotSize=%lu\n", dataSize, gotNow, gotSize));
- break;
- }
- gotSize += gotNow;
+ int gotNow = 0;
+ // check whether there's anything available:
+ fd_set read_set;
+ struct timeval tv;
+ int max_fd;
+
+ FD_ZERO(&read_set);
+ max_fd = -1;
+
+ tv.tv_sec = 1;
+ tv.tv_usec = 0;
+
+ while (mg_get_stop_flag(ctx) == 0)
+ {
+ struct timeval tv2 = tv;
+
+ FD_ZERO(&read_set);
+ max_fd = -1;
+
+ // Add listening sockets to the read set
+ mg_FD_SET(mg_get_socket(conn), &read_set, &max_fd);
+ if (select(max_fd + 1, &read_set, NULL, NULL, &tv2) < 0)
+ {
+ // signal a fatal failure:
+ // clear the handles sets to prevent 'surprises' from processing these a second time (below):
+ FD_ZERO(&read_set);
+ max_fd = -1;
+ assert(!"Should never get here");
+ mg_send_http_error(conn, 579, NULL, "select() failure"); // internal error in our custom handler
+ break;
+ }
+ else
+ {
+ if (mg_FD_ISSET(mg_get_socket(conn), &read_set))
+ {
+ break;
+ }
+ max_fd = -1;
+ }
+ }
+
+ if (max_fd >= 0)
+ {
+ // use mg_pull() instead when you're accessing custom protocol sockets
+ long int len = dataSize - gotSize;
+ unsigned long int readLen = 0;
+ if (len > bufferSize - bufferFill)
+ len = bufferSize - bufferFill;
+ gotNow = mg_read(conn, data + bufferFill, len);
+ if (gotNow > 0)
+ {
+ bufferFill += gotNow;
+ if (bufferFill == bufferSize && bufferSize != dataSize)
+ {
+ bufferFill = mg_write(conn, data, bufferSize);
+ if (bufferFill < 0)
+ {
+ mg_send_http_error(conn, 579, NULL, "POST /_echo: write error at dataSize=%lu, gotNow=%u, gotSize=%lu\n", dataSize, gotNow, gotSize);
+ break;
+ }
+ bufferFill = bufferSize - bufferFill;
+ }
+ }
+ }
+
+ if (gotNow == 0)
+ {
+ DEBUG_TRACE(("POST /_echo: ***CLOSE*** at dataSize=%lu, gotNow=%u, gotSize=%lu\n", dataSize, gotNow, gotSize));
+ break;
+ }
+ gotSize += gotNow;
+ }
+ mg_set_non_blocking_mode(mg_get_socket(conn), 0);
+ //mg_write(conn, data, gotSize);
+ if (bufferFill > 0 && mg_get_stop_flag(ctx) == 0)
+ {
+ int wlen = mg_write(conn, data, bufferFill);
+ if (bufferFill != wlen)
+ {
+ mg_send_http_error(conn, 580, NULL, "POST /_echo: ***ERR*** at dataSize=%lu, gotSize=%lu, wlen=%d\n", dataSize, gotSize, wlen); // internal error in our custom handler
+ }
}
- mg_set_non_blocking_mode(mg_get_socket(conn), 0);
- //mg_write(conn, data, gotSize);
- if (bufferFill > 0 && mg_get_stop_flag(ctx) == 0)
- {
- int wlen = mg_write(conn, data, bufferFill);
- if (bufferFill != wlen)
- {
- mg_send_http_error(conn, 580, NULL, "POST /_echo: ***ERR*** at dataSize=%lu, gotSize=%lu, wlen=%d\n", dataSize, gotSize, wlen); // internal error in our custom handler
- }
- }
free(data);
}
} else {
@@ -732,14 +732,14 @@ static void *event_callback(enum mg_event event, struct mg_connection *conn) {
}
else
{
- int file_found;
- struct mgstat fst;
+ int file_found;
+ struct mgstat fst;
- assert(request_info->phys_path);
- file_found = (0 == mg_stat(request_info->phys_path, &fst) && !fst.is_directory);
- if (file_found) {
- return NULL; // let mongoose handle the default of 'file exists'...
- }
+ assert(request_info->phys_path);
+ file_found = (0 == mg_stat(request_info->phys_path, &fst) && !fst.is_directory);
+ if (file_found) {
+ return NULL; // let mongoose handle the default of 'file exists'...
+ }
#ifdef _WIN32
// Send the systray icon as favicon
@@ -757,17 +757,17 @@ static void *event_callback(enum mg_event event, struct mg_connection *conn) {
request_info->status_code = 200;
(void) mg_printf(conn,
- "HTTP/1.1 200 OK\r\n"
- "Content-Type: image/x-icon\r\n"
- "Cache-Control: no-cache\r\n"
- "Content-Length: %u\r\n"
- "Connection: close\r\n\r\n", (unsigned int)len);
+ "HTTP/1.1 200 OK\r\n"
+ "Content-Type: image/x-icon\r\n"
+ "Cache-Control: no-cache\r\n"
+ "Content-Length: %u\r\n"
+ "Connection: close\r\n\r\n", (unsigned int)len);
mg_mark_end_of_header_transmission(conn);
if (len != mg_write(conn, data, len))
- {
+ {
mg_send_http_error(conn, 580, NULL, "not all data was written to the socket (len: %u)", (unsigned int)len); // internal error in our custom handler or client closed connection prematurely
- }
+ }
return (void *)1;
}
#endif
@@ -782,49 +782,49 @@ static BOOL WINAPI mg_win32_break_handler(DWORD signal_type)
{
switch(signal_type)
{
- // Handle the CTRL-C signal.
- case CTRL_C_EVENT:
- // CTRL-CLOSE: confirm that the user wants to exit.
- case CTRL_CLOSE_EVENT:
- case CTRL_BREAK_EVENT:
- exit_flag = 1000 + signal_type;
- //mg_signal_stop(ctx);
- return TRUE;
-
- // Pass other signals to the next handler.
- case CTRL_LOGOFF_EVENT:
- case CTRL_SHUTDOWN_EVENT:
- default:
- return FALSE;
+ // Handle the CTRL-C signal.
+ case CTRL_C_EVENT:
+ // CTRL-CLOSE: confirm that the user wants to exit.
+ case CTRL_CLOSE_EVENT:
+ case CTRL_BREAK_EVENT:
+ exit_flag = 1000 + signal_type;
+ //mg_signal_stop(ctx);
+ return TRUE;
+
+ // Pass other signals to the next handler.
+ case CTRL_LOGOFF_EVENT:
+ case CTRL_SHUTDOWN_EVENT:
+ default:
+ return FALSE;
}
}
#endif
static void start_mongoose(int argc, char *argv[]) {
- char *options[MAX_OPTIONS * 2] = { NULL };
- int i;
- struct mg_user_class_t userdef = {
- &event_callback,
- 0,
- 0,
- 0,
- option_get_callback
- };
-
- /* Edit passwords file if -A option is specified */
- if (argc > 1 && argv[1][0] == '-' && argv[1][1] == 'A') {
- if (argc != 6) {
- show_usage_and_exit(ctx);
- }
- exit(mg_modify_passwords_file(argv[2], argv[3], argv[4], argv[5]) ? EXIT_SUCCESS : EXIT_FAILURE);
- }
+ char *options[MAX_OPTIONS * 2] = { NULL };
+ int i;
+ struct mg_user_class_t userdef = {
+ &event_callback,
+ 0,
+ 0,
+ 0,
+ option_get_callback
+ };
- /* Show usage if -h or --help options are specified */
- if (argc == 2 && (!strcmp(argv[1], "-h") || !strcmp(argv[1], "--help"))) {
- show_usage_and_exit(ctx);
+ /* Edit passwords file if -A option is specified */
+ if (argc > 1 && argv[1][0] == '-' && argv[1][1] == 'A') {
+ if (argc != 6) {
+ show_usage_and_exit(ctx);
}
+ exit(mg_modify_passwords_file(argv[2], argv[3], argv[4], argv[5]) ? EXIT_SUCCESS : EXIT_FAILURE);
+ }
+
+ /* Show usage if -h or --help options are specified */
+ if (argc == 2 && (!strcmp(argv[1], "-h") || !strcmp(argv[1], "--help"))) {
+ show_usage_and_exit(ctx);
+ }
/* Update config based on command line arguments */
process_command_line_arguments(argv, options);
@@ -841,18 +841,18 @@ static void start_mongoose(int argc, char *argv[]) {
#if defined(_WIN32)
if (!SetConsoleCtrlHandler(mg_win32_break_handler, TRUE))
{
- die("Failed to set up the Win32 console Ctrl-Break handler.");
+ die("Failed to set up the Win32 console Ctrl-Break handler.");
}
#endif
/* prepare the user_arg */
{
- struct t_user_arg *pUser_arg = (struct t_user_arg *)calloc(1, sizeof(struct t_user_arg));
- if (!pUser_arg) {
- die("out of memory");
- }
- pthread_mutex_init(&pUser_arg->mutex, 0);
- userdef.user_data = pUser_arg;
+ struct t_user_arg *pUser_arg = (struct t_user_arg *)calloc(1, sizeof(struct t_user_arg));
+ if (!pUser_arg) {
+ die("out of memory");
+ }
+ pthread_mutex_init(&pUser_arg->mutex, 0);
+ userdef.user_data = pUser_arg;
}
/* Start Mongoose */
View
164 main.c
@@ -46,15 +46,15 @@ static void WINCDECL signal_handler(int sig_num) {
}
static const char *default_options[] = {
- "document_root", "./test",
- "listening_ports", "8081", // "8081,8082s"
- //"ssl_certificate", "ssl_cert.pem",
- "num_threads", "5",
- "error_log_file", "./log/%Y/%m/tws_ib_if_srv-%Y%m%d.%H-IP-%[s]-%[p]-error.log",
- "access_log_file", "./log/%Y/%m/tws_ib_if_srv-%Y%m%d.%H-IP-%[s]-%[p]-access.log",
- "keep_alive_timeout", "5",
-
- NULL
+ "document_root", "./test",
+ "listening_ports", "8081", // "8081,8082s"
+ //"ssl_certificate", "ssl_cert.pem",
+ "num_threads", "5",
+ "error_log_file", "./log/%Y/%m/tws_ib_if_srv-%Y%m%d.%H-IP-%[s]-%[p]-error.log",
+ "access_log_file", "./log/%Y/%m/tws_ib_if_srv-%Y%m%d.%H-IP-%[s]-%[p]-access.log",
+ "keep_alive_timeout", "5",
+
+ NULL
};
#if defined(_WIN32)
@@ -72,8 +72,8 @@ void die(const char *fmt, ...) {
#if defined(_WIN32)
if (!error_dialog_shown_previously)
{
- MessageBoxA(NULL, msg, "Error", MB_OK);
- error_dialog_shown_previously = 1;
+ MessageBoxA(NULL, msg, "Error", MB_OK);
+ error_dialog_shown_previously = 1;
}
#else
fprintf(stderr, "%s\n", msg);
@@ -83,8 +83,8 @@ void die(const char *fmt, ...) {
}
static void show_usage_and_exit(const struct mg_context *ctx) {
- const char **names;
- int i;
+ const char **names;
+ int i;
fprintf(stderr, "Mongoose version %s (c) Sergey Lyubka\n", mg_version());
fprintf(stderr, "Usage:\n");
@@ -108,34 +108,34 @@ static void show_usage_and_exit(const struct mg_context *ctx) {
static void verify_document_root(const char *root) {
struct mgstat st;
- if (mg_stat(root, &st) != 0 || !st.is_directory) {
- die("Invalid root directory: [%s]: %s", root, mg_strerror(errno));
- }
+ if (mg_stat(root, &st) != 0 || !st.is_directory) {
+ die("Invalid root directory: [%s]: %s", root, mg_strerror(errno));
+ }
}
static void set_option(char **options, const char *name, const char *value) {
int i;
if (mg_get_option_long_name(name))
- name = mg_get_option_long_name(name);
-
- for (i = 0; i < MAX_OPTIONS * 2; i += 2) {
- // replace option value when it was set before: command line overrules config file, which overrules global defaults.
- if (options[i] == NULL) {
- options[i] = mg_strdup(name);
- options[i + 1] = mg_strdup(value);
- break;
- } else if (strcmp(options[i], name) == 0) {
- free(options[i + 1]);
- options[i + 1] = mg_strdup(value);
- break;
- }
- }
+ name = mg_get_option_long_name(name);
- if (i > MAX_OPTIONS * 2 - 2) {
- die("Too many options specified");
+ for (i = 0; i < MAX_OPTIONS * 2; i += 2) {
+ // replace option value when it was set before: command line overrules config file, which overrules global defaults.
+ if (options[i] == NULL) {
+ options[i] = mg_strdup(name);
+ options[i + 1] = mg_strdup(value);
+ break;
+ } else if (strcmp(options[i], name) == 0) {
+ free(options[i + 1]);
+ options[i + 1] = mg_strdup(value);
+ break;
}
+ }
+
+ if (i > MAX_OPTIONS * 2 - 2) {
+ die("Too many options specified");
+ }
}
static void process_command_line_arguments(char *argv[], char **options) {
@@ -159,15 +159,15 @@ static void process_command_line_arguments(char *argv[], char **options) {
fp = mg_fopen(config_file, "r");
- // If config file was set in command line and open failed, exit
- if (argv[1] != NULL && argv[2] == NULL && fp == NULL) {
- die("Cannot open config file %s: %s", config_file, mg_strerror(errno));
- }
+ // If config file was set in command line and open failed, exit
+ if (argv[1] != NULL && argv[2] == NULL && fp == NULL) {
+ die("Cannot open config file %s: %s", config_file, mg_strerror(errno));
+ }
- // use the default values for starters (so that all options have a known reasonable value):
- for (i = 0; default_options[i]; i += 2) {
- set_option(options, default_options[i], default_options[i+1]);
- }
+ // use the default values for starters (so that all options have a known reasonable value):
+ for (i = 0; default_options[i]; i += 2) {
+ set_option(options, default_options[i], default_options[i+1]);
+ }
// Load config file settings first
if (fp != NULL) {
@@ -230,21 +230,21 @@ static void *event_callback(enum mg_event event, struct mg_connection *conn) {
if (event == MG_INIT0)
{
- verify_document_root(mg_get_conn_option(conn, "document_root"));
- return (void *)1;
+ verify_document_root(mg_get_conn_option(conn, "document_root"));
+ return (void *)1;
}
#if defined(_WIN32)
- if (event == MG_EVENT_LOG &&
- strstr(request_info->log_message, "cannot bind to") &&
- !strcmp(request_info->log_severity, "error"))
+ if (event == MG_EVENT_LOG &&
+ strstr(request_info->log_message, "cannot bind to") &&
+ !strcmp(request_info->log_severity, "error"))
{
- if (!error_dialog_shown_previously)
- {
- MessageBoxA(NULL, request_info->log_message, "Error", MB_OK);
- error_dialog_shown_previously = 1;
- }
- return 0;
+ if (!error_dialog_shown_previously)
+ {
+ MessageBoxA(NULL, request_info->log_message, "Error", MB_OK);
+ error_dialog_shown_previously = 1;
+ }
+ return 0;
}
#endif
@@ -254,14 +254,14 @@ static void *event_callback(enum mg_event event, struct mg_connection *conn) {
}
{
- int file_found;
- struct mgstat fst;
+ int file_found;
+ struct mgstat fst;
- assert(request_info->phys_path);
- file_found = (0 == mg_stat(request_info->phys_path, &fst) && !fst.is_directory);
- if (file_found) {
- return NULL; // let mongoose handle the default of 'file exists'...
- }
+ assert(request_info->phys_path);
+ file_found = (0 == mg_stat(request_info->phys_path, &fst) && !fst.is_directory);
+ if (file_found) {
+ return NULL; // let mongoose handle the default of 'file exists'...
+ }
#ifdef _WIN32
// Send the systray icon as favicon
@@ -287,9 +287,9 @@ static void *event_callback(enum mg_event event, struct mg_connection *conn) {
mg_mark_end_of_header_transmission(conn);
if (len != mg_write(conn, data, len))
- {
+ {
mg_send_http_error(conn, 580, NULL, "not all data was written to the socket (len: %u)", (unsigned int)len); // internal error in our custom handler or client closed connection prematurely
- }
+ }
return (void *)1;
}
#endif
@@ -310,7 +310,7 @@ static BOOL WINAPI mg_win32_break_handler(DWORD signal_type)
case CTRL_CLOSE_EVENT:
case CTRL_BREAK_EVENT:
exit_flag = 1000 + signal_type;
- //mg_signal_stop(ctx);
+ //mg_signal_stop(ctx);
return TRUE;
// Pass other signals to the next handler.
@@ -325,28 +325,28 @@ static BOOL WINAPI mg_win32_break_handler(DWORD signal_type)
static void start_mongoose(int argc, char *argv[]) {
- char *options[MAX_OPTIONS * 2] = { NULL };
- int i;
- struct mg_user_class_t userdef = {
- &event_callback,
- 0,
- 0,
- 0,
- 0
- };
-
- /* Edit passwords file if -A option is specified */
- if (argc > 1 && argv[1][0] == '-' && argv[1][1] == 'A') {
- if (argc != 6) {
- show_usage_and_exit(ctx);
- }
- exit(mg_modify_passwords_file(argv[2], argv[3], argv[4], argv[5]) ? EXIT_SUCCESS : EXIT_FAILURE);
- }
+ char *options[MAX_OPTIONS * 2] = { NULL };
+ int i;
+ struct mg_user_class_t userdef = {
+ &event_callback,
+ 0,
+ 0,
+ 0,
+ 0
+ };
- /* Show usage if -h or --help options are specified */
- if (argc == 2 && (!strcmp(argv[1], "-h") || !strcmp(argv[1], "--help"))) {
- show_usage_and_exit(ctx);
+ /* Edit passwords file if -A option is specified */
+ if (argc > 1 && argv[1][0] == '-' && argv[1][1] == 'A') {
+ if (argc != 6) {
+ show_usage_and_exit(ctx);
}
+ exit(mg_modify_passwords_file(argv[2], argv[3], argv[4], argv[5]) ? EXIT_SUCCESS : EXIT_FAILURE);
+ }
+
+ /* Show usage if -h or --help options are specified */
+ if (argc == 2 && (!strcmp(argv[1], "-h") || !strcmp(argv[1], "--help"))) {
+ show_usage_and_exit(ctx);
+ }
/* Update config based on command line arguments */
process_command_line_arguments(argv, options);
@@ -363,7 +363,7 @@ static void start_mongoose(int argc, char *argv[]) {
#if defined(_WIN32)
if (!SetConsoleCtrlHandler(mg_win32_break_handler, TRUE))
{
- die("Failed to set up the Win32 console Ctrl-Break handler.");
+ die("Failed to set up the Win32 console Ctrl-Break handler.");
}
#endif
View
429 mongoose.c
@@ -62,7 +62,7 @@ static CRITICAL_SECTION DisconnectExPtrCS;
static BOOL PASCAL dummy_disconnectEx(SOCKET sock, LPOVERLAPPED lpOverlapped, DWORD dwFlags, DWORD dwReserved)
{
- return 0;
+ return 0;
}
static LPFN_DISCONNECTEX get_DisconnectEx_funcptr(SOCKET sock)
@@ -205,35 +205,35 @@ struct ssl_func {
// of respective functions. The macros above (like SSL_connect()) are really
// just calling these functions indirectly via the pointer.
static struct ssl_func ssl_sw[] = {
- {"SSL_free", NULL},
- {"SSL_accept", NULL},
- {"SSL_connect", NULL},
- {"SSL_shutdown", NULL},
- {"SSL_read", NULL},
- {"SSL_write", NULL},
- {"SSL_get_error", NULL},
- {"SSL_set_fd", NULL},
- {"SSL_new", NULL},
- {"SSL_CTX_new", NULL},
- {"SSLv23_server_method", NULL},
- {"SSL_library_init", NULL},
- {"SSL_CTX_use_PrivateKey_file", NULL},
- {"SSL_CTX_use_certificate_file",NULL},
- {"SSL_CTX_set_default_passwd_cb",NULL},
- {"SSL_CTX_free", NULL},
- {"SSL_load_error_strings", NULL},
- {"SSL_CTX_use_certificate_chain_file", NULL},
- {NULL, NULL}
+ {"SSL_free", NULL},
+ {"SSL_accept", NULL},
+ {"SSL_connect", NULL},
+ {"SSL_shutdown", NULL},
+ {"SSL_read", NULL},
+ {"SSL_write", NULL},
+ {"SSL_get_error", NULL},
+ {"SSL_set_fd", NULL},
+ {"SSL_new", NULL},
+ {"SSL_CTX_new", NULL},
+ {"SSLv23_server_method", NULL},
+ {"SSL_library_init", NULL},
+ {"SSL_CTX_use_PrivateKey_file", NULL},
+ {"SSL_CTX_use_certificate_file", NULL},
+ {"SSL_CTX_set_default_passwd_cb", NULL},
+ {"SSL_CTX_free", NULL},
+ {"SSL_load_error_strings", NULL},
+ {"SSL_CTX_use_certificate_chain_file", NULL},
+ {NULL, NULL}
};
// Similar array as ssl_sw. These functions could be located in different lib.
static struct ssl_func crypto_sw[] = {
- {"CRYPTO_num_locks", NULL},
- {"CRYPTO_set_locking_callback", NULL},
- {"CRYPTO_set_id_callback", NULL},
- {"ERR_get_error", NULL},
- {"ERR_error_string", NULL},
- {NULL, NULL}
+ {"CRYPTO_num_locks", NULL},
+ {"CRYPTO_set_locking_callback", NULL},
+ {"CRYPTO_set_id_callback", NULL},
+ {"ERR_get_error", NULL},
+ {"ERR_error_string", NULL},
+ {NULL, NULL}
};
#endif // NO_SSL_DL
@@ -287,52 +287,52 @@ typedef enum {
} mg_option_index_t;
static const char *config_options[(NUM_OPTIONS + 1/* sentinel*/) * MG_ENTRIES_PER_CONFIG_OPTION] = {
- "C", "cgi_pattern", "**.cgi$|**.pl$|**.php$",
- "E", "cgi_environment", NULL,
- "G", "put_delete_passwords_file", NULL,
- "I", "cgi_interpreter", NULL,
- "P", "protect_uri", NULL,
- "R", "authentication_domain", "mydomain.com",
- "S", "ssi_pattern", "**.shtml$|**.shtm$",
- "", "ssi_marker", NULL,
- "a", "access_log_file", NULL,
- "c", "ssl_chain_file", NULL,
- "d", "enable_directory_listing", "yes",
- "e", "error_log_file", NULL,
- "g", "global_passwords_file", NULL,
- "i", "index_files", "index.html,index.htm,index.cgi,index.shtml,index.php",
- "k", "enable_keep_alive", "no",
- "K", "keep_alive_timeout", "5",
- "L", "socket_linger_timeout", "5",
- "l", "access_control_list", NULL,
- "M", "max_request_size", "16384",
- "m", "extra_mime_types", NULL,
- "p", "listening_ports", "8080",
- "r", "document_root", ".",
- "s", "ssl_certificate", NULL,
- "t", "num_threads", "10",
- "u", "run_as_user", NULL,
- "w", "url_rewrite_patterns", NULL,
+ "C", "cgi_pattern", "**.cgi$|**.pl$|**.php$",
+ "E", "cgi_environment", NULL,
+ "G", "put_delete_passwords_file", NULL,
+ "I", "cgi_interpreter", NULL,
+ "P", "protect_uri", NULL,
+ "R", "authentication_domain", "mydomain.com",
+ "S", "ssi_pattern", "**.shtml$|**.shtm$",
+ "", "ssi_marker", NULL,
+ "a", "access_log_file", NULL,
+ "c", "ssl_chain_file", NULL,
+ "d", "enable_directory_listing", "yes",
+ "e", "error_log_file", NULL,
+ "g", "global_passwords_file", NULL,
+ "i", "index_files", "index.html,index.htm,index.cgi,index.shtml,index.php",
+ "k", "enable_keep_alive", "no",
+ "K", "keep_alive_timeout", "5",
+ "L", "socket_linger_timeout", "5",
+ "l", "access_control_list", NULL,
+ "M", "max_request_size", "16384",
+ "m", "extra_mime_types", NULL,
+ "p", "listening_ports", "8080",
+ "r", "document_root", ".",
+ "s", "ssl_certificate", NULL,
+ "t", "num_threads", "10",
+ "u", "run_as_user", NULL,
+ "w", "url_rewrite_patterns", NULL,
NULL, NULL, NULL
};
struct mg_context {
- volatile int stop_flag; // Should we stop event loop
- SSL_CTX *ssl_ctx; // SSL context
- char *config[NUM_OPTIONS]; // Mongoose configuration parameters
+ volatile int stop_flag; // Should we stop event loop
+ SSL_CTX *ssl_ctx; // SSL context
+ char *config[NUM_OPTIONS]; // Mongoose configuration parameters
struct mg_user_class_t user_functions; // user-defined callbacks and data
struct socket *listening_sockets;
- volatile int num_threads; // Number of threads
- pthread_mutex_t mutex; // Protects (max|num)_threads
- pthread_cond_t cond; // Condvar for tracking workers terminations
+ volatile int num_threads; // Number of threads
+ pthread_mutex_t mutex; // Protects (max|num)_threads
+ pthread_cond_t cond; // Condvar for tracking workers terminations
- struct socket queue[20]; // Accepted sockets
- volatile int sq_head; // Head of the socket queue
- volatile int sq_tail; // Tail of the socket queue
- pthread_cond_t sq_full; // Signaled when socket is produced
- pthread_cond_t sq_empty; // Signaled when socket is consumed
+ struct socket queue[20]; // Accepted sockets
+ volatile int sq_head; // Head of the socket queue
+ volatile int sq_tail; // Tail of the socket queue
+ pthread_cond_t sq_full; // Signaled when socket is produced
+ pthread_cond_t sq_empty; // Signaled when socket is consumed
};
struct mg_connection {
@@ -418,14 +418,14 @@ static const char *call_user_conn_option_get(struct mg_connection *conn, const c
static int is_empty(const char *str)
{
- return !str || !*str;
+ return !str || !*str;
}
static int get_option_index(const char *name) {
int i;
- if (!name)
- return -1;
+ if (!name)
+ return -1;
for (i = 0; config_options[i] != NULL; i += MG_ENTRIES_PER_CONFIG_OPTION) {
if ((config_options[i][0] && strcmp(config_options[i], name) == 0) ||
strcmp(config_options[i + 1], name) == 0) {
@@ -476,25 +476,25 @@ static const char *get_option(struct mg_context *ctx, mg_option_index_t index) {
const char *rv;
assert(index >= 0 && index < NUM_OPTIONS);
rv = call_user_option_get(ctx, config_options[index * MG_ENTRIES_PER_CONFIG_OPTION + 1]);
- if (rv)
+ if (rv)
return rv;
if (ctx == NULL || ctx->config[index] == NULL)
return "";
- else
+ else
return ctx->config[index];
}
static const char *get_conn_option(struct mg_connection *conn, mg_option_index_t index) {
const char *rv;
assert(index >= 0 && index < NUM_OPTIONS);
rv = call_user_conn_option_get(conn, config_options[index * MG_ENTRIES_PER_CONFIG_OPTION + 1]);
- if (rv)
+ if (rv)
return rv;
if (conn == NULL || conn->ctx == NULL || conn->ctx->config[index] == NULL)
return "";
- else
+ else
return conn->ctx->config[index];
}
@@ -506,7 +506,7 @@ static char *sockaddr_to_string(char *buf, size_t len, const struct usa *usa) {
inet_ntop(usa->u.sa.sa_family, (usa->u.sa.sa_family == AF_INET ?
(void *) &usa->u.sin.sin_addr :
(void *) &usa->u.sin6.sin6_addr), buf, len);
-#elif defined(_WIN32) && defined(_WIN32_WINNT) && defined(_WIN32_WINNT_WINXP) && (_WIN32_WINNT >= _WIN32_WINNT_WINXP)
+#elif defined(_WIN32) && defined(_WIN32_WINNT) && defined(_WIN32_WINNT_WINXP) && (_WIN32_WINNT >= _WIN32_WINNT_WINXP)
// We use WSAAddressToString since it is supported on Windows XP and later
{
DWORD l = len;
@@ -938,27 +938,23 @@ int mg_write2log_raw(struct mg_connection *conn, const char *logfile, time_t tim
rv += fwrite(tbuf, sizeof(tbuf[0]), strftime(tbuf, ARRAY_SIZE(tbuf), "[%Y%m%dT%H%M%S] ", gmtime(&timestamp)), fp);
}
- rv += fprintf(fp,
- "[%s] ",
- severity);
+ rv += fprintf(fp, "[%s] ", severity);
if (conn != NULL)
{
char addr_buf[SOCKADDR_NTOA_BUFSIZE];
sockaddr_to_string(addr_buf, sizeof(addr_buf), &conn->client.rsa);
if (addr_buf[0])
{
- rv += fprintf(fp,
- "[client %s] ",
- addr_buf);
+ rv += fprintf(fp, "[client %s] ", addr_buf);
}
}
if (conn != NULL && conn->request_info.request_method != NULL && conn->request_info.uri != NULL)
{
rv += fprintf(fp, "%s %s: ",
- conn->request_info.request_method,
- conn->request_info.uri);
+ conn->request_info.request_method,
+ conn->request_info.uri);
}
rv += fprintf(fp, "%s\n", msg);
@@ -1321,10 +1317,10 @@ static const char *next_option(const char *list, struct vec *val,
// End of the list
val->ptr = 0;
val->len = 0;
- if (eq_val) {
- eq_val->ptr = 0;
- eq_val->len = 0;
- }
+ if (eq_val) {
+ eq_val->ptr = 0;
+ eq_val->len = 0;
+ }
list = NULL;
} else {
val->ptr = list;
@@ -1408,7 +1404,7 @@ static int should_keep_alive(struct mg_connection *conn) {
conn->request_info.status_code == 206 ||
conn->request_info.status_code == 100) &&
!mg_strcasecmp(get_conn_option(conn, ENABLE_KEEP_ALIVE), "yes") &&
- (header == NULL ?
+ (header == NULL ?
(http_version && !strcmp(http_version, "1.1")) :
!mg_strcasecmp(header, "keep-alive")));
}
@@ -2331,7 +2327,7 @@ void mg_mark_end_of_header_transmission(struct mg_connection *conn) {
}
int mg_have_headers_been_sent(const struct mg_connection *conn) {
- // When the HTTP header has been sent, it's no use to send more to override, so we
+ // When the HTTP header has been sent, it's no use to send more to override, so we
// do NOT check against what you might expect initially, i.e. 'if (conn && conn->num_bytes_sent >= 0)'
// but rather:
if (conn)
@@ -2625,7 +2621,7 @@ static struct mg_connection *mg_connect(struct mg_connection *conn,
closesocket(sock);
}
else {
- if (result) freeaddrinfo(result);
+ if (result) freeaddrinfo(result);
return newconn;
}
}
@@ -2728,47 +2724,47 @@ static const struct {
const char *mime_type;
size_t mime_type_len;
} builtin_mime_types[] = {
- {".html", 5, "text/html", 9},
- {".htm", 4, "text/html", 9},
- {".shtm", 5, "text/html", 9},
- {".shtml", 6, "text/html", 9},
- {".css", 4, "text/css", 8},
- {".js", 3, "application/x-javascript", 24},
- {".ico", 4, "image/x-icon", 12},
- {".gif", 4, "image/gif", 9},
- {".jpg", 4, "image/jpeg", 10},
- {".jpeg", 5, "image/jpeg", 10},
- {".png", 4, "image/png", 9},
- {".svg", 4, "image/svg+xml", 13},
- {".torrent", 8, "application/x-bittorrent", 24},
- {".wav", 4, "audio/x-wav", 11},
- {".mp3", 4, "audio/x-mp3", 11},
- {".mid", 4, "audio/mid", 9},
- {".m3u", 4, "audio/x-mpegurl", 15},
- {".ram", 4, "audio/x-pn-realaudio", 20},
- {".xml", 4, "text/xml", 8},
- {".xslt", 5, "application/xml", 15},
- {".ra", 3, "audio/x-pn-realaudio", 20},
- {".doc", 4, "application/msword", 19},
- {".exe", 4, "application/octet-stream", 24},
- {".zip", 4, "application/x-zip-compressed", 28},
- {".xls", 4, "application/excel", 17},
- {".tgz", 4, "application/x-tar-gz", 20},
- {".tar", 4, "application/x-tar", 17},
- {".gz", 3, "application/x-gunzip", 20},
- {".arj", 4, "application/x-arj-compressed", 28},
- {".rar", 4, "application/x-arj-compressed", 28},
- {".rtf", 4, "application/rtf", 15},
- {".pdf", 4, "application/pdf", 15},
- {".swf", 4, "application/x-shockwave-flash",29},
- {".mpg", 4, "video/mpeg", 10},
- {".mpeg", 5, "video/mpeg", 10},
- {".mp4", 4, "video/mp4", 9},
- {".m4v", 4, "video/x-m4v", 11},
- {".asf", 4, "video/x-ms-asf", 14},
- {".avi", 4, "video/x-msvideo", 15},
- {".bmp", 4, "image/bmp", 9},
- {NULL, 0, NULL, 0}
+ {".html", 5, "text/html", 9},
+ {".htm", 4, "text/html", 9},
+ {".shtm", 5, "text/html", 9},
+ {".shtml", 6, "text/html", 9},
+ {".css", 4, "text/css", 8},
+ {".js", 3, "application/x-javascript", 24},
+ {".ico", 4, "image/x-icon", 12},
+ {".gif", 4, "image/gif", 9},
+ {".jpg", 4, "image/jpeg", 10},
+ {".jpeg", 5, "image/jpeg", 10},
+ {".png", 4, "image/png", 9},
+ {".svg", 4, "image/svg+xml", 13},
+ {".torrent", 8, "application/x-bittorrent", 24},
+ {".wav", 4, "audio/x-wav", 11},
+ {".mp3", 4, "audio/x-mp3", 11},
+ {".mid", 4, "audio/mid", 9},
+ {".m3u", 4, "audio/x-mpegurl", 15},
+ {".ram", 4, "audio/x-pn-realaudio", 20},
+ {".xml", 4, "text/xml", 8},
+ {".xslt", 5, "application/xml", 15},
+ {".ra", 3, "audio/x-pn-realaudio", 20},
+ {".doc", 4, "application/msword", 19},
+ {".exe", 4, "application/octet-stream", 24},
+ {".zip", 4, "application/x-zip-compressed", 28},
+ {".xls", 4, "application/excel", 17},
+ {".tgz", 4, "application/x-tar-gz", 20},
+ {".tar", 4, "application/x-tar", 17},
+ {".gz", 3, "application/x-gunzip", 20},
+ {".arj", 4, "application/x-arj-compressed", 28},
+ {".rar", 4, "application/x-arj-compressed", 28},
+ {".rtf", 4, "application/rtf", 15},
+ {".pdf", 4, "application/pdf", 15},
+ {".swf", 4, "application/x-shockwave-flash", 29},
+ {".mpg", 4, "video/mpeg", 10},
+ {".mpeg", 5, "video/mpeg", 10},
+ {".mp4", 4, "video/mp4", 9},
+ {".m4v", 4, "video/x-m4v", 11},
+ {".asf", 4, "video/x-ms-asf", 14},
+ {".avi", 4, "video/x-msvideo", 15},
+ {".bmp", 4, "image/bmp", 9},
+ {NULL, 0, NULL, 0}
};
// Look at the "path" extension and figure what mime type it has.
@@ -4198,7 +4194,7 @@ static int do_ssi_include(struct mg_connection *conn, const char *ssi,
FILE *fp;
int rv;
- // sscanf() is safe here, since send_ssi_file() guarantees that tag is
+ // sscanf() is safe here, since send_ssi_file() guarantees that tag is
// no larger than PATH_MAX+64 bytes, so strlen(tag) is always < PATH_MAX+64.
if (sscanf(tag, " virtual=\"%[^\"]\"", file_name) == 1) {
// File name is relative to the webserver root
@@ -4232,8 +4228,8 @@ static int do_ssi_include(struct mg_connection *conn, const char *ssi,
rv = 2;
} else {
set_close_on_exec(fileno(fp));
- if (match_prefix(get_conn_option(conn, SSI_EXTENSIONS),
- -1,
+ if (match_prefix(get_conn_option(conn, SSI_EXTENSIONS),
+ -1,
conn->request_info.phys_path) > 0) {
if (send_ssi_file(conn, conn->request_info.phys_path, fp, include_level + 1) < 0)
rv = -1;
@@ -4268,6 +4264,7 @@ static int do_ssi_exec(struct mg_connection *conn, const char *tag) {
return rv;
}
}
+
#endif // !NO_POPEN
static const char *memfind(const char *haystack, size_t haysize, const char *needle, size_t needlesize)
@@ -4327,79 +4324,78 @@ static int send_ssi_file(struct mg_connection *conn, const char *path,
rlen += roff;
for(;;)
{
- const char *e;
- const char *s;
- if (rlen < taglen)
+ const char *e;
+ const char *s;
+ if (rlen < taglen)
+ {
+ if (b > buf)
{
- if (b > buf)
- {
- memmove(buf, b, rlen);
- }
- roff = rlen;
- break;
+ memmove(buf, b, rlen);
}
- s = memfind(b, rlen, ssi_start.ptr, taglen);
- if (!s)
+ roff = rlen;
+ break;
+ }
+ s = memfind(b, rlen, ssi_start.ptr, taglen);
+ if (!s)
+ {
+ if (rlen >= taglen && mg_write(conn, b, rlen - taglen + 1) != rlen - taglen + 1)
{
- if (rlen >= taglen && mg_write(conn, b, rlen - taglen + 1) != rlen - taglen + 1)
- {
- mg_send_http_error(conn, 580, NULL, "%s: not all data (len = %d) sent (%s)", __func__, rlen - taglen + 1, path);
- return -1;
- }
- memmove(buf, b + rlen - taglen + 1, taglen - 1);
- roff = taglen - 1;
- break;
+ mg_send_http_error(conn, 580, NULL, "%s: not all data (len = %d) sent (%s)", __func__, rlen - taglen + 1, path);
+ return -1;
}
- // flush part before start tag:
- if (s > b && mg_write(conn, b, s - b) != s - b)
+ memmove(buf, b + rlen - taglen + 1, taglen - 1);
+ roff = taglen - 1;
+ break;
+ }
+ // flush part before start tag:
+ if (s > b && mg_write(conn, b, s - b) != s - b)
+ {
+ mg_send_http_error(conn, 580, NULL, "%s: not all data (len = %d) sent (%s)", __func__, (int)(s - b), path);
+ return -1;
+ }
+ rlen -= s - b;
+ b = s;
+ s += taglen + 1;