Coverage Report

Created: 2026-05-24 07:04

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/ntopng/third-party/mongoose/mongoose.c
Line
Count
Source
1
// Copyright (c) 2004-2013 Sergey Lyubka
2
// Copyright (c) 2013-2026 ntop.org
3
//
4
// Permission is hereby granted, free of charge, to any person obtaining a copy
5
// of this software and associated documentation files (the "Software"), to deal
6
// in the Software without restriction, including without limitation the rights
7
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
8
// copies of the Software, and to permit persons to whom the Software is
9
// furnished to do so, subject to the following conditions:
10
//
11
// The above copyright notice and this permission notice shall be included in
12
// all copies or substantial portions of the Software.
13
//
14
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
15
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
16
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
17
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
18
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
19
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
20
// THE SOFTWARE.
21
22
#if defined(_WIN32)
23
#define NO_SSL_DL
24
25
#if 0 /* ntop */
26
#define _CRT_SECURE_NO_WARNINGS // Disable deprecation warning in VS2005
27
#endif
28
#else
29
#ifndef _XOPEN_SOURCE /* ntop */
30
#ifdef __linux__
31
#define _XOPEN_SOURCE 600     // For flockfile() on Linux
32
#endif
33
#endif
34
35
#ifndef _LARGEFILE_SOURCE /* ntop */
36
#define _LARGEFILE_SOURCE     // Enable 64-bit file offsets
37
#endif
38
#define __STDC_FORMAT_MACROS  // <inttypes.h> wants this for C++
39
#define __STDC_LIMIT_MACROS   // C++ wants that for INT64_MAX
40
#endif
41
42
#if defined (_MSC_VER)
43
// conditional expression is constant: introduced by FD_SET(..)
44
#pragma warning (disable : 4127)
45
// non-constant aggregate initializer: issued due to missing C99 support
46
#pragma warning (disable : 4204)
47
#endif
48
49
// Disable WIN32_LEAN_AND_MEAN.
50
// This makes windows.h always include winsock2.h
51
#ifdef WIN32_LEAN_AND_MEAN
52
#undef WIN32_LEAN_AND_MEAN
53
#endif
54
55
#if defined(__SYMBIAN32__)
56
#define NO_SSL // SSL is not supported
57
#define NO_CGI // CGI is not supported
58
#define PATH_MAX FILENAME_MAX
59
#endif // __SYMBIAN32__
60
61
#ifndef _WIN32_WCE // Some ANSI #includes are not available on Windows CE
62
#include <sys/types.h>
63
#include <sys/stat.h>
64
#include <errno.h>
65
#include <signal.h>
66
#include <fcntl.h>
67
#endif // !_WIN32_WCE
68
69
#include <time.h>
70
#include <stdlib.h>
71
#include <stdarg.h>
72
#include <assert.h>
73
#include <string.h>
74
#include <ctype.h>
75
#include <limits.h>
76
#include <stddef.h>
77
#include <stdio.h>
78
79
#if defined(_WIN32) && !defined(__SYMBIAN32__) // Windows specific
80
#ifndef _WIN32_WINNT /* ntop */
81
#define _WIN32_WINNT 0x0400 // To make it link in VS2005
82
#endif
83
#include <windows.h>
84
85
#ifndef PATH_MAX
86
#define PATH_MAX MAX_PATH
87
#endif
88
89
#ifndef _WIN32_WCE
90
#include <process.h>
91
#include <direct.h>
92
#include <io.h>
93
#else // _WIN32_WCE
94
#define NO_CGI // WinCE has no pipes
95
96
typedef long off_t;
97
98
#define errno   GetLastError()
99
#define strerror(x)  _ultoa(x, (char *) _alloca(sizeof(x) *3 ), 10)
100
#endif // _WIN32_WCE
101
102
#define MAKEUQUAD(lo, hi) ((uint64_t)(((uint32_t)(lo)) |    \
103
              ((uint64_t)((uint32_t)(hi))) << 32))
104
#define RATE_DIFF 10000000 // 100 nsecs
105
#define EPOCH_DIFF MAKEUQUAD(0xd53e8000, 0x019db1de)
106
#define SYS2UNIX_TIME(lo, hi)         \
107
  (time_t) ((MAKEUQUAD((lo), (hi)) - EPOCH_DIFF) / RATE_DIFF)
108
109
// Visual Studio 6 does not know __func__ or __FUNCTION__
110
// The rest of MS compilers use __FUNCTION__, not C99 __func__
111
// Also use _strtoui64 on modern M$ compilers
112
#if defined(_MSC_VER) && _MSC_VER < 1300
113
#define STRX(x) #x
114
#define STR(x) STRX(x)
115
#define __func__ __FILE__ ":" STR(__LINE__)
116
#define strtoull(x, y, z) strtoul(x, y, z)
117
#define strtoll(x, y, z) strtol(x, y, z)
118
#else
119
#define __func__  __FUNCTION__
120
#define strtoull(x, y, z) _strtoui64(x, y, z)
121
#define strtoll(x, y, z) _strtoi64(x, y, z)
122
#endif // _MSC_VER
123
124
#define ERRNO   GetLastError()
125
#define NO_SOCKLEN_T
126
#define SSL_LIB   "ssleay32.dll"
127
#define CRYPTO_LIB  "libeay32.dll"
128
#define O_NONBLOCK  0
129
#if !defined(EWOULDBLOCK)
130
#define EWOULDBLOCK  WSAEWOULDBLOCK
131
#endif // !EWOULDBLOCK
132
#define _POSIX_
133
#define INT64_FMT "I64d"
134
135
#define WINCDECL __cdecl
136
#define SHUT_WR 1
137
#define snprintf _snprintf
138
#define vsnprintf _vsnprintf
139
#define mg_sleep(x) Sleep(x)
140
141
#define pipe(x) _pipe(x, MG_BUF_LEN, _O_BINARY)
142
#define popen(x, y) _popen(x, y)
143
#define pclose(x) _pclose(x)
144
#define close(x) _close(x)
145
#define dlsym(x,y) GetProcAddress((HINSTANCE) (x), (y))
146
#define RTLD_LAZY  0
147
#define fseeko(x, y, z) _lseeki64(_fileno(x), (y), (z))
148
#define fdopen(x, y) _fdopen((x), (y))
149
#define write(x, y, z) _write((x), (y), (unsigned) z)
150
#define read(x, y, z) _read((x), (y), (unsigned) z)
151
#define flockfile(x) EnterCriticalSection(&global_log_file_lock)
152
#define funlockfile(x) LeaveCriticalSection(&global_log_file_lock)
153
// #define sleep(x) Sleep((x) * 1000)
154
#ifndef va_copy
155
#define va_copy(x, y) x = y
156
#endif
157
158
#if !defined(fileno)
159
#define fileno(x) _fileno(x)
160
#endif // !fileno MINGW #defines fileno
161
162
#if 0 /* NTOP */
163
typedef struct { HANDLE signal, broadcast; } pthread_cond_t;
164
165
typedef HANDLE pthread_mutex_t;
166
typedef DWORD pthread_t;
167
#define pid_t HANDLE // MINGW typedefs pid_t to int. Using #define here.
168
#endif
169
170
static void to_unicode(const char *path, wchar_t *wbuf, size_t wbuf_len);
171
struct file;
172
static char *mg_fgets(char *buf, size_t size, struct file *filep, char **p);
173
174
#if defined(HAVE_STDINT)
175
#include <stdint.h>
176
#else
177
typedef unsigned int  uint32_t;
178
typedef unsigned short  uint16_t;
179
typedef unsigned __int64 uint64_t;
180
typedef __int64   int64_t;
181
#ifndef INT64_MAX /* ntop */
182
#define INT64_MAX  9223372036854775807
183
#endif
184
#endif // HAVE_STDINT
185
186
// POSIX dirent interface
187
#if 0 /* ntop */
188
struct dirent {
189
  char d_name[PATH_MAX];
190
};
191
192
typedef struct DIR {
193
  HANDLE   handle;
194
  WIN32_FIND_DATAW info;
195
  struct dirent  result;
196
} DIR;
197
#endif
198
199
#ifndef HAS_POLL
200
struct pollfd {
201
  int fd;
202
  short events;
203
  short revents;
204
};
205
#define POLLIN 1
206
#endif
207
208
209
// Mark required libraries
210
#pragma comment(lib, "Ws2_32.lib")
211
212
#else    // UNIX  specific
213
#include <sys/wait.h>
214
#include <sys/socket.h>
215
#include <sys/poll.h>
216
#include <netinet/in.h>
217
#include <arpa/inet.h>
218
#include <sys/time.h>
219
#include <stdint.h>
220
#include <inttypes.h>
221
#include <netdb.h>
222
223
#include <pwd.h>
224
#include <unistd.h>
225
#include <dirent.h>
226
#if !defined(NO_SSL_DL) && !defined(NO_SSL)
227
#include <dlfcn.h>
228
#endif
229
#include <pthread.h>
230
#if defined(__MACH__)
231
#define SSL_LIB   "libssl.dylib"
232
#define CRYPTO_LIB  "libcrypto.dylib"
233
#else
234
#if !defined(SSL_LIB)
235
#define SSL_LIB   "libssl.so"
236
#endif
237
#if !defined(CRYPTO_LIB)
238
#define CRYPTO_LIB  "libcrypto.so"
239
#endif
240
#endif
241
#ifndef O_BINARY
242
#define O_BINARY  0
243
#endif // O_BINARY
244
245
#ifndef closesocket
246
0
#define closesocket(a) close(a)
247
#endif
248
0
#define mg_mkdir(x, y) mkdir(x, y)
249
0
#define mg_remove(x) remove(x)
250
#define mg_rename(x, y) rename(x, y)
251
0
#define mg_sleep(x) usleep((x) * 1000)
252
0
#define ERRNO errno
253
#ifndef INVALID_SOCKET
254
#define INVALID_SOCKET (-1)
255
#endif
256
257
/* ntop */
258
#if ((ULONG_MAX) == (UINT_MAX))
259
#define IS32BIT
260
#else
261
#define IS64BIT
262
#endif
263
264
#ifdef IS64BIT
265
#ifdef __MACH__
266
#define INT64_FMT "lld"
267
#else
268
0
#define INT64_FMT "ld"
269
#endif
270
#else
271
#define INT64_FMT "lld"
272
#endif
273
#ifndef INT64_MAX /* ntop */
274
#define INT64_MAX 0x7fffffffffffffffLL
275
#endif
276
277
//#define INT64_FMT PRId64
278
#ifndef SOCKET
279
typedef int SOCKET;
280
#endif
281
#define WINCDECL
282
283
#endif // End of Windows and UNIX specific includes
284
285
#include "mongoose.h"
286
287
#undef MONGOOSE_USE_LUA
288
289
#ifdef MONGOOSE_USE_LUA
290
291
#if 0
292
#include <lua.h>
293
#include <lauxlib.h>
294
#endif
295
296
#if 1 /* ntop */
297
#ifndef LUA_OK
298
#define LUA_OK          0
299
#endif
300
#endif
301
#endif
302
303
#ifdef  _NTOP_CLASS_H_
304
/* Disables CGI support, safer and prevents mongoose forking */
305
#define NO_CGI
306
#endif
307
308
0
#define MONGOOSE_VERSION "3.7"
309
0
#define PASSWORDS_FILE_NAME ".htpasswd"
310
#define CGI_ENVIRONMENT_SIZE 4096
311
#define MAX_CGI_ENVIR_VARS 64
312
#define MG_BUF_LEN 8192
313
0
#define MAX_REQUEST_SIZE 16384
314
0
#define ARRAY_SIZE(array) (sizeof(array) / sizeof(array[0]))
315
316
#ifdef _WIN32
317
static CRITICAL_SECTION global_log_file_lock;
318
319
static pthread_t pthread_self(void) {
320
  return (pthread_t)GetCurrentThreadId();
321
}
322
#endif // _WIN32
323
324
#ifdef DEBUG_TRACE
325
#undef DEBUG_TRACE
326
#define DEBUG_TRACE(x)
327
#else
328
#if defined(DEBUG)
329
#define DEBUG_TRACE(x) do {         \
330
    flockfile(stdout);            \
331
    printf("*** %lu.%p.%s.%d: ",        \
332
     (unsigned long) time(NULL), (void *) pthread_self(), \
333
     __func__, __LINE__);         \
334
    printf x;             \
335
    putchar('\n');            \
336
    fflush(stdout);           \
337
    funlockfile(stdout);          \
338
  } while (0)
339
#else
340
#define DEBUG_TRACE(x)
341
#endif // DEBUG
342
#endif // DEBUG_TRACE
343
344
// Darwin prior to 7.0 and Win32 do not have socklen_t
345
#ifdef NO_SOCKLEN_T
346
typedef int socklen_t;
347
#endif // NO_SOCKLEN_T
348
#define _DARWIN_UNLIMITED_SELECT
349
350
#if !defined(MSG_NOSIGNAL)
351
#define MSG_NOSIGNAL 0
352
#endif
353
354
#if !defined(SOMAXCONN)
355
#define SOMAXCONN 100
356
#endif
357
358
#if !defined(PATH_MAX)
359
#define PATH_MAX 4096
360
#endif
361
362
static const char *http_500_error = "Internal Server Error";
363
364
#if defined(NO_SSL_DL)
365
#include <openssl/ssl.h>
366
#include <openssl/err.h>
367
#else
368
// SSL loaded dynamically from DLL.
369
// I put the prototypes here to be independent from OpenSSL source installation.
370
typedef struct ssl_st SSL;
371
typedef struct ssl_method_st SSL_METHOD;
372
typedef struct ssl_ctx_st SSL_CTX;
373
374
struct ssl_func {
375
  const char *name;   // SSL function name
376
  void  (*ptr)(void); // Function pointer
377
};
378
379
#define SSL_free (* (void (*)(SSL *)) ssl_sw[0].ptr)
380
#define SSL_accept (* (int (*)(SSL *)) ssl_sw[1].ptr)
381
#define SSL_connect (* (int (*)(SSL *)) ssl_sw[2].ptr)
382
#define SSL_read (* (int (*)(SSL *, void *, int)) ssl_sw[3].ptr)
383
#define SSL_write (* (int (*)(SSL *, const void *,int)) ssl_sw[4].ptr)
384
#define SSL_get_error (* (int (*)(SSL *, int)) ssl_sw[5].ptr)
385
#define SSL_set_fd (* (int (*)(SSL *, SOCKET)) ssl_sw[6].ptr)
386
#define SSL_new (* (SSL * (*)(SSL_CTX *)) ssl_sw[7].ptr)
387
#define SSL_CTX_new (* (SSL_CTX * (*)(SSL_METHOD *)) ssl_sw[8].ptr)
388
#define SSLv23_server_method (* (SSL_METHOD * (*)(void)) ssl_sw[9].ptr)
389
#define SSL_library_init (* (int (*)(void)) ssl_sw[10].ptr)
390
#define SSL_CTX_use_PrivateKey_file (* (int (*)(SSL_CTX *,    \
391
            const char *, int)) ssl_sw[11].ptr)
392
#define SSL_CTX_use_certificate_file (* (int (*)(SSL_CTX *,   \
393
             const char *, int)) ssl_sw[12].ptr)
394
#define SSL_CTX_set_default_passwd_cb       \
395
  (* (void (*)(SSL_CTX *, mg_callback_t)) ssl_sw[13].ptr)
396
#define SSL_CTX_free (* (void (*)(SSL_CTX *)) ssl_sw[14].ptr)
397
#define SSL_load_error_strings (* (void (*)(void)) ssl_sw[15].ptr)
398
#define SSL_CTX_use_certificate_chain_file    \
399
  (* (int (*)(SSL_CTX *, const char *)) ssl_sw[16].ptr)
400
#define SSLv23_client_method (* (SSL_METHOD * (*)(void)) ssl_sw[17].ptr)
401
#define SSL_pending (* (int (*)(SSL *)) ssl_sw[18].ptr)
402
#define SSL_CTX_set_verify (* (void (*)(SSL_CTX *, int, int)) ssl_sw[19].ptr)
403
404
/* ntop */
405
#define SSL_CTX_set_cipher_list (* (int (*)(SSL_CTX *ctx, const char *str)) ssl_sw[20].ptr)
406
#define SSL_CTX_set_options (* (long (*)(SSL_CTX *ctx, long options))  ssl_sw[21].ptr)
407
#define SSL_CTX_get_options (* (long (*)(SSL_CTX *ctx))  ssl_sw[22].ptr)
408
#define SSL_CTX_set_min_proto_version (* (void (*)(SSL_CTX *ctx, int version))  ssl_sw[23].ptr)
409
#define CRYPTO_num_locks (* (int (*)(void)) crypto_sw[0].ptr)
410
#define CRYPTO_set_locking_callback         \
411
  (* (void (*)(void (*)(int, int, const char *, int))) crypto_sw[1].ptr)
412
#define CRYPTO_set_id_callback          \
413
  (* (void (*)(unsigned long (*)(void))) crypto_sw[2].ptr)
414
#define ERR_get_error (* (unsigned long (*)(void)) crypto_sw[3].ptr)
415
#define ERR_error_string (* (char * (*)(unsigned long,char *)) crypto_sw[4].ptr)
416
417
// set_ssl_option() function updates this array.
418
// It loads SSL library dynamically and changes NULLs to the actual addresses
419
// of respective functions. The macros above (like SSL_connect()) are really
420
// just calling these functions indirectly via the pointer.
421
static struct ssl_func ssl_sw[] = {
422
  {"SSL_free",   NULL},
423
  {"SSL_accept",   NULL},
424
  {"SSL_connect",   NULL},
425
  {"SSL_read",   NULL},
426
  {"SSL_write",   NULL},
427
  {"SSL_get_error",  NULL},
428
  {"SSL_set_fd",   NULL},
429
  {"SSL_new",   NULL},
430
  {"SSL_CTX_new",   NULL},
431
  {"SSLv23_server_method", NULL},
432
  {"SSL_library_init",  NULL},
433
  {"SSL_CTX_use_PrivateKey_file", NULL},
434
  {"SSL_CTX_use_certificate_file",NULL},
435
  {"SSL_CTX_set_default_passwd_cb",NULL},
436
  {"SSL_CTX_free",  NULL},
437
  {"SSL_load_error_strings", NULL},
438
  {"SSL_CTX_use_certificate_chain_file", NULL},
439
  {"SSLv23_client_method", NULL},
440
  {"SSL_pending", NULL},
441
  {"SSL_CTX_set_verify", NULL},
442
  {"SSL_CTX_set_cipher_list", NULL},
443
#ifndef __APPLE__
444
  {"SSL_CTX_set_options", NULL},
445
  {"SSL_CTX_get_options", NULL},
446
#ifdef MODERN_OPENSSL
447
  {"SSL_CTX_set_min_proto_version", NULL }, /* ntop */
448
#endif
449
#endif
450
  {NULL,    NULL}
451
};
452
453
// Similar array as ssl_sw. These functions could be located in different lib.
454
#if !defined(NO_SSL)
455
static struct ssl_func crypto_sw[] = {
456
  {"CRYPTO_num_locks",  NULL},
457
  {"CRYPTO_set_locking_callback", NULL},
458
  {"CRYPTO_set_id_callback", NULL},
459
  {"ERR_get_error",  NULL},
460
  {"ERR_error_string", NULL},
461
  {NULL,    NULL}
462
};
463
#endif // NO_SSL
464
#endif // NO_SSL_DL
465
466
static const char *month_names[] = {
467
  "Jan", "Feb", "Mar", "Apr", "May", "Jun",
468
  "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
469
};
470
471
// Describes a string (chunk of memory).
472
struct vec {
473
  const char *ptr;
474
  size_t len;
475
};
476
477
struct file {
478
  int is_directory;
479
  time_t modification_time;
480
  int64_t size;
481
  FILE *fp;
482
  const char *membuf;   // Non-NULL if file data is in memory
483
};
484
0
#define STRUCT_FILE_INITIALIZER {0, 0, 0, NULL, NULL}
485
486
// Describes listening socket, or socket which was accept()-ed by the master
487
// thread and queued for future handling by the worker thread.
488
struct socket {
489
  SOCKET sock;          // Listening socket
490
  union usa lsa;        // Local socket address
491
  union usa rsa;        // Remote socket address
492
  unsigned is_ssl:1;    // Is port SSL-ed
493
  unsigned ssl_redir:1; // Is port supposed to redirect everything to SSL port
494
};
495
496
// NOTE(lsm): this enum shoulds be in sync with the config_options below.
497
enum {
498
  CGI_EXTENSIONS, CGI_ENVIRONMENT, PUT_DELETE_PASSWORDS_FILE, CGI_INTERPRETER,
499
  PROTECT_URI, AUTHENTICATION_DOMAIN, SSI_EXTENSIONS, THROTTLE,
500
  ACCESS_LOG_FILE, ENABLE_DIRECTORY_LISTING, ERROR_LOG_FILE,
501
  GLOBAL_PASSWORDS_FILE, INDEX_FILES, ENABLE_KEEP_ALIVE, ACCESS_CONTROL_LIST,
502
  EXTRA_MIME_TYPES, LISTENING_PORTS, DOCUMENT_ROOT, SSL_CERTIFICATE,
503
  NUM_THREADS, RUN_AS_USER, REWRITE, HIDE_FILES, REQUEST_TIMEOUT,
504
  NUM_OPTIONS
505
};
506
507
static const char *config_options[] = {
508
  "C", "cgi_pattern", "**.cgi$|**.pl$|**.php$",
509
  "E", "cgi_environment", NULL,
510
  "G", "put_delete_auth_file", NULL,
511
  "I", "cgi_interpreter", NULL,
512
  "P", "protect_uri", NULL,
513
  "R", "authentication_domain", "mydomain.com",
514
  "S", "ssi_pattern", "**.shtml$|**.shtm$",
515
  "T", "throttle", NULL,
516
  "a", "access_log_file", NULL,
517
  "d", "enable_directory_listing", "yes",
518
  "e", "error_log_file", NULL,
519
  "g", "global_auth_file", NULL,
520
  "i", "index_files", "index.html,index.htm,index.cgi,index.shtml,index.php",
521
  "k", "enable_keep_alive", "no",
522
  "l", "access_control_list", NULL,
523
  "m", "extra_mime_types", NULL,
524
  "p", "listening_ports", "8080",
525
  "r", "document_root",  ".",
526
  "s", "ssl_certificate", NULL,
527
  "t", "num_threads", "20",
528
  "u", "run_as_user", NULL,
529
  "w", "url_rewrite_patterns", NULL,
530
  "x", "hide_files_patterns", NULL,
531
  "z", "request_timeout_ms", "30000",
532
  NULL
533
};
534
0
#define ENTRIES_PER_CONFIG_OPTION 3
535
536
struct mg_context {
537
  volatile int stop_flag;         // Should we stop event loop
538
  SSL_CTX *ssl_ctx;               // SSL context
539
  char *config[NUM_OPTIONS];      // Mongoose configuration parameters
540
  struct mg_callbacks callbacks;  // User-defined callback function
541
  void *user_data;                // User-defined data
542
543
  struct socket *listening_sockets;
544
  int num_listening_sockets;
545
546
  volatile int num_threads;  // Number of threads
547
  pthread_mutex_t mutex;     // Protects (max|num)_threads
548
  pthread_cond_t  cond;      // Condvar for tracking workers terminations
549
550
  struct socket queue[20];   // Accepted sockets
551
  volatile int sq_head;      // Head of the socket queue
552
  volatile int sq_tail;      // Tail of the socket queue
553
  pthread_cond_t sq_full;    // Signaled when socket is produced
554
  pthread_cond_t sq_empty;   // Signaled when socket is consumed
555
};
556
557
struct mg_connection {
558
  struct mg_request_info request_info;
559
  struct mg_context *ctx;
560
  SSL *ssl;                   // SSL descriptor
561
  SSL_CTX *client_ssl_ctx;    // SSL context for client connections
562
  struct socket client;       // Connected client
563
  time_t birth_time;          // Time when request was received
564
  int64_t num_bytes_sent;     // Total bytes sent to client
565
  int64_t content_len;        // Content-Length header value
566
  int64_t consumed_content;   // How many bytes of content have been read
567
  char *buf;                  // Buffer for received data
568
  char *path_info;            // PATH_INFO part of the URL
569
  int must_close;             // 1 if connection must be closed
570
  int buf_size;               // Buffer size
571
  int request_len;            // Size of the request + headers in a buffer
572
  int data_len;               // Total size of data in a buffer
573
  int status_code;            // HTTP reply status code, e.g. 200
574
  int throttle;               // Throttling, bytes/sec. <= 0 means no throttle
575
  time_t last_throttle_time;  // Last time throttled data was sent
576
  int64_t last_throttle_bytes;// Bytes sent this second
577
  int async_send;             // Asynchronous send
578
};
579
580
char* http_prefix = NULL; /* ntop */
581
u_int http_prefix_len = 0; /* ntop */
582
583
584
/* ntop */
585
#if defined(USE_IPV6)
586
u_int8_t is_ip6_enabled = 1;
587
588
0
static void check_ipv6_enabled() {
589
0
  const int sock6 = socket (AF_INET6, SOCK_DGRAM, 0);
590
0
  is_ip6_enabled = (sock6 >= 0) ? 1 : 0;
591
0
  closesocket (sock6);
592
0
}
593
#endif
594
595
/* ************************************************** */
596
597
0
const char **mg_get_valid_option_names(void) {
598
0
  return config_options;
599
0
}
600
601
static int is_file_in_memory(struct mg_connection *conn, const char *path,
602
0
           struct file *filep) {
603
0
  size_t size = 0;
604
0
  if ((filep->membuf = conn->ctx->callbacks.open_file == NULL ? NULL :
605
0
       conn->ctx->callbacks.open_file(conn, path, &size)) != NULL) {
606
    // NOTE: override filep->size only on success. Otherwise, it might break
607
    // constructs like if (!mg_stat() || !mg_fopen()) ...
608
0
    filep->size = size;
609
0
  }
610
0
  return filep->membuf != NULL;
611
0
}
612
613
0
static int is_file_opened(const struct file *filep) {
614
0
  return filep->membuf != NULL || filep->fp != NULL;
615
0
}
616
617
static int mg_fopen(struct mg_connection *conn, const char *path,
618
0
        const char *mode, struct file *filep) {
619
0
  if (!is_file_in_memory(conn, path, filep)) {
620
#ifdef _WIN32
621
    wchar_t wbuf[PATH_MAX], wmode[20];
622
    to_unicode(path, wbuf, ARRAY_SIZE(wbuf));
623
    MultiByteToWideChar(CP_UTF8, 0, mode, -1, wmode, ARRAY_SIZE(wmode));
624
    filep->fp = _wfopen(wbuf, wmode);
625
#else
626
0
    filep->fp = fopen(path, mode);
627
0
#endif
628
0
  }
629
630
0
  return is_file_opened(filep);
631
0
}
632
633
0
static void mg_fclose(struct file *filep) {
634
0
  if (filep != NULL && filep->fp != NULL) {
635
0
    fclose(filep->fp);
636
0
  }
637
0
}
638
639
0
static int get_option_index(const char *name) {
640
0
  int i;
641
642
0
  for (i = 0; config_options[i] != NULL; i += ENTRIES_PER_CONFIG_OPTION) {
643
0
    if (strcmp(config_options[i], name) == 0 ||
644
0
  strcmp(config_options[i + 1], name) == 0) {
645
0
      return i / ENTRIES_PER_CONFIG_OPTION;
646
0
    }
647
0
  }
648
0
  return -1;
649
0
}
650
651
0
const char *mg_get_option(const struct mg_context *ctx, const char *name) {
652
0
  int i;
653
0
  if ((i = get_option_index(name)) == -1) {
654
0
    return NULL;
655
0
  } else if (ctx->config[i] == NULL) {
656
0
    return "";
657
0
  } else {
658
0
    return ctx->config[i];
659
0
  }
660
0
}
661
662
static void sockaddr_to_string(char *buf, size_t len,
663
0
             const union usa *usa) {
664
0
  buf[0] = '\0';
665
0
#if defined(USE_IPV6)
666
0
  inet_ntop(usa->sa.sa_family, usa->sa.sa_family == AF_INET ?
667
0
      (void *) &usa->sin.sin_addr :
668
0
      (void *) &usa->sin6.sin6_addr, buf, len);
669
#elif defined(_WIN32)
670
  // Only Windoze Vista (and newer) have inet_ntop()
671
  strncpy(buf, inet_ntoa(usa->sin.sin_addr), len);
672
#else
673
  inet_ntop(usa->sa.sa_family, (void *) &usa->sin.sin_addr, buf, len);
674
#endif
675
0
}
676
677
static void cry(struct mg_connection *conn,
678
    PRINTF_FORMAT_STRING(const char *fmt), ...) PRINTF_ARGS(2, 3);
679
680
static void cry_connection(struct mg_connection *conn, const char *buf);
681
682
// Print error message to the opened error log stream.
683
0
static void cry(struct mg_connection *conn, const char *fmt, ...) {
684
0
  char buf[MG_BUF_LEN];
685
0
  va_list ap;
686
687
0
  va_start(ap, fmt);
688
0
  (void) vsnprintf(buf, sizeof(buf), fmt, ap);
689
0
  va_end(ap);
690
691
  // Do not lock when getting the callback value, here and below.
692
  // I suppose this is fine, since function cannot disappear in the
693
  // same way string option can.
694
0
  if (conn->ctx->callbacks.log_message == NULL ||
695
0
      conn->ctx->callbacks.log_message(conn, buf) == 0) {
696
0
    cry_connection(conn, buf);
697
0
  }
698
0
}
699
700
0
static void cry_connection(struct mg_connection *conn, const char *buf) {
701
0
    char src_addr[20];
702
0
    FILE *fp;
703
0
    time_t timestamp;
704
705
0
    fp = conn->ctx == NULL || conn->ctx->config[ERROR_LOG_FILE] == NULL ? NULL :
706
0
      fopen(conn->ctx->config[ERROR_LOG_FILE], "a+");
707
708
0
    if (fp != NULL) {
709
0
      flockfile(fp);
710
0
      timestamp = time(NULL);
711
712
0
      sockaddr_to_string(src_addr, sizeof(src_addr), &conn->client.rsa);
713
0
      fprintf(fp, "[%010lu] [error] [client %s] ", (unsigned long) timestamp,
714
0
        src_addr);
715
716
0
      if (conn->request_info.request_method != NULL) {
717
0
  fprintf(fp, "%s %s: ", conn->request_info.request_method,
718
0
    conn->request_info.uri);
719
0
      }
720
721
0
      fprintf(fp, "%s", buf);
722
0
      fputc('\n', fp);
723
0
      funlockfile(fp);
724
0
      fclose(fp);
725
0
    }
726
0
}
727
728
// Return fake connection structure. Used for logging, if connection
729
// is not applicable at the moment of logging.
730
0
static struct mg_connection *fc(struct mg_context *ctx) {
731
0
  static struct mg_connection fake_connection;
732
0
  fake_connection.ctx = ctx;
733
0
  return &fake_connection;
734
0
}
735
736
0
const char *mg_version(void) {
737
0
  return MONGOOSE_VERSION;
738
0
}
739
740
0
struct mg_request_info *mg_get_request_info(struct mg_connection *conn) {
741
0
  return &conn->request_info;
742
0
}
743
744
0
union usa *mg_get_client_address(struct mg_connection *conn) {
745
0
  return &conn->client.rsa;
746
0
}
747
748
0
static void mg_strlcpy(char *dst, const char *src, size_t n) {
749
0
  for (; *src != '\0' && n > 1; n--) {
750
0
    *dst++ = *src++;
751
0
  }
752
0
  *dst = '\0';
753
0
}
754
755
0
static int lowercase(const char *s) {
756
0
  return tolower(* (const unsigned char *) s);
757
0
}
758
759
0
static int mg_strncasecmp(const char *s1, const char *s2, size_t len) {
760
0
  int diff = 0;
761
762
0
  if (len > 0)
763
0
    do {
764
0
      diff = lowercase(s1++) - lowercase(s2++);
765
0
    } while (diff == 0 && s1[-1] != '\0' && --len > 0);
766
767
0
  return diff;
768
0
}
769
770
0
static int mg_strcasecmp(const char *s1, const char *s2) {
771
0
  int diff;
772
773
0
  do {
774
0
    diff = lowercase(s1++) - lowercase(s2++);
775
0
  } while (diff == 0 && s1[-1] != '\0');
776
777
0
  return diff;
778
0
}
779
780
0
static char * mg_strndup(const char *ptr, size_t len) {
781
0
  char *p;
782
783
0
  if ((p = (char *) malloc(len + 1)) != NULL) {
784
0
    mg_strlcpy(p, ptr, len + 1);
785
0
  }
786
787
0
  return p;
788
0
}
789
790
0
static char * mg_strdup(const char *str) {
791
0
  return mg_strndup(str, strlen(str));
792
0
}
793
794
// Like snprintf(), but never returns negative value, or a value
795
// that is larger than a supplied buffer.
796
// Thanks to Adam Zeldis to pointing snprintf()-caused vulnerability
797
// in his audit report.
798
static int mg_vsnprintf(struct mg_connection *conn, char *buf, size_t buflen,
799
0
      const char *fmt, va_list ap) {
800
0
  int n;
801
802
0
  if (buflen == 0)
803
0
    return 0;
804
805
0
  n = vsnprintf(buf, buflen, fmt, ap);
806
807
0
  if (n < 0) {
808
0
    cry(conn, "vsnprintf error");
809
0
    n = 0;
810
0
  } else if (n >= (int) buflen) {
811
0
    cry(conn, "truncating vsnprintf buffer: [%.*s]",
812
0
  n > 200 ? 200 : n, buf);
813
0
    n = (int) buflen - 1;
814
0
  }
815
0
  buf[n] = '\0';
816
817
0
  return n;
818
0
}
819
820
static int mg_snprintf(struct mg_connection *conn, char *buf, size_t buflen,
821
           PRINTF_FORMAT_STRING(const char *fmt), ...)
