main.c 31 KB

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