main.c 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492
  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 "mongoose.h"
  35. #ifdef _WIN32
  36. #include <windows.h>
  37. #include <winsvc.h>
  38. #define PATH_MAX MAX_PATH
  39. #define S_ISDIR(x) ((x) & _S_IFDIR)
  40. #define DIRSEP '\\'
  41. #define snprintf _snprintf
  42. #define vsnprintf _vsnprintf
  43. #define sleep(x) Sleep((x) * 1000)
  44. #define WINCDECL __cdecl
  45. #else
  46. #include <sys/wait.h>
  47. #include <unistd.h>
  48. #define DIRSEP '/'
  49. #define WINCDECL
  50. #endif // _WIN32
  51. #define MAX_OPTIONS 40
  52. #define MAX_CONF_FILE_LINE_SIZE (8 * 1024)
  53. static int exit_flag;
  54. static char server_name[40]; // Set by init_server_name()
  55. static char config_file[PATH_MAX]; // Set by process_command_line_arguments()
  56. static struct mg_context *ctx; // Set by start_mongoose()
  57. #if !defined(CONFIG_FILE)
  58. #define CONFIG_FILE "mongoose.conf"
  59. #endif /* !CONFIG_FILE */
  60. static void WINCDECL signal_handler(int sig_num) {
  61. exit_flag = sig_num;
  62. }
  63. static void die(const char *fmt, ...) {
  64. va_list ap;
  65. char msg[200];
  66. va_start(ap, fmt);
  67. vsnprintf(msg, sizeof(msg), fmt, ap);
  68. va_end(ap);
  69. #if defined(_WIN32)
  70. MessageBox(NULL, msg, "Error", MB_OK);
  71. #else
  72. fprintf(stderr, "%s\n", msg);
  73. #endif
  74. exit(EXIT_FAILURE);
  75. }
  76. static void show_usage_and_exit(void) {
  77. const char **names;
  78. int i;
  79. fprintf(stderr, "Mongoose version %s (c) Sergey Lyubka\n", mg_version());
  80. fprintf(stderr, "Usage:\n");
  81. fprintf(stderr, " mongoose -A <htpasswd_file> <realm> <user> <passwd>\n");
  82. fprintf(stderr, " mongoose <config_file>\n");
  83. fprintf(stderr, " mongoose [-option value ...]\n");
  84. fprintf(stderr, "OPTIONS:\n");
  85. names = mg_get_valid_option_names();
  86. for (i = 0; names[i] != NULL; i += 3) {
  87. fprintf(stderr, " -%s %s (default: \"%s\")\n",
  88. names[i], names[i + 1], names[i + 2] == NULL ? "" : names[i + 2]);
  89. }
  90. fprintf(stderr, "See http://code.google.com/p/mongoose/wiki/MongooseManual"
  91. " for more details.\n");
  92. fprintf(stderr, "Example:\n mongoose -s cert.pem -p 80,443s -d no\n");
  93. exit(EXIT_FAILURE);
  94. }
  95. static void verify_document_root(const char *root) {
  96. const char *p, *path;
  97. char buf[PATH_MAX];
  98. struct stat st;
  99. path = root;
  100. if ((p = strchr(root, ',')) != NULL && (size_t) (p - root) < sizeof(buf)) {
  101. memcpy(buf, root, p - root);
  102. buf[p - root] = '\0';
  103. path = buf;
  104. }
  105. if (stat(path, &st) != 0 || !S_ISDIR(st.st_mode)) {
  106. die("Invalid root directory: [%s]: %s", root, strerror(errno));
  107. }
  108. }
  109. static char *sdup(const char *str) {
  110. char *p;
  111. if ((p = (char *) malloc(strlen(str) + 1)) != NULL) {
  112. strcpy(p, str);
  113. }
  114. return p;
  115. }
  116. static void set_option(char **options, const char *name, const char *value) {
  117. int i;
  118. if (!strcmp(name, "document_root") || !(strcmp(name, "r"))) {
  119. verify_document_root(value);
  120. }
  121. for (i = 0; i < MAX_OPTIONS - 3; i++) {
  122. if (options[i] == NULL) {
  123. options[i] = sdup(name);
  124. options[i + 1] = sdup(value);
  125. options[i + 2] = NULL;
  126. break;
  127. }
  128. }
  129. if (i == MAX_OPTIONS - 3) {
  130. die("%s", "Too many options specified");
  131. }
  132. }
  133. static void process_command_line_arguments(char *argv[], char **options) {
  134. char line[MAX_CONF_FILE_LINE_SIZE], opt[sizeof(line)], val[sizeof(line)], *p;
  135. FILE *fp = NULL;
  136. size_t i, cmd_line_opts_start = 1, line_no = 0;
  137. options[0] = NULL;
  138. // Should we use a config file ?
  139. if (argv[1] != NULL && argv[1][0] != '-') {
  140. snprintf(config_file, sizeof(config_file), "%s", argv[1]);
  141. cmd_line_opts_start = 2;
  142. } else if ((p = strrchr(argv[0], DIRSEP)) == NULL) {
  143. // No command line flags specified. Look where binary lives
  144. snprintf(config_file, sizeof(config_file), "%s", CONFIG_FILE);
  145. } else {
  146. snprintf(config_file, sizeof(config_file), "%.*s%c%s",
  147. (int) (p - argv[0]), argv[0], DIRSEP, CONFIG_FILE);
  148. }
  149. fp = fopen(config_file, "r");
  150. // If config file was set in command line and open failed, die
  151. if (cmd_line_opts_start == 2 && fp == NULL) {
  152. die("Cannot open config file %s: %s", config_file, strerror(errno));
  153. }
  154. // Load config file settings first
  155. if (fp != NULL) {
  156. fprintf(stderr, "Loading config file %s\n", config_file);
  157. // Loop over the lines in config file
  158. while (fgets(line, sizeof(line), fp) != NULL) {
  159. line_no++;
  160. // Ignore empty lines and comments
  161. if (line[0] == '#' || line[0] == '\n')
  162. continue;
  163. if (sscanf(line, "%s %[^\r\n#]", opt, val) != 2) {
  164. die("%s: line %d is invalid", config_file, (int) line_no);
  165. }
  166. set_option(options, opt, val);
  167. }
  168. (void) fclose(fp);
  169. }
  170. // Now handle command line flags. They override config file settings.
  171. for (i = cmd_line_opts_start; argv[i] != NULL; i += 2) {
  172. if (argv[i][0] != '-' || argv[i + 1] == NULL) {
  173. show_usage_and_exit();
  174. }
  175. set_option(options, &argv[i][1], argv[i + 1]);
  176. }
  177. }
  178. static void init_server_name(void) {
  179. snprintf(server_name, sizeof(server_name), "Mongoose web server v. %s",
  180. mg_version());
  181. }
  182. static void start_mongoose(int argc, char *argv[]) {
  183. char *options[MAX_OPTIONS];
  184. int i;
  185. // Edit passwords file if -A option is specified
  186. if (argc > 1 && !strcmp(argv[1], "-A")) {
  187. if (argc != 6) {
  188. show_usage_and_exit();
  189. }
  190. exit(mg_modify_passwords_file(argv[2], argv[3], argv[4], argv[5]) ?
  191. EXIT_SUCCESS : EXIT_FAILURE);
  192. }
  193. // Show usage if -h or --help options are specified
  194. if (argc == 2 && (!strcmp(argv[1], "-h") || !strcmp(argv[1], "--help"))) {
  195. show_usage_and_exit();
  196. }
  197. /* Update config based on command line arguments */
  198. process_command_line_arguments(argv, options);
  199. /* Setup signal handler: quit on Ctrl-C */
  200. signal(SIGTERM, signal_handler);
  201. signal(SIGINT, signal_handler);
  202. /* Start Mongoose */
  203. ctx = mg_start(NULL, NULL, (const char **) options);
  204. for (i = 0; options[i] != NULL; i++) {
  205. free(options[i]);
  206. }
  207. if (ctx == NULL) {
  208. die("%s", "Failed to start Mongoose. Maybe some options are "
  209. "assigned bad values?\nTry to run with '-e error_log.txt' "
  210. "and check error_log.txt for more information.");
  211. }
  212. }
  213. #ifdef _WIN32
  214. static SERVICE_STATUS ss;
  215. static SERVICE_STATUS_HANDLE hStatus;
  216. static const char *service_magic_argument = "--";
  217. static void WINAPI ControlHandler(DWORD code) {
  218. if (code == SERVICE_CONTROL_STOP || code == SERVICE_CONTROL_SHUTDOWN) {
  219. ss.dwWin32ExitCode = 0;
  220. ss.dwCurrentState = SERVICE_STOPPED;
  221. }
  222. SetServiceStatus(hStatus, &ss);
  223. }
  224. static void WINAPI ServiceMain(void) {
  225. ss.dwServiceType = SERVICE_WIN32;
  226. ss.dwCurrentState = SERVICE_RUNNING;
  227. ss.dwControlsAccepted = SERVICE_ACCEPT_STOP | SERVICE_ACCEPT_SHUTDOWN;
  228. hStatus = RegisterServiceCtrlHandler(server_name, ControlHandler);
  229. SetServiceStatus(hStatus, &ss);
  230. while (ss.dwCurrentState == SERVICE_RUNNING) {
  231. Sleep(1000);
  232. }
  233. mg_stop(ctx);
  234. ss.dwCurrentState = SERVICE_STOPPED;
  235. ss.dwWin32ExitCode = (DWORD) -1;
  236. SetServiceStatus(hStatus, &ss);
  237. }
  238. #define ID_TRAYICON 100
  239. #define ID_QUIT 101
  240. #define ID_EDIT_CONFIG 102
  241. #define ID_SEPARATOR 103
  242. #define ID_INSTALL_SERVICE 104
  243. #define ID_REMOVE_SERVICE 105
  244. #define ID_ICON 200
  245. static NOTIFYICONDATA TrayIcon;
  246. static void edit_config_file(void) {
  247. const char **names, *value;
  248. FILE *fp;
  249. int i;
  250. char cmd[200];
  251. // Create config file if it is not present yet
  252. if ((fp = fopen(config_file, "r")) != NULL) {
  253. fclose(fp);
  254. } else if ((fp = fopen(config_file, "a+")) != NULL) {
  255. fprintf(fp,
  256. "# Mongoose web server configuration file.\n"
  257. "# Lines starting with '#' and empty lines are ignored.\n"
  258. "# For detailed description of every option, visit\n"
  259. "# http://code.google.com/p/mongoose/wiki/MongooseManual\n\n");
  260. names = mg_get_valid_option_names();
  261. for (i = 0; names[i] != NULL; i += 3) {
  262. value = mg_get_option(ctx, names[i]);
  263. fprintf(fp, "# %s %s\n", names[i + 1], *value ? value : "<value>");
  264. }
  265. fclose(fp);
  266. }
  267. snprintf(cmd, sizeof(cmd), "notepad.exe %s", config_file);
  268. WinExec(cmd, SW_SHOW);
  269. }
  270. static void show_error(void) {
  271. char buf[256];
  272. FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
  273. NULL, GetLastError(),
  274. MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
  275. buf, sizeof(buf), NULL);
  276. MessageBox(NULL, buf, "Error", MB_OK);
  277. }
  278. static int manage_service(int action) {
  279. static const char *service_name = "Mongoose";
  280. SC_HANDLE hSCM = NULL, hService = NULL;
  281. SERVICE_DESCRIPTION descr = {server_name};
  282. char path[PATH_MAX + 20]; // Path to executable plus magic argument
  283. int success = 1;
  284. if ((hSCM = OpenSCManager(NULL, NULL, action == ID_INSTALL_SERVICE ?
  285. GENERIC_WRITE : GENERIC_READ)) == NULL) {
  286. success = 0;
  287. show_error();
  288. } else if (action == ID_INSTALL_SERVICE) {
  289. GetModuleFileName(NULL, path, sizeof(path));
  290. strncat(path, " ", sizeof(path));
  291. strncat(path, service_magic_argument, sizeof(path));
  292. hService = CreateService(hSCM, service_name, service_name,
  293. SERVICE_ALL_ACCESS, SERVICE_WIN32_OWN_PROCESS,
  294. SERVICE_AUTO_START, SERVICE_ERROR_NORMAL,
  295. path, NULL, NULL, NULL, NULL, NULL);
  296. if (hService) {
  297. ChangeServiceConfig2(hService, SERVICE_CONFIG_DESCRIPTION, &descr);
  298. } else {
  299. show_error();
  300. }
  301. } else if (action == ID_REMOVE_SERVICE) {
  302. if ((hService = OpenService(hSCM, service_name, DELETE)) == NULL ||
  303. !DeleteService(hService)) {
  304. show_error();
  305. }
  306. } else if ((hService = OpenService(hSCM, service_name,
  307. SERVICE_QUERY_STATUS)) == NULL) {
  308. success = 0;
  309. }
  310. CloseServiceHandle(hService);
  311. CloseServiceHandle(hSCM);
  312. return success;
  313. }
  314. static LRESULT CALLBACK WindowProc(HWND hWnd, UINT msg, WPARAM wParam,
  315. LPARAM lParam) {
  316. static SERVICE_TABLE_ENTRY service_table[] = {
  317. {server_name, (LPSERVICE_MAIN_FUNCTION) ServiceMain},
  318. {NULL, NULL}
  319. };
  320. int service_installed;
  321. char buf[200], *service_argv[] = {__argv[0], NULL};
  322. POINT pt;
  323. HMENU hMenu;
  324. switch (msg) {
  325. case WM_CREATE:
  326. if (__argv[1] != NULL &&
  327. !strcmp(__argv[1], service_magic_argument)) {
  328. start_mongoose(1, service_argv);
  329. StartServiceCtrlDispatcher(service_table);
  330. exit(EXIT_SUCCESS);
  331. } else {
  332. start_mongoose(__argc, __argv);
  333. }
  334. break;
  335. case WM_COMMAND:
  336. switch (LOWORD(wParam)) {
  337. case ID_QUIT:
  338. mg_stop(ctx);
  339. Shell_NotifyIcon(NIM_DELETE, &TrayIcon);
  340. PostQuitMessage(0);
  341. break;
  342. case ID_EDIT_CONFIG:
  343. edit_config_file();
  344. break;
  345. case ID_INSTALL_SERVICE:
  346. case ID_REMOVE_SERVICE:
  347. manage_service(LOWORD(wParam));
  348. break;
  349. }
  350. break;
  351. case WM_USER:
  352. switch (lParam) {
  353. case WM_RBUTTONUP:
  354. case WM_LBUTTONUP:
  355. case WM_LBUTTONDBLCLK:
  356. hMenu = CreatePopupMenu();
  357. AppendMenu(hMenu, MF_STRING | MF_GRAYED, ID_SEPARATOR, server_name);
  358. AppendMenu(hMenu, MF_SEPARATOR, ID_SEPARATOR, "");
  359. service_installed = manage_service(0);
  360. snprintf(buf, sizeof(buf), "NT service: %s installed",
  361. service_installed ? "" : "not");
  362. AppendMenu(hMenu, MF_STRING | MF_GRAYED, ID_SEPARATOR, buf);
  363. AppendMenu(hMenu, MF_STRING | (service_installed ? MF_GRAYED : 0),
  364. ID_INSTALL_SERVICE, "Install service");
  365. AppendMenu(hMenu, MF_STRING | (!service_installed ? MF_GRAYED : 0),
  366. ID_REMOVE_SERVICE, "Deinstall service");
  367. AppendMenu(hMenu, MF_SEPARATOR, ID_SEPARATOR, "");
  368. AppendMenu(hMenu, MF_STRING, ID_EDIT_CONFIG, "Edit config file");
  369. AppendMenu(hMenu, MF_STRING, ID_QUIT, "Exit");
  370. GetCursorPos(&pt);
  371. SetForegroundWindow(hWnd);
  372. TrackPopupMenu(hMenu, 0, pt.x, pt.y, 0, hWnd, NULL);
  373. PostMessage(hWnd, WM_NULL, 0, 0);
  374. DestroyMenu(hMenu);
  375. break;
  376. }
  377. break;
  378. }
  379. return DefWindowProc(hWnd, msg, wParam, lParam);
  380. }
  381. int WINAPI WinMain(HINSTANCE hInst, HINSTANCE hPrev, LPSTR cmdline, int show) {
  382. WNDCLASS cls;
  383. HWND hWnd;
  384. MSG msg;
  385. init_server_name();
  386. memset(&cls, 0, sizeof(cls));
  387. cls.lpfnWndProc = (WNDPROC) WindowProc;
  388. cls.hIcon = LoadIcon(NULL, IDI_APPLICATION);
  389. cls.lpszClassName = server_name;
  390. RegisterClass(&cls);
  391. hWnd = CreateWindow(cls.lpszClassName, server_name, WS_OVERLAPPEDWINDOW,
  392. 0, 0, 0, 0, NULL, NULL, NULL, NULL);
  393. ShowWindow(hWnd, SW_HIDE);
  394. TrayIcon.cbSize = sizeof(TrayIcon);
  395. TrayIcon.uID = ID_TRAYICON;
  396. TrayIcon.uFlags = NIF_ICON | NIF_MESSAGE | NIF_TIP;
  397. TrayIcon.hIcon = LoadImage(GetModuleHandle(NULL), MAKEINTRESOURCE(ID_ICON),
  398. IMAGE_ICON, 16, 16, 0);
  399. TrayIcon.hWnd = hWnd;
  400. snprintf(TrayIcon.szTip, sizeof(TrayIcon.szTip), "%s", server_name);
  401. TrayIcon.uCallbackMessage = WM_USER;
  402. Shell_NotifyIcon(NIM_ADD, &TrayIcon);
  403. while (GetMessage(&msg, hWnd, 0, 0)) {
  404. TranslateMessage(&msg);
  405. DispatchMessage(&msg);
  406. }
  407. }
  408. #else
  409. int main(int argc, char *argv[]) {
  410. init_server_name();
  411. start_mongoose(argc, argv);
  412. printf("%s started on port(s) %s with web root [%s]\n",
  413. server_name, mg_get_option(ctx, "listening_ports"),
  414. mg_get_option(ctx, "document_root"));
  415. while (exit_flag == 0) {
  416. sleep(1);
  417. }
  418. printf("Exiting on signal %d, waiting for all threads to finish...",
  419. exit_flag);
  420. fflush(stdout);
  421. mg_stop(ctx);
  422. printf("%s", " done.\n");
  423. return EXIT_SUCCESS;
  424. }
  425. #endif /* _WIN32 */