822
  PRINTF_ARGS(4, 5);
823
824
static int mg_snprintf(struct mg_connection *conn, char *buf, size_t buflen,
825
0
           const char *fmt, ...) {
826
0
  va_list ap;
827
0
  int n;
828
829
0
  va_start(ap, fmt);
830
0
  n = mg_vsnprintf(conn, buf, buflen, fmt, ap);
831
0
  va_end(ap);
832
833
0
  return n;
834
0
}
835
836
// Skip the characters until one of the delimiters characters found.
837
// 0-terminate resulting word. Skip the delimiter and following whitespaces.
838
// Advance pointer to buffer to the next word. Return found 0-terminated word.
839
// Delimiters can be quoted with quotechar.
840
static char *skip_quoted(char **buf, const char *delimiters,
841
0
       const char *whitespace, char quotechar) {
842
0
  char *p, *begin_word, *end_word, *end_whitespace;
843
844
0
  begin_word = *buf;
845
0
  end_word = begin_word + strcspn(begin_word, delimiters);
846
847
  // Check for quotechar
848
0
  if (end_word > begin_word) {
849
0
    p = end_word - 1;
850
0
    while (*p == quotechar) {
851
      // If there is anything beyond end_word, copy it
852
0
      if (*end_word == '\0') {
853
0
  *p = '\0';
854
0
  break;
855
0
      } else {
856
0
  size_t end_off = strcspn(end_word + 1, delimiters);
857
0
  memmove (p, end_word, end_off + 1);
858
0
  p += end_off; // p must correspond to end_word - 1
859
0
  end_word += end_off + 1;
860
0
      }
861
0
    }
862
0
    for (p++; p < end_word; p++) {
863
0
      *p = '\0';
864
0
    }
865
0
  }
866
867
0
  if (*end_word == '\0') {
868
0
    *buf = end_word;
869
0
  } else {
870
0
    end_whitespace = end_word + 1 + strspn(end_word + 1, whitespace);
871
872
0
    for (p = end_word; p < end_whitespace; p++) {
873
0
      *p = '\0';
874
0
    }
875
876
0
    *buf = end_whitespace;
877
0
  }
878
879
0
  return begin_word;
880
0
}
881
882
// Simplified version of skip_quoted without quote char
883
// and whitespace == delimiters
884
0
static char *skip(char **buf, const char *delimiters) {
885
0
  return skip_quoted(buf, delimiters, delimiters, 0);
886
0
}
887
888
889
// Return HTTP header value, or NULL if not found.
890
static const char *get_header(const struct mg_request_info *ri,
891
0
            const char *name) {
892
0
  int i;
893
894
0
  if(!ri) return NULL;
895
896
0
  for (i = 0; i < ri->num_headers; i++)
897
0
    if (!mg_strcasecmp(name, ri->http_headers[i].name))
898
0
      return ri->http_headers[i].value;
899
900
0
  return NULL;
901
0
}
902
903
0
const char *mg_get_header(const struct mg_connection *conn, const char *name) {
904
0
  return get_header(&conn->request_info, name);
905
0
}
906
907
// A helper function for traversing a comma separated list of values.
908
// It returns a list pointer shifted to the next value, or NULL if the end
909
// of the list found.
910
// Value is stored in val vector. If value has form "x=y", then eq_val
911
// vector is initialized to point to the "y" part, and val vector length
912
// is adjusted to point only to "x".
913
static const char *next_option(const char *list, struct vec *val,
914
0
             struct vec *eq_val) {
915
0
  if (list == NULL || *list == '\0') {
916
    // End of the list
917
0
    list = NULL;
918
0
  } else {
919
0
    val->ptr = list;
920
0
    if ((list = strchr(val->ptr, ',')) != NULL) {
921
      // Comma found. Store length and shift the list ptr
922
0
      val->len = list - val->ptr;
923
0
      list++;
924
0
    } else {
925
      // This value is the last one
926
0
      list = val->ptr + strlen(val->ptr);
927
0
      val->len = list - val->ptr;
928
0
    }
929
930
0
    if (eq_val != NULL) {
931
      // Value has form "x=y", adjust pointers and lengths
932
      // so that val points to "x", and eq_val points to "y".
933
0
      eq_val->len = 0;
934
0
      eq_val->ptr = (const char *) memchr(val->ptr, '=', val->len);
935
0
      if (eq_val->ptr != NULL) {
936
0
  eq_val->ptr++;  // Skip over '=' character
937
0
  eq_val->len = val->ptr + val->len - eq_val->ptr;
938
0
  val->len = (eq_val->ptr - val->ptr) - 1;
939
0
      }
940
0
    }
941
0
  }
942
943
0
  return list;
944
0
}
945
946
0
static int match_prefix(const char *pattern, int pattern_len, const char *str) {
947
0
  const char *or_str;
948
0
  int i, j, len, res;
949
950
0
  if ((or_str = (const char *) memchr(pattern, '|', pattern_len)) != NULL) {
951
0
    res = match_prefix(pattern, or_str - pattern, str);
952
0
    return res > 0 ? res :
953
0
      match_prefix(or_str + 1, (pattern + pattern_len) - (or_str + 1), str);
954
0
  }
955
956
0
  i = j = 0;
957
0
  res = -1;
958
0
  for (; i < pattern_len; i++, j++) {
959
0
    if (pattern[i] == '?' && str[j] != '\0') {
960
0
      continue;
961
0
    } else if (pattern[i] == '$') {
962
0
      return str[j] == '\0' ? j : -1;
963
0
    } else if (pattern[i] == '*') {
964
0
      i++;
965
0
      if (pattern[i] == '*') {
966
0
  i++;
967
0
  len = (int) strlen(str + j);
968
0
      } else {
969
0
  len = (int) strcspn(str + j, "/");
970
0
      }
971
0
      if (i == pattern_len) {
972
0
  return j + len;
973
0
      }
974
0
      do {
975
0
  res = match_prefix(pattern + i, pattern_len - i, str + j + len);
976
0
      } while (res == -1 && len-- > 0);
977
0
      return res == -1 ? -1 : j + res + len;
978
0
    } else if (pattern[i] != str[j]) {
979
0
      return -1;
980
0
    }
981
0
  }
982
0
  return j;
983
0
}
984
985
// HTTP 1.1 assumes keep alive if "Connection:" header is not set
986
// This function must tolerate situations when connection info is not
987
// set up, for example if request parsing failed.
988
0
static int should_keep_alive(const struct mg_connection *conn) {
989
0
  const char *http_version = conn->request_info.http_version;
990
0
  const char *header = mg_get_header(conn, "Connection");
991
0
  if (conn->must_close ||
992
0
      conn->status_code == 401 ||
993
0
      mg_strcasecmp(conn->ctx->config[ENABLE_KEEP_ALIVE], "yes") != 0 ||
994
0
      (header != NULL && mg_strcasecmp(header, "keep-alive") != 0) ||
995
0
      (header == NULL && http_version && strcmp(http_version, "1.1"))) {
996
0
    return 0;
997
0
  }
998
0
  return 1;
999
0
}
1000
1001
0
static const char *suggest_connection_header(const struct mg_connection *conn) {
1002
0
  return should_keep_alive(conn) ? "keep-alive" : "close";
1003
0
}
1004
1005
static void send_http_error(struct mg_connection *, int, const char *,
1006
          PRINTF_FORMAT_STRING(const char *fmt), ...)
1007
  PRINTF_ARGS(4, 5);
