Skip to content
Snippets Groups Projects
mongoose.c 167 KiB
Newer Older
Sergey Lyubka's avatar
Sergey Lyubka committed
  CloseHandle(tp->hPipe);
Sergey Lyubka's avatar
Sergey Lyubka committed
  _endthread();
  return NULL;
}

static void *pull_from_stdout(void *arg) {
Daniel O'Connell's avatar
Daniel O'Connell committed
  struct threadparam *tp = (struct threadparam *)arg;
  int k = 0, stop = 0;
Sergey Lyubka's avatar
Sergey Lyubka committed
  DWORD n, sent;
  char buf[IOBUF_SIZE];

  while (!stop && ReadFile(tp->hPipe, buf, sizeof(buf), &n, NULL)) {
    for (sent = 0; !stop && sent < n; sent += k) {
      if (wait_until_ready(tp->s, 0) &&
          (k = send(tp->s, buf + sent, n - sent, 0)) <= 0) stop = 1;
    }
  }
  DBG(("%s", "EOF FROM CGI"));
  CloseHandle(tp->hPipe);
  shutdown(tp->s, 2);  // Without this, IO thread may get truncated data
  closesocket(tp->s);
Sergey Lyubka's avatar
Sergey Lyubka committed
  _endthread();
  return NULL;
}

Sergey Lyubka's avatar
Sergey Lyubka committed
static void spawn_stdio_thread(sock_t sock, HANDLE hPipe,
                               void *(*func)(void *)) {
  struct threadparam *tp = (struct threadparam *)NS_MALLOC(sizeof(*tp));
Sergey Lyubka's avatar
Sergey Lyubka committed
  if (tp != NULL) {
    tp->s = sock;
    tp->hPipe = hPipe;
    mg_start_thread(func, tp);
  }
}

static void abs_path(const char *utf8_path, char *abs_path, size_t len) {
  wchar_t buf[MAX_PATH_SIZE], buf2[MAX_PATH_SIZE];
  to_wchar(utf8_path, buf, ARRAY_SIZE(buf));
  GetFullPathNameW(buf, ARRAY_SIZE(buf2), buf2, NULL);
  WideCharToMultiByte(CP_UTF8, 0, buf2, wcslen(buf2) + 1, abs_path, len, 0, 0);
}

