main.c 28 KB

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