main.c 39 KB

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