static process_id_t start_process(char *interp, const char *cmd,
                                  const char *env, const char *envp[],
                                  const char *dir, sock_t sock) {
  STARTUPINFOW si;
  PROCESS_INFORMATION pi;
Sergey Lyubka's avatar
Sergey Lyubka committed
  HANDLE a[2], b[2], me = GetCurrentProcess();
  wchar_t wcmd[MAX_PATH_SIZE], full_dir[MAX_PATH_SIZE];
  char buf[MAX_PATH_SIZE], buf4[MAX_PATH_SIZE], buf5[MAX_PATH_SIZE],
       cmdline[MAX_PATH_SIZE], *p;
Sergey Lyubka's avatar
Sergey Lyubka committed
  DWORD flags = DUPLICATE_CLOSE_SOURCE | DUPLICATE_SAME_ACCESS;
  memset(&si, 0, sizeof(si));
  memset(&pi, 0, sizeof(pi));

  si.cb = sizeof(si);
  si.dwFlags = STARTF_USESTDHANDLES | STARTF_USESHOWWINDOW;
  si.wShowWindow = SW_HIDE;
  si.hStdError = GetStdHandle(STD_ERROR_HANDLE);
Sergey Lyubka's avatar
Sergey Lyubka committed

  CreatePipe(&a[0], &a[1], NULL, 0);
  CreatePipe(&b[0], &b[1], NULL, 0);
  DuplicateHandle(me, a[0], me, &si.hStdInput, 0, TRUE, flags);
  DuplicateHandle(me, b[1], me, &si.hStdOutput, 0, TRUE, flags);
  if (interp == NULL && (fp = fopen(cmd, "r")) != NULL) {
    buf[0] = buf[1] = '\0';
    fgets(buf, sizeof(buf), fp);
    buf[sizeof(buf) - 1] = '\0';
    if (buf[0] == '#' && buf[1] == '!') {
      interp = buf + 2;
      for (p = interp + strlen(interp) - 1;
           isspace(* (uint8_t *) p) && p > interp; p--) *p = '\0';
    fclose(fp);
  if (interp != NULL) {
    abs_path(interp, buf4, ARRAY_SIZE(buf4));
  abs_path(dir, buf5, ARRAY_SIZE(buf5));
  to_wchar(dir, full_dir, ARRAY_SIZE(full_dir));
  mg_snprintf(cmdline, sizeof(cmdline), "%s%s\"%s\"",
              interp ? interp : "", interp ? " " : "", cmd);
  to_wchar(cmdline, wcmd, ARRAY_SIZE(wcmd));
  if (CreateProcessW(NULL, wcmd, NULL, NULL, TRUE, CREATE_NEW_PROCESS_GROUP,
                     (void *) env, full_dir, &si, &pi) != 0) {
Sergey Lyubka's avatar
Sergey Lyubka committed
    spawn_stdio_thread(sock, a[1], push_to_stdin);
    spawn_stdio_thread(sock, b[0], pull_from_stdout);
  } else {
    CloseHandle(a[1]);
    CloseHandle(b[0]);
    closesocket(sock);
  }
  DBG(("CGI command: [%ls] -> %p", wcmd, pi.hProcess));
  // Not closing a[0] and b[1] because we've used DUPLICATE_CLOSE_SOURCE
  CloseHandle(si.hStdOutput);
  CloseHandle(si.hStdInput);
  //CloseHandle(pi.hThread);
  //CloseHandle(pi.hProcess);
  return pi.hProcess;
static process_id_t start_process(const char *interp, const char *cmd,
                                  const char *env, const char *envp[],
                                  const char *dir, sock_t sock) {
  char buf[500];
  process_id_t pid = fork();
  (void) env;

  if (pid == 0) {
    (void) chdir(dir);
    (void) dup2(sock, 0);
    (void) dup2(sock, 1);
    closesocket(sock);
    // After exec, all signal handlers are restored to their default values,
    // with one exception of SIGCHLD. According to POSIX.1-2001 and Linux's
    // implementation, SIGCHLD's handler will leave unchanged after exec
    // if it was set to be ignored. Restore it to default action.
    signal(SIGCHLD, SIG_DFL);
    if (interp == NULL) {
      execle(cmd, cmd, (char *) 0, envp); // Using (char *) 0 to avoid warning
      execle(interp, interp, cmd, (char *) 0, envp);
    snprintf(buf, sizeof(buf), "Status: 500\r\n\r\n"
             "500 Server Error: %s%s%s: %s", interp == NULL ? "" : interp,
             interp == NULL ? "" : " ", cmd, strerror(errno));
    send(1, buf, strlen(buf), 0);
    exit(EXIT_FAILURE);  // exec call failed
  return pid;
#endif  // _WIN32
// This structure helps to create an environment for the spawned CGI program.
// Environment is an array of "VARIABLE=VALUE\0" ASCIIZ strings,
// last element must be NULL.
// However, on Windows there is a requirement that all these VARIABLE=VALUE\0
// strings must reside in a contiguous buffer. The end of the buffer is
// marked by two '\0' characters.
// We satisfy both worlds: we create an envp array (which is vars), all
// entries are actually pointers inside buf.
struct cgi_env_block {
  struct mg_connection *conn;
  char buf[CGI_ENVIRONMENT_SIZE];       // Environment buffer
  const char *vars[MAX_CGI_ENVIR_VARS]; // char *envp[]
  int len;                              // Space taken
  int nvars;                            // Number of variables in envp[]
};
// Append VARIABLE=VALUE\0 string to the buffer, and add a respective
// pointer into the vars array.
static char *addenv(struct cgi_env_block *block, const char *fmt, ...) {
  int n, space;
  char *added;
  va_list ap;
  // Calculate how much space is left in the buffer
  space = sizeof(block->buf) - block->len - 2;
  assert(space >= 0);
  // Make a pointer to the free space int the buffer
  added = block->buf + block->len;
  // Copy VARIABLE=VALUE\0 string into the free space
  va_start(ap, fmt);
  n = mg_vsnprintf(added, (size_t) space, fmt, ap);
  va_end(ap);
  // Make sure we do not overflow buffer and the envp array
  if (n > 0 && n + 1 < space &&
      block->nvars < (int) ARRAY_SIZE(block->vars) - 2) {
    // Append a pointer to the added string into the envp array
    block->vars[block->nvars++] = added;
    // Bump up used length counter. Include \0 terminator
    block->len += n + 1;
  return added;
static void addenv2(struct cgi_env_block *blk, const char *name) {
  const char *s;
  if ((s = getenv(name)) != NULL) addenv(blk, "%s=%s", name, s);
static void prepare_cgi_environment(struct connection *conn,
                                    const char *prog,
                                    struct cgi_env_block *blk) {
  struct mg_connection *ri = &conn->mg_conn;
  const char *s, *slash;
  char *p, **opts = conn->server->config_options;
  int  i;
  blk->len = blk->nvars = 0;
  blk->conn = ri;
  if ((s = getenv("SERVER_NAME")) != NULL) {
    addenv(blk, "SERVER_NAME=%s", s);
  } else {
    addenv(blk, "SERVER_NAME=%s", ri->local_ip);
  addenv(blk, "SERVER_ROOT=%s", opts[DOCUMENT_ROOT]);
  addenv(blk, "DOCUMENT_ROOT=%s", opts[DOCUMENT_ROOT]);
  addenv(blk, "SERVER_SOFTWARE=%s/%s", "Mongoose", MONGOOSE_VERSION);
  // Prepare the environment block
  addenv(blk, "%s", "GATEWAY_INTERFACE=CGI/1.1");
  addenv(blk, "%s", "SERVER_PROTOCOL=HTTP/1.1");
  addenv(blk, "%s", "REDIRECT_STATUS=200"); // For PHP
  // TODO(lsm): fix this for IPv6 case
  //addenv(blk, "SERVER_PORT=%d", ri->remote_port);
  addenv(blk, "REQUEST_METHOD=%s", ri->request_method);
  addenv(blk, "REMOTE_ADDR=%s", ri->remote_ip);
  addenv(blk, "REMOTE_PORT=%d", ri->remote_port);
  addenv(blk, "REQUEST_URI=%s%s%s", ri->uri,
         ri->query_string == NULL ? "" : "?",
         ri->query_string == NULL ? "" : ri->query_string);
  // SCRIPT_NAME
  if (conn->path_info != NULL) {
    addenv(blk, "SCRIPT_NAME=%.*s",
           (int) (strlen(ri->uri) - strlen(conn->path_info)), ri->uri);
    addenv(blk, "PATH_INFO=%s", conn->path_info);
    s = strrchr(prog, '/');
    slash = strrchr(ri->uri, '/');
    addenv(blk, "SCRIPT_NAME=%.*s%s",
           slash == NULL ? 0 : (int) (slash - ri->uri), ri->uri,
           s == NULL ? prog : s);
  addenv(blk, "SCRIPT_FILENAME=%s", prog);
  addenv(blk, "PATH_TRANSLATED=%s", prog);
Sergey Lyubka's avatar
Sergey Lyubka committed
  addenv(blk, "HTTPS=%s", conn->ns_conn->ssl != NULL ? "on" : "off");
  if ((s = mg_get_header(ri, "Content-Type")) != NULL)
    addenv(blk, "CONTENT_TYPE=%s", s);
  if (ri->query_string != NULL)
    addenv(blk, "QUERY_STRING=%s", ri->query_string);
  if ((s = mg_get_header(ri, "Content-Length")) != NULL)
    addenv(blk, "CONTENT_LENGTH=%s", s);
  addenv2(blk, "PATH");
  addenv2(blk, "TMP");
  addenv2(blk, "TEMP");
  addenv2(blk, "PERLLIB");
  addenv2(blk, ENV_EXPORT_TO_CGI);
#if defined(_WIN32)
  addenv2(blk, "COMSPEC");
  addenv2(blk, "SYSTEMROOT");
  addenv2(blk, "SystemDrive");
  addenv2(blk, "ProgramFiles");
  addenv2(blk, "ProgramFiles(x86)");
  addenv2(blk, "CommonProgramFiles(x86)");
#else
  addenv2(blk, "LD_LIBRARY_PATH");
#endif // _WIN32
  // Add all headers as HTTP_* variables
  for (i = 0; i < ri->num_headers; i++) {
    p = addenv(blk, "HTTP_%s=%s",
        ri->http_headers[i].name, ri->http_headers[i].value);
    // Convert variable name into uppercase, and change - to _
    for (; *p != '=' && *p != '\0'; p++) {
      if (*p == '-')
        *p = '_';
      *p = (char) toupper(* (unsigned char *) p);
  blk->vars[blk->nvars++] = NULL;
  blk->buf[blk->len++] = '\0';
  assert(blk->nvars < (int) ARRAY_SIZE(blk->vars));
  assert(blk->len > 0);
  assert(blk->len < (int) sizeof(blk->buf));
static const char cgi_status[] = "HTTP/1.1 200 OK\r\n";
Sergey Lyubka's avatar
Sergey Lyubka committed

static void open_cgi_endpoint(struct connection *conn, const char *prog) {
  struct cgi_env_block blk;
  char dir[MAX_PATH_SIZE];
  const char *p;
  sock_t fds[2];

  prepare_cgi_environment(conn, prog, &blk);
  // CGI must be executed in its own directory. 'dir' must point to the
  // directory containing executable program, 'p' must point to the
  // executable program name relative to 'dir'.
Sergey Lyubka's avatar
Sergey Lyubka committed
  if ((p = strrchr(prog, '/')) == NULL) {
Sergey Lyubka's avatar
Sergey Lyubka committed
    mg_snprintf(dir, sizeof(dir), "%s", ".");
Sergey Lyubka's avatar
Sergey Lyubka committed
  } else {
    mg_snprintf(dir, sizeof(dir), "%.*s", (int) (p - prog), prog);
Sergey Lyubka's avatar
Sergey Lyubka committed
  // Try to create socketpair in a loop until success. ns_socketpair()
  // can be interrupted by a signal and fail.
  // TODO(lsm): use sigaction to restart interrupted syscall
  do {
Sergey Lyubka's avatar
Sergey Lyubka committed
    ns_socketpair(fds);
  } while (fds[0] == INVALID_SOCKET);
  if (start_process(conn->server->config_options[CGI_INTERPRETER],
                    prog, blk.buf, blk.vars, dir, fds[1]) != 0) {
    conn->endpoint_type = EP_CGI;
    conn->endpoint.nc = ns_add_sock(&conn->server->ns_mgr, fds[0],
                                    mg_ev_handler, conn);
    conn->endpoint.nc->flags |= MG_CGI_CONN;
Sergey Lyubka's avatar
Sergey Lyubka committed
    ns_send(conn->ns_conn, cgi_status, sizeof(cgi_status) - 1);
    conn->mg_conn.status_code = 200;
Sergey Lyubka's avatar
Sergey Lyubka committed
    conn->ns_conn->flags |= NSF_BUFFER_BUT_DONT_SEND;
    // Pass POST data to the CGI process
    conn->endpoint.nc->send_iobuf = conn->ns_conn->recv_iobuf;
    iobuf_init(&conn->ns_conn->recv_iobuf, 0);
  } else {
    closesocket(fds[0]);
    send_http_error(conn, 500, "start_process(%s) failed", prog);
Sergey Lyubka's avatar
Sergey Lyubka committed
#ifndef _WIN32
  closesocket(fds[1]);  // On Windows, CGI stdio thread closes that socket
#endif
Sergey Lyubka's avatar
Sergey Lyubka committed
static void on_cgi_data(struct ns_connection *nc) {
Ake Hedman's avatar
Ake Hedman committed
  struct connection *conn = (struct connection *) nc->user_data;
Sergey Lyubka's avatar
Sergey Lyubka committed
  const char *status = "500";
  struct mg_connection c;
Sergey Lyubka's avatar
Sergey Lyubka committed
  if (!conn) return;

  // Copy CGI data from CGI socket to the client send buffer
  ns_forward(nc, conn->ns_conn);
Sergey Lyubka's avatar
Sergey Lyubka committed

  // If reply has not been parsed yet, parse it
  if (conn->ns_conn->flags & NSF_BUFFER_BUT_DONT_SEND) {
    struct iobuf *io = &conn->ns_conn->send_iobuf;
    size_t s_len = sizeof(cgi_status) - 1;
    int len = get_request_len(io->buf + s_len, io->len - s_len);
Sergey Lyubka's avatar
Sergey Lyubka committed
    char buf[MAX_REQUEST_SIZE], *s = buf;

    if (len == 0) return;

    if (len < 0 || len > (int) sizeof(buf)) {
      len = io->len;
Sergey Lyubka's avatar
Sergey Lyubka committed
      iobuf_remove(io, io->len);
      send_http_error(conn, 500, "CGI program sent malformed headers: [%.*s]",
        len, io->buf);
Sergey Lyubka's avatar
Sergey Lyubka committed
    } else {
      memset(&c, 0, sizeof(c));
      memcpy(buf, io->buf + s_len, len);
      buf[len - 1] = '\0';
      parse_http_headers(&s, &c);
      if (mg_get_header(&c, "Location") != NULL) {
        status = "302";
      } else if ((status = (char *) mg_get_header(&c, "Status")) == NULL) {
        status = "200";
Sergey Lyubka's avatar
Sergey Lyubka committed
      memcpy(io->buf + 9, status, 3);
      conn->mg_conn.status_code = atoi(status);
Sergey Lyubka's avatar
Sergey Lyubka committed
    conn->ns_conn->flags &= ~NSF_BUFFER_BUT_DONT_SEND;
Sergey Lyubka's avatar
Sergey Lyubka committed
#endif  // !MONGOOSE_NO_CGI
static char *mg_strdup(const char *str) {
  char *copy = (char *) NS_MALLOC(strlen(str) + 1);
  if (copy != NULL) {
    strcpy(copy, str);
  return copy;
static int isbyte(int n) {
  return n >= 0 && n <= 255;
}
static int parse_net(const char *spec, uint32_t *net, uint32_t *mask) {
  int n, a, b, c, d, slash = 32, len = 0;
  if ((sscanf(spec, "%d.%d.%d.%d/%d%n", &a, &b, &c, &d, &slash, &n) == 5 ||
      sscanf(spec, "%d.%d.%d.%d%n", &a, &b, &c, &d, &n) == 4) &&
      isbyte(a) && isbyte(b) && isbyte(c) && isbyte(d) &&
      slash >= 0 && slash < 33) {
    len = n;
    *net = ((uint32_t)a << 24) | ((uint32_t)b << 16) | ((uint32_t)c << 8) | d;
    *mask = slash ? 0xffffffffU << (32 - slash) : 0;
  }
// Verify given socket address against the ACL.
// Return -1 if ACL is malformed, 0 if address is disallowed, 1 if allowed.
static int check_acl(const char *acl, uint32_t remote_ip) {
  int allowed, flag;
  uint32_t net, mask;
  struct vec vec;
  // If any ACL is set, deny by default
  allowed = acl == NULL ? '+' : '-';
  while ((acl = next_option(acl, &vec, NULL)) != NULL) {
    flag = vec.ptr[0];
    if ((flag != '+' && flag != '-') ||
        parse_net(&vec.ptr[1], &net, &mask) == 0) {
      return -1;
    if (net == (remote_ip & mask)) {
      allowed = flag;
  return allowed == '+';
// Protect against directory disclosure attack by removing '..',
// excessive '/' and '\' characters
static void remove_double_dots_and_double_slashes(char *s) {
  char *p = s;
  while (*s != '\0') {
    *p++ = *s++;
    if (s[-1] == '/' || s[-1] == '\\') {
      // Skip all following slashes, backslashes and double-dots
      while (s[0] != '\0') {
        if (s[0] == '/' || s[0] == '\\') { s++; }
        else if (s[0] == '.' && (s[1] == '/' || s[1] == '\\')) { s += 2; }
        else if (s[0] == '.' && s[1] == '.' && s[2] == '\0') { s += 2; }
        else if (s[0] == '.' && s[1] == '.' && (s[2] == '/' || s[2] == '\\')) { s += 3; }
        else { break; }
      }
int mg_url_decode(const char *src, size_t src_len, char *dst,
                  size_t dst_len, int is_form_url_encoded) {
  size_t i, j = 0;
  int a, b;
#define HEXTOI(x) (isdigit(x) ? (x) - '0' : (x) - 'W')
  for (i = j = 0; i < src_len && j < dst_len - 1; i++, j++) {
    if (src[i] == '%' && i + 2 < src_len &&
        isxdigit(* (const unsigned char *) (src + i + 1)) &&
        isxdigit(* (const unsigned char *) (src + i + 2))) {
      a = tolower(* (const unsigned char *) (src + i + 1));
      b = tolower(* (const unsigned char *) (src + i + 2));
      dst[j] = (char) ((HEXTOI(a) << 4) | HEXTOI(b));
      i += 2;
    } else if (is_form_url_encoded && src[i] == '+') {
      dst[j] = ' ';
    } else {
      dst[j] = src[i];
    }
  dst[j] = '\0'; // Null-terminate the destination
  return i >= src_len ? j : -1;
static int is_valid_http_method(const char *s) {
  return !strcmp(s, "GET") || !strcmp(s, "POST") || !strcmp(s, "HEAD") ||
    !strcmp(s, "CONNECT") || !strcmp(s, "PUT") || !strcmp(s, "DELETE") ||
Sergey Lyubka's avatar
Sergey Lyubka committed
    !strcmp(s, "OPTIONS") || !strcmp(s, "PROPFIND") || !strcmp(s, "MKCOL") ||
    !strcmp(s, "PATCH");
// Parse HTTP request, fill in mg_request structure.
// This function modifies the buffer by NUL-terminating
// HTTP request components, header names and header values.
// Note that len must point to the last \n of HTTP headers.
static size_t parse_http_message(char *buf, size_t len,
                                 struct mg_connection *ri) {
  int is_request, n;

  // Reset the connection. Make sure that we don't touch fields that are
  // set elsewhere: remote_ip, remote_port, server_param
  ri->request_method = ri->uri = ri->http_version = ri->query_string = NULL;
  ri->num_headers = ri->status_code = ri->is_websocket = ri->content_len = 0;

  if (len < 1) return ~0;
  buf[len - 1] = '\0';

  // RFC says that all initial whitespaces should be ignored
  while (*buf != '\0' && isspace(* (unsigned char *) buf)) {
    buf++;
  }
  ri->request_method = skip(&buf, " ");
  ri->uri = skip(&buf, " ");
  ri->http_version = skip(&buf, "\r\n");

  // HTTP message could be either HTTP request or HTTP response, e.g.
  // "GET / HTTP/1.0 ...." or  "HTTP/1.0 200 OK ..."
  is_request = is_valid_http_method(ri->request_method);
  if ((is_request && memcmp(ri->http_version, "HTTP/", 5) != 0) ||
      (!is_request && memcmp(ri->request_method, "HTTP/", 5) != 0)) {
  } else {
    if (is_request) {
      ri->http_version += 5;
MPR's avatar
MPR committed
    } else {
      ri->status_code = atoi(ri->uri);
    }
    parse_http_headers(&buf, ri);
    if ((ri->query_string = strchr(ri->uri, '?')) != NULL) {
      *(char *) ri->query_string++ = '\0';
    }
    n = (int) strlen(ri->uri);
    mg_url_decode(ri->uri, n, (char *) ri->uri, n + 1, 0);
    if (*ri->uri == '/' || *ri->uri == '.') {
      remove_double_dots_and_double_slashes((char *) ri->uri);
static int lowercase(const char *s) {
  return tolower(* (const unsigned char *) s);
}
static int mg_strcasecmp(const char *s1, const char *s2) {
  int diff;
  do {
    diff = lowercase(s1++) - lowercase(s2++);
  } while (diff == 0 && s1[-1] != '\0');
static int mg_strncasecmp(const char *s1, const char *s2, size_t len) {
  int diff = 0;
  if (len > 0)
    do {
      diff = lowercase(s1++) - lowercase(s2++);
    } while (diff == 0 && s1[-1] != '\0' && --len > 0);
  return diff;
Sergey Lyubka's avatar
Sergey Lyubka committed
// Return HTTP header value, or NULL if not found.
const char *mg_get_header(const struct mg_connection *ri, const char *s) {
  int i;

  for (i = 0; i < ri->num_headers; i++)
    if (!mg_strcasecmp(s, ri->http_headers[i].name))
      return ri->http_headers[i].value;

  return NULL;
}

// Perform case-insensitive match of string against pattern
int mg_match_prefix(const char *pattern, ssize_t pattern_len, const char *str) {
  const char *or_str;
Sergey Lyubka's avatar
Sergey Lyubka committed
  int len, res, i = 0, j = 0;
  if ((or_str = (const char *) memchr(pattern, '|', pattern_len)) != NULL) {
    res = mg_match_prefix(pattern, or_str - pattern, str);
    return res > 0 ? res : mg_match_prefix(or_str + 1,
      (pattern + pattern_len) - (or_str + 1), str);
  for (; i < pattern_len; i++, j++) {
    if (pattern[i] == '?' && str[j] != '\0') {
      continue;
    } else if (pattern[i] == '$') {
      return str[j] == '\0' ? j : -1;
    } else if (pattern[i] == '*') {
      i++;
      if (pattern[i] == '*') {
        i++;
        len = (int) strlen(str + j);
      } else {
        len = (int) strcspn(str + j, "/");
      }
      if (i == pattern_len) {
        return j + len;
        res = mg_match_prefix(pattern + i, pattern_len - i, str + j + len);
      } while (res == -1 && len-- > 0);
      return res == -1 ? -1 : j + res + len;
    } else if (lowercase(&pattern[i]) != lowercase(&str[j])) {
      return -1;
// This function prints HTML pages, and expands "{{something}}" blocks
// inside HTML by calling appropriate callback functions.
// Note that {{@path/to/file}} construct outputs embedded file's contents,
// which provides SSI-like functionality.
void mg_template(struct mg_connection *conn, const char *s,
                 struct mg_expansion *expansions) {
  int i, j, pos = 0, inside_marker = 0;

  for (i = 0; s[i] != '\0'; i++) {
    if (inside_marker == 0 && !memcmp(&s[i], "{{", 2)) {
      if (i > pos) {
        mg_send_data(conn, &s[pos], i - pos);
      }
      pos = i;
      inside_marker = 1;
    }
    if (inside_marker == 1 && !memcmp(&s[i], "}}", 2)) {
      for (j = 0; expansions[j].keyword != NULL; j++) {
        const char *kw = expansions[j].keyword;
        if ((int) strlen(kw) == i - (pos + 2) &&
            memcmp(kw, &s[pos + 2], i - (pos + 2)) == 0) {
          expansions[j].handler(conn);
          pos = i + 2;
          break;
        }
      }
      inside_marker = 0;
    }
  }
  if (i > pos) {
    mg_send_data(conn, &s[pos], i - pos);
  }
}

#ifndef MONGOOSE_NO_FILESYSTEM
static int is_dav_request(const struct connection *conn) {
  const char *s = conn->mg_conn.request_method;
  return !strcmp(s, "PUT") || !strcmp(s, "DELETE") ||
    !strcmp(s, "MKCOL") || !strcmp(s, "PROPFIND");
}

static int must_hide_file(struct connection *conn, const char *path) {
  const char *pw_pattern = "**" PASSWORDS_FILE_NAME "$";
  const char *pattern = conn->server->config_options[HIDE_FILES_PATTERN];
  return mg_match_prefix(pw_pattern, strlen(pw_pattern), path) > 0 ||
    (pattern != NULL && mg_match_prefix(pattern, strlen(pattern), path) > 0);
// Return 1 if real file has been found, 0 otherwise
static int convert_uri_to_file_name(struct connection *conn, char *buf,
                                    size_t buf_len, file_stat_t *st) {
  struct vec a, b;
Sergey Lyubka's avatar
Sergey Lyubka committed
  const char *rewrites = conn->server->config_options[URL_REWRITES];
  const char *root =
#ifndef MONGOOSE_NO_DAV
    is_dav_request(conn) && conn->server->config_options[DAV_ROOT] != NULL ?
    conn->server->config_options[DAV_ROOT] :
#endif
    conn->server->config_options[DOCUMENT_ROOT];
#ifndef MONGOOSE_NO_CGI
Sergey Lyubka's avatar
Sergey Lyubka committed
  const char *cgi_pat = conn->server->config_options[CGI_PATTERN];
#endif
  const char *uri = conn->mg_conn.uri;
  const char *domain = mg_get_header(&conn->mg_conn, "Host");
Sergey Lyubka's avatar
Sergey Lyubka committed
  // Important: match_len has to be declared as int, unless rewrites break.
  int match_len, root_len = root == NULL ? 0 : strlen(root);

  // Perform virtual hosting rewrites
  if (rewrites != NULL && domain != NULL) {
    const char *colon = strchr(domain, ':');
    size_t domain_len = colon == NULL ? strlen(domain) : colon - domain;

    while ((rewrites = next_option(rewrites, &a, &b)) != NULL) {
      if (a.len > 1 && a.ptr[0] == '@' && a.len == domain_len + 1 &&
          mg_strncasecmp(a.ptr + 1, domain, domain_len) == 0) {
        root = b.ptr;
        root_len = b.len;
        break;
      }
    }
  }
  // No filesystem access
  if (root == NULL || root_len == 0) return 0;
  // Handle URL rewrites
  mg_snprintf(buf, buf_len, "%.*s%s", root_len, root, uri);
  rewrites = conn->server->config_options[URL_REWRITES];  // Re-initialize!
  while ((rewrites = next_option(rewrites, &a, &b)) != NULL) {
    if ((match_len = mg_match_prefix(a.ptr, a.len, uri)) > 0) {
      mg_snprintf(buf, buf_len, "%.*s%s", (int) b.len, b.ptr, uri + match_len);
  if (stat(buf, st) == 0) return 1;
#ifndef MONGOOSE_NO_CGI
  // Support PATH_INFO for CGI scripts.
  for (p = buf + strlen(root) + 2; *p != '\0'; p++) {
    if (*p == '/') {
      *p = '\0';
      if (mg_match_prefix(cgi_pat, strlen(cgi_pat), buf) > 0 &&
          !stat(buf, st)) {
      DBG(("!!!! [%s]", buf));
        *p = '/';
        conn->path_info = mg_strdup(p);
        *p = '\0';
        return 1;
      }
      *p = '/';
#endif  // MONGOOSE_NO_FILESYSTEM
static int should_keep_alive(const struct mg_connection *conn) {
Sergey Lyubka's avatar
Sergey Lyubka committed
  struct connection *c = MG_CONN_2_CONN(conn);
  const char *method = conn->request_method;
  const char *http_version = conn->http_version;
  const char *header = mg_get_header(conn, "Connection");
Sergey Lyubka's avatar
Sergey Lyubka committed
  return method != NULL &&
    (!strcmp(method, "GET") || c->endpoint_type == EP_USER) &&
    ((header != NULL && !mg_strcasecmp(header, "keep-alive")) ||
     (header == NULL && http_version && !strcmp(http_version, "1.1")));
}

size_t mg_write(struct mg_connection *c, const void *buf, size_t len) {
Sergey Lyubka's avatar
Sergey Lyubka committed
  struct connection *conn = MG_CONN_2_CONN(c);
  ns_send(conn->ns_conn, buf, len);
  return conn->ns_conn->send_iobuf.len;
void mg_send_status(struct mg_connection *c, int status) {
Sergey Lyubka's avatar
Sergey Lyubka committed
  struct connection *conn = MG_CONN_2_CONN(c);
  if (c->status_code == 0) {
    c->status_code = status;
    mg_printf(c, "HTTP/1.1 %d %s\r\n", status, status_code_to_str(status));
  }
Sergey Lyubka's avatar
Sergey Lyubka committed
  conn->ns_conn->flags |= MG_USING_CHUNKED_API;
}

void mg_send_header(struct mg_connection *c, const char *name, const char *v) {
Sergey Lyubka's avatar
Sergey Lyubka committed
  struct connection *conn = MG_CONN_2_CONN(c);
  if (c->status_code == 0) {
    c->status_code = 200;
    mg_printf(c, "HTTP/1.1 %d %s\r\n", 200, status_code_to_str(200));
  }
  mg_printf(c, "%s: %s\r\n", name, v);
Sergey Lyubka's avatar
Sergey Lyubka committed
  conn->ns_conn->flags |= MG_USING_CHUNKED_API;
}

static void terminate_headers(struct mg_connection *c) {
Sergey Lyubka's avatar
Sergey Lyubka committed
  struct connection *conn = MG_CONN_2_CONN(c);
  if (!(conn->ns_conn->flags & MG_HEADERS_SENT)) {
    mg_send_header(c, "Transfer-Encoding", "chunked");
    mg_write(c, "\r\n", 2);
Sergey Lyubka's avatar
Sergey Lyubka committed
    conn->ns_conn->flags |= MG_HEADERS_SENT;
size_t mg_send_data(struct mg_connection *c, const void *data, int data_len) {
  struct connection *conn = MG_CONN_2_CONN(c);
  terminate_headers(c);
Sergey Lyubka's avatar
Sergey Lyubka committed
  write_chunk(MG_CONN_2_CONN(c), (const char *) data, data_len);
  return conn->ns_conn->send_iobuf.len;
size_t mg_printf_data(struct mg_connection *c, const char *fmt, ...) {
Sergey Lyubka's avatar
Sergey Lyubka committed
  struct connection *conn = MG_CONN_2_CONN(c);
  int len;
  char mem[IOBUF_SIZE], *buf = mem;

  terminate_headers(c);

  va_start(ap, fmt);
  len = ns_avprintf(&buf, sizeof(mem), fmt, ap);
Daniel O'Connell's avatar
Daniel O'Connell committed
  if (len >= 0) {
    write_chunk((struct connection *) conn, buf, len);
  }
  if (buf != mem && buf != NULL) {
  return conn->ns_conn->send_iobuf.len;
#if !defined(MONGOOSE_NO_WEBSOCKET) || !defined(MONGOOSE_NO_AUTH)
static int is_big_endian(void) {
  static const int n = 1;
  return ((char *) &n)[0] == 0;
}
#endif
#ifndef MONGOOSE_NO_WEBSOCKET
// START OF SHA-1 code
// Copyright(c) By Steve Reid <steve@edmweb.com>
#define SHA1HANDSOFF
#if defined(__sun)
#include "solarisfixes.h"
union char64long16 { unsigned char c[64]; uint32_t l[16]; };
#define rol(value, bits) (((value) << (bits)) | ((value) >> (32 - (bits))))
static uint32_t blk0(union char64long16 *block, int i) {
  // Forrest: SHA expect BIG_ENDIAN, swap if LITTLE_ENDIAN
  if (!is_big_endian()) {
    block->l[i] = (rol(block->l[i], 24) & 0xFF00FF00) |
      (rol(block->l[i], 8) & 0x00FF00FF);
  }
  return block->l[i];
}
Sergey Lyubka's avatar
Sergey Lyubka committed
/* Avoid redefine warning (ARM /usr/include/sys/ucontext.h define R0~R4) */
#undef blk
#undef R0
#undef R1
#undef R2
#undef R3
#undef R4

#define blk(i) (block->l[i&15] = rol(block->l[(i+13)&15]^block->l[(i+8)&15] \
    ^block->l[(i+2)&15]^block->l[i&15],1))
#define R0(v,w,x,y,z,i) z+=((w&(x^y))^y)+blk0(block, i)+0x5A827999+rol(v,5);w=rol(w,30);
#define R1(v,w,x,y,z,i) z+=((w&(x^y))^y)+blk(i)+0x5A827999+rol(v,5);w=rol(w,30);
#define R2(v,w,x,y,z,i) z+=(w^x^y)+blk(i)+0x6ED9EBA1+rol(v,5);w=rol(w,30);
#define R3(v,w,x,y,z,i) z+=(((w|x)&y)|(w&x))+blk(i)+0x8F1BBCDC+rol(v,5);w=rol(w,30);
#define R4(v,w,x,y,z,i) z+=(w^x^y)+blk(i)+0xCA62C1D6+rol(v,5);w=rol(w,30);
typedef struct {
    uint32_t state[5];
    uint32_t count[2];
    unsigned char buffer[64];
} SHA1_CTX;
static void SHA1Transform(uint32_t state[5], const unsigned char buffer[64]) {
  uint32_t a, b, c, d, e;
  union char64long16 block[1];
  memcpy(block, buffer, 64);
  a = state[0];
  b = state[1];
  c = state[2];
  d = state[3];
  e = state[4];
  R0(a,b,c,d,e, 0); R0(e,a,b,c,d, 1); R0(d,e,a,b,c, 2); R0(c,d,e,a,b, 3);
  R0(b,c,d,e,a, 4); R0(a,b,c,d,e, 5); R0(e,a,b,c,d, 6); R0(d,e,a,b,c, 7);
  R0(c,d,e,a,b, 8); R0(b,c,d,e,a, 9); R0(a,b,c,d,e,10); R0(e,a,b,c,d,11);
  R0(d,e,a,b,c,12); R0(c,d,e,a,b,13); R0(b,c,d,e,a,14); R0(a,b,c,d,e,15);
  R1(e,a,b,c,d,16); R1(d,e,a,b,c,17); R1(c,d,e,a,b,18); R1(b,c,d,e,a,19);
  R2(a,b,c,d,e,20); R2(e,a,b,c,d,21); R2(d,e,a,b,c,22); R2(c,d,e,a,b,23);
  R2(b,c,d,e,a,24); R2(a,b,c,d,e,25); R2(e,a,b,c,d,26); R2(d,e,a,b,c,27);
  R2(c,d,e,a,b,28); R2(b,c,d,e,a,29); R2(a,b,c,d,e,30); R2(e,a,b,c,d,31);
  R2(d,e,a,b,c,32); R2(c,d,e,a,b,33); R2(b,c,d,e,a,34); R2(a,b,c,d,e,35);
  R2(e,a,b,c,d,36); R2(d,e,a,b,c,37); R2(c,d,e,a,b,38); R2(b,c,d,e,a,39);
  R3(a,b,c,d,e,40); R3(e,a,b,c,d,41); R3(d,e,a,b,c,42); R3(c,d,e,a,b,43);
  R3(b,c,d,e,a,44); R3(a,b,c,d,e,45); R3(e,a,b,c,d,46); R3(d,e,a,b,c,47);
  R3(c,d,e,a,b,48); R3(b,c,d,e,a,49); R3(a,b,c,d,e,50); R3(e,a,b,c,d,51);
  R3(d,e,a,b,c,52); R3(c,d,e,a,b,53); R3(b,c,d,e,a,54); R3(a,b,c,d,e,55);
  R3(e,a,b,c,d,56); R3(d,e,a,b,c,57); R3(c,d,e,a,b,58); R3(b,c,d,e,a,59);
  R4(a,b,c,d,e,60); R4(e,a,b,c,d,61); R4(d,e,a,b,c,62); R4(c,d,e,a,b,63);
  R4(b,c,d,e,a,64); R4(a,b,c,d,e,65); R4(e,a,b,c,d,66); R4(d,e,a,b,c,67);
  R4(c,d,e,a,b,68); R4(b,c,d,e,a,69); R4(a,b,c,d,e,70); R4(e,a,b,c,d,71);
  R4(d,e,a,b,c,72); R4(c,d,e,a,b,73); R4(b,c,d,e,a,74); R4(a,b,c,d,e,75);
  R4(e,a,b,c,d,76); R4(d,e,a,b,c,77); R4(c,d,e,a,b,78); R4(b,c,d,e,a,79);
  state[0] += a;
  state[1] += b;
  state[2] += c;
  state[3] += d;
  state[4] += e;
  // Erase working structures. The order of operations is important,
  // used to ensure that compiler doesn't optimize those out.
Sergey Lyubka's avatar
Sergey Lyubka committed
  memset(block, 0, sizeof(block));
Sergey Lyubka's avatar
Sergey Lyubka committed
  a = b = c = d = e = 0;
Sergey Lyubka's avatar
Sergey Lyubka committed
  (void) a; (void) b; (void) c; (void) d; (void) e;
Pavel Pimenov's avatar
Pavel Pimenov committed
static void SHA1Init(SHA1_CTX *context) {
  context->state[0] = 0x67452301;
  context->state[1] = 0xEFCDAB89;
  context->state[2] = 0x98BADCFE;
  context->state[3] = 0x10325476;
  context->state[4] = 0xC3D2E1F0;
  context->count[0] = context->count[1] = 0;
Pavel Pimenov's avatar
Pavel Pimenov committed
static void SHA1Update(SHA1_CTX *context, const unsigned char *data,
                       size_t len) {
  size_t i, j;
  j = context->count[0];
  if ((context->count[0] += len << 3) < j)
    context->count[1]++;
  context->count[1] += (len>>29);
  j = (j >> 3) & 63;
  if ((j + len) > 63) {
    memcpy(&context->buffer[j], data, (i = 64-j));
    SHA1Transform(context->state, context->buffer);
    for ( ; i + 63 < len; i += 64) {
      SHA1Transform(context->state, &data[i]);
    }
    j = 0;
  }
  else i = 0;
  memcpy(&context->buffer[j], &data[i], len - i);
Pavel Pimenov's avatar
Pavel Pimenov committed
static void SHA1Final(unsigned char digest[20], SHA1_CTX *context) {
  unsigned i;
  unsigned char finalcount[8], c;
  for (i = 0; i < 8; i++) {
    finalcount[i] = (unsigned char)((context->count[(i >= 4 ? 0 : 1)]
                                     >> ((3-(i & 3)) * 8) ) & 255);
  c = 0200;
  SHA1Update(context, &c, 1);
  while ((context->count[0] & 504) != 448) {
    c = 0000;
    SHA1Update(context, &c, 1);
  }
  SHA1Update(context, finalcount, 8);
  for (i = 0; i < 20; i++) {
    digest[i] = (unsigned char)
      ((context->state[i>>2] >> ((3-(i & 3)) * 8) ) & 255);
  memset(context, '\0', sizeof(*context));
  memset(&finalcount, '\0', sizeof(finalcount));
// END OF SHA1 CODE
static void base64_encode(const unsigned char *src, int src_len, char *dst) {
  static const char *b64 =
    "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
  int i, j, a, b, c;
  for (i = j = 0; i < src_len; i += 3) {
    a = src[i];
    b = i + 1 >= src_len ? 0 : src[i + 1];
    c = i + 2 >= src_len ? 0 : src[i + 2];
    dst[j++] = b64[a >> 2];
    dst[j++] = b64[((a & 3) << 4) | (b >> 4)];
    if (i + 1 < src_len) {
      dst[j++] = b64[(b & 15) << 2 | (c >> 6)];
    }
    if (i + 2 < src_len) {
      dst[j++] = b64[c & 63];
  while (j % 4 != 0) {
    dst[j++] = '=';
static void send_websocket_handshake(struct mg_connection *conn,
                                     const char *key) {
  static const char *magic = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
  char buf[500], sha[20], b64_sha[sizeof(sha) * 2];
  mg_snprintf(buf, sizeof(buf), "%s%s", key, magic);
  SHA1Init(&sha_ctx);
  SHA1Update(&sha_ctx, (unsigned char *) buf, strlen(buf));
  SHA1Final((unsigned char *) sha, &sha_ctx);
  base64_encode((unsigned char *) sha, sizeof(sha), b64_sha);
  mg_snprintf(buf, sizeof(buf), "%s%s%s",
              "HTTP/1.1 101 Switching Protocols\r\n"
              "Upgrade: websocket\r\n"
              "Connection: Upgrade\r\n"
              "Sec-WebSocket-Accept: ", b64_sha, "\r\n\r\n");