main.c 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517
  1. // Copyright (c) 2004-2011 Sergey Lyubka
  2. //
  3. // Permission is hereby granted, free of charge, to any person obtaining a copy
  4. // of this software and associated documentation files (the "Software"), to deal
  5. // in the Software without restriction, including without limitation the rights
  6. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  7. // copies of the Software, and to permit persons to whom the Software is
  8. // furnished to do so, subject to the following conditions:
  9. //
  10. // The above copyright notice and this permission notice shall be included in
  11. // all copies or substantial portions of the Software.
  12. //
  13. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  14. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  15. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  16. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  17. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  18. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  19. // THE SOFTWARE.
  20. #if defined(_WIN32)
  21. #define _CRT_SECURE_NO_WARNINGS // Disable deprecation warning in VS2005
  22. #else
  23. #define _XOPEN_SOURCE 600 // For PATH_MAX on linux
  24. #endif
  25. #include <sys/stat.h>
  26. #include <stdio.h>
  27. #include <stdlib.h>
  28. #include <signal.h>
  29. #include <string.h>
  30. #include <errno.h>
  31. #include <limits.h>
  32. #include <stddef.h>
  33. #include <stdarg.h>
  34. #include <ctype.h>
  35. #include "mongoose.h"
  36. #ifdef _WIN32
  37. #include <windows.h>
  38. #include <winsvc.h>
  39. #define PATH_MAX MAX_PATH
  40. #define S_ISDIR(x) ((x) & _S_IFDIR)
  41. #define DIRSEP '\\'
  42. #define snprintf _snprintf
  43. #define vsnprintf _vsnprintf
  44. #define sleep(x) Sleep((x) * 1000)
  45. #define WINCDECL __cdecl
  46. #else
  47. #include <sys/wait.h>
  48. #include <unistd.h>
  49. #define DIRSEP '/'
  50. #define WINCDECL
  51. #endif // _WIN32
  52. #define MAX_OPTIONS 40
  53. #define MAX_CONF_FILE_LINE_SIZE (8 * 1024)
  54. static int exit_flag;
  55. static char server_name[40]; // Set by init_server_name()
  56. static char config_file[PATH_MAX]; // Set by process_command_line_arguments()
  57. static struct mg_context *ctx; // Set by start_mongoose()
  58. #if !defined(CONFIG_FILE)
  59. #define CONFIG_FILE "mongoose.conf"
  60. #endif /* !CONFIG_FILE */
  61. static void WINCDECL signal_handler(int sig_num) {
  62. exit_flag = sig_num;
  63. }
  64. static void die(const char *fmt, ...) {
  65. va_list ap;
  66. char msg[200];
  67. va_start(ap, fmt);
  68. vsnprintf(msg, sizeof(msg), fmt, ap);
  69. va_end(ap);
  70. #if defined(_WIN32)
  71. MessageBox(NULL, msg, "Error", MB_OK);
  72. #else
  73. fprintf(stderr, "%s\n", msg);
  74. #endif
  75. exit(EXIT_FAILURE);
  76. }
  77. static void show_usage_and_exit(void) {
  78. const char **names;
  79. int i;
  80. fprintf(stderr, "Mongoose version %s (c) Sergey Lyubka, built %s\n",
  81. mg_version(), __DATE__);
  82. fprintf(stderr, "Usage:\n");
  83. fprintf(stderr, " mongoose -A <htpasswd_file> <realm> <user> <passwd>\n");
  84. fprintf(stderr, " mongoose <config_file>\n");
  85. fprintf(stderr, " mongoose [-option value ...]\n");
  86. fprintf(stderr, "\nOPTIONS:\n");
  87. names = mg_get_valid_option_names();
  88. for (i = 0; names[i] != NULL; i += 3) {
  89. fprintf(stderr, " -%s %s (default: \"%s\")\n",
  90. names[i], names[i + 1], names[i + 2] == NULL ? "" : names[i + 2]);
  91. }
  92. fprintf(stderr, "\nSee http://code.google.com/p/mongoose/wiki/MongooseManual"
  93. " for more details.\n");
  94. fprintf(stderr, "Example:\n mongoose -s cert.pem -p 80,443s -d no\n");
  95. exit(EXIT_FAILURE);
  96. }
  97. static void verify_document_root(const char *root) {
  98. const char *p, *path;
  99. char buf[PATH_MAX];
  100. struct stat st;
  101. path = root;
  102. if ((p = strchr(root, ',')) != NULL && (size_t) (p - root) < sizeof(buf)) {
  103. memcpy(buf, root, p - root);
  104. buf[p - root] = '\0';
  105. path = buf;
  106. }
  107. if (stat(path, &st) != 0 || !S_ISDIR(st.st_mode)) {
  108. die("Invalid root directory: [%s]: %s", root, strerror(errno));
  109. }
  110. }
  111. static char *sdup(const char *str) {
  112. char *p;
  113. if ((p = (char *) malloc(strlen(str) + 1)) != NULL) {
  114. strcpy(p, str);
  115. }
  116. return p;
  117. }
  118. static void set_option(char **options, const char *name, const char *value) {
  119. int i;
  120. if (!strcmp(name, "document_root") || !(strcmp(name, "r"))) {
  121. verify_document_root(value);
  122. }
  123. for (i = 0; i < MAX_OPTIONS - 3; i++) {
  124. if (options[i] == NULL) {
  125. options[i] = sdup(name);
  126. options[i + 1] = sdup(value);
  127. options[i + 2] = NULL;
  128. break;
  129. }
  130. }
  131. if (i == MAX_OPTIONS - 3) {
  132. die("%s", "Too many options specified");
  133. }
  134. }
  135. static void process_command_line_arguments(char *argv[], char **options) {
  136. char line[MAX_CONF_FILE_LINE_SIZE], opt[sizeof(line)], val[sizeof(line)], *p;
  137. FILE *fp = NULL;
  138. size_t i, cmd_line_opts_start = 1, line_no = 0;
  139. options[0] = NULL;
  140. // Should we use a config file ?
  141. if (argv[1] != NULL && argv[1][0] != '-') {
  142. snprintf(config_file, sizeof(config_file), "%s", argv[1]);
  143. cmd_line_opts_start = 2;
  144. } else if ((p = strrchr(argv[0], DIRSEP)) == NULL) {
  145. // No command line flags specified. Look where binary lives
  146. snprintf(config_file, sizeof(config_file), "%s", CONFIG_FILE);
  147. } else {
  148. snprintf(config_file, sizeof(config_file), "%.*s%c%s",
  149. (int) (p - argv[0]), argv[0], DIRSEP, CONFIG_FILE);
  150. }
  151. fp = fopen(config_file, "r");
  152. // If config file was set in command line and open failed, die
  153. if (cmd_line_opts_start == 2 && fp == NULL) {
  154. die("Cannot open config file %s: %s", config_file, strerror(errno));
  155. }
  156. // Load config file settings first
  157. if (fp != NULL) {
  158. fprintf(stderr, "Loading config file %s\n", config_file);
  159. // Loop over the lines in config file
  160. while (fgets(line, sizeof(line), fp) != NULL) {
  161. line_no++;
  162. // Ignore empty lines and comments
  163. for (i = 0; isspace(* (unsigned char *) &line[i]); ) i++;
  164. if (line[i] == '#' || line[i] == '\0')
  165. continue;
  166. if (sscanf(line, "%s %[^\r\n#]", opt, val) != 2) {
  167. die("%s: line %d is invalid", config_file, (int) line_no);
  168. }
  169. set_option(options, opt, val);
  170. }
  171. (void) fclose(fp);
  172. }
  173. // Handle command line flags. They override config file and default settings.
  174. for (i = cmd_line_opts_start; argv[i] != NULL; i += 2) {
  175. if (argv[i][0] != '-' || argv[i + 1] == NULL) {
  176. show_usage_and_exit();
  177. }
  178. set_option(options, &argv[i][1], argv[i + 1]);
  179. }
  180. }
  181. static void init_server_name(void) {
  182. snprintf(server_name, sizeof(server_name), "Mongoose web server v. %s",
  183. mg_version());
  184. }
  185. static void *mongoose_callback(enum mg_event ev, struct mg_connection *conn) {
  186. if (ev == MG_EVENT_LOG) {
  187. printf("%s\n", (const char *) mg_get_request_info(conn)->ev_data);
  188. }
  189. if (ev == MG_OPEN_FILE &&
  190. !memcmp(mg_get_request_info(conn)->ev_data, "./x", 3)) {
  191. mg_get_request_info(conn)->ev_data = (void *) (int) 5;
  192. return "hello";
  193. }
  194. // Returning NULL marks request as not handled, signalling mongoose to
  195. // proceed with handling it.
  196. return NULL;
  197. }
  198. static void start_mongoose(int argc, char *argv[]) {
  199. char *options[MAX_OPTIONS];
  200. int i;
  201. // Edit passwords file if -A option is specified
  202. if (argc > 1 && !strcmp(argv[1], "-A")) {
  203. if (argc != 6) {
  204. show_usage_and_exit();
  205. }
  206. exit(mg_modify_passwords_file(argv[2], argv[3], argv[4], argv[5]) ?
  207. EXIT_SUCCESS : EXIT_FAILURE);
  208. }
  209. // Show usage if -h or --help options are specified
  210. if (argc == 2 && (!strcmp(argv[1], "-h") || !strcmp(argv[1], "--help"))) {
  211. show_usage_and_exit();
  212. }
  213. /* Update config based on command line arguments */
  214. process_command_line_arguments(argv, options);
  215. /* Setup signal handler: quit on Ctrl-C */
  216. signal(SIGTERM, signal_handler);
  217. signal(SIGINT, signal_handler);
  218. /* Start Mongoose */
  219. ctx = mg_start(&mongoose_callback, NULL, (const char **) options);
  220. for (i = 0; options[i] != NULL; i++) {
  221. free(options[i]);
  222. }
  223. if (ctx == NULL) {
  224. die("%s", "Failed to start Mongoose.");
  225. }
  226. }
  227. #ifdef _WIN32
  228. static SERVICE_STATUS ss;
  229. static SERVICE_STATUS_HANDLE hStatus;
  230. static const char *service_magic_argument = "--";
  231. static void WINAPI ControlHandler(DWORD code) {
  232. if (code == SERVICE_CONTROL_STOP || code == SERVICE_CONTROL_SHUTDOWN) {
  233. ss.dwWin32ExitCode = 0;
  234. ss.dwCurrentState = SERVICE_STOPPED;
  235. }
  236. SetServiceStatus(hStatus, &ss);
  237. }
  238. static void WINAPI ServiceMain(void) {
  239. ss.dwServiceType = SERVICE_WIN32;
  240. ss.dwCurrentState = SERVICE_RUNNING;
  241. ss.dwControlsAccepted = SERVICE_ACCEPT_STOP | SERVICE_ACCEPT_SHUTDOWN;
  242. hStatus = RegisterServiceCtrlHandler(server_name, ControlHandler);
  243. SetServiceStatus(hStatus, &ss);
  244. while (ss.dwCurrentState == SERVICE_RUNNING) {
  245. Sleep(1000);
  246. }
  247. mg_stop(ctx);
  248. ss.dwCurrentState = SERVICE_STOPPED;
  249. ss.dwWin32ExitCode = (DWORD) -1;
  250. SetServiceStatus(hStatus, &ss);
  251. }
  252. #define ID_TRAYICON 100
  253. #define ID_QUIT 101
  254. #define ID_EDIT_CONFIG 102
  255. #define ID_SEPARATOR 103
  256. #define ID_INSTALL_SERVICE 104
  257. #define ID_REMOVE_SERVICE 105
  258. #define ID_ICON 200
  259. static NOTIFYICONDATA TrayIcon;
  260. static void edit_config_file(void) {
  261. const char **names, *value;
  262. FILE *fp;
  263. int i;
  264. char cmd[200];
  265. // Create config file if it is not present yet
  266. if ((fp = fopen(config_file, "r")) != NULL) {
  267. fclose(fp);
  268. } else if ((fp = fopen(config_file, "a+")) != NULL) {
  269. fprintf(fp,
  270. "# Mongoose web server configuration file.\n"
  271. "# Lines starting with '#' and empty lines are ignored.\n"
  272. "# For detailed description of every option, visit\n"
  273. "# http://code.google.com/p/mongoose/wiki/MongooseManual\n\n");
  274. names = mg_get_valid_option_names();
  275. for (i = 0; names[i] != NULL; i += 3) {
  276. value = mg_get_option(ctx, names[i]);
  277. fprintf(fp, "# %s %s\n", names[i + 1], *value ? value : "<value>");
  278. }
  279. fclose(fp);
  280. }
  281. snprintf(cmd, sizeof(cmd), "notepad.exe %s", config_file);
  282. WinExec(cmd, SW_SHOW);
  283. }
  284. static void show_error(void) {
  285. char buf[256];
  286. FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
  287. NULL, GetLastError(),
  288. MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
  289. buf, sizeof(buf), NULL);
  290. MessageBox(NULL, buf, "Error", MB_OK);
  291. }
  292. static int manage_service(int action) {
  293. static const char *service_name = "Mongoose";
  294. SC_HANDLE hSCM = NULL, hService = NULL;
  295. SERVICE_DESCRIPTION descr = {server_name};
  296. char path[PATH_MAX + 20]; // Path to executable plus magic argument
  297. int success = 1;
  298. if ((hSCM = OpenSCManager(NULL, NULL, action == ID_INSTALL_SERVICE ?
  299. GENERIC_WRITE : GENERIC_READ)) == NULL) {
  300. success = 0;
  301. show_error();
  302. } else if (action == ID_INSTALL_SERVICE) {
  303. GetModuleFileName(NULL, path, sizeof(path));
  304. strncat(path, " ", sizeof(path));
  305. strncat(path, service_magic_argument, sizeof(path));
  306. hService = CreateService(hSCM, service_name, service_name,
  307. SERVICE_ALL_ACCESS, SERVICE_WIN32_OWN_PROCESS,
  308. SERVICE_AUTO_START, SERVICE_ERROR_NORMAL,
  309. path, NULL, NULL, NULL, NULL, NULL);
  310. if (hService) {
  311. ChangeServiceConfig2(hService, SERVICE_CONFIG_DESCRIPTION, &descr);
  312. } else {
  313. show_error();
  314. }
  315. } else if (action == ID_REMOVE_SERVICE) {
  316. if ((hService = OpenService(hSCM, service_name, DELETE)) == NULL ||
  317. !DeleteService(hService)) {
  318. show_error();
  319. }
  320. } else if ((hService = OpenService(hSCM, service_name,
  321. SERVICE_QUERY_STATUS)) == NULL) {
  322. success = 0;
  323. }
  324. CloseServiceHandle(hService);
  325. CloseServiceHandle(hSCM);
  326. return success;
  327. }
  328. static LRESULT CALLBACK WindowProc(HWND hWnd, UINT msg, WPARAM wParam,
  329. LPARAM lParam) {
  330. static SERVICE_TABLE_ENTRY service_table[] = {
  331. {server_name, (LPSERVICE_MAIN_FUNCTION) ServiceMain},
  332. {NULL, NULL}
  333. };
  334. int service_installed;
  335. char buf[200], *service_argv[] = {__argv[0], NULL};
  336. POINT pt;
  337. HMENU hMenu;
  338. switch (msg) {
  339. case WM_CREATE:
  340. if (__argv[1] != NULL &&
  341. !strcmp(__argv[1], service_magic_argument)) {
  342. start_mongoose(1, service_argv);
  343. StartServiceCtrlDispatcher(service_table);
  344. exit(EXIT_SUCCESS);
  345. } else {
  346. start_mongoose(__argc, __argv);
  347. }
  348. break;
  349. case WM_COMMAND:
  350. switch (LOWORD(wParam)) {
  351. case ID_QUIT:
  352. mg_stop(ctx);
  353. Shell_NotifyIcon(NIM_DELETE, &TrayIcon);
  354. PostQuitMessage(0);
  355. break;
  356. case ID_EDIT_CONFIG:
  357. edit_config_file();
  358. break;
  359. case ID_INSTALL_SERVICE:
  360. case ID_REMOVE_SERVICE:
  361. manage_service(LOWORD(wParam));
  362. break;
  363. }
  364. break;
  365. case WM_USER:
  366. switch (lParam) {
  367. case WM_RBUTTONUP:
  368. case WM_LBUTTONUP:
  369. case WM_LBUTTONDBLCLK:
  370. hMenu = CreatePopupMenu();
  371. AppendMenu(hMenu, MF_STRING | MF_GRAYED, ID_SEPARATOR, server_name);
  372. AppendMenu(hMenu, MF_SEPARATOR, ID_SEPARATOR, "");
  373. service_installed = manage_service(0);
  374. snprintf(buf, sizeof(buf), "NT service: %s installed",
  375. service_installed ? "" : "not");
  376. AppendMenu(hMenu, MF_STRING | MF_GRAYED, ID_SEPARATOR, buf);
  377. AppendMenu(hMenu, MF_STRING | (service_installed ? MF_GRAYED : 0),
  378. ID_INSTALL_SERVICE, "Install service");
  379. AppendMenu(hMenu, MF_STRING | (!service_installed ? MF_GRAYED : 0),
  380. ID_REMOVE_SERVICE, "Deinstall service");
  381. AppendMenu(hMenu, MF_SEPARATOR, ID_SEPARATOR, "");
  382. AppendMenu(hMenu, MF_STRING, ID_EDIT_CONFIG, "Edit config file");
  383. AppendMenu(hMenu, MF_STRING, ID_QUIT, "Exit");
  384. GetCursorPos(&pt);
  385. SetForegroundWindow(hWnd);
  386. TrackPopupMenu(hMenu, 0, pt.x, pt.y, 0, hWnd, NULL);
  387. PostMessage(hWnd, WM_NULL, 0, 0);
  388. DestroyMenu(hMenu);
  389. break;
  390. }
  391. break;
  392. case WM_CLOSE:
  393. mg_stop(ctx);
  394. Shell_NotifyIcon(NIM_DELETE, &TrayIcon);
  395. PostQuitMessage(0);
  396. return 0; // We've just sent our own quit message, with proper hwnd.
  397. }
  398. return DefWindowProc(hWnd, msg, wParam, lParam);
  399. }
  400. int WINAPI WinMain(HINSTANCE hInst, HINSTANCE hPrev, LPSTR cmdline, int show) {
  401. WNDCLASS cls;
  402. HWND hWnd;
  403. MSG msg;
  404. init_server_name();
  405. memset(&cls, 0, sizeof(cls));
  406. cls.lpfnWndProc = (WNDPROC) WindowProc;
  407. cls.hIcon = LoadIcon(NULL, IDI_APPLICATION);
  408. cls.lpszClassName = server_name;
  409. RegisterClass(&cls);
  410. hWnd = CreateWindow(cls.lpszClassName, server_name, WS_OVERLAPPEDWINDOW,
  411. 0, 0, 0, 0, NULL, NULL, NULL, NULL);
  412. ShowWindow(hWnd, SW_HIDE);
  413. TrayIcon.cbSize = sizeof(TrayIcon);
  414. TrayIcon.uID = ID_TRAYICON;
  415. TrayIcon.uFlags = NIF_ICON | NIF_MESSAGE | NIF_TIP;
  416. TrayIcon.hIcon = LoadImage(GetModuleHandle(NULL), MAKEINTRESOURCE(ID_ICON),
  417. IMAGE_ICON, 16, 16, 0);
  418. TrayIcon.hWnd = hWnd;
  419. snprintf(TrayIcon.szTip, sizeof(TrayIcon.szTip), "%s", server_name);
  420. TrayIcon.uCallbackMessage = WM_USER;
  421. Shell_NotifyIcon(NIM_ADD, &TrayIcon);
  422. while (GetMessage(&msg, hWnd, 0, 0) > 0) {
  423. TranslateMessage(&msg);
  424. DispatchMessage(&msg);
  425. }
  426. // Return the WM_QUIT value.
  427. return msg.wParam;
  428. }
  429. #else
  430. int main(int argc, char *argv[]) {
  431. init_server_name();
  432. start_mongoose(argc, argv);
  433. printf("%s started on port(s) %s with web root [%s]\n",
  434. server_name, mg_get_option(ctx, "listening_ports"),
  435. mg_get_option(ctx, "document_root"));
  436. while (exit_flag == 0) {
  437. sleep(1);
  438. }
  439. printf("Exiting on signal %d, waiting for all threads to finish...",
  440. exit_flag);
  441. fflush(stdout);
  442. mg_stop(ctx);
  443. printf("%s", " done.\n");
  444. return EXIT_SUCCESS;
  445. }
  446. #endif /* _WIN32 */