Previous 199869 Revisions Next

r31875 Tuesday 2nd September, 2014 at 13:01:21 UTC by Miodrag Milanović
(OSD BRANCH) Sync important things with main
[/branches/osd/src/lib/web]mongoose.c mongoose.h
[/branches/osd/src/osd/sdl]draw13.c osdsdl.h sdl.mak video.c video.h window.c window.h

branches/osd/src/osd/sdl/draw13.c
r31874r31875
11//============================================================
22//
3//  draw13.c - SDL 1.3 drawing implementation
3//  draw13.c - SDL 2.0 drawing implementation
44//
5//  Copyright (c) 1996-2010, Nicola Salmoria and the MAME Team.
5//  Copyright (c) 1996-2014, Nicola Salmoria and the MAME Team.
66//  Visit http://mamedev.org for licensing and usage restrictions.
77//
88//  SDLMAME by Olivier Galibert and R. Belmont
r31874r31875
145145
146146// core functions
147147
148static void draw13_exit(void);
149static void draw13_attach(sdl_draw_info *info, sdl_window_info *window);
150static int draw13_window_create(sdl_window_info *window, int width, int height);
151static void draw13_window_resize(sdl_window_info *window, int width, int height);
152static void draw13_window_destroy(sdl_window_info *window);
153static int draw13_window_draw(sdl_window_info *window, UINT32 dc, int update);
154static render_primitive_list &draw13_window_get_primitives(sdl_window_info *window);
155static void draw13_destroy_all_textures(sdl_window_info *window);
156static void draw13_window_clear(sdl_window_info *window);
157static int draw13_xy_to_render_target(sdl_window_info *window, int x, int y, int *xt, int *yt);
158static void draw13_destroy_texture(sdl_info *sdl, texture_info *texture);
148static void drawsdl2_exit(void);
149static void drawsdl2_attach(sdl_draw_info *info, sdl_window_info *window);
150static int drawsdl2_window_create(sdl_window_info *window, int width, int height);
151static void drawsdl2_window_resize(sdl_window_info *window, int width, int height);
152static void drawsdl2_window_destroy(sdl_window_info *window);
153static int drawsdl2_window_draw(sdl_window_info *window, UINT32 dc, int update);
154static render_primitive_list &drawsdl2_window_get_primitives(sdl_window_info *window);
155static void drawsdl2_destroy_all_textures(sdl_window_info *window);
156static void drawsdl2_window_clear(sdl_window_info *window);
157static int drawsdl2_xy_to_render_target(sdl_window_info *window, int x, int y, int *xt, int *yt);
158static void drawsdl2_destroy_texture(sdl_info *sdl, texture_info *texture);
159159
160160//============================================================
161161//  Textures
r31874r31875
206206   ENTRY(YUY16,            YUY2,       2, 0, yuv16_yuy2),
207207   ENTRY(YUY16,            YVYU,       2, 0, yuv16_yvyu),
208208   ENTRY(YUY16,            ARGB8888,   4, 0, yuv16_argb32),
209   ENTRY(YUY16,            RGB888,     4, 0, yuv16pal_argb32),
209   ENTRY(YUY16,            RGB888,     4, 0, yuv16_argb32),
210210
211211   ENTRY(YUY16_PALETTED,   UYVY,       2, 0, yuv16pal_uyvy),
212212   ENTRY(YUY16_PALETTED,   YUY2,       2, 0, yuv16pal_yuy2),
r31874r31875
265265{ -1 },
266266};
267267
268static copy_info blit_info_16bpp[] =
269{
270   /* no rotation */
271   ENTRY(PALETTE16,        RGB555,     2, 0, pal16_argb1555),
272   ENTRY(PALETTE16,        ARGB1555,   2, 0, pal16_argb1555),
273
274   ENTRY(RGB15_PALETTED,   RGB555,     2, 0, rgb15pal_argb1555),
275   ENTRY(RGB15_PALETTED,   ARGB1555,   2, 0, rgb15pal_argb1555),
276
277   /* rotation */
278   ENTRY(PALETTE16,        RGB555,     2, 1, rot_pal16_argb1555),
279   ENTRY(PALETTE16,        ARGB1555,   2, 1, rot_pal16_argb1555),
280
281   ENTRY(RGB15_PALETTED,   RGB555,     2, 1, rot_rgb15pal_argb1555),
282   ENTRY(RGB15_PALETTED,   ARGB1555,   2, 1, rot_rgb15pal_argb1555),
283
284{ -1 },
285};
286
287268static copy_info *blit_info[SDL_TEXFORMAT_LAST+1];
288269
289270static struct
r31874r31875
455436#endif
456437
457438//============================================================
458//  draw13_init
439//  drawsdl2_init
459440//============================================================
460441
461442static void add_list(copy_info **head, copy_info *element, Uint32 bm)
r31874r31875
486467   }
487468}
488469
489int draw13_init(running_machine &machine, sdl_draw_info *callbacks)
470int drawsdl2_init(running_machine &machine, sdl_draw_info *callbacks)
490471{
491472   const char *stemp;
492473
493474   // fill in the callbacks
494   callbacks->exit = draw13_exit;
495   callbacks->attach = draw13_attach;
475   callbacks->exit = drawsdl2_exit;
476   callbacks->attach = drawsdl2_attach;
496477
497478   osd_printf_verbose("Using SDL native texturing driver (SDL 2.0+)\n");
498479
499480   expand_copy_info(blit_info_default);
500   //FIXME: -opengl16 should be -opengl -prefer16bpp
501   //if (video_config.prefer16bpp_tex)
502   expand_copy_info(blit_info_16bpp);
503481
504482   // Load the GL library now - else MT will fail
505
506483   stemp = downcast<sdl_options &>(machine.options()).gl_lib();
507484   if (stemp != NULL && strcmp(stemp, SDLOPTVAL_AUTO) == 0)
508485      stemp = NULL;
r31874r31875
518495
519496
520497//============================================================
521//  draw13_exit
498//  drawsdl2_exit
522499//============================================================
523500
524static void draw13_exit(void)
501static void drawsdl2_exit(void)
525502{
526503   int i;
527504   copy_info *bi, *freeme;
r31874r31875
539516}
540517
541518//============================================================
542//  draw13_attach
519//  drawsdl2_attach
543520//============================================================
544521
545static void draw13_attach(sdl_draw_info *info, sdl_window_info *window)
522static void drawsdl2_attach(sdl_draw_info *info, sdl_window_info *window)
546523{
547524   // fill in the callbacks
548   window->create = draw13_window_create;
549   window->resize = draw13_window_resize;
550   window->get_primitives = draw13_window_get_primitives;
551   window->draw = draw13_window_draw;
552   window->destroy = draw13_window_destroy;
553   window->destroy_all_textures = draw13_destroy_all_textures;
554   window->clear = draw13_window_clear;
555   window->xy_to_render_target = draw13_xy_to_render_target;
525   window->create = drawsdl2_window_create;
526   window->resize = drawsdl2_window_resize;
527   window->get_primitives = drawsdl2_window_get_primitives;
528   window->draw = drawsdl2_window_draw;
529   window->destroy = drawsdl2_window_destroy;
530   window->destroy_all_textures = drawsdl2_destroy_all_textures;
531   window->clear = drawsdl2_window_clear;
532   window->xy_to_render_target = drawsdl2_xy_to_render_target;
556533}
557534
558535//============================================================
559//  draw13_window_create
536//  drawsdl2_window_create
560537//============================================================
561538
562static int draw13_window_create(sdl_window_info *window, int width, int height)
539static int drawsdl2_window_create(sdl_window_info *window, int width, int height)
563540{
564541   // allocate memory for our structures
565542   sdl_info *sdl = (sdl_info *) osd_malloc(sizeof(*sdl));
566543
567   osd_printf_verbose("Enter draw13_window_create\n");
544   osd_printf_verbose("Enter drawsdl2_window_create\n");
568545
569546   memset(sdl, 0, sizeof(*sdl));
570547
r31874r31875
638615   sdl->texture_max_height = 64;
639616
640617   SDL_RenderPresent(sdl->sdl_renderer);
641   osd_printf_verbose("Leave draw13_window_create\n");
618   osd_printf_verbose("Leave drawsdl2_window_create\n");
642619   return 0;
643620}
644621
645622//============================================================
646//  draw13_window_resize
623//  drawsdl2_window_resize
647624//============================================================
648625
649static void draw13_window_resize(sdl_window_info *window, int width, int height)
626static void drawsdl2_window_resize(sdl_window_info *window, int width, int height)
650627{
651628   sdl_info *sdl = (sdl_info *) window->dxdata;
652629
r31874r31875
665642//  drawsdl_xy_to_render_target
666643//============================================================
667644
668static int draw13_xy_to_render_target(sdl_window_info *window, int x, int y, int *xt, int *yt)
645static int drawsdl2_xy_to_render_target(sdl_window_info *window, int x, int y, int *xt, int *yt)
669646{
670647   sdl_info *sdl = (sdl_info *) window->dxdata;
671648
r31874r31875
679656}
680657
681658//============================================================
682//  draw13_window_get_primitives
659//  drawsdl2_window_get_primitives
683660//============================================================
684661
685static render_primitive_list &draw13_window_get_primitives(sdl_window_info *window)
662static render_primitive_list &drawsdl2_window_get_primitives(sdl_window_info *window)
686663{
687664   if ((!window->fullscreen) || (video_config.switchres))
688665   {
r31874r31875
697674}
698675
699676//============================================================
700//  draw13_window_draw
677//  drawsdl2_window_draw
701678//============================================================
702679
703static int draw13_window_draw(sdl_window_info *window, UINT32 dc, int update)
680static int drawsdl2_window_draw(sdl_window_info *window, UINT32 dc, int update)
704681{
705682   sdl_info *sdl = (sdl_info *) window->dxdata;
706683   render_primitive *prim;
r31874r31875
809786
810787
811788//============================================================
812//  draw13_window_clear
789//  drawsdl2_window_clear
813790//============================================================
814791
815static void draw13_window_clear(sdl_window_info *window)
792static void drawsdl2_window_clear(sdl_window_info *window)
816793{
817794   sdl_info *sdl = (sdl_info *) window->dxdata;
818795
r31874r31875
821798
822799
823800//============================================================
824//  draw13_window_destroy
801//  drawsdl2_window_destroy
825802//============================================================
826803
827static void draw13_window_destroy(sdl_window_info *window)
804static void drawsdl2_window_destroy(sdl_window_info *window)
828805{
829806   sdl_info *sdl = (sdl_info *) window->dxdata;
830807
r31874r31875
834811
835812   // free the memory in the window
836813
837   draw13_destroy_all_textures(window);
814   drawsdl2_destroy_all_textures(window);
838815
839816   SDL_DestroyWindow(window->sdl_window);
840817
r31874r31875
11071084         texture_info *expire = texture;
11081085         texture = texture->next;
11091086         if (now - expire->last_access > osd_ticks_per_second())
1110            draw13_destroy_texture(sdl, expire);
1087            drawsdl2_destroy_texture(sdl, expire);
11111088      }
11121089
11131090   // nothing found
r31874r31875
11471124   return texture;
11481125}
11491126
1150static void draw13_destroy_texture(sdl_info *sdl, texture_info *texture)
1127static void drawsdl2_destroy_texture(sdl_info *sdl, texture_info *texture)
11511128{
11521129   texture_info *p;
11531130
r31874r31875
11691146   osd_free(texture);
11701147}
11711148
1172static void draw13_destroy_all_textures(sdl_window_info *window)
1149static void drawsdl2_destroy_all_textures(sdl_window_info *window)
11731150{
11741151   sdl_info *sdl = (sdl_info *) window->dxdata;
11751152   texture_info *next_texture=NULL, *texture = NULL;
r31874r31875
11891166   while (texture)
11901167   {
11911168      next_texture = texture->next;
1192      draw13_destroy_texture(sdl, texture);
1169      drawsdl2_destroy_texture(sdl, texture);
11931170      texture = next_texture;
11941171   }
11951172
branches/osd/src/osd/sdl/sdl.mak
r31874r31875
5959# active development on sdlmame or SDL.
6060
6161# uncomment the next line to compile and link against SDL2.0
62# SDL_LIBVER = sdl2
62#SDL_LIBVER = sdl2
6363
6464# uncomment the next line to use couriersud's multi-keyboard patch for SDL 2.1? (this API was removed prior to the 2.0 release)
6565# SDL2_MULTIAPI = 1
r31874r31875
622622MOC = @moc
623623endif
624624
625LIBS += -lSDL.dll
625ifeq ($(SDL_LIBVER),sdl2)
626LIBS += -lSDL2 -lImm32 -lversion -lole32 -loleaut32 -static
627else
628LIBS += -lSDL -static
629endif
626630LIBS += -luser32 -lgdi32 -lddraw -ldsound -ldxguid -lwinmm -ladvapi32 -lcomctl32 -lshlwapi
627631
628632endif   # Win32
branches/osd/src/osd/sdl/osdsdl.h
r31874r31875
8282#define SDLOPTVAL_AUTO                  "auto"
8383
8484#define SDLOPTVAL_OPENGL                "opengl"
85#define SDLOPTVAL_OPENGL16              "opengl16"
8685#define SDLOPTVAL_SOFT                  "soft"
87#define SDLOPTVAL_SDL13                 "sdl13"
86#define SDLOPTVAL_SDL2ACCEL            "accel"
8887
8988#define SDLMAME_LED(x)                  "led" #x
9089
branches/osd/src/osd/sdl/video.c
r31874r31875
22//
33//  video.c - SDL video handling
44//
5//  Copyright (c) 1996-2010, Nicola Salmoria and the MAME Team.
5//  Copyright (c) 1996-2014, Nicola Salmoria and the MAME Team.
66//  Visit http://mamedev.org for licensing and usage restrictions.
77//
88//  SDLMAME by Olivier Galibert and R. Belmont
r31874r31875
645645   }
646646   else if (USE_OPENGL && (strcmp(stemp, SDLOPTVAL_OPENGL) == 0))
647647      video_config.mode = VIDEO_MODE_OPENGL;
648   else if (USE_OPENGL && (strcmp(stemp, SDLOPTVAL_OPENGL16) == 0))
648   else if (SDLMAME_SDL2 && (strcmp(stemp, SDLOPTVAL_SDL2ACCEL) == 0))
649649   {
650      video_config.mode = VIDEO_MODE_OPENGL;
651      video_config.prefer16bpp_tex = 1;
650      video_config.mode = VIDEO_MODE_SDL2ACCEL;
652651   }
653   else if (SDLMAME_SDL2 && (strcmp(stemp, SDLOPTVAL_SDL13) == 0))
654   {
655      video_config.mode = VIDEO_MODE_SDL13;
656      video_config.prefer16bpp_tex = 1;
657   }
658652   else
659653   {
660654      osd_printf_warning("Invalid video value %s; reverting to software\n", stemp);
r31874r31875
684678         video_config.prescale = 1;
685679      }
686680      // default to working video please
687      video_config.prefer16bpp_tex = 0;
688681      video_config.forcepow2texture = options.gl_force_pow2_texture();
689682      video_config.allowtexturerect = !(options.gl_no_texture_rect());
690683      video_config.vbo         = options.gl_vbo();
branches/osd/src/osd/sdl/video.h
r31874r31875
22//
33//  video.h - SDL implementation of MAME video routines
44//
5//  Copyright (c) 1996-2006, Nicola Salmoria and the MAME Team.
5//  Copyright (c) 1996-2014, Nicola Salmoria and the MAME Team.
66//  Visit http://mamedev.org for licensing and usage restrictions.
77//
88//  SDLMAME by Olivier Galibert and R. Belmont
r31874r31875
2121enum {
2222   VIDEO_MODE_SOFT = 0,
2323   VIDEO_MODE_OPENGL,
24   VIDEO_MODE_SDL13
24   VIDEO_MODE_SDL2ACCEL
2525};
2626
2727#define VIDEO_SCALE_MODE_NONE       (0)
r31874r31875
109109
110110   // OpenGL options
111111   int                 filter;         // enable filtering, disabled if glsl_filter>0
112   int                 prefer16bpp_tex;
113112   int                 glsl;
114113   int                 glsl_filter;        // glsl filtering, >0 disables filter
115114   char *              glsl_shader_mamebm[GLSL_SHADER_MAX]; // custom glsl shader set, mame bitmap
branches/osd/src/osd/sdl/window.c
r31874r31875
22//
33//  window.c - SDL window handling
44//
5//  Copyright (c) 1996-2010, Nicola Salmoria and the MAME Team.
5//  Copyright (c) 1996-2014, Nicola Salmoria and the MAME Team.
66//  Visit http://mamedev.org for licensing and usage restrictions.
77//
88//  SDLMAME by Olivier Galibert and R. Belmont
r31874r31875
239239   }
240240#endif
241241#if SDLMAME_SDL2
242   if (video_config.mode == VIDEO_MODE_SDL13)
242   if (video_config.mode == VIDEO_MODE_SDL2ACCEL)
243243   {
244      if (draw13_init(machine(), &draw))
244      if (drawsdl2_init(machine(), &draw))
245245         video_config.mode = VIDEO_MODE_SOFT;
246246   }
247247#endif
r31874r31875
974974      {
975975         window->minwidth = tempwidth;
976976         window->minheight = tempheight;
977
977978         if (!window->fullscreen)
978979         {
979980            sdlwindow_blit_surface_size(window, window->width, window->height);
branches/osd/src/osd/sdl/window.h
r31874r31875
22//
33//  window.h - SDL window handling
44//
5//  Copyright (c) 1996-2006, Nicola Salmoria and the MAME Team.
5//  Copyright (c) 1996-2014, Nicola Salmoria and the MAME Team.
66//  Visit http://mamedev.org for licensing and usage restrictions.
77//
88//  SDLMAME by Olivier Galibert and R. Belmont
r31874r31875
147147// PROTOTYPES - draw13.c
148148//============================================================
149149
150int draw13_init(running_machine &machine, sdl_draw_info *callbacks);
150int drawsdl2_init(running_machine &machine, sdl_draw_info *callbacks);
151151
152152#endif /* __SDLWINDOW__ */
branches/osd/src/lib/web/mongoose.h
r31874r31875
1515// Alternatively, you can license this library under a commercial
1616// license, as set out in <http://cesanta.com/>.
1717//
18// NOTE: Detailed API documentation is at http://cesanta.com/#docs
18// $Date: 2014-09-01 19:53:26 UTC $
1919
2020#ifndef MONGOOSE_HEADER_INCLUDED
2121#define  MONGOOSE_HEADER_INCLUDED
r31874r31875
3131
3232// This structure contains information about HTTP request.
3333struct mg_connection {
34   const char *request_method; // "GET", "POST", etc
35   const char *uri;            // URL-decoded URI
36   const char *http_version;   // E.g. "1.0", "1.1"
37   const char *query_string;   // URL part after '?', not including '?', or NULL
34  const char *request_method; // "GET", "POST", etc
35  const char *uri;            // URL-decoded URI
36  const char *http_version;   // E.g. "1.0", "1.1"
37  const char *query_string;   // URL part after '?', not including '?', or NULL
3838
39   char remote_ip[48];         // Max IPv6 string length is 45 characters
40   char local_ip[48];          // Local IP address
41   unsigned short remote_port; // Client's port
42   unsigned short local_port;  // Local port number
39  char remote_ip[48];         // Max IPv6 string length is 45 characters
40  char local_ip[48];          // Local IP address
41  unsigned short remote_port; // Client's port
42  unsigned short local_port;  // Local port number
4343
44   int num_headers;            // Number of HTTP headers
45   struct mg_header {
46   const char *name;         // HTTP header name
47   const char *value;        // HTTP header value
48   } http_headers[30];
44  int num_headers;            // Number of HTTP headers
45  struct mg_header {
46    const char *name;         // HTTP header name
47    const char *value;        // HTTP header value
48  } http_headers[30];
4949
50   char *content;              // POST (or websocket message) data, or NULL
51   size_t content_len;         // Data length
50  char *content;              // POST (or websocket message) data, or NULL
51  size_t content_len;         // Data length
5252
53   int is_websocket;           // Connection is a websocket connection
54   int status_code;            // HTTP status code for HTTP error handler
55   int wsbits;                 // First byte of the websocket frame
56   void *server_param;         // Parameter passed to mg_add_uri_handler()
57   void *connection_param;     // Placeholder for connection-specific data
58   void *callback_param;       // Needed by mg_iterate_over_connections()
53  int is_websocket;           // Connection is a websocket connection
54  int status_code;            // HTTP status code for HTTP error handler
55  int wsbits;                 // First byte of the websocket frame
56  void *server_param;         // Parameter passed to mg_add_uri_handler()
57  void *connection_param;     // Placeholder for connection-specific data
58  void *callback_param;       // Needed by mg_iterate_over_connections()
5959};
6060
6161struct mg_server; // Opaque structure describing server instance
6262enum mg_result { MG_FALSE, MG_TRUE, MG_MORE };
6363enum mg_event {
64   MG_POLL = 100,  // Callback return value is ignored
65   MG_CONNECT,     // If callback returns MG_FALSE, connect fails
66   MG_AUTH,        // If callback returns MG_FALSE, authentication fails
67   MG_REQUEST,     // If callback returns MG_FALSE, Mongoose continues with req
68   MG_REPLY,       // If callback returns MG_FALSE, Mongoose closes connection
69   MG_CLOSE,       // Connection is closed, callback return value is ignored
70   MG_WS_HANDSHAKE,  // New websocket connection, handshake request
71   MG_WS_CONNECT,  // New websocket connection established
72   MG_HTTP_ERROR   // If callback returns MG_FALSE, Mongoose continues with err
64  MG_POLL = 100,  // Callback return value is ignored
65  MG_CONNECT,     // If callback returns MG_FALSE, connect fails
66  MG_AUTH,        // If callback returns MG_FALSE, authentication fails
67  MG_REQUEST,     // If callback returns MG_FALSE, Mongoose continues with req
68  MG_REPLY,       // If callback returns MG_FALSE, Mongoose closes connection
69  MG_RECV,        // Mongoose has received POST data chunk.
70                  // Callback should return a number of bytes to discard from
71                  // the receive buffer, or -1 to close the connection.
72  MG_CLOSE,       // Connection is closed, callback return value is ignored
73  MG_WS_HANDSHAKE,  // New websocket connection, handshake request
74  MG_WS_CONNECT,  // New websocket connection established
75  MG_HTTP_ERROR   // If callback returns MG_FALSE, Mongoose continues with err
7376};
7477typedef int (*mg_handler_t)(struct mg_connection *, enum mg_event);
7578
7679// Websocket opcodes, from http://tools.ietf.org/html/rfc6455
7780enum {
78   WEBSOCKET_OPCODE_CONTINUATION = 0x0,
79   WEBSOCKET_OPCODE_TEXT = 0x1,
80   WEBSOCKET_OPCODE_BINARY = 0x2,
81   WEBSOCKET_OPCODE_CONNECTION_CLOSE = 0x8,
82   WEBSOCKET_OPCODE_PING = 0x9,
83   WEBSOCKET_OPCODE_PONG = 0xa
81  WEBSOCKET_OPCODE_CONTINUATION = 0x0,
82  WEBSOCKET_OPCODE_TEXT = 0x1,
83  WEBSOCKET_OPCODE_BINARY = 0x2,
84  WEBSOCKET_OPCODE_CONNECTION_CLOSE = 0x8,
85  WEBSOCKET_OPCODE_PING = 0x9,
86  WEBSOCKET_OPCODE_PONG = 0xa
8487};
8588
8689// Server management functions
r31874r31875
107110size_t mg_printf(struct mg_connection *conn, const char *fmt, ...);
108111
109112size_t mg_websocket_write(struct mg_connection *, int opcode,
110                     const char *data, size_t data_len);
113                          const char *data, size_t data_len);
111114size_t mg_websocket_printf(struct mg_connection* conn, int opcode,
112                     const char *fmt, ...);
115                           const char *fmt, ...);
113116
114117void mg_send_file(struct mg_connection *, const char *path);
118void mg_send_file_data(struct mg_connection *, int fd);
115119
116120const char *mg_get_header(const struct mg_connection *, const char *name);
117121const char *mg_get_mime_type(const char *name, const char *default_mime_type);
118122int mg_get_var(const struct mg_connection *conn, const char *var_name,
119            char *buf, size_t buf_len);
123               char *buf, size_t buf_len);
120124int mg_parse_header(const char *hdr, const char *var_name, char *buf, size_t);
121125int mg_parse_multipart(const char *buf, int buf_len,
122                  char *var_name, int var_name_len,
123                  char *file_name, int file_name_len,
124                  const char **data, int *data_len);
126                       char *var_name, int var_name_len,
127                       char *file_name, int file_name_len,
128                       const char **data, int *data_len);
125129
126130// Utility functions
127131void *mg_start_thread(void *(*func)(void *), void *param);
r31874r31875
129133int mg_authorize_digest(struct mg_connection *c, FILE *fp);
130134int mg_url_encode(const char *src, size_t s_len, char *dst, size_t dst_len);
131135int mg_url_decode(const char *src, int src_len, char *dst, int dst_len, int);
136int mg_terminate_ssl(struct mg_connection *c, const char *cert);
137int mg_forward(struct mg_connection *, const char *host, int port, int use_ssl);
132138
139
133140// Templates support
134141struct mg_expansion {
135   const char *keyword;
136   void (*handler)(struct mg_connection *);
142  const char *keyword;
143  void (*handler)(struct mg_connection *);
137144};
138145void mg_template(struct mg_connection *, const char *text,
139               struct mg_expansion *expansions);
146                 struct mg_expansion *expansions);
140147
141148
142149#ifdef __cplusplus
branches/osd/src/lib/web/mongoose.c
r31874r31875
1414//
1515// Alternatively, you can license this library under a commercial
1616// license, as set out in <http://cesanta.com/>.
17//
18// $Date: 2014-09-01 19:53:26 UTC $
1719
1820#ifdef NOEMBED_NET_SKELETON
1921#include "net_skeleton.h"
r31874r31875
4951#define _XOPEN_SOURCE 600       // For flockfile() on Linux
5052#define __STDC_FORMAT_MACROS    // <inttypes.h> wants this for C++
5153#define __STDC_LIMIT_MACROS     // C++ wants that for INT64_MAX
54#ifndef _LARGEFILE_SOURCE
5255#define _LARGEFILE_SOURCE       // Enable fseeko() and ftello() functions
56#endif
5357#define _FILE_OFFSET_BITS 64    // Enable 64-bit file offsets
5458
5559#ifdef _MSC_VER
r31874r31875
101105typedef unsigned __int64 uint64_t;
102106typedef __int64   int64_t;
103107typedef SOCKET sock_t;
108#ifndef S_ISDIR
109#define S_ISDIR(x) ((x) & _S_IFDIR)
110#endif
104111#else
105112#include <errno.h>
106113#include <fcntl.h>
r31874r31875
121128
122129#ifdef NS_ENABLE_DEBUG
123130#define DBG(x) do { printf("%-20s ", __func__); printf x; putchar('\n'); \
124   fflush(stdout); } while(0)
131  fflush(stdout); } while(0)
125132#else
126133#define DBG(x)
127134#endif
r31874r31875
143150#endif // __cplusplus
144151
145152union socket_address {
146   struct sockaddr sa;
147   struct sockaddr_in sin;
153  struct sockaddr sa;
154  struct sockaddr_in sin;
148155#ifdef NS_ENABLE_IPV6
149   struct sockaddr_in6 sin6;
156  struct sockaddr_in6 sin6;
150157#else
151   struct sockaddr sin6;
158  struct sockaddr sin6;
152159#endif
153160};
154161
155162// IO buffers interface
156163struct iobuf {
157   char *buf;
158   size_t len;
159   size_t size;
164  char *buf;
165  size_t len;
166  size_t size;
160167};
161168
162169void iobuf_init(struct iobuf *, size_t initial_size);
r31874r31875
167174// Net skeleton interface
168175// Events. Meaning of event parameter (evp) is given in the comment.
169176enum ns_event {
170   NS_POLL,     // Sent to each connection on each call to ns_server_poll()
171   NS_ACCEPT,   // New connection accept()-ed. union socket_address *remote_addr
172   NS_CONNECT,  // connect() succeeded or failed. int *success_status
173   NS_RECV,     // Data has benn received. int *num_bytes
174   NS_SEND,     // Data has been written to a socket. int *num_bytes
175   NS_CLOSE     // Connection is closed. NULL
177  NS_POLL,     // Sent to each connection on each call to ns_server_poll()
178  NS_ACCEPT,   // New connection accept()-ed. union socket_address *remote_addr
179  NS_CONNECT,  // connect() succeeded or failed. int *success_status
180  NS_RECV,     // Data has benn received. int *num_bytes
181  NS_SEND,     // Data has been written to a socket. int *num_bytes
182  NS_CLOSE     // Connection is closed. NULL
176183};
177184
178185// Callback function (event handler) prototype, must be defined by user.
r31874r31875
181188typedef void (*ns_callback_t)(struct ns_connection *, enum ns_event, void *evp);
182189
183190struct ns_server {
184   void *server_data;
185   sock_t listening_sock;
186   struct ns_connection *active_connections;
187   ns_callback_t callback;
188   SSL_CTX *ssl_ctx;
189   SSL_CTX *client_ssl_ctx;
190   sock_t ctl[2];
191  void *server_data;
192  sock_t listening_sock;
193  struct ns_connection *active_connections;
194  ns_callback_t callback;
195  SSL_CTX *ssl_ctx;
196  SSL_CTX *client_ssl_ctx;
197  const char *hexdump_file;
198  sock_t ctl[2];
191199};
192200
193201struct ns_connection {
194   struct ns_connection *prev, *next;
195   struct ns_server *server;
196   sock_t sock;
197   union socket_address sa;
198   struct iobuf recv_iobuf;
199   struct iobuf send_iobuf;
200   SSL *ssl;
201   void *connection_data;
202   time_t last_io_time;
203   unsigned int flags;
202  struct ns_connection *prev, *next;
203  struct ns_server *server;
204  sock_t sock;
205  union socket_address sa;
206  struct iobuf recv_iobuf;
207  struct iobuf send_iobuf;
208  SSL *ssl;
209  void *connection_data;
210  time_t last_io_time;
211  unsigned int flags;
204212#define NSF_FINISHED_SENDING_DATA   (1 << 0)
205213#define NSF_BUFFER_BUT_DONT_SEND    (1 << 1)
206214#define NSF_SSL_HANDSHAKE_DONE      (1 << 2)
r31874r31875
231239int ns_set_ssl_cert(struct ns_server *, const char *ssl_cert);
232240int ns_set_ssl_ca_cert(struct ns_server *, const char *ssl_ca_cert);
233241struct ns_connection *ns_connect(struct ns_server *, const char *host,
234                           int port, int ssl, void *connection_param);
242                                 int port, int ssl, void *connection_param);
235243
236244int ns_send(struct ns_connection *, const void *buf, int len);
237245int ns_printf(struct ns_connection *, const char *fmt, ...);
r31874r31875
244252void ns_set_close_on_exec(sock_t);
245253void ns_sock_to_str(sock_t sock, char *buf, size_t len, int flags);
246254int ns_hexdump(const void *buf, int len, char *dst, int dst_len);
255int ns_avprintf(char **buf, size_t size, const char *fmt, va_list ap);
247256
248257#ifdef __cplusplus
249258}
r31874r31875
280289#endif
281290
282291struct ctl_msg {
283   ns_callback_t callback;
284   char message[1024 * 8];
292  ns_callback_t callback;
293  char message[1024 * 8];
285294};
286295
287296void iobuf_init(struct iobuf *iobuf, size_t size) {
288   iobuf->len = iobuf->size = 0;
289   iobuf->buf = NULL;
297  iobuf->len = iobuf->size = 0;
298  iobuf->buf = NULL;
290299
291   if (size > 0 && (iobuf->buf = (char *) NS_MALLOC(size)) != NULL) {
292   iobuf->size = size;
293   }
300  if (size > 0 && (iobuf->buf = (char *) NS_MALLOC(size)) != NULL) {
301    iobuf->size = size;
302  }
294303}
295304
296305void iobuf_free(struct iobuf *iobuf) {
297   if (iobuf != NULL) {
298   if (iobuf->buf != NULL) NS_FREE(iobuf->buf);
299   iobuf_init(iobuf, 0);
300   }
306  if (iobuf != NULL) {
307    if (iobuf->buf != NULL) NS_FREE(iobuf->buf);
308    iobuf_init(iobuf, 0);
309  }
301310}
302311
303312size_t iobuf_append(struct iobuf *io, const void *buf, size_t len) {
304   char *p = NULL;
313  char *p = NULL;
305314
306   assert(io != NULL);
307   assert(io->len <= io->size);
315  assert(io != NULL);
316  assert(io->len <= io->size);
308317
309   if (len <= 0) {
310   } else if (io->len + len <= io->size) {
311   memcpy(io->buf + io->len, buf, len);
312   io->len += len;
313   } else if ((p = (char *) NS_REALLOC(io->buf, io->len + len)) != NULL) {
314   io->buf = p;
315   memcpy(io->buf + io->len, buf, len);
316   io->len += len;
317   io->size = io->len;
318   } else {
319   len = 0;
320   }
318  if (len <= 0) {
319  } else if (io->len + len <= io->size) {
320    memcpy(io->buf + io->len, buf, len);
321    io->len += len;
322  } else if ((p = (char *) NS_REALLOC(io->buf, io->len + len)) != NULL) {
323    io->buf = p;
324    memcpy(io->buf + io->len, buf, len);
325    io->len += len;
326    io->size = io->len;
327  } else {
328    len = 0;
329  }
321330
322   return len;
331  return len;
323332}
324333
325334void iobuf_remove(struct iobuf *io, size_t n) {
326   if (n > 0 && n <= io->len) {
327   memmove(io->buf, io->buf + n, io->len - n);
328   io->len -= n;
329   }
335  if (n > 0 && n <= io->len) {
336    memmove(io->buf, io->buf + n, io->len - n);
337    io->len -= n;
338  }
330339}
331340
332341#ifndef NS_DISABLE_THREADS
333342void *ns_start_thread(void *(*f)(void *), void *p) {
334343#ifdef _WIN32
335   return (void *) _beginthread((void (__cdecl *)(void *)) f, 0, p);
344  return (void *) _beginthread((void (__cdecl *)(void *)) f, 0, p);
336345#else
337   pthread_t thread_id = (pthread_t) 0;
338   pthread_attr_t attr;
346  pthread_t thread_id = (pthread_t) 0;
347  pthread_attr_t attr;
339348
340   (void) pthread_attr_init(&attr);
341   (void) pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
349  (void) pthread_attr_init(&attr);
350  (void) pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
342351
343352#if defined(NS_STACK_SIZE) && NS_STACK_SIZE > 1
344   (void) pthread_attr_setstacksize(&attr, NS_STACK_SIZE);
353  (void) pthread_attr_setstacksize(&attr, NS_STACK_SIZE);
345354#endif
346355
347   pthread_create(&thread_id, &attr, f, p);
348   pthread_attr_destroy(&attr);
356  pthread_create(&thread_id, &attr, f, p);
357  pthread_attr_destroy(&attr);
349358
350   return (void *) thread_id;
359  return (void *) thread_id;
351360#endif
352361}
353362#endif  // NS_DISABLE_THREADS
354363
355364static void ns_add_conn(struct ns_server *server, struct ns_connection *c) {
356   c->next = server->active_connections;
357   server->active_connections = c;
358   c->prev = NULL;
359   if (c->next != NULL) c->next->prev = c;
365  c->next = server->active_connections;
366  server->active_connections = c;
367  c->prev = NULL;
368  if (c->next != NULL) c->next->prev = c;
360369}
361370
362371static void ns_remove_conn(struct ns_connection *conn) {
363   if (conn->prev == NULL) conn->server->active_connections = conn->next;
364   if (conn->prev) conn->prev->next = conn->next;
365   if (conn->next) conn->next->prev = conn->prev;
372  if (conn->prev == NULL) conn->server->active_connections = conn->next;
373  if (conn->prev) conn->prev->next = conn->next;
374  if (conn->next) conn->next->prev = conn->prev;
366375}
367376
368377// Print message to buffer. If buffer is large enough to hold the message,
369378// return buffer. If buffer is to small, allocate large enough buffer on heap,
370379// and return allocated buffer.
371static int ns_avprintf(char **buf, size_t size, const char *fmt, va_list ap) {
372   va_list ap_copy;
373   int len;
380int ns_avprintf(char **buf, size_t size, const char *fmt, va_list ap) {
381  va_list ap_copy;
382  int len;
374383
375   va_copy(ap_copy, ap);
376   len = vsnprintf(*buf, size, fmt, ap_copy);
377   va_end(ap_copy);
384  va_copy(ap_copy, ap);
385  len = vsnprintf(*buf, size, fmt, ap_copy);
386  va_end(ap_copy);
378387
379   if (len < 0) {
380   // eCos and Windows are not standard-compliant and return -1 when
381   // the buffer is too small. Keep allocating larger buffers until we
382   // succeed or out of memory.
383   *buf = NULL;
384   while (len < 0) {
385      if (*buf) free(*buf);
386      size *= 2;
387      if ((*buf = (char *) NS_MALLOC(size)) == NULL) break;
388      va_copy(ap_copy, ap);
389      len = vsnprintf(*buf, size, fmt, ap_copy);
390      va_end(ap_copy);
391   }
392   } else if (len > (int) size) {
393   // Standard-compliant code path. Allocate a buffer that is large enough.
394   if ((*buf = (char *) NS_MALLOC(len + 1)) == NULL) {
395      len = -1;
396   } else {
397      va_copy(ap_copy, ap);
398      len = vsnprintf(*buf, len + 1, fmt, ap_copy);
399      va_end(ap_copy);
400   }
401   }
388  if (len < 0) {
389    // eCos and Windows are not standard-compliant and return -1 when
390    // the buffer is too small. Keep allocating larger buffers until we
391    // succeed or out of memory.
392    *buf = NULL;
393    while (len < 0) {
394      if (*buf) free(*buf);
395      size *= 2;
396      if ((*buf = (char *) NS_MALLOC(size)) == NULL) break;
397      va_copy(ap_copy, ap);
398      len = vsnprintf(*buf, size, fmt, ap_copy);
399      va_end(ap_copy);
400    }
401  } else if (len > (int) size) {
402    // Standard-compliant code path. Allocate a buffer that is large enough.
403    if ((*buf = (char *) NS_MALLOC(len + 1)) == NULL) {
404      len = -1;
405    } else {
406      va_copy(ap_copy, ap);
407      len = vsnprintf(*buf, len + 1, fmt, ap_copy);
408      va_end(ap_copy);
409    }
410  }
402411
403   return len;
412  return len;
404413}
405414
406415int ns_vprintf(struct ns_connection *conn, const char *fmt, va_list ap) {
407   char mem[2000], *buf = mem;
408   int len;
416  char mem[2000], *buf = mem;
417  int len;
409418
410   if ((len = ns_avprintf(&buf, sizeof(mem), fmt, ap)) > 0) {
411   iobuf_append(&conn->send_iobuf, buf, len);
412   }
413   if (buf != mem && buf != NULL) {
414   free(buf);
415   }
419  if ((len = ns_avprintf(&buf, sizeof(mem), fmt, ap)) > 0) {
420    iobuf_append(&conn->send_iobuf, buf, len);
421  }
422  if (buf != mem && buf != NULL) {
423    free(buf);
424  }
416425
417   return len;
426  return len;
418427}
419428
420429int ns_printf(struct ns_connection *conn, const char *fmt, ...) {
421   int len;
422   va_list ap;
423   va_start(ap, fmt);
424   len = ns_vprintf(conn, fmt, ap);
425   va_end(ap);
426   return len;
430  int len;
431  va_list ap;
432  va_start(ap, fmt);
433  len = ns_vprintf(conn, fmt, ap);
434  va_end(ap);
435  return len;
427436}
428437
438static void hexdump(struct ns_connection *nc, const char *path,
439                    int num_bytes, enum ns_event ev) {
440  const struct iobuf *io = ev == NS_SEND ? &nc->send_iobuf : &nc->recv_iobuf;
441  FILE *fp;
442  char *buf, src[60], dst[60];
443  int buf_size = num_bytes * 5 + 100;
444
445  if ((fp = fopen(path, "a")) != NULL) {
446    ns_sock_to_str(nc->sock, src, sizeof(src), 3);
447    ns_sock_to_str(nc->sock, dst, sizeof(dst), 7);
448    fprintf(fp, "%lu %p %s %s %s %d\n", (unsigned long) time(NULL),
449            nc->connection_data, src,
450            ev == NS_RECV ? "<-" : ev == NS_SEND ? "->" :
451            ev == NS_ACCEPT ? "<A" : ev == NS_CONNECT ? "C>" : "XX",
452            dst, num_bytes);
453    if (num_bytes > 0 && (buf = (char *) malloc(buf_size)) != NULL) {
454      ns_hexdump(io->buf + (ev == NS_SEND ? 0 : io->len) -
455        (ev == NS_SEND ? 0 : num_bytes), num_bytes, buf, buf_size);
456      fprintf(fp, "%s", buf);
457      free(buf);
458    }
459    fclose(fp);
460  }
461}
462
429463static void ns_call(struct ns_connection *conn, enum ns_event ev, void *p) {
430   if (conn->server->callback) conn->server->callback(conn, ev, p);
464  if (conn->server->hexdump_file != NULL && ev != NS_POLL) {
465    int len = (ev == NS_RECV || ev == NS_SEND) ? * (int *) p : 0;
466    hexdump(conn, conn->server->hexdump_file, len, ev);
467  }
468  if (conn->server->callback) conn->server->callback(conn, ev, p);
431469}
432470
433471static void ns_close_conn(struct ns_connection *conn) {
434   DBG(("%p %d", conn, conn->flags));
435   ns_call(conn, NS_CLOSE, NULL);
436   ns_remove_conn(conn);
437   closesocket(conn->sock);
438   iobuf_free(&conn->recv_iobuf);
439   iobuf_free(&conn->send_iobuf);
472  DBG(("%p %d", conn, conn->flags));
473  ns_call(conn, NS_CLOSE, NULL);
474  ns_remove_conn(conn);
475  closesocket(conn->sock);
476  iobuf_free(&conn->recv_iobuf);
477  iobuf_free(&conn->send_iobuf);
440478#ifdef NS_ENABLE_SSL
441   if (conn->ssl != NULL) {
442   SSL_free(conn->ssl);
443   }
479  if (conn->ssl != NULL) {
480    SSL_free(conn->ssl);
481  }
444482#endif
445   NS_FREE(conn);
483  NS_FREE(conn);
446484}
447485
448486void ns_set_close_on_exec(sock_t sock) {
449487#ifdef _WIN32
450   (void) SetHandleInformation((HANDLE) sock, HANDLE_FLAG_INHERIT, 0);
488  (void) SetHandleInformation((HANDLE) sock, HANDLE_FLAG_INHERIT, 0);
451489#else
452   fcntl(sock, F_SETFD, FD_CLOEXEC);
490  fcntl(sock, F_SETFD, FD_CLOEXEC);
453491#endif
454492}
455493
456494static void ns_set_non_blocking_mode(sock_t sock) {
457495#ifdef _WIN32
458   unsigned long on = 1;
459   ioctlsocket(sock, FIONBIO, &on);
496  unsigned long on = 1;
497  ioctlsocket(sock, FIONBIO, &on);
460498#else
461   int flags = fcntl(sock, F_GETFL, 0);
462   fcntl(sock, F_SETFL, flags | O_NONBLOCK);
499  int flags = fcntl(sock, F_GETFL, 0);
500  fcntl(sock, F_SETFL, flags | O_NONBLOCK);
463501#endif
464502}
465503
466504#ifndef NS_DISABLE_SOCKETPAIR
467505int ns_socketpair2(sock_t sp[2], int sock_type) {
468   union socket_address sa;
469   sock_t sock;
470   socklen_t len = sizeof(sa.sin);
471   int ret = 0;
506  union socket_address sa;
507  sock_t sock;
508  socklen_t len = sizeof(sa.sin);
509  int ret = 0;
472510
473   sp[0] = sp[1] = INVALID_SOCKET;
511  sp[0] = sp[1] = INVALID_SOCKET;
474512
475   (void) memset(&sa, 0, sizeof(sa));
476   sa.sin.sin_family = AF_INET;
477   sa.sin.sin_port = htons(0);
478   sa.sin.sin_addr.s_addr = htonl(0x7f000001);
513  (void) memset(&sa, 0, sizeof(sa));
514  sa.sin.sin_family = AF_INET;
515  sa.sin.sin_port = htons(0);
516  sa.sin.sin_addr.s_addr = htonl(0x7f000001);
479517
480   if ((sock = socket(AF_INET, sock_type, 0)) != INVALID_SOCKET &&
481      !bind(sock, &sa.sa, len) &&
482      (sock_type == SOCK_DGRAM || !listen(sock, 1)) &&
483      !getsockname(sock, &sa.sa, &len) &&
484      (sp[0] = socket(AF_INET, sock_type, 0)) != INVALID_SOCKET &&
485      !connect(sp[0], &sa.sa, len) &&
486      (sock_type == SOCK_STREAM ||
487      (!getsockname(sp[0], &sa.sa, &len) && !connect(sock, &sa.sa, len))) &&
488      (sp[1] = (sock_type == SOCK_DGRAM ? sock :
489            accept(sock, &sa.sa, &len))) != INVALID_SOCKET) {
490   ns_set_close_on_exec(sp[0]);
491   ns_set_close_on_exec(sp[1]);
492   ret = 1;
493   } else {
494   if (sp[0] != INVALID_SOCKET) closesocket(sp[0]);
495   if (sp[1] != INVALID_SOCKET) closesocket(sp[1]);
496   sp[0] = sp[1] = INVALID_SOCKET;
497   }
498   if (sock_type != SOCK_DGRAM) closesocket(sock);
518  if ((sock = socket(AF_INET, sock_type, 0)) != INVALID_SOCKET &&
519      !bind(sock, &sa.sa, len) &&
520      (sock_type == SOCK_DGRAM || !listen(sock, 1)) &&
521      !getsockname(sock, &sa.sa, &len) &&
522      (sp[0] = socket(AF_INET, sock_type, 0)) != INVALID_SOCKET &&
523      !connect(sp[0], &sa.sa, len) &&
524      (sock_type == SOCK_STREAM ||
525       (!getsockname(sp[0], &sa.sa, &len) && !connect(sock, &sa.sa, len))) &&
526      (sp[1] = (sock_type == SOCK_DGRAM ? sock :
527                accept(sock, &sa.sa, &len))) != INVALID_SOCKET) {
528    ns_set_close_on_exec(sp[0]);
529    ns_set_close_on_exec(sp[1]);
530    ret = 1;
531  } else {
532    if (sp[0] != INVALID_SOCKET) closesocket(sp[0]);
533    if (sp[1] != INVALID_SOCKET) closesocket(sp[1]);
534    sp[0] = sp[1] = INVALID_SOCKET;
535  }
536  if (sock_type != SOCK_DGRAM) closesocket(sock);
499537
500   return ret;
538  return ret;
501539}
502540
503541int ns_socketpair(sock_t sp[2]) {
504   return ns_socketpair2(sp, SOCK_STREAM);
542  return ns_socketpair2(sp, SOCK_STREAM);
505543}
506544#endif  // NS_DISABLE_SOCKETPAIR
507545
508546// Valid listening port spec is: [ip_address:]port, e.g. "80", "127.0.0.1:3128"
509547static int ns_parse_port_string(const char *str, union socket_address *sa) {
510   unsigned int a, b, c, d, port;
511   int len = 0;
548  unsigned int a, b, c, d, port;
549  int len = 0;
512550#ifdef NS_ENABLE_IPV6
513   char buf[100];
551  char buf[100];
514552#endif
515553
516   // MacOS needs that. If we do not zero it, subsequent bind() will fail.
517   // Also, all-zeroes in the socket address means binding to all addresses
518   // for both IPv4 and IPv6 (INADDR_ANY and IN6ADDR_ANY_INIT).
519   memset(sa, 0, sizeof(*sa));
520   sa->sin.sin_family = AF_INET;
554  // MacOS needs that. If we do not zero it, subsequent bind() will fail.
555  // Also, all-zeroes in the socket address means binding to all addresses
556  // for both IPv4 and IPv6 (INADDR_ANY and IN6ADDR_ANY_INIT).
557  memset(sa, 0, sizeof(*sa));
558  sa->sin.sin_family = AF_INET;
521559
522   if (sscanf(str, "%u.%u.%u.%u:%u%n", &a, &b, &c, &d, &port, &len) == 5) {
523   // Bind to a specific IPv4 address, e.g. 192.168.1.5:8080
524   sa->sin.sin_addr.s_addr = htonl((a << 24) | (b << 16) | (c << 8) | d);
525   sa->sin.sin_port = htons((uint16_t) port);
560  if (sscanf(str, "%u.%u.%u.%u:%u%n", &a, &b, &c, &d, &port, &len) == 5) {
561    // Bind to a specific IPv4 address, e.g. 192.168.1.5:8080
562    sa->sin.sin_addr.s_addr = htonl((a << 24) | (b << 16) | (c << 8) | d);
563    sa->sin.sin_port = htons((uint16_t) port);
526564#ifdef NS_ENABLE_IPV6
527   } else if (sscanf(str, "[%49[^]]]:%u%n", buf, &port, &len) == 2 &&
528            inet_pton(AF_INET6, buf, &sa->sin6.sin6_addr)) {
529   // IPv6 address, e.g. [3ffe:2a00:100:7031::1]:8080
530   sa->sin6.sin6_family = AF_INET6;
531   sa->sin6.sin6_port = htons((uint16_t) port);
565  } else if (sscanf(str, "[%49[^]]]:%u%n", buf, &port, &len) == 2 &&
566             inet_pton(AF_INET6, buf, &sa->sin6.sin6_addr)) {
567    // IPv6 address, e.g. [3ffe:2a00:100:7031::1]:8080
568    sa->sin6.sin6_family = AF_INET6;
569    sa->sin6.sin6_port = htons((uint16_t) port);
532570#endif
533   } else if (sscanf(str, "%u%n", &port, &len) == 1) {
534   // If only port is specified, bind to IPv4, INADDR_ANY
535   sa->sin.sin_port = htons((uint16_t) port);
536   } else {
537   port = 0;   // Parsing failure. Make port invalid.
538   }
571  } else if (sscanf(str, "%u%n", &port, &len) == 1) {
572    // If only port is specified, bind to IPv4, INADDR_ANY
573    sa->sin.sin_port = htons((uint16_t) port);
574  } else {
575    port = 0;   // Parsing failure. Make port invalid.
576  }
539577
540   return port <= 0xffff && str[len] == '\0';
578  return port <= 0xffff && str[len] == '\0';
541579}
542580
543581// 'sa' must be an initialized address to bind to
544582static sock_t ns_open_listening_socket(union socket_address *sa) {
545   socklen_t len = sizeof(*sa);
546   sock_t sock = INVALID_SOCKET;
583  socklen_t len = sizeof(*sa);
584  sock_t sock = INVALID_SOCKET;
547585#ifndef _WIN32
548   int on = 1;
586  int on = 1;
549587#endif
550588
551   if ((sock = socket(sa->sa.sa_family, SOCK_STREAM, 6)) != INVALID_SOCKET &&
589  if ((sock = socket(sa->sa.sa_family, SOCK_STREAM, 6)) != INVALID_SOCKET &&
552590#ifndef _WIN32
553      // SO_RESUSEADDR is not enabled on Windows because the semantics of
554      // SO_REUSEADDR on UNIX and Windows is different. On Windows,
555      // SO_REUSEADDR allows to bind a socket to a port without error even if
556      // the port is already open by another program. This is not the behavior
557      // SO_REUSEADDR was designed for, and leads to hard-to-track failure
558      // scenarios. Therefore, SO_REUSEADDR was disabled on Windows.
559      !setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, (void *) &on, sizeof(on)) &&
591      // SO_RESUSEADDR is not enabled on Windows because the semantics of
592      // SO_REUSEADDR on UNIX and Windows is different. On Windows,
593      // SO_REUSEADDR allows to bind a socket to a port without error even if
594      // the port is already open by another program. This is not the behavior
595      // SO_REUSEADDR was designed for, and leads to hard-to-track failure
596      // scenarios. Therefore, SO_REUSEADDR was disabled on Windows.
597      !setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, (void *) &on, sizeof(on)) &&
560598#endif
561      !bind(sock, &sa->sa, sa->sa.sa_family == AF_INET ?
562         sizeof(sa->sin) : sizeof(sa->sin6)) &&
563      !listen(sock, SOMAXCONN)) {
564   ns_set_non_blocking_mode(sock);
565   // In case port was set to 0, get the real port number
566   (void) getsockname(sock, &sa->sa, &len);
567   } else if (sock != INVALID_SOCKET) {
568   closesocket(sock);
569   sock = INVALID_SOCKET;
570   }
599      !bind(sock, &sa->sa, sa->sa.sa_family == AF_INET ?
600            sizeof(sa->sin) : sizeof(sa->sin6)) &&
601      !listen(sock, SOMAXCONN)) {
602    ns_set_non_blocking_mode(sock);
603    // In case port was set to 0, get the real port number
604    (void) getsockname(sock, &sa->sa, &len);
605  } else if (sock != INVALID_SOCKET) {
606    closesocket(sock);
607    sock = INVALID_SOCKET;
608  }
571609
572   return sock;
610  return sock;
573611}
574612
575613// Certificate generation script is at
576614// https://github.com/cesanta/net_skeleton/blob/master/examples/gen_certs.sh
577615int ns_set_ssl_ca_cert(struct ns_server *server, const char *cert) {
578616#ifdef NS_ENABLE_SSL
579   STACK_OF(X509_NAME) *list = SSL_load_client_CA_file(cert);
580   if (cert != NULL && server->ssl_ctx != NULL && list != NULL) {
581   SSL_CTX_set_client_CA_list(server->ssl_ctx, list);
582   SSL_CTX_set_verify(server->ssl_ctx, SSL_VERIFY_PEER |
583                  SSL_VERIFY_FAIL_IF_NO_PEER_CERT, NULL);
584   return 0;
585   }
617  STACK_OF(X509_NAME) *list = SSL_load_client_CA_file(cert);
618  if (cert != NULL && server->ssl_ctx != NULL && list != NULL) {
619    SSL_CTX_set_client_CA_list(server->ssl_ctx, list);
620    SSL_CTX_set_verify(server->ssl_ctx, SSL_VERIFY_PEER |
621                       SSL_VERIFY_FAIL_IF_NO_PEER_CERT, NULL);
622    return 0;
623  }
586624#endif
587   return server != NULL && cert == NULL ? 0 : -1;
625  return server != NULL && cert == NULL ? 0 : -1;
588626}
589627
590628int ns_set_ssl_cert(struct ns_server *server, const char *cert) {
591629#ifdef NS_ENABLE_SSL
592   if (cert != NULL &&
593      (server->ssl_ctx = SSL_CTX_new(SSLv23_server_method())) == NULL) {
594   return -1;
595   } else if (SSL_CTX_use_certificate_file(server->ssl_ctx, cert, 1) == 0 ||
596            SSL_CTX_use_PrivateKey_file(server->ssl_ctx, cert, 1) == 0) {
597   return -2;
598   } else {
599   SSL_CTX_use_certificate_chain_file(server->ssl_ctx, cert);
600   return 0;
601   }
630  if (cert != NULL &&
631      (server->ssl_ctx = SSL_CTX_new(SSLv23_server_method())) == NULL) {
632    return -1;
633  } else if (SSL_CTX_use_certificate_file(server->ssl_ctx, cert, 1) == 0 ||
634             SSL_CTX_use_PrivateKey_file(server->ssl_ctx, cert, 1) == 0) {
635    return -2;
636  } else {
637    SSL_CTX_set_mode(server->ssl_ctx, SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER);
638    SSL_CTX_use_certificate_chain_file(server->ssl_ctx, cert);
639    return 0;
640  }
602641#endif
603   return server != NULL && cert == NULL ? 0 : -3;
642  return server != NULL && cert == NULL ? 0 : -3;
604643}
605644
606645int ns_bind(struct ns_server *server, const char *str) {
607   union socket_address sa;
608   ns_parse_port_string(str, &sa);
609   if (server->listening_sock != INVALID_SOCKET) {
610   closesocket(server->listening_sock);
611   }
612   server->listening_sock = ns_open_listening_socket(&sa);
613   return server->listening_sock == INVALID_SOCKET ? -1 :
614   (int) ntohs(sa.sin.sin_port);
646  union socket_address sa;
647  ns_parse_port_string(str, &sa);
648  if (server->listening_sock != INVALID_SOCKET) {
649    closesocket(server->listening_sock);
650  }
651  server->listening_sock = ns_open_listening_socket(&sa);
652  return server->listening_sock == INVALID_SOCKET ? -1 :
653  (int) ntohs(sa.sin.sin_port);
615654}
616655
617656
618657static struct ns_connection *accept_conn(struct ns_server *server) {
619   struct ns_connection *c = NULL;
620   union socket_address sa;
621   socklen_t len = sizeof(sa);
622   sock_t sock = INVALID_SOCKET;
658  struct ns_connection *c = NULL;
659  union socket_address sa;
660  socklen_t len = sizeof(sa);
661  sock_t sock = INVALID_SOCKET;
623662
624   // NOTE(lsm): on Windows, sock is always > FD_SETSIZE
625   if ((sock = accept(server->listening_sock, &sa.sa, &len)) == INVALID_SOCKET) {
626   } else if ((c = (struct ns_connection *) NS_MALLOC(sizeof(*c))) == NULL ||
627            memset(c, 0, sizeof(*c)) == NULL) {
628   closesocket(sock);
663  // NOTE(lsm): on Windows, sock is always > FD_SETSIZE
664  if ((sock = accept(server->listening_sock, &sa.sa, &len)) == INVALID_SOCKET) {
665  } else if ((c = (struct ns_connection *) NS_MALLOC(sizeof(*c))) == NULL ||
666             memset(c, 0, sizeof(*c)) == NULL) {
667    closesocket(sock);
629668#ifdef NS_ENABLE_SSL
630   } else if (server->ssl_ctx != NULL &&
631            ((c->ssl = SSL_new(server->ssl_ctx)) == NULL ||
632            SSL_set_fd(c->ssl, sock) != 1)) {
633   DBG(("SSL error"));
634   closesocket(sock);
635   free(c);
636   c = NULL;
669  } else if (server->ssl_ctx != NULL &&
670             ((c->ssl = SSL_new(server->ssl_ctx)) == NULL ||
671              SSL_set_fd(c->ssl, sock) != 1)) {
672    DBG(("SSL error"));
673    closesocket(sock);
674    free(c);
675    c = NULL;
637676#endif
638   } else {
639   ns_set_close_on_exec(sock);
640   ns_set_non_blocking_mode(sock);
641   c->server = server;
642   c->sock = sock;
643   c->flags |= NSF_ACCEPTED;
677  } else {
678    ns_set_close_on_exec(sock);
679    ns_set_non_blocking_mode(sock);
680    c->server = server;
681    c->sock = sock;
682    c->flags |= NSF_ACCEPTED;
644683
645   ns_add_conn(server, c);
646   ns_call(c, NS_ACCEPT, &sa);
647   DBG(("%p %d %p %p", c, c->sock, c->ssl, server->ssl_ctx));
648   }
684    ns_add_conn(server, c);
685    ns_call(c, NS_ACCEPT, &sa);
686    DBG(("%p %d %p %p", c, c->sock, c->ssl, server->ssl_ctx));
687  }
649688
650   return c;
689  return c;
651690}
652691
653692static int ns_is_error(int n) {
654   return n == 0 ||
655   (n < 0 && errno != EINTR && errno != EINPROGRESS &&
656      errno != EAGAIN && errno != EWOULDBLOCK
693  return n == 0 ||
694    (n < 0 && errno != EINTR && errno != EINPROGRESS &&
695     errno != EAGAIN && errno != EWOULDBLOCK
657696#ifdef _WIN32
658      && WSAGetLastError() != WSAEINTR && WSAGetLastError() != WSAEWOULDBLOCK
697     && WSAGetLastError() != WSAEINTR && WSAGetLastError() != WSAEWOULDBLOCK
659698#endif
660   );
699    );
661700}
662701
663702void ns_sock_to_str(sock_t sock, char *buf, size_t len, int flags) {
664   union socket_address sa;
665   socklen_t slen = sizeof(sa);
703  union socket_address sa;
704  socklen_t slen = sizeof(sa);
666705
667   if (buf != NULL && len > 0) {
668   buf[0] = '\0';
669   memset(&sa, 0, sizeof(sa));
670   if (flags & 4) {
671      getpeername(sock, &sa.sa, &slen);
672   } else {
673      getsockname(sock, &sa.sa, &slen);
674   }
675   if (flags & 1) {
706  if (buf != NULL && len > 0) {
707    buf[0] = '\0';
708    memset(&sa, 0, sizeof(sa));
709    if (flags & 4) {
710      getpeername(sock, &sa.sa, &slen);
711    } else {
712      getsockname(sock, &sa.sa, &slen);
713    }
714    if (flags & 1) {
676715#if defined(NS_ENABLE_IPV6)
677      inet_ntop(sa.sa.sa_family, sa.sa.sa_family == AF_INET ?
678            (void *) &sa.sin.sin_addr :
679            (void *) &sa.sin6.sin6_addr, buf, len);
716      inet_ntop(sa.sa.sa_family, sa.sa.sa_family == AF_INET ?
717                (void *) &sa.sin.sin_addr :
718                (void *) &sa.sin6.sin6_addr, buf, len);
680719#elif defined(_WIN32)
681      // Only Windoze Vista (and newer) have inet_ntop()
682      strncpy(buf, inet_ntoa(sa.sin.sin_addr), len);
720      // Only Windoze Vista (and newer) have inet_ntop()
721      strncpy(buf, inet_ntoa(sa.sin.sin_addr), len);
683722#else
684      inet_ntop(sa.sa.sa_family, (void *) &sa.sin.sin_addr, buf, len);
723      inet_ntop(sa.sa.sa_family, (void *) &sa.sin.sin_addr, buf, len);
685724#endif
686   }
687   if (flags & 2) {
688      snprintf(buf + strlen(buf), len - (strlen(buf) + 1), "%s%d",
689            flags & 1 ? ":" : "", (int) ntohs(sa.sin.sin_port));
690   }
691   }
725    }
726    if (flags & 2) {
727      snprintf(buf + strlen(buf), len - (strlen(buf) + 1), "%s%d",
728               flags & 1 ? ":" : "", (int) ntohs(sa.sin.sin_port));
729    }
730  }
692731}
693732
694733int ns_hexdump(const void *buf, int len, char *dst, int dst_len) {
695   const unsigned char *p = (const unsigned char *) buf;
696   char ascii[17] = "";
697   int i, idx, n = 0;
734  const unsigned char *p = (const unsigned char *) buf;
735  char ascii[17] = "";
736  int i, idx, n = 0;
698737
699   for (i = 0; i < len; i++) {
700   idx = i % 16;
701   if (idx == 0) {
702      if (i > 0) n += snprintf(dst + n, dst_len - n, "  %s\n", ascii);
703      n += snprintf(dst + n, dst_len - n, "%04x ", i);
704   }
705   n += snprintf(dst + n, dst_len - n, " %02x", p[i]);
706   ascii[idx] = p[i] < 0x20 || p[i] > 0x7e ? '.' : p[i];
707   ascii[idx + 1] = '\0';
708   }
738  for (i = 0; i < len; i++) {
739    idx = i % 16;
740    if (idx == 0) {
741      if (i > 0) n += snprintf(dst + n, dst_len - n, "  %s\n", ascii);
742      n += snprintf(dst + n, dst_len - n, "%04x ", i);
743    }
744    n += snprintf(dst + n, dst_len - n, " %02x", p[i]);
745    ascii[idx] = p[i] < 0x20 || p[i] > 0x7e ? '.' : p[i];
746    ascii[idx + 1] = '\0';
747  }
709748
710   while (i++ % 16) n += snprintf(dst + n, dst_len - n, "%s", "   ");
711   n += snprintf(dst + n, dst_len - n, "  %s\n\n", ascii);
749  while (i++ % 16) n += snprintf(dst + n, dst_len - n, "%s", "   ");
750  n += snprintf(dst + n, dst_len - n, "  %s\n\n", ascii);
712751
713   return n;
752  return n;
714753}
715754
755#ifdef NS_ENABLE_SSL
756static int ns_ssl_err(struct ns_connection *conn, int res) {
757  int ssl_err = SSL_get_error(conn->ssl, res);
758  if (ssl_err == SSL_ERROR_WANT_READ) conn->flags |= NSF_WANT_READ;
759  if (ssl_err == SSL_ERROR_WANT_WRITE) conn->flags |= NSF_WANT_WRITE;
760  return ssl_err;
761}
762#endif
763
716764static void ns_read_from_socket(struct ns_connection *conn) {
717   char buf[2048];
718   int n = 0;
765  char buf[2048];
766  int n = 0;
719767
720   if (conn->flags & NSF_CONNECTING) {
721   int ok = 1, ret;
722   socklen_t len = sizeof(ok);
768  if (conn->flags & NSF_CONNECTING) {
769    int ok = 1, ret;
770    socklen_t len = sizeof(ok);
723771
724   ret = getsockopt(conn->sock, SOL_SOCKET, SO_ERROR, (char *) &ok, &len);
725   (void) ret;
772    ret = getsockopt(conn->sock, SOL_SOCKET, SO_ERROR, (char *) &ok, &len);
773    (void) ret;
726774#ifdef NS_ENABLE_SSL
727   if (ret == 0 && ok == 0 && conn->ssl != NULL) {
728      int res = SSL_connect(conn->ssl);
729      int ssl_err = SSL_get_error(conn->ssl, res);
730      DBG(("%p %d wres %d %d", conn, conn->flags, res, ssl_err));
731      if (ssl_err == SSL_ERROR_WANT_READ) conn->flags |= NSF_WANT_READ;
732      if (ssl_err == SSL_ERROR_WANT_WRITE) conn->flags |= NSF_WANT_WRITE;
733      if (res == 1) {
734      conn->flags |= NSF_SSL_HANDSHAKE_DONE;
735      } else if (ssl_err == SSL_ERROR_WANT_READ ||
736               ssl_err == SSL_ERROR_WANT_WRITE) {
737      return; // Call us again
738      } else {
739      ok = 1;
740      }
741   }
775    if (ret == 0 && ok == 0 && conn->ssl != NULL) {
776      int res = SSL_connect(conn->ssl);
777      int ssl_err = ns_ssl_err(conn, res);
778      if (res == 1) {
779        conn->flags |= NSF_SSL_HANDSHAKE_DONE;
780      } else if (ssl_err == SSL_ERROR_WANT_READ ||
781                 ssl_err == SSL_ERROR_WANT_WRITE) {
782        return; // Call us again
783      } else {
784        ok = 1;
785      }
786    }
742787#endif
743   conn->flags &= ~NSF_CONNECTING;
744   DBG(("%p ok=%d", conn, ok));
745   if (ok != 0) {
746      conn->flags |= NSF_CLOSE_IMMEDIATELY;
747   }
748   ns_call(conn, NS_CONNECT, &ok);
749   return;
750   }
788    conn->flags &= ~NSF_CONNECTING;
789    DBG(("%p ok=%d", conn, ok));
790    if (ok != 0) {
791      conn->flags |= NSF_CLOSE_IMMEDIATELY;
792    }
793    ns_call(conn, NS_CONNECT, &ok);
794    return;
795  }
751796
752797#ifdef NS_ENABLE_SSL
753   if (conn->ssl != NULL) {
754   if (conn->flags & NSF_SSL_HANDSHAKE_DONE) {
755      n = SSL_read(conn->ssl, buf, sizeof(buf));
756   } else {
757      int res = SSL_accept(conn->ssl);
758      int ssl_err = SSL_get_error(conn->ssl, res);
759      DBG(("%p %d rres %d %d", conn, conn->flags, res, ssl_err));
760      if (ssl_err == SSL_ERROR_WANT_READ) conn->flags |= NSF_WANT_READ;
761      if (ssl_err == SSL_ERROR_WANT_WRITE) conn->flags |= NSF_WANT_WRITE;
762      if (res == 1) {
763      conn->flags |= NSF_SSL_HANDSHAKE_DONE;
764      } else if (ssl_err == SSL_ERROR_WANT_READ ||
765               ssl_err == SSL_ERROR_WANT_WRITE) {
766      return; // Call us again
767      } else {
768      conn->flags |= NSF_CLOSE_IMMEDIATELY;
769      }
770      return;
771   }
772   } else
798  if (conn->ssl != NULL) {
799    if (conn->flags & NSF_SSL_HANDSHAKE_DONE) {
800      // SSL library may have more bytes ready to read then we ask to read.
801      // Therefore, read in a loop until we read everything. Without the loop,
802      // we skip to the next select() cycle which can just timeout.
803      while ((n = SSL_read(conn->ssl, buf, sizeof(buf))) > 0) {
804        DBG(("%p %d <- %d bytes (SSL)", conn, conn->flags, n));
805        iobuf_append(&conn->recv_iobuf, buf, n);
806        ns_call(conn, NS_RECV, &n);
807      }
808      ns_ssl_err(conn, n);
809    } else {
810      int res = SSL_accept(conn->ssl);
811      int ssl_err = ns_ssl_err(conn, res);
812      if (res == 1) {
813        conn->flags |= NSF_SSL_HANDSHAKE_DONE;
814      } else if (ssl_err == SSL_ERROR_WANT_READ ||
815                 ssl_err == SSL_ERROR_WANT_WRITE) {
816        return; // Call us again
817      } else {
818        conn->flags |= NSF_CLOSE_IMMEDIATELY;
819      }
820      return;
821    }
822  } else
773823#endif
774   {
775   n = recv(conn->sock, buf, sizeof(buf), 0);
776   }
824  {
825    while ((n = recv(conn->sock, buf, sizeof(buf), 0)) > 0) {
826      DBG(("%p %d <- %d bytes (PLAIN)", conn, conn->flags, n));
827      iobuf_append(&conn->recv_iobuf, buf, n);
828      ns_call(conn, NS_RECV, &n);
829    }
830  }
777831
778   DBG(("%p %d <- %d bytes", conn, conn->flags, n));
779
780   if (ns_is_error(n)) {
781   conn->flags |= NSF_CLOSE_IMMEDIATELY;
782   } else if (n > 0) {
783   iobuf_append(&conn->recv_iobuf, buf, n);
784   ns_call(conn, NS_RECV, &n);
785   }
832  if (ns_is_error(n)) {
833    conn->flags |= NSF_CLOSE_IMMEDIATELY;
834  }
786835}
787836
788837static void ns_write_to_socket(struct ns_connection *conn) {
789   struct iobuf *io = &conn->send_iobuf;
790   int n = 0;
838  struct iobuf *io = &conn->send_iobuf;
839  int n = 0;
791840
792841#ifdef NS_ENABLE_SSL
793   if (conn->ssl != NULL) {
794   n = SSL_write(conn->ssl, io->buf, io->len);
795   if (n < 0) {
796      int ssl_err = SSL_get_error(conn->ssl, n);
797      DBG(("%p %d %d", conn, n, ssl_err));
798      if (ssl_err == 2 || ssl_err == 3) {
799      return; // Call us again
800      } else {
801      conn->flags |= NSF_CLOSE_IMMEDIATELY;
802      }
803   }
804   } else
842  if (conn->ssl != NULL) {
843    n = SSL_write(conn->ssl, io->buf, io->len);
844    if (n <= 0) {
845      int ssl_err = ns_ssl_err(conn, n);
846      if (ssl_err == SSL_ERROR_WANT_READ || ssl_err == SSL_ERROR_WANT_WRITE) {
847        return; // Call us again
848      } else {
849        conn->flags |= NSF_CLOSE_IMMEDIATELY;
850      }
851    }
852  } else
805853#endif
806   { n = send(conn->sock, io->buf, io->len, 0); }
854  { n = send(conn->sock, io->buf, io->len, 0); }
807855
808   DBG(("%p %d -> %d bytes", conn, conn->flags, n));
856  DBG(("%p %d -> %d bytes", conn, conn->flags, n));
809857
810   ns_call(conn, NS_SEND, &n);
811   if (ns_is_error(n)) {
812   conn->flags |= NSF_CLOSE_IMMEDIATELY;
813   } else if (n > 0) {
814   iobuf_remove(io, n);
815   }
816
817   if (io->len == 0 && (conn->flags & NSF_FINISHED_SENDING_DATA)) {
818   conn->flags |= NSF_CLOSE_IMMEDIATELY;
819   }
858  ns_call(conn, NS_SEND, &n);
859  if (ns_is_error(n)) {
860    conn->flags |= NSF_CLOSE_IMMEDIATELY;
861  } else if (n > 0) {
862    iobuf_remove(io, n);
863  }
820864}
821865
822866int ns_send(struct ns_connection *conn, const void *buf, int len) {
823   return iobuf_append(&conn->send_iobuf, buf, len);
867  return iobuf_append(&conn->send_iobuf, buf, len);
824868}
825869
826870static void ns_add_to_set(sock_t sock, fd_set *set, sock_t *max_fd) {
827   if (sock != INVALID_SOCKET) {
828   FD_SET(sock, set);
829   if (*max_fd == INVALID_SOCKET || sock > *max_fd) {
830      *max_fd = sock;
831   }
832   }
871  if (sock != INVALID_SOCKET) {
872    FD_SET(sock, set);
873    if (*max_fd == INVALID_SOCKET || sock > *max_fd) {
874      *max_fd = sock;
875    }
876  }
833877}
834878
835879int ns_server_poll(struct ns_server *server, int milli) {
836   struct ns_connection *conn, *tmp_conn;
837   struct timeval tv;
838   fd_set read_set, write_set;
839   int num_active_connections = 0;
840   sock_t max_fd = INVALID_SOCKET;
841   time_t current_time = time(NULL);
880  struct ns_connection *conn, *tmp_conn;
881  struct timeval tv;
882  fd_set read_set, write_set;
883  int num_active_connections = 0;
884  sock_t max_fd = INVALID_SOCKET;
885  time_t current_time = time(NULL);
842886
843   if (server->listening_sock == INVALID_SOCKET &&
844      server->active_connections == NULL) return 0;
887  if (server->listening_sock == INVALID_SOCKET &&
888      server->active_connections == NULL) return 0;
845889
846   FD_ZERO(&read_set);
847   FD_ZERO(&write_set);
848   ns_add_to_set(server->listening_sock, &read_set, &max_fd);
849   ns_add_to_set(server->ctl[1], &read_set, &max_fd);
890  FD_ZERO(&read_set);
891  FD_ZERO(&write_set);
892  ns_add_to_set(server->listening_sock, &read_set, &max_fd);
893  ns_add_to_set(server->ctl[1], &read_set, &max_fd);
850894
851   for (conn = server->active_connections; conn != NULL; conn = tmp_conn) {
852   tmp_conn = conn->next;
853   ns_call(conn, NS_POLL, &current_time);
854   if (!(conn->flags & NSF_WANT_WRITE)) {
855      //DBG(("%p read_set", conn));
856      ns_add_to_set(conn->sock, &read_set, &max_fd);
857   }
858   if (((conn->flags & NSF_CONNECTING) && !(conn->flags & NSF_WANT_READ)) ||
859      (conn->send_iobuf.len > 0 && !(conn->flags & NSF_CONNECTING) &&
860         !(conn->flags & NSF_BUFFER_BUT_DONT_SEND))) {
861      //DBG(("%p write_set", conn));
862      ns_add_to_set(conn->sock, &write_set, &max_fd);
863   }
864   if (conn->flags & NSF_CLOSE_IMMEDIATELY) {
865      ns_close_conn(conn);
866   }
867   }
895  for (conn = server->active_connections; conn != NULL; conn = tmp_conn) {
896    tmp_conn = conn->next;
897    ns_call(conn, NS_POLL, &current_time);
898    if (!(conn->flags & NSF_WANT_WRITE)) {
899      //DBG(("%p read_set", conn));
900      ns_add_to_set(conn->sock, &read_set, &max_fd);
901    }
902    if (((conn->flags & NSF_CONNECTING) && !(conn->flags & NSF_WANT_READ)) ||
903        (conn->send_iobuf.len > 0 && !(conn->flags & NSF_CONNECTING) &&
904         !(conn->flags & NSF_BUFFER_BUT_DONT_SEND))) {
905      //DBG(("%p write_set", conn));
906      ns_add_to_set(conn->sock, &write_set, &max_fd);
907    }
908    if (conn->flags & NSF_CLOSE_IMMEDIATELY) {
909      ns_close_conn(conn);
910    }
911  }
868912
869   tv.tv_sec = milli / 1000;
870   tv.tv_usec = (milli % 1000) * 1000;
913  tv.tv_sec = milli / 1000;
914  tv.tv_usec = (milli % 1000) * 1000;
871915
872   if (select((int) max_fd + 1, &read_set, &write_set, NULL, &tv) > 0) {
873   // select() might have been waiting for a long time, reset current_time
874   // now to prevent last_io_time being set to the past.
875   current_time = time(NULL);
916  if (select((int) max_fd + 1, &read_set, &write_set, NULL, &tv) > 0) {
917    // select() might have been waiting for a long time, reset current_time
918    // now to prevent last_io_time being set to the past.
919    current_time = time(NULL);
876920
877   // Accept new connections
878   if (server->listening_sock != INVALID_SOCKET &&
879      FD_ISSET(server->listening_sock, &read_set)) {
880      // We're not looping here, and accepting just one connection at
881      // a time. The reason is that eCos does not respect non-blocking
882      // flag on a listening socket and hangs in a loop.
883      if ((conn = accept_conn(server)) != NULL) {
884      conn->last_io_time = current_time;
885      }
886   }
921    // Accept new connections
922    if (server->listening_sock != INVALID_SOCKET &&
923        FD_ISSET(server->listening_sock, &read_set)) {
924      // We're not looping here, and accepting just one connection at
925      // a time. The reason is that eCos does not respect non-blocking
926      // flag on a listening socket and hangs in a loop.
927      if ((conn = accept_conn(server)) != NULL) {
928        conn->last_io_time = current_time;
929      }
930    }
887931
888   // Read wakeup messages
889   if (server->ctl[1] != INVALID_SOCKET &&
890      FD_ISSET(server->ctl[1], &read_set)) {
891      struct ctl_msg ctl_msg;
892      int len = recv(server->ctl[1], (char *) &ctl_msg, sizeof(ctl_msg), 0);
893      send(server->ctl[1], ctl_msg.message, 1, 0);
894      if (len >= (int) sizeof(ctl_msg.callback) && ctl_msg.callback != NULL) {
895      ns_iterate(server, ctl_msg.callback, ctl_msg.message);
896      }
897   }
932    // Read wakeup messages
933    if (server->ctl[1] != INVALID_SOCKET &&
934        FD_ISSET(server->ctl[1], &read_set)) {
935      struct ctl_msg ctl_msg;
936      int len = recv(server->ctl[1], (char *) &ctl_msg, sizeof(ctl_msg), 0);
937      send(server->ctl[1], ctl_msg.message, 1, 0);
938      if (len >= (int) sizeof(ctl_msg.callback) && ctl_msg.callback != NULL) {
939        ns_iterate(server, ctl_msg.callback, ctl_msg.message);
940      }
941    }
898942
899   for (conn = server->active_connections; conn != NULL; conn = tmp_conn) {
900      tmp_conn = conn->next;
901      if (FD_ISSET(conn->sock, &read_set)) {
902      conn->last_io_time = current_time;
903      ns_read_from_socket(conn);
904      }
905      if (FD_ISSET(conn->sock, &write_set)) {
906      if (conn->flags & NSF_CONNECTING) {
907         ns_read_from_socket(conn);
908      } else if (!(conn->flags & NSF_BUFFER_BUT_DONT_SEND)) {
909         conn->last_io_time = current_time;
910         ns_write_to_socket(conn);
911      }
912      }
913   }
914   }
943    for (conn = server->active_connections; conn != NULL; conn = tmp_conn) {
944      tmp_conn = conn->next;
945      if (FD_ISSET(conn->sock, &read_set)) {
946        conn->last_io_time = current_time;
947        ns_read_from_socket(conn);
948      }
949      if (FD_ISSET(conn->sock, &write_set)) {
950        if (conn->flags & NSF_CONNECTING) {
951          ns_read_from_socket(conn);
952        } else if (!(conn->flags & NSF_BUFFER_BUT_DONT_SEND)) {
953          conn->last_io_time = current_time;
954          ns_write_to_socket(conn);
955        }
956      }
957    }
958  }
915959
916   for (conn = server->active_connections; conn != NULL; conn = tmp_conn) {
917   tmp_conn = conn->next;
918   num_active_connections++;
919   if (conn->flags & NSF_CLOSE_IMMEDIATELY) {
920      ns_close_conn(conn);
921   }
922   }
923   //DBG(("%d active connections", num_active_connections));
960  for (conn = server->active_connections; conn != NULL; conn = tmp_conn) {
961    tmp_conn = conn->next;
962    num_active_connections++;
963    if ((conn->flags & NSF_CLOSE_IMMEDIATELY) ||
964        (conn->send_iobuf.len == 0 &&
965          (conn->flags & NSF_FINISHED_SENDING_DATA))) {
966      ns_close_conn(conn);
967    }
968  }
969  //DBG(("%d active connections", num_active_connections));
924970
925   return num_active_connections;
971  return num_active_connections;
926972}
927973
928974struct ns_connection *ns_connect(struct ns_server *server, const char *host,
929                           int port, int use_ssl, void *param) {
930   sock_t sock = INVALID_SOCKET;
931   struct sockaddr_in sin;
932   struct hostent *he = NULL;
933   struct ns_connection *conn = NULL;
934   int connect_ret_val;
975                                 int port, int use_ssl, void *param) {
976  sock_t sock = INVALID_SOCKET;
977  struct sockaddr_in sin;
978  struct hostent *he = NULL;
979  struct ns_connection *conn = NULL;
980  int connect_ret_val;
935981
936   (void) use_ssl;
982  (void) use_ssl;
937983
938   if (host == NULL || (he = gethostbyname(host)) == NULL ||
939      (sock = socket(AF_INET, SOCK_STREAM, 0)) == INVALID_SOCKET) {
940   DBG(("gethostbyname(%s) failed: %s", host, strerror(errno)));
941   return NULL;
942   }
984  if (host == NULL || (he = gethostbyname(host)) == NULL ||
985      (sock = socket(AF_INET, SOCK_STREAM, 0)) == INVALID_SOCKET) {
986    DBG(("gethostbyname(%s) failed: %s", host, strerror(errno)));
987    return NULL;
988  }
943989
944   sin.sin_family = AF_INET;
945   sin.sin_port = htons((uint16_t) port);
946   sin.sin_addr = * (struct in_addr *) he->h_addr_list[0];
947   ns_set_non_blocking_mode(sock);
990  sin.sin_family = AF_INET;
991  sin.sin_port = htons((uint16_t) port);
992  sin.sin_addr = * (struct in_addr *) he->h_addr_list[0];
993  ns_set_non_blocking_mode(sock);
948994
949   connect_ret_val = connect(sock, (struct sockaddr *) &sin, sizeof(sin));
950   if (ns_is_error(connect_ret_val)) {
951   closesocket(sock);
952   return NULL;
953   } else if ((conn = (struct ns_connection *)
954            NS_MALLOC(sizeof(*conn))) == NULL) {
955   closesocket(sock);
956   return NULL;
957   }
995  connect_ret_val = connect(sock, (struct sockaddr *) &sin, sizeof(sin));
996  if (ns_is_error(connect_ret_val)) {
997    closesocket(sock);
998    return NULL;
999  } else if ((conn = (struct ns_connection *)
1000              NS_MALLOC(sizeof(*conn))) == NULL) {
1001    closesocket(sock);
1002    return NULL;
1003  }
9581004
959   memset(conn, 0, sizeof(*conn));
960   conn->server = server;
961   conn->sock = sock;
962   conn->connection_data = param;
963   conn->flags = NSF_CONNECTING;
964   conn->last_io_time = time(NULL);
1005  memset(conn, 0, sizeof(*conn));
1006  conn->server = server;
1007  conn->sock = sock;
1008  conn->connection_data = param;
1009  conn->flags = NSF_CONNECTING;
1010  conn->last_io_time = time(NULL);
9651011
9661012#ifdef NS_ENABLE_SSL
967   if (use_ssl &&
968      (conn->ssl = SSL_new(server->client_ssl_ctx)) != NULL) {
969   SSL_set_fd(conn->ssl, sock);
970   }
1013  if (use_ssl &&
1014      (conn->ssl = SSL_new(server->client_ssl_ctx)) != NULL) {
1015    SSL_set_fd(conn->ssl, sock);
1016  }
9711017#endif
9721018
973   ns_add_conn(server, conn);
974   DBG(("%p %s:%d %d %p", conn, host, port, conn->sock, conn->ssl));
1019  ns_add_conn(server, conn);
1020  DBG(("%p %s:%d %d %p", conn, host, port, conn->sock, conn->ssl));
9751021
976   return conn;
1022  return conn;
9771023}
9781024
9791025struct ns_connection *ns_add_sock(struct ns_server *s, sock_t sock, void *p) {
980   struct ns_connection *conn;
981   if ((conn = (struct ns_connection *) NS_MALLOC(sizeof(*conn))) != NULL) {
982   memset(conn, 0, sizeof(*conn));
983   ns_set_non_blocking_mode(sock);
984   conn->sock = sock;
985   conn->connection_data = p;
986   conn->server = s;
987   conn->last_io_time = time(NULL);
988   ns_add_conn(s, conn);
989   DBG(("%p %d", conn, sock));
990   }
991   return conn;
1026  struct ns_connection *conn;
1027  if ((conn = (struct ns_connection *) NS_MALLOC(sizeof(*conn))) != NULL) {
1028    memset(conn, 0, sizeof(*conn));
1029    ns_set_non_blocking_mode(sock);
1030    conn->sock = sock;
1031    conn->connection_data = p;
1032    conn->server = s;
1033    conn->last_io_time = time(NULL);
1034    ns_add_conn(s, conn);
1035    DBG(("%p %d", conn, sock));
1036  }
1037  return conn;
9921038}
9931039
9941040struct ns_connection *ns_next(struct ns_server *s, struct ns_connection *conn) {
995   return conn == NULL ? s->active_connections : conn->next;
1041  return conn == NULL ? s->active_connections : conn->next;
9961042}
9971043
9981044void ns_iterate(struct ns_server *server, ns_callback_t cb, void *param) {
999   struct ns_connection *conn, *tmp_conn;
1045  struct ns_connection *conn, *tmp_conn;
10001046
1001   for (conn = server->active_connections; conn != NULL; conn = tmp_conn) {
1002   tmp_conn = conn->next;
1003   cb(conn, NS_POLL, param);
1004   }
1047  for (conn = server->active_connections; conn != NULL; conn = tmp_conn) {
1048    tmp_conn = conn->next;
1049    cb(conn, NS_POLL, param);
1050  }
10051051}
10061052
10071053void ns_server_wakeup_ex(struct ns_server *server, ns_callback_t cb,
1008                     void *data, size_t len) {
1009   struct ctl_msg ctl_msg;
1010   if (server->ctl[0] != INVALID_SOCKET && data != NULL &&
1011      len < sizeof(ctl_msg.message)) {
1012   ctl_msg.callback = cb;
1013   memcpy(ctl_msg.message, data, len);
1014   send(server->ctl[0], (char *) &ctl_msg,
1015         offsetof(struct ctl_msg, message) + len, 0);
1016   recv(server->ctl[0], (char *) &len, 1, 0);
1017   }
1054                         void *data, size_t len) {
1055  struct ctl_msg ctl_msg;
1056  if (server->ctl[0] != INVALID_SOCKET && data != NULL &&
1057      len < sizeof(ctl_msg.message)) {
1058    ctl_msg.callback = cb;
1059    memcpy(ctl_msg.message, data, len);
1060    send(server->ctl[0], (char *) &ctl_msg,
1061         offsetof(struct ctl_msg, message) + len, 0);
1062    recv(server->ctl[0], (char *) &len, 1, 0);
1063  }
10181064}
10191065
10201066void ns_server_wakeup(struct ns_server *server) {
1021   ns_server_wakeup_ex(server, NULL, (void *) "", 0);
1067  ns_server_wakeup_ex(server, NULL, (void *) "", 0);
10221068}
10231069
10241070void ns_server_init(struct ns_server *s, void *server_data, ns_callback_t cb) {
1025   memset(s, 0, sizeof(*s));
1026   s->listening_sock = s->ctl[0] = s->ctl[1] = INVALID_SOCKET;
1027   s->server_data = server_data;
1028   s->callback = cb;
1071  memset(s, 0, sizeof(*s));
1072  s->listening_sock = s->ctl[0] = s->ctl[1] = INVALID_SOCKET;
1073  s->server_data = server_data;
1074  s->callback = cb;
10291075
10301076#ifdef _WIN32
1031   { WSADATA data; WSAStartup(MAKEWORD(2, 2), &data); }
1077  { WSADATA data; WSAStartup(MAKEWORD(2, 2), &data); }
10321078#else
1033   // Ignore SIGPIPE signal, so if client cancels the request, it
1034   // won't kill the whole process.
1035   signal(SIGPIPE, SIG_IGN);
1079  // Ignore SIGPIPE signal, so if client cancels the request, it
1080  // won't kill the whole process.
1081  signal(SIGPIPE, SIG_IGN);
10361082#endif
10371083
10381084#ifndef NS_DISABLE_SOCKETPAIR
1039   do {
1040   ns_socketpair2(s->ctl, SOCK_DGRAM);
1041   } while (s->ctl[0] == INVALID_SOCKET);
1085  do {
1086    ns_socketpair2(s->ctl, SOCK_DGRAM);
1087  } while (s->ctl[0] == INVALID_SOCKET);
10421088#endif
10431089
10441090#ifdef NS_ENABLE_SSL
1045   SSL_library_init();
1046   s->client_ssl_ctx = SSL_CTX_new(SSLv23_client_method());
1091  {static int init_done; if (!init_done) { SSL_library_init(); init_done++; }}
1092  s->client_ssl_ctx = SSL_CTX_new(SSLv23_client_method());
10471093#endif
10481094}
10491095
10501096void ns_server_free(struct ns_server *s) {
1051   struct ns_connection *conn, *tmp_conn;
1097  struct ns_connection *conn, *tmp_conn;
10521098
1053   DBG(("%p", s));
1054   if (s == NULL) return;
1055   // Do one last poll, see https://github.com/cesanta/mongoose/issues/286
1056   ns_server_poll(s, 0);
1099  DBG(("%p", s));
1100  if (s == NULL) return;
1101  // Do one last poll, see https://github.com/cesanta/mongoose/issues/286
1102  ns_server_poll(s, 0);
10571103
1058   if (s->listening_sock != INVALID_SOCKET) closesocket(s->listening_sock);
1059   if (s->ctl[0] != INVALID_SOCKET) closesocket(s->ctl[0]);
1060   if (s->ctl[1] != INVALID_SOCKET) closesocket(s->ctl[1]);
1061   s->listening_sock = s->ctl[0] = s->ctl[1] = INVALID_SOCKET;
1104  if (s->listening_sock != INVALID_SOCKET) closesocket(s->listening_sock);
1105  if (s->ctl[0] != INVALID_SOCKET) closesocket(s->ctl[0]);
1106  if (s->ctl[1] != INVALID_SOCKET) closesocket(s->ctl[1]);
1107  s->listening_sock = s->ctl[0] = s->ctl[1] = INVALID_SOCKET;
10621108
1063   for (conn = s->active_connections; conn != NULL; conn = tmp_conn) {
1064   tmp_conn = conn->next;
1065   ns_close_conn(conn);
1066   }
1109  for (conn = s->active_connections; conn != NULL; conn = tmp_conn) {
1110    tmp_conn = conn->next;
1111    ns_close_conn(conn);
1112  }
10671113
10681114#ifdef NS_ENABLE_SSL
1069   if (s->ssl_ctx != NULL) SSL_CTX_free(s->ssl_ctx);
1070   if (s->client_ssl_ctx != NULL) SSL_CTX_free(s->client_ssl_ctx);
1071   s->ssl_ctx = s->client_ssl_ctx = NULL;
1115  if (s->ssl_ctx != NULL) SSL_CTX_free(s->ssl_ctx);
1116  if (s->client_ssl_ctx != NULL) SSL_CTX_free(s->client_ssl_ctx);
1117  s->ssl_ctx = s->client_ssl_ctx = NULL;
10721118#endif
10731119}
10741120// net_skeleton end
r31874r31875
11061152#define STR(x) STRX(x)
11071153#define __func__ __FILE__ ":" STR(__LINE__)
11081154#endif
1109#define INT64_FMT  "I64d"
1155/* MINGW has adopted the MSVC formatting for 64-bit ints as of gcc 4.4 till 4.8*/
1156#if (defined(__MINGW32__) && (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 4 && __GNUC_MINOR__ < 8))) || defined(_MSC_VER)
1157#define INT64_FMT   "I64d"
1158#else
1159#define INT64_FMT   "lld"
1160#endif
11101161#define stat(x, y) mg_stat((x), (y))
11111162#define fopen(x, y) mg_fopen((x), (y))
11121163#define open(x, y) mg_open((x), (y))
r31874r31875
11501201#endif
11511202
11521203#ifndef MONGOOSE_IDLE_TIMEOUT_SECONDS
1153#define MONGOOSE_IDLE_TIMEOUT_SECONDS 30
1204#define MONGOOSE_IDLE_TIMEOUT_SECONDS 300
11541205#endif
11551206
1156#ifdef MONGOOSE_NO_SOCKETPAIR
1207#ifdef NS_DISABLE_SOCKETPAIR
11571208#define MONGOOSE_NO_CGI
11581209#endif
11591210
r31874r31875
11681219#endif
11691220
11701221struct vec {
1171   const char *ptr;
1172   int len;
1222  const char *ptr;
1223  int len;
11731224};
11741225
11751226// For directory listing and WevDAV support
11761227struct dir_entry {
1177   struct connection *conn;
1178   char *file_name;
1179   file_stat_t st;
1228  struct connection *conn;
1229  char *file_name;
1230  file_stat_t st;
11801231};
11811232
11821233// NOTE(lsm): this enum shoulds be in sync with the config_options.
11831234enum {
1184   ACCESS_CONTROL_LIST,
1235  ACCESS_CONTROL_LIST,
11851236#ifndef MONGOOSE_NO_FILESYSTEM
1186   ACCESS_LOG_FILE,
1237  ACCESS_LOG_FILE,
11871238#ifndef MONGOOSE_NO_AUTH
1188   AUTH_DOMAIN,
1239  AUTH_DOMAIN,
11891240#endif
11901241#ifndef MONGOOSE_NO_CGI
1191   CGI_INTERPRETER,
1192   CGI_PATTERN,
1242  CGI_INTERPRETER,
1243  CGI_PATTERN,
11931244#endif
1194   DAV_AUTH_FILE,
1195   DOCUMENT_ROOT,
1245  DAV_AUTH_FILE,
1246  DOCUMENT_ROOT,
11961247#ifndef MONGOOSE_NO_DIRECTORY_LISTING
1197   ENABLE_DIRECTORY_LISTING,
1248  ENABLE_DIRECTORY_LISTING,
11981249#endif
11991250#endif
1200   EXTRA_MIME_TYPES,
1251  ENABLE_PROXY,
1252  EXTRA_MIME_TYPES,
12011253#if !defined(MONGOOSE_NO_FILESYSTEM) && !defined(MONGOOSE_NO_AUTH)
1202   GLOBAL_AUTH_FILE,
1254  GLOBAL_AUTH_FILE,
12031255#endif
12041256#ifndef MONGOOSE_NO_FILESYSTEM
1205   HIDE_FILES_PATTERN,
1206   HEXDUMP_FILE,
1207   INDEX_FILES,
1257  HIDE_FILES_PATTERN,
1258  HEXDUMP_FILE,
1259  INDEX_FILES,
12081260#endif
1209   LISTENING_PORT,
1261  LISTENING_PORT,
12101262#ifndef _WIN32
1211   RUN_AS_USER,
1263  RUN_AS_USER,
12121264#endif
12131265#ifndef MONGOOSE_NO_SSI
1214   SSI_PATTERN,
1266  SSI_PATTERN,
12151267#endif
12161268#ifdef NS_ENABLE_SSL
1217   SSL_CERTIFICATE,
1218   SSL_CA_CERTIFICATE,
1219   SSL_MITM_CERTS,
1269  SSL_CERTIFICATE,
1270  SSL_CA_CERTIFICATE,
1271  SSL_MITM_CERTS,
12201272#endif
1221   URL_REWRITES,
1222   NUM_OPTIONS
1273  URL_REWRITES,
1274  NUM_OPTIONS
12231275};
12241276
12251277static const char *static_config_options[] = {
1226   "access_control_list", NULL,
1278  "access_control_list", NULL,
12271279#ifndef MONGOOSE_NO_FILESYSTEM
1228   "access_log_file", NULL,
1280  "access_log_file", NULL,
12291281#ifndef MONGOOSE_NO_AUTH
1230   "auth_domain", "mydomain.com",
1282  "auth_domain", "mydomain.com",
12311283#endif
12321284#ifndef MONGOOSE_NO_CGI
1233   "cgi_interpreter", NULL,
1234   "cgi_pattern", DEFAULT_CGI_PATTERN,
1285  "cgi_interpreter", NULL,
1286  "cgi_pattern", DEFAULT_CGI_PATTERN,
12351287#endif
1236   "dav_auth_file", NULL,
1237   "document_root",  NULL,
1288  "dav_auth_file", NULL,
1289  "document_root",  NULL,
12381290#ifndef MONGOOSE_NO_DIRECTORY_LISTING
1239   "enable_directory_listing", "yes",
1291  "enable_directory_listing", "yes",
12401292#endif
12411293#endif
1242   "extra_mime_types", NULL,
1294  "enable_proxy", NULL,
1295  "extra_mime_types", NULL,
12431296#if !defined(MONGOOSE_NO_FILESYSTEM) && !defined(MONGOOSE_NO_AUTH)
1244   "global_auth_file", NULL,
1297  "global_auth_file", NULL,
12451298#endif
12461299#ifndef MONGOOSE_NO_FILESYSTEM
1247   "hide_files_patterns", NULL,
1248   "hexdump_file", NULL,
1249   "index_files","index.html,index.htm,index.shtml,index.cgi,index.php,index.lp",
1300  "hide_files_patterns", NULL,
1301  "hexdump_file", NULL,
1302  "index_files","index.html,index.htm,index.shtml,index.cgi,index.php,index.lp",
12501303#endif
1251   "listening_port", NULL,
1304  "listening_port", NULL,
12521305#ifndef _WIN32
1253   "run_as_user", NULL,
1306  "run_as_user", NULL,
12541307#endif
12551308#ifndef MONGOOSE_NO_SSI
1256   "ssi_pattern", "**.shtml$|**.shtm$",
1309  "ssi_pattern", "**.shtml$|**.shtm$",
12571310#endif
12581311#ifdef NS_ENABLE_SSL
1259   "ssl_certificate", NULL,
1260   "ssl_ca_certificate", NULL,
1261   "ssl_mitm_certs", NULL,
1312  "ssl_certificate", NULL,
1313  "ssl_ca_certificate", NULL,
1314  "ssl_mitm_certs", NULL,
12621315#endif
1263   "url_rewrites", NULL,
1264   NULL
1316  "url_rewrites", NULL,
1317  NULL
12651318};
12661319
12671320struct mg_server {
1268   struct ns_server ns_server;
1269   union socket_address lsa;   // Listening socket address
1270   mg_handler_t event_handler;
1271   char *config_options[NUM_OPTIONS];
1321  struct ns_server ns_server;
1322  union socket_address lsa;   // Listening socket address
1323  mg_handler_t event_handler;
1324  char *config_options[NUM_OPTIONS];
12721325};
12731326
12741327// Local endpoint representation
12751328union endpoint {
1276   int fd;                     // Opened regular local file
1277   struct ns_connection *nc;   // CGI or proxy->target connection
1329  int fd;                     // Opened regular local file
1330  struct ns_connection *nc;   // CGI or proxy->target connection
12781331};
12791332
12801333enum endpoint_type {
1281   EP_NONE, EP_FILE, EP_CGI, EP_USER, EP_PUT, EP_CLIENT, EP_PROXY
1334 EP_NONE, EP_FILE, EP_CGI, EP_USER, EP_PUT, EP_CLIENT, EP_PROXY
12821335};
12831336
12841337#define MG_HEADERS_SENT NSF_USER_1
12851338#define MG_LONG_RUNNING NSF_USER_2
12861339#define MG_CGI_CONN NSF_USER_3
12871340#define MG_PROXY_CONN NSF_USER_4
1341#define MG_PROXY_DONT_PARSE NSF_USER_5
12881342
12891343struct connection {
1290   struct ns_connection *ns_conn;  // NOTE(lsm): main.c depends on this order
1291   struct mg_connection mg_conn;
1292   struct mg_server *server;
1293   union endpoint endpoint;
1294   enum endpoint_type endpoint_type;
1295   char *path_info;
1296   char *request;
1297   int64_t num_bytes_sent; // Total number of bytes sent
1298   int64_t cl;             // Reply content length, for Range support
1299   int request_len;  // Request length, including last \r\n after last header
1344  struct ns_connection *ns_conn;  // NOTE(lsm): main.c depends on this order
1345  struct mg_connection mg_conn;
1346  struct mg_server *server;
1347  union endpoint endpoint;
1348  enum endpoint_type endpoint_type;
1349  char *path_info;
1350  char *request;
1351  int64_t num_bytes_recv; // Total number of bytes received
1352  int64_t cl;             // Reply content length, for Range support
1353  int request_len;  // Request length, including last \r\n after last header
13001354};
13011355
13021356#define MG_CONN_2_CONN(c) ((struct connection *) ((char *) (c) - \
1303   offsetof(struct connection, mg_conn)))
1357  offsetof(struct connection, mg_conn)))
13041358
13051359static void open_local_endpoint(struct connection *conn, int skip_user);
13061360static void close_local_endpoint(struct connection *conn);
13071361
13081362static const struct {
1309   const char *extension;
1310   size_t ext_len;
1311   const char *mime_type;
1363  const char *extension;
1364  size_t ext_len;
1365  const char *mime_type;
13121366} static_builtin_mime_types[] = {
1313   {".html", 5, "text/html"},
1314   {".htm", 4, "text/html"},
1315   {".shtm", 5, "text/html"},
1316   {".shtml", 6, "text/html"},
1317   {".css", 4, "text/css"},
1318   {".js",  3, "application/x-javascript"},
1319   {".ico", 4, "image/x-icon"},
1320   {".gif", 4, "image/gif"},
1321   {".jpg", 4, "image/jpeg"},
1322   {".jpeg", 5, "image/jpeg"},
1323   {".png", 4, "image/png"},
1324   {".svg", 4, "image/svg+xml"},
1325   {".txt", 4, "text/plain"},
1326   {".torrent", 8, "application/x-bittorrent"},
1327   {".wav", 4, "audio/x-wav"},
1328   {".mp3", 4, "audio/x-mp3"},
1329   {".mid", 4, "audio/mid"},
1330   {".m3u", 4, "audio/x-mpegurl"},
1331   {".ogg", 4, "application/ogg"},
1332   {".ram", 4, "audio/x-pn-realaudio"},
1333   {".xml", 4, "text/xml"},
1334   {".json",  5, "text/json"},
1335   {".xslt", 5, "application/xml"},
1336   {".xsl", 4, "application/xml"},
1337   {".ra",  3, "audio/x-pn-realaudio"},
1338   {".doc", 4, "application/msword"},
1339   {".exe", 4, "application/octet-stream"},
1340   {".zip", 4, "application/x-zip-compressed"},
1341   {".xls", 4, "application/excel"},
1342   {".tgz", 4, "application/x-tar-gz"},
1343   {".tar", 4, "application/x-tar"},
1344   {".gz",  3, "application/x-gunzip"},
1345   {".arj", 4, "application/x-arj-compressed"},
1346   {".rar", 4, "application/x-rar-compressed"},
1347   {".rtf", 4, "application/rtf"},
1348   {".pdf", 4, "application/pdf"},
1349   {".swf", 4, "application/x-shockwave-flash"},
1350   {".mpg", 4, "video/mpeg"},
1351   {".webm", 5, "video/webm"},
1352   {".mpeg", 5, "video/mpeg"},
1353   {".mov", 4, "video/quicktime"},
1354   {".mp4", 4, "video/mp4"},
1355   {".m4v", 4, "video/x-m4v"},
1356   {".asf", 4, "video/x-ms-asf"},
1357   {".avi", 4, "video/x-msvideo"},
1358   {".bmp", 4, "image/bmp"},
1359   {".ttf", 4, "application/x-font-ttf"},
1360   {NULL,  0, NULL}
1367  {".html", 5, "text/html"},
1368  {".htm", 4, "text/html"},
1369  {".shtm", 5, "text/html"},
1370  {".shtml", 6, "text/html"},
1371  {".css", 4, "text/css"},
1372  {".js",  3, "application/x-javascript"},
1373  {".ico", 4, "image/x-icon"},
1374  {".gif", 4, "image/gif"},
1375  {".jpg", 4, "image/jpeg"},
1376  {".jpeg", 5, "image/jpeg"},
1377  {".png", 4, "image/png"},
1378  {".svg", 4, "image/svg+xml"},
1379  {".txt", 4, "text/plain"},
1380  {".torrent", 8, "application/x-bittorrent"},
1381  {".wav", 4, "audio/x-wav"},
1382  {".mp3", 4, "audio/x-mp3"},
1383  {".mid", 4, "audio/mid"},
1384  {".m3u", 4, "audio/x-mpegurl"},
1385  {".ogg", 4, "application/ogg"},
1386  {".ram", 4, "audio/x-pn-realaudio"},
1387  {".xml", 4, "text/xml"},
1388  {".json",  5, "application/json"},
1389  {".xslt", 5, "application/xml"},
1390  {".xsl", 4, "application/xml"},
1391  {".ra",  3, "audio/x-pn-realaudio"},
1392  {".doc", 4, "application/msword"},
1393  {".exe", 4, "application/octet-stream"},
1394  {".zip", 4, "application/x-zip-compressed"},
1395  {".xls", 4, "application/excel"},
1396  {".tgz", 4, "application/x-tar-gz"},
1397  {".tar", 4, "application/x-tar"},
1398  {".gz",  3, "application/x-gunzip"},
1399  {".arj", 4, "application/x-arj-compressed"},
1400  {".rar", 4, "application/x-rar-compressed"},
1401  {".rtf", 4, "application/rtf"},
1402  {".pdf", 4, "application/pdf"},
1403  {".swf", 4, "application/x-shockwave-flash"},
1404  {".mpg", 4, "video/mpeg"},
1405  {".webm", 5, "video/webm"},
1406  {".mpeg", 5, "video/mpeg"},
1407  {".mov", 4, "video/quicktime"},
1408  {".mp4", 4, "video/mp4"},
1409  {".m4v", 4, "video/x-m4v"},
1410  {".asf", 4, "video/x-ms-asf"},
1411  {".avi", 4, "video/x-msvideo"},
1412  {".bmp", 4, "image/bmp"},
1413  {".ttf", 4, "application/x-font-ttf"},
1414  {NULL,  0, NULL}
13611415};
13621416
13631417#ifndef MONGOOSE_NO_THREADS
13641418void *mg_start_thread(void *(*f)(void *), void *p) {
1365   return ns_start_thread(f, p);
1419  return ns_start_thread(f, p);
13661420}
13671421#endif  // MONGOOSE_NO_THREADS
13681422
r31874r31875
13701424// Encode 'path' which is assumed UTF-8 string, into UNICODE string.
13711425// wbuf and wbuf_len is a target buffer and its length.
13721426static void to_wchar(const char *path, wchar_t *wbuf, size_t wbuf_len) {
1373   char buf[MAX_PATH_SIZE * 2], buf2[MAX_PATH_SIZE * 2], *p;
1427  char buf[MAX_PATH_SIZE * 2], buf2[MAX_PATH_SIZE * 2], *p;
13741428
1375   strncpy(buf, path, sizeof(buf));
1376   buf[sizeof(buf) - 1] = '\0';
1429  strncpy(buf, path, sizeof(buf));
1430  buf[sizeof(buf) - 1] = '\0';
13771431
1378   // Trim trailing slashes. Leave backslash for paths like "X:\"
1379   p = buf + strlen(buf) - 1;
1380   while (p > buf && p[-1] != ':' && (p[0] == '\\' || p[0] == '/')) *p-- = '\0';
1432  // Trim trailing slashes. Leave backslash for paths like "X:\"
1433  p = buf + strlen(buf) - 1;
1434  while (p > buf && p[-1] != ':' && (p[0] == '\\' || p[0] == '/')) *p-- = '\0';
13811435
1382   // Convert to Unicode and back. If doubly-converted string does not
1383   // match the original, something is fishy, reject.
1384   memset(wbuf, 0, wbuf_len * sizeof(wchar_t));
1385   MultiByteToWideChar(CP_UTF8, 0, buf, -1, wbuf, (int) wbuf_len);
1386   WideCharToMultiByte(CP_UTF8, 0, wbuf, (int) wbuf_len, buf2, sizeof(buf2),
1387                  NULL, NULL);
1388   if (strcmp(buf, buf2) != 0) {
1389   wbuf[0] = L'\0';
1390   }
1436  // Convert to Unicode and back. If doubly-converted string does not
1437  // match the original, something is fishy, reject.
1438  memset(wbuf, 0, wbuf_len * sizeof(wchar_t));
1439  MultiByteToWideChar(CP_UTF8, 0, buf, -1, wbuf, (int) wbuf_len);
1440  WideCharToMultiByte(CP_UTF8, 0, wbuf, (int) wbuf_len, buf2, sizeof(buf2),
1441                      NULL, NULL);
1442  if (strcmp(buf, buf2) != 0) {
1443    wbuf[0] = L'\0';
1444  }
13911445}
13921446
13931447static int mg_stat(const char *path, file_stat_t *st) {
1394   wchar_t wpath[MAX_PATH_SIZE];
1395   to_wchar(path, wpath, ARRAY_SIZE(wpath));
1396   DBG(("[%ls] -> %d", wpath, _wstati64(wpath, st)));
1397   return _wstati64(wpath, st);
1448  wchar_t wpath[MAX_PATH_SIZE];
1449  to_wchar(path, wpath, ARRAY_SIZE(wpath));
1450  DBG(("[%ls] -> %d", wpath, _wstati64(wpath, st)));
1451  return _wstati64(wpath, st);
13981452}
13991453
14001454static FILE *mg_fopen(const char *path, const char *mode) {
1401   wchar_t wpath[MAX_PATH_SIZE], wmode[10];
1402   to_wchar(path, wpath, ARRAY_SIZE(wpath));
1403   to_wchar(mode, wmode, ARRAY_SIZE(wmode));
1404   return _wfopen(wpath, wmode);
1455  wchar_t wpath[MAX_PATH_SIZE], wmode[10];
1456  to_wchar(path, wpath, ARRAY_SIZE(wpath));
1457  to_wchar(mode, wmode, ARRAY_SIZE(wmode));
1458  return _wfopen(wpath, wmode);
14051459}
14061460
14071461static int mg_open(const char *path, int flag) {
1408   wchar_t wpath[MAX_PATH_SIZE];
1409   to_wchar(path, wpath, ARRAY_SIZE(wpath));
1410   return _wopen(wpath, flag);
1462  wchar_t wpath[MAX_PATH_SIZE];
1463  to_wchar(path, wpath, ARRAY_SIZE(wpath));
1464  return _wopen(wpath, flag);
14111465}
14121466#endif // _WIN32 && !MONGOOSE_NO_FILESYSTEM
14131467
r31874r31875
14181472// vector is initialized to point to the "y" part, and val vector length
14191473// is adjusted to point only to "x".
14201474static const char *next_option(const char *list, struct vec *val,
1421                        struct vec *eq_val) {
1422   if (list == NULL || *list == '\0') {
1423   // End of the list
1424   list = NULL;
1425   } else {
1426   val->ptr = list;
1427   if ((list = strchr(val->ptr, ',')) != NULL) {
1428      // Comma found. Store length and shift the list ptr
1429      val->len = list - val->ptr;
1430      list++;
1431   } else {
1432      // This value is the last one
1433      list = val->ptr + strlen(val->ptr);
1434      val->len = list - val->ptr;
1435   }
1475                               struct vec *eq_val) {
1476  if (list == NULL || *list == '\0') {
1477    // End of the list
1478    list = NULL;
1479  } else {
1480    val->ptr = list;
1481    if ((list = strchr(val->ptr, ',')) != NULL) {
1482      // Comma found. Store length and shift the list ptr
1483      val->len = list - val->ptr;
1484      list++;
1485    } else {
1486      // This value is the last one
1487      list = val->ptr + strlen(val->ptr);
1488      val->len = list - val->ptr;
1489    }
14361490
1437   if (eq_val != NULL) {
1438      // Value has form "x=y", adjust pointers and lengths
1439      // so that val points to "x", and eq_val points to "y".
1440      eq_val->len = 0;
1441      eq_val->ptr = (const char *) memchr(val->ptr, '=', val->len);
1442      if (eq_val->ptr != NULL) {
1443      eq_val->ptr++;  // Skip over '=' character
1444      eq_val->len = val->ptr + val->len - eq_val->ptr;
1445      val->len = (eq_val->ptr - val->ptr) - 1;
1446      }
1447   }
1448   }
1491    if (eq_val != NULL) {
1492      // Value has form "x=y", adjust pointers and lengths
1493      // so that val points to "x", and eq_val points to "y".
1494      eq_val->len = 0;
1495      eq_val->ptr = (const char *) memchr(val->ptr, '=', val->len);
1496      if (eq_val->ptr != NULL) {
1497        eq_val->ptr++;  // Skip over '=' character
1498        eq_val->len = val->ptr + val->len - eq_val->ptr;
1499        val->len = (eq_val->ptr - val->ptr) - 1;
1500      }
1501    }
1502  }
14491503
1450   return list;
1504  return list;
14511505}
14521506
14531507// Like snprintf(), but never returns negative value, or a value
14541508// that is larger than a supplied buffer.
14551509static int mg_vsnprintf(char *buf, size_t buflen, const char *fmt, va_list ap) {
1456   int n;
1457   if (buflen < 1) return 0;
1458   n = vsnprintf(buf, buflen, fmt, ap);
1459   if (n < 0) {
1460   n = 0;
1461   } else if (n >= (int) buflen) {
1462   n = (int) buflen - 1;
1463   }
1464   buf[n] = '\0';
1465   return n;
1510  int n;
1511  if (buflen < 1) return 0;
1512  n = vsnprintf(buf, buflen, fmt, ap);
1513  if (n < 0) {
1514    n = 0;
1515  } else if (n >= (int) buflen) {
1516    n = (int) buflen - 1;
1517  }
1518  buf[n] = '\0';
1519  return n;
14661520}
14671521
14681522static int mg_snprintf(char *buf, size_t buflen, const char *fmt, ...) {
1469   va_list ap;
1470   int n;
1471   va_start(ap, fmt);
1472   n = mg_vsnprintf(buf, buflen, fmt, ap);
1473   va_end(ap);
1474   return n;
1523  va_list ap;
1524  int n;
1525  va_start(ap, fmt);
1526  n = mg_vsnprintf(buf, buflen, fmt, ap);
1527  va_end(ap);
1528  return n;
14751529}
14761530
14771531// Check whether full request is buffered. Return:
r31874r31875
14791533//    0  if request is not yet fully buffered
14801534//   >0  actual request length, including last \r\n\r\n
14811535static int get_request_len(const char *s, int buf_len) {
1482   const unsigned char *buf = (unsigned char *) s;
1483   int i;
1536  const unsigned char *buf = (unsigned char *) s;
1537  int i;
14841538
1485   for (i = 0; i < buf_len; i++) {
1486   // Control characters are not allowed but >=128 are.
1487   // Abort scan as soon as one malformed character is found.
1488   if (!isprint(buf[i]) && buf[i] != '\r' && buf[i] != '\n' && buf[i] < 128) {
1489      return -1;
1490   } else if (buf[i] == '\n' && i + 1 < buf_len && buf[i + 1] == '\n') {
1491      return i + 2;
1492   } else if (buf[i] == '\n' && i + 2 < buf_len && buf[i + 1] == '\r' &&
1493            buf[i + 2] == '\n') {
1494      return i + 3;
1495   }
1496   }
1539  for (i = 0; i < buf_len; i++) {
1540    // Control characters are not allowed but >=128 are.
1541    // Abort scan as soon as one malformed character is found.
1542    if (!isprint(buf[i]) && buf[i] != '\r' && buf[i] != '\n' && buf[i] < 128) {
1543      return -1;
1544    } else if (buf[i] == '\n' && i + 1 < buf_len && buf[i + 1] == '\n') {
1545      return i + 2;
1546    } else if (buf[i] == '\n' && i + 2 < buf_len && buf[i + 1] == '\r' &&
1547               buf[i + 2] == '\n') {
1548      return i + 3;
1549    }
1550  }
14971551
1498   return 0;
1552  return 0;
14991553}
15001554
15011555// Skip the characters until one of the delimiters characters found.
15021556// 0-terminate resulting word. Skip the rest of the delimiters if any.
15031557// Advance pointer to buffer to the next word. Return found 0-terminated word.
15041558static char *skip(char **buf, const char *delimiters) {
1505   char *p, *begin_word, *end_word, *end_delimiters;
1559  char *p, *begin_word, *end_word, *end_delimiters;
15061560
1507   begin_word = *buf;
1508   end_word = begin_word + strcspn(begin_word, delimiters);
1509   end_delimiters = end_word + strspn(end_word, delimiters);
1561  begin_word = *buf;
1562  end_word = begin_word + strcspn(begin_word, delimiters);
1563  end_delimiters = end_word + strspn(end_word, delimiters);
15101564
1511   for (p = end_word; p < end_delimiters; p++) {
1512   *p = '\0';
1513   }
1565  for (p = end_word; p < end_delimiters; p++) {
1566    *p = '\0';
1567  }
15141568
1515   *buf = end_delimiters;
1569  *buf = end_delimiters;
15161570
1517   return begin_word;
1571  return begin_word;
15181572}
15191573
15201574// Parse HTTP headers from the given buffer, advance buffer to the point
15211575// where parsing stopped.
15221576static void parse_http_headers(char **buf, struct mg_connection *ri) {
1523   size_t i;
1577  size_t i;
15241578
1525   for (i = 0; i < ARRAY_SIZE(ri->http_headers); i++) {
1526   ri->http_headers[i].name = skip(buf, ": ");
1527   ri->http_headers[i].value = skip(buf, "\r\n");
1528   if (ri->http_headers[i].name[0] == '\0')
1529      break;
1530   ri->num_headers = i + 1;
1531   }
1579  for (i = 0; i < ARRAY_SIZE(ri->http_headers); i++) {
1580    ri->http_headers[i].name = skip(buf, ": ");
1581    ri->http_headers[i].value = skip(buf, "\r\n");
1582    if (ri->http_headers[i].name[0] == '\0')
1583      break;
1584    ri->num_headers = i + 1;
1585  }
15321586}
15331587
15341588static const char *status_code_to_str(int status_code) {
1535   switch (status_code) {
1536   case 200: return "OK";
1537   case 201: return "Created";
1538   case 204: return "No Content";
1539   case 301: return "Moved Permanently";
1540   case 302: return "Found";
1541   case 304: return "Not Modified";
1542   case 400: return "Bad Request";
1543   case 403: return "Forbidden";
1544   case 404: return "Not Found";
1545   case 405: return "Method Not Allowed";
1546   case 409: return "Conflict";
1547   case 411: return "Length Required";
1548   case 413: return "Request Entity Too Large";
1549   case 415: return "Unsupported Media Type";
1550   case 423: return "Locked";
1551   case 500: return "Server Error";
1552   case 501: return "Not Implemented";
1553   default:  return "Server Error";
1554   }
1589  switch (status_code) {
1590
1591    case 100: return "Continue";
1592    case 101: return "Switching Protocols";
1593    case 102: return "Processing";
1594
1595    case 200: return "OK";
1596    case 201: return "Created";
1597    case 202: return "Accepted";
1598    case 203: return "Non-Authoritative Information";
1599    case 204: return "No Content";
1600    case 205: return "Reset Content";
1601    case 206: return "Partial Content";
1602    case 207: return "Multi-Status";
1603    case 208: return "Already Reported";
1604    case 226: return "IM Used";
1605
1606    case 300: return "Multiple Choices";
1607    case 301: return "Moved Permanently";
1608    case 302: return "Found";
1609    case 303: return "See Other";
1610    case 304: return "Not Modified";
1611    case 305: return "Use Proxy";
1612    case 306: return "Switch Proxy";
1613    case 307: return "Temporary Redirect";
1614    case 308: return "Permanent Redirect";
1615
1616    case 400: return "Bad Request";
1617    case 401: return "Unauthorized";
1618    case 402: return "Payment Required";
1619    case 403: return "Forbidden";
1620    case 404: return "Not Found";
1621    case 405: return "Method Not Allowed";
1622    case 406: return "Not Acceptable";
1623    case 407: return "Proxy Authentication Required";
1624    case 408: return "Request Timeout";
1625    case 409: return "Conflict";
1626    case 410: return "Gone";
1627    case 411: return "Length Required";
1628    case 412: return "Precondition Failed";
1629    case 413: return "Payload Too Large";
1630    case 414: return "URI Too Long";
1631    case 415: return "Unsupported Media Type";
1632    case 416: return "Requested Range Not Satisfiable";
1633    case 417: return "Expectation Failed";
1634    case 418: return "I\'m a teapot";
1635    case 422: return "Unprocessable Entity";
1636    case 423: return "Locked";
1637    case 424: return "Failed Dependency";
1638    case 426: return "Upgrade Required";
1639    case 428: return "Precondition Required";
1640    case 429: return "Too Many Requests";
1641    case 431: return "Request Header Fields Too Large";
1642    case 451: return "Unavailable For Legal Reasons";
1643
1644    case 500: return "Internal Server Error";
1645    case 501: return "Not Implemented";
1646    case 502: return "Bad Gateway";
1647    case 503: return "Service Unavailable";
1648    case 504: return "Gateway Timeout";
1649    case 505: return "HTTP Version Not Supported";
1650    case 506: return "Variant Also Negotiates";
1651    case 507: return "Insufficient Storage";
1652    case 508: return "Loop Detected";
1653    case 510: return "Not Extended";
1654    case 511: return "Network Authentication Required";
1655
1656    default:  return "Server Error";
1657  }
15551658}
15561659
15571660static int call_user(struct connection *conn, enum mg_event ev) {
1558   return conn != NULL && conn->server != NULL &&
1559   conn->server->event_handler != NULL ?
1560   conn->server->event_handler(&conn->mg_conn, ev) : MG_FALSE;
1661  return conn != NULL && conn->server != NULL &&
1662    conn->server->event_handler != NULL ?
1663    conn->server->event_handler(&conn->mg_conn, ev) : MG_FALSE;
15611664}
15621665
15631666static void send_http_error(struct connection *conn, int code,
1564                     const char *fmt, ...) {
1565   const char *message = status_code_to_str(code);
1566   const char *rewrites = conn->server->config_options[URL_REWRITES];
1567   char headers[200], body[200];
1568   struct vec a, b;
1569   va_list ap;
1570   int body_len, headers_len, match_code;
1667                            const char *fmt, ...) {
1668  const char *message = status_code_to_str(code);
1669  const char *rewrites = conn->server->config_options[URL_REWRITES];
1670  char headers[200], body[200];
1671  struct vec a, b;
1672  va_list ap;
1673  int body_len, headers_len, match_code;
15711674
1572   conn->mg_conn.status_code = code;
1675  conn->mg_conn.status_code = code;
15731676
1574   // Invoke error handler if it is set
1575   if (call_user(conn, MG_HTTP_ERROR) == MG_TRUE) {
1576   close_local_endpoint(conn);
1577   return;
1578   }
1677  // Invoke error handler if it is set
1678  if (call_user(conn, MG_HTTP_ERROR) == MG_TRUE) {
1679    close_local_endpoint(conn);
1680    return;
1681  }
15791682
1580   // Handle error code rewrites
1581   while ((rewrites = next_option(rewrites, &a, &b)) != NULL) {
1582   if ((match_code = atoi(a.ptr)) > 0 && match_code == code) {
1583      struct mg_connection *c = &conn->mg_conn;
1584      c->status_code = 302;
1585      mg_printf(c, "HTTP/1.1 %d Moved\r\n"
1586            "Location: %.*s?code=%d&orig_uri=%s&query_string=%s\r\n\r\n",
1587            c->status_code, b.len, b.ptr, code, c->uri,
1588            c->query_string == NULL ? "" : c->query_string);
1589      close_local_endpoint(conn);
1590      return;
1591   }
1592   }
1683  // Handle error code rewrites
1684  while ((rewrites = next_option(rewrites, &a, &b)) != NULL) {
1685    if ((match_code = atoi(a.ptr)) > 0 && match_code == code) {
1686      struct mg_connection *c = &conn->mg_conn;
1687      c->status_code = 302;
1688      mg_printf(c, "HTTP/1.1 %d Moved\r\n"
1689                "Location: %.*s?code=%d&orig_uri=%s&query_string=%s\r\n\r\n",
1690                c->status_code, b.len, b.ptr, code, c->uri,
1691                c->query_string == NULL ? "" : c->query_string);
1692      close_local_endpoint(conn);
1693      return;
1694    }
1695  }
15931696
1594   body_len = mg_snprintf(body, sizeof(body), "%d %s\n", code, message);
1595   if (fmt != NULL) {
1596   va_start(ap, fmt);
1597   body_len += mg_vsnprintf(body + body_len, sizeof(body) - body_len, fmt, ap);
1598   va_end(ap);
1599   }
1600   if ((code >= 300 && code <= 399) || code == 204) {
1601   // 3xx errors do not have body
1602   body_len = 0;
1603   }
1604   headers_len = mg_snprintf(headers, sizeof(headers),
1605                     "HTTP/1.1 %d %s\r\nContent-Length: %d\r\n"
1606                     "Content-Type: text/plain\r\n\r\n",
1607                     code, message, body_len);
1608   ns_send(conn->ns_conn, headers, headers_len);
1609   ns_send(conn->ns_conn, body, body_len);
1610   close_local_endpoint(conn);  // This will write to the log file
1697  body_len = mg_snprintf(body, sizeof(body), "%d %s\n", code, message);
1698  if (fmt != NULL) {
1699    va_start(ap, fmt);
1700    body_len += mg_vsnprintf(body + body_len, sizeof(body) - body_len, fmt, ap);
1701    va_end(ap);
1702  }
1703  if ((code >= 300 && code <= 399) || code == 204) {
1704    // 3xx errors do not have body
1705    body_len = 0;
1706  }
1707  headers_len = mg_snprintf(headers, sizeof(headers),
1708                            "HTTP/1.1 %d %s\r\nContent-Length: %d\r\n"
1709                            "Content-Type: text/plain\r\n\r\n",
1710                            code, message, body_len);
1711  ns_send(conn->ns_conn, headers, headers_len);
1712  ns_send(conn->ns_conn, body, body_len);
1713  close_local_endpoint(conn);  // This will write to the log file
16111714}
16121715
16131716static void write_chunk(struct connection *conn, const char *buf, int len) {
1614   char chunk_size[50];
1615   int n = mg_snprintf(chunk_size, sizeof(chunk_size), "%X\r\n", len);
1616   ns_send(conn->ns_conn, chunk_size, n);
1617   ns_send(conn->ns_conn, buf, len);
1618   ns_send(conn->ns_conn, "\r\n", 2);
1717  char chunk_size[50];
1718  int n = mg_snprintf(chunk_size, sizeof(chunk_size), "%X\r\n", len);
1719  ns_send(conn->ns_conn, chunk_size, n);
1720  ns_send(conn->ns_conn, buf, len);
1721  ns_send(conn->ns_conn, "\r\n", 2);
16191722}
16201723
16211724size_t mg_printf(struct mg_connection *conn, const char *fmt, ...) {
1622   struct connection *c = MG_CONN_2_CONN(conn);
1623   va_list ap;
1725  struct connection *c = MG_CONN_2_CONN(conn);
1726  va_list ap;
16241727
1625   va_start(ap, fmt);
1626   ns_vprintf(c->ns_conn, fmt, ap);
1627   va_end(ap);
1728  va_start(ap, fmt);
1729  ns_vprintf(c->ns_conn, fmt, ap);
1730  va_end(ap);
16281731
1629   return c->ns_conn->send_iobuf.len;
1732  return c->ns_conn->send_iobuf.len;
16301733}
16311734
16321735static void ns_forward(struct ns_connection *from, struct ns_connection *to) {
1633   DBG(("%p -> %p %zu bytes", from, to, from->recv_iobuf.len));
1634   ns_send(to, from->recv_iobuf.buf, from->recv_iobuf.len);
1635   iobuf_remove(&from->recv_iobuf, from->recv_iobuf.len);
1736  DBG(("%p -> %p %lu bytes", from, to, (unsigned long)from->recv_iobuf.len));
1737  ns_send(to, from->recv_iobuf.buf, from->recv_iobuf.len);
1738  iobuf_remove(&from->recv_iobuf, from->recv_iobuf.len);
16361739}
16371740
16381741#ifndef MONGOOSE_NO_CGI
16391742#ifdef _WIN32
16401743struct threadparam {
1641   sock_t s;
1642   HANDLE hPipe;
1744  sock_t s;
1745  HANDLE hPipe;
16431746};
16441747
16451748static int wait_until_ready(sock_t sock, int for_read) {
1646   fd_set set;
1647   FD_ZERO(&set);
1648   FD_SET(sock, &set);
1649   select(sock + 1, for_read ? &set : 0, for_read ? 0 : &set, 0, 0);
1650   return 1;
1749  fd_set set;
1750  FD_ZERO(&set);
1751  FD_SET(sock, &set);
1752  select(sock + 1, for_read ? &set : 0, for_read ? 0 : &set, 0, 0);
1753  return 1;
16511754}
16521755
16531756static void *push_to_stdin(void *arg) {
1654   struct threadparam *tp = (struct threadparam *)arg;
1655   int n, sent, stop = 0;
1656   DWORD k;
1657   char buf[IOBUF_SIZE];
1757  struct threadparam *tp = (struct threadparam *)arg;
1758  int n, sent, stop = 0;
1759  DWORD k;
1760  char buf[IOBUF_SIZE];
16581761
1659   while (!stop && wait_until_ready(tp->s, 1) &&
1660         (n = recv(tp->s, buf, sizeof(buf), 0)) > 0) {
1661   if (n == -1 && GetLastError() == WSAEWOULDBLOCK) continue;
1662   for (sent = 0; !stop && sent < n; sent += k) {
1663      if (!WriteFile(tp->hPipe, buf + sent, n - sent, &k, 0)) stop = 1;
1664   }
1665   }
1666   DBG(("%s", "FORWARED EVERYTHING TO CGI"));
1667   CloseHandle(tp->hPipe);
1668   free(tp);
1669   _endthread();
1670   return NULL;
1762  while (!stop && wait_until_ready(tp->s, 1) &&
1763         (n = recv(tp->s, buf, sizeof(buf), 0)) > 0) {
1764    if (n == -1 && GetLastError() == WSAEWOULDBLOCK) continue;
1765    for (sent = 0; !stop && sent < n; sent += k) {
1766      if (!WriteFile(tp->hPipe, buf + sent, n - sent, &k, 0)) stop = 1;
1767    }
1768  }
1769  DBG(("%s", "FORWARED EVERYTHING TO CGI"));
1770  CloseHandle(tp->hPipe);
1771  free(tp);
1772  _endthread();
1773  return NULL;
16711774}
16721775
16731776static void *pull_from_stdout(void *arg) {
1674   struct threadparam *tp = (struct threadparam *)arg;
1675   int k = 0, stop = 0;
1676   DWORD n, sent;
1677   char buf[IOBUF_SIZE];
1777  struct threadparam *tp = (struct threadparam *)arg;
1778  int k = 0, stop = 0;
1779  DWORD n, sent;
1780  char buf[IOBUF_SIZE];
16781781
1679   while (!stop && ReadFile(tp->hPipe, buf, sizeof(buf), &n, NULL)) {
1680   for (sent = 0; !stop && sent < n; sent += k) {
1681      if (wait_until_ready(tp->s, 0) &&
1682         (k = send(tp->s, buf + sent, n - sent, 0)) <= 0) stop = 1;
1683   }
1684   }
1685   DBG(("%s", "EOF FROM CGI"));
1686   CloseHandle(tp->hPipe);
1687   shutdown(tp->s, 2);  // Without this, IO thread may get truncated data
1688   closesocket(tp->s);
1689   free(tp);
1690   _endthread();
1691   return NULL;
1782  while (!stop && ReadFile(tp->hPipe, buf, sizeof(buf), &n, NULL)) {
1783    for (sent = 0; !stop && sent < n; sent += k) {
1784      if (wait_until_ready(tp->s, 0) &&
1785          (k = send(tp->s, buf + sent, n - sent, 0)) <= 0) stop = 1;
1786    }
1787  }
1788  DBG(("%s", "EOF FROM CGI"));
1789  CloseHandle(tp->hPipe);
1790  shutdown(tp->s, 2);  // Without this, IO thread may get truncated data
1791  closesocket(tp->s);
1792  free(tp);
1793  _endthread();
1794  return NULL;
16921795}
16931796
16941797static void spawn_stdio_thread(sock_t sock, HANDLE hPipe,
1695                        void *(*func)(void *)) {
1696   struct threadparam *tp = (struct threadparam *)malloc(sizeof(*tp));
1697   if (tp != NULL) {
1698   tp->s = sock;
1699   tp->hPipe = hPipe;
1700   mg_start_thread(func, tp);
1701   }
1798                               void *(*func)(void *)) {
1799  struct threadparam *tp = (struct threadparam *)malloc(sizeof(*tp));
1800  if (tp != NULL) {
1801    tp->s = sock;
1802    tp->hPipe = hPipe;
1803    mg_start_thread(func, tp);
1804  }
17021805}
17031806
17041807static void abs_path(const char *utf8_path, char *abs_path, size_t len) {
1705   wchar_t buf[MAX_PATH_SIZE], buf2[MAX_PATH_SIZE];
1706   to_wchar(utf8_path, buf, ARRAY_SIZE(buf));
1707   GetFullPathNameW(buf, ARRAY_SIZE(buf2), buf2, NULL);
1708   WideCharToMultiByte(CP_UTF8, 0, buf2, wcslen(buf2) + 1, abs_path, len, 0, 0);
1808  wchar_t buf[MAX_PATH_SIZE], buf2[MAX_PATH_SIZE];
1809  to_wchar(utf8_path, buf, ARRAY_SIZE(buf));
1810  GetFullPathNameW(buf, ARRAY_SIZE(buf2), buf2, NULL);
1811  WideCharToMultiByte(CP_UTF8, 0, buf2, wcslen(buf2) + 1, abs_path, len, 0, 0);
17091812}
17101813
17111814static process_id_t start_process(char *interp, const char *cmd,
1712                           const char *env, const char *envp[],
1713                           const char *dir, sock_t sock) {
1714   STARTUPINFOW si = {0};
1715   PROCESS_INFORMATION pi = {0};
1716   HANDLE a[2], b[2], me = GetCurrentProcess();
1717   wchar_t wcmd[MAX_PATH_SIZE], full_dir[MAX_PATH_SIZE];
1718   char buf[MAX_PATH_SIZE], buf4[MAX_PATH_SIZE], buf5[MAX_PATH_SIZE],
1719      cmdline[MAX_PATH_SIZE], *p;
1720   DWORD flags = DUPLICATE_CLOSE_SOURCE | DUPLICATE_SAME_ACCESS;
1721   FILE *fp;
1815                                  const char *env, const char *envp[],
1816                                  const char *dir, sock_t sock) {
1817  STARTUPINFOW si;
1818  PROCESS_INFORMATION pi;
1819  HANDLE a[2], b[2], me = GetCurrentProcess();
1820  wchar_t wcmd[MAX_PATH_SIZE], full_dir[MAX_PATH_SIZE];
1821  char buf[MAX_PATH_SIZE], buf4[MAX_PATH_SIZE], buf5[MAX_PATH_SIZE],
1822       cmdline[MAX_PATH_SIZE], *p;
1823  DWORD flags = DUPLICATE_CLOSE_SOURCE | DUPLICATE_SAME_ACCESS;
1824  FILE *fp;
17221825
1723   si.cb = sizeof(si);
1724   si.dwFlags = STARTF_USESTDHANDLES | STARTF_USESHOWWINDOW;
1725   si.wShowWindow = SW_HIDE;
1726   si.hStdError = GetStdHandle(STD_ERROR_HANDLE);
1826  memset(&si, 0, sizeof(si));
1827  memset(&pi, 0, sizeof(pi));
17271828
1728   CreatePipe(&a[0], &a[1], NULL, 0);
1729   CreatePipe(&b[0], &b[1], NULL, 0);
1730   DuplicateHandle(me, a[0], me, &si.hStdInput, 0, TRUE, flags);
1731   DuplicateHandle(me, b[1], me, &si.hStdOutput, 0, TRUE, flags);
1829  si.cb = sizeof(si);
1830  si.dwFlags = STARTF_USESTDHANDLES | STARTF_USESHOWWINDOW;
1831  si.wShowWindow = SW_HIDE;
1832  si.hStdError = GetStdHandle(STD_ERROR_HANDLE);
17321833
1733   if (interp == NULL && (fp = fopen(cmd, "r")) != NULL) {
1734   buf[0] = buf[1] = '\0';
1735   fgets(buf, sizeof(buf), fp);
1736   buf[sizeof(buf) - 1] = '\0';
1737   if (buf[0] == '#' && buf[1] == '!') {
1738      interp = buf + 2;
1739      for (p = interp + strlen(interp);
1740         isspace(* (uint8_t *) p) && p > interp; p--) *p = '\0';
1741   }
1742   fclose(fp);
1743   }
1834  CreatePipe(&a[0], &a[1], NULL, 0);
1835  CreatePipe(&b[0], &b[1], NULL, 0);
1836  DuplicateHandle(me, a[0], me, &si.hStdInput, 0, TRUE, flags);
1837  DuplicateHandle(me, b[1], me, &si.hStdOutput, 0, TRUE, flags);
17441838
1745   if (interp != NULL) {
1746   abs_path(interp, buf4, ARRAY_SIZE(buf4));
1747   interp = buf4;
1748   }
1749   abs_path(dir, buf5, ARRAY_SIZE(buf5));
1750   to_wchar(dir, full_dir, ARRAY_SIZE(full_dir));
1751   mg_snprintf(cmdline, sizeof(cmdline), "%s%s\"%s\"",
1752            interp ? interp : "", interp ? " " : "", cmd);
1753   to_wchar(cmdline, wcmd, ARRAY_SIZE(wcmd));
1839  if (interp == NULL && (fp = fopen(cmd, "r")) != NULL) {
1840    buf[0] = buf[1] = '\0';
1841    fgets(buf, sizeof(buf), fp);
1842    buf[sizeof(buf) - 1] = '\0';
1843    if (buf[0] == '#' && buf[1] == '!') {
1844      interp = buf + 2;
1845      for (p = interp + strlen(interp);
1846           isspace(* (uint8_t *) p) && p > interp; p--) *p = '\0';
1847    }
1848    fclose(fp);
1849  }
17541850
1755   if (CreateProcessW(NULL, wcmd, NULL, NULL, TRUE, CREATE_NEW_PROCESS_GROUP,
1756                  (void *) env, full_dir, &si, &pi) != 0) {
1757   spawn_stdio_thread(sock, a[1], push_to_stdin);
1758   spawn_stdio_thread(sock, b[0], pull_from_stdout);
1759   } else {
1760   CloseHandle(a[1]);
1761   CloseHandle(b[0]);
1762   closesocket(sock);
1763   }
1764   DBG(("CGI command: [%ls] -> %p", wcmd, pi.hProcess));
1851  if (interp != NULL) {
1852    abs_path(interp, buf4, ARRAY_SIZE(buf4));
1853    interp = buf4;
1854  }
1855  abs_path(dir, buf5, ARRAY_SIZE(buf5));
1856  to_wchar(dir, full_dir, ARRAY_SIZE(full_dir));
1857  mg_snprintf(cmdline, sizeof(cmdline), "%s%s\"%s\"",
1858              interp ? interp : "", interp ? " " : "", cmd);
1859  to_wchar(cmdline, wcmd, ARRAY_SIZE(wcmd));
17651860
1766   CloseHandle(si.hStdOutput);
1767   CloseHandle(si.hStdInput);
1768   CloseHandle(a[0]);
1769   CloseHandle(b[1]);
1770   CloseHandle(pi.hThread);
1771   CloseHandle(pi.hProcess);
1861  if (CreateProcessW(NULL, wcmd, NULL, NULL, TRUE, CREATE_NEW_PROCESS_GROUP,
1862                     (void *) env, full_dir, &si, &pi) != 0) {
1863    spawn_stdio_thread(sock, a[1], push_to_stdin);
1864    spawn_stdio_thread(sock, b[0], pull_from_stdout);
1865  } else {
1866    CloseHandle(a[1]);
1867    CloseHandle(b[0]);
1868    closesocket(sock);
1869  }
1870  DBG(("CGI command: [%ls] -> %p", wcmd, pi.hProcess));
17721871
1773   return pi.hProcess;
1872  // Not closing a[0] and b[1] because we've used DUPLICATE_CLOSE_SOURCE
1873  CloseHandle(si.hStdOutput);
1874  CloseHandle(si.hStdInput);
1875  //CloseHandle(pi.hThread);
1876  //CloseHandle(pi.hProcess);
1877
1878  return pi.hProcess;
17741879}
17751880#else
17761881static process_id_t start_process(const char *interp, const char *cmd,
1777                           const char *env, const char *envp[],
1778                           const char *dir, sock_t sock) {
1779   char buf[500];
1780   process_id_t pid = fork();
1781   (void) env;
1882                                  const char *env, const char *envp[],
1883                                  const char *dir, sock_t sock) {
1884  char buf[500];
1885  process_id_t pid = fork();
1886  (void) env;
17821887
1783   if (pid == 0) {
1784   (void) chdir(dir);
1785   (void) dup2(sock, 0);
1786   (void) dup2(sock, 1);
1787   closesocket(sock);
1888  if (pid == 0) {
1889    (void) chdir(dir);
1890    (void) dup2(sock, 0);
1891    (void) dup2(sock, 1);
1892    closesocket(sock);
17881893
1789   // After exec, all signal handlers are restored to their default values,
1790   // with one exception of SIGCHLD. According to POSIX.1-2001 and Linux's
1791   // implementation, SIGCHLD's handler will leave unchanged after exec
1792   // if it was set to be ignored. Restore it to default action.
1793   signal(SIGCHLD, SIG_DFL);
1894    // After exec, all signal handlers are restored to their default values,
1895    // with one exception of SIGCHLD. According to POSIX.1-2001 and Linux's
1896    // implementation, SIGCHLD's handler will leave unchanged after exec
1897    // if it was set to be ignored. Restore it to default action.
1898    signal(SIGCHLD, SIG_DFL);
17941899
1795   if (interp == NULL) {
1796      execle(cmd, cmd, NULL, envp);
1797   } else {
1798      execle(interp, interp, cmd, NULL, envp);
1799   }
1800   snprintf(buf, sizeof(buf), "Status: 500\r\n\r\n"
1801            "500 Server Error: %s%s%s: %s", interp == NULL ? "" : interp,
1802            interp == NULL ? "" : " ", cmd, strerror(errno));
1803   send(1, buf, strlen(buf), 0);
1804   exit(EXIT_FAILURE);  // exec call failed
1805   }
1900    if (interp == NULL) {
1901      execle(cmd, cmd, (char *) 0, envp); // Using (char *) 0 to avoid warning
1902    } else {
1903      execle(interp, interp, cmd, (char *) 0, envp);
1904    }
1905    snprintf(buf, sizeof(buf), "Status: 500\r\n\r\n"
1906             "500 Server Error: %s%s%s: %s", interp == NULL ? "" : interp,
1907             interp == NULL ? "" : " ", cmd, strerror(errno));
1908    send(1, buf, strlen(buf), 0);
1909    exit(EXIT_FAILURE);  // exec call failed
1910  }
18061911
1807   return pid;
1912  return pid;
18081913}
18091914#endif  // _WIN32
18101915
r31874r31875
18171922// We satisfy both worlds: we create an envp array (which is vars), all
18181923// entries are actually pointers inside buf.
18191924struct cgi_env_block {
1820   struct mg_connection *conn;
1821   char buf[CGI_ENVIRONMENT_SIZE];       // Environment buffer
1822   const char *vars[MAX_CGI_ENVIR_VARS]; // char *envp[]
1823   int len;                              // Space taken
1824   int nvars;                            // Number of variables in envp[]
1925  struct mg_connection *conn;
1926  char buf[CGI_ENVIRONMENT_SIZE];       // Environment buffer
1927  const char *vars[MAX_CGI_ENVIR_VARS]; // char *envp[]
1928  int len;                              // Space taken
1929  int nvars;                            // Number of variables in envp[]
18251930};
18261931
18271932// Append VARIABLE=VALUE\0 string to the buffer, and add a respective
18281933// pointer into the vars array.
18291934static char *addenv(struct cgi_env_block *block, const char *fmt, ...) {
1830   int n, space;
1831   char *added;
1832   va_list ap;
1935  int n, space;
1936  char *added;
1937  va_list ap;
18331938
1834   // Calculate how much space is left in the buffer
1835   space = sizeof(block->buf) - block->len - 2;
1836   assert(space >= 0);
1939  // Calculate how much space is left in the buffer
1940  space = sizeof(block->buf) - block->len - 2;
1941  assert(space >= 0);
18371942
1838   // Make a pointer to the free space int the buffer
1839   added = block->buf + block->len;
1943  // Make a pointer to the free space int the buffer
1944  added = block->buf + block->len;
18401945
1841   // Copy VARIABLE=VALUE\0 string into the free space
1842   va_start(ap, fmt);
1843   n = mg_vsnprintf(added, (size_t) space, fmt, ap);
1844   va_end(ap);
1946  // Copy VARIABLE=VALUE\0 string into the free space
1947  va_start(ap, fmt);
1948  n = mg_vsnprintf(added, (size_t) space, fmt, ap);
1949  va_end(ap);
18451950
1846   // Make sure we do not overflow buffer and the envp array
1847   if (n > 0 && n + 1 < space &&
1848      block->nvars < (int) ARRAY_SIZE(block->vars) - 2) {
1849   // Append a pointer to the added string into the envp array
1850   block->vars[block->nvars++] = added;
1851   // Bump up used length counter. Include \0 terminator
1852   block->len += n + 1;
1853   }
1951  // Make sure we do not overflow buffer and the envp array
1952  if (n > 0 && n + 1 < space &&
1953      block->nvars < (int) ARRAY_SIZE(block->vars) - 2) {
1954    // Append a pointer to the added string into the envp array
1955    block->vars[block->nvars++] = added;
1956    // Bump up used length counter. Include \0 terminator
1957    block->len += n + 1;
1958  }
18541959
1855   return added;
1960  return added;
18561961}
18571962
18581963static void addenv2(struct cgi_env_block *blk, const char *name) {
1859   const char *s;
1860   if ((s = getenv(name)) != NULL) addenv(blk, "%s=%s", name, s);
1964  const char *s;
1965  if ((s = getenv(name)) != NULL) addenv(blk, "%s=%s", name, s);
18611966}
18621967
18631968static void prepare_cgi_environment(struct connection *conn,
1864                           const char *prog,
1865                           struct cgi_env_block *blk) {
1866   struct mg_connection *ri = &conn->mg_conn;
1867   const char *s, *slash;
1868   char *p, **opts = conn->server->config_options;
1869   int  i;
1969                                    const char *prog,
1970                                    struct cgi_env_block *blk) {
1971  struct mg_connection *ri = &conn->mg_conn;
1972  const char *s, *slash;
1973  char *p, **opts = conn->server->config_options;
1974  int  i;
18701975
1871   blk->len = blk->nvars = 0;
1872   blk->conn = ri;
1976  blk->len = blk->nvars = 0;
1977  blk->conn = ri;
18731978
1874   if ((s = getenv("SERVER_NAME")) != NULL) {
1875   addenv(blk, "SERVER_NAME=%s", s);
1876   } else {
1877   addenv(blk, "SERVER_NAME=%s", ri->local_ip);
1878   }
1879   addenv(blk, "SERVER_ROOT=%s", opts[DOCUMENT_ROOT]);
1880   addenv(blk, "DOCUMENT_ROOT=%s", opts[DOCUMENT_ROOT]);
1881   addenv(blk, "SERVER_SOFTWARE=%s/%s", "Mongoose", MONGOOSE_VERSION);
1979  if ((s = getenv("SERVER_NAME")) != NULL) {
1980    addenv(blk, "SERVER_NAME=%s", s);
1981  } else {
1982    addenv(blk, "SERVER_NAME=%s", ri->local_ip);
1983  }
1984  addenv(blk, "SERVER_ROOT=%s", opts[DOCUMENT_ROOT]);
1985  addenv(blk, "DOCUMENT_ROOT=%s", opts[DOCUMENT_ROOT]);
1986  addenv(blk, "SERVER_SOFTWARE=%s/%s", "Mongoose", MONGOOSE_VERSION);
18821987
1883   // Prepare the environment block
1884   addenv(blk, "%s", "GATEWAY_INTERFACE=CGI/1.1");
1885   addenv(blk, "%s", "SERVER_PROTOCOL=HTTP/1.1");
1886   addenv(blk, "%s", "REDIRECT_STATUS=200"); // For PHP
1988  // Prepare the environment block
1989  addenv(blk, "%s", "GATEWAY_INTERFACE=CGI/1.1");
1990  addenv(blk, "%s", "SERVER_PROTOCOL=HTTP/1.1");
1991  addenv(blk, "%s", "REDIRECT_STATUS=200"); // For PHP
18871992
1888   // TODO(lsm): fix this for IPv6 case
1889   //addenv(blk, "SERVER_PORT=%d", ri->remote_port);
1993  // TODO(lsm): fix this for IPv6 case
1994  //addenv(blk, "SERVER_PORT=%d", ri->remote_port);
18901995
1891   addenv(blk, "REQUEST_METHOD=%s", ri->request_method);
1892   addenv(blk, "REMOTE_ADDR=%s", ri->remote_ip);
1893   addenv(blk, "REMOTE_PORT=%d", ri->remote_port);
1894   addenv(blk, "REQUEST_URI=%s%s%s", ri->uri,
1895         ri->query_string == NULL ? "" : "?",
1896         ri->query_string == NULL ? "" : ri->query_string);
1996  addenv(blk, "REQUEST_METHOD=%s", ri->request_method);
1997  addenv(blk, "REMOTE_ADDR=%s", ri->remote_ip);
1998  addenv(blk, "REMOTE_PORT=%d", ri->remote_port);
1999  addenv(blk, "REQUEST_URI=%s%s%s", ri->uri,
2000         ri->query_string == NULL ? "" : "?",
2001         ri->query_string == NULL ? "" : ri->query_string);
18972002
1898   // SCRIPT_NAME
1899   if (conn->path_info != NULL) {
1900   addenv(blk, "SCRIPT_NAME=%.*s",
1901         (int) (strlen(ri->uri) - strlen(conn->path_info)), ri->uri);
1902   addenv(blk, "PATH_INFO=%s", conn->path_info);
1903   } else {
1904   s = strrchr(prog, '/');
1905   slash = strrchr(ri->uri, '/');
1906   addenv(blk, "SCRIPT_NAME=%.*s%s",
1907         slash == NULL ? 0 : (int) (slash - ri->uri), ri->uri,
1908         s == NULL ? prog : s);
1909   }
2003  // SCRIPT_NAME
2004  if (conn->path_info != NULL) {
2005    addenv(blk, "SCRIPT_NAME=%.*s",
2006           (int) (strlen(ri->uri) - strlen(conn->path_info)), ri->uri);
2007    addenv(blk, "PATH_INFO=%s", conn->path_info);
2008  } else {
2009    s = strrchr(prog, '/');
2010    slash = strrchr(ri->uri, '/');
2011    addenv(blk, "SCRIPT_NAME=%.*s%s",
2012           slash == NULL ? 0 : (int) (slash - ri->uri), ri->uri,
2013           s == NULL ? prog : s);
2014  }
19102015
1911   addenv(blk, "SCRIPT_FILENAME=%s", prog);
1912   addenv(blk, "PATH_TRANSLATED=%s", prog);
1913   addenv(blk, "HTTPS=%s", conn->ns_conn->ssl != NULL ? "on" : "off");
2016  addenv(blk, "SCRIPT_FILENAME=%s", prog);
2017  addenv(blk, "PATH_TRANSLATED=%s", prog);
2018  addenv(blk, "HTTPS=%s", conn->ns_conn->ssl != NULL ? "on" : "off");
19142019
1915   if ((s = mg_get_header(ri, "Content-Type")) != NULL)
1916   addenv(blk, "CONTENT_TYPE=%s", s);
2020  if ((s = mg_get_header(ri, "Content-Type")) != NULL)
2021    addenv(blk, "CONTENT_TYPE=%s", s);
19172022
1918   if (ri->query_string != NULL)
1919   addenv(blk, "QUERY_STRING=%s", ri->query_string);
2023  if (ri->query_string != NULL)
2024    addenv(blk, "QUERY_STRING=%s", ri->query_string);
19202025
1921   if ((s = mg_get_header(ri, "Content-Length")) != NULL)
1922   addenv(blk, "CONTENT_LENGTH=%s", s);
2026  if ((s = mg_get_header(ri, "Content-Length")) != NULL)
2027    addenv(blk, "CONTENT_LENGTH=%s", s);
19232028
1924   addenv2(blk, "PATH");
1925   addenv2(blk, "TMP");
1926   addenv2(blk, "TEMP");
1927   addenv2(blk, "TMPDIR");
1928   addenv2(blk, "PERLLIB");
1929   addenv2(blk, ENV_EXPORT_TO_CGI);
2029  addenv2(blk, "PATH");
2030  addenv2(blk, "TMP");
2031  addenv2(blk, "TEMP");
2032  addenv2(blk, "TMPDIR");
2033  addenv2(blk, "PERLLIB");
2034  addenv2(blk, ENV_EXPORT_TO_CGI);
19302035
19312036#if defined(_WIN32)
1932   addenv2(blk, "COMSPEC");
1933   addenv2(blk, "SYSTEMROOT");
1934   addenv2(blk, "SystemDrive");
1935   addenv2(blk, "ProgramFiles");
1936   addenv2(blk, "ProgramFiles(x86)");
1937   addenv2(blk, "CommonProgramFiles(x86)");
2037  addenv2(blk, "COMSPEC");
2038  addenv2(blk, "SYSTEMROOT");
2039  addenv2(blk, "SystemDrive");
2040  addenv2(blk, "ProgramFiles");
2041  addenv2(blk, "ProgramFiles(x86)");
2042  addenv2(blk, "CommonProgramFiles(x86)");
19382043#else
1939   addenv2(blk, "LD_LIBRARY_PATH");
2044  addenv2(blk, "LD_LIBRARY_PATH");
19402045#endif // _WIN32
19412046
1942   // Add all headers as HTTP_* variables
1943   for (i = 0; i < ri->num_headers; i++) {
1944   p = addenv(blk, "HTTP_%s=%s",
1945      ri->http_headers[i].name, ri->http_headers[i].value);
2047  // Add all headers as HTTP_* variables
2048  for (i = 0; i < ri->num_headers; i++) {
2049    p = addenv(blk, "HTTP_%s=%s",
2050        ri->http_headers[i].name, ri->http_headers[i].value);
19462051
1947   // Convert variable name into uppercase, and change - to _
1948   for (; *p != '=' && *p != '\0'; p++) {
1949      if (*p == '-')
1950      *p = '_';
1951      *p = (char) toupper(* (unsigned char *) p);
1952   }
1953   }
2052    // Convert variable name into uppercase, and change - to _
2053    for (; *p != '=' && *p != '\0'; p++) {
2054      if (*p == '-')
2055        *p = '_';
2056      *p = (char) toupper(* (unsigned char *) p);
2057    }
2058  }
19542059
1955   blk->vars[blk->nvars++] = NULL;
1956   blk->buf[blk->len++] = '\0';
2060  blk->vars[blk->nvars++] = NULL;
2061  blk->buf[blk->len++] = '\0';
19572062
1958   assert(blk->nvars < (int) ARRAY_SIZE(blk->vars));
1959   assert(blk->len > 0);
1960   assert(blk->len < (int) sizeof(blk->buf));
2063  assert(blk->nvars < (int) ARRAY_SIZE(blk->vars));
2064  assert(blk->len > 0);
2065  assert(blk->len < (int) sizeof(blk->buf));
19612066}
19622067
19632068static const char cgi_status[] = "HTTP/1.1 200 OK\r\n";
19642069
19652070static void open_cgi_endpoint(struct connection *conn, const char *prog) {
1966   struct cgi_env_block blk;
1967   char dir[MAX_PATH_SIZE];
1968   const char *p;
1969   sock_t fds[2];
2071  struct cgi_env_block blk;
2072  char dir[MAX_PATH_SIZE];
2073  const char *p;
2074  sock_t fds[2];
19702075
1971   prepare_cgi_environment(conn, prog, &blk);
1972   // CGI must be executed in its own directory. 'dir' must point to the
1973   // directory containing executable program, 'p' must point to the
1974   // executable program name relative to 'dir'.
1975   if ((p = strrchr(prog, '/')) == NULL) {
1976   mg_snprintf(dir, sizeof(dir), "%s", ".");
1977   } else {
1978   mg_snprintf(dir, sizeof(dir), "%.*s", (int) (p - prog), prog);
1979   }
2076  prepare_cgi_environment(conn, prog, &blk);
2077  // CGI must be executed in its own directory. 'dir' must point to the
2078  // directory containing executable program, 'p' must point to the
2079  // executable program name relative to 'dir'.
2080  if ((p = strrchr(prog, '/')) == NULL) {
2081    mg_snprintf(dir, sizeof(dir), "%s", ".");
2082  } else {
2083    mg_snprintf(dir, sizeof(dir), "%.*s", (int) (p - prog), prog);
2084  }
19802085
1981   // Try to create socketpair in a loop until success. ns_socketpair()
1982   // can be interrupted by a signal and fail.
1983   // TODO(lsm): use sigaction to restart interrupted syscall
1984   do {
1985   ns_socketpair(fds);
1986   } while (fds[0] == INVALID_SOCKET);
2086  // Try to create socketpair in a loop until success. ns_socketpair()
2087  // can be interrupted by a signal and fail.
2088  // TODO(lsm): use sigaction to restart interrupted syscall
2089  do {
2090    ns_socketpair(fds);
2091  } while (fds[0] == INVALID_SOCKET);
19872092
1988   if (start_process(conn->server->config_options[CGI_INTERPRETER],
1989               prog, blk.buf, blk.vars, dir, fds[1]) > 0) {
1990   conn->endpoint_type = EP_CGI;
1991   conn->endpoint.nc = ns_add_sock(&conn->server->ns_server,
1992                                 fds[0], conn);
1993   conn->endpoint.nc->flags |= MG_CGI_CONN;
1994   ns_send(conn->ns_conn, cgi_status, sizeof(cgi_status) - 1);
1995   conn->mg_conn.status_code = 200;
1996   conn->ns_conn->flags |= NSF_BUFFER_BUT_DONT_SEND;
1997   // Pass POST data to the CGI process
1998   conn->endpoint.nc->send_iobuf = conn->ns_conn->recv_iobuf;
1999   iobuf_init(&conn->ns_conn->recv_iobuf, 0);
2000   } else {
2001   closesocket(fds[0]);
2002   send_http_error(conn, 500, "start_process(%s) failed", prog);
2003   }
2093  if (start_process(conn->server->config_options[CGI_INTERPRETER],
2094                    prog, blk.buf, blk.vars, dir, fds[1]) != 0) {
2095    conn->endpoint_type = EP_CGI;
2096    conn->endpoint.nc = ns_add_sock(&conn->server->ns_server, fds[0], conn);
2097    conn->endpoint.nc->flags |= MG_CGI_CONN;
2098    ns_send(conn->ns_conn, cgi_status, sizeof(cgi_status) - 1);
2099    conn->mg_conn.status_code = 200;
2100    conn->ns_conn->flags |= NSF_BUFFER_BUT_DONT_SEND;
2101    // Pass POST data to the CGI process
2102    conn->endpoint.nc->send_iobuf = conn->ns_conn->recv_iobuf;
2103    iobuf_init(&conn->ns_conn->recv_iobuf, 0);
2104  } else {
2105    closesocket(fds[0]);
2106    send_http_error(conn, 500, "start_process(%s) failed", prog);
2107  }
20042108
20052109#ifndef _WIN32
2006   closesocket(fds[1]);  // On Windows, CGI stdio thread closes that socket
2110  closesocket(fds[1]);  // On Windows, CGI stdio thread closes that socket
20072111#endif
20082112}
20092113
20102114static void on_cgi_data(struct ns_connection *nc) {
2011   struct connection *conn = (struct connection *) nc->connection_data;
2012   const char *status = "500";
2013   struct mg_connection c;
2115  struct connection *conn = (struct connection *) nc->connection_data;
2116  const char *status = "500";
2117  struct mg_connection c;
20142118
2015   if (!conn) return;
2119  if (!conn) return;
20162120
2017   // Copy CGI data from CGI socket to the client send buffer
2018   ns_forward(nc, conn->ns_conn);
2121  // Copy CGI data from CGI socket to the client send buffer
2122  ns_forward(nc, conn->ns_conn);
20192123
2020   // If reply has not been parsed yet, parse it
2021   if (conn->ns_conn->flags & NSF_BUFFER_BUT_DONT_SEND) {
2022   struct iobuf *io = &conn->ns_conn->send_iobuf;
2023   int s_len = sizeof(cgi_status) - 1;
2024   int len = get_request_len(io->buf + s_len, io->len - s_len);
2025   char buf[MAX_REQUEST_SIZE], *s = buf;
2124  // If reply has not been parsed yet, parse it
2125  if (conn->ns_conn->flags & NSF_BUFFER_BUT_DONT_SEND) {
2126    struct iobuf *io = &conn->ns_conn->send_iobuf;
2127    int s_len = sizeof(cgi_status) - 1;
2128    int len = get_request_len(io->buf + s_len, io->len - s_len);
2129    char buf[MAX_REQUEST_SIZE], *s = buf;
20262130
2027   if (len == 0) return;
2131    if (len == 0) return;
20282132
2029   if (len < 0 || len > (int) sizeof(buf)) {
2030      len = io->len;
2031      iobuf_remove(io, io->len);
2032      send_http_error(conn, 500, "CGI program sent malformed headers: [%.*s]",
2033      len, io->buf);
2034   } else {
2035      memset(&c, 0, sizeof(c));
2036      memcpy(buf, io->buf + s_len, len);
2037      buf[len - 1] = '\0';
2038      parse_http_headers(&s, &c);
2039      if (mg_get_header(&c, "Location") != NULL) {
2040      status = "302";
2041      } else if ((status = (char *) mg_get_header(&c, "Status")) == NULL) {
2042      status = "200";
2043      }
2044      memcpy(io->buf + 9, status, 3);
2045      conn->mg_conn.status_code = atoi(status);
2046   }
2047   conn->ns_conn->flags &= ~NSF_BUFFER_BUT_DONT_SEND;
2048   }
2133    if (len < 0 || len > (int) sizeof(buf)) {
2134      len = io->len;
2135      iobuf_remove(io, io->len);
2136      send_http_error(conn, 500, "CGI program sent malformed headers: [%.*s]",
2137        len, io->buf);
2138    } else {
2139      memset(&c, 0, sizeof(c));
2140      memcpy(buf, io->buf + s_len, len);
2141      buf[len - 1] = '\0';
2142      parse_http_headers(&s, &c);
2143      if (mg_get_header(&c, "Location") != NULL) {
2144        status = "302";
2145      } else if ((status = (char *) mg_get_header(&c, "Status")) == NULL) {
2146        status = "200";
2147      }
2148      memcpy(io->buf + 9, status, 3);
2149      conn->mg_conn.status_code = atoi(status);
2150    }
2151    conn->ns_conn->flags &= ~NSF_BUFFER_BUT_DONT_SEND;
2152  }
20492153}
20502154#endif  // !MONGOOSE_NO_CGI
20512155
20522156static char *mg_strdup(const char *str) {
2053   char *copy = (char *) malloc(strlen(str) + 1);
2054   if (copy != NULL) {
2055   strcpy(copy, str);
2056   }
2057   return copy;
2157  char *copy = (char *) malloc(strlen(str) + 1);
2158  if (copy != NULL) {
2159    strcpy(copy, str);
2160  }
2161  return copy;
20582162}
20592163
20602164static int isbyte(int n) {
2061   return n >= 0 && n <= 255;
2165  return n >= 0 && n <= 255;
20622166}
20632167
20642168static int parse_net(const char *spec, uint32_t *net, uint32_t *mask) {
2065   int n, a, b, c, d, slash = 32, len = 0;
2169  int n, a, b, c, d, slash = 32, len = 0;
20662170
2067   if ((sscanf(spec, "%d.%d.%d.%d/%d%n", &a, &b, &c, &d, &slash, &n) == 5 ||
2068      sscanf(spec, "%d.%d.%d.%d%n", &a, &b, &c, &d, &n) == 4) &&
2069      isbyte(a) && isbyte(b) && isbyte(c) && isbyte(d) &&
2070      slash >= 0 && slash < 33) {
2071   len = n;
2072   *net = ((uint32_t)a << 24) | ((uint32_t)b << 16) | ((uint32_t)c << 8) | d;
2073   *mask = slash ? 0xffffffffU << (32 - slash) : 0;
2074   }
2171  if ((sscanf(spec, "%d.%d.%d.%d/%d%n", &a, &b, &c, &d, &slash, &n) == 5 ||
2172      sscanf(spec, "%d.%d.%d.%d%n", &a, &b, &c, &d, &n) == 4) &&
2173      isbyte(a) && isbyte(b) && isbyte(c) && isbyte(d) &&
2174      slash >= 0 && slash < 33) {
2175    len = n;
2176    *net = ((uint32_t)a << 24) | ((uint32_t)b << 16) | ((uint32_t)c << 8) | d;
2177    *mask = slash ? 0xffffffffU << (32 - slash) : 0;
2178  }
20752179
2076   return len;
2180  return len;
20772181}
20782182
20792183// Verify given socket address against the ACL.
20802184// Return -1 if ACL is malformed, 0 if address is disallowed, 1 if allowed.
20812185static int check_acl(const char *acl, uint32_t remote_ip) {
2082   int allowed, flag;
2083   uint32_t net, mask;
2084   struct vec vec;
2186  int allowed, flag;
2187  uint32_t net, mask;
2188  struct vec vec;
20852189
2086   // If any ACL is set, deny by default
2087   allowed = acl == NULL ? '+' : '-';
2190  // If any ACL is set, deny by default
2191  allowed = acl == NULL ? '+' : '-';
20882192
2089   while ((acl = next_option(acl, &vec, NULL)) != NULL) {
2090   flag = vec.ptr[0];
2091   if ((flag != '+' && flag != '-') ||
2092      parse_net(&vec.ptr[1], &net, &mask) == 0) {
2093      return -1;
2094   }
2193  while ((acl = next_option(acl, &vec, NULL)) != NULL) {
2194    flag = vec.ptr[0];
2195    if ((flag != '+' && flag != '-') ||
2196        parse_net(&vec.ptr[1], &net, &mask) == 0) {
2197      return -1;
2198    }
20952199
2096   if (net == (remote_ip & mask)) {
2097      allowed = flag;
2098   }
2099   }
2200    if (net == (remote_ip & mask)) {
2201      allowed = flag;
2202    }
2203  }
21002204
2101   return allowed == '+';
2205  return allowed == '+';
21022206}
21032207
21042208// Protect against directory disclosure attack by removing '..',
21052209// excessive '/' and '\' characters
21062210static void remove_double_dots_and_double_slashes(char *s) {
2107   char *p = s;
2211  char *p = s;
21082212
2109   while (*s != '\0') {
2110   *p++ = *s++;
2111   if (s[-1] == '/' || s[-1] == '\\') {
2112      // Skip all following slashes, backslashes and double-dots
2113      while (s[0] != '\0') {
2114      if (s[0] == '/' || s[0] == '\\') { s++; }
2115      else if (s[0] == '.' && s[1] == '.') { s += 2; }
2116      else { break; }
2117      }
2118   }
2119   }
2120   *p = '\0';
2213  while (*s != '\0') {
2214    *p++ = *s++;
2215    if (s[-1] == '/' || s[-1] == '\\') {
2216      // Skip all following slashes, backslashes and double-dots
2217      while (s[0] != '\0') {
2218        if (s[0] == '/' || s[0] == '\\') { s++; }
2219        else if (s[0] == '.' && s[1] == '.') { s += 2; }
2220        else { break; }
2221      }
2222    }
2223  }
2224  *p = '\0';
21212225}
21222226
21232227int mg_url_decode(const char *src, int src_len, char *dst,
2124               int dst_len, int is_form_url_encoded) {
2125   int i, j, a, b;
2228                  int dst_len, int is_form_url_encoded) {
2229  int i, j, a, b;
21262230#define HEXTOI(x) (isdigit(x) ? x - '0' : x - 'W')
21272231
2128   for (i = j = 0; i < src_len && j < dst_len - 1; i++, j++) {
2129   if (src[i] == '%' && i < src_len - 2 &&
2130      isxdigit(* (const unsigned char *) (src + i + 1)) &&
2131      isxdigit(* (const unsigned char *) (src + i + 2))) {
2132      a = tolower(* (const unsigned char *) (src + i + 1));
2133      b = tolower(* (const unsigned char *) (src + i + 2));
2134      dst[j] = (char) ((HEXTOI(a) << 4) | HEXTOI(b));
2135      i += 2;
2136   } else if (is_form_url_encoded && src[i] == '+') {
2137      dst[j] = ' ';
2138   } else {
2139      dst[j] = src[i];
2140   }
2141   }
2232  for (i = j = 0; i < src_len && j < dst_len - 1; i++, j++) {
2233    if (src[i] == '%' && i < src_len - 2 &&
2234        isxdigit(* (const unsigned char *) (src + i + 1)) &&
2235        isxdigit(* (const unsigned char *) (src + i + 2))) {
2236      a = tolower(* (const unsigned char *) (src + i + 1));
2237      b = tolower(* (const unsigned char *) (src + i + 2));
2238      dst[j] = (char) ((HEXTOI(a) << 4) | HEXTOI(b));
2239      i += 2;
2240    } else if (is_form_url_encoded && src[i] == '+') {
2241      dst[j] = ' ';
2242    } else {
2243      dst[j] = src[i];
2244    }
2245  }
21422246
2143   dst[j] = '\0'; // Null-terminate the destination
2247  dst[j] = '\0'; // Null-terminate the destination
21442248
2145   return i >= src_len ? j : -1;
2249  return i >= src_len ? j : -1;
21462250}
21472251
21482252static int is_valid_http_method(const char *s) {
2149   return !strcmp(s, "GET") || !strcmp(s, "POST") || !strcmp(s, "HEAD") ||
2150   !strcmp(s, "CONNECT") || !strcmp(s, "PUT") || !strcmp(s, "DELETE") ||
2151   !strcmp(s, "OPTIONS") || !strcmp(s, "PROPFIND") || !strcmp(s, "MKCOL");
2253  return !strcmp(s, "GET") || !strcmp(s, "POST") || !strcmp(s, "HEAD") ||
2254    !strcmp(s, "CONNECT") || !strcmp(s, "PUT") || !strcmp(s, "DELETE") ||
2255    !strcmp(s, "OPTIONS") || !strcmp(s, "PROPFIND") || !strcmp(s, "MKCOL");
21522256}
21532257
21542258// Parse HTTP request, fill in mg_request structure.
r31874r31875
21562260// HTTP request components, header names and header values.
21572261// Note that len must point to the last \n of HTTP headers.
21582262static int parse_http_message(char *buf, int len, struct mg_connection *ri) {
2159   int is_request, n;
2263  int is_request, n;
21602264
2161   // Reset the connection. Make sure that we don't touch fields that are
2162   // set elsewhere: remote_ip, remote_port, server_param
2163   ri->request_method = ri->uri = ri->http_version = ri->query_string = NULL;
2164   ri->num_headers = ri->status_code = ri->is_websocket = ri->content_len = 0;
2265  // Reset the connection. Make sure that we don't touch fields that are
2266  // set elsewhere: remote_ip, remote_port, server_param
2267  ri->request_method = ri->uri = ri->http_version = ri->query_string = NULL;
2268  ri->num_headers = ri->status_code = ri->is_websocket = ri->content_len = 0;
21652269
2166   buf[len - 1] = '\0';
2270  buf[len - 1] = '\0';
21672271
2168   // RFC says that all initial whitespaces should be ingored
2169   while (*buf != '\0' && isspace(* (unsigned char *) buf)) {
2170   buf++;
2171   }
2172   ri->request_method = skip(&buf, " ");
2173   ri->uri = skip(&buf, " ");
2174   ri->http_version = skip(&buf, "\r\n");
2272  // RFC says that all initial whitespaces should be ingored
2273  while (*buf != '\0' && isspace(* (unsigned char *) buf)) {
2274    buf++;
2275  }
2276  ri->request_method = skip(&buf, " ");
2277  ri->uri = skip(&buf, " ");
2278  ri->http_version = skip(&buf, "\r\n");
21752279
2176   // HTTP message could be either HTTP request or HTTP response, e.g.
2177   // "GET / HTTP/1.0 ...." or  "HTTP/1.0 200 OK ..."
2178   is_request = is_valid_http_method(ri->request_method);
2179   if ((is_request && memcmp(ri->http_version, "HTTP/", 5) != 0) ||
2180      (!is_request && memcmp(ri->request_method, "HTTP/", 5) != 0)) {
2181   len = -1;
2182   } else {
2183   if (is_request) {
2184      ri->http_version += 5;
2185   }
2186   parse_http_headers(&buf, ri);
2280  // HTTP message could be either HTTP request or HTTP response, e.g.
2281  // "GET / HTTP/1.0 ...." or  "HTTP/1.0 200 OK ..."
2282  is_request = is_valid_http_method(ri->request_method);
2283  if ((is_request && memcmp(ri->http_version, "HTTP/", 5) != 0) ||
2284      (!is_request && memcmp(ri->request_method, "HTTP/", 5) != 0)) {
2285    len = -1;
2286  } else {
2287    if (is_request) {
2288      ri->http_version += 5;
2289    }
2290    parse_http_headers(&buf, ri);
21872291
2188   if ((ri->query_string = strchr(ri->uri, '?')) != NULL) {
2189      *(char *) ri->query_string++ = '\0';
2190   }
2191   n = (int) strlen(ri->uri);
2192   mg_url_decode(ri->uri, n, (char *) ri->uri, n + 1, 0);
2193   if (*ri->uri == '/' || *ri->uri == '.') {
2194      remove_double_dots_and_double_slashes((char *) ri->uri);
2195   }
2196   }
2292    if ((ri->query_string = strchr(ri->uri, '?')) != NULL) {
2293      *(char *) ri->query_string++ = '\0';
2294    }
2295    n = (int) strlen(ri->uri);
2296    mg_url_decode(ri->uri, n, (char *) ri->uri, n + 1, 0);
2297    if (*ri->uri == '/' || *ri->uri == '.') {
2298      remove_double_dots_and_double_slashes((char *) ri->uri);
2299    }
2300  }
21972301
2198   return len;
2302  return len;
21992303}
22002304
22012305static int lowercase(const char *s) {
2202   return tolower(* (const unsigned char *) s);
2306  return tolower(* (const unsigned char *) s);
22032307}
22042308
22052309static int mg_strcasecmp(const char *s1, const char *s2) {
2206   int diff;
2310  int diff;
22072311
2208   do {
2209   diff = lowercase(s1++) - lowercase(s2++);
2210   } while (diff == 0 && s1[-1] != '\0');
2312  do {
2313    diff = lowercase(s1++) - lowercase(s2++);
2314  } while (diff == 0 && s1[-1] != '\0');
22112315
2212   return diff;
2316  return diff;
22132317}
22142318
22152319static int mg_strncasecmp(const char *s1, const char *s2, size_t len) {
2216   int diff = 0;
2320  int diff = 0;
22172321
2218   if (len > 0)
2219   do {
2220      diff = lowercase(s1++) - lowercase(s2++);
2221   } while (diff == 0 && s1[-1] != '\0' && --len > 0);
2322  if (len > 0)
2323    do {
2324      diff = lowercase(s1++) - lowercase(s2++);
2325    } while (diff == 0 && s1[-1] != '\0' && --len > 0);
22222326
2223   return diff;
2327  return diff;
22242328}
22252329
22262330// Return HTTP header value, or NULL if not found.
22272331const char *mg_get_header(const struct mg_connection *ri, const char *s) {
2228   int i;
2332  int i;
22292333
2230   for (i = 0; i < ri->num_headers; i++)
2231   if (!mg_strcasecmp(s, ri->http_headers[i].name))
2232      return ri->http_headers[i].value;
2334  for (i = 0; i < ri->num_headers; i++)
2335    if (!mg_strcasecmp(s, ri->http_headers[i].name))
2336      return ri->http_headers[i].value;
22332337
2234   return NULL;
2338  return NULL;
22352339}
22362340
22372341// Perform case-insensitive match of string against pattern
22382342int mg_match_prefix(const char *pattern, int pattern_len, const char *str) {
2239   const char *or_str;
2240   int len, res, i = 0, j = 0;
2343  const char *or_str;
2344  int len, res, i = 0, j = 0;
22412345
2242   if ((or_str = (const char *) memchr(pattern, '|', pattern_len)) != NULL) {
2243   res = mg_match_prefix(pattern, or_str - pattern, str);
2244   return res > 0 ? res : mg_match_prefix(or_str + 1,
2245      (pattern + pattern_len) - (or_str + 1), str);
2246   }
2346  if ((or_str = (const char *) memchr(pattern, '|', pattern_len)) != NULL) {
2347    res = mg_match_prefix(pattern, or_str - pattern, str);
2348    return res > 0 ? res : mg_match_prefix(or_str + 1,
2349      (pattern + pattern_len) - (or_str + 1), str);
2350  }
22472351
2248   for (; i < pattern_len; i++, j++) {
2249   if (pattern[i] == '?' && str[j] != '\0') {
2250      continue;
2251   } else if (pattern[i] == '$') {
2252      return str[j] == '\0' ? j : -1;
2253   } else if (pattern[i] == '*') {
2254      i++;
2255      if (pattern[i] == '*') {
2256      i++;
2257      len = (int) strlen(str + j);
2258      } else {
2259      len = (int) strcspn(str + j, "/");
2260      }
2261      if (i == pattern_len) {
2262      return j + len;
2263      }
2264      do {
2265      res = mg_match_prefix(pattern + i, pattern_len - i, str + j + len);
2266      } while (res == -1 && len-- > 0);
2267      return res == -1 ? -1 : j + res + len;
2268   } else if (lowercase(&pattern[i]) != lowercase(&str[j])) {
2269      return -1;
2270   }
2271   }
2272   return j;
2352  for (; i < pattern_len; i++, j++) {
2353    if (pattern[i] == '?' && str[j] != '\0') {
2354      continue;
2355    } else if (pattern[i] == '$') {
2356      return str[j] == '\0' ? j : -1;
2357    } else if (pattern[i] == '*') {
2358      i++;
2359      if (pattern[i] == '*') {
2360        i++;
2361        len = (int) strlen(str + j);
2362      } else {
2363        len = (int) strcspn(str + j, "/");
2364      }
2365      if (i == pattern_len) {
2366        return j + len;
2367      }
2368      do {
2369        res = mg_match_prefix(pattern + i, pattern_len - i, str + j + len);
2370      } while (res == -1 && len-- > 0);
2371      return res == -1 ? -1 : j + res + len;
2372    } else if (lowercase(&pattern[i]) != lowercase(&str[j])) {
2373      return -1;
2374    }
2375  }
2376  return j;
22732377}
22742378
22752379// This function prints HTML pages, and expands "{{something}}" blocks
r31874r31875
22772381// Note that {{@path/to/file}} construct outputs embedded file's contents,
22782382// which provides SSI-like functionality.
22792383void mg_template(struct mg_connection *conn, const char *s,
2280               struct mg_expansion *expansions) {
2281   int i, j, pos = 0, inside_marker = 0;
2384                 struct mg_expansion *expansions) {
2385  int i, j, pos = 0, inside_marker = 0;
22822386
2283   for (i = 0; s[i] != '\0'; i++) {
2284   if (inside_marker == 0 && !memcmp(&s[i], "{{", 2)) {
2285      if (i > pos) {
2286      mg_send_data(conn, &s[pos], i - pos);
2287      }
2288      pos = i;
2289      inside_marker = 1;
2290   }
2291   if (inside_marker == 1 && !memcmp(&s[i], "}}", 2)) {
2292      for (j = 0; expansions[j].keyword != NULL; j++) {
2293      const char *kw = expansions[j].keyword;
2294      if ((int) strlen(kw) == i - (pos + 2) &&
2295         memcmp(kw, &s[pos + 2], i - (pos + 2)) == 0) {
2296         expansions[j].handler(conn);
2297         pos = i + 2;
2298         break;
2299      }
2300      }
2301      inside_marker = 0;
2302   }
2303   }
2304   if (i > pos) {
2305   mg_send_data(conn, &s[pos], i - pos);
2306   }
2387  for (i = 0; s[i] != '\0'; i++) {
2388    if (inside_marker == 0 && !memcmp(&s[i], "{{", 2)) {
2389      if (i > pos) {
2390        mg_send_data(conn, &s[pos], i - pos);
2391      }
2392      pos = i;
2393      inside_marker = 1;
2394    }
2395    if (inside_marker == 1 && !memcmp(&s[i], "}}", 2)) {
2396      for (j = 0; expansions[j].keyword != NULL; j++) {
2397        const char *kw = expansions[j].keyword;
2398        if ((int) strlen(kw) == i - (pos + 2) &&
2399            memcmp(kw, &s[pos + 2], i - (pos + 2)) == 0) {
2400          expansions[j].handler(conn);
2401          pos = i + 2;
2402          break;
2403        }
2404      }
2405      inside_marker = 0;
2406    }
2407  }
2408  if (i > pos) {
2409    mg_send_data(conn, &s[pos], i - pos);
2410  }
23072411}
23082412
23092413#ifndef MONGOOSE_NO_FILESYSTEM
23102414static int must_hide_file(struct connection *conn, const char *path) {
2311   const char *pw_pattern = "**" PASSWORDS_FILE_NAME "$";
2312   const char *pattern = conn->server->config_options[HIDE_FILES_PATTERN];
2313   return mg_match_prefix(pw_pattern, strlen(pw_pattern), path) > 0 ||
2314   (pattern != NULL && mg_match_prefix(pattern, strlen(pattern), path) > 0);
2415  const char *pw_pattern = "**" PASSWORDS_FILE_NAME "$";
2416  const char *pattern = conn->server->config_options[HIDE_FILES_PATTERN];
2417  return mg_match_prefix(pw_pattern, strlen(pw_pattern), path) > 0 ||
2418    (pattern != NULL && mg_match_prefix(pattern, strlen(pattern), path) > 0);
23152419}
23162420
23172421// Return 1 if real file has been found, 0 otherwise
23182422static int convert_uri_to_file_name(struct connection *conn, char *buf,
2319                           size_t buf_len, file_stat_t *st) {
2320   struct vec a, b;
2321   const char *rewrites = conn->server->config_options[URL_REWRITES];
2322   const char *root = conn->server->config_options[DOCUMENT_ROOT];
2423                                    size_t buf_len, file_stat_t *st) {
2424  struct vec a, b;
2425  const char *rewrites = conn->server->config_options[URL_REWRITES];
2426  const char *root = conn->server->config_options[DOCUMENT_ROOT];
23232427#ifndef MONGOOSE_NO_CGI
2324   const char *cgi_pat = conn->server->config_options[CGI_PATTERN];
2325   char *p;
2428  const char *cgi_pat = conn->server->config_options[CGI_PATTERN];
2429  char *p;
23262430#endif
2327   const char *uri = conn->mg_conn.uri;
2328   const char *domain = mg_get_header(&conn->mg_conn, "Host");
2329   int match_len, root_len = root == NULL ? 0 : strlen(root);
2431  const char *uri = conn->mg_conn.uri;
2432  const char *domain = mg_get_header(&conn->mg_conn, "Host");
2433  int match_len, root_len = root == NULL ? 0 : strlen(root);
23302434
2331   // Perform virtual hosting rewrites
2332   if (rewrites != NULL && domain != NULL) {
2333   const char *colon = strchr(domain, ':');
2334   int domain_len = colon == NULL ? (int) strlen(domain) : colon - domain;
2435  // Perform virtual hosting rewrites
2436  if (rewrites != NULL && domain != NULL) {
2437    const char *colon = strchr(domain, ':');
2438    int domain_len = colon == NULL ? (int) strlen(domain) : colon - domain;
23352439
2336   while ((rewrites = next_option(rewrites, &a, &b)) != NULL) {
2337      if (a.len > 1 && a.ptr[0] == '@' && a.len == domain_len + 1 &&
2338         mg_strncasecmp(a.ptr + 1, domain, domain_len) == 0) {
2339      root = b.ptr;
2340      root_len = b.len;
2341      break;
2342      }
2343   }
2344   }
2440    while ((rewrites = next_option(rewrites, &a, &b)) != NULL) {
2441      if (a.len > 1 && a.ptr[0] == '@' && a.len == domain_len + 1 &&
2442          mg_strncasecmp(a.ptr + 1, domain, domain_len) == 0) {
2443        root = b.ptr;
2444        root_len = b.len;
2445        break;
2446      }
2447    }
2448  }
23452449
2346   // No filesystem access
2347   if (root == NULL || root_len == 0) return 0;
2450  // No filesystem access
2451  if (root == NULL || root_len == 0) return 0;
23482452
2349   // Handle URL rewrites
2350   mg_snprintf(buf, buf_len, "%.*s%s", root_len, root, uri);
2351   rewrites = conn->server->config_options[URL_REWRITES];  // Re-initialize!
2352   while ((rewrites = next_option(rewrites, &a, &b)) != NULL) {
2353   if ((match_len = mg_match_prefix(a.ptr, a.len, uri)) > 0) {
2354      mg_snprintf(buf, buf_len, "%.*s%s", (int) b.len, b.ptr, uri + match_len);
2355      break;
2356   }
2357   }
2453  // Handle URL rewrites
2454  mg_snprintf(buf, buf_len, "%.*s%s", root_len, root, uri);
2455  rewrites = conn->server->config_options[URL_REWRITES];  // Re-initialize!
2456  while ((rewrites = next_option(rewrites, &a, &b)) != NULL) {
2457    if ((match_len = mg_match_prefix(a.ptr, a.len, uri)) > 0) {
2458      mg_snprintf(buf, buf_len, "%.*s%s", (int) b.len, b.ptr, uri + match_len);
2459      break;
2460    }
2461  }
23582462
2359   if (stat(buf, st) == 0) return 1;
2463  if (stat(buf, st) == 0) return 1;
23602464
23612465#ifndef MONGOOSE_NO_CGI
2362   // Support PATH_INFO for CGI scripts.
2363   for (p = buf + strlen(root) + 2; *p != '\0'; p++) {
2364   if (*p == '/') {
2365      *p = '\0';
2366      if (mg_match_prefix(cgi_pat, strlen(cgi_pat), buf) > 0 &&
2367         !stat(buf, st)) {
2368      DBG(("!!!! [%s]", buf));
2369      *p = '/';
2370      conn->path_info = mg_strdup(p);
2371      *p = '\0';
2372      return 1;
2373      }
2374      *p = '/';
2375   }
2376   }
2466  // Support PATH_INFO for CGI scripts.
2467  for (p = buf + strlen(root) + 2; *p != '\0'; p++) {
2468    if (*p == '/') {
2469      *p = '\0';
2470      if (mg_match_prefix(cgi_pat, strlen(cgi_pat), buf) > 0 &&
2471          !stat(buf, st)) {
2472      DBG(("!!!! [%s]", buf));
2473        *p = '/';
2474        conn->path_info = mg_strdup(p);
2475        *p = '\0';
2476        return 1;
2477      }
2478      *p = '/';
2479    }
2480  }
23772481#endif
23782482
2379   return 0;
2483  return 0;
23802484}
23812485#endif  // MONGOOSE_NO_FILESYSTEM
23822486
23832487static int should_keep_alive(const struct mg_connection *conn) {
2384   struct connection *c = MG_CONN_2_CONN(conn);
2385   const char *method = conn->request_method;
2386   const char *http_version = conn->http_version;
2387   const char *header = mg_get_header(conn, "Connection");
2388   return method != NULL &&
2389   (!strcmp(method, "GET") || c->endpoint_type == EP_USER) &&
2390   ((header != NULL && !mg_strcasecmp(header, "keep-alive")) ||
2391      (header == NULL && http_version && !strcmp(http_version, "1.1")));
2488  struct connection *c = MG_CONN_2_CONN(conn);
2489  const char *method = conn->request_method;
2490  const char *http_version = conn->http_version;
2491  const char *header = mg_get_header(conn, "Connection");
2492  return method != NULL &&
2493    (!strcmp(method, "GET") || c->endpoint_type == EP_USER) &&
2494    ((header != NULL && !mg_strcasecmp(header, "keep-alive")) ||
2495     (header == NULL && http_version && !strcmp(http_version, "1.1")));
23922496}
23932497
23942498size_t mg_write(struct mg_connection *c, const void *buf, int len) {
2395   struct connection *conn = MG_CONN_2_CONN(c);
2396   ns_send(conn->ns_conn, buf, len);
2397   return conn->ns_conn->send_iobuf.len;
2499  struct connection *conn = MG_CONN_2_CONN(c);
2500  ns_send(conn->ns_conn, buf, len);
2501  return conn->ns_conn->send_iobuf.len;
23982502}
23992503
24002504void mg_send_status(struct mg_connection *c, int status) {
2401   if (c->status_code == 0) {
2402   c->status_code = status;
2403   mg_printf(c, "HTTP/1.1 %d %s\r\n", status, status_code_to_str(status));
2404   }
2505  if (c->status_code == 0) {
2506    c->status_code = status;
2507    mg_printf(c, "HTTP/1.1 %d %s\r\n", status, status_code_to_str(status));
2508  }
24052509}
24062510
24072511void mg_send_header(struct mg_connection *c, const char *name, const char *v) {
2408   if (c->status_code == 0) {
2409   c->status_code = 200;
2410   mg_printf(c, "HTTP/1.1 %d %s\r\n", 200, status_code_to_str(200));
2411   }
2412   mg_printf(c, "%s: %s\r\n", name, v);
2512  if (c->status_code == 0) {
2513    c->status_code = 200;
2514    mg_printf(c, "HTTP/1.1 %d %s\r\n", 200, status_code_to_str(200));
2515  }
2516  mg_printf(c, "%s: %s\r\n", name, v);
24132517}
24142518
24152519static void terminate_headers(struct mg_connection *c) {
2416   struct connection *conn = MG_CONN_2_CONN(c);
2417   if (!(conn->ns_conn->flags & MG_HEADERS_SENT)) {
2418   mg_send_header(c, "Transfer-Encoding", "chunked");
2419   mg_write(c, "\r\n", 2);
2420   conn->ns_conn->flags |= MG_HEADERS_SENT;
2421   }
2520  struct connection *conn = MG_CONN_2_CONN(c);
2521  if (!(conn->ns_conn->flags & MG_HEADERS_SENT)) {
2522    mg_send_header(c, "Transfer-Encoding", "chunked");
2523    mg_write(c, "\r\n", 2);
2524    conn->ns_conn->flags |= MG_HEADERS_SENT;
2525  }
24222526}
24232527
24242528size_t mg_send_data(struct mg_connection *c, const void *data, int data_len) {
2425   struct connection *conn = MG_CONN_2_CONN(c);
2426   terminate_headers(c);
2427   write_chunk(MG_CONN_2_CONN(c), (const char *) data, data_len);
2428   return conn->ns_conn->send_iobuf.len;
2529  struct connection *conn = MG_CONN_2_CONN(c);
2530  terminate_headers(c);
2531  write_chunk(MG_CONN_2_CONN(c), (const char *) data, data_len);
2532  return conn->ns_conn->send_iobuf.len;
24292533}
24302534
24312535size_t mg_printf_data(struct mg_connection *c, const char *fmt, ...) {
2432   struct connection *conn = MG_CONN_2_CONN(c);
2433   va_list ap;
2434   int len;
2435   char mem[IOBUF_SIZE], *buf = mem;
2536  struct connection *conn = MG_CONN_2_CONN(c);
2537  va_list ap;
2538  int len;
2539  char mem[IOBUF_SIZE], *buf = mem;
24362540
2437   terminate_headers(c);
2541  terminate_headers(c);
24382542
2439   va_start(ap, fmt);
2440   len = ns_avprintf(&buf, sizeof(mem), fmt, ap);
2441   va_end(ap);
2543  va_start(ap, fmt);
2544  len = ns_avprintf(&buf, sizeof(mem), fmt, ap);
2545  va_end(ap);
24422546
2443   if (len >= 0) {
2444   write_chunk((struct connection *) conn, buf, len);
2445   }
2446   if (buf != mem && buf != NULL) {
2447   free(buf);
2448   }
2449   return conn->ns_conn->send_iobuf.len;
2547  if (len >= 0) {
2548    write_chunk((struct connection *) conn, buf, len);
2549  }
2550  if (buf != mem && buf != NULL) {
2551    free(buf);
2552  }
2553  return conn->ns_conn->send_iobuf.len;
24502554}
24512555
24522556#if !defined(MONGOOSE_NO_WEBSOCKET) || !defined(MONGOOSE_NO_AUTH)
24532557static int is_big_endian(void) {
2454   static const int n = 1;
2455   return ((char *) &n)[0] == 0;
2558  static const int n = 1;
2559  return ((char *) &n)[0] == 0;
24562560}
24572561#endif
24582562
r31874r31875
24692573#define rol(value, bits) (((value) << (bits)) | ((value) >> (32 - (bits))))
24702574
24712575static uint32_t blk0(union char64long16 *block, int i) {
2472   // Forrest: SHA expect BIG_ENDIAN, swap if LITTLE_ENDIAN
2473   if (!is_big_endian()) {
2474   block->l[i] = (rol(block->l[i], 24) & 0xFF00FF00) |
2475      (rol(block->l[i], 8) & 0x00FF00FF);
2476   }
2477   return block->l[i];
2576  // Forrest: SHA expect BIG_ENDIAN, swap if LITTLE_ENDIAN
2577  if (!is_big_endian()) {
2578    block->l[i] = (rol(block->l[i], 24) & 0xFF00FF00) |
2579      (rol(block->l[i], 8) & 0x00FF00FF);
2580  }
2581  return block->l[i];
24782582}
24792583
24802584#define blk(i) (block->l[i&15] = rol(block->l[(i+13)&15]^block->l[(i+8)&15] \
2481   ^block->l[(i+2)&15]^block->l[i&15],1))
2585    ^block->l[(i+2)&15]^block->l[i&15],1))
24822586#define R0(v,w,x,y,z,i) z+=((w&(x^y))^y)+blk0(block, i)+0x5A827999+rol(v,5);w=rol(w,30);
24832587#define R1(v,w,x,y,z,i) z+=((w&(x^y))^y)+blk(i)+0x5A827999+rol(v,5);w=rol(w,30);
24842588#define R2(v,w,x,y,z,i) z+=(w^x^y)+blk(i)+0x6ED9EBA1+rol(v,5);w=rol(w,30);
r31874r31875
24862590#define R4(v,w,x,y,z,i) z+=(w^x^y)+blk(i)+0xCA62C1D6+rol(v,5);w=rol(w,30);
24872591
24882592typedef struct {
2489   uint32_t state[5];
2490   uint32_t count[2];
2491   unsigned char buffer[64];
2593    uint32_t state[5];
2594    uint32_t count[2];
2595    unsigned char buffer[64];
24922596} SHA1_CTX;
24932597
24942598static void SHA1Transform(uint32_t state[5], const unsigned char buffer[64]) {
2495   uint32_t a, b, c, d, e;
2496   union char64long16 block[1];
2599  uint32_t a, b, c, d, e;
2600  union char64long16 block[1];
24972601
2498   memcpy(block, buffer, 64);
2499   a = state[0];
2500   b = state[1];
2501   c = state[2];
2502   d = state[3];
2503   e = state[4];
2504   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);
2505   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);
2506   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);
2507   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);
2508   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);
2509   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);
2510   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);
2511   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);
2512   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);
2513   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);
2514   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);
2515   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);
2516   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);
2517   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);
2518   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);
2519   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);
2520   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);
2521   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);
2522   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);
2523   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);
2524   state[0] += a;
2525   state[1] += b;
2526   state[2] += c;
2527   state[3] += d;
2528   state[4] += e;
2529   // Erase working structures. The order of operations is important,
2530   // used to ensure that compiler doesn't optimize those out.
2531   memset(block, 0, sizeof(block));
2532   a = b = c = d = e = 0;
2533   (void) a; (void) b; (void) c; (void) d; (void) e;
2602  memcpy(block, buffer, 64);
2603  a = state[0];
2604  b = state[1];
2605  c = state[2];
2606  d = state[3];
2607  e = state[4];
2608  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);
2609  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);
2610  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);
2611  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);
2612  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);
2613  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);
2614  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);
2615  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);
2616  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);
2617  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);
2618  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);
2619  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);
2620  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);
2621  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);
2622  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);
2623  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);
2624  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);
2625  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);
2626  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);
2627  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);
2628  state[0] += a;
2629  state[1] += b;
2630  state[2] += c;
2631  state[3] += d;
2632  state[4] += e;
2633  // Erase working structures. The order of operations is important,
2634  // used to ensure that compiler doesn't optimize those out.
2635  memset(block, 0, sizeof(block));
2636  a = b = c = d = e = 0;
2637  (void) a; (void) b; (void) c; (void) d; (void) e;
25342638}
25352639
2536static void SHA1Init(SHA1_CTX* context) {
2537   context->state[0] = 0x67452301;
2538   context->state[1] = 0xEFCDAB89;
2539   context->state[2] = 0x98BADCFE;
2540   context->state[3] = 0x10325476;
2541   context->state[4] = 0xC3D2E1F0;
2542   context->count[0] = context->count[1] = 0;
2640static void SHA1Init(SHA1_CTX *context) {
2641  context->state[0] = 0x67452301;
2642  context->state[1] = 0xEFCDAB89;
2643  context->state[2] = 0x98BADCFE;
2644  context->state[3] = 0x10325476;
2645  context->state[4] = 0xC3D2E1F0;
2646  context->count[0] = context->count[1] = 0;
25432647}
25442648
2545static void SHA1Update(SHA1_CTX* context, const unsigned char* data,
2546                  uint32_t len) {
2547   uint32_t i, j;
2649static void SHA1Update(SHA1_CTX *context, const unsigned char *data,
2650                       uint32_t len) {
2651  uint32_t i, j;
25482652
2549   j = context->count[0];
2550   if ((context->count[0] += len << 3) < j)
2551   context->count[1]++;
2552   context->count[1] += (len>>29);
2553   j = (j >> 3) & 63;
2554   if ((j + len) > 63) {
2555   memcpy(&context->buffer[j], data, (i = 64-j));
2556   SHA1Transform(context->state, context->buffer);
2557   for ( ; i + 63 < len; i += 64) {
2558      SHA1Transform(context->state, &data[i]);
2559   }
2560   j = 0;
2561   }
2562   else i = 0;
2563   memcpy(&context->buffer[j], &data[i], len - i);
2653  j = context->count[0];
2654  if ((context->count[0] += len << 3) < j)
2655    context->count[1]++;
2656  context->count[1] += (len>>29);
2657  j = (j >> 3) & 63;
2658  if ((j + len) > 63) {
2659    memcpy(&context->buffer[j], data, (i = 64-j));
2660    SHA1Transform(context->state, context->buffer);
2661    for ( ; i + 63 < len; i += 64) {
2662      SHA1Transform(context->state, &data[i]);
2663    }
2664    j = 0;
2665  }
2666  else i = 0;
2667  memcpy(&context->buffer[j], &data[i], len - i);
25642668}
25652669
2566static void SHA1Final(unsigned char digest[20], SHA1_CTX* context) {
2567   unsigned i;
2568   unsigned char finalcount[8], c;
2670static void SHA1Final(unsigned char digest[20], SHA1_CTX *context) {
2671  unsigned i;
2672  unsigned char finalcount[8], c;
25692673
2570   for (i = 0; i < 8; i++) {
2571   finalcount[i] = (unsigned char)((context->count[(i >= 4 ? 0 : 1)]
2572                              >> ((3-(i & 3)) * 8) ) & 255);
2573   }
2574   c = 0200;
2575   SHA1Update(context, &c, 1);
2576   while ((context->count[0] & 504) != 448) {
2577   c = 0000;
2578   SHA1Update(context, &c, 1);
2579   }
2580   SHA1Update(context, finalcount, 8);
2581   for (i = 0; i < 20; i++) {
2582   digest[i] = (unsigned char)
2583      ((context->state[i>>2] >> ((3-(i & 3)) * 8) ) & 255);
2584   }
2585   memset(context, '\0', sizeof(*context));
2586   memset(&finalcount, '\0', sizeof(finalcount));
2674  for (i = 0; i < 8; i++) {
2675    finalcount[i] = (unsigned char)((context->count[(i >= 4 ? 0 : 1)]
2676                                     >> ((3-(i & 3)) * 8) ) & 255);
2677  }
2678  c = 0200;
2679  SHA1Update(context, &c, 1);
2680  while ((context->count[0] & 504) != 448) {
2681    c = 0000;
2682    SHA1Update(context, &c, 1);
2683  }
2684  SHA1Update(context, finalcount, 8);
2685  for (i = 0; i < 20; i++) {
2686    digest[i] = (unsigned char)
2687      ((context->state[i>>2] >> ((3-(i & 3)) * 8) ) & 255);
2688  }
2689  memset(context, '\0', sizeof(*context));
2690  memset(&finalcount, '\0', sizeof(finalcount));
25872691}
25882692// END OF SHA1 CODE
25892693
25902694static void base64_encode(const unsigned char *src, int src_len, char *dst) {
2591   static const char *b64 =
2592   "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
2593   int i, j, a, b, c;
2695  static const char *b64 =
2696    "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
2697  int i, j, a, b, c;
25942698
2595   for (i = j = 0; i < src_len; i += 3) {
2596   a = src[i];
2597   b = i + 1 >= src_len ? 0 : src[i + 1];
2598   c = i + 2 >= src_len ? 0 : src[i + 2];
2699  for (i = j = 0; i < src_len; i += 3) {
2700    a = src[i];
2701    b = i + 1 >= src_len ? 0 : src[i + 1];
2702    c = i + 2 >= src_len ? 0 : src[i + 2];
25992703
2600   dst[j++] = b64[a >> 2];
2601   dst[j++] = b64[((a & 3) << 4) | (b >> 4)];
2602   if (i + 1 < src_len) {
2603      dst[j++] = b64[(b & 15) << 2 | (c >> 6)];
2604   }
2605   if (i + 2 < src_len) {
2606      dst[j++] = b64[c & 63];
2607   }
2608   }
2609   while (j % 4 != 0) {
2610   dst[j++] = '=';
2611   }
2612   dst[j++] = '\0';
2704    dst[j++] = b64[a >> 2];
2705    dst[j++] = b64[((a & 3) << 4) | (b >> 4)];
2706    if (i + 1 < src_len) {
2707      dst[j++] = b64[(b & 15) << 2 | (c >> 6)];
2708    }
2709    if (i + 2 < src_len) {
2710      dst[j++] = b64[c & 63];
2711    }
2712  }
2713  while (j % 4 != 0) {
2714    dst[j++] = '=';
2715  }
2716  dst[j++] = '\0';
26132717}
26142718
26152719static void send_websocket_handshake(struct mg_connection *conn,
2616                              const char *key) {
2617   static const char *magic = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
2618   char buf[500], sha[20], b64_sha[sizeof(sha) * 2];
2619   SHA1_CTX sha_ctx;
2720                                     const char *key) {
2721  static const char *magic = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
2722  char buf[500], sha[20], b64_sha[sizeof(sha) * 2];
2723  SHA1_CTX sha_ctx;
26202724
2621   mg_snprintf(buf, sizeof(buf), "%s%s", key, magic);
2622   SHA1Init(&sha_ctx);
2623   SHA1Update(&sha_ctx, (unsigned char *) buf, strlen(buf));
2624   SHA1Final((unsigned char *) sha, &sha_ctx);
2625   base64_encode((unsigned char *) sha, sizeof(sha), b64_sha);
2626   mg_snprintf(buf, sizeof(buf), "%s%s%s",
2627            "HTTP/1.1 101 Switching Protocols\r\n"
2628            "Upgrade: websocket\r\n"
2629            "Connection: Upgrade\r\n"
2630            "Sec-WebSocket-Accept: ", b64_sha, "\r\n\r\n");
2725  mg_snprintf(buf, sizeof(buf), "%s%s", key, magic);
2726  SHA1Init(&sha_ctx);
2727  SHA1Update(&sha_ctx, (unsigned char *) buf, strlen(buf));
2728  SHA1Final((unsigned char *) sha, &sha_ctx);
2729  base64_encode((unsigned char *) sha, sizeof(sha), b64_sha);
2730  mg_snprintf(buf, sizeof(buf), "%s%s%s",
2731              "HTTP/1.1 101 Switching Protocols\r\n"
2732              "Upgrade: websocket\r\n"
2733              "Connection: Upgrade\r\n"
2734              "Sec-WebSocket-Accept: ", b64_sha, "\r\n\r\n");
26312735
2632   mg_write(conn, buf, strlen(buf));
2736  mg_write(conn, buf, strlen(buf));
26332737}
26342738
26352739static int deliver_websocket_frame(struct connection *conn) {
2636   // Having buf unsigned char * is important, as it is used below in arithmetic
2637   unsigned char *buf = (unsigned char *) conn->ns_conn->recv_iobuf.buf;
2638   int i, len, buf_len = conn->ns_conn->recv_iobuf.len, frame_len = 0,
2639      mask_len = 0, header_len = 0, data_len = 0, buffered = 0;
2740  // Having buf unsigned char * is important, as it is used below in arithmetic
2741  unsigned char *buf = (unsigned char *) conn->ns_conn->recv_iobuf.buf;
2742  int i, len, buf_len = conn->ns_conn->recv_iobuf.len, frame_len = 0,
2743      mask_len = 0, header_len = 0, data_len = 0, buffered = 0;
26402744
2641   if (buf_len >= 2) {
2642   len = buf[1] & 127;
2643   mask_len = buf[1] & 128 ? 4 : 0;
2644   if (len < 126 && buf_len >= mask_len) {
2645      data_len = len;
2646      header_len = 2 + mask_len;
2647   } else if (len == 126 && buf_len >= 4 + mask_len) {
2648      header_len = 4 + mask_len;
2649      data_len = ((((int) buf[2]) << 8) + buf[3]);
2650   } else if (buf_len >= 10 + mask_len) {
2651      header_len = 10 + mask_len;
2652      data_len = (int) (((uint64_t) htonl(* (uint32_t *) &buf[2])) << 32) +
2653      htonl(* (uint32_t *) &buf[6]);
2654   }
2655   }
2745  if (buf_len >= 2) {
2746    len = buf[1] & 127;
2747    mask_len = buf[1] & 128 ? 4 : 0;
2748    if (len < 126 && buf_len >= mask_len) {
2749      data_len = len;
2750      header_len = 2 + mask_len;
2751    } else if (len == 126 && buf_len >= 4 + mask_len) {
2752      header_len = 4 + mask_len;
2753      data_len = ((((int) buf[2]) << 8) + buf[3]);
2754    } else if (buf_len >= 10 + mask_len) {
2755      header_len = 10 + mask_len;
2756      data_len = (int) (((uint64_t) htonl(* (uint32_t *) &buf[2])) << 32) +
2757        htonl(* (uint32_t *) &buf[6]);
2758    }
2759  }
26562760
2657   frame_len = header_len + data_len;
2658   buffered = frame_len > 0 && frame_len <= buf_len;
2761  frame_len = header_len + data_len;
2762  buffered = frame_len > 0 && frame_len <= buf_len;
26592763
2660   if (buffered) {
2661   conn->mg_conn.content_len = data_len;
2662   conn->mg_conn.content = (char *) buf + header_len;
2663   conn->mg_conn.wsbits = buf[0];
2764  if (buffered) {
2765    conn->mg_conn.content_len = data_len;
2766    conn->mg_conn.content = (char *) buf + header_len;
2767    conn->mg_conn.wsbits = buf[0];
26642768
2665   // Apply mask if necessary
2666   if (mask_len > 0) {
2667      for (i = 0; i < data_len; i++) {
2668      buf[i + header_len] ^= (buf + header_len - mask_len)[i % 4];
2669      }
2670   }
2769    // Apply mask if necessary
2770    if (mask_len > 0) {
2771      for (i = 0; i < data_len; i++) {
2772        buf[i + header_len] ^= (buf + header_len - mask_len)[i % 4];
2773      }
2774    }
26712775
2672   // Call the handler and remove frame from the iobuf
2673   if (call_user(conn, MG_REQUEST) == MG_FALSE) {
2674      conn->ns_conn->flags |= NSF_FINISHED_SENDING_DATA;
2675   }
2676   iobuf_remove(&conn->ns_conn->recv_iobuf, frame_len);
2677   }
2776    // Call the handler and remove frame from the iobuf
2777    if (call_user(conn, MG_REQUEST) == MG_FALSE) {
2778      conn->ns_conn->flags |= NSF_FINISHED_SENDING_DATA;
2779    }
2780    iobuf_remove(&conn->ns_conn->recv_iobuf, frame_len);
2781  }
26782782
2679   return buffered;
2783  return buffered;
26802784}
26812785
2682size_t mg_websocket_write(struct mg_connection* conn, int opcode,
2683                  const char *data, size_t data_len) {
2684   unsigned char mem[4192], *copy = mem;
2685   size_t copy_len = 0;
2786size_t mg_websocket_write(struct mg_connection *conn, int opcode,
2787                       const char *data, size_t data_len) {
2788    unsigned char mem[4192], *copy = mem;
2789    size_t copy_len = 0;
26862790
2687   if (data_len + 10 > sizeof(mem) &&
2688      (copy = (unsigned char *) malloc(data_len + 10)) == NULL) {
2689      return 0;
2690   }
2791    if (data_len + 10 > sizeof(mem) &&
2792        (copy = (unsigned char *) malloc(data_len + 10)) == NULL) {
2793      return 0;
2794    }
26912795
2692   copy[0] = 0x80 + (opcode & 0x0f);
2796    copy[0] = 0x80 + (opcode & 0x0f);
26932797
2694   // Frame format: http://tools.ietf.org/html/rfc6455#section-5.2
2695   if (data_len < 126) {
2696      // Inline 7-bit length field
2697      copy[1] = data_len;
2698      memcpy(copy + 2, data, data_len);
2699      copy_len = 2 + data_len;
2700   } else if (data_len <= 0xFFFF) {
2701      // 16-bit length field
2702      copy[1] = 126;
2703      * (uint16_t *) (copy + 2) = (uint16_t) htons((uint16_t) data_len);
2704      memcpy(copy + 4, data, data_len);
2705      copy_len = 4 + data_len;
2706   } else {
2707      // 64-bit length field
2708      copy[1] = 127;
2709      * (uint32_t *) (copy + 2) = (uint32_t)
2710      htonl((uint32_t) ((uint64_t) data_len >> 32));
2711      * (uint32_t *) (copy + 6) = (uint32_t) htonl(data_len & 0xffffffff);
2712      memcpy(copy + 10, data, data_len);
2713      copy_len = 10 + data_len;
2714   }
2798    // Frame format: http://tools.ietf.org/html/rfc6455#section-5.2
2799    if (data_len < 126) {
2800      // Inline 7-bit length field
2801      copy[1] = data_len;
2802      memcpy(copy + 2, data, data_len);
2803      copy_len = 2 + data_len;
2804    } else if (data_len <= 0xFFFF) {
2805      // 16-bit length field
2806      copy[1] = 126;
2807      * (uint16_t *) (copy + 2) = (uint16_t) htons((uint16_t) data_len);
2808      memcpy(copy + 4, data, data_len);
2809      copy_len = 4 + data_len;
2810    } else {
2811      // 64-bit length field
2812      copy[1] = 127;
2813      * (uint32_t *) (copy + 2) = (uint32_t)
2814        htonl((uint32_t) ((uint64_t) data_len >> 32));
2815      * (uint32_t *) (copy + 6) = (uint32_t) htonl(data_len & 0xffffffff);
2816      memcpy(copy + 10, data, data_len);
2817      copy_len = 10 + data_len;
2818    }
27152819
2716   if (copy_len > 0) {
2717      mg_write(conn, copy, copy_len);
2718   }
2719   if (copy != mem) {
2720      free(copy);
2721   }
2820    if (copy_len > 0) {
2821      mg_write(conn, copy, copy_len);
2822    }
2823    if (copy != mem) {
2824      free(copy);
2825    }
27222826
2723   // If we send closing frame, schedule a connection to be closed after
2724   // data is drained to the client.
2725   if (opcode == WEBSOCKET_OPCODE_CONNECTION_CLOSE) {
2726      MG_CONN_2_CONN(conn)->ns_conn->flags |= NSF_FINISHED_SENDING_DATA;
2727   }
2827    // If we send closing frame, schedule a connection to be closed after
2828    // data is drained to the client.
2829    if (opcode == WEBSOCKET_OPCODE_CONNECTION_CLOSE) {
2830      MG_CONN_2_CONN(conn)->ns_conn->flags |= NSF_FINISHED_SENDING_DATA;
2831    }
27282832
2729   return MG_CONN_2_CONN(conn)->ns_conn->send_iobuf.len;
2833    return MG_CONN_2_CONN(conn)->ns_conn->send_iobuf.len;
27302834}
27312835
2732size_t mg_websocket_printf(struct mg_connection* conn, int opcode,
2733                     const char *fmt, ...) {
2734   char mem[4192], *buf = mem;
2735   va_list ap;
2736   int len;
2836size_t mg_websocket_printf(struct mg_connection *conn, int opcode,
2837                           const char *fmt, ...) {
2838  char mem[4192], *buf = mem;
2839  va_list ap;
2840  int len;
27372841
2738   va_start(ap, fmt);
2739   if ((len = ns_avprintf(&buf, sizeof(mem), fmt, ap)) > 0) {
2740   mg_websocket_write(conn, opcode, buf, len);
2741   }
2742   va_end(ap);
2842  va_start(ap, fmt);
2843  if ((len = ns_avprintf(&buf, sizeof(mem), fmt, ap)) > 0) {
2844    mg_websocket_write(conn, opcode, buf, len);
2845  }
2846  va_end(ap);
27432847
2744   if (buf != mem && buf != NULL) {
2745   free(buf);
2746   }
2848  if (buf != mem && buf != NULL) {
2849    free(buf);
2850  }
27472851
2748   return MG_CONN_2_CONN(conn)->ns_conn->send_iobuf.len;
2852  return MG_CONN_2_CONN(conn)->ns_conn->send_iobuf.len;
27492853}
27502854
27512855static void send_websocket_handshake_if_requested(struct mg_connection *conn) {
2752   const char *ver = mg_get_header(conn, "Sec-WebSocket-Version"),
2753      *key = mg_get_header(conn, "Sec-WebSocket-Key");
2754   if (ver != NULL && key != NULL) {
2755   conn->is_websocket = 1;
2756   if (call_user(MG_CONN_2_CONN(conn), MG_WS_HANDSHAKE) == MG_FALSE) {
2757      send_websocket_handshake(conn, key);
2758   }
2759   call_user(MG_CONN_2_CONN(conn), MG_WS_CONNECT);
2760   }
2856  const char *ver = mg_get_header(conn, "Sec-WebSocket-Version"),
2857        *key = mg_get_header(conn, "Sec-WebSocket-Key");
2858  if (ver != NULL && key != NULL) {
2859    conn->is_websocket = 1;
2860    if (call_user(MG_CONN_2_CONN(conn), MG_WS_HANDSHAKE) == MG_FALSE) {
2861      send_websocket_handshake(conn, key);
2862    }
2863    call_user(MG_CONN_2_CONN(conn), MG_WS_CONNECT);
2864  }
27612865}
27622866
27632867static void ping_idle_websocket_connection(struct connection *conn, time_t t) {
2764   if (t - conn->ns_conn->last_io_time > MONGOOSE_USE_WEBSOCKET_PING_INTERVAL) {
2765   mg_websocket_write(&conn->mg_conn, WEBSOCKET_OPCODE_PING, "", 0);
2766   }
2868  if (t - conn->ns_conn->last_io_time > MONGOOSE_USE_WEBSOCKET_PING_INTERVAL) {
2869    mg_websocket_write(&conn->mg_conn, WEBSOCKET_OPCODE_PING, "", 0);
2870  }
27672871}
27682872#else
27692873#define ping_idle_websocket_connection(conn, t)
27702874#endif // !MONGOOSE_NO_WEBSOCKET
27712875
27722876static void write_terminating_chunk(struct connection *conn) {
2773   mg_write(&conn->mg_conn, "0\r\n\r\n", 5);
2877  mg_write(&conn->mg_conn, "0\r\n\r\n", 5);
27742878}
27752879
27762880static int call_request_handler(struct connection *conn) {
2777   int result;
2778   conn->mg_conn.content = conn->ns_conn->recv_iobuf.buf;
2779   if ((result = call_user(conn, MG_REQUEST)) == MG_TRUE) {
2780   if (conn->ns_conn->flags & MG_HEADERS_SENT) {
2781      write_terminating_chunk(conn);
2782   }
2783   close_local_endpoint(conn);
2784   }
2785   return result;
2881  int result;
2882  conn->mg_conn.content = conn->ns_conn->recv_iobuf.buf;
2883  if ((result = call_user(conn, MG_REQUEST)) == MG_TRUE) {
2884    if (conn->ns_conn->flags & MG_HEADERS_SENT) {
2885      write_terminating_chunk(conn);
2886    }
2887    close_local_endpoint(conn);
2888  }
2889  return result;
27862890}
27872891
27882892const char *mg_get_mime_type(const char *path, const char *default_mime_type) {
2789   const char *ext;
2790   size_t i, path_len;
2893  const char *ext;
2894  size_t i, path_len;
27912895
2792   path_len = strlen(path);
2896  path_len = strlen(path);
27932897
2794   for (i = 0; static_builtin_mime_types[i].extension != NULL; i++) {
2795   ext = path + (path_len - static_builtin_mime_types[i].ext_len);
2796   if (path_len > static_builtin_mime_types[i].ext_len &&
2797      mg_strcasecmp(ext, static_builtin_mime_types[i].extension) == 0) {
2798      return static_builtin_mime_types[i].mime_type;
2799   }
2800   }
2898  for (i = 0; static_builtin_mime_types[i].extension != NULL; i++) {
2899    ext = path + (path_len - static_builtin_mime_types[i].ext_len);
2900    if (path_len > static_builtin_mime_types[i].ext_len &&
2901        mg_strcasecmp(ext, static_builtin_mime_types[i].extension) == 0) {
2902      return static_builtin_mime_types[i].mime_type;
2903    }
2904  }
28012905
2802   return default_mime_type;
2906  return default_mime_type;
28032907}
28042908
28052909#ifndef MONGOOSE_NO_FILESYSTEM
28062910// Convert month to the month number. Return -1 on error, or month number
28072911static int get_month_index(const char *s) {
2808   static const char *month_names[] = {
2809   "Jan", "Feb", "Mar", "Apr", "May", "Jun",
2810   "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
2811   };
2812   int i;
2912  static const char *month_names[] = {
2913    "Jan", "Feb", "Mar", "Apr", "May", "Jun",
2914    "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
2915  };
2916  int i;
28132917
2814   for (i = 0; i < (int) ARRAY_SIZE(month_names); i++)
2815   if (!strcmp(s, month_names[i]))
2816      return i;
2918  for (i = 0; i < (int) ARRAY_SIZE(month_names); i++)
2919    if (!strcmp(s, month_names[i]))
2920      return i;
28172921
2818   return -1;
2922  return -1;
28192923}
28202924
28212925static int num_leap_years(int year) {
2822   return year / 4 - year / 100 + year / 400;
2926  return year / 4 - year / 100 + year / 400;
28232927}
28242928
28252929// Parse UTC date-time string, and return the corresponding time_t value.
28262930static time_t parse_date_string(const char *datetime) {
2827   static const unsigned short days_before_month[] = {
2828   0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334
2829   };
2830   char month_str[32];
2831   int second, minute, hour, day, month, year, leap_days, days;
2832   time_t result = (time_t) 0;
2931  static const unsigned short days_before_month[] = {
2932    0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334
2933  };
2934  char month_str[32];
2935  int second, minute, hour, day, month, year, leap_days, days;
2936  time_t result = (time_t) 0;
28332937
2834   if (((sscanf(datetime, "%d/%3s/%d %d:%d:%d",
2835            &day, month_str, &year, &hour, &minute, &second) == 6) ||
2836      (sscanf(datetime, "%d %3s %d %d:%d:%d",
2837            &day, month_str, &year, &hour, &minute, &second) == 6) ||
2838      (sscanf(datetime, "%*3s, %d %3s %d %d:%d:%d",
2839            &day, month_str, &year, &hour, &minute, &second) == 6) ||
2840      (sscanf(datetime, "%d-%3s-%d %d:%d:%d",
2841            &day, month_str, &year, &hour, &minute, &second) == 6)) &&
2842      year > 1970 &&
2843      (month = get_month_index(month_str)) != -1) {
2844   leap_days = num_leap_years(year) - num_leap_years(1970);
2845   year -= 1970;
2846   days = year * 365 + days_before_month[month] + (day - 1) + leap_days;
2847   result = days * 24 * 3600 + hour * 3600 + minute * 60 + second;
2848   }
2938  if (((sscanf(datetime, "%d/%3s/%d %d:%d:%d",
2939               &day, month_str, &year, &hour, &minute, &second) == 6) ||
2940       (sscanf(datetime, "%d %3s %d %d:%d:%d",
2941               &day, month_str, &year, &hour, &minute, &second) == 6) ||
2942       (sscanf(datetime, "%*3s, %d %3s %d %d:%d:%d",
2943               &day, month_str, &year, &hour, &minute, &second) == 6) ||
2944       (sscanf(datetime, "%d-%3s-%d %d:%d:%d",
2945               &day, month_str, &year, &hour, &minute, &second) == 6)) &&
2946      year > 1970 &&
2947      (month = get_month_index(month_str)) != -1) {
2948    leap_days = num_leap_years(year) - num_leap_years(1970);
2949    year -= 1970;
2950    days = year * 365 + days_before_month[month] + (day - 1) + leap_days;
2951    result = days * 24 * 3600 + hour * 3600 + minute * 60 + second;
2952  }
28492953
2850   return result;
2954  return result;
28512955}
28522956
28532957// Look at the "path" extension and figure what mime type it has.
28542958// Store mime type in the vector.
28552959static void get_mime_type(const struct mg_server *server, const char *path,
2856                     struct vec *vec) {
2857   struct vec ext_vec, mime_vec;
2858   const char *list, *ext;
2859   size_t path_len;
2960                          struct vec *vec) {
2961  struct vec ext_vec, mime_vec;
2962  const char *list, *ext;
2963  size_t path_len;
28602964
2861   path_len = strlen(path);
2965  path_len = strlen(path);
28622966
2863   // Scan user-defined mime types first, in case user wants to
2864   // override default mime types.
2865   list = server->config_options[EXTRA_MIME_TYPES];
2866   while ((list = next_option(list, &ext_vec, &mime_vec)) != NULL) {
2867   // ext now points to the path suffix
2868   ext = path + path_len - ext_vec.len;
2869   if (mg_strncasecmp(ext, ext_vec.ptr, ext_vec.len) == 0) {
2870      *vec = mime_vec;
2871      return;
2872   }
2873   }
2967  // Scan user-defined mime types first, in case user wants to
2968  // override default mime types.
2969  list = server->config_options[EXTRA_MIME_TYPES];
2970  while ((list = next_option(list, &ext_vec, &mime_vec)) != NULL) {
2971    // ext now points to the path suffix
2972    ext = path + path_len - ext_vec.len;
2973    if (mg_strncasecmp(ext, ext_vec.ptr, ext_vec.len) == 0) {
2974      *vec = mime_vec;
2975      return;
2976    }
2977  }
28742978
2875   vec->ptr = mg_get_mime_type(path, "text/plain");
2876   vec->len = strlen(vec->ptr);
2979  vec->ptr = mg_get_mime_type(path, "text/plain");
2980  vec->len = strlen(vec->ptr);
28772981}
28782982
28792983static const char *suggest_connection_header(const struct mg_connection *conn) {
2880   return should_keep_alive(conn) ? "keep-alive" : "close";
2984  return should_keep_alive(conn) ? "keep-alive" : "close";
28812985}
28822986
28832987static void construct_etag(char *buf, size_t buf_len, const file_stat_t *st) {
2884   mg_snprintf(buf, buf_len, "\"%lx.%" INT64_FMT "\"",
2885            (unsigned long) st->st_mtime, (int64_t) st->st_size);
2988  mg_snprintf(buf, buf_len, "\"%lx.%" INT64_FMT "\"",
2989              (unsigned long) st->st_mtime, (int64_t) st->st_size);
28862990}
28872991
28882992// Return True if we should reply 304 Not Modified.
28892993static int is_not_modified(const struct connection *conn,
2890                     const file_stat_t *stp) {
2891   char etag[64];
2892   const char *ims = mg_get_header(&conn->mg_conn, "If-Modified-Since");
2893   const char *inm = mg_get_header(&conn->mg_conn, "If-None-Match");
2894   construct_etag(etag, sizeof(etag), stp);
2895   return (inm != NULL && !mg_strcasecmp(etag, inm)) ||
2896   (ims != NULL && stp->st_mtime <= parse_date_string(ims));
2994                           const file_stat_t *stp) {
2995  char etag[64];
2996  const char *ims = mg_get_header(&conn->mg_conn, "If-Modified-Since");
2997  const char *inm = mg_get_header(&conn->mg_conn, "If-None-Match");
2998  construct_etag(etag, sizeof(etag), stp);
2999  return (inm != NULL && !mg_strcasecmp(etag, inm)) ||
3000    (ims != NULL && stp->st_mtime <= parse_date_string(ims));
28973001}
28983002
28993003// For given directory path, substitute it to valid index file.
29003004// Return 0 if index file has been found, -1 if not found.
29013005// If the file is found, it's stats is returned in stp.
29023006static int find_index_file(struct connection *conn, char *path,
2903                     size_t path_len, file_stat_t *stp) {
2904   const char *list = conn->server->config_options[INDEX_FILES];
2905   file_stat_t st;
2906   struct vec filename_vec;
2907   size_t n = strlen(path), found = 0;
3007                           size_t path_len, file_stat_t *stp) {
3008  const char *list = conn->server->config_options[INDEX_FILES];
3009  file_stat_t st;
3010  struct vec filename_vec;
3011  size_t n = strlen(path), found = 0;
29083012
2909   // The 'path' given to us points to the directory. Remove all trailing
2910   // directory separator characters from the end of the path, and
2911   // then append single directory separator character.
2912   while (n > 0 && path[n - 1] == '/') {
2913   n--;
2914   }
2915   path[n] = '/';
3013  // The 'path' given to us points to the directory. Remove all trailing
3014  // directory separator characters from the end of the path, and
3015  // then append single directory separator character.
3016  while (n > 0 && path[n - 1] == '/') {
3017    n--;
3018  }
3019  path[n] = '/';
29163020
2917   // Traverse index files list. For each entry, append it to the given
2918   // path and see if the file exists. If it exists, break the loop
2919   while ((list = next_option(list, &filename_vec, NULL)) != NULL) {
2920   // Ignore too long entries that may overflow path buffer
2921   if (filename_vec.len > (int) (path_len - (n + 2)))
2922      continue;
3021  // Traverse index files list. For each entry, append it to the given
3022  // path and see if the file exists. If it exists, break the loop
3023  while ((list = next_option(list, &filename_vec, NULL)) != NULL) {
29233024
2924   // Prepare full path to the index file
2925   strncpy(path + n + 1, filename_vec.ptr, filename_vec.len);
2926   path[n + 1 + filename_vec.len] = '\0';
3025    // Ignore too long entries that may overflow path buffer
3026    if (filename_vec.len > (int) (path_len - (n + 2)))
3027      continue;
29273028
2928   //DBG(("[%s]", path));
3029    // Prepare full path to the index file
3030    strncpy(path + n + 1, filename_vec.ptr, filename_vec.len);
3031    path[n + 1 + filename_vec.len] = '\0';
29293032
2930   // Does it exist?
2931   if (!stat(path, &st)) {
2932      // Yes it does, break the loop
2933      *stp = st;
2934      found = 1;
2935      break;
2936   }
2937   }
3033    //DBG(("[%s]", path));
29383034
2939   // If no index file exists, restore directory path
2940   if (!found) {
2941   path[n] = '\0';
2942   }
3035    // Does it exist?
3036    if (!stat(path, &st)) {
3037      // Yes it does, break the loop
3038      *stp = st;
3039      found = 1;
3040      break;
3041    }
3042  }
29433043
2944   return found;
3044  // If no index file exists, restore directory path
3045  if (!found) {
3046    path[n] = '\0';
3047  }
3048
3049  return found;
29453050}
29463051
29473052static int parse_range_header(const char *header, int64_t *a, int64_t *b) {
2948   return sscanf(header, "bytes=%" INT64_FMT "-%" INT64_FMT, a, b);
3053  return sscanf(header, "bytes=%" INT64_FMT "-%" INT64_FMT, a, b);
29493054}
29503055
29513056static void gmt_time_string(char *buf, size_t buf_len, time_t *t) {
2952   strftime(buf, buf_len, "%a, %d %b %Y %H:%M:%S GMT", gmtime(t));
3057  strftime(buf, buf_len, "%a, %d %b %Y %H:%M:%S GMT", gmtime(t));
29533058}
29543059
29553060static void open_file_endpoint(struct connection *conn, const char *path,
2956                        file_stat_t *st) {
2957   char date[64], lm[64], etag[64], range[64], headers[500];
2958   const char *msg = "OK", *hdr;
2959   time_t curtime = time(NULL);
2960   int64_t r1, r2;
2961   struct vec mime_vec;
2962   int n;
3061                               file_stat_t *st) {
3062  char date[64], lm[64], etag[64], range[64], headers[500];
3063  const char *msg = "OK", *hdr;
3064  time_t curtime = time(NULL);
3065  int64_t r1, r2;
3066  struct vec mime_vec;
3067  int n;
29633068
2964   conn->endpoint_type = EP_FILE;
2965   ns_set_close_on_exec(conn->endpoint.fd);
2966   conn->mg_conn.status_code = 200;
3069  conn->endpoint_type = EP_FILE;
3070  ns_set_close_on_exec(conn->endpoint.fd);
3071  conn->mg_conn.status_code = 200;
29673072
2968   get_mime_type(conn->server, path, &mime_vec);
2969   conn->cl = st->st_size;
2970   range[0] = '\0';
3073  get_mime_type(conn->server, path, &mime_vec);
3074  conn->cl = st->st_size;
3075  range[0] = '\0';
29713076
2972   // If Range: header specified, act accordingly
2973   r1 = r2 = 0;
2974   hdr = mg_get_header(&conn->mg_conn, "Range");
2975   if (hdr != NULL && (n = parse_range_header(hdr, &r1, &r2)) > 0 &&
2976      r1 >= 0 && r2 >= 0) {
2977   conn->mg_conn.status_code = 206;
2978   conn->cl = n == 2 ? (r2 > conn->cl ? conn->cl : r2) - r1 + 1: conn->cl - r1;
2979   mg_snprintf(range, sizeof(range), "Content-Range: bytes "
2980            "%" INT64_FMT "-%" INT64_FMT "/%" INT64_FMT "\r\n",
2981            r1, r1 + conn->cl - 1, (int64_t) st->st_size);
2982   msg = "Partial Content";
2983   lseek(conn->endpoint.fd, r1, SEEK_SET);
2984   }
3077  // If Range: header specified, act accordingly
3078  r1 = r2 = 0;
3079  hdr = mg_get_header(&conn->mg_conn, "Range");
3080  if (hdr != NULL && (n = parse_range_header(hdr, &r1, &r2)) > 0 &&
3081      r1 >= 0 && r2 >= 0) {
3082    conn->mg_conn.status_code = 206;
3083    conn->cl = n == 2 ? (r2 > conn->cl ? conn->cl : r2) - r1 + 1: conn->cl - r1;
3084    mg_snprintf(range, sizeof(range), "Content-Range: bytes "
3085                "%" INT64_FMT "-%" INT64_FMT "/%" INT64_FMT "\r\n",
3086                r1, r1 + conn->cl - 1, (int64_t) st->st_size);
3087    msg = "Partial Content";
3088    lseek(conn->endpoint.fd, r1, SEEK_SET);
3089  }
29853090
2986   // Prepare Etag, Date, Last-Modified headers. Must be in UTC, according to
2987   // http://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.3
2988   gmt_time_string(date, sizeof(date), &curtime);
2989   gmt_time_string(lm, sizeof(lm), &st->st_mtime);
2990   construct_etag(etag, sizeof(etag), st);
3091  // Prepare Etag, Date, Last-Modified headers. Must be in UTC, according to
3092  // http://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.3
3093  gmt_time_string(date, sizeof(date), &curtime);
3094  gmt_time_string(lm, sizeof(lm), &st->st_mtime);
3095  construct_etag(etag, sizeof(etag), st);
29913096
2992   n = mg_snprintf(headers, sizeof(headers),
2993               "HTTP/1.1 %d %s\r\n"
2994               "Date: %s\r\n"
2995               "Last-Modified: %s\r\n"
2996               "Etag: %s\r\n"
2997               "Content-Type: %.*s\r\n"
2998               "Content-Length: %" INT64_FMT "\r\n"
2999               "Connection: %s\r\n"
3000               "Accept-Ranges: bytes\r\n"
3001               "%s%s\r\n",
3002               conn->mg_conn.status_code, msg, date, lm, etag,
3003               (int) mime_vec.len, mime_vec.ptr, conn->cl,
3004               suggest_connection_header(&conn->mg_conn),
3005               range, MONGOOSE_USE_EXTRA_HTTP_HEADERS);
3006   ns_send(conn->ns_conn, headers, n);
3097  n = mg_snprintf(headers, sizeof(headers),
3098                  "HTTP/1.1 %d %s\r\n"
3099                  "Date: %s\r\n"
3100                  "Last-Modified: %s\r\n"
3101                  "Etag: %s\r\n"
3102                  "Content-Type: %.*s\r\n"
3103                  "Content-Length: %" INT64_FMT "\r\n"
3104                  "Connection: %s\r\n"
3105                  "Accept-Ranges: bytes\r\n"
3106                  "%s%s\r\n",
3107                  conn->mg_conn.status_code, msg, date, lm, etag,
3108                  (int) mime_vec.len, mime_vec.ptr, conn->cl,
3109                  suggest_connection_header(&conn->mg_conn),
3110                  range, MONGOOSE_USE_EXTRA_HTTP_HEADERS);
3111  ns_send(conn->ns_conn, headers, n);
30073112
3008   if (!strcmp(conn->mg_conn.request_method, "HEAD")) {
3009   conn->ns_conn->flags |= NSF_FINISHED_SENDING_DATA;
3010   close(conn->endpoint.fd);
3011   conn->endpoint_type = EP_NONE;
3012   }
3113  if (!strcmp(conn->mg_conn.request_method, "HEAD")) {
3114    conn->ns_conn->flags |= NSF_FINISHED_SENDING_DATA;
3115    close(conn->endpoint.fd);
3116    conn->endpoint_type = EP_NONE;
3117  }
30133118}
3119
3120void mg_send_file_data(struct mg_connection *c, int fd) {
3121  struct connection *conn = MG_CONN_2_CONN(c);
3122  conn->endpoint_type = EP_FILE;
3123  conn->endpoint.fd = fd;
3124  ns_set_close_on_exec(conn->endpoint.fd);
3125}
30143126#endif  // MONGOOSE_NO_FILESYSTEM
30153127
30163128static void call_request_handler_if_data_is_buffered(struct connection *conn) {
3017   struct iobuf *loc = &conn->ns_conn->recv_iobuf;
3018   struct mg_connection *c = &conn->mg_conn;
3019
30203129#ifndef MONGOOSE_NO_WEBSOCKET
3021   if (conn->mg_conn.is_websocket) {
3022   do { } while (deliver_websocket_frame(conn));
3023   } else
3130  if (conn->mg_conn.is_websocket) {
3131    do { } while (deliver_websocket_frame(conn));
3132  } else
30243133#endif
3025   if ((size_t) loc->len >= c->content_len &&
3026      call_request_handler(conn) == MG_FALSE) {
3027   open_local_endpoint(conn, 1);
3028   }
3134  if (conn->num_bytes_recv >= (conn->cl + conn->request_len) &&
3135      call_request_handler(conn) == MG_FALSE) {
3136    open_local_endpoint(conn, 1);
3137  }
30293138}
30303139
30313140#if !defined(MONGOOSE_NO_DIRECTORY_LISTING) || !defined(MONGOOSE_NO_DAV)
30323141
30333142#ifdef _WIN32
30343143struct dirent {
3035   char d_name[MAX_PATH_SIZE];
3144  char d_name[MAX_PATH_SIZE];
30363145};
30373146
30383147typedef struct DIR {
3039   HANDLE   handle;
3040   WIN32_FIND_DATAW info;
3041   struct dirent result;
3148  HANDLE   handle;
3149  WIN32_FIND_DATAW info;
3150  struct dirent result;
30423151} DIR;
30433152
30443153// Implementation of POSIX opendir/closedir/readdir for Windows.
30453154static DIR *opendir(const char *name) {
3046   DIR *dir = NULL;
3047   wchar_t wpath[MAX_PATH_SIZE];
3048   DWORD attrs;
3155  DIR *dir = NULL;
3156  wchar_t wpath[MAX_PATH_SIZE];
3157  DWORD attrs;
30493158
3050   if (name == NULL) {
3051   SetLastError(ERROR_BAD_ARGUMENTS);
3052   } else if ((dir = (DIR *) malloc(sizeof(*dir))) == NULL) {
3053   SetLastError(ERROR_NOT_ENOUGH_MEMORY);
3054   } else {
3055   to_wchar(name, wpath, ARRAY_SIZE(wpath));
3056   attrs = GetFileAttributesW(wpath);
3057   if (attrs != 0xFFFFFFFF &&
3058      ((attrs & FILE_ATTRIBUTE_DIRECTORY) == FILE_ATTRIBUTE_DIRECTORY)) {
3059      (void) wcscat(wpath, L"\\*");
3060      dir->handle = FindFirstFileW(wpath, &dir->info);
3061      dir->result.d_name[0] = '\0';
3062   } else {
3063      free(dir);
3064      dir = NULL;
3065   }
3066   }
3159  if (name == NULL) {
3160    SetLastError(ERROR_BAD_ARGUMENTS);
3161  } else if ((dir = (DIR *) malloc(sizeof(*dir))) == NULL) {
3162    SetLastError(ERROR_NOT_ENOUGH_MEMORY);
3163  } else {
3164    to_wchar(name, wpath, ARRAY_SIZE(wpath));
3165    attrs = GetFileAttributesW(wpath);
3166    if (attrs != 0xFFFFFFFF &&
3167        ((attrs & FILE_ATTRIBUTE_DIRECTORY) == FILE_ATTRIBUTE_DIRECTORY)) {
3168      (void) wcscat(wpath, L"\\*");
3169      dir->handle = FindFirstFileW(wpath, &dir->info);
3170      dir->result.d_name[0] = '\0';
3171    } else {
3172      free(dir);
3173      dir = NULL;
3174    }
3175  }
30673176
3068   return dir;
3177  return dir;
30693178}
30703179
30713180static int closedir(DIR *dir) {
3072   int result = 0;
3181  int result = 0;
30733182
3074   if (dir != NULL) {
3075   if (dir->handle != INVALID_HANDLE_VALUE)
3076      result = FindClose(dir->handle) ? 0 : -1;
3183  if (dir != NULL) {
3184    if (dir->handle != INVALID_HANDLE_VALUE)
3185      result = FindClose(dir->handle) ? 0 : -1;
30773186
3078   free(dir);
3079   } else {
3080   result = -1;
3081   SetLastError(ERROR_BAD_ARGUMENTS);
3082   }
3187    free(dir);
3188  } else {
3189    result = -1;
3190    SetLastError(ERROR_BAD_ARGUMENTS);
3191  }
30833192
3084   return result;
3193  return result;
30853194}
30863195
30873196static struct dirent *readdir(DIR *dir) {
3088   struct dirent *result = 0;
3197  struct dirent *result = 0;
30893198
3090   if (dir) {
3091   if (dir->handle != INVALID_HANDLE_VALUE) {
3092      result = &dir->result;
3093      (void) WideCharToMultiByte(CP_UTF8, 0,
3094         dir->info.cFileName, -1, result->d_name,
3095         sizeof(result->d_name), NULL, NULL);
3199  if (dir) {
3200    if (dir->handle != INVALID_HANDLE_VALUE) {
3201      result = &dir->result;
3202      (void) WideCharToMultiByte(CP_UTF8, 0,
3203          dir->info.cFileName, -1, result->d_name,
3204          sizeof(result->d_name), NULL, NULL);
30963205
3097      if (!FindNextFileW(dir->handle, &dir->info)) {
3098      (void) FindClose(dir->handle);
3099      dir->handle = INVALID_HANDLE_VALUE;
3100      }
3206      if (!FindNextFileW(dir->handle, &dir->info)) {
3207        (void) FindClose(dir->handle);
3208        dir->handle = INVALID_HANDLE_VALUE;
3209      }
31013210
3102   } else {
3103      SetLastError(ERROR_FILE_NOT_FOUND);
3104   }
3105   } else {
3106   SetLastError(ERROR_BAD_ARGUMENTS);
3107   }
3211    } else {
3212      SetLastError(ERROR_FILE_NOT_FOUND);
3213    }
3214  } else {
3215    SetLastError(ERROR_BAD_ARGUMENTS);
3216  }
31083217
3109   return result;
3218  return result;
31103219}
31113220#endif // _WIN32  POSIX opendir/closedir/readdir implementation
31123221
31133222static int scan_directory(struct connection *conn, const char *dir,
3114                     struct dir_entry **arr) {
3115   char path[MAX_PATH_SIZE];
3116   struct dir_entry *p;
3117   struct dirent *dp;
3118   int arr_size = 0, arr_ind = 0, inc = 100;
3119   DIR *dirp;
3223                          struct dir_entry **arr) {
3224  char path[MAX_PATH_SIZE];
3225  struct dir_entry *p;
3226  struct dirent *dp;
3227  int arr_size = 0, arr_ind = 0, inc = 100;
3228  DIR *dirp;
31203229
3121   *arr = NULL;
3122   if ((dirp = (opendir(dir))) == NULL) return 0;
3230  *arr = NULL;
3231  if ((dirp = (opendir(dir))) == NULL) return 0;
31233232
3124   while ((dp = readdir(dirp)) != NULL) {
3125   // Do not show current dir and hidden files
3126   if (!strcmp(dp->d_name, ".") ||
3127      !strcmp(dp->d_name, "..") ||
3128      must_hide_file(conn, dp->d_name)) {
3129      continue;
3130   }
3131   mg_snprintf(path, sizeof(path), "%s%c%s", dir, '/', dp->d_name);
3233  while ((dp = readdir(dirp)) != NULL) {
3234    // Do not show current dir and hidden files
3235    if (!strcmp(dp->d_name, ".") ||
3236        !strcmp(dp->d_name, "..") ||
3237        must_hide_file(conn, dp->d_name)) {
3238      continue;
3239    }
3240    mg_snprintf(path, sizeof(path), "%s%c%s", dir, '/', dp->d_name);
31323241
3133   // Resize the array if nesessary
3134   if (arr_ind >= arr_size) {
3135      if ((p = (struct dir_entry *)
3136         realloc(*arr, (inc + arr_size) * sizeof(**arr))) != NULL) {
3137      // Memset new chunk to zero, otherwize st_mtime will have garbage which
3138      // can make strftime() segfault, see
3139      // http://code.google.com/p/mongoose/issues/detail?id=79
3140      memset(p + arr_size, 0, sizeof(**arr) * inc);
3242    // Resize the array if nesessary
3243    if (arr_ind >= arr_size) {
3244      if ((p = (struct dir_entry *)
3245           realloc(*arr, (inc + arr_size) * sizeof(**arr))) != NULL) {
3246        // Memset new chunk to zero, otherwize st_mtime will have garbage which
3247        // can make strftime() segfault, see
3248        // http://code.google.com/p/mongoose/issues/detail?id=79
3249        memset(p + arr_size, 0, sizeof(**arr) * inc);
31413250
3142      *arr = p;
3143      arr_size += inc;
3144      }
3145   }
3251        *arr = p;
3252        arr_size += inc;
3253      }
3254    }
31463255
3147   if (arr_ind < arr_size) {
3148      (*arr)[arr_ind].conn = conn;
3149      (*arr)[arr_ind].file_name = strdup(dp->d_name);
3150      stat(path, &(*arr)[arr_ind].st);
3151      arr_ind++;
3152   }
3153   }
3154   closedir(dirp);
3256    if (arr_ind < arr_size) {
3257      (*arr)[arr_ind].conn = conn;
3258      (*arr)[arr_ind].file_name = strdup(dp->d_name);
3259      stat(path, &(*arr)[arr_ind].st);
3260      arr_ind++;
3261    }
3262  }
3263  closedir(dirp);
31553264
3156   return arr_ind;
3265  return arr_ind;
31573266}
31583267
31593268int mg_url_encode(const char *src, size_t s_len, char *dst, size_t dst_len) {
3160   static const char *dont_escape = "._-$,;~()";
3161   static const char *hex = "0123456789abcdef";
3162   size_t i = 0, j = 0;
3269  static const char *dont_escape = "._-$,;~()";
3270  static const char *hex = "0123456789abcdef";
3271  size_t i = 0, j = 0;
31633272
3164   for (i = j = 0; dst_len > 0 && i < s_len && j < dst_len - 1; i++, j++) {
3165   if (isalnum(* (const unsigned char *) (src + i)) ||
3166      strchr(dont_escape, * (const unsigned char *) (src + i)) != NULL) {
3167      dst[j] = src[i];
3168   } else if (j + 3 < dst_len) {
3169      dst[j] = '%';
3170      dst[j + 1] = hex[(* (const unsigned char *) (src + i)) >> 4];
3171      dst[j + 2] = hex[(* (const unsigned char *) (src + i)) & 0xf];
3172      j += 2;
3173   }
3174   }
3273  for (i = j = 0; dst_len > 0 && i < s_len && j + 2 < dst_len - 1; i++, j++) {
3274    if (isalnum(* (const unsigned char *) (src + i)) ||
3275        strchr(dont_escape, * (const unsigned char *) (src + i)) != NULL) {
3276      dst[j] = src[i];
3277    } else if (j + 3 < dst_len) {
3278      dst[j] = '%';
3279      dst[j + 1] = hex[(* (const unsigned char *) (src + i)) >> 4];
3280      dst[j + 2] = hex[(* (const unsigned char *) (src + i)) & 0xf];
3281      j += 2;
3282    }
3283  }
31753284
3176   dst[j] = '\0';
3177   return j;
3285  dst[j] = '\0';
3286  return j;
31783287}
31793288#endif  // !NO_DIRECTORY_LISTING || !MONGOOSE_NO_DAV
31803289
31813290#ifndef MONGOOSE_NO_DIRECTORY_LISTING
31823291
31833292static void print_dir_entry(const struct dir_entry *de) {
3184   char size[64], mod[64], href[MAX_PATH_SIZE * 3];
3185   int64_t fsize = de->st.st_size;
3186   int is_dir = S_ISDIR(de->st.st_mode);
3187   const char *slash = is_dir ? "/" : "";
3293  char size[64], mod[64], href[MAX_PATH_SIZE * 3];
3294  int64_t fsize = de->st.st_size;
3295  int is_dir = S_ISDIR(de->st.st_mode);
3296  const char *slash = is_dir ? "/" : "";
31883297
3189   if (is_dir) {
3190   mg_snprintf(size, sizeof(size), "%s", "[DIRECTORY]");
3191   } else {
3192      // We use (signed) cast below because MSVC 6 compiler cannot
3193      // convert unsigned __int64 to double.
3194   if (fsize < 1024) {
3195      mg_snprintf(size, sizeof(size), "%d", (int) fsize);
3196   } else if (fsize < 0x100000) {
3197      mg_snprintf(size, sizeof(size), "%.1fk", (double) fsize / 1024.0);
3198   } else if (fsize < 0x40000000) {
3199      mg_snprintf(size, sizeof(size), "%.1fM", (double) fsize / 1048576);
3200   } else {
3201      mg_snprintf(size, sizeof(size), "%.1fG", (double) fsize / 1073741824);
3202   }
3203   }
3204   strftime(mod, sizeof(mod), "%d-%b-%Y %H:%M", localtime(&de->st.st_mtime));
3205   mg_url_encode(de->file_name, strlen(de->file_name), href, sizeof(href));
3206   mg_printf_data(&de->conn->mg_conn,
3207               "<tr><td><a href=\"%s%s\">%s%s</a></td>"
3208               "<td>&nbsp;%s</td><td>&nbsp;&nbsp;%s</td></tr>\n",
3209               href, slash, de->file_name, slash, mod, size);
3298  if (is_dir) {
3299    mg_snprintf(size, sizeof(size), "%s", "[DIRECTORY]");
3300  } else {
3301     // We use (signed) cast below because MSVC 6 compiler cannot
3302     // convert unsigned __int64 to double.
3303    if (fsize < 1024) {
3304      mg_snprintf(size, sizeof(size), "%d", (int) fsize);
3305    } else if (fsize < 0x100000) {
3306      mg_snprintf(size, sizeof(size), "%.1fk", (double) fsize / 1024.0);
3307    } else if (fsize < 0x40000000) {
3308      mg_snprintf(size, sizeof(size), "%.1fM", (double) fsize / 1048576);
3309    } else {
3310      mg_snprintf(size, sizeof(size), "%.1fG", (double) fsize / 1073741824);
3311    }
3312  }
3313  strftime(mod, sizeof(mod), "%d-%b-%Y %H:%M", localtime(&de->st.st_mtime));
3314  mg_url_encode(de->file_name, strlen(de->file_name), href, sizeof(href));
3315  mg_printf_data(&de->conn->mg_conn,
3316                  "<tr><td><a href=\"%s%s\">%s%s</a></td>"
3317                  "<td>&nbsp;%s</td><td>&nbsp;&nbsp;%s</td></tr>\n",
3318                  href, slash, de->file_name, slash, mod, size);
32103319}
32113320
32123321// Sort directory entries by size, or name, or modification time.
32133322// On windows, __cdecl specification is needed in case if project is built
32143323// with __stdcall convention. qsort always requires __cdels callback.
32153324static int __cdecl compare_dir_entries(const void *p1, const void *p2) {
3216   const struct dir_entry *a = (const struct dir_entry *) p1,
3217      *b = (const struct dir_entry *) p2;
3218   const char *qs = a->conn->mg_conn.query_string ?
3219   a->conn->mg_conn.query_string : "na";
3220   int cmp_result = 0;
3325  const struct dir_entry *a = (const struct dir_entry *) p1,
3326        *b = (const struct dir_entry *) p2;
3327  const char *qs = a->conn->mg_conn.query_string ?
3328    a->conn->mg_conn.query_string : "na";
3329  int cmp_result = 0;
32213330
3222   if (S_ISDIR(a->st.st_mode) && !S_ISDIR(b->st.st_mode)) {
3223   return -1;  // Always put directories on top
3224   } else if (!S_ISDIR(a->st.st_mode) && S_ISDIR(b->st.st_mode)) {
3225   return 1;   // Always put directories on top
3226   } else if (*qs == 'n') {
3227   cmp_result = strcmp(a->file_name, b->file_name);
3228   } else if (*qs == 's') {
3229   cmp_result = a->st.st_size == b->st.st_size ? 0 :
3230      a->st.st_size > b->st.st_size ? 1 : -1;
3231   } else if (*qs == 'd') {
3232   cmp_result = a->st.st_mtime == b->st.st_mtime ? 0 :
3233      a->st.st_mtime > b->st.st_mtime ? 1 : -1;
3234   }
3331  if (S_ISDIR(a->st.st_mode) && !S_ISDIR(b->st.st_mode)) {
3332    return -1;  // Always put directories on top
3333  } else if (!S_ISDIR(a->st.st_mode) && S_ISDIR(b->st.st_mode)) {
3334    return 1;   // Always put directories on top
3335  } else if (*qs == 'n') {
3336    cmp_result = strcmp(a->file_name, b->file_name);
3337  } else if (*qs == 's') {
3338    cmp_result = a->st.st_size == b->st.st_size ? 0 :
3339      a->st.st_size > b->st.st_size ? 1 : -1;
3340  } else if (*qs == 'd') {
3341    cmp_result = a->st.st_mtime == b->st.st_mtime ? 0 :
3342      a->st.st_mtime > b->st.st_mtime ? 1 : -1;
3343  }
32353344
3236   return qs[1] == 'd' ? -cmp_result : cmp_result;
3345  return qs[1] == 'd' ? -cmp_result : cmp_result;
32373346}
32383347
32393348static void send_directory_listing(struct connection *conn, const char *dir) {
3240   struct dir_entry *arr = NULL;
3241   int i, num_entries, sort_direction = conn->mg_conn.query_string != NULL &&
3242   conn->mg_conn.query_string[1] == 'd' ? 'a' : 'd';
3349  struct dir_entry *arr = NULL;
3350  int i, num_entries, sort_direction = conn->mg_conn.query_string != NULL &&
3351    conn->mg_conn.query_string[1] == 'd' ? 'a' : 'd';
32433352
3244   mg_send_header(&conn->mg_conn, "Transfer-Encoding", "chunked");
3245   mg_send_header(&conn->mg_conn, "Content-Type", "text/html; charset=utf-8");
3353  mg_send_header(&conn->mg_conn, "Transfer-Encoding", "chunked");
3354  mg_send_header(&conn->mg_conn, "Content-Type", "text/html; charset=utf-8");
32463355
3247   mg_printf_data(&conn->mg_conn,
3248            "<html><head><title>Index of %s</title>"
3249            "<style>th {text-align: left;}</style></head>"
3250            "<body><h1>Index of %s</h1><pre><table cellpadding=\"0\">"
3251            "<tr><th><a href=\"?n%c\">Name</a></th>"
3252            "<th><a href=\"?d%c\">Modified</a></th>"
3253            "<th><a href=\"?s%c\">Size</a></th></tr>"
3254            "<tr><td colspan=\"3\"><hr></td></tr>",
3255            conn->mg_conn.uri, conn->mg_conn.uri,
3256            sort_direction, sort_direction, sort_direction);
3356  mg_printf_data(&conn->mg_conn,
3357              "<html><head><title>Index of %s</title>"
3358              "<style>th {text-align: left;}</style></head>"
3359              "<body><h1>Index of %s</h1><pre><table cellpadding=\"0\">"
3360              "<tr><th><a href=\"?n%c\">Name</a></th>"
3361              "<th><a href=\"?d%c\">Modified</a></th>"
3362              "<th><a href=\"?s%c\">Size</a></th></tr>"
3363              "<tr><td colspan=\"3\"><hr></td></tr>",
3364              conn->mg_conn.uri, conn->mg_conn.uri,
3365              sort_direction, sort_direction, sort_direction);
32573366
3258   num_entries = scan_directory(conn, dir, &arr);
3259   qsort(arr, num_entries, sizeof(arr[0]), compare_dir_entries);
3260   for (i = 0; i < num_entries; i++) {
3261   print_dir_entry(&arr[i]);
3262   free(arr[i].file_name);
3263   }
3264   free(arr);
3367  num_entries = scan_directory(conn, dir, &arr);
3368  qsort(arr, num_entries, sizeof(arr[0]), compare_dir_entries);
3369  for (i = 0; i < num_entries; i++) {
3370    print_dir_entry(&arr[i]);
3371    free(arr[i].file_name);
3372  }
3373  free(arr);
32653374
3266   write_terminating_chunk(conn);
3267   close_local_endpoint(conn);
3375  write_terminating_chunk(conn);
3376  close_local_endpoint(conn);
32683377}
32693378#endif  // MONGOOSE_NO_DIRECTORY_LISTING
32703379
32713380#ifndef MONGOOSE_NO_DAV
32723381static void print_props(struct connection *conn, const char *uri,
3273                  file_stat_t *stp) {
3274   char mtime[64];
3382                        file_stat_t *stp) {
3383  char mtime[64];
32753384
3276   gmt_time_string(mtime, sizeof(mtime), &stp->st_mtime);
3277   mg_printf(&conn->mg_conn,
3278      "<d:response>"
3279      "<d:href>%s</d:href>"
3280      "<d:propstat>"
3281      "<d:prop>"
3282         "<d:resourcetype>%s</d:resourcetype>"
3283         "<d:getcontentlength>%" INT64_FMT "</d:getcontentlength>"
3284         "<d:getlastmodified>%s</d:getlastmodified>"
3285      "</d:prop>"
3286      "<d:status>HTTP/1.1 200 OK</d:status>"
3287      "</d:propstat>"
3288      "</d:response>\n",
3289      uri, S_ISDIR(stp->st_mode) ? "<d:collection/>" : "",
3290      (int64_t) stp->st_size, mtime);
3385  gmt_time_string(mtime, sizeof(mtime), &stp->st_mtime);
3386  mg_printf(&conn->mg_conn,
3387      "<d:response>"
3388       "<d:href>%s</d:href>"
3389       "<d:propstat>"
3390        "<d:prop>"
3391         "<d:resourcetype>%s</d:resourcetype>"
3392         "<d:getcontentlength>%" INT64_FMT "</d:getcontentlength>"
3393         "<d:getlastmodified>%s</d:getlastmodified>"
3394        "</d:prop>"
3395        "<d:status>HTTP/1.1 200 OK</d:status>"
3396       "</d:propstat>"
3397      "</d:response>\n",
3398      uri, S_ISDIR(stp->st_mode) ? "<d:collection/>" : "",
3399      (int64_t) stp->st_size, mtime);
32913400}
32923401
32933402static void handle_propfind(struct connection *conn, const char *path,
3294                     file_stat_t *stp, int exists) {
3295   static const char header[] = "HTTP/1.1 207 Multi-Status\r\n"
3296   "Connection: close\r\n"
3297   "Content-Type: text/xml; charset=utf-8\r\n\r\n"
3298   "<?xml version=\"1.0\" encoding=\"utf-8\"?>"
3299   "<d:multistatus xmlns:d='DAV:'>\n";
3300   static const char footer[] = "</d:multistatus>";
3301   const char *depth = mg_get_header(&conn->mg_conn, "Depth"),
3302      *list_dir = conn->server->config_options[ENABLE_DIRECTORY_LISTING];
3403                            file_stat_t *stp, int exists) {
3404  static const char header[] = "HTTP/1.1 207 Multi-Status\r\n"
3405    "Connection: close\r\n"
3406    "Content-Type: text/xml; charset=utf-8\r\n\r\n"
3407    "<?xml version=\"1.0\" encoding=\"utf-8\"?>"
3408    "<d:multistatus xmlns:d='DAV:'>\n";
3409  static const char footer[] = "</d:multistatus>";
3410  const char *depth = mg_get_header(&conn->mg_conn, "Depth"),
3411        *list_dir = conn->server->config_options[ENABLE_DIRECTORY_LISTING];
33033412
3304   conn->mg_conn.status_code = 207;
3413  conn->mg_conn.status_code = 207;
33053414
3306   // Print properties for the requested resource itself
3307   if (!exists) {
3308   conn->mg_conn.status_code = 404;
3309   mg_printf(&conn->mg_conn, "%s", "HTTP/1.1 404 Not Found\r\n\r\n");
3310   } else if (S_ISDIR(stp->st_mode) && mg_strcasecmp(list_dir, "yes") != 0) {
3311   conn->mg_conn.status_code = 403;
3312   mg_printf(&conn->mg_conn, "%s",
3313            "HTTP/1.1 403 Directory Listing Denied\r\n\r\n");
3314   } else {
3315   ns_send(conn->ns_conn, header, sizeof(header) - 1);
3316   print_props(conn, conn->mg_conn.uri, stp);
3415  // Print properties for the requested resource itself
3416  if (!exists) {
3417    conn->mg_conn.status_code = 404;
3418    mg_printf(&conn->mg_conn, "%s", "HTTP/1.1 404 Not Found\r\n\r\n");
3419  } else if (S_ISDIR(stp->st_mode) && mg_strcasecmp(list_dir, "yes") != 0) {
3420    conn->mg_conn.status_code = 403;
3421    mg_printf(&conn->mg_conn, "%s",
3422              "HTTP/1.1 403 Directory Listing Denied\r\n\r\n");
3423  } else {
3424    ns_send(conn->ns_conn, header, sizeof(header) - 1);
3425    print_props(conn, conn->mg_conn.uri, stp);
33173426
3318   if (S_ISDIR(stp->st_mode) &&
3319            (depth == NULL || strcmp(depth, "0") != 0)) {
3320      struct dir_entry *arr = NULL;
3321      int i, num_entries = scan_directory(conn, path, &arr);
3427    if (S_ISDIR(stp->st_mode) &&
3428             (depth == NULL || strcmp(depth, "0") != 0)) {
3429      struct dir_entry *arr = NULL;
3430      int i, num_entries = scan_directory(conn, path, &arr);
33223431
3323      for (i = 0; i < num_entries; i++) {
3324      char buf[MAX_PATH_SIZE * 3];
3325      struct dir_entry *de = &arr[i];
3326      mg_url_encode(de->file_name, strlen(de->file_name), buf, sizeof(buf));
3327      print_props(conn, buf, &de->st);
3328      }
3329   }
3330   ns_send(conn->ns_conn, footer, sizeof(footer) - 1);
3331   }
3432      for (i = 0; i < num_entries; i++) {
3433        char buf[MAX_PATH_SIZE * 3];
3434        struct dir_entry *de = &arr[i];
3435        mg_url_encode(de->file_name, strlen(de->file_name), buf, sizeof(buf));
3436        print_props(conn, buf, &de->st);
3437        free(de->file_name);
3438      }
3439      free(arr);
3440    }
3441    ns_send(conn->ns_conn, footer, sizeof(footer) - 1);
3442  }
33323443
3333   close_local_endpoint(conn);
3444  close_local_endpoint(conn);
33343445}
33353446
33363447static void handle_mkcol(struct connection *conn, const char *path) {
3337   int status_code = 500;
3448  int status_code = 500;
33383449
3339   if (conn->mg_conn.content_len > 0) {
3340   status_code = 415;
3341   } else if (!mkdir(path, 0755)) {
3342   status_code = 201;
3343   } else if (errno == EEXIST) {
3344   status_code = 405;
3345   } else if (errno == EACCES) {
3346   status_code = 403;
3347   } else if (errno == ENOENT) {
3348   status_code = 409;
3349   }
3350   send_http_error(conn, status_code, NULL);
3450  if (conn->mg_conn.content_len > 0) {
3451    status_code = 415;
3452  } else if (!mkdir(path, 0755)) {
3453    status_code = 201;
3454  } else if (errno == EEXIST) {
3455    status_code = 405;
3456  } else if (errno == EACCES) {
3457    status_code = 403;
3458  } else if (errno == ENOENT) {
3459    status_code = 409;
3460  }
3461  send_http_error(conn, status_code, NULL);
33513462}
33523463
33533464static int remove_directory(const char *dir) {
3354   char path[MAX_PATH_SIZE];
3355   struct dirent *dp;
3356   file_stat_t st;
3357   DIR *dirp;
3465  char path[MAX_PATH_SIZE];
3466  struct dirent *dp;
3467  file_stat_t st;
3468  DIR *dirp;
33583469
3359   if ((dirp = opendir(dir)) == NULL) return 0;
3470  if ((dirp = opendir(dir)) == NULL) return 0;
33603471
3361   while ((dp = readdir(dirp)) != NULL) {
3362   if (!strcmp(dp->d_name, ".") || !strcmp(dp->d_name, "..")) continue;
3363   mg_snprintf(path, sizeof(path), "%s%c%s", dir, '/', dp->d_name);
3364   stat(path, &st);
3365   if (S_ISDIR(st.st_mode)) {
3366      remove_directory(path);
3367   } else {
3368      remove(path);
3369   }
3370   }
3371   closedir(dirp);
3372   rmdir(dir);
3472  while ((dp = readdir(dirp)) != NULL) {
3473    if (!strcmp(dp->d_name, ".") || !strcmp(dp->d_name, "..")) continue;
3474    mg_snprintf(path, sizeof(path), "%s%c%s", dir, '/', dp->d_name);
3475    stat(path, &st);
3476    if (S_ISDIR(st.st_mode)) {
3477      remove_directory(path);
3478    } else {
3479      remove(path);
3480    }
3481  }
3482  closedir(dirp);
3483  rmdir(dir);
33733484
3374   return 1;
3485  return 1;
33753486}
33763487
33773488static void handle_delete(struct connection *conn, const char *path) {
3378   file_stat_t st;
3489  file_stat_t st;
33793490
3380   if (stat(path, &st) != 0) {
3381   send_http_error(conn, 404, NULL);
3382   } else if (S_ISDIR(st.st_mode)) {
3383   remove_directory(path);
3384   send_http_error(conn, 204, NULL);
3385   } else if (remove(path) == 0) {
3386   send_http_error(conn, 204, NULL);
3387   } else {
3388   send_http_error(conn, 423, NULL);
3389   }
3491  if (stat(path, &st) != 0) {
3492    send_http_error(conn, 404, NULL);
3493  } else if (S_ISDIR(st.st_mode)) {
3494    remove_directory(path);
3495    send_http_error(conn, 204, NULL);
3496  } else if (remove(path) == 0) {
3497    send_http_error(conn, 204, NULL);
3498  } else {
3499    send_http_error(conn, 423, NULL);
3500  }
33903501}
33913502
33923503// For a given PUT path, create all intermediate subdirectories
33933504// for given path. Return 0 if the path itself is a directory,
33943505// or -1 on error, 1 if OK.
33953506static int put_dir(const char *path) {
3396   char buf[MAX_PATH_SIZE];
3397   const char *s, *p;
3398   file_stat_t st;
3507  char buf[MAX_PATH_SIZE];
3508  const char *s, *p;
3509  file_stat_t st;
33993510
3400   // Create intermediate directories if they do not exist
3401   for (s = p = path + 1; (p = strchr(s, '/')) != NULL; s = ++p) {
3402   if (p - path >= (int) sizeof(buf)) return -1; // Buffer overflow
3403   memcpy(buf, path, p - path);
3404   buf[p - path] = '\0';
3405   if (stat(buf, &st) != 0 && mkdir(buf, 0755) != 0) return -1;
3406   if (p[1] == '\0') return 0;  // Path is a directory itself
3407   }
3511  // Create intermediate directories if they do not exist
3512  for (s = p = path + 1; (p = strchr(s, '/')) != NULL; s = ++p) {
3513    if (p - path >= (int) sizeof(buf)) return -1; // Buffer overflow
3514    memcpy(buf, path, p - path);
3515    buf[p - path] = '\0';
3516    if (stat(buf, &st) != 0 && mkdir(buf, 0755) != 0) return -1;
3517    if (p[1] == '\0') return 0;  // Path is a directory itself
3518  }
34083519
3409   return 1;
3520  return 1;
34103521}
34113522
34123523static void handle_put(struct connection *conn, const char *path) {
3413   file_stat_t st;
3414   const char *range, *cl_hdr = mg_get_header(&conn->mg_conn, "Content-Length");
3415   int64_t r1, r2;
3416   int rc;
3524  file_stat_t st;
3525  const char *range, *cl_hdr = mg_get_header(&conn->mg_conn, "Content-Length");
3526  int64_t r1, r2;
3527  int rc;
34173528
3418   conn->mg_conn.status_code = !stat(path, &st) ? 200 : 201;
3419   if ((rc = put_dir(path)) == 0) {
3420   mg_printf(&conn->mg_conn, "HTTP/1.1 %d OK\r\n\r\n",
3421            conn->mg_conn.status_code);
3422   close_local_endpoint(conn);
3423   } else if (rc == -1) {
3424   send_http_error(conn, 500, "put_dir: %s", strerror(errno));
3425   } else if (cl_hdr == NULL) {
3426   send_http_error(conn, 411, NULL);
3529  conn->mg_conn.status_code = !stat(path, &st) ? 200 : 201;
3530  if ((rc = put_dir(path)) == 0) {
3531    mg_printf(&conn->mg_conn, "HTTP/1.1 %d OK\r\n\r\n",
3532              conn->mg_conn.status_code);
3533    close_local_endpoint(conn);
3534  } else if (rc == -1) {
3535    send_http_error(conn, 500, "put_dir: %s", strerror(errno));
3536  } else if (cl_hdr == NULL) {
3537    send_http_error(conn, 411, NULL);
34273538#ifdef _WIN32
3428   //On Windows, open() is a macro with 2 params
3429   } else if ((conn->endpoint.fd =
3430            open(path, O_RDWR | O_CREAT | O_TRUNC)) < 0) {
3539    //On Windows, open() is a macro with 2 params
3540  } else if ((conn->endpoint.fd =
3541              open(path, O_RDWR | O_CREAT | O_TRUNC)) < 0) {
34313542#else
3432   } else if ((conn->endpoint.fd =
3433            open(path, O_RDWR | O_CREAT | O_TRUNC, 0644)) < 0) {
3543  } else if ((conn->endpoint.fd =
3544              open(path, O_RDWR | O_CREAT | O_TRUNC, 0644)) < 0) {
34343545#endif
3435   send_http_error(conn, 500, "open(%s): %s", path, strerror(errno));
3436   } else {
3437   DBG(("PUT [%s] %zu", path, conn->ns_conn->recv_iobuf.len));
3438   conn->endpoint_type = EP_PUT;
3439   ns_set_close_on_exec(conn->endpoint.fd);
3440   range = mg_get_header(&conn->mg_conn, "Content-Range");
3441   conn->cl = to64(cl_hdr);
3442   r1 = r2 = 0;
3443   if (range != NULL && parse_range_header(range, &r1, &r2) > 0) {
3444      conn->mg_conn.status_code = 206;
3445      lseek(conn->endpoint.fd, r1, SEEK_SET);
3446      conn->cl = r2 > r1 ? r2 - r1 + 1: conn->cl - r1;
3447   }
3448   mg_printf(&conn->mg_conn, "HTTP/1.1 %d OK\r\nContent-Length: 0\r\n\r\n",
3449            conn->mg_conn.status_code);
3450   }
3546    send_http_error(conn, 500, "open(%s): %s", path, strerror(errno));
3547  } else {
3548    DBG(("PUT [%s] %lu", path, (unsigned long) conn->ns_conn->recv_iobuf.len));
3549    conn->endpoint_type = EP_PUT;
3550    ns_set_close_on_exec(conn->endpoint.fd);
3551    range = mg_get_header(&conn->mg_conn, "Content-Range");
3552    conn->cl = to64(cl_hdr);
3553    r1 = r2 = 0;
3554    if (range != NULL && parse_range_header(range, &r1, &r2) > 0) {
3555      conn->mg_conn.status_code = 206;
3556      lseek(conn->endpoint.fd, r1, SEEK_SET);
3557      conn->cl = r2 > r1 ? r2 - r1 + 1: conn->cl - r1;
3558    }
3559    mg_printf(&conn->mg_conn, "HTTP/1.1 %d OK\r\nContent-Length: 0\r\n\r\n",
3560              conn->mg_conn.status_code);
3561  }
34513562}
34523563
34533564static void forward_put_data(struct connection *conn) {
3454   struct iobuf *io = &conn->ns_conn->recv_iobuf;
3455   size_t k = conn->cl < (int64_t) io->len ? conn->cl : io->len;   // To write
3456   int n = write(conn->endpoint.fd, io->buf, k);   // Write them!
3457   if (n > 0) {
3458   iobuf_remove(io, n);
3459   conn->cl -= n;
3460   }
3461   if (conn->cl <= 0) {
3462   close_local_endpoint(conn);
3463   }
3565  struct iobuf *io = &conn->ns_conn->recv_iobuf;
3566  size_t k = conn->cl < (int64_t) io->len ? conn->cl : (int64_t) io->len;   // To write
3567  int n = write(conn->endpoint.fd, io->buf, k);   // Write them!
3568  if (n > 0) {
3569    iobuf_remove(io, n);
3570    conn->cl -= n;
3571  }
3572  if (conn->cl <= 0) {
3573    close_local_endpoint(conn);
3574  }
34643575}
34653576#endif //  MONGOOSE_NO_DAV
34663577
34673578static void send_options(struct connection *conn) {
3468   conn->mg_conn.status_code = 200;
3469   mg_printf(&conn->mg_conn, "%s",
3470         "HTTP/1.1 200 OK\r\nAllow: GET, POST, HEAD, CONNECT, PUT, "
3471         "DELETE, OPTIONS, PROPFIND, MKCOL\r\nDAV: 1\r\n\r\n");
3472   close_local_endpoint(conn);
3579  conn->mg_conn.status_code = 200;
3580  mg_printf(&conn->mg_conn, "%s",
3581            "HTTP/1.1 200 OK\r\nAllow: GET, POST, HEAD, CONNECT, PUT, "
3582            "DELETE, OPTIONS, PROPFIND, MKCOL\r\nDAV: 1\r\n\r\n");
3583  close_local_endpoint(conn);
34733584}
34743585
34753586#ifndef MONGOOSE_NO_AUTH
34763587void mg_send_digest_auth_request(struct mg_connection *c) {
3477   struct connection *conn = MG_CONN_2_CONN(c);
3478   c->status_code = 401;
3479   mg_printf(c,
3480         "HTTP/1.1 401 Unauthorized\r\n"
3481         "WWW-Authenticate: Digest qop=\"auth\", "
3482         "realm=\"%s\", nonce=\"%lu\"\r\n\r\n",
3483         conn->server->config_options[AUTH_DOMAIN],
3484         (unsigned long) time(NULL));
3485   close_local_endpoint(conn);
3588  struct connection *conn = MG_CONN_2_CONN(c);
3589  c->status_code = 401;
3590  mg_printf(c,
3591            "HTTP/1.1 401 Unauthorized\r\n"
3592            "WWW-Authenticate: Digest qop=\"auth\", "
3593            "realm=\"%s\", nonce=\"%lu\"\r\n\r\n",
3594            conn->server->config_options[AUTH_DOMAIN],
3595            (unsigned long) time(NULL));
3596  close_local_endpoint(conn);
34863597}
34873598
34883599// Use the global passwords file, if specified by auth_gpass option,
34893600// or search for .htpasswd in the requested directory.
3490static FILE *open_auth_file(struct connection *conn, const char *path) {
3491   char name[MAX_PATH_SIZE];
3492   const char *p, *gpass = conn->server->config_options[GLOBAL_AUTH_FILE];
3493   file_stat_t st;
3494   FILE *fp = NULL;
3601static FILE *open_auth_file(struct connection *conn, const char *path,
3602                            int is_directory) {
3603  char name[MAX_PATH_SIZE];
3604  const char *p, *gpass = conn->server->config_options[GLOBAL_AUTH_FILE];
3605  FILE *fp = NULL;
34953606
3496   if (gpass != NULL) {
3497   // Use global passwords file
3498   fp = fopen(gpass, "r");
3499   } else if (!stat(path, &st) && S_ISDIR(st.st_mode)) {
3500   mg_snprintf(name, sizeof(name), "%s%c%s", path, '/', PASSWORDS_FILE_NAME);
3501   fp = fopen(name, "r");
3502   } else {
3503   // Try to find .htpasswd in requested directory.
3504   if ((p = strrchr(path, '/')) == NULL) p = path;
3505   mg_snprintf(name, sizeof(name), "%.*s%c%s",
3506            (int) (p - path), path, '/', PASSWORDS_FILE_NAME);
3507   fp = fopen(name, "r");
3508   }
3607  if (gpass != NULL) {
3608    // Use global passwords file
3609    fp = fopen(gpass, "r");
3610  } else if (is_directory) {
3611    mg_snprintf(name, sizeof(name), "%s%c%s", path, '/', PASSWORDS_FILE_NAME);
3612    fp = fopen(name, "r");
3613  } else {
3614    // Try to find .htpasswd in requested directory.
3615    if ((p = strrchr(path, '/')) == NULL) p = path;
3616    mg_snprintf(name, sizeof(name), "%.*s%c%s",
3617                (int) (p - path), path, '/', PASSWORDS_FILE_NAME);
3618    fp = fopen(name, "r");
3619  }
35093620
3510   return fp;
3621  return fp;
35113622}
35123623
35133624#if !defined(HAVE_MD5) && !defined(MONGOOSE_NO_AUTH)
35143625typedef struct MD5Context {
3515   uint32_t buf[4];
3516   uint32_t bits[2];
3517   unsigned char in[64];
3626  uint32_t buf[4];
3627  uint32_t bits[2];
3628  unsigned char in[64];
35183629} MD5_CTX;
35193630
35203631static void byteReverse(unsigned char *buf, unsigned longs) {
3521   uint32_t t;
3632  uint32_t t;
35223633
3523   // Forrest: MD5 expect LITTLE_ENDIAN, swap if BIG_ENDIAN
3524   if (is_big_endian()) {
3525   do {
3526      t = (uint32_t) ((unsigned) buf[3] << 8 | buf[2]) << 16 |
3527      ((unsigned) buf[1] << 8 | buf[0]);
3528      * (uint32_t *) buf = t;
3529      buf += 4;
3530   } while (--longs);
3531   }
3634  // Forrest: MD5 expect LITTLE_ENDIAN, swap if BIG_ENDIAN
3635  if (is_big_endian()) {
3636    do {
3637      t = (uint32_t) ((unsigned) buf[3] << 8 | buf[2]) << 16 |
3638        ((unsigned) buf[1] << 8 | buf[0]);
3639      * (uint32_t *) buf = t;
3640      buf += 4;
3641    } while (--longs);
3642  }
35323643}
35333644
35343645#define F1(x, y, z) (z ^ (x & (y ^ z)))
r31874r31875
35373648#define F4(x, y, z) (y ^ (x | ~z))
35383649
35393650#define MD5STEP(f, w, x, y, z, data, s) \
3540   ( w += f(x, y, z) + data,  w = w<<s | w>>(32-s),  w += x )
3651  ( w += f(x, y, z) + data,  w = w<<s | w>>(32-s),  w += x )
35413652
35423653// Start MD5 accumulation.  Set bit count to 0 and buffer to mysterious
35433654// initialization constants.
35443655static void MD5Init(MD5_CTX *ctx) {
3545   ctx->buf[0] = 0x67452301;
3546   ctx->buf[1] = 0xefcdab89;
3547   ctx->buf[2] = 0x98badcfe;
3548   ctx->buf[3] = 0x10325476;
3656  ctx->buf[0] = 0x67452301;
3657  ctx->buf[1] = 0xefcdab89;
3658  ctx->buf[2] = 0x98badcfe;
3659  ctx->buf[3] = 0x10325476;
35493660
3550   ctx->bits[0] = 0;
3551   ctx->bits[1] = 0;
3661  ctx->bits[0] = 0;
3662  ctx->bits[1] = 0;
35523663}
35533664
35543665static void MD5Transform(uint32_t buf[4], uint32_t const in[16]) {
3555   register uint32_t a, b, c, d;
3666  register uint32_t a, b, c, d;
35563667
3557   a = buf[0];
3558   b = buf[1];
3559   c = buf[2];
3560   d = buf[3];
3668  a = buf[0];
3669  b = buf[1];
3670  c = buf[2];
3671  d = buf[3];
35613672
3562   MD5STEP(F1, a, b, c, d, in[0] + 0xd76aa478, 7);
3563   MD5STEP(F1, d, a, b, c, in[1] + 0xe8c7b756, 12);
3564   MD5STEP(F1, c, d, a, b, in[2] + 0x242070db, 17);
3565   MD5STEP(F1, b, c, d, a, in[3] + 0xc1bdceee, 22);
3566   MD5STEP(F1, a, b, c, d, in[4] + 0xf57c0faf, 7);
3567   MD5STEP(F1, d, a, b, c, in[5] + 0x4787c62a, 12);
3568   MD5STEP(F1, c, d, a, b, in[6] + 0xa8304613, 17);
3569   MD5STEP(F1, b, c, d, a, in[7] + 0xfd469501, 22);
3570   MD5STEP(F1, a, b, c, d, in[8] + 0x698098d8, 7);
3571   MD5STEP(F1, d, a, b, c, in[9] + 0x8b44f7af, 12);
3572   MD5STEP(F1, c, d, a, b, in[10] + 0xffff5bb1, 17);
3573   MD5STEP(F1, b, c, d, a, in[11] + 0x895cd7be, 22);
3574   MD5STEP(F1, a, b, c, d, in[12] + 0x6b901122, 7);
3575   MD5STEP(F1, d, a, b, c, in[13] + 0xfd987193, 12);
3576   MD5STEP(F1, c, d, a, b, in[14] + 0xa679438e, 17);
3577   MD5STEP(F1, b, c, d, a, in[15] + 0x49b40821, 22);
3673  MD5STEP(F1, a, b, c, d, in[0] + 0xd76aa478, 7);
3674  MD5STEP(F1, d, a, b, c, in[1] + 0xe8c7b756, 12);
3675  MD5STEP(F1, c, d, a, b, in[2] + 0x242070db, 17);
3676  MD5STEP(F1, b, c, d, a, in[3] + 0xc1bdceee, 22);
3677  MD5STEP(F1, a, b, c, d, in[4] + 0xf57c0faf, 7);
3678  MD5STEP(F1, d, a, b, c, in[5] + 0x4787c62a, 12);
3679  MD5STEP(F1, c, d, a, b, in[6] + 0xa8304613, 17);
3680  MD5STEP(F1, b, c, d, a, in[7] + 0xfd469501, 22);
3681  MD5STEP(F1, a, b, c, d, in[8] + 0x698098d8, 7);
3682  MD5STEP(F1, d, a, b, c, in[9] + 0x8b44f7af, 12);
3683  MD5STEP(F1, c, d, a, b, in[10] + 0xffff5bb1, 17);
3684  MD5STEP(F1, b, c, d, a, in[11] + 0x895cd7be, 22);
3685  MD5STEP(F1, a, b, c, d, in[12] + 0x6b901122, 7);
3686  MD5STEP(F1, d, a, b, c, in[13] + 0xfd987193, 12);
3687  MD5STEP(F1, c, d, a, b, in[14] + 0xa679438e, 17);
3688  MD5STEP(F1, b, c, d, a, in[15] + 0x49b40821, 22);
35783689
3579   MD5STEP(F2, a, b, c, d, in[1] + 0xf61e2562, 5);
3580   MD5STEP(F2, d, a, b, c, in[6] + 0xc040b340, 9);
3581   MD5STEP(F2, c, d, a, b, in[11] + 0x265e5a51, 14);
3582   MD5STEP(F2, b, c, d, a, in[0] + 0xe9b6c7aa, 20);
3583   MD5STEP(F2, a, b, c, d, in[5] + 0xd62f105d, 5);
3584   MD5STEP(F2, d, a, b, c, in[10] + 0x02441453, 9);
3585   MD5STEP(F2, c, d, a, b, in[15] + 0xd8a1e681, 14);
3586   MD5STEP(F2, b, c, d, a, in[4] + 0xe7d3fbc8, 20);
3587   MD5STEP(F2, a, b, c, d, in[9] + 0x21e1cde6, 5);
3588   MD5STEP(F2, d, a, b, c, in[14] + 0xc33707d6, 9);
3589   MD5STEP(F2, c, d, a, b, in[3] + 0xf4d50d87, 14);
3590   MD5STEP(F2, b, c, d, a, in[8] + 0x455a14ed, 20);
3591   MD5STEP(F2, a, b, c, d, in[13] + 0xa9e3e905, 5);
3592   MD5STEP(F2, d, a, b, c, in[2] + 0xfcefa3f8, 9);
3593   MD5STEP(F2, c, d, a, b, in[7] + 0x676f02d9, 14);
3594   MD5STEP(F2, b, c, d, a, in[12] + 0x8d2a4c8a, 20);
3690  MD5STEP(F2, a, b, c, d, in[1] + 0xf61e2562, 5);
3691  MD5STEP(F2, d, a, b, c, in[6] + 0xc040b340, 9);
3692  MD5STEP(F2, c, d, a, b, in[11] + 0x265e5a51, 14);
3693  MD5STEP(F2, b, c, d, a, in[0] + 0xe9b6c7aa, 20);
3694  MD5STEP(F2, a, b, c, d, in[5] + 0xd62f105d, 5);
3695  MD5STEP(F2, d, a, b, c, in[10] + 0x02441453, 9);
3696  MD5STEP(F2, c, d, a, b, in[15] + 0xd8a1e681, 14);
3697  MD5STEP(F2, b, c, d, a, in[4] + 0xe7d3fbc8, 20);
3698  MD5STEP(F2, a, b, c, d, in[9] + 0x21e1cde6, 5);
3699  MD5STEP(F2, d, a, b, c, in[14] + 0xc33707d6, 9);
3700  MD5STEP(F2, c, d, a, b, in[3] + 0xf4d50d87, 14);
3701  MD5STEP(F2, b, c, d, a, in[8] + 0x455a14ed, 20);
3702  MD5STEP(F2, a, b, c, d, in[13] + 0xa9e3e905, 5);
3703  MD5STEP(F2, d, a, b, c, in[2] + 0xfcefa3f8, 9);
3704  MD5STEP(F2, c, d, a, b, in[7] + 0x676f02d9, 14);
3705  MD5STEP(F2, b, c, d, a, in[12] + 0x8d2a4c8a, 20);
35953706
3596   MD5STEP(F3, a, b, c, d, in[5] + 0xfffa3942, 4);
3597   MD5STEP(F3, d, a, b, c, in[8] + 0x8771f681, 11);
3598   MD5STEP(F3, c, d, a, b, in[11] + 0x6d9d6122, 16);
3599   MD5STEP(F3, b, c, d, a, in[14] + 0xfde5380c, 23);
3600   MD5STEP(F3, a, b, c, d, in[1] + 0xa4beea44, 4);
3601   MD5STEP(F3, d, a, b, c, in[4] + 0x4bdecfa9, 11);
3602   MD5STEP(F3, c, d, a, b, in[7] + 0xf6bb4b60, 16);
3603   MD5STEP(F3, b, c, d, a, in[10] + 0xbebfbc70, 23);
3604   MD5STEP(F3, a, b, c, d, in[13] + 0x289b7ec6, 4);
3605   MD5STEP(F3, d, a, b, c, in[0] + 0xeaa127fa, 11);
3606   MD5STEP(F3, c, d, a, b, in[3] + 0xd4ef3085, 16);
3607   MD5STEP(F3, b, c, d, a, in[6] + 0x04881d05, 23);
3608   MD5STEP(F3, a, b, c, d, in[9] + 0xd9d4d039, 4);
3609   MD5STEP(F3, d, a, b, c, in[12] + 0xe6db99e5, 11);
3610   MD5STEP(F3, c, d, a, b, in[15] + 0x1fa27cf8, 16);
3611   MD5STEP(F3, b, c, d, a, in[2] + 0xc4ac5665, 23);
3707  MD5STEP(F3, a, b, c, d, in[5] + 0xfffa3942, 4);
3708  MD5STEP(F3, d, a, b, c, in[8] + 0x8771f681, 11);
3709  MD5STEP(F3, c, d, a, b, in[11] + 0x6d9d6122, 16);
3710  MD5STEP(F3, b, c, d, a, in[14] + 0xfde5380c, 23);
3711  MD5STEP(F3, a, b, c, d, in[1] + 0xa4beea44, 4);
3712  MD5STEP(F3, d, a, b, c, in[4] + 0x4bdecfa9, 11);
3713  MD5STEP(F3, c, d, a, b, in[7] + 0xf6bb4b60, 16);
3714  MD5STEP(F3, b, c, d, a, in[10] + 0xbebfbc70, 23);
3715  MD5STEP(F3, a, b, c, d, in[13] + 0x289b7ec6, 4);
3716  MD5STEP(F3, d, a, b, c, in[0] + 0xeaa127fa, 11);
3717  MD5STEP(F3, c, d, a, b, in[3] + 0xd4ef3085, 16);
3718  MD5STEP(F3, b, c, d, a, in[6] + 0x04881d05, 23);
3719  MD5STEP(F3, a, b, c, d, in[9] + 0xd9d4d039, 4);
3720  MD5STEP(F3, d, a, b, c, in[12] + 0xe6db99e5, 11);
3721  MD5STEP(F3, c, d, a, b, in[15] + 0x1fa27cf8, 16);
3722  MD5STEP(F3, b, c, d, a, in[2] + 0xc4ac5665, 23);
36123723
3613   MD5STEP(F4, a, b, c, d, in[0] + 0xf4292244, 6);
3614   MD5STEP(F4, d, a, b, c, in[7] + 0x432aff97, 10);
3615   MD5STEP(F4, c, d, a, b, in[14] + 0xab9423a7, 15);
3616   MD5STEP(F4, b, c, d, a, in[5] + 0xfc93a039, 21);
3617   MD5STEP(F4, a, b, c, d, in[12] + 0x655b59c3, 6);
3618   MD5STEP(F4, d, a, b, c, in[3] + 0x8f0ccc92, 10);
3619   MD5STEP(F4, c, d, a, b, in[10] + 0xffeff47d, 15);
3620   MD5STEP(F4, b, c, d, a, in[1] + 0x85845dd1, 21);
3621   MD5STEP(F4, a, b, c, d, in[8] + 0x6fa87e4f, 6);
3622   MD5STEP(F4, d, a, b, c, in[15] + 0xfe2ce6e0, 10);
3623   MD5STEP(F4, c, d, a, b, in[6] + 0xa3014314, 15);
3624   MD5STEP(F4, b, c, d, a, in[13] + 0x4e0811a1, 21);
3625   MD5STEP(F4, a, b, c, d, in[4] + 0xf7537e82, 6);
3626   MD5STEP(F4, d, a, b, c, in[11] + 0xbd3af235, 10);
3627   MD5STEP(F4, c, d, a, b, in[2] + 0x2ad7d2bb, 15);
3628   MD5STEP(F4, b, c, d, a, in[9] + 0xeb86d391, 21);
3724  MD5STEP(F4, a, b, c, d, in[0] + 0xf4292244, 6);
3725  MD5STEP(F4, d, a, b, c, in[7] + 0x432aff97, 10);
3726  MD5STEP(F4, c, d, a, b, in[14] + 0xab9423a7, 15);
3727  MD5STEP(F4, b, c, d, a, in[5] + 0xfc93a039, 21);
3728  MD5STEP(F4, a, b, c, d, in[12] + 0x655b59c3, 6);
3729  MD5STEP(F4, d, a, b, c, in[3] + 0x8f0ccc92, 10);
3730  MD5STEP(F4, c, d, a, b, in[10] + 0xffeff47d, 15);
3731  MD5STEP(F4, b, c, d, a, in[1] + 0x85845dd1, 21);
3732  MD5STEP(F4, a, b, c, d, in[8] + 0x6fa87e4f, 6);
3733  MD5STEP(F4, d, a, b, c, in[15] + 0xfe2ce6e0, 10);
3734  MD5STEP(F4, c, d, a, b, in[6] + 0xa3014314, 15);
3735  MD5STEP(F4, b, c, d, a, in[13] + 0x4e0811a1, 21);
3736  MD5STEP(F4, a, b, c, d, in[4] + 0xf7537e82, 6);
3737  MD5STEP(F4, d, a, b, c, in[11] + 0xbd3af235, 10);
3738  MD5STEP(F4, c, d, a, b, in[2] + 0x2ad7d2bb, 15);
3739  MD5STEP(F4, b, c, d, a, in[9] + 0xeb86d391, 21);
36293740
3630   buf[0] += a;
3631   buf[1] += b;
3632   buf[2] += c;
3633   buf[3] += d;
3741  buf[0] += a;
3742  buf[1] += b;
3743  buf[2] += c;
3744  buf[3] += d;
36343745}
36353746
36363747static void MD5Update(MD5_CTX *ctx, unsigned char const *buf, unsigned len) {
3637   uint32_t t;
3748  uint32_t t;
36383749
3639   t = ctx->bits[0];
3640   if ((ctx->bits[0] = t + ((uint32_t) len << 3)) < t)
3641   ctx->bits[1]++;
3642   ctx->bits[1] += len >> 29;
3750  t = ctx->bits[0];
3751  if ((ctx->bits[0] = t + ((uint32_t) len << 3)) < t)
3752    ctx->bits[1]++;
3753  ctx->bits[1] += len >> 29;
36433754
3644   t = (t >> 3) & 0x3f;
3755  t = (t >> 3) & 0x3f;
36453756
3646   if (t) {
3647   unsigned char *p = (unsigned char *) ctx->in + t;
3757  if (t) {
3758    unsigned char *p = (unsigned char *) ctx->in + t;
36483759
3649   t = 64 - t;
3650   if (len < t) {
3651      memcpy(p, buf, len);
3652      return;
3653   }
3654   memcpy(p, buf, t);
3655   byteReverse(ctx->in, 16);
3656   MD5Transform(ctx->buf, (uint32_t *) ctx->in);
3657   buf += t;
3658   len -= t;
3659   }
3760    t = 64 - t;
3761    if (len < t) {
3762      memcpy(p, buf, len);
3763      return;
3764    }
3765    memcpy(p, buf, t);
3766    byteReverse(ctx->in, 16);
3767    MD5Transform(ctx->buf, (uint32_t *) ctx->in);
3768    buf += t;
3769    len -= t;
3770  }
36603771
3661   while (len >= 64) {
3662   memcpy(ctx->in, buf, 64);
3663   byteReverse(ctx->in, 16);
3664   MD5Transform(ctx->buf, (uint32_t *) ctx->in);
3665   buf += 64;
3666   len -= 64;
3667   }
3772  while (len >= 64) {
3773    memcpy(ctx->in, buf, 64);
3774    byteReverse(ctx->in, 16);
3775    MD5Transform(ctx->buf, (uint32_t *) ctx->in);
3776    buf += 64;
3777    len -= 64;
3778  }
36683779
3669   memcpy(ctx->in, buf, len);
3780  memcpy(ctx->in, buf, len);
36703781}
36713782
36723783static void MD5Final(unsigned char digest[16], MD5_CTX *ctx) {
3673   unsigned count;
3674   unsigned char *p;
3675   uint32_t *a;
3784  unsigned count;
3785  unsigned char *p;
3786  uint32_t *a;
36763787
3677   count = (ctx->bits[0] >> 3) & 0x3F;
3788  count = (ctx->bits[0] >> 3) & 0x3F;
36783789
3679   p = ctx->in + count;
3680   *p++ = 0x80;
3681   count = 64 - 1 - count;
3682   if (count < 8) {
3683   memset(p, 0, count);
3684   byteReverse(ctx->in, 16);
3685   MD5Transform(ctx->buf, (uint32_t *) ctx->in);
3686   memset(ctx->in, 0, 56);
3687   } else {
3688   memset(p, 0, count - 8);
3689   }
3690   byteReverse(ctx->in, 14);
3790  p = ctx->in + count;
3791  *p++ = 0x80;
3792  count = 64 - 1 - count;
3793  if (count < 8) {
3794    memset(p, 0, count);
3795    byteReverse(ctx->in, 16);
3796    MD5Transform(ctx->buf, (uint32_t *) ctx->in);
3797    memset(ctx->in, 0, 56);
3798  } else {
3799    memset(p, 0, count - 8);
3800  }
3801  byteReverse(ctx->in, 14);
36913802
3692   a = (uint32_t *)ctx->in;
3693   a[14] = ctx->bits[0];
3694   a[15] = ctx->bits[1];
3803  a = (uint32_t *)ctx->in;
3804  a[14] = ctx->bits[0];
3805  a[15] = ctx->bits[1];
36953806
3696   MD5Transform(ctx->buf, (uint32_t *) ctx->in);
3697   byteReverse((unsigned char *) ctx->buf, 4);
3698   memcpy(digest, ctx->buf, 16);
3699   memset((char *) ctx, 0, sizeof(*ctx));
3807  MD5Transform(ctx->buf, (uint32_t *) ctx->in);
3808  byteReverse((unsigned char *) ctx->buf, 4);
3809  memcpy(digest, ctx->buf, 16);
3810  memset((char *) ctx, 0, sizeof(*ctx));
37003811}
37013812#endif // !HAVE_MD5
37023813
r31874r31875
37053816// Stringify binary data. Output buffer must be twice as big as input,
37063817// because each byte takes 2 bytes in string representation
37073818static void bin2str(char *to, const unsigned char *p, size_t len) {
3708   static const char *hex = "0123456789abcdef";
3819  static const char *hex = "0123456789abcdef";
37093820
3710   for (; len--; p++) {
3711   *to++ = hex[p[0] >> 4];
3712   *to++ = hex[p[0] & 0x0f];
3713   }
3714   *to = '\0';
3821  for (; len--; p++) {
3822    *to++ = hex[p[0] >> 4];
3823    *to++ = hex[p[0] & 0x0f];
3824  }
3825  *to = '\0';
37153826}
37163827
37173828// Return stringified MD5 hash for list of strings. Buffer must be 33 bytes.
37183829char *mg_md5(char buf[33], ...) {
3719   unsigned char hash[16];
3720   const char *p;
3721   va_list ap;
3722   MD5_CTX ctx;
3830  unsigned char hash[16];
3831  const char *p;
3832  va_list ap;
3833  MD5_CTX ctx;
37233834
3724   MD5Init(&ctx);
3835  MD5Init(&ctx);
37253836
3726   va_start(ap, buf);
3727   while ((p = va_arg(ap, const char *)) != NULL) {
3728   MD5Update(&ctx, (const unsigned char *) p, (unsigned) strlen(p));
3729   }
3730   va_end(ap);
3837  va_start(ap, buf);
3838  while ((p = va_arg(ap, const char *)) != NULL) {
3839    MD5Update(&ctx, (const unsigned char *) p, (unsigned) strlen(p));
3840  }
3841  va_end(ap);
37313842
3732   MD5Final(hash, &ctx);
3733   bin2str(buf, hash, sizeof(hash));
3734   return buf;
3843  MD5Final(hash, &ctx);
3844  bin2str(buf, hash, sizeof(hash));
3845  return buf;
37353846}
37363847
37373848// Check the user's password, return 1 if OK
37383849static int check_password(const char *method, const char *ha1, const char *uri,
3739                     const char *nonce, const char *nc, const char *cnonce,
3740                     const char *qop, const char *response) {
3741   char ha2[32 + 1], expected_response[32 + 1];
3850                          const char *nonce, const char *nc, const char *cnonce,
3851                          const char *qop, const char *response) {
3852  char ha2[32 + 1], expected_response[32 + 1];
37423853
37433854#if 0
3744   // Check for authentication timeout
3745   if ((unsigned long) time(NULL) - (unsigned long) to64(nonce) > 3600 * 2) {
3746   return 0;
3747   }
3855  // Check for authentication timeout
3856  if ((unsigned long) time(NULL) - (unsigned long) to64(nonce) > 3600 * 2) {
3857    return 0;
3858  }
37483859#endif
37493860
3750   mg_md5(ha2, method, ":", uri, NULL);
3751   mg_md5(expected_response, ha1, ":", nonce, ":", nc,
3752      ":", cnonce, ":", qop, ":", ha2, NULL);
3861  mg_md5(ha2, method, ":", uri, NULL);
3862  mg_md5(expected_response, ha1, ":", nonce, ":", nc,
3863      ":", cnonce, ":", qop, ":", ha2, NULL);
37533864
3754   return mg_strcasecmp(response, expected_response) == 0 ? MG_TRUE : MG_FALSE;
3865  return mg_strcasecmp(response, expected_response) == 0 ? MG_TRUE : MG_FALSE;
37553866}
37563867
37573868
37583869// Authorize against the opened passwords file. Return 1 if authorized.
37593870int mg_authorize_digest(struct mg_connection *c, FILE *fp) {
3760   struct connection *conn = MG_CONN_2_CONN(c);
3761   const char *hdr;
3762   char line[256], f_user[256], ha1[256], f_domain[256], user[100], nonce[100],
3763      uri[MAX_REQUEST_SIZE], cnonce[100], resp[100], qop[100], nc[100];
3871  struct connection *conn = MG_CONN_2_CONN(c);
3872  const char *hdr;
3873  char line[256], f_user[256], ha1[256], f_domain[256], user[100], nonce[100],
3874       uri[MAX_REQUEST_SIZE], cnonce[100], resp[100], qop[100], nc[100];
37643875
3765   if (c == NULL || fp == NULL) return 0;
3766   if ((hdr = mg_get_header(c, "Authorization")) == NULL ||
3767      mg_strncasecmp(hdr, "Digest ", 7) != 0) return 0;
3768   if (!mg_parse_header(hdr, "username", user, sizeof(user))) return 0;
3769   if (!mg_parse_header(hdr, "cnonce", cnonce, sizeof(cnonce))) return 0;
3770   if (!mg_parse_header(hdr, "response", resp, sizeof(resp))) return 0;
3771   if (!mg_parse_header(hdr, "uri", uri, sizeof(uri))) return 0;
3772   if (!mg_parse_header(hdr, "qop", qop, sizeof(qop))) return 0;
3773   if (!mg_parse_header(hdr, "nc", nc, sizeof(nc))) return 0;
3774   if (!mg_parse_header(hdr, "nonce", nonce, sizeof(nonce))) return 0;
3876  if (c == NULL || fp == NULL) return 0;
3877  if ((hdr = mg_get_header(c, "Authorization")) == NULL ||
3878      mg_strncasecmp(hdr, "Digest ", 7) != 0) return 0;
3879  if (!mg_parse_header(hdr, "username", user, sizeof(user))) return 0;
3880  if (!mg_parse_header(hdr, "cnonce", cnonce, sizeof(cnonce))) return 0;
3881  if (!mg_parse_header(hdr, "response", resp, sizeof(resp))) return 0;
3882  if (!mg_parse_header(hdr, "uri", uri, sizeof(uri))) return 0;
3883  if (!mg_parse_header(hdr, "qop", qop, sizeof(qop))) return 0;
3884  if (!mg_parse_header(hdr, "nc", nc, sizeof(nc))) return 0;
3885  if (!mg_parse_header(hdr, "nonce", nonce, sizeof(nonce))) return 0;
37753886
3776   while (fgets(line, sizeof(line), fp) != NULL) {
3777   if (sscanf(line, "%[^:]:%[^:]:%s", f_user, f_domain, ha1) == 3 &&
3778      !strcmp(user, f_user) &&
3779      // NOTE(lsm): due to a bug in MSIE, we do not compare URIs
3780      !strcmp(conn->server->config_options[AUTH_DOMAIN], f_domain))
3781      return check_password(c->request_method, ha1, uri,
3782                     nonce, nc, cnonce, qop, resp);
3783   }
3784   return MG_FALSE;
3887  while (fgets(line, sizeof(line), fp) != NULL) {
3888    if (sscanf(line, "%[^:]:%[^:]:%s", f_user, f_domain, ha1) == 3 &&
3889        !strcmp(user, f_user) &&
3890        // NOTE(lsm): due to a bug in MSIE, we do not compare URIs
3891        !strcmp(conn->server->config_options[AUTH_DOMAIN], f_domain))
3892      return check_password(c->request_method, ha1, uri,
3893                            nonce, nc, cnonce, qop, resp);
3894  }
3895  return MG_FALSE;
37853896}
37863897
37873898
37883899// Return 1 if request is authorised, 0 otherwise.
3789static int is_authorized(struct connection *conn, const char *path) {
3790   FILE *fp;
3791   int authorized = MG_TRUE;
3900static int is_authorized(struct connection *conn, const char *path,
3901                         int is_directory) {
3902  FILE *fp;
3903  int authorized = MG_TRUE;
37923904
3793   if ((fp = open_auth_file(conn, path)) != NULL) {
3794   authorized = mg_authorize_digest(&conn->mg_conn, fp);
3795   fclose(fp);
3796   }
3905  if ((fp = open_auth_file(conn, path, is_directory)) != NULL) {
3906    authorized = mg_authorize_digest(&conn->mg_conn, fp);
3907    fclose(fp);
3908  }
37973909
3798   return authorized;
3910  return authorized;
37993911}
38003912
38013913static int is_authorized_for_dav(struct connection *conn) {
3802   const char *auth_file = conn->server->config_options[DAV_AUTH_FILE];
3803   const char *method = conn->mg_conn.request_method;
3804   FILE *fp;
3805   int authorized = MG_FALSE;
3914  const char *auth_file = conn->server->config_options[DAV_AUTH_FILE];
3915  const char *method = conn->mg_conn.request_method;
3916  FILE *fp;
3917  int authorized = MG_FALSE;
38063918
3807   // If dav_auth_file is not set, allow non-authorized PROPFIND
3808   if (method != NULL && !strcmp(method, "PROPFIND") && auth_file == NULL) {
3809   authorized = MG_TRUE;
3810   } else if (auth_file != NULL && (fp = fopen(auth_file, "r")) != NULL) {
3811   authorized = mg_authorize_digest(&conn->mg_conn, fp);
3812   fclose(fp);
3813   }
3919  // If dav_auth_file is not set, allow non-authorized PROPFIND
3920  if (method != NULL && !strcmp(method, "PROPFIND") && auth_file == NULL) {
3921    authorized = MG_TRUE;
3922  } else if (auth_file != NULL && (fp = fopen(auth_file, "r")) != NULL) {
3923    authorized = mg_authorize_digest(&conn->mg_conn, fp);
3924    fclose(fp);
3925  }
38143926
3815   return authorized;
3927  return authorized;
38163928}
38173929
38183930static int is_dav_request(const struct connection *conn) {
3819   const char *s = conn->mg_conn.request_method;
3820   return !strcmp(s, "PUT") || !strcmp(s, "DELETE") ||
3821   !strcmp(s, "MKCOL") || !strcmp(s, "PROPFIND");
3931  const char *s = conn->mg_conn.request_method;
3932  return !strcmp(s, "PUT") || !strcmp(s, "DELETE") ||
3933    !strcmp(s, "MKCOL") || !strcmp(s, "PROPFIND");
38223934}
38233935#endif // MONGOOSE_NO_AUTH
38243936
38253937static int parse_header(const char *str, int str_len, const char *var_name,
3826                  char *buf, size_t buf_size) {
3827   int ch = ' ', len = 0, n = strlen(var_name);
3828   const char *p, *end = str + str_len, *s = NULL;
3938                        char *buf, size_t buf_size) {
3939  int ch = ' ', len = 0, n = strlen(var_name);
3940  const char *p, *end = str + str_len, *s = NULL;
38293941
3830   if (buf != NULL && buf_size > 0) buf[0] = '\0';
3942  if (buf != NULL && buf_size > 0) buf[0] = '\0';
38313943
3832   // Find where variable starts
3833   for (s = str; s != NULL && s + n < end; s++) {
3834   if ((s == str || s[-1] == ' ' || s[-1] == ',') && s[n] == '=' &&
3835      !memcmp(s, var_name, n)) break;
3836   }
3944  // Find where variable starts
3945  for (s = str; s != NULL && s + n < end; s++) {
3946    if ((s == str || s[-1] == ' ' || s[-1] == ',') && s[n] == '=' &&
3947        !memcmp(s, var_name, n)) break;
3948  }
38373949
3838   if (s != NULL && &s[n + 1] < end) {
3839   s += n + 1;
3840   if (*s == '"' || *s == '\'') ch = *s++;
3841   p = s;
3842   while (p < end && p[0] != ch && p[0] != ',' && len < (int) buf_size) {
3843      if (p[0] == '\\' && p[1] == ch) p++;
3844      buf[len++] = *p++;
3845   }
3846   if (len >= (int) buf_size || (ch != ' ' && *p != ch)) {
3847      len = 0;
3848   } else {
3849      if (len > 0 && s[len - 1] == ',') len--;
3850      if (len > 0 && s[len - 1] == ';') len--;
3851      buf[len] = '\0';
3852   }
3853   }
3950  if (s != NULL && &s[n + 1] < end) {
3951    s += n + 1;
3952    if (*s == '"' || *s == '\'') ch = *s++;
3953    p = s;
3954    while (p < end && p[0] != ch && p[0] != ',' && len < (int) buf_size) {
3955      if (p[0] == '\\' && p[1] == ch) p++;
3956      buf[len++] = *p++;
3957    }
3958    if (len >= (int) buf_size || (ch != ' ' && *p != ch)) {
3959      len = 0;
3960    } else {
3961      if (len > 0 && s[len - 1] == ',') len--;
3962      if (len > 0 && s[len - 1] == ';') len--;
3963      buf[len] = '\0';
3964    }
3965  }
38543966
3855   return len;
3967  return len;
38563968}
38573969
38583970int mg_parse_header(const char *s, const char *var_name, char *buf,
3859               size_t buf_size) {
3860   return parse_header(s, s == NULL ? 0 : strlen(s), var_name, buf, buf_size);
3971                    size_t buf_size) {
3972  return parse_header(s, s == NULL ? 0 : strlen(s), var_name, buf, buf_size);
38613973}
38623974
38633975#ifndef MONGOOSE_NO_SSI
38643976static void send_ssi_file(struct mg_connection *, const char *, FILE *, int);
38653977
38663978static void send_file_data(struct mg_connection *conn, FILE *fp) {
3867   char buf[IOBUF_SIZE];
3868   int n;
3869   while ((n = fread(buf, 1, sizeof(buf), fp)) > 0) {
3870   mg_write(conn, buf, n);
3871   }
3979  char buf[IOBUF_SIZE];
3980  int n;
3981  while ((n = fread(buf, 1, sizeof(buf), fp)) > 0) {
3982    mg_write(conn, buf, n);
3983  }
38723984}
38733985
38743986static void do_ssi_include(struct mg_connection *conn, const char *ssi,
3875                     char *tag, int include_level) {
3876   char file_name[IOBUF_SIZE], path[MAX_PATH_SIZE], *p;
3877   char **opts = (MG_CONN_2_CONN(conn))->server->config_options;
3878   FILE *fp;
3987                           char *tag, int include_level) {
3988  char file_name[IOBUF_SIZE], path[MAX_PATH_SIZE], *p;
3989  char **opts = (MG_CONN_2_CONN(conn))->server->config_options;
3990  FILE *fp;
38793991
3880   // sscanf() is safe here, since send_ssi_file() also uses buffer
3881   // of size MG_BUF_LEN to get the tag. So strlen(tag) is always < MG_BUF_LEN.
3882   if (sscanf(tag, " virtual=\"%[^\"]\"", file_name) == 1) {
3883   // File name is relative to the webserver root
3884   mg_snprintf(path, sizeof(path), "%s%c%s",
3885            opts[DOCUMENT_ROOT], '/', file_name);
3886   } else if (sscanf(tag, " abspath=\"%[^\"]\"", file_name) == 1) {
3887   // File name is relative to the webserver working directory
3888   // or it is absolute system path
3889   mg_snprintf(path, sizeof(path), "%s", file_name);
3890   } else if (sscanf(tag, " file=\"%[^\"]\"", file_name) == 1 ||
3891            sscanf(tag, " \"%[^\"]\"", file_name) == 1) {
3892   // File name is relative to the currect document
3893   mg_snprintf(path, sizeof(path), "%s", ssi);
3894   if ((p = strrchr(path, '/')) != NULL) {
3895      p[1] = '\0';
3896   }
3897   mg_snprintf(path + strlen(path), sizeof(path) - strlen(path), "%s",
3898            file_name);
3899   } else {
3900   mg_printf(conn, "Bad SSI #include: [%s]", tag);
3901   return;
3902   }
3992  // sscanf() is safe here, since send_ssi_file() also uses buffer
3993  // of size MG_BUF_LEN to get the tag. So strlen(tag) is always < MG_BUF_LEN.
3994  if (sscanf(tag, " virtual=\"%[^\"]\"", file_name) == 1) {
3995    // File name is relative to the webserver root
3996    mg_snprintf(path, sizeof(path), "%s%c%s",
3997                opts[DOCUMENT_ROOT], '/', file_name);
3998  } else if (sscanf(tag, " abspath=\"%[^\"]\"", file_name) == 1) {
3999    // File name is relative to the webserver working directory
4000    // or it is absolute system path
4001    mg_snprintf(path, sizeof(path), "%s", file_name);
4002  } else if (sscanf(tag, " file=\"%[^\"]\"", file_name) == 1 ||
4003             sscanf(tag, " \"%[^\"]\"", file_name) == 1) {
4004    // File name is relative to the currect document
4005    mg_snprintf(path, sizeof(path), "%s", ssi);
4006    if ((p = strrchr(path, '/')) != NULL) {
4007      p[1] = '\0';
4008    }
4009    mg_snprintf(path + strlen(path), sizeof(path) - strlen(path), "%s",
4010                file_name);
4011  } else {
4012    mg_printf(conn, "Bad SSI #include: [%s]", tag);
4013    return;
4014  }
39034015
3904   if ((fp = fopen(path, "rb")) == NULL) {
3905   mg_printf(conn, "Cannot open SSI #include: [%s]: fopen(%s): %s",
3906            tag, path, strerror(errno));
3907   } else {
3908   ns_set_close_on_exec(fileno(fp));
3909   if (mg_match_prefix(opts[SSI_PATTERN], strlen(opts[SSI_PATTERN]),
3910      path) > 0) {
3911      send_ssi_file(conn, path, fp, include_level + 1);
3912   } else {
3913      send_file_data(conn, fp);
3914   }
3915   fclose(fp);
3916   }
4016  if ((fp = fopen(path, "rb")) == NULL) {
4017    mg_printf(conn, "Cannot open SSI #include: [%s]: fopen(%s): %s",
4018              tag, path, strerror(errno));
4019  } else {
4020    ns_set_close_on_exec(fileno(fp));
4021    if (mg_match_prefix(opts[SSI_PATTERN], strlen(opts[SSI_PATTERN]),
4022        path) > 0) {
4023      send_ssi_file(conn, path, fp, include_level + 1);
4024    } else {
4025      send_file_data(conn, fp);
4026    }
4027    fclose(fp);
4028  }
39174029}
39184030
39194031#ifndef MONGOOSE_NO_POPEN
39204032static void do_ssi_exec(struct mg_connection *conn, char *tag) {
3921   char cmd[IOBUF_SIZE];
3922   FILE *fp;
4033  char cmd[IOBUF_SIZE];
4034  FILE *fp;
39234035
3924   if (sscanf(tag, " \"%[^\"]\"", cmd) != 1) {
3925   mg_printf(conn, "Bad SSI #exec: [%s]", tag);
3926   } else if ((fp = popen(cmd, "r")) == NULL) {
3927   mg_printf(conn, "Cannot SSI #exec: [%s]: %s", cmd, strerror(errno));
3928   } else {
3929   send_file_data(conn, fp);
3930   pclose(fp);
3931   }
4036  if (sscanf(tag, " \"%[^\"]\"", cmd) != 1) {
4037    mg_printf(conn, "Bad SSI #exec: [%s]", tag);
4038  } else if ((fp = popen(cmd, "r")) == NULL) {
4039    mg_printf(conn, "Cannot SSI #exec: [%s]: %s", cmd, strerror(errno));
4040  } else {
4041    send_file_data(conn, fp);
4042    pclose(fp);
4043  }
39324044}
39334045#endif // !MONGOOSE_NO_POPEN
39344046
39354047static void send_ssi_file(struct mg_connection *conn, const char *path,
3936                     FILE *fp, int include_level) {
3937   char buf[IOBUF_SIZE];
3938   int ch, offset, len, in_ssi_tag;
4048                          FILE *fp, int include_level) {
4049  char buf[IOBUF_SIZE];
4050  int ch, offset, len, in_ssi_tag;
39394051
3940   if (include_level > 10) {
3941   mg_printf(conn, "SSI #include level is too deep (%s)", path);
3942   return;
3943   }
4052  if (include_level > 10) {
4053    mg_printf(conn, "SSI #include level is too deep (%s)", path);
4054    return;
4055  }
39444056
3945   in_ssi_tag = len = offset = 0;
3946   while ((ch = fgetc(fp)) != EOF) {
3947   if (in_ssi_tag && ch == '>') {
3948      in_ssi_tag = 0;
3949      buf[len++] = (char) ch;
3950      buf[len] = '\0';
3951      assert(len <= (int) sizeof(buf));
3952      if (len < 6 || memcmp(buf, "<!--#", 5) != 0) {
3953      // Not an SSI tag, pass it
3954      (void) mg_write(conn, buf, (size_t) len);
3955      } else {
3956      if (!memcmp(buf + 5, "include", 7)) {
3957         do_ssi_include(conn, path, buf + 12, include_level);
4057  in_ssi_tag = len = offset = 0;
4058  while ((ch = fgetc(fp)) != EOF) {
4059    if (in_ssi_tag && ch == '>') {
4060      in_ssi_tag = 0;
4061      buf[len++] = (char) ch;
4062      buf[len] = '\0';
4063      assert(len <= (int) sizeof(buf));
4064      if (len < 6 || memcmp(buf, "<!--#", 5) != 0) {
4065        // Not an SSI tag, pass it
4066        (void) mg_write(conn, buf, (size_t) len);
4067      } else {
4068        if (!memcmp(buf + 5, "include", 7)) {
4069          do_ssi_include(conn, path, buf + 12, include_level);
39584070#if !defined(MONGOOSE_NO_POPEN)
3959      } else if (!memcmp(buf + 5, "exec", 4)) {
3960         do_ssi_exec(conn, buf + 9);
4071        } else if (!memcmp(buf + 5, "exec", 4)) {
4072          do_ssi_exec(conn, buf + 9);
39614073#endif // !NO_POPEN
3962      } else {
3963         mg_printf(conn, "%s: unknown SSI " "command: \"%s\"", path, buf);
3964      }
3965      }
3966      len = 0;
3967   } else if (in_ssi_tag) {
3968      if (len == 5 && memcmp(buf, "<!--#", 5) != 0) {
3969      // Not an SSI tag
3970      in_ssi_tag = 0;
3971      } else if (len == (int) sizeof(buf) - 2) {
3972      mg_printf(conn, "%s: SSI tag is too large", path);
3973      len = 0;
3974      }
3975      buf[len++] = ch & 0xff;
3976   } else if (ch == '<') {
3977      in_ssi_tag = 1;
3978      if (len > 0) {
3979      mg_write(conn, buf, (size_t) len);
3980      }
3981      len = 0;
3982      buf[len++] = ch & 0xff;
3983   } else {
3984      buf[len++] = ch & 0xff;
3985      if (len == (int) sizeof(buf)) {
3986      mg_write(conn, buf, (size_t) len);
3987      len = 0;
3988      }
3989   }
3990   }
4074        } else {
4075          mg_printf(conn, "%s: unknown SSI " "command: \"%s\"", path, buf);
4076        }
4077      }
4078      len = 0;
4079    } else if (in_ssi_tag) {
4080      if (len == 5 && memcmp(buf, "<!--#", 5) != 0) {
4081        // Not an SSI tag
4082        in_ssi_tag = 0;
4083      } else if (len == (int) sizeof(buf) - 2) {
4084        mg_printf(conn, "%s: SSI tag is too large", path);
4085        len = 0;
4086      }
4087      buf[len++] = ch & 0xff;
4088    } else if (ch == '<') {
4089      in_ssi_tag = 1;
4090      if (len > 0) {
4091        mg_write(conn, buf, (size_t) len);
4092      }
4093      len = 0;
4094      buf[len++] = ch & 0xff;
4095    } else {
4096      buf[len++] = ch & 0xff;
4097      if (len == (int) sizeof(buf)) {
4098        mg_write(conn, buf, (size_t) len);
4099        len = 0;
4100      }
4101    }
4102  }
39914103
3992   // Send the rest of buffered data
3993   if (len > 0) {
3994   mg_write(conn, buf, (size_t) len);
3995   }
4104  // Send the rest of buffered data
4105  if (len > 0) {
4106    mg_write(conn, buf, (size_t) len);
4107  }
39964108}
39974109
39984110static void handle_ssi_request(struct connection *conn, const char *path) {
3999   FILE *fp;
4000   struct vec mime_vec;
4111  FILE *fp;
4112  struct vec mime_vec;
40014113
4002   if ((fp = fopen(path, "rb")) == NULL) {
4003   send_http_error(conn, 500, "fopen(%s): %s", path, strerror(errno));
4004   } else {
4005   ns_set_close_on_exec(fileno(fp));
4006   get_mime_type(conn->server, path, &mime_vec);
4007   conn->mg_conn.status_code = 200;
4008   mg_printf(&conn->mg_conn,
4009            "HTTP/1.1 %d OK\r\n"
4010            "Content-Type: %.*s\r\n"
4011            "Connection: close\r\n\r\n",
4012            conn->mg_conn.status_code, (int) mime_vec.len, mime_vec.ptr);
4013   send_ssi_file(&conn->mg_conn, path, fp, 0);
4014   fclose(fp);
4015   close_local_endpoint(conn);
4016   }
4114  if ((fp = fopen(path, "rb")) == NULL) {
4115    send_http_error(conn, 500, "fopen(%s): %s", path, strerror(errno));
4116  } else {
4117    ns_set_close_on_exec(fileno(fp));
4118    get_mime_type(conn->server, path, &mime_vec);
4119    conn->mg_conn.status_code = 200;
4120    mg_printf(&conn->mg_conn,
4121              "HTTP/1.1 %d OK\r\n"
4122              "Content-Type: %.*s\r\n"
4123              "Connection: close\r\n\r\n",
4124              conn->mg_conn.status_code, (int) mime_vec.len, mime_vec.ptr);
4125    send_ssi_file(&conn->mg_conn, path, fp, 0);
4126    fclose(fp);
4127    close_local_endpoint(conn);
4128  }
40174129}
40184130#endif
40194131
40204132static void proxy_request(struct ns_connection *pc, struct mg_connection *c) {
4021   int i, sent_close_header = 0;
4133  int i, sent_close_header = 0;
40224134
4023   ns_printf(pc, "%s %s HTTP/%s\r\n", c->request_method, c->uri,
4024         c->http_version);
4025   for (i = 0; i < c->num_headers; i++) {
4026   if (mg_strcasecmp(c->http_headers[i].name, "Connection") == 0) {
4027      // Force connection close, cause we don't parse proxy replies
4028      // therefore we don't know message boundaries
4029      //ns_printf(pc, "%s: %s\r\n", "Connection", "close");
4030      sent_close_header = 1;
4031   //} else {
4032   }
4033      ns_printf(pc, "%s: %s\r\n", c->http_headers[i].name,
4034            c->http_headers[i].value);
4035   }
4036   if (!sent_close_header) {
4037   ns_printf(pc, "%s: %s\r\n", "Connection", "close");
4038   }
4039   ns_printf(pc, "%s", "\r\n");
4040   ns_send(pc, c->content, c->content_len);
4135  ns_printf(pc, "%s %s HTTP/%s\r\n", c->request_method, c->uri,
4136            c->http_version);
4137  for (i = 0; i < c->num_headers; i++) {
4138    if (mg_strcasecmp(c->http_headers[i].name, "Connection") == 0) {
4139      // Force connection close, cause we don't parse proxy replies
4140      // therefore we don't know message boundaries
4141      ns_printf(pc, "%s: %s\r\n", "Connection", "close");
4142      sent_close_header = 1;
4143    } else {
4144      ns_printf(pc, "%s: %s\r\n", c->http_headers[i].name,
4145                c->http_headers[i].value);
4146    }
4147  }
4148  if (!sent_close_header) {
4149    ns_printf(pc, "%s: %s\r\n", "Connection", "close");
4150  }
4151  ns_printf(pc, "%s", "\r\n");
4152  ns_send(pc, c->content, c->content_len);
40414153
40424154}
40434155
40444156#ifdef NS_ENABLE_SSL
40454157int mg_terminate_ssl(struct mg_connection *c, const char *cert) {
4046   static const char ok[] = "HTTP/1.0 200 OK\r\n\r\n";
4047   struct connection *conn = MG_CONN_2_CONN(c);
4048   int n;
4049   SSL_CTX *ctx;
4158  static const char ok[] = "HTTP/1.0 200 OK\r\n\r\n";
4159  struct connection *conn = MG_CONN_2_CONN(c);
4160  SSL_CTX *ctx;
40504161
4051   DBG(("%p MITM", conn));
4052   SSL_library_init();
4053   if ((ctx = SSL_CTX_new(SSLv23_server_method())) == NULL) return 0;
4162  DBG(("%p MITM", conn));
4163  SSL_library_init();
4164  if ((ctx = SSL_CTX_new(SSLv23_server_method())) == NULL) return 0;
40544165
4055   SSL_CTX_use_certificate_file(ctx, cert, 1);
4056   SSL_CTX_use_PrivateKey_file(ctx, cert, 1);
4057   SSL_CTX_use_certificate_chain_file(ctx, cert);
4166  SSL_CTX_use_certificate_file(ctx, cert, 1);
4167  SSL_CTX_use_PrivateKey_file(ctx, cert, 1);
4168  SSL_CTX_use_certificate_chain_file(ctx, cert);
40584169
4059   // When clear-text reply is pushed to client, switch to SSL mode.
4060   n = send(conn->ns_conn->sock, ok, sizeof(ok) - 1, 0);
4061   DBG(("%p %lu %d SEND", c, sizeof(ok) - 1, n));
4062   conn->ns_conn->send_iobuf.len = 0;
4063   conn->endpoint_type = EP_USER;  // To keep-alive in close_local_endpoint()
4064   close_local_endpoint(conn);     // Clean up current CONNECT request
4065   if ((conn->ns_conn->ssl = SSL_new(ctx)) != NULL) {
4066   SSL_set_fd(conn->ns_conn->ssl, conn->ns_conn->sock);
4067   }
4068   SSL_CTX_free(ctx);
4069   return 1;
4170  // When clear-text reply is pushed to client, switch to SSL mode.
4171  // TODO(lsm): check for send() failure
4172  send(conn->ns_conn->sock, ok, sizeof(ok) - 1, 0);
4173  DBG(("%p %lu %d SEND", c, (unsigned long)sizeof(ok) - 1, n));
4174  conn->ns_conn->send_iobuf.len = 0;
4175  conn->endpoint_type = EP_USER;  // To keep-alive in close_local_endpoint()
4176  close_local_endpoint(conn);     // Clean up current CONNECT request
4177  if ((conn->ns_conn->ssl = SSL_new(ctx)) != NULL) {
4178    SSL_set_fd(conn->ns_conn->ssl, conn->ns_conn->sock);
4179  }
4180  SSL_CTX_free(ctx);
4181  return 1;
40704182}
40714183#endif
40724184
4185int mg_forward(struct mg_connection *c, const char *host, int port, int ssl) {
4186  struct connection *conn = MG_CONN_2_CONN(c);
4187  struct ns_server *server = &conn->server->ns_server;
4188  struct ns_connection *pc;
4189
4190  if ((pc = ns_connect(server, host, port, ssl, conn)) == NULL) {
4191    conn->ns_conn->flags |= NSF_CLOSE_IMMEDIATELY;
4192    return 0;
4193  }
4194
4195  // Interlink two connections
4196  pc->flags |= MG_PROXY_CONN;
4197  conn->endpoint_type = EP_PROXY;
4198  conn->endpoint.nc = pc;
4199  DBG(("%p [%s] [%s:%d] -> %p %p",
4200      conn, c->uri, host, port, pc, conn->ns_conn->ssl));
4201
4202  if (strcmp(c->request_method, "CONNECT") == 0) {
4203    // For CONNECT request, reply with 200 OK. Tunnel is established.
4204    mg_printf(c, "%s", "HTTP/1.1 200 OK\r\n\r\n");
4205  } else {
4206    // Strip "http://host:port" part from the URI
4207    if (memcmp(c->uri, "http://", 7) == 0) c->uri += 7;
4208    while (*c->uri != '\0' && *c->uri != '/') c->uri++;
4209    proxy_request(pc, c);
4210  }
4211  return 1;
4212}
4213
40734214static void proxify_connection(struct connection *conn) {
4074   char proto[10], host[500], cert[500];
4075   unsigned short port = 80;
4076   struct mg_connection *c = &conn->mg_conn;
4077   struct ns_server *server = &conn->server->ns_server;
4078   struct ns_connection *pc = NULL;
4079   int n = 0;
4080   const char *url = c->uri;
4215  char proto[10], host[500], cert[500];
4216  unsigned short port = 80;
4217  struct mg_connection *c = &conn->mg_conn;
4218  int n = 0;
4219  const char *url = c->uri;
40814220
4082   proto[0] = host[0] = cert[0] = '\0';
4083   if (sscanf(url, "%499[^: ]:%hu%n", host, &port, &n) != 2 &&
4084      sscanf(url, "%9[a-z]://%499[^: ]:%hu%n", proto, host, &port, &n) != 3 &&
4085      sscanf(url, "%9[a-z]://%499[^/ ]%n", proto, host, &n) != 2) {
4086   n = 0;
4087   }
4221  proto[0] = host[0] = cert[0] = '\0';
4222  if (sscanf(url, "%499[^: ]:%hu%n", host, &port, &n) != 2 &&
4223      sscanf(url, "%9[a-z]://%499[^: ]:%hu%n", proto, host, &port, &n) != 3 &&
4224      sscanf(url, "%9[a-z]://%499[^/ ]%n", proto, host, &n) != 2) {
4225    n = 0;
4226  }
40884227
40894228#ifdef NS_ENABLE_SSL
4090   // Find out whether we should be in the MITM mode
4091   {
4092   const char *certs = conn->server->config_options[SSL_MITM_CERTS];
4093   int host_len = strlen(host);
4094   struct vec a, b;
4229  // Find out whether we should be in the MITM mode
4230  {
4231    const char *certs = conn->server->config_options[SSL_MITM_CERTS];
4232    int host_len = strlen(host);
4233    struct vec a, b;
40954234
4096   while (conn->ns_conn->ssl == NULL && port != 80 &&
4097         (certs = next_option(certs, &a, &b)) != NULL) {
4098      if (a.len != host_len || mg_strncasecmp(a.ptr, host, a.len)) continue;
4099      snprintf(cert, sizeof(cert), "%.*s", b.len, b.ptr);
4100      mg_terminate_ssl(&conn->mg_conn, cert);
4101      return;
4102   }
4103   }
4235    while (conn->ns_conn->ssl == NULL && port != 80 &&
4236           (certs = next_option(certs, &a, &b)) != NULL) {
4237      if (a.len != host_len || mg_strncasecmp(a.ptr, host, a.len)) continue;
4238      snprintf(cert, sizeof(cert), "%.*s", b.len, b.ptr);
4239      mg_terminate_ssl(&conn->mg_conn, cert);
4240      return;
4241    }
4242  }
41044243#endif
41054244
4106   if (n > 0 &&
4107      (pc = ns_connect(server, host, port, conn->ns_conn->ssl != NULL,
4108                  conn)) != NULL) {
4109   // Interlink two connections
4110   pc->flags |= MG_PROXY_CONN;
4111   conn->endpoint_type = EP_PROXY;
4112   conn->endpoint.nc = pc;
4113   DBG(("%p [%s] -> %p %p", conn, c->uri, pc, conn->ns_conn->ssl));
4114
4115   if (strcmp(c->request_method, "CONNECT") == 0) {
4116      // For CONNECT request, reply with 200 OK. Tunnel is established.
4117      mg_printf(c, "%s", "HTTP/1.1 200 OK\r\n\r\n");
4118      conn->request_len = 0;
4119      free(conn->request);
4120      conn->request = NULL;
4121   } else {
4122      // For other methods, forward the request to the target host.
4123      c->uri += n;
4124      proxy_request(pc, c);
4125   }
4126   } else {
4127   conn->ns_conn->flags |= NSF_CLOSE_IMMEDIATELY;
4128   }
4245  if (n > 0 && mg_forward(c, host, port, conn->ns_conn->ssl != NULL)) {
4246  } else {
4247    conn->ns_conn->flags |= NSF_CLOSE_IMMEDIATELY;
4248  }
41294249}
41304250
41314251#ifndef MONGOOSE_NO_FILESYSTEM
4132void mg_send_file(struct mg_connection *c, const char *file_name) {
4133   struct connection *conn = MG_CONN_2_CONN(c);
4134   file_stat_t st;
4135   char path[MAX_PATH_SIZE];
4136   int exists = 0, is_directory = 0;
4252void mg_send_file_internal(struct mg_connection *c, const char *file_name,
4253                           file_stat_t *st, int exists) {
4254  struct connection *conn = MG_CONN_2_CONN(c);
4255  char path[MAX_PATH_SIZE];
4256  const int is_directory = S_ISDIR(st->st_mode);
41374257#ifndef MONGOOSE_NO_CGI
4138   const char *cgi_pat = conn->server->config_options[CGI_PATTERN];
4258  const char *cgi_pat = conn->server->config_options[CGI_PATTERN];
41394259#else
4140   const char *cgi_pat = DEFAULT_CGI_PATTERN;
4260  const char *cgi_pat = DEFAULT_CGI_PATTERN;
41414261#endif
41424262#ifndef MONGOOSE_NO_DIRECTORY_LISTING
4143   const char *dir_lst = conn->server->config_options[ENABLE_DIRECTORY_LISTING];
4263  const char *dir_lst = conn->server->config_options[ENABLE_DIRECTORY_LISTING];
41444264#else
4145   const char *dir_lst = "yes";
4265  const char *dir_lst = "yes";
41464266#endif
41474267
4148   mg_snprintf(path, sizeof(path), "%s", file_name);
4149   exists = stat(path, &st) == 0;
4150   is_directory = S_ISDIR(st.st_mode);
4268  mg_snprintf(path, sizeof(path), "%s", file_name);
41514269
4152   if (!exists || must_hide_file(conn, path)) {
4153   send_http_error(conn, 404, NULL);
4154   } else if (is_directory &&
4155            conn->mg_conn.uri[strlen(conn->mg_conn.uri) - 1] != '/') {
4156   conn->mg_conn.status_code = 301;
4157   mg_printf(&conn->mg_conn, "HTTP/1.1 301 Moved Permanently\r\n"
4158            "Location: %s/\r\n\r\n", conn->mg_conn.uri);
4159   close_local_endpoint(conn);
4160   } else if (is_directory && !find_index_file(conn, path, sizeof(path), &st)) {
4161   if (!mg_strcasecmp(dir_lst, "yes")) {
4270  if (!exists || must_hide_file(conn, path)) {
4271    send_http_error(conn, 404, NULL);
4272  } else if (is_directory &&
4273             conn->mg_conn.uri[strlen(conn->mg_conn.uri) - 1] != '/') {
4274    conn->mg_conn.status_code = 301;
4275    mg_printf(&conn->mg_conn, "HTTP/1.1 301 Moved Permanently\r\n"
4276              "Location: %s/\r\n\r\n", conn->mg_conn.uri);
4277    close_local_endpoint(conn);
4278  } else if (is_directory && !find_index_file(conn, path, sizeof(path), st)) {
4279    if (!mg_strcasecmp(dir_lst, "yes")) {
41624280#ifndef MONGOOSE_NO_DIRECTORY_LISTING
4163      send_directory_listing(conn, path);
4281      send_directory_listing(conn, path);
41644282#else
4165      send_http_error(conn, 501, NULL);
4283      send_http_error(conn, 501, NULL);
41664284#endif
4167   } else {
4168      send_http_error(conn, 403, NULL);
4169   }
4170   } else if (mg_match_prefix(cgi_pat, strlen(cgi_pat), path) > 0) {
4285    } else {
4286      send_http_error(conn, 403, NULL);
4287    }
4288  } else if (mg_match_prefix(cgi_pat, strlen(cgi_pat), path) > 0) {
41714289#if !defined(MONGOOSE_NO_CGI)
4172   open_cgi_endpoint(conn, path);
4290    open_cgi_endpoint(conn, path);
41734291#else
4174   send_http_error(conn, 501, NULL);
4292    send_http_error(conn, 501, NULL);
41754293#endif // !MONGOOSE_NO_CGI
41764294#ifndef MONGOOSE_NO_SSI
4177   } else if (mg_match_prefix(conn->server->config_options[SSI_PATTERN],
4178                        strlen(conn->server->config_options[SSI_PATTERN]),
4179                        path) > 0) {
4180   handle_ssi_request(conn, path);
4295  } else if (mg_match_prefix(conn->server->config_options[SSI_PATTERN],
4296                             strlen(conn->server->config_options[SSI_PATTERN]),
4297                             path) > 0) {
4298    handle_ssi_request(conn, path);
41814299#endif
4182   } else if (is_not_modified(conn, &st)) {
4183   send_http_error(conn, 304, NULL);
4184   } else if ((conn->endpoint.fd = open(path, O_RDONLY | O_BINARY)) != -1) {
4185   // O_BINARY is required for Windows, otherwise in default text mode
4186   // two bytes \r\n will be read as one.
4187   open_file_endpoint(conn, path, &st);
4188   } else {
4189   send_http_error(conn, 404, NULL);
4190   }
4300  } else if (is_not_modified(conn, st)) {
4301    send_http_error(conn, 304, NULL);
4302  } else if ((conn->endpoint.fd = open(path, O_RDONLY | O_BINARY)) != -1) {
4303    // O_BINARY is required for Windows, otherwise in default text mode
4304    // two bytes \r\n will be read as one.
4305    open_file_endpoint(conn, path, st);
4306  } else {
4307    send_http_error(conn, 404, NULL);
4308  }
41914309}
4310void mg_send_file(struct mg_connection *c, const char *file_name) {
4311  file_stat_t st;
4312  const int exists = stat(file_name, &st) == 0;
4313  mg_send_file_internal(c, file_name, &st, exists);
4314}
41924315#endif  // !MONGOOSE_NO_FILESYSTEM
41934316
41944317static void open_local_endpoint(struct connection *conn, int skip_user) {
41954318#ifndef MONGOOSE_NO_FILESYSTEM
4196   char path[MAX_PATH_SIZE];
4197   file_stat_t st;
4198   int exists = 0;
4319  char path[MAX_PATH_SIZE];
4320  file_stat_t st;
4321  int exists = 0;
41994322#endif
42004323
4201   // If EP_USER was set in a prev call, reset it
4202   conn->endpoint_type = EP_NONE;
4324  // If EP_USER was set in a prev call, reset it
4325  conn->endpoint_type = EP_NONE;
42034326
42044327#ifndef MONGOOSE_NO_AUTH
4205   if (conn->server->event_handler && call_user(conn, MG_AUTH) == MG_FALSE) {
4206   mg_send_digest_auth_request(&conn->mg_conn);
4207   return;
4208   }
4328  if (conn->server->event_handler && call_user(conn, MG_AUTH) == MG_FALSE) {
4329    mg_send_digest_auth_request(&conn->mg_conn);
4330    return;
4331  }
42094332#endif
42104333
4211   // Call URI handler if one is registered for this URI
4212   if (skip_user == 0 && conn->server->event_handler != NULL) {
4213   conn->endpoint_type = EP_USER;
4334  // Call URI handler if one is registered for this URI
4335  if (skip_user == 0 && conn->server->event_handler != NULL) {
4336    conn->endpoint_type = EP_USER;
42144337#if MONGOOSE_POST_SIZE_LIMIT > 1
4215   {
4216      const char *cl = mg_get_header(&conn->mg_conn, "Content-Length");
4217      if ((strcmp(conn->mg_conn.request_method, "POST") == 0 ||
4218         strcmp(conn->mg_conn.request_method, "PUT") == 0) &&
4219         (cl == NULL || to64(cl) > MONGOOSE_POST_SIZE_LIMIT)) {
4220      send_http_error(conn, 500, "POST size > %zu",
4221                  (size_t) MONGOOSE_POST_SIZE_LIMIT);
4222      }
4223   }
4338    {
4339      const char *cl = mg_get_header(&conn->mg_conn, "Content-Length");
4340      if ((strcmp(conn->mg_conn.request_method, "POST") == 0 ||
4341           strcmp(conn->mg_conn.request_method, "PUT") == 0) &&
4342          (cl == NULL || to64(cl) > MONGOOSE_POST_SIZE_LIMIT)) {
4343        send_http_error(conn, 500, "POST size > %lu",
4344                        (unsigned long) MONGOOSE_POST_SIZE_LIMIT);
4345      }
4346    }
42244347#endif
4225   return;
4226   }
4348    return;
4349  }
42274350
4228   if (strcmp(conn->mg_conn.request_method, "CONNECT") == 0 ||
4229      memcmp(conn->mg_conn.uri, "http", 4) == 0) {
4230   proxify_connection(conn);
4231   return;
4232   }
4351  if (strcmp(conn->mg_conn.request_method, "CONNECT") == 0 ||
4352      mg_strncasecmp(conn->mg_conn.uri, "http", 4) == 0) {
4353    const char *enp = conn->server->config_options[ENABLE_PROXY];
4354    if (enp == NULL || strcmp(enp, "yes") != 0) {
4355      send_http_error(conn, 405, NULL);
4356    } else {
4357      proxify_connection(conn);
4358    }
4359    return;
4360  }
42334361
4234   if (!strcmp(conn->mg_conn.request_method, "OPTIONS")) {
4235   send_options(conn);
4236   return;
4237   }
4362  if (!strcmp(conn->mg_conn.request_method, "OPTIONS")) {
4363    send_options(conn);
4364    return;
4365  }
42384366
42394367#ifdef MONGOOSE_NO_FILESYSTEM
4240   send_http_error(conn, 404, NULL);
4368  send_http_error(conn, 404, NULL);
42414369#else
4242   exists = convert_uri_to_file_name(conn, path, sizeof(path), &st);
4370  exists = convert_uri_to_file_name(conn, path, sizeof(path), &st);
42434371
4244   if (!strcmp(conn->mg_conn.request_method, "OPTIONS")) {
4245   send_options(conn);
4246   } else if (conn->server->config_options[DOCUMENT_ROOT] == NULL) {
4247   send_http_error(conn, 404, NULL);
4372  if (!strcmp(conn->mg_conn.request_method, "OPTIONS")) {
4373    send_options(conn);
4374  } else if (conn->server->config_options[DOCUMENT_ROOT] == NULL) {
4375    send_http_error(conn, 404, NULL);
42484376#ifndef MONGOOSE_NO_AUTH
4249   } else if ((!is_dav_request(conn) && !is_authorized(conn, path)) ||
4250            (is_dav_request(conn) && !is_authorized_for_dav(conn))) {
4251   mg_send_digest_auth_request(&conn->mg_conn);
4252   close_local_endpoint(conn);
4377  } else if ((!is_dav_request(conn) && !is_authorized(conn, path,
4378               exists && S_ISDIR(st.st_mode))) ||
4379             (is_dav_request(conn) && !is_authorized_for_dav(conn))) {
4380    mg_send_digest_auth_request(&conn->mg_conn);
4381    close_local_endpoint(conn);
42534382#endif
42544383#ifndef MONGOOSE_NO_DAV
4255   } else if (!strcmp(conn->mg_conn.request_method, "PROPFIND")) {
4256   handle_propfind(conn, path, &st, exists);
4257   } else if (!strcmp(conn->mg_conn.request_method, "MKCOL")) {
4258   handle_mkcol(conn, path);
4259   } else if (!strcmp(conn->mg_conn.request_method, "DELETE")) {
4260   handle_delete(conn, path);
4261   } else if (!strcmp(conn->mg_conn.request_method, "PUT")) {
4262   handle_put(conn, path);
4384  } else if (must_hide_file(conn, path)) {
4385    send_http_error(conn, 404, NULL);
4386  } else if (!strcmp(conn->mg_conn.request_method, "PROPFIND")) {
4387    handle_propfind(conn, path, &st, exists);
4388  } else if (!strcmp(conn->mg_conn.request_method, "MKCOL")) {
4389    handle_mkcol(conn, path);
4390  } else if (!strcmp(conn->mg_conn.request_method, "DELETE")) {
4391    handle_delete(conn, path);
4392  } else if (!strcmp(conn->mg_conn.request_method, "PUT")) {
4393    handle_put(conn, path);
42634394#endif
4264   } else {
4265   mg_send_file(&conn->mg_conn, path);
4266   }
4395  } else {
4396    mg_send_file_internal(&conn->mg_conn, path, &st, exists);
4397  }
42674398#endif  // MONGOOSE_NO_FILESYSTEM
42684399}
42694400
42704401static void send_continue_if_expected(struct connection *conn) {
4271   static const char expect_response[] = "HTTP/1.1 100 Continue\r\n\r\n";
4272   const char *expect_hdr = mg_get_header(&conn->mg_conn, "Expect");
4402  static const char expect_response[] = "HTTP/1.1 100 Continue\r\n\r\n";
4403  const char *expect_hdr = mg_get_header(&conn->mg_conn, "Expect");
42734404
4274   if (expect_hdr != NULL && !mg_strcasecmp(expect_hdr, "100-continue")) {
4275   ns_send(conn->ns_conn, expect_response, sizeof(expect_response) - 1);
4276   }
4405  if (expect_hdr != NULL && !mg_strcasecmp(expect_hdr, "100-continue")) {
4406    ns_send(conn->ns_conn, expect_response, sizeof(expect_response) - 1);
4407  }
42774408}
42784409
42794410// Conform to http://www.w3.org/Protocols/rfc2616/rfc2616-sec5.html#sec5.1.2
42804411static int is_valid_uri(const char *uri) {
4281   unsigned short n;
4282   return uri[0] == '/' ||
4283   strcmp(uri, "*") == 0 ||            // OPTIONS method can use asterisk URI
4284   memcmp(uri, "http", 4) == 0 ||      // Naive check for the absolute URI
4285   sscanf(uri, "%*[^ :]:%hu", &n) > 0; // CONNECT method can use host:port
4412  unsigned short n;
4413  return uri[0] == '/' ||
4414    strcmp(uri, "*") == 0 ||            // OPTIONS method can use asterisk URI
4415    mg_strncasecmp(uri, "http", 4) == 0 || // Naive check for the absolute URI
4416    sscanf(uri, "%*[^ :]:%hu", &n) > 0; // CONNECT method can use host:port
42864417}
42874418
42884419static void try_parse(struct connection *conn) {
4289   struct iobuf *io = &conn->ns_conn->recv_iobuf;
4420  struct iobuf *io = &conn->ns_conn->recv_iobuf;
42904421
4291   if (conn->request_len == 0 &&
4292      (conn->request_len = get_request_len(io->buf, io->len)) > 0) {
4293   // If request is buffered in, remove it from the iobuf. This is because
4294   // iobuf could be reallocated, and pointers in parsed request could
4295   // become invalid.
4296   conn->request = (char *) malloc(conn->request_len);
4297   memcpy(conn->request, io->buf, conn->request_len);
4298   //DBG(("%p [%.*s]", conn, conn->request_len, conn->request));
4299   iobuf_remove(io, conn->request_len);
4300   conn->request_len = parse_http_message(conn->request, conn->request_len,
4301                                 &conn->mg_conn);
4302   if (conn->request_len > 0) {
4303      const char *cl_hdr = mg_get_header(&conn->mg_conn, "Content-Length");
4304      conn->cl = cl_hdr == NULL ? 0 : to64(cl_hdr);
4305      conn->mg_conn.content_len = (size_t) conn->cl;
4306   }
4307   }
4422  if (conn->request_len == 0 &&
4423      (conn->request_len = get_request_len(io->buf, io->len)) > 0) {
4424    // If request is buffered in, remove it from the iobuf. This is because
4425    // iobuf could be reallocated, and pointers in parsed request could
4426    // become invalid.
4427    conn->request = (char *) malloc(conn->request_len);
4428    memcpy(conn->request, io->buf, conn->request_len);
4429    //DBG(("%p [%.*s]", conn, conn->request_len, conn->request));
4430    iobuf_remove(io, conn->request_len);
4431    conn->request_len = parse_http_message(conn->request, conn->request_len,
4432                                           &conn->mg_conn);
4433    if (conn->request_len > 0) {
4434      const char *cl_hdr = mg_get_header(&conn->mg_conn, "Content-Length");
4435      conn->cl = cl_hdr == NULL ? 0 : to64(cl_hdr);
4436      conn->mg_conn.content_len = (size_t) conn->cl;
4437    }
4438  }
43084439}
43094440
43104441static void do_proxy(struct connection *conn) {
4311   if (conn->request_len == 0) {
4312   try_parse(conn);
4313   DBG(("%p parsing -> %d", conn, conn->request_len));
4314   if (conn->request_len > 0 && call_user(conn, MG_REQUEST) == MG_FALSE) {
4315      proxy_request(conn->endpoint.nc, &conn->mg_conn);
4316   } else if (conn->request_len < 0) {
4317      ns_forward(conn->ns_conn, conn->endpoint.nc);
4318   }
4319   } else {
4320   DBG(("%p forwarding", conn));
4321   ns_forward(conn->ns_conn, conn->endpoint.nc);
4322   }
4442  if (0 && conn->request_len == 0) {
4443    try_parse(conn);
4444    DBG(("%p parsing -> %d", conn, conn->request_len));
4445    if (conn->request_len > 0 && call_user(conn, MG_REQUEST) == MG_FALSE) {
4446      proxy_request(conn->endpoint.nc, &conn->mg_conn);
4447    } else if (conn->request_len < 0) {
4448      ns_forward(conn->ns_conn, conn->endpoint.nc);
4449    }
4450  } else {
4451    DBG(("%p forwarding", conn));
4452    ns_forward(conn->ns_conn, conn->endpoint.nc);
4453  }
43234454}
43244455
43254456static void on_recv_data(struct connection *conn) {
4326   struct iobuf *io = &conn->ns_conn->recv_iobuf;
4457  struct iobuf *io = &conn->ns_conn->recv_iobuf;
4458  int n;
43274459
4328   if (conn->endpoint_type == EP_PROXY && conn->endpoint.nc != NULL) {
4329   do_proxy(conn);
4330   return;
4331   }
4460  if (conn->endpoint_type == EP_PROXY) {
4461    if (conn->endpoint.nc != NULL) do_proxy(conn);
4462    return;
4463  }
43324464
4333   try_parse(conn);
4334   DBG(("%p %d %zu %d", conn, conn->request_len, io->len, conn->ns_conn->flags));
4335   if (conn->request_len < 0 ||
4336      (conn->request_len > 0 && !is_valid_uri(conn->mg_conn.uri))) {
4337   send_http_error(conn, 400, NULL);
4338   } else if (conn->request_len == 0 && io->len > MAX_REQUEST_SIZE) {
4339   send_http_error(conn, 413, NULL);
4340   } else if (conn->request_len > 0 &&
4341            strcmp(conn->mg_conn.http_version, "1.0") != 0 &&
4342            strcmp(conn->mg_conn.http_version, "1.1") != 0) {
4343   send_http_error(conn, 505, NULL);
4344   } else if (conn->request_len > 0 && conn->endpoint_type == EP_NONE) {
4465  try_parse(conn);
4466  DBG(("%p %d %lu %d", conn, conn->request_len, (unsigned long)io->len,
4467       conn->ns_conn->flags));
4468  if (conn->request_len < 0 ||
4469      (conn->request_len > 0 && !is_valid_uri(conn->mg_conn.uri))) {
4470    send_http_error(conn, 400, NULL);
4471  } else if (conn->request_len == 0 && io->len > MAX_REQUEST_SIZE) {
4472    send_http_error(conn, 413, NULL);
4473  } else if (conn->request_len > 0 &&
4474             strcmp(conn->mg_conn.http_version, "1.0") != 0 &&
4475             strcmp(conn->mg_conn.http_version, "1.1") != 0) {
4476    send_http_error(conn, 505, NULL);
4477  } else if (conn->request_len > 0 && conn->endpoint_type == EP_NONE) {
43454478#ifndef MONGOOSE_NO_WEBSOCKET
4346   send_websocket_handshake_if_requested(&conn->mg_conn);
4479    send_websocket_handshake_if_requested(&conn->mg_conn);
43474480#endif
4348   send_continue_if_expected(conn);
4349   open_local_endpoint(conn, 0);
4350   }
4481    send_continue_if_expected(conn);
4482    open_local_endpoint(conn, 0);
4483  }
43514484
43524485#ifndef MONGOOSE_NO_CGI
4353   if (conn->endpoint_type == EP_CGI && conn->endpoint.nc != NULL) {
4354   ns_forward(conn->ns_conn, conn->endpoint.nc);
4355   }
4486  if (conn->endpoint_type == EP_CGI && conn->endpoint.nc != NULL) {
4487    ns_forward(conn->ns_conn, conn->endpoint.nc);
4488  }
43564489#endif
4357   if (conn->endpoint_type == EP_USER) {
4358   call_request_handler_if_data_is_buffered(conn);
4359   }
4490  if (conn->endpoint_type == EP_USER) {
4491    conn->mg_conn.content = io->buf;
4492    conn->mg_conn.content_len = io->len;
4493    n = call_user(conn, MG_RECV);
4494    if (n < 0) {
4495      conn->ns_conn->flags |= NSF_FINISHED_SENDING_DATA;
4496    } else if ((size_t) n <= io->len) {
4497      iobuf_remove(io, n);
4498    }
4499    call_request_handler_if_data_is_buffered(conn);
4500  }
43604501#ifndef MONGOOSE_NO_DAV
4361   if (conn->endpoint_type == EP_PUT && io->len > 0) {
4362   forward_put_data(conn);
4363   }
4502  if (conn->endpoint_type == EP_PUT && io->len > 0) {
4503    forward_put_data(conn);
4504  }
43644505#endif
43654506}
43664507
43674508static void call_http_client_handler(struct connection *conn) {
4368   //conn->mg_conn.status_code = code;
4369   // For responses without Content-Lengh, use the whole buffer
4370   if (conn->cl == 0) {
4371   conn->mg_conn.content_len = conn->ns_conn->recv_iobuf.len;
4372   }
4373   conn->mg_conn.content = conn->ns_conn->recv_iobuf.buf;
4374   if (call_user(conn, MG_REPLY) == MG_FALSE) {
4375   conn->ns_conn->flags |= NSF_CLOSE_IMMEDIATELY;
4376   }
4377   iobuf_remove(&conn->ns_conn->recv_iobuf, conn->mg_conn.content_len);
4378   conn->mg_conn.status_code = 0;
4379   conn->cl = conn->num_bytes_sent = conn->request_len = 0;
4380   free(conn->request);
4381   conn->request = NULL;
4509  //conn->mg_conn.status_code = code;
4510  // For responses without Content-Lengh, use the whole buffer
4511  if (conn->cl == 0) {
4512    conn->mg_conn.content_len = conn->ns_conn->recv_iobuf.len;
4513  }
4514  conn->mg_conn.content = conn->ns_conn->recv_iobuf.buf;
4515  if (call_user(conn, MG_REPLY) == MG_FALSE) {
4516    conn->ns_conn->flags |= NSF_CLOSE_IMMEDIATELY;
4517  }
4518  iobuf_remove(&conn->ns_conn->recv_iobuf, conn->mg_conn.content_len);
4519  conn->mg_conn.status_code = 0;
4520  conn->cl = conn->num_bytes_recv = conn->request_len = 0;
4521  free(conn->request);
4522  conn->request = NULL;
43824523}
43834524
43844525static void process_response(struct connection *conn) {
4385   struct iobuf *io = &conn->ns_conn->recv_iobuf;
4526  struct iobuf *io = &conn->ns_conn->recv_iobuf;
43864527
4387   try_parse(conn);
4388   DBG(("%p %d %zu", conn, conn->request_len, io->len));
4389   if (conn->request_len < 0 ||
4390      (conn->request_len == 0 && io->len > MAX_REQUEST_SIZE)) {
4391   call_http_client_handler(conn);
4392   } else if ((int64_t) io->len >= conn->cl) {
4393   call_http_client_handler(conn);
4394   }
4528  try_parse(conn);
4529  DBG(("%p %d %lu", conn, conn->request_len, (unsigned long)io->len));
4530  if (conn->request_len < 0 ||
4531      (conn->request_len == 0 && io->len > MAX_REQUEST_SIZE)) {
4532    call_http_client_handler(conn);
4533  } else if ((int64_t) io->len >= conn->cl) {
4534    call_http_client_handler(conn);
4535  }
43954536}
43964537
43974538struct mg_connection *mg_connect(struct mg_server *server, const char *host,
4398                           int port, int use_ssl) {
4399   struct ns_connection *nsconn;
4400   struct connection *conn;
4539                                 int port, int use_ssl) {
4540  struct ns_connection *nsconn;
4541  struct connection *conn;
44014542
4402   nsconn = ns_connect(&server->ns_server, host, port, use_ssl, NULL);
4403   if (nsconn == NULL) return 0;
4543  nsconn = ns_connect(&server->ns_server, host, port, use_ssl, NULL);
4544  if (nsconn == NULL) return 0;
44044545
4405   if ((conn = (struct connection *) calloc(1, sizeof(*conn))) == NULL) {
4406   nsconn->flags |= NSF_CLOSE_IMMEDIATELY;
4407   return 0;
4408   }
4546  if ((conn = (struct connection *) calloc(1, sizeof(*conn))) == NULL) {
4547    nsconn->flags |= NSF_CLOSE_IMMEDIATELY;
4548    return 0;
4549  }
44094550
4410   // Interlink two structs
4411   conn->ns_conn = nsconn;
4412   nsconn->connection_data = conn;
4551  // Interlink two structs
4552  conn->ns_conn = nsconn;
4553  nsconn->connection_data = conn;
44134554
4414   conn->server = server;
4415   conn->endpoint_type = EP_CLIENT;
4416   //conn->handler = handler;
4417   conn->mg_conn.server_param = server->ns_server.server_data;
4418   conn->ns_conn->flags = NSF_CONNECTING;
4555  conn->server = server;
4556  conn->endpoint_type = EP_CLIENT;
4557  //conn->handler = handler;
4558  conn->mg_conn.server_param = server->ns_server.server_data;
4559  conn->ns_conn->flags = NSF_CONNECTING;
44194560
4420   return &conn->mg_conn;
4561  return &conn->mg_conn;
44214562}
44224563
44234564#ifndef MONGOOSE_NO_LOGGING
44244565static void log_header(const struct mg_connection *conn, const char *header,
4425                  FILE *fp) {
4426   const char *header_value;
4566                       FILE *fp) {
4567  const char *header_value;
44274568
4428   if ((header_value = mg_get_header(conn, header)) == NULL) {
4429   (void) fprintf(fp, "%s", " -");
4430   } else {
4431   (void) fprintf(fp, " \"%s\"", header_value);
4432   }
4569  if ((header_value = mg_get_header(conn, header)) == NULL) {
4570    (void) fprintf(fp, "%s", " -");
4571  } else {
4572    (void) fprintf(fp, " \"%s\"", header_value);
4573  }
44334574}
44344575
44354576static void log_access(const struct connection *conn, const char *path) {
4436   const struct mg_connection *c = &conn->mg_conn;
4437   FILE *fp = (path == NULL) ?  NULL : fopen(path, "a+");
4438   char date[64], user[100];
4439   time_t now;
4577  const struct mg_connection *c = &conn->mg_conn;
4578  FILE *fp = (path == NULL) ?  NULL : fopen(path, "a+");
4579  char date[64], user[100];
4580  time_t now;
44404581
4441   if (fp == NULL) return;
4442   now = time(NULL);
4443   strftime(date, sizeof(date), "%d/%b/%Y:%H:%M:%S %z", localtime(&now));
4582  if (fp == NULL) return;
4583  now = time(NULL);
4584  strftime(date, sizeof(date), "%d/%b/%Y:%H:%M:%S %z", localtime(&now));
44444585
4445   flockfile(fp);
4446   mg_parse_header(mg_get_header(&conn->mg_conn, "Authorization"), "username",
4447               user, sizeof(user));
4448   fprintf(fp, "%s - %s [%s] \"%s %s%s%s HTTP/%s\" %d %" INT64_FMT,
4449         c->remote_ip, user[0] == '\0' ? "-" : user, date,
4450         c->request_method ? c->request_method : "-",
4451         c->uri ? c->uri : "-", c->query_string ? "?" : "",
4452         c->query_string ? c->query_string : "",
4453         c->http_version, c->status_code, conn->num_bytes_sent);
4454   log_header(c, "Referer", fp);
4455   log_header(c, "User-Agent", fp);
4456   fputc('\n', fp);
4457   fflush(fp);
4586  flockfile(fp);
4587  mg_parse_header(mg_get_header(&conn->mg_conn, "Authorization"), "username",
4588                  user, sizeof(user));
4589  fprintf(fp, "%s - %s [%s] \"%s %s%s%s HTTP/%s\" %d 0",
4590          c->remote_ip, user[0] == '\0' ? "-" : user, date,
4591          c->request_method ? c->request_method : "-",
4592          c->uri ? c->uri : "-", c->query_string ? "?" : "",
4593          c->query_string ? c->query_string : "",
4594          c->http_version, c->status_code);
4595  log_header(c, "Referer", fp);
4596  log_header(c, "User-Agent", fp);
4597  fputc('\n', fp);
4598  fflush(fp);
44584599
4459   funlockfile(fp);
4460   fclose(fp);
4600  funlockfile(fp);
4601  fclose(fp);
44614602}
44624603#endif
44634604
44644605static void close_local_endpoint(struct connection *conn) {
4465   struct mg_connection *c = &conn->mg_conn;
4466   // Must be done before free()
4467   int keep_alive = should_keep_alive(&conn->mg_conn) &&
4468   (conn->endpoint_type == EP_FILE || conn->endpoint_type == EP_USER);
4469   DBG(("%p %d %d %d", conn, conn->endpoint_type, keep_alive,
4470      conn->ns_conn->flags));
4606  struct mg_connection *c = &conn->mg_conn;
4607  // Must be done before free()
4608  int keep_alive = should_keep_alive(&conn->mg_conn) &&
4609    (conn->endpoint_type == EP_FILE || conn->endpoint_type == EP_USER);
4610  DBG(("%p %d %d %d", conn, conn->endpoint_type, keep_alive,
4611       conn->ns_conn->flags));
44714612
4472   switch (conn->endpoint_type) {
4473   case EP_PUT:
4474   case EP_FILE:
4475      close(conn->endpoint.fd);
4476      break;
4477   case EP_CGI:
4478   case EP_PROXY:
4479      if (conn->endpoint.nc != NULL) {
4480      DBG(("%p %p %p :-)", conn, conn->ns_conn, conn->endpoint.nc));
4481      conn->endpoint.nc->flags |= NSF_CLOSE_IMMEDIATELY;
4482      conn->endpoint.nc->connection_data = NULL;
4483      }
4484      break;
4485   default: break;
4486   }
4613  switch (conn->endpoint_type) {
4614    case EP_PUT:
4615    case EP_FILE:
4616      close(conn->endpoint.fd);
4617      break;
4618    case EP_CGI:
4619    case EP_PROXY:
4620      if (conn->endpoint.nc != NULL) {
4621        DBG(("%p %p %p :-)", conn, conn->ns_conn, conn->endpoint.nc));
4622        conn->endpoint.nc->flags |= NSF_CLOSE_IMMEDIATELY;
4623        conn->endpoint.nc->connection_data = NULL;
4624      }
4625      break;
4626    default: break;
4627  }
44874628
44884629#ifndef MONGOOSE_NO_LOGGING
4489   if (c->status_code > 0 && conn->endpoint_type != EP_CLIENT &&
4490      c->status_code != 400) {
4491   log_access(conn, conn->server->config_options[ACCESS_LOG_FILE]);
4492   }
4630  if (c->status_code > 0 && conn->endpoint_type != EP_CLIENT &&
4631      c->status_code != 400) {
4632    log_access(conn, conn->server->config_options[ACCESS_LOG_FILE]);
4633  }
44934634#endif
44944635
4495   // Gobble possible POST data sent to the URI handler
4496   iobuf_free(&conn->ns_conn->recv_iobuf);
4497   free(conn->request);
4498   free(conn->path_info);
4636  // Gobble possible POST data sent to the URI handler
4637  iobuf_free(&conn->ns_conn->recv_iobuf);
4638  free(conn->request);
4639  free(conn->path_info);
4640  conn->endpoint.nc = NULL;
4641  conn->request = conn->path_info = NULL;
44994642
4500   conn->endpoint_type = EP_NONE;
4501   conn->cl = conn->num_bytes_sent = conn->request_len = 0;
4502   conn->ns_conn->flags &= ~(NSF_FINISHED_SENDING_DATA |
4503                     NSF_BUFFER_BUT_DONT_SEND | NSF_CLOSE_IMMEDIATELY |
4504                     MG_HEADERS_SENT | MG_LONG_RUNNING);
4505   c->num_headers = c->status_code = c->is_websocket = c->content_len = 0;
4506   conn->endpoint.nc = NULL;
4507   c->request_method = c->uri = c->http_version = c->query_string = NULL;
4508   conn->request = conn->path_info = NULL;
4643  conn->endpoint_type = EP_NONE;
4644  conn->cl = conn->num_bytes_recv = conn->request_len = 0;
4645  conn->ns_conn->flags &= ~(NSF_FINISHED_SENDING_DATA |
4646                            NSF_BUFFER_BUT_DONT_SEND | NSF_CLOSE_IMMEDIATELY |
4647                            MG_HEADERS_SENT | MG_LONG_RUNNING);
45094648
4510   if (keep_alive) {
4511   on_recv_data(conn);  // Can call us recursively if pipelining is used
4512   } else {
4513   conn->ns_conn->flags |= conn->ns_conn->send_iobuf.len == 0 ?
4514      NSF_CLOSE_IMMEDIATELY : NSF_FINISHED_SENDING_DATA;
4515   }
4649  // Do not memset() the whole structure, as some of the fields
4650  // (IP addresses & ports, server_param) must survive. Nullify the rest.
4651  c->request_method = c->uri = c->http_version = c->query_string = NULL;
4652  c->num_headers = c->status_code = c->is_websocket = c->content_len = 0;
4653  c->connection_param = c->callback_param = NULL;
4654
4655  if (keep_alive) {
4656    on_recv_data(conn);  // Can call us recursively if pipelining is used
4657  } else {
4658    conn->ns_conn->flags |= conn->ns_conn->send_iobuf.len == 0 ?
4659      NSF_CLOSE_IMMEDIATELY : NSF_FINISHED_SENDING_DATA;
4660  }
45164661}
45174662
45184663static void transfer_file_data(struct connection *conn) {
4519   char buf[IOBUF_SIZE];
4520   int n;
4664  char buf[IOBUF_SIZE];
4665  int n;
45214666
4522   // If output buffer is too big, don't send anything. Wait until
4523   // mongoose drains already buffered data to the client.
4524   if (conn->ns_conn->send_iobuf.len > sizeof(buf) * 2) return;
4667  // If output buffer is too big, don't send anything. Wait until
4668  // mongoose drains already buffered data to the client.
4669  if (conn->ns_conn->send_iobuf.len > sizeof(buf) * 2) return;
45254670
4526   // Do not send anyt
4527   n = read(conn->endpoint.fd, buf, conn->cl < (int64_t) sizeof(buf) ?
4528         (int) conn->cl : (int) sizeof(buf));
4671  // Do not send anyt
4672  n = read(conn->endpoint.fd, buf, conn->cl < (int64_t) sizeof(buf) ?
4673           (int) conn->cl : (int) sizeof(buf));
45294674
4530   if (n <= 0) {
4531   close_local_endpoint(conn);
4532   } else if (n > 0) {
4533   conn->cl -= n;
4534   ns_send(conn->ns_conn, buf, n);
4535   if (conn->cl <= 0) {
4536      close_local_endpoint(conn);
4537   }
4538   }
4675  if (n <= 0) {
4676    close_local_endpoint(conn);
4677  } else if (n > 0) {
4678    conn->cl -= n;
4679    ns_send(conn->ns_conn, buf, n);
4680    if (conn->cl <= 0) {
4681      close_local_endpoint(conn);
4682    }
4683  }
45394684}
45404685
45414686int mg_poll_server(struct mg_server *server, int milliseconds) {
4542   return ns_server_poll(&server->ns_server, milliseconds);
4687  return ns_server_poll(&server->ns_server, milliseconds);
45434688}
45444689
45454690void mg_destroy_server(struct mg_server **server) {
4546   if (server != NULL && *server != NULL) {
4547   struct mg_server *s = *server;
4548   int i;
4691  if (server != NULL && *server != NULL) {
4692    struct mg_server *s = *server;
4693    int i;
45494694
4550   ns_server_free(&s->ns_server);
4551   for (i = 0; i < (int) ARRAY_SIZE(s->config_options); i++) {
4552      free(s->config_options[i]);  // It is OK to free(NULL)
4553   }
4554   free(s);
4555   *server = NULL;
4556   }
4695    ns_server_free(&s->ns_server);
4696    for (i = 0; i < (int) ARRAY_SIZE(s->config_options); i++) {
4697      free(s->config_options[i]);  // It is OK to free(NULL)
4698    }
4699    free(s);
4700    *server = NULL;
4701  }
45574702}
45584703
45594704struct mg_iterator {
4560   mg_handler_t cb;
4561   void *param;
4705  mg_handler_t cb;
4706  void *param;
45624707};
45634708
45644709static void iter(struct ns_connection *nsconn, enum ns_event ev, void *param) {
4565   if (ev == NS_POLL) {
4566   struct mg_iterator *it = (struct mg_iterator *) param;
4567   struct connection *c = (struct connection *) nsconn->connection_data;
4568   if (c != NULL) c->mg_conn.callback_param = it->param;
4569   it->cb(&c->mg_conn, MG_POLL);
4570   }
4710  if (ev == NS_POLL) {
4711    struct mg_iterator *it = (struct mg_iterator *) param;
4712    struct connection *c = (struct connection *) nsconn->connection_data;
4713    if (c != NULL) c->mg_conn.callback_param = it->param;
4714    it->cb(&c->mg_conn, MG_POLL);
4715  }
45714716}
45724717
45734718struct mg_connection *mg_next(struct mg_server *s, struct mg_connection *c) {
4574   struct connection *conn = MG_CONN_2_CONN(c);
4575   struct ns_connection *nc = ns_next(&s->ns_server,
4576                              c == NULL ? NULL : conn->ns_conn);
4719  struct connection *conn = MG_CONN_2_CONN(c);
4720  struct ns_connection *nc = ns_next(&s->ns_server,
4721                                     c == NULL ? NULL : conn->ns_conn);
45774722
4578   return nc == NULL ? NULL :
4579   & ((struct connection *) nc->connection_data)->mg_conn;
4723  return nc == NULL ? NULL :
4724    & ((struct connection *) nc->connection_data)->mg_conn;
45804725}
45814726
45824727// Apply function to all active connections.
45834728void mg_iterate_over_connections(struct mg_server *server, mg_handler_t cb,
4584   void *param) {
4585   struct mg_iterator it = { cb, param };
4586   ns_iterate(&server->ns_server, iter, &it);
4729  void *param) {
4730  struct mg_iterator it = { cb, param };
4731  ns_iterate(&server->ns_server, iter, &it);
45874732}
45884733
45894734static int get_var(const char *data, size_t data_len, const char *name,
4590               char *dst, size_t dst_len) {
4591   const char *p, *e, *s;
4592   size_t name_len;
4593   int len;
4735                   char *dst, size_t dst_len) {
4736  const char *p, *e, *s;
4737  size_t name_len;
4738  int len;
45944739
4595   if (dst == NULL || dst_len == 0) {
4596   len = -2;
4597   } else if (data == NULL || name == NULL || data_len == 0) {
4598   len = -1;
4599   dst[0] = '\0';
4600   } else {
4601   name_len = strlen(name);
4602   e = data + data_len;
4603   len = -1;
4604   dst[0] = '\0';
4740  if (dst == NULL || dst_len == 0) {
4741    len = -2;
4742  } else if (data == NULL || name == NULL || data_len == 0) {
4743    len = -1;
4744    dst[0] = '\0';
4745  } else {
4746    name_len = strlen(name);
4747    e = data + data_len;
4748    len = -1;
4749    dst[0] = '\0';
46054750
4606   // data is "var1=val1&var2=val2...". Find variable first
4607   for (p = data; p + name_len < e; p++) {
4608      if ((p == data || p[-1] == '&') && p[name_len] == '=' &&
4609         !mg_strncasecmp(name, p, name_len)) {
4610      // Point p to variable value
4611      p += name_len + 1;
4751    // data is "var1=val1&var2=val2...". Find variable first
4752    for (p = data; p + name_len < e; p++) {
4753      if ((p == data || p[-1] == '&') && p[name_len] == '=' &&
4754          !mg_strncasecmp(name, p, name_len)) {
46124755
4613      // Point s to the end of the value
4614      s = (const char *) memchr(p, '&', (size_t)(e - p));
4615      if (s == NULL) {
4616         s = e;
4617      }
4618      assert(s >= p);
4756        // Point p to variable value
4757        p += name_len + 1;
46194758
4620      // Decode variable into destination buffer
4621      len = mg_url_decode(p, (size_t)(s - p), dst, dst_len, 1);
4759        // Point s to the end of the value
4760        s = (const char *) memchr(p, '&', (size_t)(e - p));
4761        if (s == NULL) {
4762          s = e;
4763        }
4764        assert(s >= p);
46224765
4623      // Redirect error code from -1 to -2 (destination buffer too small).
4624      if (len == -1) {
4625         len = -2;
4626      }
4627      break;
4628      }
4629   }
4630   }
4766        // Decode variable into destination buffer
4767        len = mg_url_decode(p, (size_t)(s - p), dst, dst_len, 1);
46314768
4632   return len;
4769        // Redirect error code from -1 to -2 (destination buffer too small).
4770        if (len == -1) {
4771          len = -2;
4772        }
4773        break;
4774      }
4775    }
4776  }
4777
4778  return len;
46334779}
46344780
46354781int mg_get_var(const struct mg_connection *conn, const char *name,
4636            char *dst, size_t dst_len) {
4637   int len = get_var(conn->query_string, conn->query_string == NULL ? 0 :
4638               strlen(conn->query_string), name, dst, dst_len);
4639   if (len < 0) {
4640   len = get_var(conn->content, conn->content_len, name, dst, dst_len);
4641   }
4642   return len;
4782               char *dst, size_t dst_len) {
4783  int len = get_var(conn->query_string, conn->query_string == NULL ? 0 :
4784                    strlen(conn->query_string), name, dst, dst_len);
4785  if (len < 0) {
4786    len = get_var(conn->content, conn->content_len, name, dst, dst_len);
4787  }
4788  return len;
46434789}
46444790
46454791static int get_line_len(const char *buf, int buf_len) {
4646   int len = 0;
4647   while (len < buf_len && buf[len] != '\n') len++;
4648   return buf[len] == '\n' ? len + 1: -1;
4792  int len = 0;
4793  while (len < buf_len && buf[len] != '\n') len++;
4794  return buf[len] == '\n' ? len + 1: -1;
46494795}
46504796
46514797int mg_parse_multipart(const char *buf, int buf_len,
4652                  char *var_name, int var_name_len,
4653                  char *file_name, int file_name_len,
4654                  const char **data, int *data_len) {
4655   static const char cd[] = "Content-Disposition: ";
4656   //struct mg_connection c;
4657   int hl, bl, n, ll, pos, cdl = sizeof(cd) - 1;
4658   //char *p;
4798                       char *var_name, int var_name_len,
4799                       char *file_name, int file_name_len,
4800                       const char **data, int *data_len) {
4801  static const char cd[] = "Content-Disposition: ";
4802  //struct mg_connection c;
4803  int hl, bl, n, ll, pos, cdl = sizeof(cd) - 1;
4804  //char *p;
46594805
4660   if (buf == NULL || buf_len <= 0) return 0;
4661   if ((hl = get_request_len(buf, buf_len)) <= 0) return 0;
4662   if (buf[0] != '-' || buf[1] != '-' || buf[2] == '\n') return 0;
4806  if (buf == NULL || buf_len <= 0) return 0;
4807  if ((hl = get_request_len(buf, buf_len)) <= 0) return 0;
4808  if (buf[0] != '-' || buf[1] != '-' || buf[2] == '\n') return 0;
46634809
4664   // Get boundary length
4665   bl = get_line_len(buf, buf_len);
4810  // Get boundary length
4811  bl = get_line_len(buf, buf_len);
46664812
4667   // Loop through headers, fetch variable name and file name
4668   var_name[0] = file_name[0] = '\0';
4669   for (n = bl; (ll = get_line_len(buf + n, hl - n)) > 0; n += ll) {
4670   if (mg_strncasecmp(cd, buf + n, cdl) == 0) {
4671      parse_header(buf + n + cdl, ll - (cdl + 2), "name",
4672               var_name, var_name_len);
4673      parse_header(buf + n + cdl, ll - (cdl + 2), "filename",
4674               file_name, file_name_len);
4675   }
4676   }
4813  // Loop through headers, fetch variable name and file name
4814  var_name[0] = file_name[0] = '\0';
4815  for (n = bl; (ll = get_line_len(buf + n, hl - n)) > 0; n += ll) {
4816    if (mg_strncasecmp(cd, buf + n, cdl) == 0) {
4817      parse_header(buf + n + cdl, ll - (cdl + 2), "name",
4818                   var_name, var_name_len);
4819      parse_header(buf + n + cdl, ll - (cdl + 2), "filename",
4820                   file_name, file_name_len);
4821    }
4822  }
46774823
4678   // Scan body, search for terminating boundary
4679   for (pos = hl; pos + (bl - 2) < buf_len; pos++) {
4680   if (buf[pos] == '-' && !memcmp(buf, &buf[pos], bl - 2)) {
4681      if (data_len != NULL) *data_len = (pos - 2) - hl;
4682      if (data != NULL) *data = buf + hl;
4683      return pos;
4684   }
4685   }
4824  // Scan body, search for terminating boundary
4825  for (pos = hl; pos + (bl - 2) < buf_len; pos++) {
4826    if (buf[pos] == '-' && !memcmp(buf, &buf[pos], bl - 2)) {
4827      if (data_len != NULL) *data_len = (pos - 2) - hl;
4828      if (data != NULL) *data = buf + hl;
4829      return pos;
4830    }
4831  }
46864832
4687   return 0;
4833  return 0;
46884834}
46894835
46904836const char **mg_get_valid_option_names(void) {
4691   return static_config_options;
4837  return static_config_options;
46924838}
46934839
46944840static int get_option_index(const char *name) {
4695   int i;
4841  int i;
46964842
4697   for (i = 0; static_config_options[i * 2] != NULL; i++) {
4698   if (strcmp(static_config_options[i * 2], name) == 0) {
4699      return i;
4700   }
4701   }
4702   return -1;
4843  for (i = 0; static_config_options[i * 2] != NULL; i++) {
4844    if (strcmp(static_config_options[i * 2], name) == 0) {
4845      return i;
4846    }
4847  }
4848  return -1;
47034849}
47044850
47054851static void set_default_option_values(char **opts) {
4706   const char *value, **all_opts = mg_get_valid_option_names();
4707   int i;
4852  const char *value, **all_opts = mg_get_valid_option_names();
4853  int i;
47084854
4709   for (i = 0; all_opts[i * 2] != NULL; i++) {
4710   value = all_opts[i * 2 + 1];
4711   if (opts[i] == NULL && value != NULL) {
4712      opts[i] = mg_strdup(value);
4713   }
4714   }
4855  for (i = 0; all_opts[i * 2] != NULL; i++) {
4856    value = all_opts[i * 2 + 1];
4857    if (opts[i] == NULL && value != NULL) {
4858      opts[i] = mg_strdup(value);
4859    }
4860  }
47154861}
47164862
47174863const char *mg_set_option(struct mg_server *server, const char *name,
4718                     const char *value) {
4719   int ind = get_option_index(name);
4720   const char *error_msg = NULL;
4721   char **v = NULL;
4864                          const char *value) {
4865  int ind = get_option_index(name);
4866  const char *error_msg = NULL;
4867  char **v = NULL;
47224868
4723   if (ind < 0) return  "No such option";
4724   v = &server->config_options[ind];
4869  if (ind < 0) return  "No such option";
4870  v = &server->config_options[ind];
47254871
4726   // Return success immediately if setting to the same value
4727   if ((*v == NULL && value == NULL) ||
4728      (value != NULL && *v != NULL && !strcmp(value, *v))) {
4729   return NULL;
4730   }
4872  // Return success immediately if setting to the same value
4873  if ((*v == NULL && value == NULL) ||
4874      (value != NULL && *v != NULL && !strcmp(value, *v))) {
4875    return NULL;
4876  }
47314877
4732   if (*v != NULL) {
4733   free(*v);
4734   *v = NULL;
4735   }
4878  if (*v != NULL) {
4879    free(*v);
4880    *v = NULL;
4881  }
47364882
4737   if (value == NULL || value[0] == '\0') return NULL;
4883  if (value == NULL || value[0] == '\0') return NULL;
47384884
4739   *v = mg_strdup(value);
4740   DBG(("%s [%s]", name, *v));
4885  *v = mg_strdup(value);
4886  DBG(("%s [%s]", name, *v));
47414887
4742   if (ind == LISTENING_PORT) {
4743   int port = ns_bind(&server->ns_server, value);
4744   if (port < 0) {
4745      error_msg = "Cannot bind to port";
4746   } else {
4747      char buf[100];
4748      ns_sock_to_str(server->ns_server.listening_sock, buf, sizeof(buf), 2);
4749      free(*v);
4750      *v = mg_strdup(buf);
4751   }
4888  if (ind == LISTENING_PORT) {
4889    int port = ns_bind(&server->ns_server, value);
4890    if (port < 0) {
4891      error_msg = "Cannot bind to port";
4892    } else {
4893      char buf[100];
4894      ns_sock_to_str(server->ns_server.listening_sock, buf, sizeof(buf), 2);
4895      free(*v);
4896      *v = mg_strdup(buf);
4897    }
4898#ifndef MONGOOSE_NO_FILESYSTEM
4899  } else if (ind == HEXDUMP_FILE) {
4900    server->ns_server.hexdump_file = *v;
4901#endif
47524902#ifndef _WIN32
4753   } else if (ind == RUN_AS_USER) {
4754   struct passwd *pw;
4755   if ((pw = getpwnam(value)) == NULL) {
4756      error_msg = "Unknown user";
4757   } else if (setgid(pw->pw_gid) != 0) {
4758      error_msg = "setgid() failed";
4759   } else if (setuid(pw->pw_uid) != 0) {
4760      error_msg = "setuid() failed";
4761   }
4903  } else if (ind == RUN_AS_USER) {
4904    struct passwd *pw;
4905    if ((pw = getpwnam(value)) == NULL) {
4906      error_msg = "Unknown user";
4907    } else if (setgid(pw->pw_gid) != 0) {
4908      error_msg = "setgid() failed";
4909    } else if (setuid(pw->pw_uid) != 0) {
4910      error_msg = "setuid() failed";
4911    }
47624912#endif
47634913#ifdef NS_ENABLE_SSL
4764   } else if (ind == SSL_CERTIFICATE) {
4765   int res = ns_set_ssl_cert(&server->ns_server, value);
4766   if (res == -2) {
4767      error_msg = "Cannot load PEM";
4768   } else if (res == -3) {
4769      error_msg = "SSL not enabled";
4770   } else if (res == -1) {
4771      error_msg = "SSL_CTX_new() failed";
4772   }
4773   } else if (ind == SSL_CA_CERTIFICATE) {
4774   if (ns_set_ssl_ca_cert(&server->ns_server, value) != 0) {
4775      error_msg = "Error setting CA cert";
4776      }
4914  } else if (ind == SSL_CERTIFICATE) {
4915    int res = ns_set_ssl_cert(&server->ns_server, value);
4916    if (res == -2) {
4917      error_msg = "Cannot load PEM";
4918    } else if (res == -3) {
4919      error_msg = "SSL not enabled";
4920    } else if (res == -1) {
4921      error_msg = "SSL_CTX_new() failed";
4922    }
4923  } else if (ind == SSL_CA_CERTIFICATE) {
4924    if (ns_set_ssl_ca_cert(&server->ns_server, value) != 0) {
4925       error_msg = "Error setting CA cert";
4926     }
47774927#endif
4778   }
4928  }
47794929
4780   return error_msg;
4930  return error_msg;
47814931}
47824932
47834933static void set_ips(struct ns_connection *nc, int is_rem) {
4784   struct connection *conn = (struct connection *) nc->connection_data;
4785   struct mg_connection *c = &conn->mg_conn;
4786   char buf[100];
4934  struct connection *conn = (struct connection *) nc->connection_data;
4935  struct mg_connection *c = &conn->mg_conn;
4936  char buf[100];
47874937
4788   ns_sock_to_str(nc->sock, buf, sizeof(buf), is_rem ? 7 : 3);
4789   sscanf(buf, "%47[^:]:%hu",
4790         is_rem ? c->remote_ip : c->local_ip,
4791         is_rem ? &c->remote_port : &c->local_port);
4792   //DBG(("%p %s %s", conn, is_rem ? "rem" : "loc", buf));
4938  ns_sock_to_str(nc->sock, buf, sizeof(buf), is_rem ? 7 : 3);
4939  sscanf(buf, "%47[^:]:%hu",
4940         is_rem ? c->remote_ip : c->local_ip,
4941         is_rem ? &c->remote_port : &c->local_port);
4942  //DBG(("%p %s %s", conn, is_rem ? "rem" : "loc", buf));
47934943}
47944944
47954945static void on_accept(struct ns_connection *nc, union socket_address *sa) {
4796   struct mg_server *server = (struct mg_server *) nc->server;
4797   struct connection *conn;
4946  struct mg_server *server = (struct mg_server *) nc->server;
4947  struct connection *conn;
47984948
4799   if (!check_acl(server->config_options[ACCESS_CONTROL_LIST],
4800               ntohl(* (uint32_t *) &sa->sin.sin_addr)) ||
4801      (conn = (struct connection *) calloc(1, sizeof(*conn))) == NULL) {
4802   nc->flags |= NSF_CLOSE_IMMEDIATELY;
4803   } else {
4804   // Circularly link two connection structures
4805   nc->connection_data = conn;
4806   conn->ns_conn = nc;
4949  if (!check_acl(server->config_options[ACCESS_CONTROL_LIST],
4950                 ntohl(* (uint32_t *) &sa->sin.sin_addr)) ||
4951      (conn = (struct connection *) calloc(1, sizeof(*conn))) == NULL) {
4952    nc->flags |= NSF_CLOSE_IMMEDIATELY;
4953  } else {
4954    // Circularly link two connection structures
4955    nc->connection_data = conn;
4956    conn->ns_conn = nc;
48074957
4808   // Initialize the rest of connection attributes
4809   conn->server = server;
4810   conn->mg_conn.server_param = nc->server->server_data;
4811   set_ips(nc, 1);
4812   set_ips(nc, 0);
4813   }
4958    // Initialize the rest of connection attributes
4959    conn->server = server;
4960    conn->mg_conn.server_param = nc->server->server_data;
4961    set_ips(nc, 1);
4962    set_ips(nc, 0);
4963  }
48144964}
48154965
4816#ifndef MONGOOSE_NO_FILESYSTEM
4817static void hexdump(struct ns_connection *nc, const char *path,
4818               int num_bytes, int is_sent) {
4819   const struct iobuf *io = is_sent ? &nc->send_iobuf : &nc->recv_iobuf;
4820   FILE *fp;
4821   char *buf, src[60], dst[60];
4822   int buf_size = num_bytes * 5 + 100;
4823
4824   if (path != NULL && (fp = fopen(path, "a")) != NULL) {
4825   ns_sock_to_str(nc->sock, src, sizeof(src), 3);
4826   ns_sock_to_str(nc->sock, dst, sizeof(dst), 7);
4827   fprintf(fp, "%lu %p %s %s %s %d\n", (unsigned long) time(NULL),
4828         nc->connection_data, src,
4829         is_sent == 0 ? "<-" : is_sent == 1 ? "->" :
4830         is_sent == 2 ? "<A" : "C>", dst, num_bytes);
4831   if (num_bytes > 0 && (buf = (char *) malloc(buf_size)) != NULL) {
4832      ns_hexdump(io->buf + (is_sent ? 0 : io->len) - (is_sent ? 0 : num_bytes),
4833               num_bytes, buf, buf_size);
4834      fprintf(fp, "%s", buf);
4835      free(buf);
4836   }
4837   fclose(fp);
4838   }
4839}
4840#endif
4841
48424966static void mg_ev_handler(struct ns_connection *nc, enum ns_event ev, void *p) {
4843   struct connection *conn = (struct connection *) nc->connection_data;
4844#ifndef MONGOOSE_NO_FILESYSTEM
4845   struct mg_server *server = (struct mg_server *) nc->server;
4846#endif
4967  struct connection *conn = (struct connection *) nc->connection_data;
48474968
4848   // Send NS event to the handler. Note that call_user won't send an event
4849   // if conn == NULL. Therefore, repeat this for NS_ACCEPT event as well.
4969  // Send NS event to the handler. Note that call_user won't send an event
4970  // if conn == NULL. Therefore, repeat this for NS_ACCEPT event as well.
48504971#ifdef MONGOOSE_SEND_NS_EVENTS
4851   {
4852   struct connection *conn = (struct connection *) nc->connection_data;
4853   if (conn != NULL) conn->mg_conn.callback_param = p;
4854   call_user(conn, (enum mg_event) ev);
4855   }
4972  {
4973    struct connection *conn = (struct connection *) nc->connection_data;
4974    void *param[2] = { nc, p };
4975    if (conn != NULL) conn->mg_conn.callback_param = param;
4976    call_user(conn, (enum mg_event) ev);
4977  }
48564978#endif
48574979
4858   switch (ev) {
4859   case NS_ACCEPT:
4860      on_accept(nc, (union socket_address *) p);
4861#ifndef MONGOOSE_NO_FILESYSTEM
4862      hexdump(nc, server->config_options[HEXDUMP_FILE], 0, 2);
4863#endif
4980  switch (ev) {
4981    case NS_ACCEPT:
4982      on_accept(nc, (union socket_address *) p);
48644983#ifdef MONGOOSE_SEND_NS_EVENTS
4865      {
4866      struct connection *conn = (struct connection *) nc->connection_data;
4867      if (conn != NULL) conn->mg_conn.callback_param = p;
4868      call_user(conn, (enum mg_event) ev);
4869      }
4984      {
4985        struct connection *conn = (struct connection *) nc->connection_data;
4986        void *param[2] = { nc, p };
4987        if (conn != NULL) conn->mg_conn.callback_param = param;
4988        call_user(conn, (enum mg_event) ev);
4989      }
48704990#endif
4871      break;
4991      break;
48724992
4873   case NS_CONNECT:
4874      if (nc->connection_data != NULL) {
4875      set_ips(nc, 1);
4876      set_ips(nc, 0);
4877      }
4878#ifndef MONGOOSE_NO_FILESYSTEM
4879      hexdump(nc, server->config_options[HEXDUMP_FILE], 0, 3);
4880#endif
4881      conn->mg_conn.status_code = * (int *) p;
4882      if (conn->mg_conn.status_code != 0 ||
4883         (!(nc->flags & MG_PROXY_CONN) &&
4884         call_user(conn, MG_CONNECT) == MG_FALSE)) {
4885      nc->flags |= NSF_CLOSE_IMMEDIATELY;
4886      }
4887      break;
4993    case NS_CONNECT:
4994      if (nc->connection_data != NULL) {
4995        set_ips(nc, 1);
4996        set_ips(nc, 0);
4997      }
4998      conn->mg_conn.status_code = * (int *) p;
4999      if (conn->mg_conn.status_code != 0 ||
5000          (!(nc->flags & MG_PROXY_CONN) &&
5001           call_user(conn, MG_CONNECT) == MG_FALSE)) {
5002        nc->flags |= NSF_CLOSE_IMMEDIATELY;
5003      }
5004      break;
48885005
4889   case NS_RECV:
4890#ifndef MONGOOSE_NO_FILESYSTEM
4891      hexdump(nc, server->config_options[HEXDUMP_FILE], * (int *) p, 0);
4892#endif
4893      if (nc->flags & NSF_ACCEPTED) {
4894      on_recv_data(conn);
5006    case NS_RECV:
5007      if (conn != NULL) {
5008        conn->num_bytes_recv += * (int *) p;
5009      }
5010      if (nc->flags & NSF_ACCEPTED) {
5011        on_recv_data(conn);
48955012#ifndef MONGOOSE_NO_CGI
4896      } else if (nc->flags & MG_CGI_CONN) {
4897      on_cgi_data(nc);
5013      } else if (nc->flags & MG_CGI_CONN) {
5014        on_cgi_data(nc);
48985015#endif
4899      } else if (nc->flags & MG_PROXY_CONN) {
4900      if (conn != NULL) {
4901         ns_forward(nc, conn->ns_conn);
4902      }
4903      } else {
4904      process_response(conn);
4905      }
4906      break;
5016      } else if (nc->flags & MG_PROXY_CONN) {
5017        if (conn != NULL) {
5018          ns_forward(nc, conn->ns_conn);
5019        }
5020      } else {
5021        process_response(conn);
5022      }
5023      break;
49075024
4908   case NS_SEND:
4909#ifndef MONGOOSE_NO_FILESYSTEM
4910      hexdump(nc, server->config_options[HEXDUMP_FILE], * (int *) p, 1);
4911#endif
4912      break;
5025    case NS_SEND:
5026      break;
49135027
4914   case NS_CLOSE:
4915      nc->connection_data = NULL;
4916      if (nc->flags & (MG_CGI_CONN | MG_PROXY_CONN)) {
4917      DBG(("%p %p closing cgi/proxy conn", conn, nc));
4918      if (conn && conn->ns_conn) {
4919         conn->ns_conn->flags &= ~NSF_BUFFER_BUT_DONT_SEND;
4920         conn->ns_conn->flags |= conn->ns_conn->send_iobuf.len > 0 ?
4921         NSF_FINISHED_SENDING_DATA : NSF_CLOSE_IMMEDIATELY;
4922         conn->endpoint.nc = NULL;
4923      }
4924      } else if (conn != NULL) {
4925      DBG(("%p %p %d closing", conn, nc, conn->endpoint_type));
5028    case NS_CLOSE:
5029      nc->connection_data = NULL;
5030      if (nc->flags & (MG_CGI_CONN | MG_PROXY_CONN)) {
5031        DBG(("%p %p closing cgi/proxy conn", conn, nc));
5032        if (conn && conn->ns_conn) {
5033          conn->ns_conn->flags &= ~NSF_BUFFER_BUT_DONT_SEND;
5034          conn->ns_conn->flags |= conn->ns_conn->send_iobuf.len > 0 ?
5035            NSF_FINISHED_SENDING_DATA : NSF_CLOSE_IMMEDIATELY;
5036          conn->endpoint.nc = NULL;
5037        }
5038      } else if (conn != NULL) {
5039        DBG(("%p %p %d closing", conn, nc, conn->endpoint_type));
49265040
4927      if (conn->endpoint_type == EP_CLIENT && nc->recv_iobuf.len > 0) {
4928         call_http_client_handler(conn);
4929      }
5041        if (conn->endpoint_type == EP_CLIENT && nc->recv_iobuf.len > 0) {
5042          call_http_client_handler(conn);
5043        }
49305044
4931      call_user(conn, MG_CLOSE);
4932      close_local_endpoint(conn);
4933      conn->ns_conn = NULL;
4934      free(conn);
4935      }
4936      break;
5045        call_user(conn, MG_CLOSE);
5046        close_local_endpoint(conn);
5047        conn->ns_conn = NULL;
5048        free(conn);
5049      }
5050      break;
49375051
4938   case NS_POLL:
4939      if (call_user(conn, MG_POLL) == MG_TRUE) {
4940      if (conn->ns_conn->flags & MG_HEADERS_SENT) {
4941         write_terminating_chunk(conn);
4942      }
4943      close_local_endpoint(conn);
4944      }
5052    case NS_POLL:
5053      if (conn != NULL) {
5054        if (call_user(conn, MG_POLL) == MG_TRUE) {
5055          if (conn->ns_conn->flags & MG_HEADERS_SENT) {
5056            write_terminating_chunk(conn);
5057          }
5058          close_local_endpoint(conn);
5059        }
49455060
4946      if (conn != NULL && conn->endpoint_type == EP_FILE) {
4947      transfer_file_data(conn);
4948      }
5061        if (conn->endpoint_type == EP_FILE) {
5062          transfer_file_data(conn);
5063        }
5064      }
49495065
4950      // Expire idle connections
4951      {
4952      time_t current_time = * (time_t *) p;
5066      // Expire idle connections
5067      {
5068        time_t current_time = * (time_t *) p;
49535069
4954      if (conn != NULL && conn->mg_conn.is_websocket) {
4955         ping_idle_websocket_connection(conn, current_time);
4956      }
5070        if (conn != NULL && conn->mg_conn.is_websocket) {
5071          ping_idle_websocket_connection(conn, current_time);
5072        }
49575073
4958      if (nc->last_io_time + MONGOOSE_IDLE_TIMEOUT_SECONDS < current_time) {
4959         mg_ev_handler(nc, NS_CLOSE, NULL);
4960         nc->flags |= NSF_CLOSE_IMMEDIATELY;
4961      }
4962      }
4963      break;
5074        if (nc->last_io_time + MONGOOSE_IDLE_TIMEOUT_SECONDS < current_time) {
5075          mg_ev_handler(nc, NS_CLOSE, NULL);
5076          nc->flags |= NSF_CLOSE_IMMEDIATELY;
5077        }
5078      }
5079      break;
49645080
4965   default:
4966      break;
4967   }
5081    default:
5082      break;
5083  }
49685084}
49695085
49705086static void iter2(struct ns_connection *nc, enum ns_event ev, void *param) {
4971   mg_handler_t func = NULL;
4972   struct connection *conn = (struct connection *) nc->connection_data;
4973   const char *msg = (const char *) param;
4974   int n;
4975   (void) ev;
5087  mg_handler_t func = NULL;
5088  struct connection *conn = (struct connection *) nc->connection_data;
5089  const char *msg = (const char *) param;
5090  int n;
5091  (void) ev;
49765092
4977   //DBG(("%p [%s]", conn, msg));
4978   if (sscanf(msg, "%p %n", &func, &n) && func != NULL) {
4979   conn->mg_conn.callback_param = (void *) (msg + n);
4980   func(&conn->mg_conn, MG_POLL);
4981   }
5093  //DBG(("%p [%s]", conn, msg));
5094  if (sscanf(msg, "%p %n", &func, &n) && func != NULL) {
5095    conn->mg_conn.callback_param = (void *) (msg + n);
5096    func(&conn->mg_conn, MG_POLL);
5097  }
49825098}
49835099
49845100void mg_wakeup_server_ex(struct mg_server *server, mg_handler_t cb,
4985                     const char *fmt, ...) {
4986   va_list ap;
4987   char buf[8 * 1024];
4988   int len;
5101                         const char *fmt, ...) {
5102  va_list ap;
5103  char buf[8 * 1024];
5104  int len;
49895105
4990   // Encode callback (cb) into a buffer
4991   len = snprintf(buf, sizeof(buf), "%p ", cb);
4992   va_start(ap, fmt);
4993   len += vsnprintf(buf + len, sizeof(buf) - len, fmt, ap);
4994   va_end(ap);
5106  // Encode callback (cb) into a buffer
5107  len = snprintf(buf, sizeof(buf), "%p ", cb);
5108  va_start(ap, fmt);
5109  len += vsnprintf(buf + len, sizeof(buf) - len, fmt, ap);
5110  va_end(ap);
49955111
4996   // "len + 1" is to include terminating \0 in the message
4997   ns_server_wakeup_ex(&server->ns_server, iter2, buf, len + 1);
5112  // "len + 1" is to include terminating \0 in the message
5113  ns_server_wakeup_ex(&server->ns_server, iter2, buf, len + 1);
49985114}
49995115
50005116void mg_wakeup_server(struct mg_server *server) {
5001   ns_server_wakeup_ex(&server->ns_server, NULL, (void *) "", 0);
5117  ns_server_wakeup_ex(&server->ns_server, NULL, (void *) "", 0);
50025118}
50035119
50045120void mg_set_listening_socket(struct mg_server *server, int sock) {
5005   if (server->ns_server.listening_sock != INVALID_SOCKET) {
5006   closesocket(server->ns_server.listening_sock);
5007   }
5008   server->ns_server.listening_sock = (sock_t) sock;
5121  if (server->ns_server.listening_sock != INVALID_SOCKET) {
5122    closesocket(server->ns_server.listening_sock);
5123  }
5124  server->ns_server.listening_sock = (sock_t) sock;
50095125}
50105126
50115127int mg_get_listening_socket(struct mg_server *server) {
5012   return server->ns_server.listening_sock;
5128  return server->ns_server.listening_sock;
50135129}
50145130
50155131const char *mg_get_option(const struct mg_server *server, const char *name) {
5016   const char **opts = (const char **) server->config_options;
5017   int i = get_option_index(name);
5018   return i == -1 ? NULL : opts[i] == NULL ? "" : opts[i];
5132  const char **opts = (const char **) server->config_options;
5133  int i = get_option_index(name);
5134  return i == -1 ? NULL : opts[i] == NULL ? "" : opts[i];
50195135}
50205136
50215137struct mg_server *mg_create_server(void *server_data, mg_handler_t handler) {
5022   struct mg_server *server = (struct mg_server *) calloc(1, sizeof(*server));
5023   ns_server_init(&server->ns_server, server_data, mg_ev_handler);
5024   set_default_option_values(server->config_options);
5025   server->event_handler = handler;
5026   return server;
5138  struct mg_server *server = (struct mg_server *) calloc(1, sizeof(*server));
5139  ns_server_init(&server->ns_server, server_data, mg_ev_handler);
5140  set_default_option_values(server->config_options);
5141  server->event_handler = handler;
5142  return server;
50275143}

Previous 199869 Revisions Next


© 1997-2024 The MAME Team