1008
1009
1010
static void send_http_error(struct mg_connection *conn, int status,
1011
0
          const char *reason, const char *fmt, ...) {
1012
0
  char buf[MG_BUF_LEN];
1013
0
  va_list ap;
1014
0
  int len = 0;
1015
1016
0
  conn->status_code = status;
1017
0
  buf[0] = '\0';
1018
1019
  // Errors 1xx, 204 and 304 MUST NOT send a body
1020
0
  if (status > 199 && status != 204 && status != 304) {
1021
0
    len = mg_snprintf(conn, buf, sizeof(buf), "Error %d: %s", status, reason);
1022
0
    buf[len++] = '\n';
1023
1024
0
    va_start(ap, fmt);
1025
0
    len += mg_vsnprintf(conn, buf + len, sizeof(buf) - len, fmt, ap);
1026
0
    va_end(ap);
1027
0
  }
1028
0
  DEBUG_TRACE(("[%s]", buf));
1029
1030
0
  mg_printf(conn, "HTTP/1.1 %d %s\r\n"
1031
0
      "Content-Length: %d\r\n"
1032
0
      "Connection: %s\r\n\r\n", status, reason, len,
1033
0
      suggest_connection_header(conn));
1034
0
  conn->num_bytes_sent += mg_printf(conn, "%s", buf);
1035
1036
0
  traceHTTP(conn, (u_int16_t)status);
1037
0
}
1038
1039
#if defined(_WIN32) && !defined(__SYMBIAN32__)
1040
1041
#if 0
1042
/* static */int pthread_mutex_init(pthread_mutex_t *mutex, void *unused) {
1043
  unused = NULL;
1044
  *mutex = CreateMutex(NULL, FALSE, NULL);
1045
  return *mutex == NULL ? -1 : 0;
1046
}
1047
1048
/* static */int pthread_mutex_destroy(pthread_mutex_t *mutex) {
1049
  return CloseHandle(*mutex) == 0 ? -1 : 0;
1050
}
1051
1052
/* static */int pthread_mutex_lock(pthread_mutex_t *mutex) {
1053
  return WaitForSingleObject(*mutex, INFINITE) == WAIT_OBJECT_0? 0 : -1;
1054
}
1055
1056
/* static */int pthread_mutex_unlock(pthread_mutex_t *mutex) {
1057
  return ReleaseMutex(*mutex) == 0 ? -1 : 0;
1058
}
1059
#endif
1060
1061
#if 0 /* see ntop_win32.c */
1062
/* static */int pthread_cond_init(pthread_cond_t *cv, const void *unused) {
1063
  unused = NULL;
1064
  cv->signal = CreateEvent(NULL, FALSE, FALSE, NULL);
1065
  cv->broadcast = CreateEvent(NULL, TRUE, FALSE, NULL);
1066
  return cv->signal != NULL && cv->broadcast != NULL ? 0 : -1;
1067
}
1068
1069
/* static */int pthread_cond_wait(pthread_cond_t *cv, pthread_mutex_t *mutex) {
1070
  HANDLE handles[] = {cv->signal, cv->broadcast};
1071
  ReleaseMutex(*mutex);
1072
  WaitForMultipleObjects(2, handles, FALSE, INFINITE);
1073
  return WaitForSingleObject(*mutex, INFINITE) == WAIT_OBJECT_0? 0 : -1;
1074
}
1075
1076
/* static */int pthread_cond_signal(pthread_cond_t *cv) {
1077
  return SetEvent(cv->signal) == 0 ? -1 : 0;
1078
}
1079
1080
/* static */int pthread_cond_broadcast(pthread_cond_t *cv) {
1081
  // Implementation with PulseEvent() has race condition, see
1082
  // http://www.cs.wustl.edu/~schmidt/win32-cv-1.html
1083
  return PulseEvent(cv->broadcast) == 0 ? -1 : 0;
1084
}
1085
1086
/* static */int pthread_cond_timedwait(pthread_cond_t* cv, pthread_mutex_t* mutex, const struct timespec* abstime) {
1087
    HANDLE handles[] = { cv->signal, cv->broadcast };
1088
    DWORD msec = abstime->tv_sec * 1000 + abstime->tv_sec / 1000;
1089
1090
    ReleaseMutex(*mutex);
1091
    WaitForMultipleObjects(2, handles, FALSE, msec);
1092
    return WaitForSingleObject(*mutex, msec) == WAIT_OBJECT_0 ? 0 : -1;
1093
}
1094
1095
/* static */int pthread_cond_destroy(pthread_cond_t *cv) {
1096
  return CloseHandle(cv->signal) && CloseHandle(cv->broadcast) ? 0 : -1;
1097
}
1098
#endif
1099
1100
1101
// For Windows, change all slashes to backslashes in path names.
1102
static void change_slashes_to_backslashes(char *path) {
1103
  int i;
1104
1105
  for (i = 0; path[i] != '\0'; i++) {
1106
    if (path[i] == '/')
1107
      path[i] = '\\';
1108
    // i > 0 check is to preserve UNC paths, like \\server\file.txt
1109
    if (path[i] == '\\' && i > 0)
1110
      while (path[i + 1] == '\\' || path[i + 1] == '/')
1111
  (void) memmove(path + i + 1,
1112
           path + i + 2, strlen(path + i + 1));
1113
  }
1114
}
1115
1116
// Encode 'path' which is assumed UTF-8 string, into UNICODE string.
1117
// wbuf and wbuf_len is a target buffer and its length.
1118
static void to_unicode(const char *path, wchar_t *wbuf, size_t wbuf_len) {
1119
  char buf[PATH_MAX], buf2[PATH_MAX], *p;
1120
1121
  mg_strlcpy(buf, path, sizeof(buf));
1122
  change_slashes_to_backslashes(buf);
1123
1124
  // Point p to the end of the file name
1125
  p = buf + strlen(buf) - 1;
1126
1127
  // Convert to Unicode and back. If doubly-converted string does not
1128
  // match the original, something is fishy, reject.
1129
  memset(wbuf, 0, wbuf_len * sizeof(wchar_t));
1130
  MultiByteToWideChar(CP_UTF8, 0, buf, -1, wbuf, (int) wbuf_len);
1131
  WideCharToMultiByte(CP_UTF8, 0, wbuf, (int) wbuf_len, buf2, sizeof(buf2),
1132
          NULL, NULL);
1133
  if (strcmp(buf, buf2) != 0) {
1134
    wbuf[0] = L'\0';
1135
  }
1136
}
1137
1138
#if defined(_WIN32_WCE)
1139
static time_t time(time_t *ptime) {
1140
  time_t t;
1141
  SYSTEMTIME st;
1142
  FILETIME ft;
1143
1144
  GetSystemTime(&st);
1145
  SystemTimeToFileTime(&st, &ft);
1146
  t = SYS2UNIX_TIME(ft.dwLowDateTime, ft.dwHighDateTime);
1147
1148
  if (ptime != NULL) {
1149
    *ptime = t;
1150
  }
1151
1152
  return t;
1153
}
1154
1155
static struct tm *localtime(const time_t *ptime, struct tm *ptm) {
1156
  int64_t t = ((int64_t) *ptime) * RATE_DIFF + EPOCH_DIFF;
1157
  FILETIME ft, lft;
1158
  SYSTEMTIME st;
1159
  TIME_ZONE_INFORMATION tzinfo;
1160
1161
  if (ptm == NULL) {
1162
    return NULL;
1163
  }
1164
1165
  * (int64_t *) &ft = t;
1166
  FileTimeToLocalFileTime(&ft, &lft);
1167
  FileTimeToSystemTime(&lft, &st);
1168
  ptm->tm_year = st.wYear - 1900;
1169
  ptm->tm_mon = st.wMonth - 1;
1170
  ptm->tm_wday = st.wDayOfWeek;
1171
  ptm->tm_mday = st.wDay;
1172
  ptm->tm_hour = st.wHour;
1173
  ptm->tm_min = st.wMinute;
1174
  ptm->tm_sec = st.wSecond;
1175
  ptm->tm_yday = 0; // hope nobody uses this
1176
  ptm->tm_isdst =
1177
    GetTimeZoneInformation(&tzinfo) == TIME_ZONE_ID_DAYLIGHT ? 1 : 0;
1178
1179
  return ptm;
1180
}
1181
1182
static struct tm *gmtime(const time_t *ptime, struct tm *ptm) {
1183
  // FIXME(lsm): fix this.
1184
  return localtime(ptime, ptm);
1185
}
1186
1187
static size_t strftime(char *dst, size_t dst_size, const char *fmt,
1188
           const struct tm *tm) {
1189
  (void) snprintf(dst, dst_size, "implement strftime() for WinCE");
1190
  return 0;
1191
}
1192
#endif
1193
1194
static int mg_rename(const char* oldname, const char* newname) {
1195
  wchar_t woldbuf[PATH_MAX];
1196
  wchar_t wnewbuf[PATH_MAX];
1197
1198
  to_unicode(oldname, woldbuf, ARRAY_SIZE(woldbuf));
1199
  to_unicode(newname, wnewbuf, ARRAY_SIZE(wnewbuf));
1200
1201
  return MoveFileW(woldbuf, wnewbuf) ? 0 : -1;
1202
}
1203
1204
// Windows happily opens files with some garbage at the end of file name.
1205
// For example, fopen("a.cgi    ", "r") on Windows successfully opens
1206
// "a.cgi", despite one would expect an error back.
1207
// This function returns non-0 if path ends with some garbage.
1208
static int path_cannot_disclose_cgi(const char *path) {
1209
  static const char *allowed_last_characters = "_-";
1210
  int last = path[strlen(path) - 1];
1211
  return isalnum(last) || strchr(allowed_last_characters, last) != NULL;
1212
}
1213
1214
static int mg_stat(struct mg_connection *conn, const char *path,
1215
       struct file *filep) {
1216
  wchar_t wbuf[PATH_MAX];
1217
  WIN32_FILE_ATTRIBUTE_DATA info;
1218
1219
  if (!is_file_in_memory(conn, path, filep)) {
1220
    to_unicode(path, wbuf, ARRAY_SIZE(wbuf));
1221
    if (GetFileAttributesExW(wbuf, GetFileExInfoStandard, &info) != 0) {
1222
      filep->size = MAKEUQUAD(info.nFileSizeLow, info.nFileSizeHigh);
1223
      filep->modification_time = SYS2UNIX_TIME(
1224
                 info.ftLastWriteTime.dwLowDateTime,
1225
                 info.ftLastWriteTime.dwHighDateTime);
1226
      filep->is_directory = info.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY;
1227
      // If file name is fishy, reset the file structure and return error.
1228
      // Note it is important to reset, not just return the error, cause
1229
      // functions like is_file_opened() check the struct.
1230
      if (!filep->is_directory && !path_cannot_disclose_cgi(path)) {
1231
  memset(filep, 0, sizeof(*filep));
1232
      }
1233
    }
1234
  }
1235
1236
  return filep->membuf != NULL || filep->modification_time != 0;
1237
}
1238
1239
static int mg_remove(const char *path) {
1240
  wchar_t wbuf[PATH_MAX];
1241
  to_unicode(path, wbuf, ARRAY_SIZE(wbuf));
1242
  return DeleteFileW(wbuf) ? 0 : -1;
1243
}
1244
1245
static int mg_mkdir(const char *path, int mode) {
1246
  char buf[PATH_MAX];
1247
  wchar_t wbuf[PATH_MAX];
1248
1249
  mode = 0; // Unused
1250
  mg_strlcpy(buf, path, sizeof(buf));
1251
  change_slashes_to_backslashes(buf);
1252
1253
  (void) MultiByteToWideChar(CP_UTF8, 0, buf, -1, wbuf, ARRAY_SIZE(wbuf));
1254
1255
  return CreateDirectoryW(wbuf, NULL) ? 0 : -1;
1256
}
1257
1258
// Implementation of POSIX opendir/closedir/readdir for Windows.
1259
/*static*/ DIR * opendir(const char *name) {
1260
  DIR *dir = NULL;
1261
  wchar_t wpath[PATH_MAX];
1262
  DWORD attrs;
1263
1264
  if (name == NULL) {
1265
    SetLastError(ERROR_BAD_ARGUMENTS);
1266
  } else if ((dir = (DIR *) malloc(sizeof(*dir))) == NULL) {
1267
    SetLastError(ERROR_NOT_ENOUGH_MEMORY);
1268
  } else {
1269
    to_unicode(name, wpath, ARRAY_SIZE(wpath));
1270
    attrs = GetFileAttributesW(wpath);
1271
    if (attrs != 0xFFFFFFFF &&
1272
  ((attrs & FILE_ATTRIBUTE_DIRECTORY) == FILE_ATTRIBUTE_DIRECTORY)) {
1273
      (void) wcscat(wpath, L"\\*");
1274
      dir->handle = FindFirstFileW(wpath, &dir->info);
1275
      dir->result.d_name[0] = '\0';
1276
    } else {
1277
      free(dir);
1278
      dir = NULL;
1279
    }
1280
  }
1281
1282
  return dir;
1283
}
1284
1285
/*static*/ int closedir(DIR *dir) {
1286
  int result = 0;
1287
1288
  if (dir != NULL) {
1289
    if (dir->handle != INVALID_HANDLE_VALUE)
1290
      result = FindClose(dir->handle) ? 0 : -1;
1291
1292
    free(dir);
1293
  } else {
1294
    result = -1;
1295
    SetLastError(ERROR_BAD_ARGUMENTS);
1296
  }
1297
1298
  return result;
1299
}
1300
1301
/*static*/ struct dirent *readdir(DIR *dir) {
1302
  struct dirent *result = 0;
1303
1304
  if (dir) {
1305
    if (dir->handle != INVALID_HANDLE_VALUE) {
1306
      result = &dir->result;
1307
      (void) WideCharToMultiByte(CP_UTF8, 0,
1308
         dir->info.cFileName, -1, result->d_name,
1309
         sizeof(result->d_name), NULL, NULL);
1310
1311
      if (!FindNextFileW(dir->handle, &dir->info)) {
1312
  (void) FindClose(dir->handle);
1313
  dir->handle = INVALID_HANDLE_VALUE;
1314
      }
1315
1316
    } else {
1317
      SetLastError(ERROR_FILE_NOT_FOUND);
1318
    }
1319
  } else {
1320
    SetLastError(ERROR_BAD_ARGUMENTS);
1321
  }
1322
1323
  return result;
1324
}
1325
1326
int readdir_r(DIR *dirp, struct dirent *entry, struct dirent **result) {
1327
  *result = readdir(dirp);
1328
1329
  if (*result == NULL)
1330
    return(-1);
1331
  else
1332
    return(0);
1333
}
1334
1335
#ifndef HAVE_POLL
1336
static int poll(struct pollfd *pfd, int n, int milliseconds) {
1337
  struct timeval tv;
1338
  fd_set set;
1339
  int i, result;
1340
1341
  tv.tv_sec = milliseconds / 1000;
1342
  tv.tv_usec = (milliseconds % 1000) * 1000;
1343
  FD_ZERO(&set);
1344
1345
  for (i = 0; i < n; i++) {
1346
    FD_SET((SOCKET) pfd[i].fd, &set);
1347
    pfd[i].revents = 0;
1348
  }
1349
1350
  if ((result = select(0, &set, NULL, NULL, &tv)) > 0) {
1351
    for (i = 0; i < n; i++) {
1352
      if (FD_ISSET(pfd[i].fd, &set)) {
1353
  pfd[i].revents = POLLIN;
1354
      }
1355
    }
1356
  }
1357
1358
  return result;
1359
}
1360
#endif // HAVE_POLL
1361
1362
#define set_close_on_exec(x) // No FD_CLOEXEC on Windows
1363
1364
int mg_start_thread(mg_thread_func_t f, void *p) {
1365
  return _beginthread((void (__cdecl *)(void *)) f, 0, p) == -1L ? -1 : 0;
1366
}
1367
1368
static HANDLE dlopen(const char *dll_name, int flags) {
1369
  wchar_t wbuf[PATH_MAX];
1370
  flags = 0; // Unused
1371
  to_unicode(dll_name, wbuf, ARRAY_SIZE(wbuf));
1372
  return LoadLibraryW(wbuf);
1373
}
1374
1375
#if !defined(NO_CGI)
1376
#define SIGKILL 0
1377
static int kill(pid_t pid, int sig_num) {
1378
  (void) TerminateProcess(pid, sig_num);
1379
  (void) CloseHandle(pid);
1380
  return 0;
1381
}
1382
1383
static void trim_trailing_whitespaces(char *s) {
1384
  char *e = s + strlen(s) - 1;
1385
  while (e > s && isspace(* (unsigned char *) e)) {
1386
    *e-- = '\0';
1387
  }
1388
}
1389
1390
static pid_t spawn_process(struct mg_connection *conn, const char *prog,
1391
         char *envblk, char *envp[], int fd_stdin,
1392
         int fd_stdout, const char *dir) {
1393
  HANDLE me;
1394
  char *p, *interp, full_interp[PATH_MAX], full_dir[PATH_MAX],
1395
    cmdline[PATH_MAX], buf[PATH_MAX];
1396
  struct file file = STRUCT_FILE_INITIALIZER;
1397
  STARTUPINFOA si = { sizeof(si) };
1398
  PROCESS_INFORMATION pi = { 0 };
1399
1400
  envp = NULL; // Unused
1401
1402
  // TODO(lsm): redirect CGI errors to the error log file
1403
  si.dwFlags = STARTF_USESTDHANDLES | STARTF_USESHOWWINDOW;
1404
  si.wShowWindow = SW_HIDE;
1405
1406
  me = GetCurrentProcess();
1407
  DuplicateHandle(me, (HANDLE) _get_osfhandle(fd_stdin), me,
1408
      &si.hStdInput, 0, TRUE, DUPLICATE_SAME_ACCESS);
1409
  DuplicateHandle(me, (HANDLE) _get_osfhandle(fd_stdout), me,
1410
      &si.hStdOutput, 0, TRUE, DUPLICATE_SAME_ACCESS);
1411
1412
  // If CGI file is a script, try to read the interpreter line
1413
  interp = conn->ctx->config[CGI_INTERPRETER];
1414
  if (interp == NULL) {
1415
    buf[0] = buf[1] = '\0';
1416
1417
    // Read the first line of the script into the buffer
1418
    snprintf(cmdline, sizeof(cmdline), "%s%c%s", dir, '/', prog);
1419
    if (mg_fopen(conn, cmdline, "r", &file)) {
1420
      p = (char *) file.membuf;
1421
      mg_fgets(buf, sizeof(buf), &file, &p);
1422
      mg_fclose(&file);
1423
      buf[sizeof(buf) - 1] = '\0';
1424
    }
1425
1426
    if (buf[0] == '#' && buf[1] == '!') {
1427
      trim_trailing_whitespaces(buf + 2);
1428
    } else {
1429
      buf[2] = '\0';
1430
    }
1431
    interp = buf + 2;
1432
  }
1433
1434
  if (interp[0] != '\0') {
1435
    GetFullPathNameA(interp, sizeof(full_interp), full_interp, NULL);
1436
    interp = full_interp;
1437
  }
1438
  GetFullPathNameA(dir, sizeof(full_dir), full_dir, NULL);
1439
1440
  mg_snprintf(conn, cmdline, sizeof(cmdline), "%s%s%s\\%s",
1441
        interp, interp[0] == '\0' ? "" : " ", full_dir, prog);
1442
1443
  DEBUG_TRACE(("Running [%s]", cmdline));
1444
  if (CreateProcessA(NULL, cmdline, NULL, NULL, TRUE,
1445
         CREATE_NEW_PROCESS_GROUP, envblk, NULL, &si, &pi) == 0) {
1446
    cry(conn, "%s: CreateProcess(%s): %d",
1447
  __func__, cmdline, ERRNO);
1448
    pi.hProcess = (pid_t) -1;
1449
  }
1450
1451
  // Always close these to prevent handle leakage.
1452
  (void) close(fd_stdin);
1453
  (void) close(fd_stdout);
1454
1455
  (void) CloseHandle(si.hStdOutput);
1456
  (void) CloseHandle(si.hStdInput);
1457
  (void) CloseHandle(pi.hThread);
1458
1459
  return (pid_t) pi.hProcess;
1460
}
1461
#endif // !NO_CGI
1462
1463
static int set_non_blocking_mode(SOCKET sock) {
1464
  unsigned long on = 1;
1465
  return ioctlsocket(sock, FIONBIO, &on);
1466
}
1467
1468
#else
1469
static int mg_stat(struct mg_connection *conn, const char *path,
1470
0
       struct file *filep) {
1471
0
  struct stat st;
1472
1473
0
  if (!is_file_in_memory(conn, path, filep) && !stat(path, &st)) {
1474
0
    filep->size = st.st_size;
1475
0
    filep->modification_time = st.st_mtime;
1476
0
    filep->is_directory = S_ISDIR(st.st_mode);
1477
0
  } else {
1478
0
    filep->modification_time = (time_t) 0;
1479
0
  }
1480
1481
0
  return filep->membuf != NULL || filep->modification_time != (time_t) 0;
1482
0
}
1483
1484
0
static void set_close_on_exec(int fd) {
1485
0
  fcntl(fd, F_SETFD, FD_CLOEXEC);
1486
0
}
1487
1488
0
int mg_start_thread(mg_thread_func_t func, void *param) {
1489
0
  pthread_t thread_id;
1490
0
  pthread_attr_t attr;
1491
1492
0
  (void) pthread_attr_init(&attr);
1493
0
  (void) pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
1494
  // TODO(lsm): figure out why mongoose dies on Linux if next line is enabled
1495
  // (void) pthread_attr_setstacksize(&attr, sizeof(struct mg_connection) * 5);
1496
1497
0
  return pthread_create(&thread_id, &attr, func, param);
1498
0
}
1499
1500
#ifndef NO_CGI
1501
static pid_t spawn_process(struct mg_connection *conn, const char *prog,
1502
         char *envblk, char *envp[], int fd_stdin,
1503
         int fd_stdout, const char *dir) {
1504
  pid_t pid;
1505
  const char *interp;
1506
1507
  (void) envblk;
1508
1509
  if ((pid = fork()) == -1) {
1510
    // Parent
1511
    send_http_error(conn, 500, http_500_error, "fork(): %s", strerror(ERRNO));
1512
  } else if (pid == 0) {
1513
    // Child
1514
    if (chdir(dir) != 0) {
1515
      cry(conn, "%s: chdir(%s): %s", __func__, dir, strerror(ERRNO));
1516
    } else if (dup2(fd_stdin, 0) == -1) {
1517
      cry(conn, "%s: dup2(%d, 0): %s", __func__, fd_stdin, strerror(ERRNO));
1518
    } else if (dup2(fd_stdout, 1) == -1) {
1519
      cry(conn, "%s: dup2(%d, 1): %s", __func__, fd_stdout, strerror(ERRNO));
1520
    } else {
1521
      (void) dup2(fd_stdout, 2);
1522
      (void) close(fd_stdin);
1523
      (void) close(fd_stdout);
1524
1525
      // After exec, all signal handlers are restored to their default values,
1526
      // with one exception of SIGCHLD. According to POSIX.1-2001 and Linux's
1527
      // implementation, SIGCHLD's handler will leave unchanged after exec
1528
      // if it was set to be ignored. Restore it to default action.
1529
      signal(SIGCHLD, SIG_DFL);
1530
1531
      interp = conn->ctx->config[CGI_INTERPRETER];
1532
      if (interp == NULL) {
1533
  (void) execle(prog, prog, NULL, envp);
1534
  cry(conn, "%s: execle(%s): %s", __func__, prog, strerror(ERRNO));
1535
      } else {
1536
  (void) execle(interp, interp, prog, NULL, envp);
1537
  cry(conn, "%s: execle(%s %s): %s", __func__, interp, prog,
1538
      strerror(ERRNO));
1539
      }
1540
    }
1541
    exit(EXIT_FAILURE);
1542
  }
1543
1544
  // Parent. Close stdio descriptors
1545
  (void) close(fd_stdin);
1546
  (void) close(fd_stdout);
1547
1548
  return pid;
1549
}
1550
#endif // !NO_CGI
1551
1552
0
static int set_non_blocking_mode(SOCKET sock) {
1553
0
  int flags;
1554
1555
0
  flags = fcntl(sock, F_GETFL, 0);
1556
0
  (void) fcntl(sock, F_SETFL, flags | O_NONBLOCK);
1557
1558
0
  return 0;
1559
0
}
1560
#endif // _WIN32
1561
1562
// Write data to the IO channel - opened file descriptor, socket or SSL
1563
// descriptor. Return number of bytes written.
1564
static int64_t push(FILE *fp, SOCKET sock, SSL *ssl, const char *buf,
1565
0
        int64_t len) {
1566
0
  int64_t sent;
1567
0
  int n, k;
1568
1569
0
  sent = 0;
1570
0
  while (sent < len) {
1571
    // How many bytes we send in this iteration
1572
0
    k = len - sent > INT_MAX ? INT_MAX : (int) (len - sent);
1573
1574
0
#ifndef NO_SSL
1575
0
    if (ssl != NULL) {
1576
0
      n = SSL_write(ssl, buf + sent, k);
1577
0
    } else
1578
0
#endif
1579
0
      if (fp != NULL) {
1580
0
  n = (int) fwrite(buf + sent, 1, (size_t) k, fp);
1581
0
  if (ferror(fp))
1582
0
    n = -1;
1583
0
      } else {
1584
0
  n = send(sock, buf + sent, (size_t) k, MSG_NOSIGNAL);
1585
0
      }
1586
1587
#ifdef DEBUG /* ntop */
1588
    printf("[MONGOOSE][DEBUG] %s sent = %d bytes\n", __FUNCTION__, n);
1589
#endif
1590
1591
0
    if (n <= 0)
1592
0
      break;
1593
1594
0
    sent += n;
1595
0
  }
1596
1597
0
  return sent;
1598
0
}
1599
1600
// Read from IO channel - opened file descriptor, socket, or SSL descriptor.
1601
// Return negative value on error, or number of bytes read on success.
1602
0
static int pull(FILE *fp, struct mg_connection *conn, char *buf, int len) {
1603
0
  int nread;
1604
1605
0
  if (fp != NULL) {
1606
    // Use read() instead of fread(), because if we're reading from the CGI
1607
    // pipe, fread() may block until IO buffer is filled up. We cannot afford
1608
    // to block and must pass all read bytes immediately to the client.
1609
0
    nread = read(fileno(fp), buf, (size_t) len);
1610
0
#ifndef NO_SSL
1611
0
  } else if (conn->ssl != NULL) {
1612
0
    nread = SSL_read(conn->ssl, buf, len);
1613
    
1614
#ifdef DEBUG
1615
    buf[len] = '\0';
1616
    printf("%s", buf);
1617
#endif
1618
1619
0
#endif
1620
0
  } else {
1621
0
    nread = recv(conn->client.sock, buf, (size_t) len, 0);
1622
0
  }
1623
1624
0
  return conn->ctx->stop_flag ? -1 : nread;
1625
0
}
1626
1627
0
int64_t mg_get_content_len(struct mg_connection *conn) {
1628
0
  return conn->content_len;
1629
0
}
1630
1631
0
int mg_read(struct mg_connection *conn, void *buf, size_t len) {
1632
0
  int n, buffered_len, nread;
1633
0
  const char *body;
1634
1635
0
  nread = 0;
1636
0
  if (conn->consumed_content < conn->content_len) {
1637
    // Adjust number of bytes to read.
1638
0
    int64_t to_read = conn->content_len - conn->consumed_content;
1639
0
    if (to_read < (int64_t) len) {
1640
0
      len = (size_t) to_read;
1641
0
    }
1642
1643
    // Return buffered data
1644
0
    body = conn->buf + conn->request_len + conn->consumed_content;
1645
0
    buffered_len = &conn->buf[conn->data_len] - body;
1646
0
    if (buffered_len > 0) {
1647
0
      if (len < (size_t) buffered_len) {
1648
0
  buffered_len = (int) len;
1649
0
      }
1650
0
      memcpy(buf, body, (size_t) buffered_len);
1651
0
      len -= buffered_len;
1652
0
      conn->consumed_content += buffered_len;
1653
0
      nread += buffered_len;
1654
0
      buf = (char *) buf + buffered_len;
1655
0
    }
1656
1657
    // We have returned all buffered data. Read new data from the remote socket.
1658
0
    while (len > 0) {
1659
0
      n = pull(NULL, conn, (char *) buf, (int) len);
1660
0
      if (n < 0) {
1661
0
  nread = n;  // Propagate the error
1662
0
  break;
1663
0
      } else if (n == 0) {
1664
0
  break;  // No more data to read
1665
0
      } else {
1666
0
  buf = (char *) buf + n;
1667
0
  conn->consumed_content += n;
1668
0
  nread += n;
1669
0
  len -= n;
1670
0
      }
1671
0
    }
1672
0
  }
1673
0
  return nread;
1674
0
}
1675
1676
0
int mg_write(struct mg_connection *conn, const void *buf, size_t len) {
1677
0
  time_t now;
1678
0
  int64_t n, total, allowed;
1679
1680
0
  if (conn->throttle > 0) {
1681
0
    if ((now = time(NULL)) != conn->last_throttle_time) {
1682
0
      conn->last_throttle_time = now;
1683
0
      conn->last_throttle_bytes = 0;
1684
0
    }
1685
0
    allowed = conn->throttle - conn->last_throttle_bytes;
1686
0
    if (allowed > (int64_t) len) {
1687
0
      allowed = len;
1688
0
    }
1689
0
    if ((total = push(NULL, conn->client.sock, conn->ssl, (const char *) buf,
1690
0
          (int64_t) allowed)) == allowed) {
1691
0
      buf = (char *) buf + total;
1692
0
      conn->last_throttle_bytes += total;
1693
0
      while (total < (int64_t) len && conn->ctx->stop_flag == 0) {
1694
0
  allowed = conn->throttle > (int64_t) len - total ?
1695
0
    (int64_t) len - total : conn->throttle;
1696
0
  if ((n = push(NULL, conn->client.sock, conn->ssl, (const char *) buf,
1697
0
          (int64_t) allowed)) != allowed) {
1698
0
    break;
1699
0
  }
1700
0
  sleep(1);
1701
0
  conn->last_throttle_bytes = allowed;
1702
0
  conn->last_throttle_time = time(NULL);
1703
0
  buf = (char *) buf + n;
1704
0
  total += n;
1705
0
      }
1706
0
    }
1707
0
  } else {
1708
0
    total = push(NULL, conn->client.sock, conn->ssl, (const char *) buf,
1709
0
     (int64_t) len);
1710
0
  }
1711
0
  return (int) total;
1712
0
}
1713
1714
1715
0
int mg_write_async(struct mg_connection *conn, const void *buf, size_t len) {
1716
0
  int total;
1717
1718
0
  if(!conn->async_send) {
1719
    /* Enable asynchronous send */
1720
#ifdef WIN32
1721
    u_long iMode = 0;
1722
1723
    /*
1724
      Set the socket I/O mode: In this case FIONBIO
1725
      enables or disables the blocking mode for the
1726
      socket based on the numerical value of iMode.
1727
      If iMode = 0, blocking is enabled;
1728
      If iMode != 0, non-blocking mode is enabled.
1729
      
1730
      https://docs.microsoft.com/en-us/windows/desktop/api/winsock/nf-winsock-ioctlsocket
1731
    */
1732
    
1733
    ioctlsocket(conn->client.sock, FIONBIO, &iMode);
1734
#else
1735
0
    int flags = fcntl(conn->client.sock, F_GETFL, 0);
1736
1737
0
    fcntl(conn->client.sock, F_SETFL, flags | O_NONBLOCK);
1738
0
#endif
1739
0
    conn->async_send = 1;
1740
0
  }
1741
  
1742
0
  total = push(NULL, conn->client.sock, conn->ssl, (const char *) buf, (int64_t) len);
1743
1744
  /*
1745
    In case you want to disable async ... 
1746
1747
    fcntl(conn->client.sock, F_SETFL, flags & (~O_NONBLOCK)); 
1748
  */
1749
1750
0
  return(total);
1751
0
}
1752
1753
0
int mg_is_client_connected(struct mg_connection *conn) {
1754
0
  char c;
1755
0
  int rv;
1756
#ifdef WIN32
1757
  rv = 1;
1758
#else  
1759
0
  rv = recv(conn->client.sock, &c, 1, MSG_PEEK | MSG_DONTWAIT | MSG_NOSIGNAL);
1760
0
#endif
1761
1762
0
  return(rv != 0);
1763
0
}
1764
1765
// Print message to buffer. If buffer is large enough to hold the message,
1766
// return buffer. If buffer is to small, allocate large enough buffer on heap,
1767
// and return allocated buffer.
1768
0
static int alloc_vprintf(char **buf, size_t size, const char *fmt, va_list ap) {
1769
0
  va_list ap_copy;
1770
0
  int len;
1771
1772
  // Windows is not standard-compliant, and vsnprintf() returns -1 if
1773
  // buffer is too small. Also, older versions of msvcrt.dll do not have
1774
  // _vscprintf().  However, if size is 0, vsnprintf() behaves correctly.
1775
  // Therefore, we make two passes: on first pass, get required message length.
1776
  // On second pass, actually print the message.
1777
0
  va_copy(ap_copy, ap);
1778
0
  len = vsnprintf(NULL, 0, fmt, ap_copy);
1779
1780
0
  if (len > (int) size &&
1781
0
      (size = len + 1) > 0 &&
1782
0
      (*buf = (char *) malloc(size)) == NULL) {
1783
0
    len = -1;  // Allocation failed, mark failure
1784
0
  } else {
1785
0
    va_copy(ap_copy, ap);
1786
0
    vsnprintf(*buf, size, fmt, ap_copy);
1787
0
  }
1788
1789
0
  va_end(ap_copy);
1790
0
  return len;
1791
0
}
1792
1793
0
int mg_vprintf(struct mg_connection *conn, const char *fmt, va_list ap) {
1794
0
  char mem[MG_BUF_LEN], *buf = mem;
1795
0
  int len;
1796
1797
0
  if ((len = alloc_vprintf(&buf, sizeof(mem), fmt, ap)) > 0) {
1798
0
    len = mg_write(conn, buf, (size_t) len);
1799
0
  }
1800
0
  if (buf != mem && buf != NULL) {
1801
0
    free(buf);
1802
0
  }
1803
1804
0
  return len;
1805
0
}
1806
1807
0
int mg_printf(struct mg_connection *conn, const char *fmt, ...) {
1808
0
  va_list ap;
1809
0
  va_start(ap, fmt);
1810
0
  return mg_vprintf(conn, fmt, ap);
1811
0
}
1812
1813
// URL-decode input buffer into destination buffer.
1814
// 0-terminate the destination buffer. Return the length of decoded data.
1815
// form-url-encoded data differs from URI encoding in a way that it
1816
// uses '+' as character for space, see RFC 1866 section 8.2.1
1817
// http://ftp.ics.uci.edu/pub/ietf/html/rfc1866.txt
1818
1819
/* static */ /* ntop */
1820
int url_decode(const char *src, int src_len, char *dst,
1821
0
         int dst_len, int is_form_url_encoded) {
1822
0
  int i, j, a, b;
1823
0
#define HEXTOI(x) (isdigit(x) ? x - '0' : x - 'W')
1824
1825
0
  for (i = j = 0; i < src_len && j < dst_len - 1; i++, j++) {
1826
0
    if (src[i] == '%' &&
1827
0
  isxdigit(* (const unsigned char *) (src + i + 1)) &&
1828
0
  isxdigit(* (const unsigned char *) (src + i + 2))) {
1829
0
      a = tolower(* (const unsigned char *) (src + i + 1));
1830
0
      b = tolower(* (const unsigned char *) (src + i + 2));
1831
0
      dst[j] = (char) ((HEXTOI(a) << 4) | HEXTOI(b));
1832
0
      i += 2;
1833
0
    } else if (is_form_url_encoded && src[i] == '+') {
1834
0
      dst[j] = ' ';
1835
0
    } else {
1836
0
      dst[j] = src[i];
1837
0
    }
1838
0
  }
1839
1840
0
  dst[j] = '\0'; // Null-terminate the destination
1841
1842
0
  return i >= src_len ? j : -1;
1843
0
}
1844
1845
int mg_get_var(const char *data, size_t data_len, const char *name,
1846
0
         char *dst, size_t dst_len) {
1847
0
  const char *p, *e, *s;
1848
0
  size_t name_len;
1849
0
  int len;
1850
1851
0
  if (dst == NULL || dst_len == 0) {
1852
0
    len = -2;
1853
0
  } else if (data == NULL || name == NULL || data_len == 0) {
1854
0
    len = -1;
1855
0
    dst[0] = '\0';
1856
0
  } else {
1857
0
    name_len = strlen(name);
1858
0
    e = data + data_len;
1859
0
    len = -1;
1860
0
    dst[0] = '\0';
1861
1862
    // data is "var1=val1&var2=val2...". Find variable first
1863
0
    for (p = data; p + name_len < e; p++) {
1864
0
      if ((p == data || p[-1] == '&') && p[name_len] == '=' &&
1865
0
    !mg_strncasecmp(name, p, name_len)) {
1866
1867
  // Point p to variable value
1868
0
  p += name_len + 1;
1869
1870
  // Point s to the end of the value
1871
0
  s = (const char *) memchr(p, '&', (size_t)(e - p));
1872
0
  if (s == NULL) {
1873
0
    s = e;
1874
0
  }
1875
0
  assert(s >= p);
1876
1877
  // Decode variable into destination buffer
1878
0
  len = url_decode(p, (size_t)(s - p), dst, dst_len, 1);
1879
1880
  // Redirect error code from -1 to -2 (destination buffer too small).
1881
0
  if (len == -1) {
1882
0
    len = -2;
1883
0
  }
1884
0
  break;
1885
0
      }
1886
0
    }
1887
0
  }
1888
1889
0
  return len;
1890
0
}
1891
1892
int mg_get_cookie(const struct mg_connection *conn, const char *cookie_name,
1893
0
      char *dst, size_t dst_size) {
1894
0
  const char *s, *p, *end, *start;
1895
0
  int name_len, len = -1;
1896
1897
0
  if (dst == NULL || dst_size == 0) {
1898
0
    len = -2;
1899
0
  } else if (cookie_name == NULL || (start = mg_get_header(conn, "Cookie")) == NULL) {
1900
0
    len = -1;
1901
0
    dst[0] = '\0';
1902
0
  } else {
1903
0
    name_len = (int) strlen(cookie_name);
1904
0
    end = start + strlen(start);
1905
0
    dst[0] = '\0';
1906
1907
0
    for (s = start; (s = strstr(s, cookie_name)) != NULL; s += name_len) {
1908
0
      if ((s[name_len] == '=') && ((s == start) || (s[-1] == ' ') || (s[-1] == ';'))) {
1909
0
  s += name_len + 1;
1910
0
  if ((p = strchr(s, ' ')) == NULL)
1911
0
    p = end;
1912
0
  if (p[-1] == ';')
1913
0
    p--;
1914
0
  if (*s == '"' && p[-1] == '"' && p > s + 1) {
1915
0
    s++;
1916
0
    p--;
1917
0
  }
1918
0
  if ((size_t) (p - s) < dst_size) {
1919
0
    len = p - s;
1920
0
    mg_strlcpy(dst, s, (size_t) len + 1);
1921
0
  } else {
1922
0
    len = -2;
1923
0
  }
1924
0
  break;
1925
0
      }
1926
0
    }
1927
0
  }
1928
0
  return len;
1929
0
}
1930
1931
static void convert_uri_to_file_name(struct mg_connection *conn, char *buf,
1932
0
             size_t buf_len, struct file *filep) {
1933
0
  struct vec a, b;
1934
0
  const char *rewrite, *uri;
1935
0
  char *p;
1936
0
  int match_len;
1937
1938
0
  if((strlen(conn->request_info.uri) > http_prefix_len)
1939
0
     && (strncmp(conn->request_info.uri, http_prefix, http_prefix_len) == 0))
1940
0
    conn->request_info.uri = &conn->request_info.uri[http_prefix_len];
1941
1942
0
  uri = conn->request_info.uri;
1943
  
1944
  // Using buf_len - 1 because memmove() for PATH_INFO may shift part
1945
  // of the path one byte on the right.
1946
0
  mg_snprintf(conn, buf, buf_len - 1, "%s%s", conn->ctx->config[DOCUMENT_ROOT],
1947
0
        uri);
1948
1949
0
  rewrite = conn->ctx->config[REWRITE];
1950
0
  while ((rewrite = next_option(rewrite, &a, &b)) != NULL) {
1951
0
    if ((match_len = match_prefix(a.ptr, a.len, uri)) > 0) {
1952
0
      mg_snprintf(conn, buf, buf_len - 1, "%.*s%s", (int) b.len, b.ptr,
1953
0
      uri + match_len);
1954
0
      break;
1955
0
    }
1956
0
  }
1957
1958
0
  if (!mg_stat(conn, buf, filep)) {
1959
    // Support PATH_INFO for CGI scripts.
1960
0
    for (p = buf + strlen(buf); p > buf + 1; p--) {
1961
0
      if (*p == '/') {
1962
0
  *p = '\0';
1963
0
  if (match_prefix(conn->ctx->config[CGI_EXTENSIONS],
1964
0
       strlen(conn->ctx->config[CGI_EXTENSIONS]), buf) > 0 &&
1965
0
      mg_stat(conn, buf, filep)) {
1966
    // Shift PATH_INFO block one character right, e.g.
1967
    //  "/x.cgi/foo/bar\x00" => "/x.cgi\x00/foo/bar\x00"
1968
    // conn->path_info is pointing to the local variable "path" declared
1969
    // in handle_request(), so PATH_INFO is not valid after
1970
    // handle_request returns.
1971
0
    conn->path_info = p + 1;
1972
0
    memmove(p + 2, p + 1, strlen(p + 1) + 1);  // +1 is for trailing \0
1973
0
    p[1] = '/';
1974
0
    break;
1975
0
  } else {
1976
0
    *p = '/';
1977
0
  }
1978
0
      }
1979
0
    }
1980
0
  }
1981
0
}
1982
1983
// Check whether full request is buffered. Return:
1984
//   -1  if request is malformed
1985
//    0  if request is not yet fully buffered
1986
//   >0  actual request length, including last \r\n\r\n
1987
0
static int get_request_len(const char *buf, int buflen) {
1988
0
  const char *s, *e;
1989
0
  int len = 0;
1990
1991
0
  for (s = buf, e = s + buflen - 1; len <= 0 && s < e; s++)
1992
    // Control characters are not allowed but >=128 is.
1993
0
    if (!isprint(* (const unsigned char *) s) && *s != '\r' &&
1994
0
  *s != '\n' && * (const unsigned char *) s < 128) {
1995
0
      len = -1;
1996
0
      break;  // [i_a] abort scan as soon as one malformed character is found;
1997
        // don't let subsequent \r\n\r\n win us over anyhow
1998
0
    } else if (s[0] == '\n' && s[1] == '\n') {
1999
0
      len = (int) (s - buf) + 2;
2000
0
    } else if (s[0] == '\n' && &s[1] < e &&
2001
0
         s[1] == '\r' && s[2] == '\n') {
2002
0
      len = (int) (s - buf) + 3;
2003
0
    }
2004
2005
0
  return len;
2006
0
}
2007
2008
// Convert month to the month number. Return -1 on error, or month number
2009
0
static int get_month_index(const char *s) {
2010
0
  size_t i;
2011
2012
0
  for (i = 0; i < ARRAY_SIZE(month_names); i++)
2013
0
    if (!strcmp(s, month_names[i]))
2014
0
      return (int) i;
2015
2016
0
  return -1;
2017
0
}
2018
2019
0
static int num_leap_years(int year) {
2020
0
  return year / 4 - year / 100 + year / 400;
2021
0
}
2022
2023
// Parse UTC date-time string, and return the corresponding time_t value.
2024
0
static time_t parse_date_string(const char *datetime) {
2025
0
  static const unsigned short days_before_month[] = {
2026
0
    0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334
2027
0
  };
2028
0
  char month_str[32];
2029
0
  int second, minute, hour, day, month, year, leap_days, days;
2030
0
  time_t result = (time_t) 0;
2031
2032
0
  if (((sscanf(datetime, "%d/%3s/%d %d:%d:%d",
2033
0
         &day, month_str, &year, &hour, &minute, &second) == 6) ||
2034
0
       (sscanf(datetime, "%d %3s %d %d:%d:%d",
2035
0
         &day, month_str, &year, &hour, &minute, &second) == 6) ||
2036
0
       (sscanf(datetime, "%*3s, %d %3s %d %d:%d:%d",
2037
0
         &day, month_str, &year, &hour, &minute, &second) == 6) ||
2038
0
       (sscanf(datetime, "%d-%3s-%d %d:%d:%d",
2039
0
         &day, month_str, &year, &hour, &minute, &second) == 6)) &&
2040
0
      year > 1970 &&
2041
0
      (month = get_month_index(month_str)) != -1) {
2042
0
    leap_days = num_leap_years(year) - num_leap_years(1970);
2043
0
    year -= 1970;
2044
0
    days = year * 365 + days_before_month[month] + (day - 1) + leap_days;
2045
0
    result = days * 24 * 3600 + hour * 3600 + minute * 60 + second;
2046
0
  }
2047
2048
0
  return result;
2049
0
}
2050
2051
// Protect against directory disclosure attack by removing '..',
2052
// excessive '/' and '\' characters
2053
0
static void remove_double_dots_and_double_slashes(char *s) {
2054
0
  char *p = s;
2055
2056
0
  while (*s != '\0') {
2057
0
    *p++ = *s++;
2058
0
    if (s[-1] == '/' || s[-1] == '\\') {
2059
      // Skip all following slashes, backslashes and double-dots
2060
0
      while (s[0] != '\0') {
2061
0
  if (s[0] == '/' || s[0] == '\\') {
2062
0
    s++;
2063
0
  } else if (s[0] == '.' && s[1] == '.') {
2064
0
    s += 2;
2065
0
  } else {
2066
0
    break;
2067
0
  }
2068
0
      }
2069
0
    }
2070
0
  }
2071
0
  *p = '\0';
2072
0
}
2073
2074
static const struct {
2075
  const char *extension;
2076
  size_t ext_len;
2077
  const char *mime_type;
2078
} builtin_mime_types[] = {
2079
  {".html", 5, "text/html"},
2080
  {".htm", 4, "text/html"},
2081
  {".shtm", 5, "text/html"},
2082
  {".shtml", 6, "text/html"},
2083
  {".css", 4, "text/css"},
2084
  {".js",  3, "application/x-javascript"},
2085
  {".ico", 4, "image/x-icon"},
2086
  {".gif", 4, "image/gif"},
2087
  {".jpg", 4, "image/jpeg"},
2088
  {".jpeg", 5, "image/jpeg"},
2089
  {".png", 4, "image/png"},
2090
  {".svg", 4, "image/svg+xml"},
2091
  {".txt", 4, "text/plain"},
2092
  {".torrent", 8, "application/x-bittorrent"},
2093
  {".wav", 4, "audio/x-wav"},
2094
  {".mp3", 4, "audio/x-mp3"},
2095
  {".mid", 4, "audio/mid"},
2096
  {".m3u", 4, "audio/x-mpegurl"},
2097
  {".ogg", 4, "audio/ogg"},
2098
  {".ram", 4, "audio/x-pn-realaudio"},
2099
  {".xml", 4, "text/xml"},
2100
  {".json",  5, "text/json"},
2101
  {".xslt", 5, "application/xml"},
2102
  {".xsl", 4, "application/xml"},
2103
  {".ra",  3, "audio/x-pn-realaudio"},
2104
  {".doc", 4, "application/msword"},
2105
  {".exe", 4, "application/octet-stream"},
2106
  {".zip", 4, "application/x-zip-compressed"},
2107
  {".xls", 4, "application/excel"},
2108
  {".tgz", 4, "application/x-tar-gz"},
2109
  {".tar", 4, "application/x-tar"},
2110
  {".gz",  3, "application/x-gunzip"},
2111
  {".arj", 4, "application/x-arj-compressed"},
2112
  {".rar", 4, "application/x-arj-compressed"},
2113
  {".rtf", 4, "application/rtf"},
2114
  {".pdf", 4, "application/pdf"},
2115
  {".swf", 4, "application/x-shockwave-flash"},
2116
  {".mpg", 4, "video/mpeg"},
2117
  {".webm", 5, "video/webm"},
2118
  {".mpeg", 5, "video/mpeg"},
2119
  {".mp4", 4, "video/mp4"},
2120
  {".m4v", 4, "video/x-m4v"},
2121
  {".asf", 4, "video/x-ms-asf"},
2122
  {".avi", 4, "video/x-msvideo"},
2123
  {".bmp", 4, "image/bmp"},
2124
2125
  /* ntop */
2126
  {".woff", 5, "application/font-woff"},
2127
  {".woff2", 6, "application/font-woff2"},
2128
  {".ttf", 4, "application/x-font-ttf"},
2129
  {".inc", 4, "text/html"},
2130
  {".css", 4, "text/css"},
2131
  {".eot", 4, "application/vnd.ms-fontobject"},
2132
  {".js", 3, "application/javascript"},
2133
  {".css.map", 8, "text/css"},
2134
  {".js.map", 7, "application/javascript"},
2135
  
2136
  {NULL,  0, NULL}
2137
};
2138
2139
0
const char *mg_get_builtin_mime_type(const char *path) {
2140
0
  const char *ext;
2141
0
  size_t i, path_len;
2142
2143
0
  path_len = strlen(path);
2144
2145
0
  for (i = 0; builtin_mime_types[i].extension != NULL; i++) {
2146
0
    ext = path + (path_len - builtin_mime_types[i].ext_len);
2147
0
    if (path_len > builtin_mime_types[i].ext_len &&
2148
0
  mg_strcasecmp(ext, builtin_mime_types[i].extension) == 0) {
2149
0
      return builtin_mime_types[i].mime_type;
2150
0
    }
2151
0
  }
2152
2153
0
  return "text/plain";
2154
0
}
2155
2156
// Look at the "path" extension and figure what mime type it has.
2157
// Store mime type in the vector.
2158
static void get_mime_type(struct mg_context *ctx, const char *path,
2159
0
        struct vec *vec) {
2160
0
  struct vec ext_vec, mime_vec;
2161
0
  const char *list, *ext;
2162
0
  size_t path_len;
2163
2164
0
  path_len = strlen(path);
2165
2166
  // Scan user-defined mime types first, in case user wants to
2167
  // override default mime types.
2168
0
  list = ctx->config[EXTRA_MIME_TYPES];
2169
0
  while ((list = next_option(list, &ext_vec, &mime_vec)) != NULL) {
2170
    // ext now points to the path suffix
2171
0
    ext = path + path_len - ext_vec.len;
2172
0
    if (mg_strncasecmp(ext, ext_vec.ptr, ext_vec.len) == 0) {
2173
0
      *vec = mime_vec;
2174
0
      return;
2175
0
    }
2176
0
  }
2177
2178
0
  vec->ptr = mg_get_builtin_mime_type(path);
2179
0
  vec->len = strlen(vec->ptr);
2180
0
}
2181
2182
0
static int is_big_endian(void) {
2183
0
  static const int n = 1;
2184
0
  return ((char *) &n)[0] == 0;
2185
0
}
2186
2187
#ifndef HAVE_MD5
2188
typedef struct MD5Context {
2189
  uint32_t buf[4];
2190
  uint32_t bits[2];
2191
  unsigned char in[64];
2192
} MD5_CTX;
2193
2194
0
static void byteReverse(unsigned char *buf, unsigned longs) {
2195
0
  uint32_t t;
2196
2197
  // Forrest: MD5 expect LITTLE_ENDIAN, swap if BIG_ENDIAN
2198
0
  if (is_big_endian()) {
2199
0
    do {
2200
0
      t = (uint32_t) ((unsigned) buf[3] << 8 | buf[2]) << 16 |
2201
0
  ((unsigned) buf[1] << 8 | buf[0]);
2202
0
      * (uint32_t *) buf = t;
2203
0
      buf += 4;
2204
0
    } while (--longs);
2205
0
  }
2206
0
}
2207
2208
0
#define F1(x, y, z) (z ^ (x & (y ^ z)))
2209
0
#define F2(x, y, z) F1(z, x, y)
2210
0
#define F3(x, y, z) (x ^ y ^ z)
2211
0
#define F4(x, y, z) (y ^ (x | ~z))
2212
2213
#define MD5STEP(f, w, x, y, z, data, s)       \
2214
0
  ( w += f(x, y, z) + data,  w = w<<s | w>>(32-s),  w += x )
