main.c 15 KB

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