main.c 15 KB

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