2215
2216
// Start MD5 accumulation.  Set bit count to 0 and buffer to mysterious
2217
// initialization constants.
2218
0
static void MD5Init(MD5_CTX *ctx) {
2219
0
  ctx->buf[0] = 0x67452301;
2220
0
  ctx->buf[1] = 0xefcdab89;
2221
0
  ctx->buf[2] = 0x98badcfe;
2222
0
  ctx->buf[3] = 0x10325476;
2223
2224
0
  ctx->bits[0] = 0;
2225
0
  ctx->bits[1] = 0;
2226
0
}
2227
2228
0
static void MD5Transform(uint32_t buf[4], uint32_t const in[16]) {
2229
0
  uint32_t a, b, c, d;
2230
2231
0
  a = buf[0];
2232
0
  b = buf[1];
2233
0
  c = buf[2];
2234
0
  d = buf[3];
2235
2236
0
  MD5STEP(F1, a, b, c, d, in[0] + 0xd76aa478, 7);
2237
0
  MD5STEP(F1, d, a, b, c, in[1] + 0xe8c7b756, 12);
2238
0
  MD5STEP(F1, c, d, a, b, in[2] + 0x242070db, 17);
2239
0
  MD5STEP(F1, b, c, d, a, in[3] + 0xc1bdceee, 22);
2240
0
  MD5STEP(F1, a, b, c, d, in[4] + 0xf57c0faf, 7);
2241
0
  MD5STEP(F1, d, a, b, c, in[5] + 0x4787c62a, 12);
2242
0
  MD5STEP(F1, c, d, a, b, in[6] + 0xa8304613, 17);
2243
0
  MD5STEP(F1, b, c, d, a, in[7] + 0xfd469501, 22);
2244
0
  MD5STEP(F1, a, b, c, d, in[8] + 0x698098d8, 7);
2245
0
  MD5STEP(F1, d, a, b, c, in[9] + 0x8b44f7af, 12);
2246
0
  MD5STEP(F1, c, d, a, b, in[10] + 0xffff5bb1, 17);
2247
0
  MD5STEP(F1, b, c, d, a, in[11] + 0x895cd7be, 22);
2248
0
  MD5STEP(F1, a, b, c, d, in[12] + 0x6b901122, 7);
2249
0
  MD5STEP(F1, d, a, b, c, in[13] + 0xfd987193, 12);
2250
0
  MD5STEP(F1, c, d, a, b, in[14] + 0xa679438e, 17);
2251
0
  MD5STEP(F1, b, c, d, a, in[15] + 0x49b40821, 22);
2252
2253
0
  MD5STEP(F2, a, b, c, d, in[1] + 0xf61e2562, 5);
2254
0
  MD5STEP(F2, d, a, b, c, in[6] + 0xc040b340, 9);
2255
0
  MD5STEP(F2, c, d, a, b, in[11] + 0x265e5a51, 14);
2256
0
  MD5STEP(F2, b, c, d, a, in[0] + 0xe9b6c7aa, 20);
2257
0
  MD5STEP(F2, a, b, c, d, in[5] + 0xd62f105d, 5);
2258
0
  MD5STEP(F2, d, a, b, c, in[10] + 0x02441453, 9);
2259
0
  MD5STEP(F2, c, d, a, b, in[15] + 0xd8a1e681, 14);
2260
0
  MD5STEP(F2, b, c, d, a, in[4] + 0xe7d3fbc8, 20);
2261
0
  MD5STEP(F2, a, b, c, d, in[9] + 0x21e1cde6, 5);
2262
0
  MD5STEP(F2, d, a, b, c, in[14] + 0xc33707d6, 9);
2263
0
  MD5STEP(F2, c, d, a, b, in[3] + 0xf4d50d87, 14);
2264
0
  MD5STEP(F2, b, c, d, a, in[8] + 0x455a14ed, 20);
2265
0
  MD5STEP(F2, a, b, c, d, in[13] + 0xa9e3e905, 5);
2266
0
  MD5STEP(F2, d, a, b, c, in[2] + 0xfcefa3f8, 9);
2267
0
  MD5STEP(F2, c, d, a, b, in[7] + 0x676f02d9, 14);
2268
0
  MD5STEP(F2, b, c, d, a, in[12] + 0x8d2a4c8a, 20);
2269
2270
0
  MD5STEP(F3, a, b, c, d, in[5] + 0xfffa3942, 4);
2271
0
  MD5STEP(F3, d, a, b, c, in[8] + 0x8771f681, 11);
2272
0
  MD5STEP(F3, c, d, a, b, in[11] + 0x6d9d6122, 16);
2273
0
  MD5STEP(F3, b, c, d, a, in[14] + 0xfde5380c, 23);
2274
0
  MD5STEP(F3, a, b, c, d, in[1] + 0xa4beea44, 4);
2275
0
  MD5STEP(F3, d, a, b, c, in[4] + 0x4bdecfa9, 11);
2276
0
  MD5STEP(F3, c, d, a, b, in[7] + 0xf6bb4b60, 16);
2277
0
  MD5STEP(F3, b, c, d, a, in[10] + 0xbebfbc70, 23);
2278
0
  MD5STEP(F3, a, b, c, d, in[13] + 0x289b7ec6, 4);
2279
0
  MD5STEP(F3, d, a, b, c, in[0] + 0xeaa127fa, 11);
2280
0
  MD5STEP(F3, c, d, a, b, in[3] + 0xd4ef3085, 16);
2281
0
  MD5STEP(F3, b, c, d, a, in[6] + 0x04881d05, 23);
2282
0
  MD5STEP(F3, a, b, c, d, in[9] + 0xd9d4d039, 4);
2283
0
  MD5STEP(F3, d, a, b, c, in[12] + 0xe6db99e5, 11);
2284
0
  MD5STEP(F3, c, d, a, b, in[15] + 0x1fa27cf8, 16);
2285
0
  MD5STEP(F3, b, c, d, a, in[2] + 0xc4ac5665, 23);
2286
2287
0
  MD5STEP(F4, a, b, c, d, in[0] + 0xf4292244, 6);
2288
0
  MD5STEP(F4, d, a, b, c, in[7] + 0x432aff97, 10);
2289
0
  MD5STEP(F4, c, d, a, b, in[14] + 0xab9423a7, 15);
2290
0
  MD5STEP(F4, b, c, d, a, in[5] + 0xfc93a039, 21);
2291
0
  MD5STEP(F4, a, b, c, d, in[12] + 0x655b59c3, 6);
2292
0
  MD5STEP(F4, d, a, b, c, in[3] + 0x8f0ccc92, 10);
2293
0
  MD5STEP(F4, c, d, a, b, in[10] + 0xffeff47d, 15);
2294
0
  MD5STEP(F4, b, c, d, a, in[1] + 0x85845dd1, 21);
2295
0
  MD5STEP(F4, a, b, c, d, in[8] + 0x6fa87e4f, 6);
2296
0
  MD5STEP(F4, d, a, b, c, in[15] + 0xfe2ce6e0, 10);
2297
0
  MD5STEP(F4, c, d, a, b, in[6] + 0xa3014314, 15);
2298
0
  MD5STEP(F4, b, c, d, a, in[13] + 0x4e0811a1, 21);
2299
0
  MD5STEP(F4, a, b, c, d, in[4] + 0xf7537e82, 6);
2300
0
  MD5STEP(F4, d, a, b, c, in[11] + 0xbd3af235, 10);
2301
0
  MD5STEP(F4, c, d, a, b, in[2] + 0x2ad7d2bb, 15);
2302
0
  MD5STEP(F4, b, c, d, a, in[9] + 0xeb86d391, 21);
2303
2304
0
  buf[0] += a;
2305
0
  buf[1] += b;
2306
0
  buf[2] += c;
2307
0
  buf[3] += d;
2308
0
}
2309
2310
0
static void MD5Update(MD5_CTX *ctx, unsigned char const *buf, unsigned len) {
2311
0
  uint32_t t;
2312
2313
0
  t = ctx->bits[0];
2314
0
  if ((ctx->bits[0] = t + ((uint32_t) len << 3)) < t)
2315
0
    ctx->bits[1]++;
2316
0
  ctx->bits[1] += len >> 29;
2317
2318
0
  t = (t >> 3) & 0x3f;
2319
2320
0
  if (t) {
2321
0
    unsigned char *p = (unsigned char *) ctx->in + t;
2322
2323
0
    t = 64 - t;
2324
0
    if (len < t) {
2325
0
      memcpy(p, buf, len);
2326
0
      return;
2327
0
    }
2328
0
    memcpy(p, buf, t);
2329
0
    byteReverse(ctx->in, 16);
2330
0
    MD5Transform(ctx->buf, (uint32_t *) ctx->in);
2331
0
    buf += t;
2332
0
    len -= t;
2333
0
  }
2334
2335
0
  while (len >= 64) {
2336
0
    memcpy(ctx->in, buf, 64);
2337
0
    byteReverse(ctx->in, 16);
2338
0
    MD5Transform(ctx->buf, (uint32_t *) ctx->in);
2339
0
    buf += 64;
2340
0
    len -= 64;
2341
0
  }
2342
2343
0
  memcpy(ctx->in, buf, len);
2344
0
}
2345
2346
0
static void MD5Final(unsigned char digest[16], MD5_CTX *ctx) {
2347
0
  unsigned count;
2348
0
  unsigned char *p;
2349
0
  uint32_t *c = (uint32_t*)ctx->in;
2350
2351
0
  count = (ctx->bits[0] >> 3) & 0x3F;
2352
2353
0
  p = ctx->in + count;
2354
0
  *p++ = 0x80;
2355
0
  count = 64 - 1 - count;
2356
0
  if (count < 8) {
2357
0
    memset(p, 0, count);
2358
0
    byteReverse(ctx->in, 16);
2359
0
    MD5Transform(ctx->buf, (uint32_t *) ctx->in);
2360
0
    memset(ctx->in, 0, 56);
2361
0
  } else {
2362
0
    memset(p, 0, count - 8);
2363
0
  }
2364
0
  byteReverse(ctx->in, 14);
2365
2366
0
  c[14] = ctx->bits[0];
2367
0
  c[15] = ctx->bits[1];
2368
2369
0
  MD5Transform(ctx->buf, (uint32_t *) ctx->in);
2370
0
  byteReverse((unsigned char *) ctx->buf, 4);
2371
0
  memcpy(digest, ctx->buf, 16);
2372
0
  memset((char *) ctx, 0, sizeof(*ctx));
2373
0
}
2374
#endif // !HAVE_MD5
2375
2376
// Stringify binary data. Output buffer must be twice as big as input,
2377
// because each byte takes 2 bytes in string representation
2378
0
static void bin2str(char *to, const unsigned char *p, size_t len) {
2379
0
  static const char *hex = "0123456789abcdef";
2380
2381
0
  for (; len--; p++) {
2382
0
    *to++ = hex[p[0] >> 4];
2383
0
    *to++ = hex[p[0] & 0x0f];
2384
0
  }
2385
0
  *to = '\0';
2386
0
}
2387
2388
// Return stringified MD5 hash for list of strings. Buffer must be 33 bytes.
2389
0
void mg_md5(char buf[33], ...) {
2390
0
  unsigned char hash[16];
2391
0
  const char *p;
2392
0
  va_list ap;
2393
0
  MD5_CTX ctx;
2394
2395
0
  MD5Init(&ctx);
2396
2397
0
  va_start(ap, buf);
2398
0
  while ((p = va_arg(ap, const char *)) != NULL) {
2399
0
    MD5Update(&ctx, (const unsigned char *) p, (unsigned) strlen(p));
2400
0
  }
2401
0
  va_end(ap);
2402
2403
0
  MD5Final(hash, &ctx);
2404
0
  bin2str(buf, hash, sizeof(hash));
2405
0
}
2406
2407
// Check the user's password, return 1 if OK
2408
static int check_password(const char *method, const char *ha1, const char *uri,
2409
        const char *nonce, const char *nc, const char *cnonce,
2410
0
        const char *qop, const char *response) {
2411
0
  char ha2[32 + 1], expected_response[32 + 1];
2412
2413
  // Some of the parameters may be NULL
2414
0
  if (method == NULL || nonce == NULL || nc == NULL || cnonce == NULL ||
2415
0
      qop == NULL || response == NULL) {
2416
0
    return 0;
2417
0
  }
2418
2419
  // NOTE(lsm): due to a bug in MSIE, we do not compare the URI
2420
  // TODO(lsm): check for authentication timeout
2421
0
  if (// strcmp(dig->uri, c->ouri) != 0 ||
2422
0
      strlen(response) != 32
2423
      // || now - strtoul(dig->nonce, NULL, 10) > 3600
2424
0
      ) {
2425
0
    return 0;
2426
0
  }
2427
2428
0
  mg_md5(ha2, method, ":", uri, NULL);
2429
0
  mg_md5(expected_response, ha1, ":", nonce, ":", nc,
2430
0
   ":", cnonce, ":", qop, ":", ha2, NULL);
2431
2432
0
  return mg_strcasecmp(response, expected_response) == 0;
2433
0
}
2434
2435
// Use the global passwords file, if specified by auth_gpass option,
2436
// or search for .htpasswd in the requested directory.
2437
static void open_auth_file(struct mg_connection *conn, const char *path,
2438
0
         struct file *filep) {
2439
0
  char name[PATH_MAX];
2440
0
  const char *p, *e, *gpass = conn->ctx->config[GLOBAL_PASSWORDS_FILE];
2441
2442
0
  if (gpass != NULL) {
2443
    // Use global passwords file
2444
0
    if (!mg_fopen(conn, gpass, "r", filep)) {
2445
0
      cry(conn, "fopen(%s): %s", gpass, strerror(ERRNO));
2446
0
    }
2447
0
  } else if (mg_stat(conn, path, filep) && filep->is_directory) {
2448
0
    mg_snprintf(conn, name, sizeof(name), "%s%c%s",
2449
0
    path, '/', PASSWORDS_FILE_NAME);
2450
0
    mg_fopen(conn, name, "r", filep);
2451
0
  } else {
2452
    // Try to find .htpasswd in requested directory.
2453
0
    for (p = path, e = p + strlen(p) - 1; e > p; e--)
2454
0
      if (e[0] == '/')
2455
0
  break;
2456
0
    mg_snprintf(conn, name, sizeof(name), "%.*s%c%s",
2457
0
    (int) (e - p), p, '/', PASSWORDS_FILE_NAME);
2458
0
    mg_fopen(conn, name, "r", filep);
2459
0
  }
2460
0
}
2461
2462
// Parsed Authorization header
2463
struct ah {
2464
  char *user, *uri, *cnonce, *response, *qop, *nc, *nonce;
2465
};
2466
2467
// Return 1 on success. Always initializes the ah structure.
2468
static int parse_auth_header(struct mg_connection *conn, char *buf,
2469
0
           size_t buf_size, struct ah *ah) {
2470
0
  char *name, *value, *s;
2471
0
  const char *auth_header;
2472
2473
0
  (void) memset(ah, 0, sizeof(*ah));
2474
0
  if ((auth_header = mg_get_header(conn, "Authorization")) == NULL ||
2475
0
      mg_strncasecmp(auth_header, "Digest ", 7) != 0) {
2476
0
    return 0;
2477
0
  }
2478
2479
  // Make modifiable copy of the auth header
2480
0
  (void) mg_strlcpy(buf, auth_header + 7, buf_size);
2481
0
  s = buf;
2482
2483
  // Parse authorization header
2484
0
  for (;;) {
2485
    // Gobble initial spaces
2486
0
    while (isspace(* (unsigned char *) s)) {
2487
0
      s++;
2488
0
    }
2489
0
    name = skip_quoted(&s, "=", " ", 0);
2490
    // Value is either quote-delimited, or ends at first comma or space.
2491
0
    if (s[0] == '\"') {
2492
0
      s++;
2493
0
      value = skip_quoted(&s, "\"", " ", '\\');
2494
0
      if (s[0] == ',') {
2495
0
  s++;
2496
0
      }
2497
0
    } else {
2498
0
      value = skip_quoted(&s, ", ", " ", 0);  // IE uses commas, FF uses spaces
2499
0
    }
2500
0
    if (*name == '\0') {
2501
0
      break;
2502
0
    }
2503
2504
0
    if (!strcmp(name, "username")) {
2505
0
      ah->user = value;
2506
0
    } else if (!strcmp(name, "cnonce")) {
2507
0
      ah->cnonce = value;
2508
0
    } else if (!strcmp(name, "response")) {
2509
0
      ah->response = value;
2510
0
    } else if (!strcmp(name, "uri")) {
2511
0
      ah->uri = value;
2512
0
    } else if (!strcmp(name, "qop")) {
2513
0
      ah->qop = value;
2514
0
    } else if (!strcmp(name, "nc")) {
2515
0
      ah->nc = value;
2516
0
    } else if (!strcmp(name, "nonce")) {
2517
0
      ah->nonce = value;
2518
0
    }
2519
0
  }
2520
2521
  // CGI needs it as REMOTE_USER
2522
0
  if (ah->user != NULL) {
2523
0
    conn->request_info.remote_user = mg_strdup(ah->user);
2524
0
  } else {
2525
0
    return 0;
2526
0
  }
2527
2528
0
  return 1;
2529
0
}
2530
2531
0
static char *mg_fgets(char *buf, size_t size, struct file *filep, char **p) {
2532
0
  char *eof;
2533
0
  size_t len;
2534
2535
0
  if (filep->membuf != NULL && *p != NULL) {
2536
0
    eof = (char*)memchr(*p, '\n', &filep->membuf[filep->size] - *p);
2537
0
    len = (size_t) (eof - *p) > size - 1 ? size - 1 : (size_t) (eof - *p);
2538
0
    memcpy(buf, *p, len);
2539
0
    buf[len] = '\0';
2540
0
    *p = eof;
2541
0
    return eof;
2542
0
  } else if (filep->fp != NULL) {
2543
0
    return fgets(buf, size, filep->fp);
2544
0
  } else {
2545
0
    return NULL;
2546
0
  }
2547
0
}
2548
2549
// Authorize against the opened passwords file. Return 1 if authorized.
2550
0
static int authorize(struct mg_connection *conn, struct file *filep) {
2551
0
  struct ah ah;
2552
0
  char line[256], f_user[256], ha1[256], f_domain[256], buf[MG_BUF_LEN], *p;
2553
2554
0
  if (!parse_auth_header(conn, buf, sizeof(buf), &ah)) {
2555
0
    return 0;
2556
0
  }
2557
2558
  // Loop over passwords file
2559
0
  p = (char *) filep->membuf;
2560
0
  while (mg_fgets(line, sizeof(line), filep, &p) != NULL) {
2561
0
    if (sscanf(line, "%[^:]:%[^:]:%s", f_user, f_domain, ha1) != 3) {
2562
0
      continue;
2563
0
    }
2564
2565
0
    if (!strcmp(ah.user, f_user) &&
2566
0
  !strcmp(conn->ctx->config[AUTHENTICATION_DOMAIN], f_domain))
2567
0
      return check_password(conn->request_info.request_method, ha1, ah.uri,
2568
0
          ah.nonce, ah.nc, ah.cnonce, ah.qop, ah.response);
2569
0
  }
2570
2571
0
  return 0;
2572
0
}
2573
2574
// Return 1 if request is authorised, 0 otherwise.
2575
0
static int check_authorization(struct mg_connection *conn, const char *path) {
2576
0
  char fname[PATH_MAX];
2577
0
  struct vec uri_vec, filename_vec;
2578
0
  const char *list;
2579
0
  struct file file = STRUCT_FILE_INITIALIZER;
2580
0
  int authorized = 1;
2581
2582
0
  list = conn->ctx->config[PROTECT_URI];
2583
0
  while ((list = next_option(list, &uri_vec, &filename_vec)) != NULL) {
2584
0
    if (!memcmp(conn->request_info.uri, uri_vec.ptr, uri_vec.len)) {
2585
0
      mg_snprintf(conn, fname, sizeof(fname), "%.*s",
2586
0
      (int) filename_vec.len, filename_vec.ptr);
2587
0
      if (!mg_fopen(conn, fname, "r", &file)) {
2588
0
  cry(conn, "%s: cannot open %s: %s", __func__, fname, strerror(errno));
2589
0
      }
2590
0
      break;
2591
0
    }
2592
0
  }
2593
2594
0
  if (!is_file_opened(&file)) {
2595
0
    open_auth_file(conn, path, &file);
2596
0
  }
2597
2598
0
  if (is_file_opened(&file)) {
2599
0
    authorized = authorize(conn, &file);
2600
0
    mg_fclose(&file);
2601
0
  }
2602
2603
0
  return authorized;
2604
0
}
2605
2606
0
static void send_authorization_request(struct mg_connection *conn) {
2607
0
  conn->status_code = 401;
2608
0
  mg_printf(conn,
2609
0
      "HTTP/1.1 401 Unauthorized\r\n"
2610
0
      "Content-Length: 0\r\n"
2611
0
      "WWW-Authenticate: Digest qop=\"auth\", "
2612
0
      "realm=\"%s\", nonce=\"%lu\"\r\n\r\n",
2613
0
      conn->ctx->config[AUTHENTICATION_DOMAIN],
2614
0
      (unsigned long) time(NULL));
2615
0
}
2616
2617
0
static int is_authorized_for_put(struct mg_connection *conn) {
2618
0
  struct file file = STRUCT_FILE_INITIALIZER;
2619
0
  const char *passfile = conn->ctx->config[PUT_DELETE_PASSWORDS_FILE];
2620
0
  int ret = 0;
2621
2622
0
  if (passfile != NULL && mg_fopen(conn, passfile, "r", &file)) {
2623
0
    ret = authorize(conn, &file);
2624
0
    mg_fclose(&file);
2625
0
  }
2626
2627
0
  return ret;
2628
0
}
2629
2630
int mg_modify_passwords_file(const char *fname, const char *domain,
2631
0
           const char *user, const char *pass) {
2632
0
  int found;
2633
0
  char line[512], u[512], d[512], ha1[33], tmp[PATH_MAX];
2634
0
  FILE *fp, *fp2;
2635
2636
0
  found = 0;
2637
0
  fp = fp2 = NULL;
2638
2639
  // Regard empty password as no password - remove user record.
2640
0
  if (pass != NULL && pass[0] == '\0') {
2641
0
    pass = NULL;
2642
0
  }
2643
2644
0
  (void) snprintf(tmp, sizeof(tmp), "%s.tmp", fname);
2645
2646
  // Create the file if does not exist
2647
0
  if ((fp = fopen(fname, "a+")) != NULL) {
2648
0
    (void) fclose(fp);
2649
0
  }
2650
2651
  // Open the given file and temporary file
2652
0
  if ((fp = fopen(fname, "r")) == NULL) {
2653
0
    return 0;
2654
0
  } else if ((fp2 = fopen(tmp, "w+")) == NULL) {
2655
0
    fclose(fp);
2656
0
    return 0;
2657
0
  }
2658
2659
  // Copy the stuff to temporary file
2660
0
  while (fgets(line, sizeof(line), fp) != NULL) {
2661
0
    if (sscanf(line, "%[^:]:%[^:]:%*s", u, d) != 2) {
2662
0
      continue;
2663
0
    }
2664
2665
0
    if (!strcmp(u, user) && !strcmp(d, domain)) {
2666
0
      found++;
2667
0
      if (pass != NULL) {
2668
0
  mg_md5(ha1, user, ":", domain, ":", pass, NULL);
2669
0
  fprintf(fp2, "%s:%s:%s\n", user, domain, ha1);
2670
0
      }
2671
0
    } else {
2672
0
      fprintf(fp2, "%s", line);
2673
0
    }
2674
0
  }
2675
2676
  // If new user, just add it
2677
0
  if (!found && pass != NULL) {
2678
0
    mg_md5(ha1, user, ":", domain, ":", pass, NULL);
2679
0
    fprintf(fp2, "%s:%s:%s\n", user, domain, ha1);
2680
0
  }
2681
2682
  // Close files
2683
0
  fclose(fp);
2684
0
  fclose(fp2);
2685
2686
  // Put the temp file in place of real file
2687
0
  remove(fname);
2688
0
  rename(tmp, fname);
2689
2690
0
  return 1;
2691
0
}
2692
2693
struct de {
2694
  struct mg_connection *conn;
2695
  char *file_name;
2696
  struct file file;
2697
};
2698
2699
0
static void url_encode(const char *src, char *dst, size_t dst_len) {
2700
0
  static const char *dont_escape = "._-$,;~()";
2701
0
  static const char *hex = "0123456789abcdef";
2702
0
  const char *end = dst + dst_len - 1;
2703
2704
0
  for (; *src != '\0' && dst < end; src++, dst++) {
2705
0
    if (isalnum(*(const unsigned char *) src) ||
2706
0
  strchr(dont_escape, * (const unsigned char *) src) != NULL) {
2707
0
      *dst = *src;
2708
0
    } else if (dst + 2 < end) {
2709
0
      dst[0] = '%';
2710
0
      dst[1] = hex[(* (const unsigned char *) src) >> 4];
2711
0
      dst[2] = hex[(* (const unsigned char *) src) & 0xf];
2712
0
      dst += 2;
2713
0
    }
2714
0
  }
2715
2716
0
  *dst = '\0';
2717
0
}
2718
2719
0
static void print_dir_entry(struct de *de) {
2720
0
  char size[64], mod[64], href[PATH_MAX];
2721
2722
0
  if (de->file.is_directory) {
2723
0
    mg_snprintf(de->conn, size, sizeof(size), "%s", "[DIRECTORY]");
2724
0
  } else {
2725
    // We use (signed) cast below because MSVC 6 compiler cannot
2726
    // convert unsigned __int64 to double. Sigh.
2727
0
    if (de->file.size < 1024) {
2728
0
      mg_snprintf(de->conn, size, sizeof(size), "%d", (int) de->file.size);
2729
0
    } else if (de->file.size < 0x100000) {
2730
0
      mg_snprintf(de->conn, size, sizeof(size),
2731
0
      "%.1fk", (double) de->file.size / 1024.0);
2732
0
    } else if (de->file.size < 0x40000000) {
2733
0
      mg_snprintf(de->conn, size, sizeof(size),
2734
0
      "%.1fM", (double) de->file.size / 1048576);
2735
0
    } else {
2736
0
      mg_snprintf(de->conn, size, sizeof(size),
2737
0
      "%.1fG", (double) de->file.size / 1073741824);
2738
0
    }
2739
0
  }
2740
0
  strftime(mod, sizeof(mod), "%d-%b-%Y %H:%M",
2741
0
     localtime(&de->file.modification_time));
2742
0
  url_encode(de->file_name, href, sizeof(href));
2743
0
  de->conn->num_bytes_sent += mg_printf(de->conn,
2744
0
          "<tr><td><a href=\"%s%s%s\">%s%s</a></td>"
2745
0
          "<td>&nbsp;%s</td><td>&nbsp;&nbsp;%s</td></tr>\n",
2746
0
          de->conn->request_info.uri, href, de->file.is_directory ? "/" : "",
2747
0
          de->file_name, de->file.is_directory ? "/" : "", mod, size);
2748
0
}
2749
2750
// This function is called from send_directory() and used for
2751
// sorting directory entries by size, or name, or modification time.
2752
// On windows, __cdecl specification is needed in case if project is built
2753
// with __stdcall convention. qsort always requires __cdels callback.
2754
0
static int WINCDECL compare_dir_entries(const void *p1, const void *p2) {
2755
0
  const struct de *a = (const struct de *) p1, *b = (const struct de *) p2;
2756
0
  const char *query_string = a->conn->request_info.query_string;
2757
0
  int cmp_result = 0;
2758
2759
0
  if (query_string == NULL) {
2760
0
    query_string = "na";
2761
0
  }
2762
2763
0
  if (a->file.is_directory && !b->file.is_directory) {
2764
0
    return -1;  // Always put directories on top
2765
0
  } else if (!a->file.is_directory && b->file.is_directory) {
2766
0
    return 1;   // Always put directories on top
2767
0
  } else if (*query_string == 'n') {
2768
0
    cmp_result = strcmp(a->file_name, b->file_name);
2769
0
  } else if (*query_string == 's') {
2770
0
    cmp_result = a->file.size == b->file.size ? 0 :
2771
0
      a->file.size > b->file.size ? 1 : -1;
2772
0
  } else if (*query_string == 'd') {
2773
0
    cmp_result = a->file.modification_time == b->file.modification_time ? 0 :
2774
0
      a->file.modification_time > b->file.modification_time ? 1 : -1;
2775
0
  }
2776
2777
0
  return query_string[1] == 'd' ? -cmp_result : cmp_result;
2778
0
}
2779
2780
0
static int must_hide_file(struct mg_connection *conn, const char *path) {
2781
0
  const char *pw_pattern = "**" PASSWORDS_FILE_NAME "$";
2782
0
  const char *pattern = conn->ctx->config[HIDE_FILES];
2783
0
  return match_prefix(pw_pattern, strlen(pw_pattern), path) > 0 ||
2784
0
    (pattern != NULL && match_prefix(pattern, strlen(pattern), path) > 0);
2785
0
}
2786
2787
static int scan_directory(struct mg_connection *conn, const char *dir,
2788
0
        void *data, void (*cb)(struct de *, void *)) {
2789
0
  char path[PATH_MAX];
2790
0
  struct dirent *dp;
2791
0
  DIR *dirp;
2792
0
  struct de de;
2793
2794
0
  if ((dirp = opendir(dir)) == NULL) {
2795
0
    return 0;
2796
0
  } else {
2797
0
    de.conn = conn;
2798
2799
0
    while ((dp = readdir(dirp)) != NULL) {
2800
      // Do not show current dir and hidden files
2801
0
      if (!strcmp(dp->d_name, ".") ||
2802
0
    !strcmp(dp->d_name, "..") ||
2803
0
    must_hide_file(conn, dp->d_name)) {
2804
0
  continue;
2805
0
      }
2806
2807
0
      mg_snprintf(conn, path, sizeof(path), "%s%c%s", dir, '/', dp->d_name);
2808
2809
      // If we don't memset stat structure to zero, mtime will have
2810
      // garbage and strftime() will segfault later on in
2811
      // print_dir_entry(). memset is required only if mg_stat()
2812
      // fails. For more details, see
2813
      // http://code.google.com/p/mongoose/issues/detail?id=79
2814
0
      memset(&de.file, 0, sizeof(de.file));
2815
0
      mg_stat(conn, path, &de.file);
2816
2817
0
      de.file_name = dp->d_name;
2818
0
      cb(&de, data);
2819
0
    }
2820
0
    (void) closedir(dirp);
2821
0
  }
2822
0
  return 1;
2823
0
}
2824
2825
struct dir_scan_data {
2826
  struct de *entries;
2827
  int num_entries;
2828
  int arr_size;
2829
};
2830
2831
0
static void dir_scan_callback(struct de *de, void *data) {
2832
0
  struct dir_scan_data *dsd = (struct dir_scan_data *) data;
2833
2834
0
  if (dsd->entries == NULL || dsd->num_entries >= dsd->arr_size) {
2835
0
    dsd->arr_size *= 2;
2836
0
    dsd->entries = (struct de *) realloc(dsd->entries, dsd->arr_size *
2837
0
           sizeof(dsd->entries[0]));
2838
0
  }
2839
0
  if (dsd->entries == NULL) {
2840
    // TODO(lsm): propagate an error to the caller
2841
0
    dsd->num_entries = 0;
2842
0
  } else {
2843
0
    dsd->entries[dsd->num_entries].file_name = mg_strdup(de->file_name);
2844
0
    dsd->entries[dsd->num_entries].file = de->file;
2845
0
    dsd->entries[dsd->num_entries].conn = de->conn;
2846
0
    dsd->num_entries++;
2847
0
  }
2848
0
}
2849
2850
static void handle_directory_request(struct mg_connection *conn,
2851
0
             const char *dir) {
2852
0
  int i, sort_direction;
2853
0
  struct dir_scan_data data = { NULL, 0, 128 };
2854
2855
0
  if (!scan_directory(conn, dir, &data, dir_scan_callback)) {
2856
0
    send_http_error(conn, 500, "Cannot open directory",
2857
0
        "Error: opendir(%s): %s", dir, strerror(ERRNO));
2858
0
    return;
2859
0
  }
2860
2861
0
  sort_direction = conn->request_info.query_string != NULL &&
2862
0
    conn->request_info.query_string[1] == 'd' ? 'a' : 'd';
2863
2864
0
  conn->must_close = 1;
2865
0
  mg_printf(conn, "%s",
2866
0
      "HTTP/1.1 200 OK\r\n"
2867
0
      "Connection: close\r\n"
2868
0
      "Content-Type: text/html; charset=utf-8\r\n\r\n");
2869
2870
0
  conn->num_bytes_sent += mg_printf(conn,
2871
0
            "<html><head><title>Index of %s</title>"
2872
0
            "<style>th {text-align: left;}</style></head>"
2873
0
            "<body><h1>Index of %s</h1><pre><table cellpadding=\"0\">"
2874
0
            "<tr><th><a href=\"?n%c\">Name</a></th>"
2875
0
            "<th><a href=\"?d%c\">Modified</a></th>"
2876
0
            "<th><a href=\"?s%c\">Size</a></th></tr>"
2877
0
            "<tr><td colspan=\"3\"><hr></td></tr>",
2878
0
            conn->request_info.uri, conn->request_info.uri,
2879
0
            sort_direction, sort_direction, sort_direction);
2880
2881
  // Print first entry - link to a parent directory
2882
0
  conn->num_bytes_sent += mg_printf(conn,
2883
0
            "<tr><td><a href=\"%s%s\">%s</a></td>"
2884
0
            "<td>&nbsp;%s</td><td>&nbsp;&nbsp;%s</td></tr>\n",
2885
0
            conn->request_info.uri, "..", "Parent directory", "-", "-");
2886
2887
  // Sort and print directory entries
2888
0
  qsort(data.entries, (size_t) data.num_entries, sizeof(data.entries[0]),
2889
0
  compare_dir_entries);
2890
0
  for (i = 0; i < data.num_entries; i++) {
2891
0
    print_dir_entry(&data.entries[i]);
2892
0
    free(data.entries[i].file_name);
2893
0
  }
2894
0
  free(data.entries);
2895
2896
0
  conn->num_bytes_sent += mg_printf(conn, "%s", "</table></body></html>");
2897
0
  conn->status_code = 200;
2898
0
}
2899
2900
// Send len bytes from the opened file to the client.
2901
static void send_file_data(struct mg_connection *conn, struct file *filep,
2902
0
         int64_t offset, int64_t len) {
2903
0
  char buf[MG_BUF_LEN];
2904
0
  int to_read, num_read, num_written;
2905
2906
#ifdef DEBUG /* ntop */
2907
  printf("[MONGOOSE][DEBUG] %s offset = %" INT64_FMT " len = %" INT64_FMT " \n",
2908
   __FUNCTION__, offset, len);
2909
#endif
2910
2911
0
  if (len > 0 && filep->membuf != NULL && filep->size > 0) {
2912
0
    if (len > filep->size - offset) {
2913
0
      len = filep->size - offset;
2914
0
    }
2915
0
    mg_write(conn, filep->membuf + offset, (size_t) len);
2916
0
  } else if (len > 0 && filep->fp != NULL) {
2917
0
    fseeko(filep->fp, offset, SEEK_SET);
2918
0
    while (len > 0) {
2919
      // Calculate how much to read from the file in the buffer
2920
0
      to_read = sizeof(buf);
2921
0
      if ((int64_t) to_read > len) {
2922
0
  to_read = (int) len;
2923
0
      }
2924
2925
      // Read from file, exit the loop on error
2926
0
      if ((num_read = fread(buf, 1, (size_t) to_read, filep->fp)) <= 0) {
2927
0
  break;
2928
0
      }
2929
2930
      // Send read bytes to the client, exit the loop on error
2931
0
      if ((num_written = mg_write(conn, buf, (size_t) num_read)) != num_read) {
2932
0
  break;
2933
0
      }
2934
2935
      // Both read and were successful, adjust counters
2936
0
      conn->num_bytes_sent += num_written;
2937
0
      len -= num_written;
2938
0
    }
2939
0
  }
2940
0
}
2941
2942
0
static int parse_range_header(const char *header, int64_t *a, int64_t *b) {
2943
0
  return sscanf(header, "bytes=%" INT64_FMT "-%" INT64_FMT, a, b);
2944
0
}
2945
2946
0
static void gmt_time_string(char *buf, size_t buf_len, time_t *t) {
2947
0
  strftime(buf, buf_len, "%a, %d %b %Y %H:%M:%S GMT", gmtime(t));
2948
0
}
2949
2950
static void construct_etag(char *buf, size_t buf_len,
2951
0
         const struct file *filep) {
2952
0
  snprintf(buf, buf_len, "\"%lx.%" INT64_FMT "\"",
2953
0
     (unsigned long) filep->modification_time, filep->size);
2954
0
}
2955
2956
0
static void fclose_on_exec(struct file *filep) {
2957
0
  if (filep != NULL && filep->fp != NULL) {
2958
0
#ifndef _WIN32
2959
0
    fcntl(fileno(filep->fp), F_SETFD, FD_CLOEXEC);
2960
0
#endif
2961
0
  }
2962
0
}
2963
2964
static void handle_file_request(struct mg_connection *conn, const char *path,
2965
0
        struct file *filep) {
2966
0
  char date[64], lm[64], etag[64], range[64];
2967
0
  const char *msg = "OK", *hdr;
2968
0
  time_t curtime = time(NULL);
2969
0
  int64_t cl, r1, r2;
2970
0
  struct vec mime_vec;
2971
0
  int n;
2972
0
  char gz_path[PATH_MAX];
2973
0
  struct file gz_file = STRUCT_FILE_INITIALIZER;
2974
0
  int use_gzip = 0;
2975
2976
0
  get_mime_type(conn->ctx, path, &mime_vec);
2977
2978
  // Serve pre-compressed .gz file if the browser accepts gzip and it exists
2979
0
  hdr = mg_get_header(conn, "Accept-Encoding");
2980
0
  if (hdr != NULL && strstr(hdr, "gzip") != NULL) {
2981
0
    mg_snprintf(conn, gz_path, sizeof(gz_path), "%s.gz", path);
2982
0
    if (mg_stat(conn, gz_path, &gz_file)) {
2983
0
      use_gzip = 1;
2984
0
      filep->size = gz_file.size;
2985
0
      filep->modification_time = gz_file.modification_time;
2986
0
    }
2987
0
  }
2988
2989
0
  cl = filep->size;
2990
0
  conn->status_code = 200;
2991
0
  range[0] = '\0';
2992
2993
0
  if (!mg_fopen(conn, use_gzip ? gz_path : path, "rb", filep)) {
2994
0
    send_http_error(conn, 500, http_500_error,
2995
0
        "fopen(%s): %s", path, strerror(ERRNO));
2996
0
    return;
2997
0
  }
2998
0
  fclose_on_exec(filep);
2999
3000
  // If Range: header specified, act accordingly
3001
0
  r1 = r2 = 0;
3002
0
  hdr = mg_get_header(conn, "Range");
3003
0
  if (hdr != NULL && (n = parse_range_header(hdr, &r1, &r2)) > 0 &&
3004
0
      r1 >= 0 && r2 > 0) {
3005
0
    conn->status_code = 206;
3006
0
    cl = n == 2 ? (r2 > cl ? cl : r2) - r1 + 1: cl - r1;
3007
0
    mg_snprintf(conn, range, sizeof(range),
3008
0
    "Content-Range: bytes "
3009
0
    "%" INT64_FMT "-%"
3010
0
    INT64_FMT "/%" INT64_FMT "\r\n",
3011
0
    r1, r1 + cl - 1, filep->size);
3012
0
    msg = "Partial Content";
3013
0
  }
3014
3015
  // Prepare Etag, Date, Last-Modified headers. Must be in UTC, according to
3016
  // http://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.3
3017
0
  gmt_time_string(date, sizeof(date), &curtime);
3018
0
  gmt_time_string(lm, sizeof(lm), &filep->modification_time);
3019
0
  construct_etag(etag, sizeof(etag), filep);
3020
3021
0
  (void) mg_printf(conn,
3022
0
       "HTTP/1.1 %d %s\r\n"
3023
0
       "Date: %s\r\n"
3024
0
       "Last-Modified: %s\r\n"
3025
0
       "Etag: %s\r\n"
3026
0
       "Content-Type: %.*s\r\n"
3027
0
       "Content-Length: %" INT64_FMT "\r\n"
3028
0
       "Connection: %s\r\n"
3029
0
       "Accept-Ranges: bytes\r\n"
3030
0
       "%s"
3031
0
       "%s\r\n",
3032
0
       conn->status_code, msg, date, lm, etag, (int) mime_vec.len,
3033
0
       mime_vec.ptr, cl, suggest_connection_header(conn),
3034
0
       use_gzip ? "Content-Encoding: gzip\r\n" : "",
3035
0
       range);
3036
3037
#ifdef DEBUG /* ntop */
3038
  printf(
3039
   "[MONGOOSE][DEBUG] %s\n"
3040
   "HTTP/1.1 %d %s\n"
3041
   "Date: %s\n"
3042
   "Last-Modified: %s\n"
3043
   "Etag: %s\n"
3044
   "Content-Type: %.*s\n"
3045
   "Content-Length: %" INT64_FMT "\n"
3046
   "Connection: %s\n"
3047
   "Accept-Ranges: bytes\n"
3048
   "%s"
3049
   "%s\n",
3050
   __FUNCTION__,
3051
   conn->status_code, msg, date, lm, etag, (int) mime_vec.len,
3052
   mime_vec.ptr, cl, suggest_connection_header(conn),
3053
   use_gzip ? "Content-Encoding: gzip\n" : "",
3054
   range);
3055
#endif
3056
3057
0
  if (strcmp(conn->request_info.request_method, "HEAD") != 0) {
3058
0
    send_file_data(conn, filep, r1, cl);
3059
0
  }
3060
0
  mg_fclose(filep);
3061
0
}
3062
3063
0
void mg_send_file(struct mg_connection *conn, const char *path) {
3064
0
  struct file file = STRUCT_FILE_INITIALIZER;
3065
0
  if (mg_stat(conn, path, &file)) {
3066
0
    handle_file_request(conn, path, &file);
3067
0
  } else {
3068
0
    send_http_error(conn, 404, "Not Found", "%s", "File not found");
3069
0
  }
3070
0
}
3071
3072
3073
// Parse HTTP headers from the given buffer, advance buffer to the point
3074
// where parsing stopped.
3075
0
static void parse_http_headers(char **buf, struct mg_request_info *ri) {
3076
0
  int i;
3077
3078
0
  for (i = 0; i < (int) ARRAY_SIZE(ri->http_headers); i++) {
3079
0
    ri->http_headers[i].name = skip_quoted(buf, ":", " ", 0);
3080
0
    ri->http_headers[i].value = skip(buf, "\r\n");
3081
0
    if (ri->http_headers[i].name[0] == '\0')
3082
0
      break;
3083
0
    ri->num_headers = i + 1;
3084
0
  }
3085
0
}
3086
3087
0
static int is_valid_http_method(const char *method) {
3088
0
  return !strcmp(method, "GET") || !strcmp(method, "POST") ||
3089
0
    !strcmp(method, "HEAD") || !strcmp(method, "CONNECT") ||
3090
0
    !strcmp(method, "PUT") || !strcmp(method, "DELETE") ||
3091
0
    !strcmp(method, "OPTIONS") || !strcmp(method, "PROPFIND");
3092
0
}
3093
3094
// Parse HTTP request, fill in mg_request_info structure.
3095
// This function modifies the buffer by NUL-terminating
3096
// HTTP request components, header names and header values.
3097
0
static int parse_http_message(char *buf, int len, struct mg_request_info *ri) {
3098
0
  int is_request, request_length = get_request_len(buf, len);
3099
0
  if (request_length > 0) {
3100
    // Reset attributes. DO NOT TOUCH is_ssl, remote_ip, remote_port
3101
0
    ri->remote_user = ri->request_method = ri->http_version = ri->uri = NULL;
3102
0
    ri->num_headers = 0;
3103
3104
0
    buf[request_length - 1] = '\0';
3105
3106
    // RFC says that all initial whitespaces should be ingored
3107
0
    while (*buf != '\0' && isspace(* (unsigned char *) buf)) {
3108
0
      buf++;
3109
0
    }
3110
0
    ri->request_method = skip(&buf, " ");
3111
0
    ri->uri = skip(&buf, " ");
3112
0
    ri->http_version = skip(&buf, "\r\n");
3113
0
    if (((is_request = is_valid_http_method(ri->request_method)) &&
3114
0
   memcmp(ri->http_version, "HTTP/", 5) != 0) ||
3115
0
  (!is_request && memcmp(ri->request_method, "HTTP/", 5)) != 0) {
3116
0
      request_length = -1;
3117
0
    } else {
3118
0
      if (is_request) {
3119
0
  ri->http_version += 5;
3120
0
      }
3121
0
      parse_http_headers(&buf, ri);
3122
0
    }
3123
0
  }
3124
0
  return request_length;
3125
0
}
3126
3127
// Keep reading the input (either opened file descriptor fd, or socket sock,
3128
// or SSL descriptor ssl) into buffer buf, until \r\n\r\n appears in the
3129
// buffer (which marks the end of HTTP request). Buffer buf may already
3130
// have some data. The length of the data is stored in nread.
3131
// Upon every read operation, increase nread by the number of bytes read.
3132
static int read_request(FILE *fp, struct mg_connection *conn,
3133
0
      char *buf, int bufsiz, int *nread) {
3134
0
  int request_len, n = 0;
3135
3136
0
  request_len = get_request_len(buf, *nread);
3137
0
  while (*nread < bufsiz && request_len == 0 &&
3138
0
   (n = pull(fp, conn, buf + *nread, bufsiz - *nread)) > 0) {
3139
0
    *nread += n;
3140
0
    request_len = get_request_len(buf, *nread);
3141
0
  }
3142
3143
0
  return request_len <= 0 && n <= 0 ? -1 : request_len;
3144
0
}
3145
3146
// For given directory path, substitute it to valid index file.
3147
// Return 0 if index file has been found, -1 if not found.
3148
// If the file is found, it's stats is returned in stp.
3149
static int substitute_index_file(struct mg_connection *conn, char *path,
3150
0
         size_t path_len, struct file *filep) {
3151
0
  const char *list = conn->ctx->config[INDEX_FILES];
3152
0
  struct file file = STRUCT_FILE_INITIALIZER;
3153
0
  struct vec filename_vec;
3154
0
  size_t n = strlen(path);
3155
0
  int found = 0;
3156
3157
  // The 'path' given to us points to the directory. Remove all trailing
3158
  // directory separator characters from the end of the path, and
3159
  // then append single directory separator character.
3160
0
  while (n > 0 && path[n - 1] == '/') {
3161
0
    n--;
3162
0
  }
3163
0
  path[n] = '/';
3164
3165
  // Traverse index files list. For each entry, append it to the given
3166
  // path and see if the file exists. If it exists, break the loop
3167
0
  while ((list = next_option(list, &filename_vec, NULL)) != NULL) {
3168
3169
    // Ignore too long entries that may overflow path buffer
3170
0
    if (filename_vec.len > path_len - (n + 2))
3171
0
      continue;
3172
3173
    // Prepare full path to the index file
3174
0
    mg_strlcpy(path + n + 1, filename_vec.ptr, filename_vec.len + 1);
3175
3176
    // Does it exist?
3177
0
    if (mg_stat(conn, path, &file)) {
3178
      // Yes it does, break the loop
3179
0
      *filep = file;
3180
0
      found = 1;
3181
0
      break;
3182
0
    }
3183
0
  }
3184
3185
  // If no index file exists, restore directory path
3186
0
  if (!found) {
3187
0
    path[n] = '\0';
3188
0
  }
3189
3190
0
  return found;
3191
0
}
3192
3193
// Return True if we should reply 304 Not Modified.
3194
static int is_not_modified(const struct mg_connection *conn,
3195
0
         const struct file *filep) {
3196
0
  char etag[64];
3197
0
  const char *ims = mg_get_header(conn, "If-Modified-Since");
3198
0
  const char *inm = mg_get_header(conn, "If-None-Match");
3199
0
  construct_etag(etag, sizeof(etag), filep);
3200
0
  return (inm != NULL && !mg_strcasecmp(etag, inm)) ||
3201
0
    (ims != NULL && filep->modification_time <= parse_date_string(ims));
3202
0
}
3203
3204
static int forward_body_data(struct mg_connection *conn, FILE *fp,
3205
0
           SOCKET sock, SSL *ssl) {
3206
0
  const char *expect, *body;
3207
0
  char buf[MG_BUF_LEN];
3208
0
  int to_read, nread, buffered_len, success = 0;
3209
3210
0
  expect = mg_get_header(conn, "Expect");
3211
0
  assert(fp != NULL);
3212
3213
0
  if (conn->content_len == -1) {
3214
0
    send_http_error(conn, 411, "Length Required", "%s", "");
3215
0
  } else if (expect != NULL && mg_strcasecmp(expect, "100-continue")) {
3216
0
    send_http_error(conn, 417, "Expectation Failed", "%s", "");
3217
0
  } else {
3218
0
    if (expect != NULL) {
3219
0
      (void) mg_printf(conn, "%s", "HTTP/1.1 100 Continue\r\n\r\n");
3220
0
    }
3221
3222
0
    body = conn->buf + conn->request_len + conn->consumed_content;
3223
0
    buffered_len = &conn->buf[conn->data_len] - body;
3224
0
    assert(buffered_len >= 0);
3225
0
    assert(conn->consumed_content == 0);
3226
3227
0
    if (buffered_len > 0) {
3228
0
      if ((int64_t) buffered_len > conn->content_len) {
3229
0
  buffered_len = (int) conn->content_len;
3230
0
      }
3231
0
      push(fp, sock, ssl, body, (int64_t) buffered_len);
3232
0
      conn->consumed_content += buffered_len;
3233
0
    }
3234
3235
0
    nread = 0;
3236
0
    while (conn->consumed_content < conn->content_len) {
3237
0
      to_read = sizeof(buf);
3238
0
      if ((int64_t) to_read > conn->content_len - conn->consumed_content) {
3239
0
  to_read = (int) (conn->content_len - conn->consumed_content);
3240
0
      }
3241
0
      nread = pull(NULL, conn, buf, to_read);
3242
0
      if (nread <= 0 || push(fp, sock, ssl, buf, nread) != nread) {
3243
0
  break;
3244
0
      }
3245
0
      conn->consumed_content += nread;
3246
0
    }
3247
3248
0
    if (conn->consumed_content == conn->content_len) {
3249
0
      success = nread >= 0;
3250
0
    }
3251
3252
    // Each error code path in this function must send an error
3253
0
    if (!success) {
3254
0
      send_http_error(conn, 577, http_500_error, "%s", "");
3255
0
    }
3256
0
  }
3257
3258
0
  return success;
3259
0
}
3260
3261
#if !defined(NO_CGI)
3262
// This structure helps to create an environment for the spawned CGI program.
3263
// Environment is an array of "VARIABLE=VALUE\0" ASCIIZ strings,
3264
// last element must be NULL.
3265
// However, on Windows there is a requirement that all these VARIABLE=VALUE\0
3266
// strings must reside in a contiguous buffer. The end of the buffer is
3267
// marked by two '\0' characters.
3268
// We satisfy both worlds: we create an envp array (which is vars), all
3269
// entries are actually pointers inside buf.
3270
struct cgi_env_block {
3271
  struct mg_connection *conn;
3272
  char buf[CGI_ENVIRONMENT_SIZE]; // Environment buffer
3273
  int len; // Space taken
3274
  char *vars[MAX_CGI_ENVIR_VARS]; // char **envp
3275
  int nvars; // Number of variables
3276
};
3277
3278
static char *addenv(struct cgi_env_block *block,
3279
        PRINTF_FORMAT_STRING(const char *fmt), ...)
