main.c 31 KB

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