main.c 27 KB

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