3280
  PRINTF_ARGS(2, 3);
3281
3282
// Append VARIABLE=VALUE\0 string to the buffer, and add a respective
3283
// pointer into the vars array.
3284
static char *addenv(struct cgi_env_block *block, const char *fmt, ...) {
3285
  int n, space;
3286
  char *added;
3287
  va_list ap;
3288
3289
  // Calculate how much space is left in the buffer
3290
  space = sizeof(block->buf) - block->len - 2;
3291
  assert(space >= 0);
3292
3293
  // Make a pointer to the free space int the buffer
3294
  added = block->buf + block->len;
3295
3296
  // Copy VARIABLE=VALUE\0 string into the free space
3297
  va_start(ap, fmt);
3298
  n = mg_vsnprintf(block->conn, added, (size_t) space, fmt, ap);
3299
  va_end(ap);
3300
3301
  // Make sure we do not overflow buffer and the envp array
3302
  if (n > 0 && n + 1 < space &&
3303
      block->nvars < (int) ARRAY_SIZE(block->vars) - 2) {
3304
    // Append a pointer to the added string into the envp array
3305
    block->vars[block->nvars++] = added;
3306
    // Bump up used length counter. Include \0 terminator
3307
    block->len += n + 1;
3308
  } else {
3309
    cry(block->conn, "%s: CGI env buffer truncated for [%s]", __func__, fmt);
3310
  }
3311
3312
  return added;
3313
}
3314
3315
static void prepare_cgi_environment(struct mg_connection *conn,
3316
            const char *prog,
3317
            struct cgi_env_block *blk) {
3318
  const char *s, *slash;
3319
  struct vec var_vec;
3320
  char *p, src_addr[20];
3321
  int  i;
3322
3323
  blk->len = blk->nvars = 0;
3324
  blk->conn = conn;
3325
  sockaddr_to_string(src_addr, sizeof(src_addr), &conn->client.rsa);
3326
3327
  addenv(blk, "SERVER_NAME=%s", conn->ctx->config[AUTHENTICATION_DOMAIN]);
3328
  addenv(blk, "SERVER_ROOT=%s", conn->ctx->config[DOCUMENT_ROOT]);
3329
  addenv(blk, "DOCUMENT_ROOT=%s", conn->ctx->config[DOCUMENT_ROOT]);
3330
3331
  // Prepare the environment block
3332
  addenv(blk, "%s", "GATEWAY_INTERFACE=CGI/1.1");
3333
  addenv(blk, "%s", "SERVER_PROTOCOL=HTTP/1.1");
3334
  addenv(blk, "%s", "REDIRECT_STATUS=200"); // For PHP
3335
3336
  // TODO(lsm): fix this for IPv6 case
3337
  addenv(blk, "SERVER_PORT=%d", ntohs(conn->client.lsa.sin.sin_port));
3338
3339
  addenv(blk, "REQUEST_METHOD=%s", conn->request_info.request_method);
3340
  addenv(blk, "REMOTE_ADDR=%s", src_addr);
3341
  addenv(blk, "REMOTE_PORT=%d", conn->request_info.remote_port);
3342
  addenv(blk, "REQUEST_URI=%s", conn->request_info.uri);
3343
3344
  // SCRIPT_NAME
3345
  assert(conn->request_info.uri[0] == '/');
3346
  slash = strrchr(conn->request_info.uri, '/');
3347
  if ((s = strrchr(prog, '/')) == NULL)
3348
    s = prog;
3349
  addenv(blk, "SCRIPT_NAME=%.*s%s", (int) (slash - conn->request_info.uri),
3350
   conn->request_info.uri, s);
3351
3352
  addenv(blk, "SCRIPT_FILENAME=%s", prog);
3353
  addenv(blk, "PATH_TRANSLATED=%s", prog);
3354
  addenv(blk, "HTTPS=%s", conn->ssl == NULL ? "off" : "on");
3355
3356
  if ((s = mg_get_header(conn, "Content-Type")) != NULL)
3357
    addenv(blk, "CONTENT_TYPE=%s", s);
3358
3359
  if (conn->request_info.query_string != NULL)
3360
    addenv(blk, "QUERY_STRING=%s", conn->request_info.query_string);
3361
3362
  if ((s = mg_get_header(conn, "Content-Length")) != NULL)
3363
    addenv(blk, "CONTENT_LENGTH=%s", s);
3364
3365
  if ((s = getenv("PATH")) != NULL)
3366
    addenv(blk, "PATH=%s", s);
3367
3368
  if (conn->path_info != NULL) {
3369
    addenv(blk, "PATH_INFO=%s", conn->path_info);
3370
  }
3371
3372
#if defined(_WIN32)
3373
  if ((s = getenv("COMSPEC")) != NULL) {
3374
    addenv(blk, "COMSPEC=%s", s);
3375
  }
3376
  if ((s = getenv("SYSTEMROOT")) != NULL) {
3377
    addenv(blk, "SYSTEMROOT=%s", s);
3378
  }
3379
  if ((s = getenv("SystemDrive")) != NULL) {
3380
    addenv(blk, "SystemDrive=%s", s);
3381
  }
3382
#else
3383
  if ((s = getenv("LD_LIBRARY_PATH")) != NULL)
3384
    addenv(blk, "LD_LIBRARY_PATH=%s", s);
3385
#endif // _WIN32
3386
3387
  if ((s = getenv("PERLLIB")) != NULL)
3388
    addenv(blk, "PERLLIB=%s", s);
3389
3390
  if (conn->request_info.remote_user != NULL) {
3391
    addenv(blk, "REMOTE_USER=%s", conn->request_info.remote_user);
3392
    addenv(blk, "%s", "AUTH_TYPE=Digest");
3393
  }
3394
3395
  // Add all headers as HTTP_* variables
3396
  for (i = 0; i < conn->request_info.num_headers; i++) {
3397
    p = addenv(blk, "HTTP_%s=%s",
3398
         conn->request_info.http_headers[i].name,
3399
         conn->request_info.http_headers[i].value);
3400
3401
    // Convert variable name into uppercase, and change - to _
3402
    for (; *p != '=' && *p != '\0'; p++) {
3403
      if (*p == '-')
3404
  *p = '_';
3405
      *p = (char) toupper(* (unsigned char *) p);
3406
    }
3407
  }
3408
3409
  // Add user-specified variables
3410
  s = conn->ctx->config[CGI_ENVIRONMENT];
3411
  while ((s = next_option(s, &var_vec, NULL)) != NULL) {
3412
    addenv(blk, "%.*s", (int) var_vec.len, var_vec.ptr);
3413
  }
3414
3415
  blk->vars[blk->nvars++] = NULL;
3416
  blk->buf[blk->len++] = '\0';
3417
3418
  assert(blk->nvars < (int) ARRAY_SIZE(blk->vars));
3419
  assert(blk->len > 0);
3420
  assert(blk->len < (int) sizeof(blk->buf));
3421
}
3422
3423
static void handle_cgi_request(struct mg_connection *conn, const char *prog) {
3424
  int headers_len, data_len, i, fd_stdin[2], fd_stdout[2];
3425
  const char *status, *status_text;
3426
  char buf[16384], *pbuf, dir[PATH_MAX], *p;
3427
  struct mg_request_info ri;
3428
  struct cgi_env_block blk;
3429
  FILE *in, *out;
3430
  struct file fout = STRUCT_FILE_INITIALIZER;
3431
  pid_t pid;
3432
3433
  memset(&ri, 0, sizeof(ri));
3434
  prepare_cgi_environment(conn, prog, &blk);
3435
3436
  // CGI must be executed in its own directory. 'dir' must point to the
3437
  // directory containing executable program, 'p' must point to the
3438
  // executable program name relative to 'dir'.
3439
  (void) mg_snprintf(conn, dir, sizeof(dir), "%s", prog);
3440
  if ((p = strrchr(dir, '/')) != NULL) {
3441
    *p++ = '\0';
3442
  } else {
3443
    dir[0] = '.', dir[1] = '\0';
3444
    p = (char *) prog;
3445
  }
3446
3447
  pid = (pid_t) -1;
3448
  fd_stdin[0] = fd_stdin[1] = fd_stdout[0] = fd_stdout[1] = -1;
3449
  in = out = NULL;
3450
3451
  if (pipe(fd_stdin) != 0 || pipe(fd_stdout) != 0) {
3452
    send_http_error(conn, 500, http_500_error,
3453
        "Cannot create CGI pipe: %s", strerror(ERRNO));
3454
    goto done;
3455
  }
3456
3457
  pid = spawn_process(conn, p, blk.buf, blk.vars, fd_stdin[0], fd_stdout[1],
3458
          dir);
3459
  // spawn_process() must close those!
3460
  // If we don't mark them as closed, close() attempt before
3461
  // return from this function throws an exception on Windows.
3462
  // Windows does not like when closed descriptor is closed again.
3463
  fd_stdin[0] = fd_stdout[1] = -1;
3464
3465
  if (pid == (pid_t) -1) {
3466
    send_http_error(conn, 500, http_500_error,
3467
        "Cannot spawn CGI process [%s]: %s", prog, strerror(ERRNO));
3468
    goto done;
3469
  }
3470
3471
  if ((in = fdopen(fd_stdin[1], "wb")) == NULL ||
3472
      (out = fdopen(fd_stdout[0], "rb")) == NULL) {
3473
    send_http_error(conn, 500, http_500_error,
3474
        "fopen: %s", strerror(ERRNO));
3475
    goto done;
3476
  }
3477
3478
  setbuf(in, NULL);
3479
  setbuf(out, NULL);
3480
  fout.fp = out;
3481
3482
  // Send POST data to the CGI process if needed
3483
  if (!strcmp(conn->request_info.request_method, "POST") &&
3484
      !forward_body_data(conn, in, INVALID_SOCKET, NULL)) {
3485
    goto done;
3486
  }
3487
3488
  // Close so child gets an EOF.
3489
  fclose(in);
3490
  in = NULL;
3491
  fd_stdin[1] = -1;
3492
3493
  // Now read CGI reply into a buffer. We need to set correct
3494
  // status code, thus we need to see all HTTP headers first.
3495
  // Do not send anything back to client, until we buffer in all
3496
  // HTTP headers.
3497
  data_len = 0;
3498
  headers_len = read_request(out, conn, buf, sizeof(buf), &data_len);
3499
  if (headers_len <= 0) {
3500
    send_http_error(conn, 500, http_500_error,
3501
        "CGI program sent malformed or too big (>%u bytes) "
3502
        "HTTP headers: [%.*s]",
3503
        (unsigned) sizeof(buf), data_len, buf);
3504
    goto done;
3505
  }
3506
  pbuf = buf;
3507
  buf[headers_len - 1] = '\0';
3508
  parse_http_headers(&pbuf, &ri);
3509
3510
  // Make up and send the status line
3511
  status_text = "OK";
3512
  if ((status = get_header(&ri, "Status")) != NULL) {
3513
    conn->status_code = atoi(status);
3514
    status_text = status;
3515
    while (isdigit(* (unsigned char *) status_text) || *status_text == ' ') {
3516
      status_text++;
3517
    }
3518
  } else if (get_header(&ri, "Location") != NULL) {
3519
    conn->status_code = 302;
3520
  } else {
3521
    conn->status_code = 200;
3522
  }
3523
  if (get_header(&ri, "Connection") != NULL &&
3524
      !mg_strcasecmp(get_header(&ri, "Connection"), "keep-alive")) {
3525
    conn->must_close = 1;
3526
  }
3527
  (void) mg_printf(conn, "HTTP/1.1 %d %s\r\n", conn->status_code,
3528
       status_text);
3529
3530
  // Send headers
3531
  for (i = 0; i < ri.num_headers; i++) {
3532
    mg_printf(conn, "%s: %s\r\n",
3533
        ri.http_headers[i].name, ri.http_headers[i].value);
3534
  }
3535
  mg_write(conn, "\r\n", 2);
3536
3537
  // Send chunk of data that may have been read after the headers
3538
  conn->num_bytes_sent += mg_write(conn, buf + headers_len,
3539
           (size_t)(data_len - headers_len));
3540
3541
  // Read the rest of CGI output and send to the client
3542
  send_file_data(conn, &fout, 0, INT64_MAX);
3543
3544
 done:
3545
  if (pid != (pid_t) -1) {
3546
    kill(pid, SIGKILL);
3547
  }
3548
  if (fd_stdin[0] != -1) {
3549
    close(fd_stdin[0]);
3550
  }
3551
  if (fd_stdout[1] != -1) {
3552
    close(fd_stdout[1]);
3553
  }
3554
3555
  if (in != NULL) {
3556
    fclose(in);
3557
  } else if (fd_stdin[1] != -1) {
3558
    close(fd_stdin[1]);
3559
  }
3560
3561
  if (out != NULL) {
3562
    fclose(out);
3563
  } else if (fd_stdout[0] != -1) {
3564
    close(fd_stdout[0]);
3565
  }
3566
}
3567
#endif // !NO_CGI
3568
3569
// For a given PUT path, create all intermediate subdirectories
3570
// for given path. Return 0 if the path itself is a directory,
3571
// or -1 on error, 1 if OK.
3572
0
static int put_dir(struct mg_connection *conn, const char *path) {
3573
0
  char buf[PATH_MAX];
3574
0
  const char *s, *p;
3575
0
  struct file file = STRUCT_FILE_INITIALIZER;
3576
0
  int len, res = 1;
3577
3578
0
  for (s = p = path + 2; (p = strchr(s, '/')) != NULL; s = ++p) {
3579
0
    len = p - path;
3580
0
    if (len >= (int) sizeof(buf)) {
3581
0
      res = -1;
3582
0
      break;
3583
0
    }
3584
0
    memcpy(buf, path, len);
3585
0
    buf[len] = '\0';
3586
3587
    // Try to create intermediate directory
3588
0
    DEBUG_TRACE(("mkdir(%s)", buf));
3589
0
    if (!mg_stat(conn, buf, &file) && mg_mkdir(buf, 0755) != 0) {
3590
0
      res = -1;
3591
0
      break;
3592
0
    }
3593
3594
    // Is path itself a directory?
3595
0
    if (p[1] == '\0') {
3596
0
      res = 0;
3597
0
    }
3598
0
  }
3599
3600
0
  return res;
3601
0
}
3602
3603
0
static void put_file(struct mg_connection *conn, const char *path) {
3604
0
  struct file file = STRUCT_FILE_INITIALIZER;
3605
0
  const char *range;
3606
0
  int64_t r1, r2;
3607
0
  int rc;
3608
3609
0
  conn->status_code = mg_stat(conn, path, &file) ? 200 : 201;
3610
3611
0
  if ((rc = put_dir(conn, path)) == 0) {
3612
0
    mg_printf(conn, "HTTP/1.1 %d OK\r\n\r\n", conn->status_code);
3613
0
  } else if (rc == -1) {
3614
0
    send_http_error(conn, 500, http_500_error,
3615
0
        "put_dir(%s): %s", path, strerror(ERRNO));
3616
0
  } else if (!mg_fopen(conn, path, "wb+", &file) || file.fp == NULL) {
3617
0
    mg_fclose(&file);
3618
0
    send_http_error(conn, 500, http_500_error,
3619
0
        "fopen(%s): %s", path, strerror(ERRNO));
3620
0
  } else {
3621
0
    fclose_on_exec(&file);
3622
0
    range = mg_get_header(conn, "Content-Range");
3623
0
    r1 = r2 = 0;
3624
0
    if (range != NULL && parse_range_header(range, &r1, &r2) > 0) {
3625
0
      conn->status_code = 206;
3626
0
      fseeko(file.fp, r1, SEEK_SET);
3627
0
    }
3628
0
    if (forward_body_data(conn, file.fp, INVALID_SOCKET, NULL)) {
3629
0
      mg_printf(conn, "HTTP/1.1 %d OK\r\n\r\n", conn->status_code);
3630
0
    }
3631
0
    mg_fclose(&file);
3632
0
  }
3633
0
}
3634
3635
static void send_ssi_file(struct mg_connection *, const char *,
3636
        struct file *, int);
