main.c 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895
  1. // Copyright (c) 2004-2013 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. #include <shlobj.h>
  40. #define PATH_MAX MAX_PATH
  41. #define S_ISDIR(x) ((x) & _S_IFDIR)
  42. #define DIRSEP '\\'
  43. #define snprintf _snprintf
  44. #define vsnprintf _vsnprintf
  45. #define sleep(x) Sleep((x) * 1000)
  46. #define WINCDECL __cdecl
  47. #else
  48. #include <sys/wait.h>
  49. #include <unistd.h>
  50. #define DIRSEP '/'
  51. #define WINCDECL
  52. #endif // _WIN32
  53. #define MAX_OPTIONS 40
  54. #define MAX_CONF_FILE_LINE_SIZE (8 * 1024)
  55. static int exit_flag;
  56. static char server_name[40]; // Set by init_server_name()
  57. static char config_file[PATH_MAX]; // Set by process_command_line_arguments()
  58. static struct mg_context *ctx; // Set by start_mongoose()
  59. #if !defined(CONFIG_FILE)
  60. #define CONFIG_FILE "mongoose.conf"
  61. #endif /* !CONFIG_FILE */
  62. static void WINCDECL signal_handler(int sig_num) {
  63. exit_flag = sig_num;
  64. }
  65. static void die(const char *fmt, ...) {
  66. va_list ap;
  67. char msg[200];
  68. va_start(ap, fmt);
  69. vsnprintf(msg, sizeof(msg), fmt, ap);
  70. va_end(ap);
  71. #if defined(_WIN32)
  72. MessageBox(NULL, msg, "Error", MB_OK);
  73. #else
  74. fprintf(stderr, "%s\n", msg);
  75. #endif
  76. exit(EXIT_FAILURE);
  77. }
  78. static void show_usage_and_exit(void) {
  79. const char **names;
  80. int i;
  81. fprintf(stderr, "Mongoose version %s (c) Sergey Lyubka, built %s\n",
  82. mg_version(), __DATE__);
  83. fprintf(stderr, "Usage:\n");
  84. fprintf(stderr, " mongoose -A <htpasswd_file> <realm> <user> <passwd>\n");
  85. fprintf(stderr, " mongoose <config_file>\n");
  86. fprintf(stderr, " mongoose [-option value ...]\n");
  87. fprintf(stderr, "\nOPTIONS:\n");
  88. names = mg_get_valid_option_names();
  89. for (i = 0; names[i] != NULL; i += 3) {
  90. fprintf(stderr, " -%s %s (default: \"%s\")\n",
  91. names[i], names[i + 1], names[i + 2] == NULL ? "" : names[i + 2]);
  92. }
  93. exit(EXIT_FAILURE);
  94. }
  95. #if defined(_WIN32) || defined(USE_COCOA)
  96. static const char *config_file_top_comment =
  97. "# Mongoose web server configuration file.\n"
  98. "# For detailed description of every option, visit\n"
  99. "# https://github.com/valenok/mongoose/blob/master/UserManual.md\n"
  100. "# Lines starting with '#' and empty lines are ignored.\n"
  101. "# To make a change, remove leading '#', modify option's value,\n"
  102. "# save this file and then restart Mongoose.\n\n";
  103. static const char *get_url_to_first_open_port(const struct mg_context *ctx) {
  104. static char url[100];
  105. const char *open_ports = mg_get_option(ctx, "listening_ports");
  106. int a, b, c, d, port, n;
  107. if (sscanf(open_ports, "%d.%d.%d.%d:%d%n", &a, &b, &c, &d, &port, &n) == 5) {
  108. snprintf(url, sizeof(url), "%s://%d.%d.%d.%d:%d",
  109. open_ports[n] == 's' ? "https" : "http", a, b, c, d, port);
  110. } else if (sscanf(open_ports, "%d%n", &port, &n) == 1) {
  111. snprintf(url, sizeof(url), "%s://localhost:%d",
  112. open_ports[n] == 's' ? "https" : "http", port);
  113. } else {
  114. snprintf(url, sizeof(url), "%s", "http://localhost:8080");
  115. }
  116. return url;
  117. }
  118. static void create_config_file(const char *path) {
  119. const char **names, *value;
  120. FILE *fp;
  121. int i;
  122. // Create config file if it is not present yet
  123. if ((fp = fopen(path, "r")) != NULL) {
  124. fclose(fp);
  125. } else if ((fp = fopen(path, "a+")) != NULL) {
  126. fprintf(fp, "%s", config_file_top_comment);
  127. names = mg_get_valid_option_names();
  128. for (i = 0; names[i] != NULL; i += 3) {
  129. value = mg_get_option(ctx, names[i]);
  130. fprintf(fp, "# %s %s\n", names[i + 1], *value ? value : "<value>");
  131. }
  132. fclose(fp);
  133. }
  134. }
  135. #endif
  136. static void verify_document_root(const char *root) {
  137. const char *p, *path;
  138. char buf[PATH_MAX];
  139. struct stat st;
  140. path = root;
  141. if ((p = strchr(root, ',')) != NULL && (size_t) (p - root) < sizeof(buf)) {
  142. memcpy(buf, root, p - root);
  143. buf[p - root] = '\0';
  144. path = buf;
  145. }
  146. if (stat(path, &st) != 0 || !S_ISDIR(st.st_mode)) {
  147. die("Invalid root directory: [%s]: %s", root, strerror(errno));
  148. }
  149. }
  150. static char *sdup(const char *str) {
  151. char *p;
  152. if ((p = (char *) malloc(strlen(str) + 1)) != NULL) {
  153. strcpy(p, str);
  154. }
  155. return p;
  156. }
  157. static void set_option(char **options, const char *name, const char *value) {
  158. int i;
  159. if (!strcmp(name, "document_root") || !(strcmp(name, "r"))) {
  160. verify_document_root(value);
  161. }
  162. for (i = 0; i < MAX_OPTIONS - 3; i++) {
  163. if (options[i] == NULL) {
  164. options[i] = sdup(name);
  165. options[i + 1] = sdup(value);
  166. options[i + 2] = NULL;
  167. break;
  168. }
  169. }
  170. if (i == MAX_OPTIONS - 3) {
  171. die("%s", "Too many options specified");
  172. }
  173. }
  174. static void process_command_line_arguments(char *argv[], char **options) {
  175. char line[MAX_CONF_FILE_LINE_SIZE], opt[sizeof(line)], val[sizeof(line)], *p;
  176. FILE *fp = NULL;
  177. size_t i, cmd_line_opts_start = 1, line_no = 0;
  178. options[0] = NULL;
  179. // Should we use a config file ?
  180. if (argv[1] != NULL && argv[1][0] != '-') {
  181. snprintf(config_file, sizeof(config_file), "%s", argv[1]);
  182. cmd_line_opts_start = 2;
  183. } else if ((p = strrchr(argv[0], DIRSEP)) == NULL) {
  184. // No command line flags specified. Look where binary lives
  185. snprintf(config_file, sizeof(config_file), "%s", CONFIG_FILE);
  186. } else {
  187. snprintf(config_file, sizeof(config_file), "%.*s%c%s",
  188. (int) (p - argv[0]), argv[0], DIRSEP, CONFIG_FILE);
  189. }
  190. fp = fopen(config_file, "r");
  191. // If config file was set in command line and open failed, die
  192. if (cmd_line_opts_start == 2 && fp == NULL) {
  193. die("Cannot open config file %s: %s", config_file, strerror(errno));
  194. }
  195. // Load config file settings first
  196. if (fp != NULL) {
  197. fprintf(stderr, "Loading config file %s\n", config_file);
  198. // Loop over the lines in config file
  199. while (fgets(line, sizeof(line), fp) != NULL) {
  200. line_no++;
  201. // Ignore empty lines and comments
  202. for (i = 0; isspace(* (unsigned char *) &line[i]); ) i++;
  203. if (line[i] == '#' || line[i] == '\0') {
  204. continue;
  205. }
  206. if (sscanf(line, "%s %[^\r\n#]", opt, val) != 2) {
  207. printf("%s: line %d is invalid, ignoring it:\n %s",
  208. config_file, (int) line_no, line);
  209. } else {
  210. set_option(options, opt, val);
  211. }
  212. }
  213. (void) fclose(fp);
  214. }
  215. // Handle command line flags. They override config file and default settings.
  216. for (i = cmd_line_opts_start; argv[i] != NULL; i += 2) {
  217. if (argv[i][0] != '-' || argv[i + 1] == NULL) {
  218. show_usage_and_exit();
  219. }
  220. set_option(options, &argv[i][1], argv[i + 1]);
  221. }
  222. }
  223. static void init_server_name(void) {
  224. snprintf(server_name, sizeof(server_name), "Mongoose web server v. %s",
  225. mg_version());
  226. }
  227. static int log_message(const struct mg_connection *conn, const char *message) {
  228. (void) conn;
  229. printf("%s\n", message);
  230. return 0;
  231. }
  232. static void start_mongoose(int argc, char *argv[]) {
  233. struct mg_callbacks callbacks;
  234. char *options[MAX_OPTIONS];
  235. int i;
  236. // Edit passwords file if -A option is specified
  237. if (argc > 1 && !strcmp(argv[1], "-A")) {
  238. if (argc != 6) {
  239. show_usage_and_exit();
  240. }
  241. exit(mg_modify_passwords_file(argv[2], argv[3], argv[4], argv[5]) ?
  242. EXIT_SUCCESS : EXIT_FAILURE);
  243. }
  244. // Show usage if -h or --help options are specified
  245. if (argc == 2 && (!strcmp(argv[1], "-h") || !strcmp(argv[1], "--help"))) {
  246. show_usage_and_exit();
  247. }
  248. /* Update config based on command line arguments */
  249. process_command_line_arguments(argv, options);
  250. /* Setup signal handler: quit on Ctrl-C */
  251. signal(SIGTERM, signal_handler);
  252. signal(SIGINT, signal_handler);
  253. /* Start Mongoose */
  254. memset(&callbacks, 0, sizeof(callbacks));
  255. callbacks.log_message = &log_message;
  256. ctx = mg_start(&callbacks, NULL, (const char **) options);
  257. for (i = 0; options[i] != NULL; i++) {
  258. free(options[i]);
  259. }
  260. if (ctx == NULL) {
  261. die("%s", "Failed to start Mongoose.");
  262. }
  263. }
  264. #ifdef _WIN32
  265. enum {
  266. ID_ICON = 100, ID_QUIT, ID_SETTINGS, ID_SEPARATOR, ID_INSTALL_SERVICE,
  267. ID_REMOVE_SERVICE, ID_STATIC, ID_GROUP, ID_SAVE, ID_RESET_DEFAULTS,
  268. ID_STATUS, ID_CONNECT,
  269. // All dynamically created text boxes for options have IDs starting from
  270. // ID_CONTROLS, incremented by one.
  271. ID_CONTROLS = 200,
  272. // Text boxes for files have "..." buttons to open file browser. These
  273. // buttons have IDs that are ID_FILE_BUTTONS_DELTA higher than associated
  274. // text box ID.
  275. ID_FILE_BUTTONS_DELTA = 1000
  276. };
  277. static HICON hIcon;
  278. static SERVICE_STATUS ss;
  279. static SERVICE_STATUS_HANDLE hStatus;
  280. static const char *service_magic_argument = "--";
  281. static NOTIFYICONDATA TrayIcon;
  282. static void WINAPI ControlHandler(DWORD code) {
  283. if (code == SERVICE_CONTROL_STOP || code == SERVICE_CONTROL_SHUTDOWN) {
  284. ss.dwWin32ExitCode = 0;
  285. ss.dwCurrentState = SERVICE_STOPPED;
  286. }
  287. SetServiceStatus(hStatus, &ss);
  288. }
  289. static void WINAPI ServiceMain(void) {
  290. ss.dwServiceType = SERVICE_WIN32;
  291. ss.dwCurrentState = SERVICE_RUNNING;
  292. ss.dwControlsAccepted = SERVICE_ACCEPT_STOP | SERVICE_ACCEPT_SHUTDOWN;
  293. hStatus = RegisterServiceCtrlHandler(server_name, ControlHandler);
  294. SetServiceStatus(hStatus, &ss);
  295. while (ss.dwCurrentState == SERVICE_RUNNING) {
  296. Sleep(1000);
  297. }
  298. mg_stop(ctx);
  299. ss.dwCurrentState = SERVICE_STOPPED;
  300. ss.dwWin32ExitCode = (DWORD) -1;
  301. SetServiceStatus(hStatus, &ss);
  302. }
  303. static void show_error(void) {
  304. char buf[256];
  305. FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
  306. NULL, GetLastError(),
  307. MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
  308. buf, sizeof(buf), NULL);
  309. MessageBox(NULL, buf, "Error", MB_OK);
  310. }
  311. static void *align(void *ptr, DWORD alig) {
  312. ULONG ul = (ULONG) ptr;
  313. ul += alig;
  314. ul &= ~alig;
  315. return ((void *) ul);
  316. }
  317. static int is_boolean_option(const char *option_name) {
  318. return !strcmp(option_name, "enable_directory_listing") ||
  319. !strcmp(option_name, "enable_keep_alive");
  320. }
  321. static int is_filename_option(const char *option_name) {
  322. return !strcmp(option_name, "cgi_interpreter") ||
  323. !strcmp(option_name, "global_auth_file") ||
  324. !strcmp(option_name, "put_delete_auth_file") ||
  325. !strcmp(option_name, "access_log_file") ||
  326. !strcmp(option_name, "error_log_file") ||
  327. !strcmp(option_name, "ssl_certificate");
  328. }
  329. static int is_directory_option(const char *option_name) {
  330. return !strcmp(option_name, "document_root");
  331. }
  332. static int is_numeric_options(const char *option_name) {
  333. return !strcmp(option_name, "num_threads");
  334. }
  335. static void save_config(HWND hDlg, FILE *fp) {
  336. char value[2000];
  337. const char **options, *name, *default_value;
  338. int i, id;
  339. fprintf(fp, "%s", config_file_top_comment);
  340. options = mg_get_valid_option_names();
  341. for (i = 0; options[i] != NULL; i += 3) {
  342. name = options[i + 1];
  343. id = ID_CONTROLS + i / 3;
  344. if (is_boolean_option(name)) {
  345. snprintf(value, sizeof(value), "%s",
  346. IsDlgButtonChecked(hDlg, id) ? "yes" : "no");
  347. } else {
  348. GetDlgItemText(hDlg, id, value, sizeof(value));
  349. }
  350. default_value = options[i + 2] == NULL ? "" : options[i + 2];
  351. // If value is the same as default, skip it
  352. if (strcmp(value, default_value) != 0) {
  353. fprintf(fp, "%s %s\n", name, value);
  354. }
  355. }
  356. }
  357. static BOOL CALLBACK DlgProc(HWND hDlg, UINT msg, WPARAM wParam, LPARAM lP) {
  358. FILE *fp;
  359. int i;
  360. const char *name, *value, **options = mg_get_valid_option_names();
  361. switch (msg) {
  362. case WM_CLOSE:
  363. DestroyWindow(hDlg);
  364. break;
  365. case WM_COMMAND:
  366. switch (LOWORD(wParam)) {
  367. case ID_SAVE:
  368. EnableWindow(GetDlgItem(hDlg, ID_SAVE), FALSE);
  369. if ((fp = fopen(config_file, "w+")) != NULL) {
  370. save_config(hDlg, fp);
  371. fclose(fp);
  372. mg_stop(ctx);
  373. start_mongoose(__argc, __argv);
  374. }
  375. EnableWindow(GetDlgItem(hDlg, ID_SAVE), TRUE);
  376. break;
  377. case ID_RESET_DEFAULTS:
  378. for (i = 0; options[i] != NULL; i += 3) {
  379. name = options[i + 1];
  380. value = options[i + 2] == NULL ? "" : options[i + 2];
  381. if (is_boolean_option(name)) {
  382. CheckDlgButton(hDlg, ID_CONTROLS + i / 3, !strcmp(value, "yes") ?
  383. BST_CHECKED : BST_UNCHECKED);
  384. } else {
  385. SetWindowText(GetDlgItem(hDlg, ID_CONTROLS + i / 3), value);
  386. }
  387. }
  388. break;
  389. }
  390. for (i = 0; options[i] != NULL; i += 3) {
  391. name = options[i + 1];
  392. if ((is_filename_option(name) || is_directory_option(name)) &&
  393. LOWORD(wParam) == ID_CONTROLS + i / 3 + ID_FILE_BUTTONS_DELTA) {
  394. OPENFILENAME of;
  395. BROWSEINFO bi;
  396. char path[PATH_MAX] = "";
  397. memset(&of, 0, sizeof(of));
  398. of.lStructSize = sizeof(of);
  399. of.hwndOwner = (HWND) hDlg;
  400. of.lpstrFile = path;
  401. of.nMaxFile = sizeof(path);
  402. of.lpstrInitialDir = mg_get_option(ctx, "document_root");
  403. of.Flags = OFN_CREATEPROMPT | OFN_NOCHANGEDIR;
  404. memset(&bi, 0, sizeof(bi));
  405. bi.hwndOwner = (HWND) hDlg;
  406. bi.lpszTitle = "Choose WWW root directory:";
  407. bi.ulFlags = BIF_RETURNONLYFSDIRS;
  408. if (is_directory_option(name)) {
  409. SHGetPathFromIDList(SHBrowseForFolder(&bi), path);
  410. } else {
  411. GetOpenFileName(&of);
  412. }
  413. if (path[0] != '\0') {
  414. SetWindowText(GetDlgItem(hDlg, ID_CONTROLS + i / 3), path);
  415. }
  416. }
  417. }
  418. break;
  419. case WM_INITDIALOG:
  420. SendMessage(hDlg, WM_SETICON,(WPARAM) ICON_SMALL, (LPARAM) hIcon);
  421. SendMessage(hDlg, WM_SETICON,(WPARAM) ICON_BIG, (LPARAM) hIcon);
  422. SetWindowText(hDlg, "Mongoose settings");
  423. SetFocus(GetDlgItem(hDlg, ID_SAVE));
  424. for (i = 0; options[i] != NULL; i += 3) {
  425. name = options[i + 1];
  426. value = mg_get_option(ctx, name);
  427. if (is_boolean_option(name)) {
  428. CheckDlgButton(hDlg, ID_CONTROLS + i / 3, !strcmp(value, "yes") ?
  429. BST_CHECKED : BST_UNCHECKED);
  430. } else {
  431. SetDlgItemText(hDlg, ID_CONTROLS + i / 3, value == NULL ? "" : value);
  432. }
  433. }
  434. break;
  435. default:
  436. break;
  437. }
  438. return FALSE;
  439. }
  440. static void add_control(unsigned char **mem, DLGTEMPLATE *dia, WORD type,
  441. DWORD id, DWORD style, WORD x, WORD y,
  442. WORD cx, WORD cy, const char *caption) {
  443. DLGITEMTEMPLATE *tp;
  444. LPWORD p;
  445. dia->cdit++;
  446. *mem = align(*mem, 3);
  447. tp = (DLGITEMTEMPLATE *) *mem;
  448. tp->id = (WORD)id;
  449. tp->style = style;
  450. tp->dwExtendedStyle = 0;
  451. tp->x = x;
  452. tp->y = y;
  453. tp->cx = cx;
  454. tp->cy = cy;
  455. p = align(*mem + sizeof(*tp), 1);
  456. *p++ = 0xffff;
  457. *p++ = type;
  458. while (*caption != '\0') {
  459. *p++ = (WCHAR) *caption++;
  460. }
  461. *p++ = 0;
  462. p = align(p, 1);
  463. *p++ = 0;
  464. *mem = (unsigned char *) p;
  465. }
  466. static void show_settings_dialog() {
  467. #define HEIGHT 15
  468. #define WIDTH 400
  469. #define LABEL_WIDTH 80
  470. unsigned char mem[4096], *p;
  471. const char **option_names, *long_option_name;
  472. DWORD style;
  473. DLGTEMPLATE *dia = (DLGTEMPLATE *) mem;
  474. WORD i, cl, x, y, width, nelems = 0;
  475. static int guard;
  476. static struct {
  477. DLGTEMPLATE template; // 18 bytes
  478. WORD menu, class;
  479. wchar_t caption[1];
  480. WORD fontsiz;
  481. wchar_t fontface[7];
  482. } dialog_header = {{WS_CAPTION | WS_POPUP | WS_SYSMENU | WS_VISIBLE |
  483. DS_SETFONT | WS_DLGFRAME, WS_EX_TOOLWINDOW, 0, 200, 200, WIDTH, 0},
  484. 0, 0, L"", 8, L"Tahoma"};
  485. if (guard == 0) {
  486. guard++;
  487. } else {
  488. return;
  489. }
  490. (void) memset(mem, 0, sizeof(mem));
  491. (void) memcpy(mem, &dialog_header, sizeof(dialog_header));
  492. p = mem + sizeof(dialog_header);
  493. option_names = mg_get_valid_option_names();
  494. for (i = 0; option_names[i] != NULL; i += 3) {
  495. long_option_name = option_names[i + 1];
  496. style = WS_CHILD | WS_VISIBLE | WS_TABSTOP;
  497. x = 10 + (WIDTH / 2) * (nelems % 2);
  498. y = (nelems/2 + 1) * HEIGHT + 5;
  499. width = WIDTH / 2 - 20 - LABEL_WIDTH;
  500. if (is_numeric_options(long_option_name)) {
  501. style |= ES_NUMBER;
  502. cl = 0x81;
  503. style |= WS_BORDER | ES_AUTOHSCROLL;
  504. } else if (is_boolean_option(long_option_name)) {
  505. cl = 0x80;
  506. style |= BS_AUTOCHECKBOX;
  507. } else if (is_filename_option(long_option_name) ||
  508. is_directory_option(long_option_name)) {
  509. style |= WS_BORDER | ES_AUTOHSCROLL;
  510. width -= 20;
  511. cl = 0x81;
  512. add_control(&p, dia, 0x80,
  513. ID_CONTROLS + (i / 3) + ID_FILE_BUTTONS_DELTA,
  514. WS_VISIBLE | WS_CHILD | BS_PUSHBUTTON,
  515. (WORD) (x + width + LABEL_WIDTH + 5),
  516. y, 15, 12, "...");
  517. } else {
  518. cl = 0x81;
  519. style |= WS_BORDER | ES_AUTOHSCROLL;
  520. }
  521. add_control(&p, dia, 0x82, ID_STATIC, WS_VISIBLE | WS_CHILD,
  522. x, y, LABEL_WIDTH, HEIGHT, long_option_name);
  523. add_control(&p, dia, cl, ID_CONTROLS + (i / 3), style,
  524. (WORD) (x + LABEL_WIDTH), y, width, 12, "");
  525. nelems++;
  526. }
  527. y = (WORD) (((nelems + 1) / 2 + 1) * HEIGHT + 5);
  528. add_control(&p, dia, 0x80, ID_GROUP, WS_CHILD | WS_VISIBLE |
  529. BS_GROUPBOX, 5, 5, WIDTH - 10, y, " Settings ");
  530. y += 10;
  531. add_control(&p, dia, 0x80, ID_SAVE,
  532. WS_CHILD | WS_VISIBLE | BS_PUSHBUTTON | WS_TABSTOP,
  533. WIDTH - 70, y, 65, 12, "Save Settings");
  534. add_control(&p, dia, 0x80, ID_RESET_DEFAULTS,
  535. WS_CHILD | WS_VISIBLE | BS_PUSHBUTTON | WS_TABSTOP,
  536. WIDTH - 140, y, 65, 12, "Reset to defaults");
  537. add_control(&p, dia, 0x82, ID_STATIC,
  538. WS_CHILD | WS_VISIBLE | WS_DISABLED,
  539. 5, y, 180, 12, server_name);
  540. dia->cy = ((nelems + 1) / 2 + 1) * HEIGHT + 30;
  541. DialogBoxIndirectParam(NULL, dia, NULL, DlgProc, (LPARAM) NULL);
  542. guard--;
  543. }
  544. static int manage_service(int action) {
  545. static const char *service_name = "Mongoose";
  546. SC_HANDLE hSCM = NULL, hService = NULL;
  547. SERVICE_DESCRIPTION descr = {server_name};
  548. char path[PATH_MAX + 20]; // Path to executable plus magic argument
  549. int success = 1;
  550. if ((hSCM = OpenSCManager(NULL, NULL, action == ID_INSTALL_SERVICE ?
  551. GENERIC_WRITE : GENERIC_READ)) == NULL) {
  552. success = 0;
  553. show_error();
  554. } else if (action == ID_INSTALL_SERVICE) {
  555. GetModuleFileName(NULL, path, sizeof(path));
  556. strncat(path, " ", sizeof(path));
  557. strncat(path, service_magic_argument, sizeof(path));
  558. hService = CreateService(hSCM, service_name, service_name,
  559. SERVICE_ALL_ACCESS, SERVICE_WIN32_OWN_PROCESS,
  560. SERVICE_AUTO_START, SERVICE_ERROR_NORMAL,
  561. path, NULL, NULL, NULL, NULL, NULL);
  562. if (hService) {
  563. ChangeServiceConfig2(hService, SERVICE_CONFIG_DESCRIPTION, &descr);
  564. } else {
  565. show_error();
  566. }
  567. } else if (action == ID_REMOVE_SERVICE) {
  568. if ((hService = OpenService(hSCM, service_name, DELETE)) == NULL ||
  569. !DeleteService(hService)) {
  570. show_error();
  571. }
  572. } else if ((hService = OpenService(hSCM, service_name,
  573. SERVICE_QUERY_STATUS)) == NULL) {
  574. success = 0;
  575. }
  576. CloseServiceHandle(hService);
  577. CloseServiceHandle(hSCM);
  578. return success;
  579. }
  580. static LRESULT CALLBACK WindowProc(HWND hWnd, UINT msg, WPARAM wParam,
  581. LPARAM lParam) {
  582. static SERVICE_TABLE_ENTRY service_table[] = {
  583. {server_name, (LPSERVICE_MAIN_FUNCTION) ServiceMain},
  584. {NULL, NULL}
  585. };
  586. int service_installed;
  587. char buf[200], *service_argv[] = {__argv[0], NULL};
  588. POINT pt;
  589. HMENU hMenu;
  590. switch (msg) {
  591. case WM_CREATE:
  592. if (__argv[1] != NULL &&
  593. !strcmp(__argv[1], service_magic_argument)) {
  594. start_mongoose(1, service_argv);
  595. StartServiceCtrlDispatcher(service_table);
  596. exit(EXIT_SUCCESS);
  597. } else {
  598. start_mongoose(__argc, __argv);
  599. }
  600. break;
  601. case WM_COMMAND:
  602. switch (LOWORD(wParam)) {
  603. case ID_QUIT:
  604. mg_stop(ctx);
  605. Shell_NotifyIcon(NIM_DELETE, &TrayIcon);
  606. PostQuitMessage(0);
  607. return 0;
  608. case ID_SETTINGS:
  609. show_settings_dialog();
  610. break;
  611. case ID_INSTALL_SERVICE:
  612. case ID_REMOVE_SERVICE:
  613. manage_service(LOWORD(wParam));
  614. break;
  615. case ID_CONNECT:
  616. printf("[%s]\n", get_url_to_first_open_port(ctx));
  617. ShellExecute(NULL, "open", get_url_to_first_open_port(ctx),
  618. NULL, NULL, SW_SHOW);
  619. break;
  620. }
  621. break;
  622. case WM_USER:
  623. switch (lParam) {
  624. case WM_RBUTTONUP:
  625. case WM_LBUTTONUP:
  626. case WM_LBUTTONDBLCLK:
  627. hMenu = CreatePopupMenu();
  628. AppendMenu(hMenu, MF_STRING | MF_GRAYED, ID_SEPARATOR, server_name);
  629. AppendMenu(hMenu, MF_SEPARATOR, ID_SEPARATOR, "");
  630. service_installed = manage_service(0);
  631. snprintf(buf, sizeof(buf), "NT service: %s installed",
  632. service_installed ? "" : "not");
  633. AppendMenu(hMenu, MF_STRING | MF_GRAYED, ID_SEPARATOR, buf);
  634. AppendMenu(hMenu, MF_STRING | (service_installed ? MF_GRAYED : 0),
  635. ID_INSTALL_SERVICE, "Install service");
  636. AppendMenu(hMenu, MF_STRING | (!service_installed ? MF_GRAYED : 0),
  637. ID_REMOVE_SERVICE, "Deinstall service");
  638. AppendMenu(hMenu, MF_SEPARATOR, ID_SEPARATOR, "");
  639. AppendMenu(hMenu, MF_STRING, ID_CONNECT, "Start browser");
  640. AppendMenu(hMenu, MF_STRING, ID_SETTINGS, "Edit Settings");
  641. AppendMenu(hMenu, MF_SEPARATOR, ID_SEPARATOR, "");
  642. AppendMenu(hMenu, MF_STRING, ID_QUIT, "Exit");
  643. GetCursorPos(&pt);
  644. SetForegroundWindow(hWnd);
  645. TrackPopupMenu(hMenu, 0, pt.x, pt.y, 0, hWnd, NULL);
  646. PostMessage(hWnd, WM_NULL, 0, 0);
  647. DestroyMenu(hMenu);
  648. break;
  649. }
  650. break;
  651. case WM_CLOSE:
  652. mg_stop(ctx);
  653. Shell_NotifyIcon(NIM_DELETE, &TrayIcon);
  654. PostQuitMessage(0);
  655. return 0; // We've just sent our own quit message, with proper hwnd.
  656. }
  657. return DefWindowProc(hWnd, msg, wParam, lParam);
  658. }
  659. int WINAPI WinMain(HINSTANCE hInst, HINSTANCE hPrev, LPSTR cmdline, int show) {
  660. WNDCLASS cls;
  661. HWND hWnd;
  662. MSG msg;
  663. init_server_name();
  664. memset(&cls, 0, sizeof(cls));
  665. cls.lpfnWndProc = (WNDPROC) WindowProc;
  666. cls.hIcon = LoadIcon(NULL, IDI_APPLICATION);
  667. cls.lpszClassName = server_name;
  668. RegisterClass(&cls);
  669. hWnd = CreateWindow(cls.lpszClassName, server_name, WS_OVERLAPPEDWINDOW,
  670. 0, 0, 0, 0, NULL, NULL, NULL, NULL);
  671. ShowWindow(hWnd, SW_HIDE);
  672. TrayIcon.cbSize = sizeof(TrayIcon);
  673. TrayIcon.uID = ID_ICON;
  674. TrayIcon.uFlags = NIF_ICON | NIF_MESSAGE | NIF_TIP;
  675. TrayIcon.hIcon = hIcon = LoadImage(GetModuleHandle(NULL),
  676. MAKEINTRESOURCE(ID_ICON),
  677. IMAGE_ICON, 16, 16, 0);
  678. TrayIcon.hWnd = hWnd;
  679. snprintf(TrayIcon.szTip, sizeof(TrayIcon.szTip), "%s", server_name);
  680. TrayIcon.uCallbackMessage = WM_USER;
  681. Shell_NotifyIcon(NIM_ADD, &TrayIcon);
  682. while (GetMessage(&msg, hWnd, 0, 0) > 0) {
  683. TranslateMessage(&msg);
  684. DispatchMessage(&msg);
  685. }
  686. // Return the WM_QUIT value.
  687. return msg.wParam;
  688. }
  689. #elif defined(USE_COCOA)
  690. #import <Cocoa/Cocoa.h>
  691. @interface Mongoose : NSObject<NSApplicationDelegate>
  692. - (void) openBrowser;
  693. - (void) shutDown;
  694. @end
  695. @implementation Mongoose
  696. - (void) openBrowser {
  697. [[NSWorkspace sharedWorkspace]
  698. openURL:[NSURL URLWithString:
  699. [NSString stringWithUTF8String:get_url_to_first_open_port(ctx)]]];
  700. }
  701. - (void) editConfig {
  702. create_config_file(config_file);
  703. [[NSWorkspace sharedWorkspace]
  704. openFile:[NSString stringWithUTF8String:config_file]
  705. withApplication:@"TextEdit"];
  706. }
  707. - (void)shutDown{
  708. [NSApp terminate:nil];
  709. }
  710. @end
  711. int main(int argc, char *argv[]) {
  712. init_server_name();
  713. start_mongoose(argc, argv);
  714. [NSAutoreleasePool new];
  715. [NSApplication sharedApplication];
  716. // Add delegate to process menu item actions
  717. Mongoose *myDelegate = [[Mongoose alloc] autorelease];
  718. [NSApp setDelegate: myDelegate];
  719. // Run this app as agent
  720. ProcessSerialNumber psn = { 0, kCurrentProcess };
  721. TransformProcessType(&psn, kProcessTransformToBackgroundApplication);
  722. SetFrontProcess(&psn);
  723. // Add status bar menu
  724. id menu = [[NSMenu new] autorelease];
  725. // Add version menu item
  726. [menu addItem:[[[NSMenuItem alloc]
  727. //initWithTitle:[NSString stringWithFormat:@"%s", server_name]
  728. initWithTitle:[NSString stringWithUTF8String:server_name]
  729. action:@selector(noexist) keyEquivalent:@""] autorelease]];
  730. // Add configuration menu item
  731. [menu addItem:[[[NSMenuItem alloc]
  732. initWithTitle:@"Edit configuration"
  733. action:@selector(editConfig) keyEquivalent:@""] autorelease]];
  734. // Add connect menu item
  735. [menu addItem:[[[NSMenuItem alloc]
  736. initWithTitle:@"Open web root in a browser"
  737. action:@selector(openBrowser) keyEquivalent:@""] autorelease]];
  738. // Separator
  739. [menu addItem:[NSMenuItem separatorItem]];
  740. // Add quit menu item
  741. [menu addItem:[[[NSMenuItem alloc]
  742. initWithTitle:@"Quit"
  743. action:@selector(shutDown) keyEquivalent:@"q"] autorelease]];
  744. // Attach menu to the status bar
  745. id item = [[[NSStatusBar systemStatusBar]
  746. statusItemWithLength:NSVariableStatusItemLength] retain];
  747. [item setHighlightMode:YES];
  748. [item setImage:[NSImage imageNamed:@"mongoose_22x22.png"]];
  749. [item setMenu:menu];
  750. // Run the app
  751. [NSApp activateIgnoringOtherApps:YES];
  752. [NSApp run];
  753. mg_stop(ctx);
  754. return EXIT_SUCCESS;
  755. }
  756. #else
  757. int main(int argc, char *argv[]) {
  758. init_server_name();
  759. start_mongoose(argc, argv);
  760. printf("%s started on port(s) %s with web root [%s]\n",
  761. server_name, mg_get_option(ctx, "listening_ports"),
  762. mg_get_option(ctx, "document_root"));
  763. while (exit_flag == 0) {
  764. sleep(1);
  765. }
  766. printf("Exiting on signal %d, waiting for all threads to finish...",
  767. exit_flag);
  768. fflush(stdout);
  769. mg_stop(ctx);
  770. printf("%s", " done.\n");
  771. return EXIT_SUCCESS;
  772. }
  773. #endif /* _WIN32 */