main.c 33 KB

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