3637
3638
static void do_ssi_include(struct mg_connection *conn, const char *ssi,
3639
0
         char *tag, int include_level) {
3640
0
  char file_name[MG_BUF_LEN], path[PATH_MAX], *p;
3641
0
  struct file file = STRUCT_FILE_INITIALIZER;
3642
3643
  // sscanf() is safe here, since send_ssi_file() also uses buffer
3644
  // of size MG_BUF_LEN to get the tag. So strlen(tag) is always < MG_BUF_LEN.
3645
0
  if (sscanf(tag, " virtual=\"%[^\"]\"", file_name) == 1) {
3646
    // File name is relative to the webserver root
3647
0
    (void) mg_snprintf(conn, path, sizeof(path), "%s%c%s",
3648
0
           conn->ctx->config[DOCUMENT_ROOT], '/', file_name);
3649
0
  } else if (sscanf(tag, " file=\"%[^\"]\"", file_name) == 1) {
3650
    // File name is relative to the webserver working directory
3651
    // or it is absolute system path
3652
0
    (void) mg_snprintf(conn, path, sizeof(path), "%s", file_name);
3653
0
  } else if (sscanf(tag, " \"%[^\"]\"", file_name) == 1) {
3654
    // File name is relative to the currect document
3655
0
    (void) mg_snprintf(conn, path, sizeof(path), "%s", ssi);
3656
0
    if ((p = strrchr(path, '/')) != NULL) {
3657
0
      p[1] = '\0';
3658
0
    }
3659
0
    (void) mg_snprintf(conn, path + strlen(path),
3660
0
           sizeof(path) - strlen(path), "%s", file_name);
3661
0
  } else {
3662
0
    cry(conn, "Bad SSI #include: [%s]", tag);
3663
0
    return;
3664
0
  }
3665
3666
0
  if (!mg_fopen(conn, path, "rb", &file)) {
3667
0
    cry(conn, "Cannot open SSI #include: [%s]: fopen(%s): %s",
3668
0
  tag, path, strerror(ERRNO));
3669
0
  } else {
3670
0
    fclose_on_exec(&file);
3671
0
    if (match_prefix(conn->ctx->config[SSI_EXTENSIONS],
3672
0
         strlen(conn->ctx->config[SSI_EXTENSIONS]), path) > 0) {
3673
0
      send_ssi_file(conn, path, &file, include_level + 1);
3674
0
    } else {
3675
0
      send_file_data(conn, &file, 0, INT64_MAX);
3676
0
    }
3677
0
    mg_fclose(&file);
3678
0
  }
3679
0
}
3680
3681
#if !defined(NO_POPEN)
3682
0
static void do_ssi_exec(struct mg_connection *conn, char *tag) {
3683
0
  char cmd[MG_BUF_LEN];
3684
0
  struct file file = STRUCT_FILE_INITIALIZER;
3685
3686
0
  if (sscanf(tag, " \"%[^\"]\"", cmd) != 1) {
3687
0
    cry(conn, "Bad SSI #exec: [%s]", tag);
3688
0
  } else if ((file.fp = popen(cmd, "r")) == NULL) {
3689
0
    cry(conn, "Cannot SSI #exec: [%s]: %s", cmd, strerror(ERRNO));
3690
0
  } else {
3691
0
    send_file_data(conn, &file, 0, INT64_MAX);
3692
0
    pclose(file.fp);
3693
0
  }
3694
0
}
3695
#endif // !NO_POPEN
3696
3697
0
static int mg_fgetc(struct file *filep, int offset) {
3698
0
  if (filep->membuf != NULL && offset >=0 && offset < filep->size) {
3699
0
    return ((unsigned char *) filep->membuf)[offset];
3700
0
  } else if (filep->fp != NULL) {
3701
0
    return fgetc(filep->fp);
3702
0
  } else {
3703
0
    return EOF;
3704
0
  }
3705
0
}
3706
3707
static void send_ssi_file(struct mg_connection *conn, const char *path,
3708
0
        struct file *filep, int include_level) {
3709
0
  char buf[MG_BUF_LEN];
3710
0
  int ch, offset, len, in_ssi_tag;
3711
3712
0
  if (include_level > 10) {
3713
0
    cry(conn, "SSI #include level is too deep (%s)", path);
3714
0
    return;
3715
0
  }
3716
3717
0
  in_ssi_tag = len = offset = 0;
3718
0
  while ((ch = mg_fgetc(filep, offset)) != EOF) {
3719
0
    if (in_ssi_tag && ch == '>') {
3720
0
      in_ssi_tag = 0;
3721
0
      buf[len++] = (char) ch;
3722
0
      buf[len] = '\0';
3723
0
      assert(len <= (int) sizeof(buf));
3724
0
      if (len < 6 || memcmp(buf, "<!--#", 5) != 0) {
3725
  // Not an SSI tag, pass it
3726
0
  (void) mg_write(conn, buf, (size_t) len);
3727
0
      } else {
3728
0
  if (!memcmp(buf + 5, "include", 7)) {
3729
0
    do_ssi_include(conn, path, buf + 12, include_level);
3730
0
#if !defined(NO_POPEN)
3731
0
  } else if (!memcmp(buf + 5, "exec", 4)) {
3732
0
    do_ssi_exec(conn, buf + 9);
3733
0
#endif // !NO_POPEN
3734
0
  } else {
3735
0
    cry(conn, "%s: unknown SSI " "command: \"%s\"", path, buf);
3736
0
  }
3737
0
      }
3738
0
      len = 0;
3739
0
    } else if (in_ssi_tag) {
3740
0
      if (len == 5 && memcmp(buf, "<!--#", 5) != 0) {
3741
  // Not an SSI tag
3742
0
  in_ssi_tag = 0;
3743
0
      } else if (len == (int) sizeof(buf) - 2) {
3744
0
  cry(conn, "%s: SSI tag is too large", path);
3745
0
  len = 0;
3746
0
      }
3747
0
      buf[len++] = ch & 0xff;
3748
0
    } else if (ch == '<') {
3749
0
      in_ssi_tag = 1;
3750
0
      if (len > 0) {
3751
0
  mg_write(conn, buf, (size_t) len);
3752
0
      }
3753
0
      len = 0;
3754
0
      buf[len++] = ch & 0xff;
3755
0
    } else {
3756
0
      buf[len++] = ch & 0xff;
3757
0
      if (len == (int) sizeof(buf)) {
3758
0
  mg_write(conn, buf, (size_t) len);
3759
0
  len = 0;
3760
0
      }
3761
0
    }
3762
0
  }
3763
3764
  // Send the rest of buffered data
3765
0
  if (len > 0) {
3766
0
    mg_write(conn, buf, (size_t) len);
3767
0
  }
3768
0
}
3769
3770
static void handle_ssi_file_request(struct mg_connection *conn,
3771
0
            const char *path) {
3772
0
  struct file file = STRUCT_FILE_INITIALIZER;
3773
3774
0
  if (!mg_fopen(conn, path, "rb", &file)) {
3775
0
    send_http_error(conn, 500, http_500_error, "fopen(%s): %s", path,
3776
0
        strerror(ERRNO));
3777
0
  } else {
3778
0
    conn->must_close = 1;
3779
0
    fclose_on_exec(&file);
3780
0
    mg_printf(conn, "HTTP/1.1 200 OK\r\n"
3781
0
        "Content-Type: text/html\r\nConnection: %s\r\n\r\n",
3782
0
        suggest_connection_header(conn));
3783
0
    send_ssi_file(conn, path, &file, 0);
3784
0
    mg_fclose(&file);
3785
0
  }
3786
0
}
3787
3788
0
static void send_options(struct mg_connection *conn) {
3789
0
  conn->status_code = 200;
3790
3791
0
  mg_printf(conn, "%s", "HTTP/1.1 200 OK\r\n"
3792
0
      "Allow: GET, POST, HEAD, CONNECT, PUT, DELETE, OPTIONS\r\n"
3793
0
      "DAV: 1\r\n\r\n");
3794
0
}
3795
3796
// Writes PROPFIND properties for a collection element
3797
static void print_props(struct mg_connection *conn, const char* uri,
3798
0
      struct file *filep) {
3799
0
  char mtime[64];
3800
0
  gmt_time_string(mtime, sizeof(mtime), &filep->modification_time);
3801
0
  conn->num_bytes_sent += mg_printf(conn,
3802
0
            "<d:response>"
3803
0
            "<d:href>%s</d:href>"
3804
0
            "<d:propstat>"
3805
0
            "<d:prop>"
3806
0
            "<d:resourcetype>%s</d:resourcetype>"
3807
0
            "<d:getcontentlength>%" INT64_FMT "</d:getcontentlength>"
3808
0
            "<d:getlastmodified>%s</d:getlastmodified>"
3809
0
            "</d:prop>"
3810
0
            "<d:status>HTTP/1.1 200 OK</d:status>"
3811
0
            "</d:propstat>"
3812
0
            "</d:response>\n",
3813
0
            uri,
3814
0
            filep->is_directory ? "<d:collection/>" : "",
3815
0
            filep->size,
3816
0
            mtime);
3817
0
}
3818
3819
0
static void print_dav_dir_entry(struct de *de, void *data) {
3820
0
  char href[PATH_MAX];
3821
0
  struct mg_connection *conn = (struct mg_connection *) data;
3822
0
  mg_snprintf(conn, href, sizeof(href), "%s%s",
3823
0
        conn->request_info.uri, de->file_name);
3824
0
  print_props(conn, href, &de->file);
3825
0
}
3826
3827
static void handle_propfind(struct mg_connection *conn, const char *path,
3828
0
          struct file *filep) {
3829
0
  const char *depth = mg_get_header(conn, "Depth");
3830
3831
0
  conn->must_close = 1;
3832
0
  conn->status_code = 207;
3833
0
  mg_printf(conn, "HTTP/1.1 207 Multi-Status\r\n"
3834
0
      "Connection: close\r\n"
3835
0
      "Content-Type: text/xml; charset=utf-8\r\n\r\n");
3836
3837
0
  conn->num_bytes_sent += mg_printf(conn,
3838
0
            "<?xml version=\"1.0\" encoding=\"utf-8\"?>"
3839
0
            "<d:multistatus xmlns:d='DAV:'>\n");
3840
3841
  // Print properties for the requested resource itself
3842
0
  print_props(conn, conn->request_info.uri, filep);
3843
3844
  // If it is a directory, print directory entries too if Depth is not 0
3845
0
  if (filep->is_directory &&
3846
0
      !mg_strcasecmp(conn->ctx->config[ENABLE_DIRECTORY_LISTING], "yes") &&
3847
0
      (depth == NULL || strcmp(depth, "0") != 0)) {
3848
0
    scan_directory(conn, path, conn, &print_dav_dir_entry);
3849
0
  }
3850
3851
0
  conn->num_bytes_sent += mg_printf(conn, "%s\n", "</d:multistatus>");
3852
0
}
3853
3854
#if defined(USE_WEBSOCKET)
3855
3856
// START OF SHA-1 code
3857
// Copyright(c) By Steve Reid <steve@edmweb.com>
3858
#define SHA1HANDSOFF
3859
#if defined(__sun)
3860
#include "solarisfixes.h"
3861
#endif
3862
3863
union char64long16 { unsigned char c[64]; uint32_t l[16]; };
3864
3865
#define rol(value, bits) (((value) << (bits)) | ((value) >> (32 - (bits))))
3866
3867
static uint32_t blk0(union char64long16 *block, int i) {
3868
  // Forrest: SHA expect BIG_ENDIAN, swap if LITTLE_ENDIAN
3869
  if (!is_big_endian()) {
3870
    block->l[i] = (rol(block->l[i], 24) & 0xFF00FF00) |
3871
      (rol(block->l[i], 8) & 0x00FF00FF);
3872
  }
3873
  return block->l[i];
3874
}
3875
3876
#define blk(i) (block->l[i&15] = rol(block->l[(i+13)&15]^block->l[(i+8)&15] \
3877
             ^block->l[(i+2)&15]^block->l[i&15],1))
3878
#define R0(v,w,x,y,z,i) z+=((w&(x^y))^y)+blk0(block, i)+0x5A827999+rol(v,5);w=rol(w,30);
3879
#define R1(v,w,x,y,z,i) z+=((w&(x^y))^y)+blk(i)+0x5A827999+rol(v,5);w=rol(w,30);
3880
#define R2(v,w,x,y,z,i) z+=(w^x^y)+blk(i)+0x6ED9EBA1+rol(v,5);w=rol(w,30);
3881
#define R3(v,w,x,y,z,i) z+=(((w|x)&y)|(w&x))+blk(i)+0x8F1BBCDC+rol(v,5);w=rol(w,30);
3882
#define R4(v,w,x,y,z,i) z+=(w^x^y)+blk(i)+0xCA62C1D6+rol(v,5);w=rol(w,30);
3883
3884
typedef struct {
3885
  uint32_t state[5];
3886
  uint32_t count[2];
3887
  unsigned char buffer[64];
3888
} SHA1_CTX;
3889
3890
static void SHA1Transform(uint32_t state[5], const unsigned char buffer[64]) {
3891
  uint32_t a, b, c, d, e;
3892
  union char64long16 block[1];
3893
3894
  memcpy(block, buffer, 64);
3895
  a = state[0];
3896
  b = state[1];
3897
  c = state[2];
3898
  d = state[3];
3899
  e = state[4];
3900
  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);
3901
  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);
3902
  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);
3903
  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);
3904
  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);
3905
  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);
3906
  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);
3907
  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);
3908
  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);
3909
  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);
3910
  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);
3911
  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);
3912
  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);
3913
  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);
3914
  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);
3915
  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);
3916
  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);
3917
  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);
3918
  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);
3919
  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);
3920
  state[0] += a;
3921
  state[1] += b;
3922
  state[2] += c;
3923
  state[3] += d;
3924
  state[4] += e;
3925
  a = b = c = d = e = 0;
3926
  memset(block, '\0', sizeof(block));
