#include "internal.h" static int call_user(int type, struct mg_connection *conn, void *p) { if (conn != NULL && conn->ctx != NULL) { conn->event.user_data = conn->ctx->user_data; conn->event.type = type; conn->event.event_param = p; conn->event.request_info = &conn->request_info; conn->event.conn = conn; } return conn == NULL || conn->ctx == NULL || conn->ctx->event_handler == NULL ? 0 : conn->ctx->event_handler(&conn->event); } static int mg_socketpair(sock_t sp[2]) { struct sockaddr_in sa; sock_t sock, ret = -1; socklen_t len = sizeof(sa); sp[0] = sp[1] = INVALID_SOCKET; (void) memset(&sa, 0, sizeof(sa)); sa.sin_family = AF_INET; sa.sin_port = htons(0); sa.sin_addr.s_addr = htonl(0x7f000001); if ((sock = socket(AF_INET, SOCK_STREAM, 0)) != INVALID_SOCKET && !bind(sock, (struct sockaddr *) &sa, len) && !listen(sock, 1) && !getsockname(sock, (struct sockaddr *) &sa, &len) && (sp[0] = socket(AF_INET, SOCK_STREAM, 6)) != -1 && !connect(sp[0], (struct sockaddr *) &sa, len) && (sp[1] = accept(sock,(struct sockaddr *) &sa, &len)) != INVALID_SOCKET) { set_close_on_exec(sp[0]); set_close_on_exec(sp[1]); ret = 0; } else { if (sp[0] != INVALID_SOCKET) closesocket(sp[0]); if (sp[1] != INVALID_SOCKET) closesocket(sp[1]); sp[0] = sp[1] = INVALID_SOCKET; } closesocket(sock); return ret; } static FILE *mg_fopen(const char *path, const char *mode) { #ifdef _WIN32 wchar_t wbuf[PATH_MAX], wmode[20]; to_unicode(path, wbuf, ARRAY_SIZE(wbuf)); MultiByteToWideChar(CP_UTF8, 0, mode, -1, wmode, ARRAY_SIZE(wmode)); return _wfopen(wbuf, wmode); #else return fopen(path, mode); #endif } // Print error message to the opened error log stream. static void cry(struct mg_connection *conn, const char *fmt, ...) { char buf[MG_BUF_LEN], src_addr[IP_ADDR_STR_LEN]; va_list ap; FILE *fp; time_t timestamp; va_start(ap, fmt); (void) vsnprintf(buf, sizeof(buf), fmt, ap); va_end(ap); // Do not lock when getting the callback value, here and below. // I suppose this is fine, since function cannot disappear in the // same way string option can. if (call_user(MG_EVENT_LOG, conn, buf) == 0) { fp = conn->ctx == NULL || conn->ctx->config[ERROR_LOG_FILE] == NULL ? NULL : fopen(conn->ctx->config[ERROR_LOG_FILE], "a+"); if (fp != NULL) { flockfile(fp); timestamp = time(NULL); sockaddr_to_string(src_addr, sizeof(src_addr), &conn->client.rsa); fprintf(fp, "[%010lu] [error] [client %s] ", (unsigned long) timestamp, src_addr); if (conn->request_info.request_method != NULL) { fprintf(fp, "%s %s: ", conn->request_info.request_method, conn->request_info.uri); } fprintf(fp, "%s", buf); fputc('\n', fp); funlockfile(fp); fclose(fp); } } } const char *mg_version(void) { return MONGOOSE_VERSION; } // HTTP 1.1 assumes keep alive if "Connection:" header is not set // This function must tolerate situations when connection info is not // set up, for example if request parsing failed. static int should_keep_alive(const struct mg_connection *conn) { const char *http_version = conn->request_info.http_version; const char *header = mg_get_header(conn, "Connection"); if (conn->must_close || conn->status_code == 401 || mg_strcasecmp(conn->ctx->config[ENABLE_KEEP_ALIVE], "yes") != 0 || (header != NULL && mg_strcasecmp(header, "keep-alive") != 0) || (header == NULL && http_version && strcmp(http_version, "1.1"))) { return 0; } return 1; } static const char *suggest_connection_header(const struct mg_connection *conn) { return should_keep_alive(conn) ? "keep-alive" : "close"; } static void send_http_error(struct mg_connection *conn, int status, const char *reason, const char *fmt, ...) { char buf[MG_BUF_LEN]; va_list ap; int len = 0; conn->status_code = status; buf[0] = '\0'; // Errors 1xx, 204 and 304 MUST NOT send a body if (status > 199 && status != 204 && status != 304) { len = mg_snprintf(buf, sizeof(buf), "Error %d: %s", status, reason); buf[len++] = '\n'; va_start(ap, fmt); len += mg_vsnprintf(buf + len, sizeof(buf) - len, fmt, ap); va_end(ap); } DEBUG_TRACE(("[%s]", buf)); if (call_user(MG_HTTP_ERROR, conn, (void *) (long) status) == 0) { mg_printf(conn, "HTTP/1.1 %d %s\r\n" "Content-Length: %d\r\n" "Connection: %s\r\n\r\n", status, reason, len, suggest_connection_header(conn)); conn->num_bytes_sent += mg_printf(conn, "%s", buf); } if (status >= 500) { conn->must_close = 1; } } // Return 1 if real file has been found, 0 otherwise static int convert_uri_to_file_name(struct mg_connection *conn, char *buf, size_t buf_len, struct file *filep) { struct vec a, b; const char *rewrite, *uri = conn->request_info.uri, *root = conn->ctx->config[DOCUMENT_ROOT]; char *p; int match_len; char gz_path[PATH_MAX]; char const* accept_encoding; // No filesystem access if (root == NULL) { return 0; } // Using buf_len - 1 because memmove() for PATH_INFO may shift part // of the path one byte on the right. // If document_root is NULL, leave the file empty. mg_snprintf(buf, buf_len - 1, "%s%s", root, uri); rewrite = conn->ctx->config[REWRITE]; while ((rewrite = next_option(rewrite, &a, &b)) != NULL) { if ((match_len = match_prefix(a.ptr, a.len, uri)) > 0) { mg_snprintf(buf, buf_len - 1, "%.*s%s", (int) b.len, b.ptr, uri + match_len); break; } } if (mg_stat(buf, filep)) { return 1; } // if we can't find the actual file, look for the file // with the same name but a .gz extension. If we find it, // use that and set the gzipped flag in the file struct // to indicate that the response need to have the content- // encoding: gzip header // we can only do this if the browser declares support if ((accept_encoding = mg_get_header(conn, "Accept-Encoding")) != NULL) { if (strstr(accept_encoding,"gzip") != NULL) { snprintf(gz_path, sizeof(gz_path), "%s.gz", buf); if (mg_stat(gz_path, filep)) { filep->gzipped = 1; return 1; } } } // Support PATH_INFO for CGI scripts. for (p = buf + strlen(root == NULL ? "" : root); *p != '\0'; p++) { if (*p == '/') { *p = '\0'; if (match_prefix(conn->ctx->config[CGI_EXTENSIONS], strlen(conn->ctx->config[CGI_EXTENSIONS]), buf) > 0 && mg_stat(buf, filep)) { // Shift PATH_INFO block one character right, e.g. // "/x.cgi/foo/bar\x00" => "/x.cgi\x00/foo/bar\x00" // conn->path_info is pointing to the local variable "path" declared // in handle_request(), so PATH_INFO is not valid after // handle_request returns. conn->path_info = p + 1; memmove(p + 2, p + 1, strlen(p + 1) + 1); // +1 is for trailing \0 p[1] = '/'; return 1; } else { *p = '/'; } } } return 0; } static void construct_etag(char *buf, size_t buf_len, const struct file *filep) { snprintf(buf, buf_len, "\"%lx.%" INT64_FMT "\"", (unsigned long) filep->modification_time, filep->size); } static void fclose_on_exec(FILE *fp) { if (fp != NULL) { #ifndef _WIN32 fcntl(fileno(fp), F_SETFD, FD_CLOEXEC); #endif } } static void handle_file_request(struct mg_connection *conn, const char *path, struct file *filep) { char date[64], lm[64], etag[64], range[64]; const char *msg = "OK", *hdr; time_t curtime = time(NULL); int64_t cl, r1, r2; struct vec mime_vec; int n; char gz_path[PATH_MAX]; char const* encoding = ""; FILE *fp; get_mime_type(conn->ctx, path, &mime_vec); cl = filep->size; conn->status_code = 200; range[0] = '\0'; // if this file is in fact a pre-gzipped file, rewrite its filename // it's important to rewrite the filename after resolving // the mime type from it, to preserve the actual file's type if (filep->gzipped) { snprintf(gz_path, sizeof(gz_path), "%s.gz", path); path = gz_path; encoding = "Content-Encoding: gzip\r\n"; } if ((fp = mg_fopen(path, "rb")) == NULL) { send_http_error(conn, 500, http_500_error, "fopen(%s): %s", path, strerror(ERRNO)); return; } fclose_on_exec(fp); // 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 && r1 >= 0 && r2 >= 0) { // actually, range requests don't play well with a pre-gzipped // file (since the range is specified in the uncmpressed space) if (filep->gzipped) { send_http_error(conn, 501, "Not Implemented", "range requests in gzipped files are not supported"); return; } conn->status_code = 206; cl = n == 2 ? (r2 > cl ? cl : r2) - r1 + 1: cl - r1; mg_snprintf(range, sizeof(range), "Content-Range: bytes " "%" INT64_FMT "-%" INT64_FMT "/%" INT64_FMT "\r\n", r1, r1 + cl - 1, filep->size); msg = "Partial Content"; } // Prepare Etag, Date, Last-Modified headers. Must be in UTC, according to // http://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.3 gmt_time_string(date, sizeof(date), &curtime); gmt_time_string(lm, sizeof(lm), &filep->modification_time); construct_etag(etag, sizeof(etag), filep); (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: %.*s\r\n" "Content-Length: %" INT64_FMT "\r\n" "Connection: %s\r\n" "Accept-Ranges: bytes\r\n" "%s%s%s\r\n", conn->status_code, msg, date, lm, etag, (int) mime_vec.len, mime_vec.ptr, cl, suggest_connection_header(conn), range, encoding, EXTRA_HTTP_HEADERS); if (strcmp(conn->request_info.request_method, "HEAD") != 0) { send_file_data(conn, fp, r1, cl); } fclose(fp); } void mg_send_file(struct mg_connection *conn, const char *path) { struct file file = STRUCT_FILE_INITIALIZER; if (mg_stat(path, &file)) { handle_file_request(conn, path, &file); } else { send_http_error(conn, 404, "Not Found", "%s", "File not found"); } } // For given directory path, substitute it to valid index file. // Return 0 if index file has been found, -1 if not found. // If the file is found, it's stats is returned in stp. static int substitute_index_file(struct mg_connection *conn, char *path, size_t path_len, struct file *filep) { const char *list = conn->ctx->config[INDEX_FILES]; struct file file = STRUCT_FILE_INITIALIZER; struct vec filename_vec; size_t n = strlen(path); int found = 0; // The 'path' given to us points to the directory. Remove all trailing // directory separator characters from the end of the path, and // then append single directory separator character. while (n > 0 && path[n - 1] == '/') { n--; } path[n] = '/'; // Traverse index files list. For each entry, append it to the given // path and see if the file exists. If it exists, break the loop while ((list = next_option(list, &filename_vec, NULL)) != NULL) { // Ignore too long entries that may overflow path buffer if (filename_vec.len > path_len - (n + 2)) continue; // Prepare full path to the index file mg_strlcpy(path + n + 1, filename_vec.ptr, filename_vec.len + 1); // Does it exist? if (mg_stat(path, &file)) { // Yes it does, break the loop *filep = file; found = 1; break; } } // If no index file exists, restore directory path if (!found) { path[n] = '\0'; } return found; } // Return True if we should reply 304 Not Modified. static int is_not_modified(const struct mg_connection *conn, const struct file *filep) { char etag[64]; const char *ims = mg_get_header(conn, "If-Modified-Since"); const char *inm = mg_get_header(conn, "If-None-Match"); construct_etag(etag, sizeof(etag), filep); return (inm != NULL && !mg_strcasecmp(etag, inm)) || (ims != NULL && filep->modification_time <= parse_date_string(ims)); } static void mkcol(struct mg_connection *conn, const char *path) { int rc, body_len; struct de de; memset(&de.file, 0, sizeof(de.file)); mg_stat(path, &de.file); if (de.file.modification_time) { send_http_error(conn, 405, "Method Not Allowed", "mkcol(%s): %s", path, strerror(ERRNO)); return; } body_len = conn->data_len - conn->request_len; if(body_len > 0) { send_http_error(conn, 415, "Unsupported media type", "mkcol(%s): %s", path, strerror(ERRNO)); return; } rc = mg_mkdir(path, 0755); if (rc == 0) { conn->status_code = 201; mg_printf(conn, "HTTP/1.1 %d Created\r\n\r\n", conn->status_code); } else if (rc == -1) { if(errno == EEXIST) send_http_error(conn, 405, "Method Not Allowed", "mkcol(%s): %s", path, strerror(ERRNO)); else if(errno == EACCES) send_http_error(conn, 403, "Forbidden", "mkcol(%s): %s", path, strerror(ERRNO)); else if(errno == ENOENT) send_http_error(conn, 409, "Conflict", "mkcol(%s): %s", path, strerror(ERRNO)); else send_http_error(conn, 500, http_500_error, "fopen(%s): %s", path, strerror(ERRNO)); } } static void put_file(struct mg_connection *conn, const char *path) { struct file file = STRUCT_FILE_INITIALIZER; FILE *fp; const char *range; int64_t r1, r2; int rc; conn->status_code = mg_stat(path, &file) ? 200 : 201; if ((rc = put_dir(path)) == 0) { mg_printf(conn, "HTTP/1.1 %d OK\r\n\r\n", conn->status_code); } else if (rc == -1) { send_http_error(conn, 500, http_500_error, "put_dir(%s): %s", path, strerror(ERRNO)); } else if ((fp = mg_fopen(path, "wb+")) == NULL) { fclose(fp); send_http_error(conn, 500, http_500_error, "fopen(%s): %s", path, strerror(ERRNO)); } else { fclose_on_exec(fp); range = mg_get_header(conn, "Content-Range"); r1 = r2 = 0; if (range != NULL && parse_range_header(range, &r1, &r2) > 0) { conn->status_code = 206; fseeko(fp, r1, SEEK_SET); } if (!forward_body_data(conn, fp, INVALID_SOCKET, NULL)) { conn->status_code = 500; } mg_printf(conn, "HTTP/1.1 %d OK\r\nContent-Length: 0\r\n\r\n", conn->status_code); fclose(fp); } } static void send_ssi_file(struct mg_connection *, const char *, FILE *, int); static void do_ssi_include(struct mg_connection *conn, const char *ssi, char *tag, int include_level) { char file_name[MG_BUF_LEN], path[PATH_MAX], *p; FILE *fp; // sscanf() is safe here, since send_ssi_file() also uses buffer // of size MG_BUF_LEN to get the tag. So strlen(tag) is always < MG_BUF_LEN. if (sscanf(tag, " virtual=\"%[^\"]\"", file_name) == 1) { // File name is relative to the webserver root (void) mg_snprintf(path, sizeof(path), "%s%c%s", conn->ctx->config[DOCUMENT_ROOT], '/', file_name); } else if (sscanf(tag, " abspath=\"%[^\"]\"", file_name) == 1) { // File name is relative to the webserver working directory // or it is absolute system path (void) mg_snprintf(path, sizeof(path), "%s", file_name); } else if (sscanf(tag, " file=\"%[^\"]\"", file_name) == 1 || sscanf(tag, " \"%[^\"]\"", file_name) == 1) { // File name is relative to the currect document (void) mg_snprintf(path, sizeof(path), "%s", ssi); if ((p = strrchr(path, '/')) != NULL) { p[1] = '\0'; } (void) mg_snprintf(path + strlen(path), sizeof(path) - strlen(path), "%s", file_name); } else { cry(conn, "Bad SSI #include: [%s]", tag); return; } if ((fp = mg_fopen(path, "rb")) == NULL) { cry(conn, "Cannot open SSI #include: [%s]: fopen(%s): %s", tag, path, strerror(ERRNO)); } else { fclose_on_exec(fp); if (match_prefix(conn->ctx->config[SSI_EXTENSIONS], strlen(conn->ctx->config[SSI_EXTENSIONS]), path) > 0) { send_ssi_file(conn, path, fp, include_level + 1); } else { send_file_data(conn, fp, 0, INT64_MAX); } fclose(fp); } } #if !defined(NO_POPEN) static void do_ssi_exec(struct mg_connection *conn, char *tag) { char cmd[MG_BUF_LEN]; FILE *fp; if (sscanf(tag, " \"%[^\"]\"", cmd) != 1) { cry(conn, "Bad SSI #exec: [%s]", tag); } else if ((fp = popen(cmd, "r")) == NULL) { cry(conn, "Cannot SSI #exec: [%s]: %s", cmd, strerror(ERRNO)); } else { send_file_data(conn, fp, 0, INT64_MAX); pclose(fp); } } #endif // !NO_POPEN static void send_ssi_file(struct mg_connection *conn, const char *path, FILE *fp, int include_level) { char buf[MG_BUF_LEN]; int ch, offset, len, in_ssi_tag; if (include_level > 10) { cry(conn, "SSI #include level is too deep (%s)", path); return; } in_ssi_tag = len = offset = 0; while ((ch = fgetc(fp)) != EOF) { if (in_ssi_tag && ch == '>') { in_ssi_tag = 0; buf[len++] = (char) ch; buf[len] = '\0'; assert(len <= (int) sizeof(buf)); if (len < 6 || memcmp(buf, "