main.c 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991
  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. 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/docs/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. set_absolute_path(options, "document_root", argv[0]);
  317. set_absolute_path(options, "put_delete_auth_file", argv[0]);
  318. set_absolute_path(options, "cgi_interpreter", argv[0]);
  319. set_absolute_path(options, "access_log_file", argv[0]);
  320. set_absolute_path(options, "error_log_file", argv[0]);
  321. set_absolute_path(options, "global_auth_file", argv[0]);
  322. set_absolute_path(options, "ssl_certificate", argv[0]);
  323. // Make extra verification for certain options
  324. verify_existence(options, "document_root", 1);
  325. verify_existence(options, "cgi_interpreter", 0);
  326. verify_existence(options, "ssl_certificate", 0);
  327. // Setup signal handler: quit on Ctrl-C
  328. signal(SIGTERM, signal_handler);
  329. signal(SIGINT, signal_handler);
  330. // Start Civetweb
  331. memset(&callbacks, 0, sizeof(callbacks));
  332. callbacks.log_message = &log_message;
  333. ctx = mg_start(&callbacks, NULL, (const char **) options);
  334. for (i = 0; options[i] != NULL; i++) {
  335. free(options[i]);
  336. }
  337. if (ctx == NULL) {
  338. die("%s", "Failed to start Civetweb.");
  339. }
  340. }
  341. #ifdef _WIN32
  342. enum {
  343. ID_ICON = 100, ID_QUIT, ID_SETTINGS, ID_SEPARATOR, ID_INSTALL_SERVICE,
  344. ID_REMOVE_SERVICE, ID_STATIC, ID_GROUP, ID_SAVE, ID_RESET_DEFAULTS,
  345. ID_STATUS, ID_CONNECT,
  346. // All dynamically created text boxes for options have IDs starting from
  347. // ID_CONTROLS, incremented by one.
  348. ID_CONTROLS = 200,
  349. // Text boxes for files have "..." buttons to open file browser. These
  350. // buttons have IDs that are ID_FILE_BUTTONS_DELTA higher than associated
  351. // text box ID.
  352. ID_FILE_BUTTONS_DELTA = 1000
  353. };
  354. static HICON hIcon;
  355. static SERVICE_STATUS ss;
  356. static SERVICE_STATUS_HANDLE hStatus;
  357. static const char *service_magic_argument = "--";
  358. static NOTIFYICONDATA TrayIcon;
  359. static void WINAPI ControlHandler(DWORD code) {
  360. if (code == SERVICE_CONTROL_STOP || code == SERVICE_CONTROL_SHUTDOWN) {
  361. ss.dwWin32ExitCode = 0;
  362. ss.dwCurrentState = SERVICE_STOPPED;
  363. }
  364. SetServiceStatus(hStatus, &ss);
  365. }
  366. static void WINAPI ServiceMain(void) {
  367. ss.dwServiceType = SERVICE_WIN32;
  368. ss.dwCurrentState = SERVICE_RUNNING;
  369. ss.dwControlsAccepted = SERVICE_ACCEPT_STOP | SERVICE_ACCEPT_SHUTDOWN;
  370. hStatus = RegisterServiceCtrlHandler(server_name, ControlHandler);
  371. SetServiceStatus(hStatus, &ss);
  372. while (ss.dwCurrentState == SERVICE_RUNNING) {
  373. Sleep(1000);
  374. }
  375. mg_stop(ctx);
  376. ss.dwCurrentState = SERVICE_STOPPED;
  377. ss.dwWin32ExitCode = (DWORD) -1;
  378. SetServiceStatus(hStatus, &ss);
  379. }
  380. static void show_error(void) {
  381. char buf[256];
  382. FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
  383. NULL, GetLastError(),
  384. MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
  385. buf, sizeof(buf), NULL);
  386. MessageBox(NULL, buf, "Error", MB_OK);
  387. }
  388. static void *align(void *ptr, DWORD alig) {
  389. ULONG ul = (ULONG) ptr;
  390. ul += alig;
  391. ul &= ~alig;
  392. return ((void *) ul);
  393. }
  394. static int is_boolean_option(const char *option_name) {
  395. return !strcmp(option_name, "enable_directory_listing") ||
  396. !strcmp(option_name, "enable_keep_alive");
  397. }
  398. static int is_filename_option(const char *option_name) {
  399. return !strcmp(option_name, "cgi_interpreter") ||
  400. !strcmp(option_name, "global_auth_file") ||
  401. !strcmp(option_name, "put_delete_auth_file") ||
  402. !strcmp(option_name, "access_log_file") ||
  403. !strcmp(option_name, "error_log_file") ||
  404. !strcmp(option_name, "ssl_certificate");
  405. }
  406. static int is_directory_option(const char *option_name) {
  407. return !strcmp(option_name, "document_root");
  408. }
  409. static int is_numeric_options(const char *option_name) {
  410. return !strcmp(option_name, "num_threads");
  411. }
  412. static void save_config(HWND hDlg, FILE *fp) {
  413. char value[2000];
  414. const char **options, *name, *default_value;
  415. int i, id;
  416. fprintf(fp, "%s", config_file_top_comment);
  417. options = mg_get_valid_option_names();
  418. for (i = 0; options[i * 2] != NULL; i++) {
  419. name = options[i * 2];
  420. id = ID_CONTROLS + i;
  421. if (is_boolean_option(name)) {
  422. snprintf(value, sizeof(value), "%s",
  423. IsDlgButtonChecked(hDlg, id) ? "yes" : "no");
  424. } else {
  425. GetDlgItemText(hDlg, id, value, sizeof(value));
  426. }
  427. default_value = options[i * 2 + 1] == NULL ? "" : options[i * 2 + 1];
  428. // If value is the same as default, skip it
  429. if (strcmp(value, default_value) != 0) {
  430. fprintf(fp, "%s %s\n", name, value);
  431. }
  432. }
  433. }
  434. static BOOL CALLBACK DlgProc(HWND hDlg, UINT msg, WPARAM wParam, LPARAM lP) {
  435. FILE *fp;
  436. int i;
  437. const char *name, *value, **options = mg_get_valid_option_names();
  438. switch (msg) {
  439. case WM_CLOSE:
  440. DestroyWindow(hDlg);
  441. break;
  442. case WM_COMMAND:
  443. switch (LOWORD(wParam)) {
  444. case ID_SAVE:
  445. EnableWindow(GetDlgItem(hDlg, ID_SAVE), FALSE);
  446. if ((fp = fopen(config_file, "w+")) != NULL) {
  447. save_config(hDlg, fp);
  448. fclose(fp);
  449. mg_stop(ctx);
  450. start_civetweb(__argc, __argv);
  451. }
  452. EnableWindow(GetDlgItem(hDlg, ID_SAVE), TRUE);
  453. break;
  454. case ID_RESET_DEFAULTS:
  455. for (i = 0; options[i * 2] != NULL; i++) {
  456. name = options[i * 2];
  457. value = options[i * 2 + 1] == NULL ? "" : options[i * 2 + 1];
  458. if (is_boolean_option(name)) {
  459. CheckDlgButton(hDlg, ID_CONTROLS + i, !strcmp(value, "yes") ?
  460. BST_CHECKED : BST_UNCHECKED);
  461. } else {
  462. SetWindowText(GetDlgItem(hDlg, ID_CONTROLS + i), value);
  463. }
  464. }
  465. break;
  466. }
  467. for (i = 0; options[i * 2] != NULL; i++) {
  468. name = options[i * 2];
  469. if ((is_filename_option(name) || is_directory_option(name)) &&
  470. LOWORD(wParam) == ID_CONTROLS + i + ID_FILE_BUTTONS_DELTA) {
  471. OPENFILENAME of;
  472. BROWSEINFO bi;
  473. char path[PATH_MAX] = "";
  474. memset(&of, 0, sizeof(of));
  475. of.lStructSize = sizeof(of);
  476. of.hwndOwner = (HWND) hDlg;
  477. of.lpstrFile = path;
  478. of.nMaxFile = sizeof(path);
  479. of.lpstrInitialDir = mg_get_option(ctx, "document_root");
  480. of.Flags = OFN_CREATEPROMPT | OFN_NOCHANGEDIR;
  481. memset(&bi, 0, sizeof(bi));
  482. bi.hwndOwner = (HWND) hDlg;
  483. bi.lpszTitle = "Choose WWW root directory:";
  484. bi.ulFlags = BIF_RETURNONLYFSDIRS;
  485. if (is_directory_option(name)) {
  486. SHGetPathFromIDList(SHBrowseForFolder(&bi), path);
  487. } else {
  488. GetOpenFileName(&of);
  489. }
  490. if (path[0] != '\0') {
  491. SetWindowText(GetDlgItem(hDlg, ID_CONTROLS + i), path);
  492. }
  493. }
  494. }
  495. break;
  496. case WM_INITDIALOG:
  497. SendMessage(hDlg, WM_SETICON,(WPARAM) ICON_SMALL, (LPARAM) hIcon);
  498. SendMessage(hDlg, WM_SETICON,(WPARAM) ICON_BIG, (LPARAM) hIcon);
  499. SetWindowText(hDlg, "Civetweb settings");
  500. SetFocus(GetDlgItem(hDlg, ID_SAVE));
  501. for (i = 0; options[i * 2] != NULL; i++) {
  502. name = options[i * 2];
  503. value = mg_get_option(ctx, name);
  504. if (is_boolean_option(name)) {
  505. CheckDlgButton(hDlg, ID_CONTROLS + i, !strcmp(value, "yes") ?
  506. BST_CHECKED : BST_UNCHECKED);
  507. } else {
  508. SetDlgItemText(hDlg, ID_CONTROLS + i, value == NULL ? "" : value);
  509. }
  510. }
  511. break;
  512. default:
  513. break;
  514. }
  515. return FALSE;
  516. }
  517. static void add_control(unsigned char **mem, DLGTEMPLATE *dia, WORD type,
  518. DWORD id, DWORD style, WORD x, WORD y,
  519. WORD cx, WORD cy, const char *caption) {
  520. DLGITEMTEMPLATE *tp;
  521. LPWORD p;
  522. dia->cdit++;
  523. *mem = align(*mem, 3);
  524. tp = (DLGITEMTEMPLATE *) *mem;
  525. tp->id = (WORD)id;
  526. tp->style = style;
  527. tp->dwExtendedStyle = 0;
  528. tp->x = x;
  529. tp->y = y;
  530. tp->cx = cx;
  531. tp->cy = cy;
  532. p = align(*mem + sizeof(*tp), 1);
  533. *p++ = 0xffff;
  534. *p++ = type;
  535. while (*caption != '\0') {
  536. *p++ = (WCHAR) *caption++;
  537. }
  538. *p++ = 0;
  539. p = align(p, 1);
  540. *p++ = 0;
  541. *mem = (unsigned char *) p;
  542. }
  543. static void show_settings_dialog() {
  544. #define HEIGHT 15
  545. #define WIDTH 400
  546. #define LABEL_WIDTH 80
  547. unsigned char mem[4096], *p;
  548. const char **option_names, *long_option_name;
  549. DWORD style;
  550. DLGTEMPLATE *dia = (DLGTEMPLATE *) mem;
  551. WORD i, cl, x, y, width, nelems = 0;
  552. static int guard;
  553. static struct {
  554. DLGTEMPLATE template; // 18 bytes
  555. WORD menu, class;
  556. wchar_t caption[1];
  557. WORD fontsiz;
  558. wchar_t fontface[7];
  559. } dialog_header = {{WS_CAPTION | WS_POPUP | WS_SYSMENU | WS_VISIBLE |
  560. DS_SETFONT | WS_DLGFRAME, WS_EX_TOOLWINDOW, 0, 200, 200, WIDTH, 0},
  561. 0, 0, L"", 8, L"Tahoma"};
  562. if (guard == 0) {
  563. guard++;
  564. } else {
  565. return;
  566. }
  567. (void) memset(mem, 0, sizeof(mem));
  568. (void) memcpy(mem, &dialog_header, sizeof(dialog_header));
  569. p = mem + sizeof(dialog_header);
  570. option_names = mg_get_valid_option_names();
  571. for (i = 0; option_names[i * 2] != NULL; i++) {
  572. long_option_name = option_names[i * 2];
  573. style = WS_CHILD | WS_VISIBLE | WS_TABSTOP;
  574. x = 10 + (WIDTH / 2) * (nelems % 2);
  575. y = (nelems/2 + 1) * HEIGHT + 5;
  576. width = WIDTH / 2 - 20 - LABEL_WIDTH;
  577. if (is_numeric_options(long_option_name)) {
  578. style |= ES_NUMBER;
  579. cl = 0x81;
  580. style |= WS_BORDER | ES_AUTOHSCROLL;
  581. } else if (is_boolean_option(long_option_name)) {
  582. cl = 0x80;
  583. style |= BS_AUTOCHECKBOX;
  584. } else if (is_filename_option(long_option_name) ||
  585. is_directory_option(long_option_name)) {
  586. style |= WS_BORDER | ES_AUTOHSCROLL;
  587. width -= 20;
  588. cl = 0x81;
  589. add_control(&p, dia, 0x80,
  590. ID_CONTROLS + i + ID_FILE_BUTTONS_DELTA,
  591. WS_VISIBLE | WS_CHILD | BS_PUSHBUTTON,
  592. (WORD) (x + width + LABEL_WIDTH + 5),
  593. y, 15, 12, "...");
  594. } else {
  595. cl = 0x81;
  596. style |= WS_BORDER | ES_AUTOHSCROLL;
  597. }
  598. add_control(&p, dia, 0x82, ID_STATIC, WS_VISIBLE | WS_CHILD,
  599. x, y, LABEL_WIDTH, HEIGHT, long_option_name);
  600. add_control(&p, dia, cl, ID_CONTROLS + i, style,
  601. (WORD) (x + LABEL_WIDTH), y, width, 12, "");
  602. nelems++;
  603. }
  604. y = (WORD) (((nelems + 1) / 2 + 1) * HEIGHT + 5);
  605. add_control(&p, dia, 0x80, ID_GROUP, WS_CHILD | WS_VISIBLE |
  606. BS_GROUPBOX, 5, 5, WIDTH - 10, y, " Settings ");
  607. y += 10;
  608. add_control(&p, dia, 0x80, ID_SAVE,
  609. WS_CHILD | WS_VISIBLE | BS_PUSHBUTTON | WS_TABSTOP,
  610. WIDTH - 70, y, 65, 12, "Save Settings");
  611. add_control(&p, dia, 0x80, ID_RESET_DEFAULTS,
  612. WS_CHILD | WS_VISIBLE | BS_PUSHBUTTON | WS_TABSTOP,
  613. WIDTH - 140, y, 65, 12, "Reset to defaults");
  614. add_control(&p, dia, 0x82, ID_STATIC,
  615. WS_CHILD | WS_VISIBLE | WS_DISABLED,
  616. 5, y, 180, 12, server_name);
  617. dia->cy = ((nelems + 1) / 2 + 1) * HEIGHT + 30;
  618. DialogBoxIndirectParam(NULL, dia, NULL, DlgProc, (LPARAM) NULL);
  619. guard--;
  620. }
  621. static int manage_service(int action) {
  622. static const char *service_name = "Civetweb";
  623. SC_HANDLE hSCM = NULL, hService = NULL;
  624. SERVICE_DESCRIPTION descr = {server_name};
  625. char path[PATH_MAX + 20]; // Path to executable plus magic argument
  626. int success = 1;
  627. if ((hSCM = OpenSCManager(NULL, NULL, action == ID_INSTALL_SERVICE ?
  628. GENERIC_WRITE : GENERIC_READ)) == NULL) {
  629. success = 0;
  630. show_error();
  631. } else if (action == ID_INSTALL_SERVICE) {
  632. GetModuleFileName(NULL, path, sizeof(path));
  633. strncat(path, " ", sizeof(path));
  634. strncat(path, service_magic_argument, sizeof(path));
  635. hService = CreateService(hSCM, service_name, service_name,
  636. SERVICE_ALL_ACCESS, SERVICE_WIN32_OWN_PROCESS,
  637. SERVICE_AUTO_START, SERVICE_ERROR_NORMAL,
  638. path, NULL, NULL, NULL, NULL, NULL);
  639. if (hService) {
  640. ChangeServiceConfig2(hService, SERVICE_CONFIG_DESCRIPTION, &descr);
  641. } else {
  642. show_error();
  643. }
  644. } else if (action == ID_REMOVE_SERVICE) {
  645. if ((hService = OpenService(hSCM, service_name, DELETE)) == NULL ||
  646. !DeleteService(hService)) {
  647. show_error();
  648. }
  649. } else if ((hService = OpenService(hSCM, service_name,
  650. SERVICE_QUERY_STATUS)) == NULL) {
  651. success = 0;
  652. }
  653. CloseServiceHandle(hService);
  654. CloseServiceHandle(hSCM);
  655. return success;
  656. }
  657. static LRESULT CALLBACK WindowProc(HWND hWnd, UINT msg, WPARAM wParam,
  658. LPARAM lParam) {
  659. static SERVICE_TABLE_ENTRY service_table[] = {
  660. {server_name, (LPSERVICE_MAIN_FUNCTION) ServiceMain},
  661. {NULL, NULL}
  662. };
  663. int service_installed;
  664. char buf[200], *service_argv[] = {__argv[0], NULL};
  665. POINT pt;
  666. HMENU hMenu;
  667. static UINT s_uTaskbarRestart; // for taskbar creation
  668. switch (msg) {
  669. case WM_CREATE:
  670. if (__argv[1] != NULL &&
  671. !strcmp(__argv[1], service_magic_argument)) {
  672. start_civetweb(1, service_argv);
  673. StartServiceCtrlDispatcher(service_table);
  674. exit(EXIT_SUCCESS);
  675. } else {
  676. start_civetweb(__argc, __argv);
  677. s_uTaskbarRestart = RegisterWindowMessage(TEXT("TaskbarCreated"));
  678. }
  679. break;
  680. case WM_COMMAND:
  681. switch (LOWORD(wParam)) {
  682. case ID_QUIT:
  683. mg_stop(ctx);
  684. Shell_NotifyIcon(NIM_DELETE, &TrayIcon);
  685. PostQuitMessage(0);
  686. return 0;
  687. case ID_SETTINGS:
  688. show_settings_dialog();
  689. break;
  690. case ID_INSTALL_SERVICE:
  691. case ID_REMOVE_SERVICE:
  692. manage_service(LOWORD(wParam));
  693. break;
  694. case ID_CONNECT:
  695. printf("[%s]\n", get_url_to_first_open_port(ctx));
  696. ShellExecute(NULL, "open", get_url_to_first_open_port(ctx),
  697. NULL, NULL, SW_SHOW);
  698. break;
  699. }
  700. break;
  701. case WM_USER:
  702. switch (lParam) {
  703. case WM_RBUTTONUP:
  704. case WM_LBUTTONUP:
  705. case WM_LBUTTONDBLCLK:
  706. hMenu = CreatePopupMenu();
  707. AppendMenu(hMenu, MF_STRING | MF_GRAYED, ID_SEPARATOR, server_name);
  708. AppendMenu(hMenu, MF_SEPARATOR, ID_SEPARATOR, "");
  709. service_installed = manage_service(0);
  710. snprintf(buf, sizeof(buf), "NT service: %s installed",
  711. service_installed ? "" : "not");
  712. AppendMenu(hMenu, MF_STRING | MF_GRAYED, ID_SEPARATOR, buf);
  713. AppendMenu(hMenu, MF_STRING | (service_installed ? MF_GRAYED : 0),
  714. ID_INSTALL_SERVICE, "Install service");
  715. AppendMenu(hMenu, MF_STRING | (!service_installed ? MF_GRAYED : 0),
  716. ID_REMOVE_SERVICE, "Deinstall service");
  717. AppendMenu(hMenu, MF_SEPARATOR, ID_SEPARATOR, "");
  718. AppendMenu(hMenu, MF_STRING, ID_CONNECT, "Start browser");
  719. AppendMenu(hMenu, MF_STRING, ID_SETTINGS, "Edit Settings");
  720. AppendMenu(hMenu, MF_SEPARATOR, ID_SEPARATOR, "");
  721. AppendMenu(hMenu, MF_STRING, ID_QUIT, "Exit");
  722. GetCursorPos(&pt);
  723. SetForegroundWindow(hWnd);
  724. TrackPopupMenu(hMenu, 0, pt.x, pt.y, 0, hWnd, NULL);
  725. PostMessage(hWnd, WM_NULL, 0, 0);
  726. DestroyMenu(hMenu);
  727. break;
  728. }
  729. break;
  730. case WM_CLOSE:
  731. mg_stop(ctx);
  732. Shell_NotifyIcon(NIM_DELETE, &TrayIcon);
  733. PostQuitMessage(0);
  734. return 0; // We've just sent our own quit message, with proper hwnd.
  735. default:
  736. if (msg==s_uTaskbarRestart)
  737. Shell_NotifyIcon(NIM_ADD, &TrayIcon);
  738. }
  739. return DefWindowProc(hWnd, msg, wParam, lParam);
  740. }
  741. int WINAPI WinMain(HINSTANCE hInst, HINSTANCE hPrev, LPSTR cmdline, int show) {
  742. WNDCLASS cls;
  743. HWND hWnd;
  744. MSG msg;
  745. init_server_name();
  746. memset(&cls, 0, sizeof(cls));
  747. cls.lpfnWndProc = (WNDPROC) WindowProc;
  748. cls.hIcon = LoadIcon(NULL, IDI_APPLICATION);
  749. cls.lpszClassName = server_name;
  750. RegisterClass(&cls);
  751. hWnd = CreateWindow(cls.lpszClassName, server_name, WS_OVERLAPPEDWINDOW,
  752. 0, 0, 0, 0, NULL, NULL, NULL, NULL);
  753. ShowWindow(hWnd, SW_HIDE);
  754. TrayIcon.cbSize = sizeof(TrayIcon);
  755. TrayIcon.uID = ID_ICON;
  756. TrayIcon.uFlags = NIF_ICON | NIF_MESSAGE | NIF_TIP;
  757. TrayIcon.hIcon = hIcon = LoadImage(GetModuleHandle(NULL),
  758. MAKEINTRESOURCE(ID_ICON),
  759. IMAGE_ICON, 16, 16, 0);
  760. TrayIcon.hWnd = hWnd;
  761. snprintf(TrayIcon.szTip, sizeof(TrayIcon.szTip), "%s", server_name);
  762. TrayIcon.uCallbackMessage = WM_USER;
  763. Shell_NotifyIcon(NIM_ADD, &TrayIcon);
  764. while (GetMessage(&msg, hWnd, 0, 0) > 0) {
  765. TranslateMessage(&msg);
  766. DispatchMessage(&msg);
  767. }
  768. // Return the WM_QUIT value.
  769. return msg.wParam;
  770. }
  771. #elif defined(USE_COCOA)
  772. #import <Cocoa/Cocoa.h>
  773. @interface Civetweb : NSObject<NSApplicationDelegate>
  774. - (void) openBrowser;
  775. - (void) shutDown;
  776. @end
  777. @implementation Civetweb
  778. - (void) openBrowser {
  779. [[NSWorkspace sharedWorkspace]
  780. openURL:[NSURL URLWithString:
  781. [NSString stringWithUTF8String:get_url_to_first_open_port(ctx)]]];
  782. }
  783. - (void) editConfig {
  784. create_config_file(config_file);
  785. [[NSWorkspace sharedWorkspace]
  786. openFile:[NSString stringWithUTF8String:config_file]
  787. withApplication:@"TextEdit"];
  788. }
  789. - (void)shutDown{
  790. [NSApp terminate:nil];
  791. }
  792. @end
  793. int main(int argc, char *argv[]) {
  794. init_server_name();
  795. start_civetweb(argc, argv);
  796. [NSAutoreleasePool new];
  797. [NSApplication sharedApplication];
  798. // Add delegate to process menu item actions
  799. Civetweb *myDelegate = [[Civetweb alloc] autorelease];
  800. [NSApp setDelegate: myDelegate];
  801. // Run this app as agent
  802. ProcessSerialNumber psn = { 0, kCurrentProcess };
  803. TransformProcessType(&psn, kProcessTransformToBackgroundApplication);
  804. SetFrontProcess(&psn);
  805. // Add status bar menu
  806. id menu = [[NSMenu new] autorelease];
  807. // Add version menu item
  808. [menu addItem:[[[NSMenuItem alloc]
  809. //initWithTitle:[NSString stringWithFormat:@"%s", server_name]
  810. initWithTitle:[NSString stringWithUTF8String:server_name]
  811. action:@selector(noexist) keyEquivalent:@""] autorelease]];
  812. // Add configuration menu item
  813. [menu addItem:[[[NSMenuItem alloc]
  814. initWithTitle:@"Edit configuration"
  815. action:@selector(editConfig) keyEquivalent:@""] autorelease]];
  816. // Add connect menu item
  817. [menu addItem:[[[NSMenuItem alloc]
  818. initWithTitle:@"Open web root in a browser"
  819. action:@selector(openBrowser) keyEquivalent:@""] autorelease]];
  820. // Separator
  821. [menu addItem:[NSMenuItem separatorItem]];
  822. // Add quit menu item
  823. [menu addItem:[[[NSMenuItem alloc]
  824. initWithTitle:@"Quit"
  825. action:@selector(shutDown) keyEquivalent:@"q"] autorelease]];
  826. // Attach menu to the status bar
  827. id item = [[[NSStatusBar systemStatusBar]
  828. statusItemWithLength:NSVariableStatusItemLength] retain];
  829. [item setHighlightMode:YES];
  830. [item setImage:[NSImage imageNamed:@"civetweb_22x22.png"]];
  831. [item setMenu:menu];
  832. // Run the app
  833. [NSApp activateIgnoringOtherApps:YES];
  834. [NSApp run];
  835. mg_stop(ctx);
  836. return EXIT_SUCCESS;
  837. }
  838. #else
  839. int main(int argc, char *argv[]) {
  840. init_server_name();
  841. start_civetweb(argc, argv);
  842. printf("%s started on port(s) %s with web root [%s]\n",
  843. server_name, mg_get_option(ctx, "listening_ports"),
  844. mg_get_option(ctx, "document_root"));
  845. while (exit_flag == 0) {
  846. sleep(1);
  847. }
  848. printf("Exiting on signal %d, waiting for all threads to finish...",
  849. exit_flag);
  850. fflush(stdout);
  851. mg_stop(ctx);
  852. printf("%s", " done.\n");
  853. return EXIT_SUCCESS;
  854. }
  855. #endif /* _WIN32 */