3927
}
3928
3929
static void SHA1Init(SHA1_CTX* context) {
3930
  context->state[0] = 0x67452301;
3931
  context->state[1] = 0xEFCDAB89;
3932
  context->state[2] = 0x98BADCFE;
3933
  context->state[3] = 0x10325476;
3934
  context->state[4] = 0xC3D2E1F0;
3935
  context->count[0] = context->count[1] = 0;
3936
}
3937
3938
static void SHA1Update(SHA1_CTX* context, const unsigned char* data,
3939
           uint32_t len) {
3940
  uint32_t i, j;
3941
3942
  j = context->count[0];
3943
  if ((context->count[0] += len << 3) < j)
3944
    context->count[1]++;
3945
  context->count[1] += (len>>29);
3946
  j = (j >> 3) & 63;
3947
  if ((j + len) > 63) {
3948
    memcpy(&context->buffer[j], data, (i = 64-j));
3949
    SHA1Transform(context->state, context->buffer);
3950
    for ( ; i + 63 < len; i += 64) {
3951
      SHA1Transform(context->state, &data[i]);
3952
    }
3953
    j = 0;
3954
  }
3955
  else i = 0;
3956
  memcpy(&context->buffer[j], &data[i], len - i);
3957
}
3958
3959
static void SHA1Final(unsigned char digest[20], SHA1_CTX* context) {
3960
  unsigned i;
3961
  unsigned char finalcount[8], c;
3962
3963
  for (i = 0; i < 8; i++) {
3964
    finalcount[i] = (unsigned char)((context->count[(i >= 4 ? 0 : 1)]
3965
             >> ((3-(i & 3)) * 8) ) & 255);
3966
  }
3967
  c = 0200;
3968
  SHA1Update(context, &c, 1);
3969
  while ((context->count[0] & 504) != 448) {
3970
    c = 0000;
3971
    SHA1Update(context, &c, 1);
3972
  }
3973
  SHA1Update(context, finalcount, 8);
3974
  for (i = 0; i < 20; i++) {
3975
    digest[i] = (unsigned char)
3976
      ((context->state[i>>2] >> ((3-(i & 3)) * 8) ) & 255);
3977
  }
3978
  memset(context, '\0', sizeof(*context));
3979
  memset(&finalcount, '\0', sizeof(finalcount));
3980
}
3981
// END OF SHA1 CODE
3982
3983
static void base64_encode(const unsigned char *src, int src_len, char *dst) {
3984
  static const char *b64 =
3985
    "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
3986
  int i, j, a, b, c;
3987
3988
  for (i = j = 0; i < src_len; i += 3) {
3989
    a = src[i];
3990
    b = i + 1 >= src_len ? 0 : src[i + 1];
3991
    c = i + 2 >= src_len ? 0 : src[i + 2];
3992
3993
    dst[j++] = b64[a >> 2];
3994
    dst[j++] = b64[((a & 3) << 4) | (b >> 4)];
3995
    if (i + 1 < src_len) {
3996
      dst[j++] = b64[(b & 15) << 2 | (c >> 6)];
3997
    }
3998
    if (i + 2 < src_len) {
3999
      dst[j++] = b64[c & 63];
4000
    }
4001
  }
4002
  while (j % 4 != 0) {
4003
    dst[j++] = '=';
4004
  }
4005
  dst[j++] = '\0';
4006
}
4007
4008
static void send_websocket_handshake(struct mg_connection *conn) {
4009
  static const char *magic = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
4010
  char buf[100], sha[20], b64_sha[sizeof(sha) * 2];
4011
  SHA1_CTX sha_ctx;
4012
4013
  mg_snprintf(conn, buf, sizeof(buf), "%s%s",
4014
        mg_get_header(conn, "Sec-WebSocket-Key"), magic);
4015
  SHA1Init(&sha_ctx);
4016
  SHA1Update(&sha_ctx, (unsigned char *) buf, strlen(buf));
4017
  SHA1Final((unsigned char *) sha, &sha_ctx);
4018
  base64_encode((unsigned char *) sha, sizeof(sha), b64_sha);
4019
  mg_printf(conn, "%s%s%s",
4020
      "HTTP/1.1 101 Switching Protocols\r\n"
4021
      "Upgrade: websocket\r\n"
4022
      "Connection: Upgrade\r\n"
4023
      "Sec-WebSocket-Accept: ", b64_sha, "\r\n\r\n");
4024
}
4025
4026
static void read_websocket(struct mg_connection *conn) {
4027
  unsigned char *buf = (unsigned char *) conn->buf + conn->request_len;
4028
  int n, len, mask_len, body_len, discard_len;
4029
4030
  for (;;) {
4031
    if ((body_len = conn->data_len - conn->request_len) >= 2) {
4032
      len = buf[1] & 127;
4033
      mask_len = buf[1] & 128 ? 4 : 0;
4034
      if (len < 126) {
4035
  conn->content_len = 2 + mask_len + len;
4036
      } else if (len == 126 && body_len >= 4) {
4037
  conn->content_len = 4 + mask_len + ((((int) buf[2]) << 8) + buf[3]);
4038
      } else if (body_len >= 10) {
4039
  conn->content_len = 10 + mask_len +
4040
    (((uint64_t) htonl(* (uint32_t *) &buf[2])) << 32) +
4041
    htonl(* (uint32_t *) &buf[6]);
4042
      }
4043
    }
4044
4045
    if (conn->content_len > 0) {
4046
      if (conn->ctx->callbacks.websocket_data != NULL &&
4047
    conn->ctx->callbacks.websocket_data(conn) == 0) {
4048
  break;  // Callback signalled to exit
4049
      }
4050
      discard_len = conn->content_len > body_len ?
4051
  body_len : (int) conn->content_len;
4052
      memmove(buf, buf + discard_len, conn->data_len - discard_len);
4053
      conn->data_len -= discard_len;
4054
      conn->content_len = conn->consumed_content = 0;
4055
    } else {
4056
      n = pull(NULL, conn, conn->buf + conn->data_len,
4057
         conn->buf_size - conn->data_len);
4058
      if (n <= 0) {
4059
  break;
4060
      }
4061
      conn->data_len += n;
4062
    }
4063
  }
4064
}
4065
4066
static void handle_websocket_request(struct mg_connection *conn) {
4067
  if (strcmp(mg_get_header(conn, "Sec-WebSocket-Version"), "13") != 0) {
4068
    send_http_error(conn, 426, "Upgrade Required", "%s", "Upgrade Required");
4069
  } else if (conn->ctx->callbacks.websocket_connect != NULL &&
4070
       conn->ctx->callbacks.websocket_connect(conn) != 0) {
4071
    // Callback has returned non-zero, do not proceed with handshake
4072
  } else {
4073
    send_websocket_handshake(conn);
4074
    if (conn->ctx->callbacks.websocket_ready != NULL) {
4075
      conn->ctx->callbacks.websocket_ready(conn);
4076
    }
4077
    read_websocket(conn);
4078
  }
4079
}
4080
4081
static int is_websocket_request(const struct mg_connection *conn) {
4082
  const char *host, *upgrade, *connection, *version, *key;
4083
4084
  host = mg_get_header(conn, "Host");
4085
  upgrade = mg_get_header(conn, "Upgrade");
4086
  connection = mg_get_header(conn, "Connection");
4087
  key = mg_get_header(conn, "Sec-WebSocket-Key");
4088
  version = mg_get_header(conn, "Sec-WebSocket-Version");
4089
4090
  return host != NULL && upgrade != NULL && connection != NULL &&
4091
    key != NULL && version != NULL &&
4092
    strstr(upgrade, "websocket") != NULL &&
4093
    strstr(connection, "Upgrade") != NULL;
4094
}
4095
#endif // !USE_WEBSOCKET
4096
4097
0
static int isbyte(int n) {
4098
0
  return n >= 0 && n <= 255;
4099
0
}
4100
4101
0
static int parse_net(const char *spec, uint32_t *net, uint32_t *mask) {
4102
0
  int n, a, b, c, d, slash = 32, len = 0;
4103
4104
0
  if ((sscanf(spec, "%d.%d.%d.%d/%d%n", &a, &b, &c, &d, &slash, &n) == 5 ||
4105
0
       sscanf(spec, "%d.%d.%d.%d%n", &a, &b, &c, &d, &n) == 4) &&
4106
0
      isbyte(a) && isbyte(b) && isbyte(c) && isbyte(d) &&
4107
0
      slash >= 0 && slash < 33) {
4108
0
    len = n;
4109
0
    *net = ((uint32_t)a << 24) | ((uint32_t)b << 16) | ((uint32_t)c << 8) | d;
4110
0
    *mask = slash ? 0xffffffffU << (32 - slash) : 0;
4111
0
  }
4112
4113
0
  return len;
4114
0
}
4115
4116
0
static int set_throttle(const char *spec, uint32_t remote_ip, const char *uri) {
4117
0
  int throttle = 0;
4118
0
  struct vec vec, val;
4119
0
  uint32_t net, mask;
4120
0
  char mult;
4121
0
  double v;
4122
4123
0
  while ((spec = next_option(spec, &vec, &val)) != NULL) {
4124
0
    mult = ',';
4125
0
    if (sscanf(val.ptr, "%lf%c", &v, &mult) < 1 || v < 0 ||
4126
0
  (lowercase(&mult) != 'k' && lowercase(&mult) != 'm' && mult != ',')) {
4127
0
      continue;
4128
0
    }
4129
0
    v *= lowercase(&mult) == 'k' ? 1024 : lowercase(&mult) == 'm' ? 1048576 : 1;
4130
0
    if (vec.len == 1 && vec.ptr[0] == '*') {
4131
0
      throttle = (int) v;
4132
0
    } else if (parse_net(vec.ptr, &net, &mask) > 0) {
4133
0
      if ((remote_ip & mask) == net) {
4134
0
  throttle = (int) v;
4135
0
      }
4136
0
    } else if (match_prefix(vec.ptr, vec.len, uri) > 0) {
4137
0
      throttle = (int) v;
4138
0
    }
4139
0
  }
4140
4141
0
  return throttle;
4142
0
}
4143
4144
0
static uint32_t get_remote_ip(const struct mg_connection *conn) {
4145
0
  return ntohl(* (uint32_t *) &conn->client.rsa.sin.sin_addr);
4146
0
}
4147
4148
#ifdef MONGOOSE_USE_LUA
4149
4150
#ifdef _WIN32
4151
static void *mmap(void *addr, int64_t len, int prot, int flags, int fd,
4152
      int offset) {
4153
  HANDLE fh = (HANDLE) _get_osfhandle(fd);
4154
  HANDLE mh = CreateFileMapping(fh, 0, PAGE_READONLY, 0, 0, 0);
4155
  void *p = MapViewOfFile(mh, FILE_MAP_READ, 0, 0, (size_t) len);
4156
  CloseHandle(fh);
4157
  CloseHandle(mh);
4158
  return p;
4159
}
4160
#define munmap(x, y)  UnmapViewOfFile(x)
4161
#define MAP_FAILED NULL
4162
#define MAP_PRIVATE 0
4163
#define PROT_READ 0
4164
#else
4165
#include <sys/mman.h>
4166
#endif
4167
4168
static void lsp(struct mg_connection *conn, const char *p, int64_t len,
4169
    lua_State *L) {
4170
  int i, j, pos = 0;
4171
4172
  for (i = 0; i < len; i++) {
4173
    if (p[i] == '<' && p[i + 1] == '?') {
4174
      for (j = i + 1; j < len ; j++) {
4175
  if (p[j] == '?' && p[j + 1] == '>') {
4176
    mg_write(conn, p + pos, i - pos);
4177
    if (luaL_loadbuffer(L, p + (i + 2), j - (i + 2), "") == LUA_OK) {
4178
      lua_pcall(L, 0, LUA_MULTRET, 0);
4179
    }
4180
    pos = j + 2;
4181
    i = pos - 1;
4182
    break;
4183
  }
4184
      }
4185
    }
4186
  }
4187
4188
  if (i > pos) {
4189
    mg_write(conn, p + pos, i - pos);
4190
  }
4191
}
4192
4193
static int lsp_mg_print(lua_State *L) {
4194
  int i, num_args;
4195
  const char *str;
4196
  size_t size;
4197
  struct mg_connection *conn = (struct mg_connection*) /* ntop */lua_touserdata(L, lua_upvalueindex(1));
4198
4199
  num_args = lua_gettop(L);
4200
  for (i = 1; i <= num_args; i++) {
4201
    if (lua_isstring(L, i)) {
4202
      str = lua_tolstring(L, i, &size);
4203
      mg_write(conn, str, size);
4204
    }
4205
  }
4206
4207
  return 0;
4208
}
4209
4210
static int lsp_mg_read(lua_State *L) {
4211
  struct mg_connection *conn = (struct mg_connection*) /* ntop */lua_touserdata(L, lua_upvalueindex(1));
4212
  char buf[1024];
4213
  int len = mg_read(conn, buf, sizeof(buf));
4214
4215
  lua_settop(L, 0);
4216
  lua_pushlstring(L, buf, len);
4217
4218
  return 1;
4219
}
4220
4221
static void reg_string(struct lua_State *L, const char *name, const char *val) {
4222
  lua_pushstring(L, name);
4223
  lua_pushstring(L, val);
4224
  lua_rawset(L, -3);
4225
}
4226
4227
static void reg_int(struct lua_State *L, const char *name, int val) {
4228
  lua_pushstring(L, name);
4229
  lua_pushinteger(L, val);
4230
  lua_rawset(L, -3);
4231
}
4232
4233
static void prepare_lua_environment(struct mg_connection *conn, lua_State *L) {
4234
  const struct mg_request_info *ri = mg_get_request_info(conn);
4235
  extern void luaL_openlibs(lua_State *);
4236
  int i;
4237
4238
  luaL_openlibs(L);
4239
#ifdef MONGOOSE_USE_LUA_SQLITE3
4240
  { extern int luaopen_lsqlite3(lua_State *); luaopen_lsqlite3(L); }
4241
#endif
4242
4243
  // Register "print" function which calls mg_write()
4244
  lua_pushlightuserdata(L, conn);
4245
  lua_pushcclosure(L, lsp_mg_print, 1);
4246
  lua_setglobal(L, "print");
4247
4248
  // Register mg_read()
4249
  lua_pushlightuserdata(L, conn);
4250
  lua_pushcclosure(L, lsp_mg_read, 1);
4251
  lua_setglobal(L, "read");
4252
4253
  // Export request_info
4254
  lua_newtable(L);
4255
  reg_string(L, "request_method", ri->request_method);
4256
  reg_string(L, "uri", ri->uri);
4257
  reg_string(L, "http_version", ri->http_version);
4258
  reg_string(L, "query_string", ri->query_string);
4259
  reg_int(L, "remote_ip", ri->remote_ip);
4260
  reg_int(L, "remote_port", ri->remote_port);
4261
  reg_int(L, "num_headers", ri->num_headers);
4262
  lua_pushstring(L, "http_headers");
4263
  lua_newtable(L);
4264
  for (i = 0; i < ri->num_headers; i++) {
4265
    reg_string(L, ri->http_headers[i].name, ri->http_headers[i].value);
4266
  }
4267
  lua_rawset(L, -3);
4268
  lua_setglobal(L, "request_info");
4269
}
4270
4271
static void handle_lsp_request(struct mg_connection *conn, const char *path,
4272
             struct file *filep) {
4273
  void *p = NULL;
4274
  lua_State *L = NULL;
4275
4276
  if (!mg_stat(conn, path, filep) || !mg_fopen(conn, path, "r", filep)) {
4277
    send_http_error(conn, 404, "Not Found", "%s", "File not found");
4278
  } else if (filep->membuf == NULL &&
4279
       (p = mmap(NULL, (size_t) filep->size, PROT_READ, MAP_PRIVATE,
4280
           fileno(filep->fp), 0)) == MAP_FAILED) {
4281
    send_http_error(conn, 500, http_500_error, "mmap(%s, %zu, %d): %s", path,
4282
        (size_t) filep->size, fileno(filep->fp), strerror(errno));
4283
  } else if ((L = luaL_newstate()) == NULL) {
4284
    send_http_error(conn, 500, http_500_error, "%s", "luaL_newstate failed");
4285
  } else {
4286
    // We're not sending HTTP headers here, Lua page must do it.
4287
    prepare_lua_environment(conn, L);
4288
    if (conn->ctx->callbacks.init_lua != NULL) {
4289
      conn->ctx->callbacks.init_lua(conn, L);
4290
    }
4291
    lsp(conn, (const char*)/* ntop */(filep->membuf == NULL ? p : filep->membuf), filep->size, L);
4292
  }
4293
4294
  if (L) lua_close(L);
4295
  if (p) munmap(p, filep->size);
4296
  mg_fclose(filep);
4297
}
4298
#endif // MONGOOSE_USE_LUA
4299
4300
int mg_upload(struct mg_connection *conn, const char *destination_dir,
4301
0
        char *fname, u_int fname_len) {
4302
0
  const char *content_type_header, *boundary_start;
4303
0
  char buf[MG_BUF_LEN], path[PATH_MAX], boundary[100], *s;
4304
0
  FILE *fp;
4305
0
  int bl, n, i, j, headers_len, boundary_len, len = 0, num_uploaded_files = 0;
4306
4307
0
  fname[0] = '\0';
4308
  // Request looks like this:
4309
  //
4310
  // POST /upload HTTP/1.1
4311
  // Host: 127.0.0.1:8080
4312
  // Content-Length: 244894
4313
  // Content-Type: multipart/form-data; boundary=----WebKitFormBoundaryRVr
4314
  //
4315
  // ------WebKitFormBoundaryRVr
4316
  // Content-Disposition: form-data; name="file"; filename="accum.png"
4317
  // Content-Type: image/png
4318
  //
4319
  //  <89>PNG
4320
  //  <PNG DATA>
4321
  // ------WebKitFormBoundaryRVr
4322
4323
  // Extract boundary string from the Content-Type header
4324
0
  if ((content_type_header = mg_get_header(conn, "Content-Type")) == NULL ||
4325
0
      (boundary_start = strstr(content_type_header, "boundary=")) == NULL ||
4326
0
      (sscanf(boundary_start, "boundary=\"%99[^\"]\"", boundary) == 0 &&
4327
0
       sscanf(boundary_start, "boundary=%99s", boundary) == 0) ||
4328
0
      boundary[0] == '\0') {
4329
0
    return num_uploaded_files;
4330
0
  }
4331
4332
0
  boundary_len = strlen(boundary);
4333
0
  bl = boundary_len + 4;  // \r\n--<boundary>
4334
0
  for (;;) {
4335
    // Pull in headers
4336
0
    assert(len >= 0 && len <= (int) sizeof(buf));
4337
0
    while ((n = mg_read(conn, buf + len, sizeof(buf) - len)) > 0) {
4338
0
      len += n;
4339
0
    }
4340
0
    if ((headers_len = get_request_len(buf, len)) <= 0) {
4341
0
      break;
4342
0
    }
4343
4344
    // Fetch file name.
4345
0
    fname[0] = '\0';
4346
0
    for (i = j = 0; i < headers_len; i++) {
4347
0
      if (buf[i] == '\r' && buf[i + 1] == '\n') {
4348
0
  buf[i] = buf[i + 1] = '\0';
4349
  // TODO(lsm): don't expect filename to be the 3rd field,
4350
  // parse the header properly instead.
4351
0
  sscanf(&buf[j], "Content-Disposition: %*s %*s filename=\"%1023[^\"]",
4352
0
         fname);
4353
0
  j = i + 2;
4354
0
      }
4355
0
    }
4356
4357
    // Give up if the headers are not what we expect
4358
0
    if (fname[0] == '\0') {
4359
0
      break;
4360
0
    }
4361
4362
    // Move data to the beginning of the buffer
4363
0
    assert(len >= headers_len);
4364
0
    memmove(buf, &buf[headers_len], len - headers_len);
4365
0
    len -= headers_len;
4366
4367
    // We open the file with exclusive lock held. This guarantee us
4368
    // there is no other thread can save into the same file simultaneously.
4369
0
    fp = NULL;
4370
    // Construct destination file name. Do not allow paths to have slashes.
4371
0
    if ((s = strrchr(fname, '/')) == NULL) {
4372
0
      s = fname;
4373
0
    }
4374
    // Open file in binary mode. TODO: set an exclusive lock.
4375
0
    snprintf(path, sizeof(path)-1, "%s/%s", destination_dir, s);
4376
    
4377
0
    if ((fp = fopen(path, "wb")) == NULL) {
4378
0
      break;
4379
0
    }
4380
4381
    // Read POST data, write into file until boundary is found.
4382
0
    n = 0;
4383
0
    do {
4384
0
      len += n;
4385
0
      for (i = 0; i < len - bl; i++) {
4386
0
  if (!memcmp(&buf[i], "\r\n--", 4) &&
4387
0
      !memcmp(&buf[i + 4], boundary, boundary_len)) {
4388
    // Found boundary, that's the end of file data.
4389
0
    fwrite(buf, 1, i, fp);
4390
0
    fflush(fp);
4391
0
    num_uploaded_files++;
4392
0
    if (conn->ctx->callbacks.upload != NULL) {
4393
0
      conn->ctx->callbacks.upload(conn, path);
4394
0
    }
4395
0
    memmove(buf, &buf[i + bl], len - (i + bl));
4396
0
    len -= i + bl;
4397
0
    break;
4398
0
  }
4399
0
      }
4400
0
      if (len > bl) {
4401
0
  fwrite(buf, 1, len - bl, fp);
4402
0
  memmove(buf, &buf[len - bl], bl);
4403
0
  len = bl;
4404
0
      }
4405
0
    } while ((n = mg_read(conn, buf + len, sizeof(buf) - len)) > 0);
4406
0
    fclose(fp);
4407
0
  }
4408
4409
0
  return num_uploaded_files;
4410
0
}
4411
4412
0
static int is_put_or_delete_request(const struct mg_connection *conn) {
4413
0
  const char *s = conn->request_info.request_method;
4414
0
  return s != NULL && (!strcmp(s, "PUT") || !strcmp(s, "DELETE"));
4415
0
}
4416
4417
0
static int get_first_ssl_listener_index(const struct mg_context *ctx) {
4418
0
  int i, index = -1;
4419
0
  for (i = 0; index == -1 && i < ctx->num_listening_sockets; i++) {
4420
0
    index = ctx->listening_sockets[i].is_ssl ? i : -1;
4421
0
  }
4422
0
  return index;
4423
0
}
4424
4425
0
static void redirect_to_https_port(struct mg_connection *conn, int ssl_index) {
4426
0
  char host[1025];
4427
0
  const char *host_header;
4428
4429
0
  if ((host_header = mg_get_header(conn, "Host")) == NULL ||
4430
0
      sscanf(host_header, "%1024[^:]", host) == 0) {
4431
    // Cannot get host from the Host: header. Fallback to our IP address.
4432
0
    sockaddr_to_string(host, sizeof(host), &conn->client.lsa);
4433
0
  }
4434
4435
0
  mg_printf(conn, "HTTP/1.1 302 Found\r\nLocation: https://%s:%d%s\r\n\r\n",
4436
0
      host, (int) ntohs(conn->ctx->listening_sockets[ssl_index].
4437
0
            lsa.sin.sin_port), conn->request_info.uri);
4438
0
}
4439
4440
// This is the heart of the Mongoose's logic.
4441
// This function is called when the request is read, parsed and validated,
4442
// and Mongoose must decide what action to take: serve a file, or
4443
// a directory, or call embedded function, etcetera.
4444
0
static void handle_request(struct mg_connection *conn) {
4445
0
  struct mg_request_info *ri = &conn->request_info;
4446
0
  char path[PATH_MAX];
4447
0
  int uri_len, ssl_index;
4448
0
  struct file file = STRUCT_FILE_INITIALIZER;
4449
0
  u_int8_t ntop_serving_lua_source = 0; /* NTOP */
4450
  
4451
0
  if ((conn->request_info.query_string = strchr(ri->uri, '?')) != NULL) {
4452
0
    * ((char *) conn->request_info.query_string++) = '\0';
4453
0
  }
4454
  
4455
0
  uri_len = (int) strlen(ri->uri);
4456
0
  url_decode(ri->uri, uri_len, (char *) ri->uri, uri_len + 1, 0);
4457
0
  remove_double_dots_and_double_slashes((char *) ri->uri);
4458
4459
  /* BEGIN NTOP */
4460
0
  if((strncmp(conn->request_info.uri, "/plugins-src", 12) == 0)  /* Serve lua files */
4461
0
     && (!strstr(conn->request_info.uri, "/pro/"))
4462
0
     && (!strstr(conn->request_info.uri, "/enterprise/")) /* Skip non-community edition files */
4463
0
     )
4464
0
    ntop_serving_lua_source = 1;
4465
  /* END NTOP */
4466
  
4467
0
  convert_uri_to_file_name(conn, path, sizeof(path), &file);
4468
0
  conn->throttle = set_throttle(conn->ctx->config[THROTTLE],
4469
0
        get_remote_ip(conn), ri->uri);
4470
4471
0
  DEBUG_TRACE(("%s", ri->uri));
4472
0
  if (conn->ctx->callbacks.begin_request != NULL &&
4473
0
      conn->ctx->callbacks.begin_request(conn)) {
4474
    // Do nothing, callback has served the request
4475
0
  } else {
4476
    /* BEGIN NTOP */
4477
0
    if(ntop_serving_lua_source) {
4478
0
      char *httpdocs;
4479
4480
      // ntop->getTrace()->traceEvent(TRACE_WARNING, "From %s", path);
4481
      
4482
0
      httpdocs = strstr(path, "/httpdocs/plugins-src/");
4483
4484
0
      if(httpdocs) {
4485
0
  char buf[256];      
4486
0
  u_int len;
4487
4488
0
  snprintf(buf, sizeof(buf), "/scripts/plugins%s", &httpdocs[21]);
4489
0
  len = strlen(buf);
4490
  
4491
0
  memmove(httpdocs, buf, len+1);
4492
0
      }
4493
4494
      // ntop->getTrace()->traceEvent(TRACE_WARNING, "Renamed to %s", path);
4495
0
      mg_stat(conn, path, &file);
4496
      // ntop->getTrace()->traceEvent(TRACE_WARNING, "New path %s", path);
4497
0
    }
4498
    /* END NTOP */
4499
    
4500
0
  if (!conn->client.is_ssl && conn->client.ssl_redir &&
4501
0
    (ssl_index = get_first_ssl_listener_index(conn->ctx)) > -1) {
4502
0
   redirect_to_https_port(conn, ssl_index);
4503
0
 } else if (!is_put_or_delete_request(conn) &&
4504
0
      !check_authorization(conn, path)) {
4505
0
   send_authorization_request(conn);
4506
#if defined(USE_WEBSOCKET)
4507
 } else if (is_websocket_request(conn)) {
4508
   handle_websocket_request(conn);
4509
#endif
4510
0
 } else if (!strcmp(ri->request_method, "OPTIONS")) {
4511
0
   send_options(conn);
4512
0
 } else if (conn->ctx->config[DOCUMENT_ROOT] == NULL) {
4513
0
   send_http_error(conn, 404, "Not Found", "Not Found");
4514
0
 } else if (is_put_or_delete_request(conn) &&
4515
0
      (conn->ctx->config[PUT_DELETE_PASSWORDS_FILE] == NULL ||
4516
0
       is_authorized_for_put(conn) != 1)) {
4517
0
   send_authorization_request(conn);
4518
0
 } else if (!strcmp(ri->request_method, "PUT")) {
4519
0
   put_file(conn, path);
4520
0
 } else if (!strcmp(ri->request_method, "DELETE")) {
4521
0
   if (mg_remove(path) == 0) {
4522
0
     send_http_error(conn, 200, "OK", "%s", "");
4523
0
   } else {
4524
0
     send_http_error(conn, 500, http_500_error, "remove(%s): %s", path,
4525
0
         strerror(ERRNO));
4526
0
   }
4527
0
 } else if ((file.membuf == NULL && file.modification_time == (time_t) 0) ||
4528
0
      must_hide_file(conn, path)) {
4529
0
   send_http_error(conn, 404, "Not Found", "%s", "File not found");
4530
0
 } else if (file.is_directory && ri->uri[uri_len - 1] != '/') {
4531
0
   mg_printf(conn, "HTTP/1.1 301 Moved Permanently\r\n"
4532
0
       "Location: %s/\r\n\r\n", ri->uri);
4533
0
 } else if (!strcmp(ri->request_method, "PROPFIND")) {
4534
0
   handle_propfind(conn, path, &file);
4535
0
 } else if (file.is_directory &&
4536
0
      !substitute_index_file(conn, path, sizeof(path), &file)) {
4537
0
   if (!mg_strcasecmp(conn->ctx->config[ENABLE_DIRECTORY_LISTING], "yes")) {
4538
0
     handle_directory_request(conn, path);
4539
0
   } else {
4540
0
     send_http_error(conn, 403, "Directory Listing Denied",
4541
0
         "Directory listing denied");
4542
0
   }
4543
#ifdef MONGOOSE_USE_LUA
4544
 } else if (match_prefix("**.lp$", 6, path) > 0) {
4545
   handle_lsp_request(conn, path, &file);
4546
#endif
4547
#if !defined(NO_CGI)
4548
 } else if (match_prefix(conn->ctx->config[CGI_EXTENSIONS],
4549
       strlen(conn->ctx->config[CGI_EXTENSIONS]),
4550
       path) > 0) {
4551
   if (strcmp(ri->request_method, "POST") &&
4552
       strcmp(ri->request_method, "HEAD") &&
4553
       strcmp(ri->request_method, "GET")) {
4554
     send_http_error(conn, 501, "Not Implemented",
4555
         "Method %s is not implemented", ri->request_method);
4556
   } else {
4557
     handle_cgi_request(conn, path);
4558
   }
4559
#endif // !NO_CGI
4560
0
 } else if (match_prefix(conn->ctx->config[SSI_EXTENSIONS],
4561
0
       strlen(conn->ctx->config[SSI_EXTENSIONS]),
4562
0
       path) > 0) {
4563
0
   handle_ssi_file_request(conn, path);
4564
0
 } else if (is_not_modified(conn, &file)) {
4565
0
   send_http_error(conn, 304, "Not Modified", "%s", "");
4566
0
 } else {
4567
0
   handle_file_request(conn, path, &file);
4568
0
 }
4569
0
  }
4570
0
}
4571
4572
0
static void close_all_listening_sockets(struct mg_context *ctx) {
4573
0
  int i;
4574
0
  for (i = 0; i < ctx->num_listening_sockets; i++) {
4575
0
    closesocket(ctx->listening_sockets[i].sock);
4576
0
  }
4577
0
  free(ctx->listening_sockets);
4578
0
}
4579
4580
// Valid listening port specification is: [ip_address:]port[s]
4581
// Examples: 80, 443s, 127.0.0.1:3128, 1.2.3.4:8080s
4582
// TODO(lsm): add parsing of the IPv6 address
4583
0
static int parse_port_string(const struct vec *vec, struct socket *so) {
4584
0
  union usa *sa = (union usa *)&so->lsa;
4585
0
  int a, b, c, d, port = 0, len = 0;
4586
0
#if defined(USE_IPV6)
4587
0
  char buf[100];
4588
0
#endif
4589
  // MacOS needs that. If we do not zero it, subsequent bind() will fail.
4590
  // Also, all-zeroes in the socket address means binding to all addresses
4591
  // for both IPv4 and IPv6 (INADDR_ANY and IN6ADDR_ANY_INIT).
4592
0
  memset(sa, 0, sizeof(*sa));
4593
4594
0
  sa->sin.sin_family = AF_INET;
4595
4596
0
  if (sscanf(vec->ptr, "%u.%u.%u.%u:%u%n", &a, &b, &c, &d, &port, &len) == 5) {
4597
    /* Bind to a specific IPv4 address, e.g. 127.0.0.1:8080 */
4598
0
    sa->sin.sin_addr.s_addr =
4599
0
      htonl(((uint32_t) a << 24) | ((uint32_t) b << 16) | c << 8 | d);
4600
0
    sa->sin.sin_port = htons((uint16_t) port);
4601
4602
0
#if defined(USE_IPV6)
4603
0
  } else if (sscanf(vec->ptr, "[%[^]]]:%u%n", buf, &port, &len) == 2 &&
4604
0
       inet_pton(AF_INET6, buf, &sa->sin6.sin6_addr)) {
4605
    /* IPv6 address, e.g. [3ffe:2a00:100:7031::1]:8080 */
4606
0
    sa->sin6.sin6_family = AF_INET6;
4607
0
    sa->sin.sin_port = htons((uint16_t) port);
4608
0
#endif
4609
4610
0
  } else if (sscanf(vec->ptr, ":%u%n", &port, &len) == 1 ||
4611
0
       sscanf(vec->ptr, "%u%n", &port, &len) == 1) {
4612
    /* If only port is specified, bind to IPv4, INADDR_ANY */
4613
0
    sa->sin.sin_port = htons((uint16_t) port);
4614
0
  } else {
4615
0
    return -1;
4616
0
  }
4617
4618
0
  so->is_ssl = (vec->ptr[len] && vec->ptr[len] == 's');
4619
0
  so->ssl_redir = (vec->ptr[len] && vec->ptr[len] == 'r');
4620
4621
#if defined(__FreeBSD__) || defined(__NetBSD__) || defined(__OpenBSD__)
4622
  so->lsa.sin.sin_len = sizeof(struct sockaddr_in);
4623
#endif
4624
4625
0
  return 1;
4626
0
}
4627
4628
0
static int set_ports_option(struct mg_context *ctx) {
4629
0
  const char *list = ctx->config[LISTENING_PORTS];
4630
0
  int on = 1, success = 1;
4631
0
  struct vec vec;
4632
0
  struct socket so;
4633
0
  int rc_setsockopt = 0, rc_bind = 0, rc_listen = 0;
4634
0
  union usa *sa = (union usa *)&so.lsa;
4635
4636
  /*
4637
    #if defined(USE_IPV6)
4638
    if(is_ip6_enabled)
4639
    sa = (const struct sockaddr *)&so.lsa.sin6, sa_len = sizeof(so.lsa.sin6);
4640
    #endif
4641
  */
4642
4643
0
  while (success && (list = next_option(list, &vec, NULL)) != NULL) {
4644
0
    if (!parse_port_string(&vec, &so)) {
4645
0
      cry(fc(ctx), "%s: %.*s: invalid port spec. Expecting list of: %s",
4646
0
    __func__, (int) vec.len, vec.ptr, "[IP_ADDRESS:]PORT[s|p]");
4647
0
      success = 0;
4648
0
    } else if (so.is_ssl && ctx->ssl_ctx == NULL) {
4649
0
      cry(fc(ctx), "Cannot add SSL socket, is -ssl_certificate option set?");
4650
0
      success = 0;
4651
0
    } else if ((so.sock = socket(so.lsa.sa.sa_family, SOCK_STREAM, IPPROTO_TCP)) ==
4652
0
         INVALID_SOCKET ||
4653
         // On Windows, SO_REUSEADDR is recommended only for
4654
         // broadcast UDP sockets
4655
0
         (rc_setsockopt = setsockopt(so.sock, SOL_SOCKET, SO_REUSEADDR,
4656
#ifdef WIN32
4657
             (const char*)
4658
#else
4659
0
             (void *)
4660
0
#endif
4661
0
             &on, sizeof(on))) != 0 ||
4662
0
         (rc_bind = ::bind(so.sock,
4663
0
             &sa->sa,
4664
0
             (sa->sa.sa_family == AF_INET) ? sizeof(sa->sin) : sizeof(sa->sin6))
4665
0
    ) != 0 ||
4666
         /*
4667
#if defined _UTILS_H_ && defined _NTOP_CLASS_H_
4668
         (ntop->getPrefs()->do_change_user() && Utils::dropPrivileges())      ||
4669
#endif
4670
         */
4671
0
         (rc_listen = listen(so.sock, SOMAXCONN)) != 0) {
4672
0
      cry(fc(ctx), "%s: cannot bind to %.*s: %s", __func__,
4673
0
    (int) vec.len, vec.ptr, strerror(ERRNO));
4674
0
#if defined _NTOP_CLASS_H_
4675
0
      ntop->getTrace()->traceEvent(TRACE_ERROR, "%s: cannot bind to %.*s: %s", __func__,
4676
0
           (int) vec.len, vec.ptr, strerror(ERRNO));
4677
0
#endif
4678
0
      closesocket(so.sock);
4679
0
      success = 0;
4680
0
    } else {
4681
0
      set_close_on_exec(so.sock);
4682
      // TODO: handle realloc failure
4683
0
      ctx->listening_sockets = (struct socket*)realloc(ctx->listening_sockets,
4684
0
                   (ctx->num_listening_sockets + 1) *
4685
0
                   sizeof(ctx->listening_sockets[0]));
4686
0
      ctx->listening_sockets[ctx->num_listening_sockets] = so;
4687
0
      ctx->num_listening_sockets++;
4688
0
    }
4689
0
  }
4690
4691
0
  if (!success) {
4692
0
    close_all_listening_sockets(ctx);
4693
0
  }
4694
4695
0
  return success;
4696
0
}
4697
4698
static void log_header(const struct mg_connection *conn, const char *header,
4699
0
           FILE *fp) {
4700
0
  const char *header_value;
4701
4702
0
  if ((header_value = mg_get_header(conn, header)) == NULL) {
4703
0
    (void) fprintf(fp, "%s", " -");
4704
0
  } else {
4705
0
    (void) fprintf(fp, " \"%s\"", header_value);
4706
0
  }
4707
0
}
4708
4709
0
static void log_access(const struct mg_connection *conn) {
4710
0
  const struct mg_request_info *ri;
4711
0
  FILE *fp;
4712
0
  char date[64], src_addr[20];
4713
4714
0
  fp = conn->ctx->config[ACCESS_LOG_FILE] == NULL ?  NULL :
4715
0
    fopen(conn->ctx->config[ACCESS_LOG_FILE], "a+");
4716
4717
0
  if (fp == NULL)
4718
0
    return;
4719
4720
0
  strftime(date, sizeof(date), "%d/%b/%Y:%H:%M:%S %z",
4721
0
     localtime(&conn->birth_time));
4722
4723
0
  ri = &conn->request_info;
4724
0
  flockfile(fp);
4725
4726
0
  sockaddr_to_string(src_addr, sizeof(src_addr), &conn->client.rsa);
4727
0
  fprintf(fp, "%s - %s [%s] \"%s %s HTTP/%s\" %d %" INT64_FMT,
4728
0
    src_addr, ri->remote_user == NULL ? "-" : ri->remote_user, date,
4729
0
    ri->request_method ? ri->request_method : "-",
4730
0
    ri->uri ? ri->uri : "-", ri->http_version,
4731
0
    conn->status_code, conn->num_bytes_sent);
4732
0
  log_header(conn, "Referer", fp);
4733
0
  log_header(conn, "User-Agent", fp);
4734
0
  fputc('\n', fp);
4735
0
  fflush(fp);
4736
4737
0
  funlockfile(fp);
4738
0
  fclose(fp);
4739
0
}
4740
4741
// Verify given socket address against the ACL.
4742
// Return -1 if ACL is malformed, 0 if address is disallowed, 1 if allowed.
4743
0
static int check_acl(struct mg_context *ctx, uint32_t remote_ip) {
4744
0
  int allowed, flag;
4745
0
  uint32_t net, mask;
4746
0
  struct vec vec;
4747
0
  const char *list = ctx->config[ACCESS_CONTROL_LIST];
4748
4749
  // If any ACL is set, deny by default
4750
0
  allowed = list == NULL ? '+' : '-';
4751
4752
0
  while ((list = next_option(list, &vec, NULL)) != NULL) {
4753
0
    flag = vec.ptr[0];
4754
0
    if ((flag != '+' && flag != '-') ||
4755
0
  parse_net(&vec.ptr[1], &net, &mask) == 0) {
4756
0
      cry(fc(ctx), "%s: subnet must be [+|-]x.x.x.x[/x]", __func__);
4757
0
      return -1;
4758
0
    }
4759
4760
0
    if (net == (remote_ip & mask)) {
4761
0
      allowed = flag;
4762
0
    }
4763
0
  }
4764
4765
0
  return allowed == '+';
4766
0
}
4767
4768
#if !defined(_WIN32)
4769
0
static int set_uid_option(struct mg_context *ctx) {
4770
0
  struct passwd *pw;
4771
0
  const char *uid = ctx->config[RUN_AS_USER];
4772
0
  int success = 0;
4773
4774
0
  if (uid == NULL) {
4775
0
    success = 1;
4776
0
  } else {
4777
0
    if ((pw = getpwnam(uid)) == NULL) {
4778
0
      cry(fc(ctx), "%s: unknown user [%s]", __func__, uid);
4779
0
    } else if (setgid(pw->pw_gid) == -1) {
4780
0
      cry(fc(ctx), "%s: setgid(%s): %s", __func__, uid, strerror(errno));
4781
0
    } else if (setuid(pw->pw_uid) == -1) {
4782
0
      cry(fc(ctx), "%s: setuid(%s): %s", __func__, uid, strerror(errno));
4783
0
    } else {
4784
0
      success = 1;
4785
0
    }
4786
0
  }
4787
4788
0
  return success;
4789
0
}
4790
#endif // !_WIN32
4791
4792
#if !defined(NO_SSL)
4793
static pthread_mutex_t *ssl_mutexes;
4794
4795
0
static int sslize(struct mg_connection *conn, SSL_CTX *s, int (*func)(SSL *)) {
4796
0
  return (conn->ssl = SSL_new(s)) != NULL &&
4797
0
    SSL_set_fd(conn->ssl, conn->client.sock) == 1 &&
4798
0
    func(conn->ssl) == 1;
4799
0
}
4800
4801
// Return OpenSSL error message
4802
0
static const char *ssl_error(void) {
4803
0
  unsigned long err;
4804
0
  err = ERR_get_error();
4805
0
  return err == 0 ? "" : ERR_error_string(err, NULL);
4806
0
}
4807
4808
#if !defined(NO_SSL_DL)
4809
static int load_dll(struct mg_context *ctx, const char *dll_name,
4810
        struct ssl_func *sw) {
4811
  union {void *p; void (*fp)(void);} u;
4812
  void  *dll_handle;
4813
  struct ssl_func *fp;
4814
4815
  if ((dll_handle = dlopen(dll_name, RTLD_LAZY)) == NULL) {
4816
    cry(fc(ctx), "%s: cannot load %s", __func__, dll_name);
4817
#if defined _NTOP_CLASS_H_
4818
    ntop->getTrace()->traceEvent(TRACE_ERROR, "%s: cannot load %s", __func__, dll_name);
4819
#endif
4820
    return 0;
4821
  }
4822
4823
  for (fp = sw; fp->name != NULL; fp++) {
4824
#ifdef _WIN32
4825
    // GetProcAddress() returns pointer to function
4826
    u.fp = (void (*)(void)) dlsym(dll_handle, fp->name);
4827
#else
4828
    // dlsym() on UNIX returns void *. ISO C forbids casts of data pointers to
4829
    // function pointers. We need to use a union to make a cast.
4830
    u.p = dlsym(dll_handle, fp->name);
4831
#endif // _WIN32
4832
    if (u.fp == NULL) {
4833
      cry(fc(ctx), "%s: %s: cannot find %s", __func__, dll_name, fp->name);
4834
#if defined _NTOP_CLASS_H_
4835
      ntop->getTrace()->traceEvent(TRACE_ERROR,  "%s: %s: cannot find %s", __func__, dll_name, fp->name);
4836
#endif
4837
      return 0;
4838
    } else {
4839
      fp->ptr = u.fp;
4840
    }
4841
  }
4842
4843
  return 1;
4844
}
4845
#endif // NO_SSL_DL
4846
4847
#if !defined(NO_SSL)
4848
4849
0
static unsigned long ssl_id_callback(void) {
4850
0
  return (unsigned long) pthread_self();
4851
0
}
4852
4853
static void ssl_locking_callback(int mode, int mutex_num, const char *file,
4854
0
         int line) {
4855
0
  (void) line;
4856
0
  (void) file;
4857
0
4858
0
  if (mode & 1) {  // 1 is CRYPTO_LOCK
4859
0
    (void) pthread_mutex_lock(&ssl_mutexes[mutex_num]);
4860
0
  } else {
4861
0
    (void) pthread_mutex_unlock(&ssl_mutexes[mutex_num]);
4862
0
  }
4863
0
}
4864
4865
// Dynamically load SSL library. Set up ctx->ssl_ctx pointer.
4866
0
static int set_ssl_option(struct mg_context *ctx) {
4867
0
  int i, size;
4868
0
  const char *pem, *ciphers;
4869
4870
  // If PEM file is not specified, skip SSL initialization.
4871
0
  if ((pem = ctx->config[SSL_CERTIFICATE]) == NULL) {
4872
0
    return 1;
4873
0
  }
4874
4875
#if !defined(NO_SSL_DL)
4876
  if (!load_dll(ctx, SSL_LIB, ssl_sw) ||
4877
      !load_dll(ctx, CRYPTO_LIB, crypto_sw)) {
4878
    return 0;
4879
  }
4880
#endif // NO_SSL_DL
4881
4882
  // Initialize SSL library
4883
0
  SSL_library_init();
4884
0
  SSL_load_error_strings();
4885
4886
0
  if ((ctx->ssl_ctx = SSL_CTX_new(SSLv23_server_method())) == NULL) {
4887
0
    cry(fc(ctx), "SSL_CTX_new (server) error: %s", ssl_error());
4888
0
    return 0;
4889
0
  }
4890
4891
  /* ntop */
4892
0
  ciphers = (const char*)ntop->getPrefs()->getCiphersList();
4893
0
  if(ciphers == NULL) ciphers = CONST_DEFAULT_TLS_CIPHERS;
4894
4895
0
  ntop->getTrace()->traceEvent(TRACE_NORMAL, "Using TLS ciphers %s", ciphers);
4896
  
4897
0
  SSL_CTX_set_cipher_list(ctx->ssl_ctx, ciphers);
4898
4899
0
#ifndef __APPLE__ /* Brew comes with an old OpenSSL version */
4900
#ifdef MODERN_OPENSSL
4901
#ifndef TLS1_2_VERSION
4902
#define TLS1_2_VERSION          0x0303
4903
#endif
4904
  SSL_CTX_set_min_proto_version(ctx->ssl_ctx, TLS1_2_VERSION);
4905
#else
4906
0
  {
4907
#ifndef SSL_OP_NO_TLSv1
4908
#define SSL_OP_NO_TLSv1 0x04000000L
4909
#endif
4910
#ifndef SSL_OP_NO_TLSv1_1
4911
#define SSL_OP_NO_TLSv1_1 0x10000000L
4912
#endif
4913
#ifndef SSL_OP_NO_SSLv2
4914
#define SSL_OP_NO_SSLv2 0x01000000L
4915
#endif
4916
#ifndef SSL_OP_NO_SSLv3
4917
#define SSL_OP_NO_SSLv3 0x02000000L
4918
#endif
4919
 
4920
0
    long opts = SSL_CTX_get_options(ctx->ssl_ctx);
4921
    
4922
0
    opts |= SSL_OP_NO_TLSv1;
4923
0
    opts |= SSL_OP_NO_TLSv1_1;
4924
0
    opts |= SSL_OP_NO_SSLv2;
4925
0
    opts |= SSL_OP_NO_SSLv3;
4926
0
    SSL_CTX_set_options(ctx->ssl_ctx, opts);
4927
0
  }
4928
0
#endif
4929
0
#endif
4930
  /* end ntop */
4931
4932
  // If user callback returned non-NULL, that means that user callback has
4933
  // set up certificate itself. In this case, skip sertificate setting.
4934
0
  if ((ctx->callbacks.init_ssl == NULL ||
4935
0
       !ctx->callbacks.init_ssl(ctx->ssl_ctx)) &&
4936
0
      (SSL_CTX_use_certificate_file(ctx->ssl_ctx, pem, 1) == 0 ||
4937
0
       SSL_CTX_use_PrivateKey_file(ctx->ssl_ctx, pem, 1) == 0)) {
4938
0
    cry(fc(ctx), "%s: cannot open %s: %s", __func__, pem, ssl_error());
4939
0
    return 0;
4940
0
  }
4941
4942
0
  if (pem != NULL) {
4943
0
    (void) SSL_CTX_use_certificate_chain_file(ctx->ssl_ctx, pem);
4944
0
  }
4945
4946
  // Initialize locking callbacks, needed for thread safety.
4947
  // http://www.openssl.org/support/faq.html#PROG1
4948
0
  size = sizeof(pthread_mutex_t) * CRYPTO_num_locks();
4949
0
  if ((ssl_mutexes = (pthread_mutex_t *) malloc((size_t)size)) == NULL) {
4950
0
    cry(fc(ctx), "%s: cannot allocate mutexes: %s", __func__, ssl_error());
4951
0
    return 0;
4952
0
  }
4953
4954
0
  for (i = 0; i < CRYPTO_num_locks(); i++) {
4955
0
    pthread_mutex_init(&ssl_mutexes[i], NULL);
4956
0
  }
4957
4958
0
  CRYPTO_set_locking_callback(&ssl_locking_callback);
4959
0
  CRYPTO_set_id_callback(&ssl_id_callback);
4960
4961
0
  return 1;
4962
0
}
4963
#endif
4964
4965
0
static void uninitialize_ssl(struct mg_context *ctx) {
4966
0
  int i;
4967
0
  if (ctx->ssl_ctx != NULL) {
4968
0
    CRYPTO_set_locking_callback(NULL);
4969
0
    for (i = 0; i < CRYPTO_num_locks(); i++) {
4970
0
      pthread_mutex_destroy(&ssl_mutexes[i]);
4971
0
    }
4972
0
    CRYPTO_set_locking_callback(NULL);
4973
0
    CRYPTO_set_id_callback(NULL);
4974
0
  }
4975
0
}
4976
#endif // !NO_SSL
4977
4978
0
static int set_gpass_option(struct mg_context *ctx) {
4979
0
  struct file file = STRUCT_FILE_INITIALIZER;
4980
0
  const char *path = ctx->config[GLOBAL_PASSWORDS_FILE];
4981
0
  if (path != NULL && !mg_stat(fc(ctx), path, &file)) {
4982
0
    cry(fc(ctx), "Cannot open %s: %s", path, strerror(ERRNO));
4983
0
    return 0;
4984
0
  }
4985
0
  return 1;
4986
0
}
4987
4988
0
static int set_acl_option(struct mg_context *ctx) {
4989
0
  return check_acl(ctx, (uint32_t) 0x7f000001UL) != -1;
4990
0
}
4991
4992
0
static void reset_per_request_attributes(struct mg_connection *conn) {
4993
0
  conn->path_info = NULL;
4994
0
  conn->num_bytes_sent = conn->consumed_content = 0;
4995
0
  conn->status_code = -1;
4996
0
  conn->must_close = conn->request_len = conn->throttle = 0;
4997
0
}
4998
4999
0
static void close_socket_gracefully(struct mg_connection *conn) {
5000
#if defined(_WIN32)
5001
  char buf[MG_BUF_LEN];
5002
  int n;
5003
#endif
5004
0
  struct linger linger;
5005
5006
  // Set linger option to avoid socket hanging out after close. This prevent
5007
  // ephemeral port exhaust problem under high QPS.
5008
0
  linger.l_onoff = 1;
5009
0
  linger.l_linger = 1;
5010
0
  setsockopt(conn->client.sock, SOL_SOCKET, SO_LINGER,
5011
0
       (char *) &linger, sizeof(linger));
5012
5013
  // Send FIN to the client
5014
0
  shutdown(conn->client.sock, SHUT_WR);
5015
0
  set_non_blocking_mode(conn->client.sock);
5016
5017
#if defined(_WIN32)
5018
  // Read and discard pending incoming data. If we do not do that and close the
5019
  // socket, the data in the send buffer may be discarded. This
5020
  // behaviour is seen on Windows, when client keeps sending data
5021
  // when server decides to close the connection; then when client
5022
  // does recv() it gets no data back.
5023
  do {
5024
    n = pull(NULL, conn, buf, sizeof(buf));
5025
  } while (n > 0);
5026
#endif
5027
5028
  // Now we know that our FIN is ACK-ed, safe to close
5029
0
  closesocket(conn->client.sock);
5030
0
}
5031
5032
0
static void close_connection(struct mg_connection *conn) {
5033
0
  conn->must_close = 1;
5034
0
  if (conn->client.sock != INVALID_SOCKET) {
5035
0
    close_socket_gracefully(conn);
5036
0
  }
5037
0
#ifndef NO_SSL
5038
  // Must be done AFTER socket is closed
5039
0
  if (conn->ssl != NULL) {
5040
0
    SSL_free(conn->ssl);
5041
0
    conn->ssl = NULL; /* ntop */
5042
0
  }
5043
0
#endif
5044
0
}
5045
5046
0
void mg_close_connection(struct mg_connection *conn) {
5047
0
#ifndef NO_SSL
5048
0
  if (conn->client_ssl_ctx != NULL) {
5049
0
    SSL_CTX_free((SSL_CTX *) conn->client_ssl_ctx);
5050
0
  }
5051
0
#endif
5052
0
  close_connection(conn);
5053
0
  free(conn);
5054
0
}
5055
5056
struct mg_connection *mg_connect(const char *host, int port, int use_ssl,
5057
0
         char *ebuf, size_t ebuf_len) {
5058
0
  static struct mg_context fake_ctx;
5059
0
  struct mg_connection *conn = NULL;
5060
0
  struct sockaddr_in sin;
5061
0
  struct hostent *he;
5062
0
  int sock;
5063
5064
0
  if (host == NULL) {
5065
0
    snprintf(ebuf, ebuf_len, "%s", "NULL host");
5066
#if 0
5067
  } else if (use_ssl && SSLv23_client_method == NULL) {
5068
    snprintf(ebuf, ebuf_len, "%s", "SSL is not initialized");
5069
#endif
5070
0
  } else if ((he = gethostbyname(host)) == NULL) {
5071
0
    snprintf(ebuf, ebuf_len, "gethostbyname(%s): %s", host, strerror(ERRNO));
5072
0
  } else if ((sock = socket(PF_INET, SOCK_STREAM, 0)) == INVALID_SOCKET) {
5073
0
    snprintf(ebuf, ebuf_len, "socket(): %s", strerror(ERRNO));
5074
0
  } else {
5075
0
    sin.sin_family = AF_INET;
5076
0
    sin.sin_port = htons((uint16_t) port);
5077
0
    sin.sin_addr = * (struct in_addr *) he->h_addr_list[0];
5078
0
    if (connect(sock, (struct sockaddr *) &sin, sizeof(sin)) != 0) {
5079
0
      snprintf(ebuf, ebuf_len, "connect(%s:%d): %s",
5080
0
         host, port, strerror(ERRNO));
5081
0
      closesocket(sock);
5082
0
    } else if ((conn = (struct mg_connection *)
5083
0
    calloc(1, sizeof(*conn) + MAX_REQUEST_SIZE)) == NULL) {
5084
0
      snprintf(ebuf, ebuf_len, "calloc(): %s", strerror(ERRNO));
5085
0
      closesocket(sock);
5086
0
#ifndef NO_SSL
5087
0
    } else if (use_ssl && (conn->client_ssl_ctx =
5088
0
         SSL_CTX_new(SSLv23_client_method())) == NULL) {
5089
0
      snprintf(ebuf, ebuf_len, "SSL_CTX_new error");
5090
0
      closesocket(sock);
5091
0
      free(conn);
5092
0
      conn = NULL;
5093
0
#endif // NO_SSL
5094
0
    } else {
5095
0
      conn->buf_size = MAX_REQUEST_SIZE;
5096
0
      conn->buf = (char *) (conn + 1);
5097
0
      conn->ctx = &fake_ctx;
5098
0
      conn->client.sock = sock;
5099
0
      conn->client.rsa.sin = sin;
5100
0
      conn->client.is_ssl = use_ssl;
5101
0
#ifndef NO_SSL
5102
0
      if (use_ssl) {
5103
  // SSL_CTX_set_verify call is needed to switch off server certificate
5104
  // checking, which is off by default in OpenSSL and on in yaSSL.
5105
0
  SSL_CTX_set_verify(conn->client_ssl_ctx, 0, 0);
5106
0
  sslize(conn, conn->client_ssl_ctx, SSL_connect);
5107
0
      }
5108
0
#endif
5109
0
    }
5110
0
  }
5111
5112
0
  return conn;
5113
0
}
5114
5115
0
static int is_valid_uri(const char *uri) {
5116
  // Conform to http://www.w3.org/Protocols/rfc2616/rfc2616-sec5.html#sec5.1.2
5117
  // URI can be an asterisk (*) or should start with slash.
5118
0
  return uri[0] == '/' || (uri[0] == '*' && uri[1] == '\0');
5119
0
}
5120
5121
0
static int getreq(struct mg_connection *conn, char *ebuf, size_t ebuf_len) {
5122
0
  const char *cl;
5123
5124
0
  ebuf[0] = '\0';
5125
0
  reset_per_request_attributes(conn);
5126
0
  conn->request_len = read_request(NULL, conn, conn->buf, conn->buf_size,
5127
0
           &conn->data_len);
5128
0
  assert(conn->request_len < 0 || conn->data_len >= conn->request_len);
5129
5130
0
  if (conn->request_len == 0 && conn->data_len == conn->buf_size) {
5131
0
    snprintf(ebuf, ebuf_len, "%s", "Request Too Large");
5132
0
  } if (conn->request_len <= 0) {
5133
0
    snprintf(ebuf, ebuf_len, "%s", "Client closed connection");
5134
0
  } else if (parse_http_message(conn->buf, conn->buf_size,
5135
0
        &conn->request_info) <= 0) {
5136
0
    snprintf(ebuf, ebuf_len, "Bad request: [%.*s]", conn->data_len, conn->buf);
5137
0
  } else {
5138
    // Request is valid
5139
0
    if ((cl = get_header(&conn->request_info, "Content-Length")) != NULL) {
5140
0
      conn->content_len = strtoll(cl, NULL, 10);
5141
0
    } else if (!mg_strcasecmp(conn->request_info.request_method, "POST") ||
5142
0
         !mg_strcasecmp(conn->request_info.request_method, "PUT")) {
5143
0
      conn->content_len = -1;
5144
0
    } else {
5145
0
      conn->content_len = 0;
5146
0
    }
5147
0
    conn->birth_time = time(NULL);
5148
0
  }
5149
0
  return ebuf[0] == '\0';
5150
0
}
5151
5152
struct mg_connection *mg_download(const char *host, int port, int use_ssl,
5153
          char *ebuf, size_t ebuf_len,
5154
0
          const char *fmt, ...) {
5155
0
  struct mg_connection *conn;
5156
0
  va_list ap;
5157
5158
0
  va_start(ap, fmt);
5159
0
  ebuf[0] = '\0';
5160
0
  if ((conn = mg_connect(host, port, use_ssl, ebuf, ebuf_len)) == NULL) {
5161
0
  } else if (mg_vprintf(conn, fmt, ap) <= 0) {
5162
0
    snprintf(ebuf, ebuf_len, "%s", "Error sending request");
5163
0
  } else {
5164
0
    getreq(conn, ebuf, ebuf_len);
5165
0
  }
5166
0
  if (ebuf[0] != '\0' && conn != NULL) {
5167
0
    mg_close_connection(conn);
5168
0
    conn = NULL;
5169
0
  }
5170
5171
0
  return conn;
5172
0
}
5173
5174
0
static void process_new_connection(struct mg_connection *conn) {
5175
0
  struct mg_request_info *ri = &conn->request_info;
5176
0
  int keep_alive_enabled, keep_alive, discard_len;
5177
0
  char ebuf[100];
5178
5179
0
  keep_alive_enabled = !strcmp(conn->ctx->config[ENABLE_KEEP_ALIVE], "yes");
5180
0
  keep_alive = 0;
5181
5182
  // Important: on new connection, reset the receiving buffer. Credit goes
5183
  // to crule42.
5184
0
  conn->data_len = 0;
5185
0
  do {
5186
0
    if (!getreq(conn, ebuf, sizeof(ebuf))) {
5187
0
      send_http_error(conn, 500, "Server Error", "%s", ebuf);
5188
0
    } else if (!is_valid_uri(conn->request_info.uri)) {
5189
0
      snprintf(ebuf, sizeof(ebuf), "Invalid URI: [%s]", ri->uri);
5190
0
      send_http_error(conn, 400, "Bad Request", "%s", ebuf);
5191
0
    } else if (strcmp(ri->http_version, "1.0") &&
5192
0
         strcmp(ri->http_version, "1.1")) {
5193
0
      snprintf(ebuf, sizeof(ebuf), "Bad HTTP version: [%s]", ri->http_version);
5194
0
      send_http_error(conn, 505, "Bad HTTP version", "%s", ebuf);
5195
0
    } else if (!strcmp(ri->http_version, "1.1") &&
5196
0
         !mg_get_header(conn, "Host")) {
5197
0
      snprintf(ebuf, sizeof(ebuf), "Missing mandatory Host header");
5198
      /* RFC 7230: "A server MUST respond with a 400 (Bad Request) status code to any HTTP/1.1
5199
   request message that lacks a Host header field. */
5200
0
      send_http_error(conn, 400, "Bad Request", "%s", ebuf);
5201
0
    }
5202
5203
0
    if (ebuf[0] == '\0') {
5204
0
      handle_request(conn);
5205
0
      if (conn->ctx->callbacks.end_request != NULL) {
5206
0
  conn->ctx->callbacks.end_request(conn, conn->status_code);
5207
0
      }
5208
0
#if 1 /* NTOP */
5209
0
      if(conn->status_code == 200) traceHTTP(conn, conn->status_code);
5210
0
#endif
5211
0
      log_access(conn);
5212
0
    }
5213
0
    if (ri->remote_user != NULL) {
5214
0
      free((void *) ri->remote_user);
5215
0
    }
5216
5217
    // NOTE(lsm): order is important here. should_keep_alive() call
5218
    // is using parsed request, which will be invalid after memmove's below.
5219
    // Therefore, memorize should_keep_alive() result now for later use
5220
    // in loop exit condition.
5221
0
    keep_alive = should_keep_alive(conn);
5222
5223
    // Discard all buffered data for this request
5224
0
    discard_len = conn->content_len >= 0 &&
5225
0
      conn->request_len + conn->content_len < (int64_t) conn->data_len ?
5226
0
      (int) (conn->request_len + conn->content_len) : conn->data_len;
5227
0
    memmove(conn->buf, conn->buf + discard_len, conn->data_len - discard_len);
5228
0
    conn->data_len -= discard_len;
5229
0
    assert(conn->data_len >= 0);
5230
0
    assert(conn->data_len <= conn->buf_size);
5231
5232
0
  } while (conn->ctx->stop_flag == 0 &&
5233
0
     keep_alive_enabled &&
5234
0
     conn->content_len >= 0 &&
5235
0
     keep_alive);
5236
0
}
5237
5238
// Worker threads take accepted socket from the queue
5239
0
static int consume_socket(struct mg_context *ctx, struct socket *sp) {
5240
0
  (void) pthread_mutex_lock(&ctx->mutex);
5241
0
  DEBUG_TRACE(("going idle"));
5242
5243
  // If the queue is empty, wait. We're idle at this point.
5244
0
  while (ctx->sq_head == ctx->sq_tail && ctx->stop_flag == 0) {
5245
0
    pthread_cond_wait(&ctx->sq_full, &ctx->mutex);
5246
0
  }
5247
5248
  // If we're stopping, sq_head may be equal to sq_tail.
5249
0
  if (ctx->sq_head > ctx->sq_tail) {
5250
    // Copy socket from the queue and increment tail
5251
0
    *sp = ctx->queue[ctx->sq_tail % ARRAY_SIZE(ctx->queue)];
5252
0
    ctx->sq_tail++;
5253
0
    DEBUG_TRACE(("grabbed socket %d, going busy", sp->sock));
5254
5255
    // Wrap pointers if needed
5256
0
    while (ctx->sq_tail > (int) ARRAY_SIZE(ctx->queue)) {
5257
0
      ctx->sq_tail -= ARRAY_SIZE(ctx->queue);
5258
0
      ctx->sq_head -= ARRAY_SIZE(ctx->queue);
5259
0
    }
5260
0
  }
5261
5262
0
  (void) pthread_cond_signal(&ctx->sq_empty);
5263
0
  (void) pthread_mutex_unlock(&ctx->mutex);
5264
5265
0
  return !ctx->stop_flag;
5266
0
}
5267
5268
0
static void *worker_thread(void *thread_func_param) {
5269
0
  struct mg_context *ctx = (struct mg_context *)thread_func_param;
5270
0
  struct mg_connection *conn;
5271
5272
0
  Utils::setThreadName("n-http-worker");
5273
  
5274
0
  conn = (struct mg_connection *) calloc(1, sizeof(*conn) + MAX_REQUEST_SIZE);
5275
0
  if (conn == NULL) {
5276
0
    cry(fc(ctx), "%s", "Cannot create new connection struct, OOM");
5277
0
  } else {
5278
0
    conn->buf_size = MAX_REQUEST_SIZE;
5279
0
    conn->buf = (char *) (conn + 1);
5280
0
    conn->ctx = ctx;
5281
0
    conn->request_info.user_data = ctx->user_data;
5282
5283
    // Call consume_socket() even when ctx->stop_flag > 0, to let it signal
5284
    // sq_empty condvar to wake up the master waiting in produce_socket()
5285
0
    while (consume_socket(ctx, &conn->client)) {
5286
0
      conn->birth_time = time(NULL);
5287
5288
      // Fill in IP, port info early so even if SSL setup below fails,
5289
      // error handler would have the corresponding info.
5290
      // Thanks to Johannes Winkelmann for the patch.
5291
      // TODO(lsm): Fix IPv6 case
5292
0
      conn->request_info.remote_port = ntohs(conn->client.rsa.sin.sin_port);
5293
0
      memcpy(&conn->request_info.remote_ip,
5294
0
       &conn->client.rsa.sin.sin_addr.s_addr, 4);
5295
0
      conn->request_info.remote_ip = ntohl(conn->request_info.remote_ip);
5296
0
      conn->request_info.is_ssl = conn->client.is_ssl;
5297
5298
0
      if (!conn->client.is_ssl
5299
0
#ifndef NO_SSL
5300
0
    || sslize(conn, conn->ctx->ssl_ctx, SSL_accept)
5301
0
#endif
5302
0
    ) {
5303
0
  process_new_connection(conn);
5304
0
      }
5305
5306
0
      close_connection(conn);
5307
0
    }
5308
0
    free(conn);
5309
0
  }
5310
5311
  // Signal master that we're done with connection and exiting
5312
0
  (void) pthread_mutex_lock(&ctx->mutex);
5313
0
  ctx->num_threads--;
5314
0
  (void) pthread_cond_signal(&ctx->cond);
5315
0
  assert(ctx->num_threads >= 0);
5316
0
  (void) pthread_mutex_unlock(&ctx->mutex);
5317
5318
0
  DEBUG_TRACE(("exiting"));
5319
0
  return NULL;
5320
0
}
5321
5322
// Master thread adds accepted socket to a queue
5323
0
static void produce_socket(struct mg_context *ctx, const struct socket *sp) {
5324
0
  (void) pthread_mutex_lock(&ctx->mutex);
5325
5326
  // If the queue is full, wait
5327
0
  while (ctx->stop_flag == 0 &&
5328
0
   ctx->sq_head - ctx->sq_tail >= (int) ARRAY_SIZE(ctx->queue)) {
5329
0
    (void) pthread_cond_wait(&ctx->sq_empty, &ctx->mutex);
5330
0
  }
5331
5332
0
  if (ctx->sq_head - ctx->sq_tail < (int) ARRAY_SIZE(ctx->queue)) {
5333
    // Copy socket to the queue and increment head
5334
0
    ctx->queue[ctx->sq_head % ARRAY_SIZE(ctx->queue)] = *sp;
5335
0
    ctx->sq_head++;
5336
0
    DEBUG_TRACE(("queued socket %d", sp->sock));
5337
0
  }
5338
5339
0
  (void) pthread_cond_signal(&ctx->sq_full);
5340
0
  (void) pthread_mutex_unlock(&ctx->mutex);
5341
0
}
5342
5343
0
static int set_sock_timeout(SOCKET sock, int milliseconds) {
5344
#ifdef _WIN32
5345
  DWORD t = milliseconds;
5346
#else
5347
0
  struct timeval t;
5348
0
  t.tv_sec = milliseconds / 1000;
5349
0
  t.tv_usec = (milliseconds * 1000) % 1000000;
5350
0
#endif
5351
0
  return setsockopt(sock, SOL_SOCKET, SO_RCVTIMEO,
5352
#ifdef WIN32
5353
        (const char*)
5354
#else
5355
0
        (void *)
5356
0
#endif
5357
0
        &t, sizeof(t)) ||
5358
0
    setsockopt(sock, SOL_SOCKET, SO_SNDTIMEO,
5359
#ifdef WIN32
5360
         (const char*)
5361
#else
5362
0
         (void *)
5363
0
#endif
5364
0
         &t, sizeof(t));
5365
0
}
5366
5367
static void accept_new_connection(const struct socket *listener,
5368
0
          struct mg_context *ctx) {
5369
0
  struct socket so;
5370
0
  char src_addr[20];
5371
0
  socklen_t len = sizeof(so.rsa);
5372
0
  int on = 1;
5373
5374
0
  if ((so.sock = accept(listener->sock, &so.rsa.sa, &len)) == INVALID_SOCKET) {
5375
0
  } else if (!check_acl(ctx, ntohl(* (uint32_t *) &so.rsa.sin.sin_addr))) {
5376
0
    sockaddr_to_string(src_addr, sizeof(src_addr), &so.rsa);
5377
0
    cry(fc(ctx), "%s: %s is not allowed to connect", __func__, src_addr);
5378
0
    closesocket(so.sock);
5379
0
  } else {
5380
    // Put so socket structure into the queue
5381
0
    DEBUG_TRACE(("Accepted socket %d", (int) so.sock));
5382
0
    so.is_ssl = listener->is_ssl;
5383
0
    so.ssl_redir = listener->ssl_redir;
5384
0
    getsockname(so.sock, &so.lsa.sa, &len);
5385
    // Set TCP keep-alive. This is needed because if HTTP-level keep-alive
5386
    // is enabled, and client resets the connection, server won't get
5387
    // TCP FIN or RST and will keep the connection open forever. With TCP
5388
    // keep-alive, next keep-alive handshake will figure out that the client
5389
    // is down and will close the server end.
5390
    // Thanks to Igor Klopov who suggested the patch.
5391
0
    setsockopt(so.sock, SOL_SOCKET, SO_KEEPALIVE,
5392
#ifdef WIN32
5393
         (const char*)
5394
#else
5395
0
         (void *)
5396
0
#endif
5397
0
         &on, sizeof(on));
5398
0
    set_sock_timeout(so.sock, atoi(ctx->config[REQUEST_TIMEOUT]));
5399
0
    produce_socket(ctx, &so);
5400
0
  }
5401
0
}
5402
5403
0
static void *master_thread(void *thread_func_param) {
5404
0
  struct mg_context *ctx = (struct mg_context *)thread_func_param;
5405
0
  struct pollfd *pfd;
5406
0
  int i;
5407
5408
0
  Utils::setThreadName("n-mongoose");
5409
  
5410
  // Increase priority of the master thread
5411
#if defined(_WIN32)
5412
  SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_ABOVE_NORMAL);
