main.c 32 KB

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