main.c 30 KB

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