5413
#endif
5414
5415
#if defined(ISSUE_317)
5416
  struct sched_param sched_param;
5417
  sched_param.sched_priority = sched_get_priority_max(SCHED_RR);
5418
  pthread_setschedparam(pthread_self(), SCHED_RR, &sched_param);
5419
#endif
5420
5421
0
  pfd = (pollfd*)calloc(ctx->num_listening_sockets, sizeof(pfd[0]));
5422
0
  while (ctx->stop_flag == 0) {
5423
0
    for (i = 0; i < ctx->num_listening_sockets; i++) {
5424
0
      pfd[i].fd = ctx->listening_sockets[i].sock;
5425
0
      pfd[i].events = POLLIN;
5426
0
    }
5427
5428
0
    if (poll(pfd, ctx->num_listening_sockets, 200) > 0) {
5429
0
      for (i = 0; i < ctx->num_listening_sockets; i++) {
5430
0
  if (ctx->stop_flag == 0 && pfd[i].revents == POLLIN) {
5431
0
    accept_new_connection(&ctx->listening_sockets[i], ctx);
5432
0
  }
5433
0
      }
5434
0
    }
5435
0
  }
5436
0
  free(pfd);
5437
0
  DEBUG_TRACE(("stopping workers"));
5438
5439
  // Stop signal received: somebody called mg_stop. Quit.
5440
0
  close_all_listening_sockets(ctx);
5441
5442
  // Wakeup workers that are waiting for connections to handle.
5443
0
  pthread_cond_broadcast(&ctx->sq_full);
5444
5445
  // Wait until all threads finish
5446
0
  (void) pthread_mutex_lock(&ctx->mutex);
5447
0
  while (ctx->num_threads > 0) {
5448
0
    (void) pthread_cond_wait(&ctx->cond, &ctx->mutex);
5449
0
  }
5450
0
  (void) pthread_mutex_unlock(&ctx->mutex);
5451
5452
  // All threads exited, no sync is needed. Destroy mutex and condvars
5453
0
  (void) pthread_mutex_destroy(&ctx->mutex);
5454
0
  (void) pthread_cond_destroy(&ctx->cond);
5455
0
  (void) pthread_cond_destroy(&ctx->sq_empty);
5456
0
  (void) pthread_cond_destroy(&ctx->sq_full);
5457
5458
0
#if !defined(NO_SSL)
5459
0
  uninitialize_ssl(ctx);
5460
0
#endif
5461
0
  DEBUG_TRACE(("exiting"));
5462
5463
  // Signal mg_stop() that we're done.
5464
  // WARNING: This must be the very last thing this
5465
  // thread does, as ctx becomes invalid after this line.
5466
0
  ctx->stop_flag = 2;
5467
0
  return NULL;
5468
0
}
5469
5470
0
static void free_context(struct mg_context *ctx) {
5471
0
  int i;
5472
5473
  // Deallocate config parameters
5474
0
  for (i = 0; i < NUM_OPTIONS; i++) {
5475
0
    if (ctx->config[i] != NULL)
5476
0
      free(ctx->config[i]);
5477
0
  }
5478
5479
0
#ifndef NO_SSL
5480
  // Deallocate SSL context
5481
0
  if (ctx->ssl_ctx != NULL) {
5482
0
    SSL_CTX_free(ctx->ssl_ctx);
5483
0
  }
5484
0
  if (ssl_mutexes != NULL) {
5485
0
    free(ssl_mutexes);
5486
0
    ssl_mutexes = NULL;
5487
0
  }
5488
0
#endif // !NO_SSL
5489
5490
  // Deallocate context itself
5491
0
  free(ctx);
5492
0
}
5493
5494
0
void mg_stop(struct mg_context *ctx) {
5495
0
  ctx->stop_flag = 1;
5496
5497
  // Wait until mg_fini() stops
5498
0
  while (ctx->stop_flag != 2) {
5499
0
    (void) mg_sleep(10);
5500
0
  }
5501
0
  free_context(ctx);
5502
5503
#if defined(_WIN32) && !defined(__SYMBIAN32__)
5504
  (void) WSACleanup();
5505
#endif // _WIN32
5506
0
}
5507
5508
struct mg_context *mg_start(const struct mg_callbacks *callbacks,
5509
          void *user_data,
5510
0
          const char **options) {
5511
0
  struct mg_context *ctx;
5512
0
  const char *name, *value, *default_value;
5513
0
  int i;
5514
5515
0
#if defined(USE_IPV6)
5516
0
  check_ipv6_enabled();
5517
0
#endif
5518
5519
#if defined(__FreeBSD__) || defined(__NetBSD__) || defined(__OpenBSD__)
5520
  is_ip6_enabled = 0;
5521
#endif
5522
5523
#if defined(_WIN32) && !defined(__SYMBIAN32__)
5524
  WSADATA data;
5525
  WSAStartup(MAKEWORD(2,2), &data);
5526
  InitializeCriticalSection(&global_log_file_lock);
5527
#endif // _WIN32
5528
5529
  // Allocate context and initialize reasonable general case defaults.
5530
  // TODO(lsm): do proper error handling here.
5531
0
  if ((ctx = (struct mg_context *) calloc(1, sizeof(*ctx))) == NULL) {
5532
0
    return NULL;
5533
0
  }
5534
0
  ctx->callbacks = *callbacks;
5535
0
  ctx->user_data = user_data;
5536
5537
0
  while (options && (name = *options++) != NULL) {
5538
0
    if ((i = get_option_index(name)) == -1) {
5539
0
      cry(fc(ctx), "Invalid option: %s", name);
5540
0
      free_context(ctx);
5541
0
      return NULL;
5542
0
    } else if ((value = *options++) == NULL) {
5543
0
      cry(fc(ctx), "%s: option value cannot be NULL", name);
5544
0
      free_context(ctx);
5545
0
      return NULL;
5546
0
    }
5547
0
    if (ctx->config[i] != NULL) {
5548
0
      cry(fc(ctx), "warning: %s: duplicate option", name);
5549
0
      free(ctx->config[i]);
5550
0
    }
5551
0
    ctx->config[i] = mg_strdup(value);
5552
0
    DEBUG_TRACE(("[%s] -> [%s]", name, value));
5553
0
  }
5554
5555
  // Set default value if needed
5556
0
  for (i = 0; config_options[i * ENTRIES_PER_CONFIG_OPTION] != NULL; i++) {
5557
0
    default_value = config_options[i * ENTRIES_PER_CONFIG_OPTION + 2];
5558
0
    if (ctx->config[i] == NULL && default_value != NULL) {
5559
0
      ctx->config[i] = mg_strdup(default_value);
5560
0
      DEBUG_TRACE(("Setting default: [%s] -> [%s]",
5561
0
       config_options[i * ENTRIES_PER_CONFIG_OPTION + 1],
5562
0
       default_value));
5563
0
    }
5564
0
  }
5565
5566
  // NOTE(lsm): order is important here. SSL certificates must
5567
  // be initialized before listening ports. UID must be set last.
5568
0
  if (!set_gpass_option(ctx) ||
5569
0
#if !defined(NO_SSL)
5570
0
      !set_ssl_option(ctx) ||
5571
0
#endif
5572
0
      !set_ports_option(ctx) ||
5573
0
#if !defined(_WIN32)
5574
0
      !set_uid_option(ctx) ||
5575
0
#endif
5576
0
      !set_acl_option(ctx)) {
5577
0
    free_context(ctx);
5578
0
    return NULL;
5579
0
  }
5580
5581
0
#if !defined(_WIN32) && !defined(__SYMBIAN32__)
5582
  // Ignore SIGPIPE signal, so if browser cancels the request, it
5583
  // won't kill the whole process.
5584
0
  (void) signal(SIGPIPE, SIG_IGN);
5585
  // Also ignoring SIGCHLD to let the OS to reap zombies properly.
5586
#ifndef NO_CGI /* Only CGI support causes mongoose to fork */
5587
  (void) signal(SIGCHLD, SIG_IGN);
5588
#endif
5589
0
#endif // !_WIN32
5590
5591
0
  (void) pthread_mutex_init(&ctx->mutex, NULL);
5592
0
  (void) pthread_cond_init(&ctx->cond, NULL);
5593
0
  (void) pthread_cond_init(&ctx->sq_empty, NULL);
5594
0
  (void) pthread_cond_init(&ctx->sq_full, NULL);
5595
5596
  // Start master (listening) thread
5597
0
  mg_start_thread(master_thread, ctx);
5598
5599
  // Start worker threads
5600
0
  for (i = 0; i < atoi(ctx->config[NUM_THREADS]); i++) {
5601
0
    if (mg_start_thread(worker_thread, ctx) != 0) {
5602
0
      cry(fc(ctx), "Cannot start worker thread: %d", ERRNO);
5603
0
    } else {
5604
0
      ctx->num_threads++;
5605
0
    }
5606
0
  }
5607
5608
0
  return ctx;
5609
0
}