main.c 53 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689
  1. /* Copyright (c) 2013-2015 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. #ifndef _WIN32_WINNT
  44. #define _WIN32_WINNT 0x0501 /* Target Windows XP or higher */
  45. #endif
  46. #include <windows.h>
  47. #include <winsvc.h>
  48. #include <shlobj.h>
  49. #include <io.h>
  50. #define getcwd(a,b) _getcwd(a,b)
  51. #if !defined(__MINGW32__)
  52. extern char *_getcwd(char *buf, size_t size);
  53. #endif
  54. static int guard = 0; /* test if any dialog is already open */
  55. #ifndef PATH_MAX
  56. #define PATH_MAX MAX_PATH
  57. #endif
  58. #ifndef S_ISDIR
  59. #define S_ISDIR(x) ((x) & _S_IFDIR)
  60. #endif
  61. #define DIRSEP '\\'
  62. #define snprintf _snprintf
  63. #define vsnprintf _vsnprintf
  64. #define sleep(x) Sleep((x) * 1000)
  65. #define WINCDECL __cdecl
  66. #define abs_path(rel, abs, abs_size) _fullpath((abs), (rel), (abs_size))
  67. #else
  68. #include <sys/wait.h>
  69. #include <unistd.h>
  70. #define DIRSEP '/'
  71. #define WINCDECL
  72. #define abs_path(rel, abs, abs_size) realpath((rel), (abs))
  73. #endif /* _WIN32 */
  74. #define MAX_OPTIONS 50
  75. #define MAX_CONF_FILE_LINE_SIZE (8 * 1024)
  76. static int exit_flag = 0; /* Main loop should exit */
  77. static char server_base_name[40]; /* Set by init_server_name() */
  78. static char *server_name; /* Set by init_server_name() */
  79. static char *icon_name; /* Set by init_server_name() */
  80. static char config_file[PATH_MAX] = ""; /* Set by process_command_line_arguments() */
  81. static struct mg_context *ctx; /* Set by start_civetweb() */
  82. #if !defined(CONFIG_FILE)
  83. #define CONFIG_FILE "civetweb.conf"
  84. #endif /* !CONFIG_FILE */
  85. #if !defined(PASSWORDS_FILE_NAME)
  86. #define PASSWORDS_FILE_NAME ".htpasswd"
  87. #endif
  88. /* backup config file */
  89. #if !defined(CONFIG_FILE2) && defined(LINUX)
  90. #define CONFIG_FILE2 "/usr/local/etc/civetweb.conf"
  91. #endif
  92. enum {
  93. OPTION_TITLE,
  94. OPTION_ICON,
  95. NUM_MAIN_OPTIONS
  96. };
  97. static struct mg_option main_config_options[] = {
  98. {"title", CONFIG_TYPE_STRING, NULL},
  99. {"icon", CONFIG_TYPE_STRING, NULL},
  100. {NULL, CONFIG_TYPE_UNKNOWN, NULL}
  101. };
  102. static void WINCDECL signal_handler(int sig_num)
  103. {
  104. exit_flag = sig_num;
  105. }
  106. static void die(const char *fmt, ...)
  107. {
  108. va_list ap;
  109. char msg[200] = "";
  110. va_start(ap, fmt);
  111. (void) vsnprintf(msg, sizeof(msg) -1, fmt, ap);
  112. msg[sizeof(msg)-1] = 0;
  113. va_end(ap);
  114. #if defined(_WIN32)
  115. MessageBox(NULL, msg, "Error", MB_OK);
  116. #else
  117. fprintf(stderr, "%s\n", msg);
  118. #endif
  119. exit(EXIT_FAILURE);
  120. }
  121. #ifdef WIN32
  122. static int MakeConsole();
  123. #endif
  124. static void show_usage_and_exit(const char *exeName)
  125. {
  126. const struct mg_option *options;
  127. int i;
  128. #ifdef WIN32
  129. MakeConsole();
  130. #endif
  131. if (exeName==0 || *exeName==0) {
  132. exeName = "civetweb";
  133. }
  134. fprintf(stderr, "Civetweb v%s, built on %s\n",
  135. mg_version(), __DATE__);
  136. fprintf(stderr, "Usage:\n");
  137. fprintf(stderr, " Start server with a set of options:\n");
  138. fprintf(stderr, " %s [config_file]\n", exeName);
  139. fprintf(stderr, " %s [-option value ...]\n", exeName);
  140. fprintf(stderr, " Add user/change password:\n");
  141. fprintf(stderr, " %s -A <htpasswd_file> <realm> <user> <passwd>\n", exeName);
  142. fprintf(stderr, " Remove user:\n");
  143. fprintf(stderr, " %s -R <htpasswd_file> <realm> <user>\n", exeName);
  144. fprintf(stderr, "\nOPTIONS:\n");
  145. options = mg_get_valid_options();
  146. for (i = 0; options[i].name != NULL; i++) {
  147. fprintf(stderr, " -%s %s\n", options[i].name, ((options[i].default_value == NULL) ? "<empty>" : options[i].default_value));
  148. }
  149. options = main_config_options;
  150. for (i = 0; options[i].name != NULL; i++) {
  151. fprintf(stderr, " -%s %s\n", options[i].name, ((options[i].default_value == NULL) ? "<empty>" : options[i].default_value));
  152. }
  153. exit(EXIT_FAILURE);
  154. }
  155. #if defined(_WIN32) || defined(USE_COCOA)
  156. static const char *config_file_top_comment =
  157. "# Civetweb web server configuration file.\n"
  158. "# For detailed description of every option, visit\n"
  159. "# https://github.com/bel2125/civetweb/blob/master/docs/UserManual.md\n"
  160. "# Lines starting with '#' and empty lines are ignored.\n"
  161. "# To make a change, remove leading '#', modify option's value,\n"
  162. "# save this file and then restart Civetweb.\n\n";
  163. static const char *get_url_to_first_open_port(const struct mg_context *ctx)
  164. {
  165. static char url[100];
  166. const char *open_ports = mg_get_option(ctx, "listening_ports");
  167. int a, b, c, d, port, n;
  168. if (sscanf(open_ports, "%d.%d.%d.%d:%d%n", &a, &b, &c, &d, &port, &n) == 5) {
  169. snprintf(url, sizeof(url), "%s://%d.%d.%d.%d:%d",
  170. open_ports[n] == 's' ? "https" : "http", a, b, c, d, port);
  171. } else if (sscanf(open_ports, "%d%n", &port, &n) == 1) {
  172. snprintf(url, sizeof(url), "%s://localhost:%d",
  173. open_ports[n] == 's' ? "https" : "http", port);
  174. } else {
  175. snprintf(url, sizeof(url), "%s", "http://localhost:8080");
  176. }
  177. return url;
  178. }
  179. static void create_config_file(const char *path)
  180. {
  181. const struct mg_option *options;
  182. const char *value;
  183. FILE *fp;
  184. int i;
  185. /* Create config file if it is not present yet */
  186. if ((fp = fopen(path, "r")) != NULL) {
  187. fclose(fp);
  188. } else if ((fp = fopen(path, "a+")) != NULL) {
  189. fprintf(fp, "%s", config_file_top_comment);
  190. options = mg_get_valid_options();
  191. for (i = 0; options[i].name != NULL; i++) {
  192. value = mg_get_option(ctx, options[i].name);
  193. fprintf(fp, "# %s %s\n", options[i].name, value ? value : "<value>");
  194. }
  195. fclose(fp);
  196. }
  197. }
  198. #endif
  199. static char *sdup(const char *str)
  200. {
  201. size_t len;
  202. char *p;
  203. len = strlen(str) + 1;
  204. if ((p = (char *) malloc(len)) != NULL) {
  205. memcpy(p, str, len);
  206. }
  207. return p;
  208. }
  209. static const char *get_option(char **options, const char *option_name)
  210. {
  211. int i = 0;
  212. const char *opt_value = NULL;
  213. /* TODO: options should be an array of key-value-pairs, like
  214. struct {const char * key, const char * value} options[]
  215. but it currently is an array with
  216. options[2*i] = key, options[2*i + 1] = value
  217. */
  218. while (options[2*i] != NULL) {
  219. if (strcmp(options[2*i], option_name) == 0) {
  220. opt_value = options[2*i + 1];
  221. break;
  222. }
  223. i++;
  224. }
  225. return opt_value;
  226. }
  227. static int set_option(char **options, const char *name, const char *value)
  228. {
  229. int i, type;
  230. const struct mg_option *default_options = mg_get_valid_options();
  231. for (i = 0; main_config_options[i].name != NULL; i++) {
  232. if (0==strcmp(name, main_config_options[i].name)) {
  233. /* This option is evaluated by main.c, not civetweb.c - just skip it and return OK */
  234. return 1;
  235. }
  236. }
  237. type = CONFIG_TYPE_UNKNOWN;
  238. for (i = 0; default_options[i].name != NULL; i++) {
  239. if (!strcmp(default_options[i].name, name)) {
  240. type = default_options[i].type;
  241. }
  242. }
  243. switch (type) {
  244. case CONFIG_TYPE_UNKNOWN:
  245. /* unknown option */
  246. return 0;
  247. case CONFIG_TYPE_NUMBER:
  248. /* integer number > 0, e.g. number of threads */
  249. if (atol(value)<1) {
  250. /* invalid number */
  251. return 0;
  252. }
  253. break;
  254. case CONFIG_TYPE_STRING:
  255. /* any text */
  256. break;
  257. case CONFIG_TYPE_BOOLEAN:
  258. /* boolean value, yes or no */
  259. if ((0!=strcmp(value,"yes")) && (0!=strcmp(value,"no"))) {
  260. /* invalid boolean */
  261. return 0;
  262. }
  263. break;
  264. case CONFIG_TYPE_FILE:
  265. case CONFIG_TYPE_DIRECTORY:
  266. /* TODO: check this option when it is set, instead of calling verify_existence later */
  267. break;
  268. case CONFIG_TYPE_EXT_PATTERN:
  269. /* list of file extentions */
  270. break;
  271. default:
  272. die("Unknown option type - option %s", name);
  273. break;
  274. }
  275. for (i = 0; i < MAX_OPTIONS; i++) {
  276. if (options[2*i] == NULL) {
  277. options[2*i] = sdup(name);
  278. options[2*i + 1] = sdup(value);
  279. options[2*i + 2] = NULL;
  280. break;
  281. } else if (!strcmp(options[2*i], name)) {
  282. free(options[2*i + 1]);
  283. options[2*i + 1] = sdup(value);
  284. break;
  285. }
  286. }
  287. if (i == MAX_OPTIONS) {
  288. die("Too many options specified");
  289. }
  290. if (options[2*i] == NULL || options[2*i + 1] == NULL) {
  291. die("Out of memory");
  292. }
  293. /* option set correctly */
  294. return 1;
  295. }
  296. static void read_config_file(const char *config_file, char **options)
  297. {
  298. char line[MAX_CONF_FILE_LINE_SIZE], *p;
  299. FILE *fp = NULL;
  300. size_t i, j, cmd_line_opts_start = 1, line_no = 0;
  301. fp = fopen(config_file, "r");
  302. /* If config file was set in command line and open failed, die */
  303. if (cmd_line_opts_start == 2 && fp == NULL) {
  304. die("Cannot open config file %s: %s", config_file, strerror(errno));
  305. }
  306. /* Load config file settings first */
  307. if (fp != NULL) {
  308. fprintf(stderr, "Loading config file %s\n", config_file);
  309. /* Loop over the lines in config file */
  310. while (fgets(line, sizeof(line), fp) != NULL) {
  311. if (!line_no && !memcmp(line,"\xEF\xBB\xBF",3)) {
  312. /* strip UTF-8 BOM */
  313. p = line+3;
  314. } else {
  315. p = line;
  316. }
  317. line_no++;
  318. /* Ignore empty lines and comments */
  319. for (i = 0; isspace(* (unsigned char *) &line[i]); ) i++;
  320. if (p[i] == '#' || p[i] == '\0') {
  321. continue;
  322. }
  323. /* Skip spaces, \r and \n at the end of the line */
  324. for (j = strlen(line)-1; isspace(* (unsigned char *) &line[j]) || iscntrl(* (unsigned char *) &line[j]); ) line[j--]=0;
  325. /* Find the space character between option name and value */
  326. for (j=i; !isspace(* (unsigned char *) &line[j]) && (line[j]!=0); ) j++;
  327. /* Terminate the string - then the string at (line+i) contains the option name */
  328. line[j] = 0;
  329. j++;
  330. /* Trim additional spaces between option name and value - then (line+j) contains the option value */
  331. while (isspace(line[j])) j++;
  332. /* Set option */
  333. if (!set_option(options, line+i, line+j)) {
  334. printf("%s: line %d is invalid, ignoring it:\n %s",
  335. config_file, (int) line_no, p);
  336. }
  337. }
  338. (void) fclose(fp);
  339. }
  340. }
  341. static void process_command_line_arguments(char *argv[], char **options)
  342. {
  343. char *p;
  344. size_t i, cmd_line_opts_start = 1;
  345. #ifdef CONFIG_FILE2
  346. FILE *fp = NULL;
  347. #endif
  348. /* Should we use a config file ? */
  349. if (argv[1] != NULL && argv[1][0] != '-') {
  350. snprintf(config_file, sizeof(config_file), "%s", argv[1]);
  351. cmd_line_opts_start = 2;
  352. } else if ((p = strrchr(argv[0], DIRSEP)) == NULL) {
  353. /* No command line flags specified. Look where binary lives */
  354. snprintf(config_file, sizeof(config_file)-1, "%s", CONFIG_FILE);
  355. config_file[sizeof(config_file)-1] = 0;
  356. } else {
  357. snprintf(config_file, sizeof(config_file)-1, "%.*s%c%s",
  358. (int) (p - argv[0]), argv[0], DIRSEP, CONFIG_FILE);
  359. config_file[sizeof(config_file)-1] = 0;
  360. }
  361. #ifdef CONFIG_FILE2
  362. fp = fopen(config_file, "r");
  363. /* try alternate config file */
  364. if (fp == NULL) {
  365. fp = fopen(CONFIG_FILE2, "r");
  366. if (fp != NULL) {
  367. strcpy(config_file, CONFIG_FILE2);
  368. }
  369. }
  370. if (fp != NULL) {
  371. fclose(fp);
  372. }
  373. #endif
  374. /* read all configurations from a config file */
  375. (void)read_config_file(config_file, options);
  376. /* If we're under MacOS and started by launchd, then the second
  377. argument is process serial number, -psn_.....
  378. In this case, don't process arguments at all. */
  379. if (argv[1] == NULL || memcmp(argv[1], "-psn_", 5) != 0) {
  380. /* Handle command line flags.
  381. They override config file and default settings. */
  382. for (i = cmd_line_opts_start; argv[i] != NULL; i += 2) {
  383. if (argv[i][0] != '-' || argv[i + 1] == NULL) {
  384. show_usage_and_exit(argv[0]);
  385. }
  386. if (!set_option(options, &argv[i][1], argv[i + 1])) {
  387. printf("command line option is invalid, ignoring it:\n %s %s\n",
  388. argv[i], argv[i + 1]);
  389. }
  390. }
  391. }
  392. }
  393. static void init_server_name(int argc, const char *argv[])
  394. {
  395. int i;
  396. assert(sizeof(main_config_options)/sizeof(main_config_options[0]) == NUM_MAIN_OPTIONS+1);
  397. assert((strlen(mg_version())+12)<sizeof(server_base_name));
  398. snprintf(server_base_name, sizeof(server_base_name), "Civetweb V%s",
  399. mg_version());
  400. server_name = server_base_name;
  401. for (i=0; i<argc-1; i++) {
  402. if ((argv[i][0]=='-') && (0==strcmp(argv[i]+1, main_config_options[OPTION_TITLE].name))) {
  403. server_name = (char*)(argv[i+1]);
  404. }
  405. }
  406. icon_name = NULL;
  407. for (i=0; i<argc-1; i++) {
  408. if ((argv[i][0]=='-') && (0==strcmp(argv[i]+1, main_config_options[OPTION_ICON].name))) {
  409. icon_name = (char*)(argv[i+1]);
  410. }
  411. }
  412. }
  413. static int log_message(const struct mg_connection *conn, const char *message)
  414. {
  415. (void) conn;
  416. printf("%s\n", message);
  417. return 0;
  418. }
  419. static int is_path_absolute(const char *path)
  420. {
  421. #ifdef _WIN32
  422. return path != NULL &&
  423. ((path[0] == '\\' && path[1] == '\\') || /* UNC path, e.g.
  424. \\server\dir */
  425. (isalpha(path[0]) && path[1] == ':' && path[2] == '\\')); /* E.g. X:\dir */
  426. #else
  427. return path != NULL && path[0] == '/';
  428. #endif
  429. }
  430. static void verify_existence(char **options, const char *option_name,
  431. int must_be_dir)
  432. {
  433. struct stat st;
  434. const char *path = get_option(options, option_name);
  435. #ifdef _WIN32
  436. wchar_t wbuf[1024];
  437. char mbbuf[1024];
  438. int len;
  439. if (path) {
  440. memset(wbuf, 0, sizeof(wbuf));
  441. memset(mbbuf, 0, sizeof(mbbuf));
  442. len = MultiByteToWideChar(CP_UTF8, 0, path, -1, wbuf, (int) sizeof(wbuf)/sizeof(wbuf[0])-1);
  443. wcstombs(mbbuf, wbuf, sizeof(mbbuf)-1);
  444. path = mbbuf;
  445. }
  446. #endif
  447. if (path != NULL && (stat(path, &st) != 0 ||
  448. ((S_ISDIR(st.st_mode) ? 1 : 0) != must_be_dir))) {
  449. die("Invalid path for %s: [%s]: (%s). Make sure that path is either "
  450. "absolute, or it is relative to civetweb executable.",
  451. option_name, path, strerror(errno));
  452. }
  453. }
  454. static void set_absolute_path(char *options[], const char *option_name,
  455. const char *path_to_civetweb_exe)
  456. {
  457. char path[PATH_MAX] = "", abs[PATH_MAX] = "";
  458. const char *option_value;
  459. const char *p;
  460. /* Check whether option is already set */
  461. option_value = get_option(options, option_name);
  462. /* If option is already set and it is an absolute path,
  463. leave it as it is -- it's already absolute. */
  464. if (option_value != NULL && !is_path_absolute(option_value)) {
  465. /* Not absolute. Use the directory where civetweb executable lives
  466. be the relative directory for everything.
  467. Extract civetweb executable directory into path. */
  468. if ((p = strrchr(path_to_civetweb_exe, DIRSEP)) == NULL) {
  469. IGNORE_UNUSED_RESULT(getcwd(path, sizeof(path)));
  470. } else {
  471. snprintf(path, sizeof(path)-1, "%.*s", (int) (p - path_to_civetweb_exe),
  472. path_to_civetweb_exe);
  473. path[sizeof(path)-1] = 0;
  474. }
  475. strncat(path, "/", sizeof(path) - strlen(path) - 1);
  476. strncat(path, option_value, sizeof(path) - strlen(path) - 1);
  477. /* Absolutize the path, and set the option */
  478. IGNORE_UNUSED_RESULT(abs_path(path, abs, sizeof(abs)));
  479. set_option(options, option_name, abs);
  480. }
  481. }
  482. #ifdef USE_LUA
  483. #define main luatest_main
  484. #define luaL_openlibs lua_civet_open_all_libs
  485. struct lua_State;
  486. extern void lua_civet_open_all_libs(struct lua_State *L);
  487. #include "../src/third_party/lua-5.2.4/src/lua.c"
  488. #undef main
  489. #endif
  490. static void start_civetweb(int argc, char *argv[])
  491. {
  492. struct mg_callbacks callbacks;
  493. char *options[2*MAX_OPTIONS+1];
  494. int i;
  495. /* Edit passwords file: Add user or change password, if -A option is specified */
  496. if (argc > 1 && !strcmp(argv[1], "-A")) {
  497. if (argc != 6) {
  498. show_usage_and_exit(argv[0]);
  499. }
  500. exit(mg_modify_passwords_file(argv[2], argv[3], argv[4], argv[5]) ?
  501. EXIT_SUCCESS : EXIT_FAILURE);
  502. }
  503. /* Edit passwords file: Remove user, if -R option is specified */
  504. if (argc > 1 && !strcmp(argv[1], "-R")) {
  505. if (argc != 5) {
  506. show_usage_and_exit(argv[0]);
  507. }
  508. exit(mg_modify_passwords_file(argv[2], argv[3], argv[4], NULL) ?
  509. EXIT_SUCCESS : EXIT_FAILURE);
  510. }
  511. /* Call Lua with additional Civetweb specific Lua functions, if -L option is specified */
  512. if (argc > 1 && !strcmp(argv[1], "-L")) {
  513. #ifdef WIN32
  514. MakeConsole();
  515. #endif
  516. #ifdef USE_LUA
  517. exit(luatest_main(argc-1, &argv[1]));
  518. #endif
  519. exit(EXIT_FAILURE);
  520. }
  521. /* Show usage if -h or --help options are specified */
  522. if (argc == 2 && (!strcmp(argv[1], "-h") || !strcmp(argv[1], "-H") || !strcmp(argv[1], "--help"))) {
  523. show_usage_and_exit(argv[0]);
  524. }
  525. options[0] = NULL;
  526. set_option(options, "document_root", ".");
  527. /* Update config based on command line arguments */
  528. process_command_line_arguments(argv, options);
  529. /* Make sure we have absolute paths for files and directories */
  530. set_absolute_path(options, "document_root", argv[0]);
  531. set_absolute_path(options, "put_delete_auth_file", argv[0]);
  532. set_absolute_path(options, "cgi_interpreter", argv[0]);
  533. set_absolute_path(options, "access_log_file", argv[0]);
  534. set_absolute_path(options, "error_log_file", argv[0]);
  535. set_absolute_path(options, "global_auth_file", argv[0]);
  536. #ifdef USE_LUA
  537. set_absolute_path(options, "lua_preload_file", argv[0]);
  538. #endif
  539. set_absolute_path(options, "ssl_certificate", argv[0]);
  540. /* Make extra verification for certain options */
  541. verify_existence(options, "document_root", 1);
  542. verify_existence(options, "cgi_interpreter", 0);
  543. verify_existence(options, "ssl_certificate", 0);
  544. #ifdef USE_LUA
  545. verify_existence(options, "lua_preload_file", 0);
  546. #endif
  547. /* Setup signal handler: quit on Ctrl-C */
  548. signal(SIGTERM, signal_handler);
  549. signal(SIGINT, signal_handler);
  550. /* Start Civetweb */
  551. memset(&callbacks, 0, sizeof(callbacks));
  552. callbacks.log_message = &log_message;
  553. ctx = mg_start(&callbacks, NULL, (const char **) options);
  554. for (i = 0; options[i] != NULL; i++) {
  555. free(options[i]);
  556. }
  557. if (ctx == NULL) {
  558. die("%s", "Failed to start Civetweb.");
  559. }
  560. }
  561. #ifdef _WIN32
  562. enum {
  563. ID_ICON = 100, ID_QUIT, ID_SETTINGS, ID_SEPARATOR, ID_INSTALL_SERVICE,
  564. ID_REMOVE_SERVICE, ID_STATIC, ID_GROUP, ID_PASSWORD,
  565. ID_SAVE, ID_RESET_DEFAULTS, ID_RESET_FILE, ID_RESET_ACTIVE,
  566. ID_STATUS, ID_CONNECT, ID_ADD_USER, ID_ADD_USER_NAME, ID_ADD_USER_REALM,
  567. ID_INPUT_LINE,
  568. /* All dynamically created text boxes for options have IDs starting from
  569. ID_CONTROLS, incremented by one. */
  570. ID_CONTROLS = 200,
  571. /* Text boxes for files have "..." buttons to open file browser. These
  572. buttons have IDs that are ID_FILE_BUTTONS_DELTA higher than associated
  573. text box ID. */
  574. ID_FILE_BUTTONS_DELTA = 1000
  575. };
  576. static HICON hIcon;
  577. static SERVICE_STATUS ss;
  578. static SERVICE_STATUS_HANDLE hStatus;
  579. static const char *service_magic_argument = "--";
  580. static NOTIFYICONDATA TrayIcon;
  581. static void WINAPI ControlHandler(DWORD code)
  582. {
  583. if (code == SERVICE_CONTROL_STOP || code == SERVICE_CONTROL_SHUTDOWN) {
  584. ss.dwWin32ExitCode = 0;
  585. ss.dwCurrentState = SERVICE_STOPPED;
  586. }
  587. SetServiceStatus(hStatus, &ss);
  588. }
  589. static void WINAPI ServiceMain(void)
  590. {
  591. ss.dwServiceType = SERVICE_WIN32;
  592. ss.dwCurrentState = SERVICE_RUNNING;
  593. ss.dwControlsAccepted = SERVICE_ACCEPT_STOP | SERVICE_ACCEPT_SHUTDOWN;
  594. hStatus = RegisterServiceCtrlHandler(server_name, ControlHandler);
  595. SetServiceStatus(hStatus, &ss);
  596. while (ss.dwCurrentState == SERVICE_RUNNING) {
  597. Sleep(1000);
  598. }
  599. mg_stop(ctx);
  600. ss.dwCurrentState = SERVICE_STOPPED;
  601. ss.dwWin32ExitCode = (DWORD) -1;
  602. SetServiceStatus(hStatus, &ss);
  603. }
  604. static void show_error(void)
  605. {
  606. char buf[256];
  607. FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
  608. NULL, GetLastError(),
  609. MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
  610. buf, sizeof(buf), NULL);
  611. MessageBox(NULL, buf, "Error", MB_OK);
  612. }
  613. static void *align(void *ptr, DWORD alig)
  614. {
  615. ULONG ul = (ULONG) ptr;
  616. ul += alig;
  617. ul &= ~alig;
  618. return ((void *) ul);
  619. }
  620. static void save_config(HWND hDlg, FILE *fp)
  621. {
  622. char value[2000] = "";
  623. const char *default_value;
  624. const struct mg_option *options;
  625. int i, id;
  626. fprintf(fp, "%s", config_file_top_comment);
  627. options = mg_get_valid_options();
  628. for (i = 0; options[i].name != NULL; i++) {
  629. id = ID_CONTROLS + i;
  630. if (options[i].type == CONFIG_TYPE_BOOLEAN) {
  631. snprintf(value, sizeof(value)-1, "%s",
  632. IsDlgButtonChecked(hDlg, id) ? "yes" : "no");
  633. value[sizeof(value)-1] = 0;
  634. } else {
  635. GetDlgItemText(hDlg, id, value, sizeof(value));
  636. }
  637. default_value = options[i].default_value == NULL ? "" : options[i].default_value;
  638. /* If value is the same as default, skip it */
  639. if (strcmp(value, default_value) != 0) {
  640. fprintf(fp, "%s %s\n", options[i].name, value);
  641. }
  642. }
  643. }
  644. static BOOL CALLBACK SettingsDlgProc(HWND hDlg, UINT msg, WPARAM wParam, LPARAM lP)
  645. {
  646. FILE *fp;
  647. int i, j;
  648. const char *name, *value;
  649. const struct mg_option *default_options = mg_get_valid_options();
  650. char *file_options[MAX_OPTIONS*2+1] = {0};
  651. char *title;
  652. switch (msg) {
  653. case WM_CLOSE:
  654. DestroyWindow(hDlg);
  655. break;
  656. case WM_COMMAND:
  657. switch (LOWORD(wParam)) {
  658. case ID_SAVE:
  659. EnableWindow(GetDlgItem(hDlg, ID_SAVE), FALSE);
  660. if ((fp = fopen(config_file, "w+")) != NULL) {
  661. save_config(hDlg, fp);
  662. fclose(fp);
  663. mg_stop(ctx);
  664. start_civetweb(__argc, __argv);
  665. }
  666. EnableWindow(GetDlgItem(hDlg, ID_SAVE), TRUE);
  667. break;
  668. case ID_RESET_DEFAULTS:
  669. for (i = 0; default_options[i].name != NULL; i++) {
  670. name = default_options[i].name;
  671. value = default_options[i].default_value == NULL ? "" : default_options[i].default_value;
  672. if (default_options[i].type == CONFIG_TYPE_BOOLEAN) {
  673. CheckDlgButton(hDlg, ID_CONTROLS + i, !strcmp(value, "yes") ?
  674. BST_CHECKED : BST_UNCHECKED);
  675. } else {
  676. SetWindowText(GetDlgItem(hDlg, ID_CONTROLS + i), value);
  677. }
  678. }
  679. break;
  680. case ID_RESET_FILE:
  681. read_config_file(config_file, file_options);
  682. for (i = 0; default_options[i].name != NULL; i++) {
  683. name = default_options[i].name;
  684. value = default_options[i].default_value;
  685. for (j = 0; file_options[j * 2] != NULL; j++) {
  686. if (!strcmp(name, file_options[j * 2])) {
  687. value = file_options[j * 2 + 1];
  688. }
  689. }
  690. if (value == NULL) {
  691. value = "";
  692. }
  693. if (default_options[i].type == CONFIG_TYPE_BOOLEAN) {
  694. CheckDlgButton(hDlg, ID_CONTROLS + i, !strcmp(value, "yes") ? BST_CHECKED : BST_UNCHECKED);
  695. } else {
  696. SetWindowText(GetDlgItem(hDlg, ID_CONTROLS + i), value);
  697. }
  698. }
  699. for (i = 0; i<MAX_OPTIONS; i++) {
  700. free(file_options[2*i]);
  701. free(file_options[2*i+1]);
  702. }
  703. break;
  704. case ID_RESET_ACTIVE:
  705. for (i = 0; default_options[i].name != NULL; i++) {
  706. name = default_options[i].name;
  707. value = mg_get_option(ctx, name);
  708. if (default_options[i].type == CONFIG_TYPE_BOOLEAN) {
  709. CheckDlgButton(hDlg, ID_CONTROLS + i, !strcmp(value, "yes") ?
  710. BST_CHECKED : BST_UNCHECKED);
  711. } else {
  712. SetDlgItemText(hDlg, ID_CONTROLS + i, value == NULL ? "" : value);
  713. }
  714. }
  715. break;
  716. }
  717. for (i = 0; default_options[i].name != NULL; i++) {
  718. name = default_options[i].name;
  719. if (((default_options[i].type == CONFIG_TYPE_FILE) || (default_options[i].type == CONFIG_TYPE_DIRECTORY)) &&
  720. LOWORD(wParam) == ID_CONTROLS + i + ID_FILE_BUTTONS_DELTA) {
  721. OPENFILENAME of;
  722. BROWSEINFO bi;
  723. char path[PATH_MAX] = "";
  724. memset(&of, 0, sizeof(of));
  725. of.lStructSize = sizeof(of);
  726. of.hwndOwner = (HWND) hDlg;
  727. of.lpstrFile = path;
  728. of.nMaxFile = sizeof(path);
  729. of.lpstrInitialDir = mg_get_option(ctx, "document_root");
  730. of.Flags = OFN_CREATEPROMPT | OFN_NOCHANGEDIR | OFN_HIDEREADONLY;
  731. memset(&bi, 0, sizeof(bi));
  732. bi.hwndOwner = (HWND) hDlg;
  733. bi.lpszTitle = "Choose WWW root directory:";
  734. bi.ulFlags = BIF_RETURNONLYFSDIRS;
  735. if (default_options[i].type == CONFIG_TYPE_DIRECTORY) {
  736. SHGetPathFromIDList(SHBrowseForFolder(&bi), path);
  737. } else {
  738. GetOpenFileName(&of);
  739. }
  740. if (path[0] != '\0') {
  741. SetWindowText(GetDlgItem(hDlg, ID_CONTROLS + i), path);
  742. }
  743. }
  744. }
  745. break;
  746. case WM_INITDIALOG:
  747. SendMessage(hDlg, WM_SETICON, (WPARAM) ICON_SMALL, (LPARAM) hIcon);
  748. SendMessage(hDlg, WM_SETICON, (WPARAM) ICON_BIG, (LPARAM) hIcon);
  749. title = malloc(strlen(server_name)+16);
  750. if (title) {
  751. strcpy(title, server_name);
  752. strcat(title, " settings");
  753. SetWindowText(hDlg, title);
  754. free(title);
  755. }
  756. SetFocus(GetDlgItem(hDlg, ID_SAVE));
  757. /* Init dialog with active settings */
  758. SendMessage(hDlg, WM_COMMAND, ID_RESET_ACTIVE, 0);
  759. /* alternative: SendMessage(hDlg, WM_COMMAND, ID_RESET_FILE, 0); */
  760. break;
  761. default:
  762. break;
  763. }
  764. return FALSE;
  765. }
  766. struct tstring_input_buf {
  767. unsigned buflen;
  768. char * buffer;
  769. };
  770. static BOOL CALLBACK InputDlgProc(HWND hDlg, UINT msg, WPARAM wParam, LPARAM lP)
  771. {
  772. static struct tstring_input_buf *inBuf = 0;
  773. WORD ctrlId;
  774. switch (msg) {
  775. case WM_CLOSE:
  776. inBuf = 0;
  777. DestroyWindow(hDlg);
  778. break;
  779. case WM_COMMAND:
  780. ctrlId = LOWORD(wParam);
  781. if (ctrlId == IDOK) {
  782. /* Add user */
  783. GetWindowText(GetDlgItem(hDlg, ID_INPUT_LINE), inBuf->buffer, inBuf->buflen);
  784. if (strlen(inBuf->buffer)>0) {
  785. EndDialog(hDlg, IDOK);
  786. }
  787. } else if (ctrlId == IDCANCEL) {
  788. EndDialog(hDlg, IDCANCEL);
  789. }
  790. break;
  791. case WM_INITDIALOG:
  792. inBuf = (struct tstring_input_buf *) lP;
  793. assert(inBuf != NULL);
  794. assert((inBuf->buffer != NULL) && (inBuf->buflen != 0));
  795. assert(strlen(inBuf->buffer) < inBuf->buflen);
  796. SendMessage(hDlg, WM_SETICON, (WPARAM) ICON_SMALL, (LPARAM) hIcon);
  797. SendMessage(hDlg, WM_SETICON, (WPARAM) ICON_BIG, (LPARAM) hIcon);
  798. SendDlgItemMessage(hDlg, ID_INPUT_LINE, EM_LIMITTEXT, inBuf->buflen-1, 0);
  799. SetWindowText(GetDlgItem(hDlg, ID_INPUT_LINE), inBuf->buffer);
  800. SetWindowText(hDlg, "Modify password");
  801. SetFocus(GetDlgItem(hDlg, ID_INPUT_LINE));
  802. break;
  803. default:
  804. break;
  805. }
  806. return FALSE;
  807. }
  808. void suggest_passwd(char *passwd)
  809. {
  810. unsigned u;
  811. char * p;
  812. union {
  813. FILETIME ft;
  814. LARGE_INTEGER li;
  815. } num;
  816. /* valid characters are 32 to 126 */
  817. GetSystemTimeAsFileTime(&num.ft);
  818. num.li.HighPart |= GetCurrentProcessId();
  819. p = passwd;
  820. while (num.li.QuadPart) {
  821. u = (unsigned)(num.li.QuadPart % 95);
  822. num.li.QuadPart -= u;
  823. num.li.QuadPart /= 95;
  824. *p = (char)(u+32);
  825. p++;
  826. }
  827. }
  828. static void add_control(unsigned char **mem, DLGTEMPLATE *dia, WORD type,
  829. DWORD id, DWORD style, WORD x, WORD y,
  830. WORD cx, WORD cy, const char *caption);
  831. static int get_password(const char * user, const char * realm, char * passwd, unsigned passwd_len)
  832. {
  833. #define HEIGHT 15
  834. #define WIDTH 280
  835. #define LABEL_WIDTH 90
  836. HWND hDlg = NULL;
  837. unsigned char mem[4096], *p;
  838. DLGTEMPLATE *dia = (DLGTEMPLATE *) mem;
  839. int ok, y;
  840. struct tstring_input_buf dlgprms = {passwd_len, passwd};
  841. static struct {
  842. DLGTEMPLATE template; /* 18 bytes */
  843. WORD menu, class;
  844. wchar_t caption[1];
  845. WORD fontsiz;
  846. wchar_t fontface[7];
  847. } dialog_header = {{
  848. WS_CAPTION | WS_POPUP | WS_SYSMENU | WS_VISIBLE |
  849. DS_SETFONT | WS_DLGFRAME, WS_EX_TOOLWINDOW, 0, 200, 200, WIDTH, 0
  850. },
  851. 0, 0, L"", 8, L"Tahoma"
  852. };
  853. assert((user!=NULL) && (realm!=NULL) && (passwd!=NULL));
  854. if (guard < 100) {
  855. guard += 100;
  856. } else {
  857. return 0;
  858. }
  859. /* Create a password suggestion */
  860. memset(passwd, 0, passwd_len);
  861. suggest_passwd(passwd);
  862. /* Create the dialog */
  863. (void) memset(mem, 0, sizeof(mem));
  864. (void) memcpy(mem, &dialog_header, sizeof(dialog_header));
  865. p = mem + sizeof(dialog_header);
  866. y = HEIGHT;
  867. add_control(&p, dia, 0x82, ID_STATIC, WS_VISIBLE | WS_CHILD,
  868. 10, y, LABEL_WIDTH, HEIGHT, "User:");
  869. add_control(&p, dia, 0x81, ID_CONTROLS + 1,
  870. WS_CHILD | WS_VISIBLE | WS_BORDER | ES_AUTOHSCROLL | WS_DISABLED,
  871. 15+LABEL_WIDTH, y, WIDTH - LABEL_WIDTH - 25, HEIGHT, user);
  872. y += HEIGHT;
  873. add_control(&p, dia, 0x82, ID_STATIC, WS_VISIBLE | WS_CHILD,
  874. 10, y, LABEL_WIDTH, HEIGHT, "Realm:");
  875. add_control(&p, dia, 0x81, ID_CONTROLS + 2,
  876. WS_CHILD | WS_VISIBLE | WS_BORDER | ES_AUTOHSCROLL | WS_DISABLED,
  877. 15+LABEL_WIDTH, y, WIDTH - LABEL_WIDTH - 25, HEIGHT, realm);
  878. y += HEIGHT;
  879. add_control(&p, dia, 0x82, ID_STATIC, WS_VISIBLE | WS_CHILD,
  880. 10, y, LABEL_WIDTH, HEIGHT, "Password:");
  881. add_control(&p, dia, 0x81, ID_INPUT_LINE,
  882. WS_CHILD | WS_VISIBLE | WS_BORDER | ES_AUTOHSCROLL | WS_TABSTOP,
  883. 15+LABEL_WIDTH, y, WIDTH - LABEL_WIDTH - 25, HEIGHT, "");
  884. y += (WORD)(HEIGHT * 2);
  885. add_control(&p, dia, 0x80, IDOK,
  886. WS_CHILD | WS_VISIBLE | BS_PUSHBUTTON | WS_TABSTOP,
  887. 80, y, 55, 12, "Ok");
  888. add_control(&p, dia, 0x80, IDCANCEL,
  889. WS_CHILD | WS_VISIBLE | BS_PUSHBUTTON | WS_TABSTOP,
  890. 140, y, 55, 12, "Cancel");
  891. assert((int)p - (int)mem < sizeof(mem));
  892. dia->cy = y + (WORD)(HEIGHT * 1.5);
  893. ok = (IDOK == DialogBoxIndirectParam(NULL, dia, NULL, InputDlgProc, (LPARAM) &dlgprms));
  894. guard -= 100;
  895. return ok;
  896. #undef HEIGHT
  897. #undef WIDTH
  898. #undef LABEL_WIDTH
  899. }
  900. static BOOL CALLBACK PasswordDlgProc(HWND hDlg, UINT msg, WPARAM wParam, LPARAM lP)
  901. {
  902. static const char *passfile = 0;
  903. char domain[256], user[256], password[256];
  904. WORD ctrlId;
  905. switch (msg) {
  906. case WM_CLOSE:
  907. passfile = 0;
  908. DestroyWindow(hDlg);
  909. break;
  910. case WM_COMMAND:
  911. ctrlId = LOWORD(wParam);
  912. if (ctrlId == ID_ADD_USER) {
  913. /* Add user */
  914. GetWindowText(GetDlgItem(hDlg, ID_ADD_USER_NAME), user, sizeof(user));
  915. GetWindowText(GetDlgItem(hDlg, ID_ADD_USER_REALM), domain, sizeof(domain));
  916. if (get_password(user, domain, password, sizeof(password))) {
  917. mg_modify_passwords_file(passfile, domain, user, password);
  918. EndDialog(hDlg, IDOK);
  919. }
  920. } else if ((ctrlId>=(ID_CONTROLS + ID_FILE_BUTTONS_DELTA * 3)) &&
  921. (ctrlId<(ID_CONTROLS + ID_FILE_BUTTONS_DELTA * 4))) {
  922. /* Modify password */
  923. GetWindowText(GetDlgItem(hDlg, ctrlId - ID_FILE_BUTTONS_DELTA * 3), user, sizeof(user));
  924. GetWindowText(GetDlgItem(hDlg, ctrlId - ID_FILE_BUTTONS_DELTA * 2), domain, sizeof(domain));
  925. if (get_password(user, domain, password, sizeof(password))) {
  926. mg_modify_passwords_file(passfile, domain, user, password);
  927. EndDialog(hDlg, IDOK);
  928. }
  929. } else if ((ctrlId>=(ID_CONTROLS + ID_FILE_BUTTONS_DELTA * 2)) &&
  930. (ctrlId<(ID_CONTROLS + ID_FILE_BUTTONS_DELTA * 3))) {
  931. /* Remove user */
  932. GetWindowText(GetDlgItem(hDlg, ctrlId - ID_FILE_BUTTONS_DELTA * 2), user, sizeof(user));
  933. GetWindowText(GetDlgItem(hDlg, ctrlId - ID_FILE_BUTTONS_DELTA), domain, sizeof(domain));
  934. mg_modify_passwords_file(passfile, domain, user, NULL);
  935. EndDialog(hDlg, IDOK);
  936. }
  937. break;
  938. case WM_INITDIALOG:
  939. passfile = (const char *)lP;
  940. SendMessage(hDlg, WM_SETICON, (WPARAM) ICON_SMALL, (LPARAM) hIcon);
  941. SendMessage(hDlg, WM_SETICON, (WPARAM) ICON_BIG, (LPARAM) hIcon);
  942. SetWindowText(hDlg, passfile);
  943. SetFocus(GetDlgItem(hDlg, ID_ADD_USER_NAME));
  944. break;
  945. default:
  946. break;
  947. }
  948. return FALSE;
  949. }
  950. static void add_control(unsigned char **mem, DLGTEMPLATE *dia, WORD type,
  951. DWORD id, DWORD style, WORD x, WORD y,
  952. WORD cx, WORD cy, const char *caption)
  953. {
  954. DLGITEMTEMPLATE *tp;
  955. LPWORD p;
  956. dia->cdit++;
  957. *mem = align(*mem, 3);
  958. tp = (DLGITEMTEMPLATE *) *mem;
  959. tp->id = (WORD)id;
  960. tp->style = style;
  961. tp->dwExtendedStyle = 0;
  962. tp->x = x;
  963. tp->y = y;
  964. tp->cx = cx;
  965. tp->cy = cy;
  966. p = align(*mem + sizeof(*tp), 1);
  967. *p++ = 0xffff;
  968. *p++ = type;
  969. while (*caption != '\0') {
  970. *p++ = (WCHAR) *caption++;
  971. }
  972. *p++ = 0;
  973. p = align(p, 1);
  974. *p++ = 0;
  975. *mem = (unsigned char *) p;
  976. }
  977. static void show_settings_dialog()
  978. {
  979. #define HEIGHT 15
  980. #define WIDTH 460
  981. #define LABEL_WIDTH 90
  982. unsigned char mem[4096], *p;
  983. const struct mg_option *options;
  984. DWORD style;
  985. DLGTEMPLATE *dia = (DLGTEMPLATE *) mem;
  986. WORD i, cl, x, y, width, nelems = 0;
  987. static struct {
  988. DLGTEMPLATE template; /* 18 bytes */
  989. WORD menu, class;
  990. wchar_t caption[1];
  991. WORD fontsiz;
  992. wchar_t fontface[7];
  993. } dialog_header = {{
  994. WS_CAPTION | WS_POPUP | WS_SYSMENU | WS_VISIBLE |
  995. DS_SETFONT | WS_DLGFRAME, WS_EX_TOOLWINDOW, 0, 200, 200, WIDTH, 0
  996. },
  997. 0, 0, L"", 8, L"Tahoma"
  998. };
  999. if (guard == 0) {
  1000. guard++;
  1001. } else {
  1002. return;
  1003. }
  1004. (void) memset(mem, 0, sizeof(mem));
  1005. (void) memcpy(mem, &dialog_header, sizeof(dialog_header));
  1006. p = mem + sizeof(dialog_header);
  1007. options = mg_get_valid_options();
  1008. for (i = 0; options[i].name != NULL; i++) {
  1009. style = WS_CHILD | WS_VISIBLE | WS_TABSTOP;
  1010. x = 10 + (WIDTH / 2) * (nelems % 2);
  1011. y = (nelems/2 + 1) * HEIGHT + 5;
  1012. width = WIDTH / 2 - 20 - LABEL_WIDTH;
  1013. if (options[i].type == CONFIG_TYPE_NUMBER) {
  1014. style |= ES_NUMBER;
  1015. cl = 0x81;
  1016. style |= WS_BORDER | ES_AUTOHSCROLL;
  1017. } else if (options[i].type == CONFIG_TYPE_BOOLEAN) {
  1018. cl = 0x80;
  1019. style |= BS_AUTOCHECKBOX;
  1020. } else if ((options[i].type == CONFIG_TYPE_FILE) ||
  1021. (options[i].type == CONFIG_TYPE_DIRECTORY)) {
  1022. style |= WS_BORDER | ES_AUTOHSCROLL;
  1023. width -= 20;
  1024. cl = 0x81;
  1025. add_control(&p, dia, 0x80,
  1026. ID_CONTROLS + i + ID_FILE_BUTTONS_DELTA,
  1027. WS_VISIBLE | WS_CHILD | BS_PUSHBUTTON,
  1028. (WORD) (x + width + LABEL_WIDTH + 5),
  1029. y, 15, 12, "...");
  1030. } else {
  1031. cl = 0x81;
  1032. style |= WS_BORDER | ES_AUTOHSCROLL;
  1033. }
  1034. add_control(&p, dia, 0x82, ID_STATIC, WS_VISIBLE | WS_CHILD,
  1035. x, y, LABEL_WIDTH, HEIGHT, options[i].name);
  1036. add_control(&p, dia, cl, ID_CONTROLS + i, style,
  1037. (WORD) (x + LABEL_WIDTH), y, width, 12, "");
  1038. nelems++;
  1039. assert((int)p - (int)mem < sizeof(mem));
  1040. }
  1041. y = (WORD) (((nelems + 1) / 2 + 1) * HEIGHT + 5);
  1042. add_control(&p, dia, 0x80, ID_GROUP, WS_CHILD | WS_VISIBLE |
  1043. BS_GROUPBOX, 5, 5, WIDTH - 10, y, " Settings ");
  1044. y += 10;
  1045. add_control(&p, dia, 0x80, ID_SAVE,
  1046. WS_CHILD | WS_VISIBLE | BS_PUSHBUTTON | WS_TABSTOP,
  1047. WIDTH - 70, y, 65, 12, "Save Settings");
  1048. add_control(&p, dia, 0x80, ID_RESET_DEFAULTS,
  1049. WS_CHILD | WS_VISIBLE | BS_PUSHBUTTON | WS_TABSTOP,
  1050. WIDTH - 140, y, 65, 12, "Reset to defaults");
  1051. add_control(&p, dia, 0x80, ID_RESET_FILE,
  1052. WS_CHILD | WS_VISIBLE | BS_PUSHBUTTON | WS_TABSTOP,
  1053. WIDTH - 210, y, 65, 12, "Reload from file");
  1054. add_control(&p, dia, 0x80, ID_RESET_ACTIVE,
  1055. WS_CHILD | WS_VISIBLE | BS_PUSHBUTTON | WS_TABSTOP,
  1056. WIDTH - 280, y, 65, 12, "Reload active");
  1057. add_control(&p, dia, 0x82, ID_STATIC,
  1058. WS_CHILD | WS_VISIBLE | WS_DISABLED,
  1059. 5, y, 100, 12, server_base_name);
  1060. assert((int)p - (int)mem < sizeof(mem));
  1061. dia->cy = ((nelems + 1) / 2 + 1) * HEIGHT + 30;
  1062. DialogBoxIndirectParam(NULL, dia, NULL, SettingsDlgProc, (LPARAM) NULL);
  1063. guard--;
  1064. #undef HEIGHT
  1065. #undef WIDTH
  1066. #undef LABEL_WIDTH
  1067. }
  1068. static void change_password_file()
  1069. {
  1070. #define HEIGHT 15
  1071. #define WIDTH 320
  1072. #define LABEL_WIDTH 90
  1073. OPENFILENAME of;
  1074. char path[PATH_MAX] = PASSWORDS_FILE_NAME;
  1075. char strbuf[256], u[256], d[256];
  1076. HWND hDlg = NULL;
  1077. FILE * f;
  1078. int y, nelems;
  1079. unsigned char mem[4096], *p;
  1080. DLGTEMPLATE *dia = (DLGTEMPLATE *) mem;
  1081. const char * domain = mg_get_option(ctx, "authentication_domain");
  1082. static struct {
  1083. DLGTEMPLATE template; /* 18 bytes */
  1084. WORD menu, class;
  1085. wchar_t caption[1];
  1086. WORD fontsiz;
  1087. wchar_t fontface[7];
  1088. } dialog_header = {{
  1089. WS_CAPTION | WS_POPUP | WS_SYSMENU | WS_VISIBLE |
  1090. DS_SETFONT | WS_DLGFRAME, WS_EX_TOOLWINDOW, 0, 200, 200, WIDTH, 0
  1091. },
  1092. 0, 0, L"", 8, L"Tahoma"
  1093. };
  1094. if (guard == 0) {
  1095. guard++;
  1096. } else {
  1097. return;
  1098. }
  1099. memset(&of, 0, sizeof(of));
  1100. of.lStructSize = sizeof(of);
  1101. of.hwndOwner = (HWND) hDlg;
  1102. of.lpstrFile = path;
  1103. of.nMaxFile = sizeof(path);
  1104. of.lpstrInitialDir = mg_get_option(ctx, "document_root");
  1105. of.Flags = OFN_CREATEPROMPT | OFN_NOCHANGEDIR | OFN_HIDEREADONLY;
  1106. if (IDOK != GetSaveFileName(&of)) {
  1107. guard--;
  1108. return;
  1109. }
  1110. f = fopen(path, "a+");
  1111. if (f) {
  1112. fclose(f);
  1113. } else {
  1114. MessageBox(NULL, path, "Can not open file", MB_ICONERROR);
  1115. guard--;
  1116. return;
  1117. }
  1118. do {
  1119. (void) memset(mem, 0, sizeof(mem));
  1120. (void) memcpy(mem, &dialog_header, sizeof(dialog_header));
  1121. p = mem + sizeof(dialog_header);
  1122. f = fopen(path, "r+");
  1123. if (!f) {
  1124. MessageBox(NULL, path, "Can not open file", MB_ICONERROR);
  1125. guard--;
  1126. return;
  1127. }
  1128. nelems = 0;
  1129. while (fgets(strbuf, sizeof(strbuf), f)) {
  1130. if (sscanf(strbuf, "%255[^:]:%255[^:]:%*s", u, d) != 2) {
  1131. continue;
  1132. }
  1133. u[255]=0;
  1134. d[255]=0;
  1135. y = (nelems + 1) * HEIGHT + 5;
  1136. add_control(&p, dia, 0x80, ID_CONTROLS + nelems + ID_FILE_BUTTONS_DELTA * 3,
  1137. WS_CHILD | WS_VISIBLE | BS_PUSHBUTTON | WS_TABSTOP,
  1138. 10, y, 65, 12, "Modify password");
  1139. add_control(&p, dia, 0x80, ID_CONTROLS + nelems + ID_FILE_BUTTONS_DELTA * 2,
  1140. WS_CHILD | WS_VISIBLE | BS_PUSHBUTTON | WS_TABSTOP,
  1141. 80, y, 55, 12, "Remove user");
  1142. add_control(&p, dia, 0x81, ID_CONTROLS + nelems + ID_FILE_BUTTONS_DELTA,
  1143. WS_CHILD | WS_VISIBLE | WS_BORDER | ES_AUTOHSCROLL | WS_DISABLED,
  1144. 245, y, 60, 12, d);
  1145. add_control(&p, dia, 0x81, ID_CONTROLS + nelems,
  1146. WS_CHILD | WS_VISIBLE | WS_BORDER | ES_AUTOHSCROLL | WS_DISABLED,
  1147. 140, y, 100, 12, u);
  1148. nelems++;
  1149. assert((int)p - (int)mem < sizeof(mem));
  1150. }
  1151. fclose(f);
  1152. y = (WORD) ((nelems + 1) * HEIGHT + 10);
  1153. add_control(&p, dia, 0x80, ID_ADD_USER,
  1154. WS_CHILD | WS_VISIBLE | BS_PUSHBUTTON | WS_TABSTOP,
  1155. 80, y, 55, 12, "Add user");
  1156. add_control(&p, dia, 0x81, ID_ADD_USER_NAME,
  1157. WS_CHILD | WS_VISIBLE | WS_BORDER | ES_AUTOHSCROLL | WS_TABSTOP,
  1158. 140, y, 100, 12, "");
  1159. add_control(&p, dia, 0x81, ID_ADD_USER_REALM,
  1160. WS_CHILD | WS_VISIBLE | WS_BORDER | ES_AUTOHSCROLL | WS_TABSTOP,
  1161. 245, y, 60, 12, domain);
  1162. y = (WORD) ((nelems + 2) * HEIGHT + 10);
  1163. add_control(&p, dia, 0x80, ID_GROUP, WS_CHILD | WS_VISIBLE |
  1164. BS_GROUPBOX, 5, 5, WIDTH - 10, y, " Users ");
  1165. y += HEIGHT;
  1166. add_control(&p, dia, 0x82, ID_STATIC,
  1167. WS_CHILD | WS_VISIBLE | WS_DISABLED,
  1168. 5, y, 100, 12, server_base_name);
  1169. assert((int)p - (int)mem < sizeof(mem));
  1170. dia->cy = y + 20;
  1171. } while ((IDOK == DialogBoxIndirectParam(NULL, dia, NULL, PasswordDlgProc, (LPARAM) path)) && (!exit_flag));
  1172. guard--;
  1173. #undef HEIGHT
  1174. #undef WIDTH
  1175. #undef LABEL_WIDTH
  1176. }
  1177. static int manage_service(int action)
  1178. {
  1179. static const char *service_name = "Civetweb"; /* TODO: check using server_name instead of service_name */
  1180. SC_HANDLE hSCM = NULL, hService = NULL;
  1181. SERVICE_DESCRIPTION descr = {server_name};
  1182. char path[PATH_MAX + 20] = "";/* Path to executable plus magic argument */
  1183. int success = 1;
  1184. if ((hSCM = OpenSCManager(NULL, NULL, action == ID_INSTALL_SERVICE ?
  1185. GENERIC_WRITE : GENERIC_READ)) == NULL) {
  1186. success = 0;
  1187. show_error();
  1188. } else if (action == ID_INSTALL_SERVICE) {
  1189. path[sizeof(path)-1] = 0;
  1190. GetModuleFileName(NULL, path, sizeof(path)-1);
  1191. strncat(path, " ", sizeof(path)-1);
  1192. strncat(path, service_magic_argument, sizeof(path)-1);
  1193. hService = CreateService(hSCM, service_name, service_name,
  1194. SERVICE_ALL_ACCESS, SERVICE_WIN32_OWN_PROCESS,
  1195. SERVICE_AUTO_START, SERVICE_ERROR_NORMAL,
  1196. path, NULL, NULL, NULL, NULL, NULL);
  1197. if (hService) {
  1198. ChangeServiceConfig2(hService, SERVICE_CONFIG_DESCRIPTION, &descr);
  1199. } else {
  1200. show_error();
  1201. }
  1202. } else if (action == ID_REMOVE_SERVICE) {
  1203. if ((hService = OpenService(hSCM, service_name, DELETE)) == NULL ||
  1204. !DeleteService(hService)) {
  1205. show_error();
  1206. }
  1207. } else if ((hService = OpenService(hSCM, service_name,
  1208. SERVICE_QUERY_STATUS)) == NULL) {
  1209. success = 0;
  1210. }
  1211. if (hService)
  1212. CloseServiceHandle(hService);
  1213. if (hSCM)
  1214. CloseServiceHandle(hSCM);
  1215. return success;
  1216. }
  1217. static LRESULT CALLBACK WindowProc(HWND hWnd, UINT msg, WPARAM wParam,
  1218. LPARAM lParam)
  1219. {
  1220. static SERVICE_TABLE_ENTRY service_table[2] = {0};
  1221. int service_installed;
  1222. char buf[200], *service_argv[] = {__argv[0], NULL};
  1223. POINT pt;
  1224. HMENU hMenu;
  1225. static UINT s_uTaskbarRestart; /* for taskbar creation */
  1226. service_table[0].lpServiceName = server_name;
  1227. service_table[0].lpServiceProc = (LPSERVICE_MAIN_FUNCTION)ServiceMain;
  1228. switch (msg) {
  1229. case WM_CREATE:
  1230. if (__argv[1] != NULL &&
  1231. !strcmp(__argv[1], service_magic_argument)) {
  1232. start_civetweb(1, service_argv);
  1233. StartServiceCtrlDispatcher(service_table);
  1234. exit(EXIT_SUCCESS);
  1235. } else {
  1236. start_civetweb(__argc, __argv);
  1237. s_uTaskbarRestart = RegisterWindowMessage(TEXT("TaskbarCreated"));
  1238. }
  1239. break;
  1240. case WM_COMMAND:
  1241. switch (LOWORD(wParam)) {
  1242. case ID_QUIT:
  1243. mg_stop(ctx);
  1244. Shell_NotifyIcon(NIM_DELETE, &TrayIcon);
  1245. exit_flag = 1;
  1246. PostQuitMessage(0);
  1247. return 0;
  1248. case ID_SETTINGS:
  1249. show_settings_dialog();
  1250. break;
  1251. case ID_PASSWORD:
  1252. change_password_file();
  1253. break;
  1254. case ID_INSTALL_SERVICE:
  1255. case ID_REMOVE_SERVICE:
  1256. manage_service(LOWORD(wParam));
  1257. break;
  1258. case ID_CONNECT:
  1259. printf("[%s]\n", get_url_to_first_open_port(ctx));
  1260. ShellExecute(NULL, "open", get_url_to_first_open_port(ctx),
  1261. NULL, NULL, SW_SHOW);
  1262. break;
  1263. }
  1264. break;
  1265. case WM_USER:
  1266. switch (lParam) {
  1267. case WM_RBUTTONUP:
  1268. case WM_LBUTTONUP:
  1269. case WM_LBUTTONDBLCLK:
  1270. hMenu = CreatePopupMenu();
  1271. AppendMenu(hMenu, MF_STRING | MF_GRAYED, ID_SEPARATOR, server_name);
  1272. AppendMenu(hMenu, MF_SEPARATOR, ID_SEPARATOR, "");
  1273. service_installed = manage_service(0);
  1274. snprintf(buf, sizeof(buf)-1, "NT service: %s installed",
  1275. service_installed ? "" : "not");
  1276. buf[sizeof(buf)-1] = 0;
  1277. AppendMenu(hMenu, MF_STRING | MF_GRAYED, ID_SEPARATOR, buf);
  1278. AppendMenu(hMenu, MF_STRING | (service_installed ? MF_GRAYED : 0),
  1279. ID_INSTALL_SERVICE, "Install service");
  1280. AppendMenu(hMenu, MF_STRING | (!service_installed ? MF_GRAYED : 0),
  1281. ID_REMOVE_SERVICE, "Deinstall service");
  1282. AppendMenu(hMenu, MF_SEPARATOR, ID_SEPARATOR, "");
  1283. AppendMenu(hMenu, MF_STRING, ID_CONNECT, "Start browser");
  1284. AppendMenu(hMenu, MF_STRING, ID_SETTINGS, "Edit settings");
  1285. AppendMenu(hMenu, MF_STRING, ID_PASSWORD, "Modify password file");
  1286. AppendMenu(hMenu, MF_SEPARATOR, ID_SEPARATOR, "");
  1287. AppendMenu(hMenu, MF_STRING, ID_QUIT, "Exit");
  1288. GetCursorPos(&pt);
  1289. SetForegroundWindow(hWnd);
  1290. TrackPopupMenu(hMenu, 0, pt.x, pt.y, 0, hWnd, NULL);
  1291. PostMessage(hWnd, WM_NULL, 0, 0);
  1292. DestroyMenu(hMenu);
  1293. break;
  1294. }
  1295. break;
  1296. case WM_CLOSE:
  1297. mg_stop(ctx);
  1298. Shell_NotifyIcon(NIM_DELETE, &TrayIcon);
  1299. exit_flag = 1;
  1300. PostQuitMessage(0);
  1301. return 0;/* We've just sent our own quit message, with proper hwnd. */
  1302. default:
  1303. if (msg==s_uTaskbarRestart)
  1304. Shell_NotifyIcon(NIM_ADD, &TrayIcon);
  1305. }
  1306. return DefWindowProc(hWnd, msg, wParam, lParam);
  1307. }
  1308. static int MakeConsole() {
  1309. DWORD err;
  1310. int ok = (GetConsoleWindow() != NULL);
  1311. if (!ok) {
  1312. if (!AttachConsole(ATTACH_PARENT_PROCESS)) {
  1313. FreeConsole();
  1314. if (!AllocConsole()) {
  1315. err = GetLastError();
  1316. if (err==ERROR_ACCESS_DENIED) {
  1317. MessageBox(NULL, "Insufficient rights to create a console window", "Error", MB_ICONERROR);
  1318. }
  1319. }
  1320. AttachConsole(GetCurrentProcessId());
  1321. }
  1322. ok = (GetConsoleWindow() != NULL);
  1323. if (ok) {
  1324. freopen("CONIN$", "r", stdin);
  1325. freopen("CONOUT$", "w", stdout);
  1326. freopen("CONOUT$", "w", stderr);
  1327. }
  1328. }
  1329. if (ok) {
  1330. SetConsoleTitle(server_name);
  1331. }
  1332. return ok;
  1333. }
  1334. int WINAPI WinMain(HINSTANCE hInst, HINSTANCE hPrev, LPSTR cmdline, int show)
  1335. {
  1336. WNDCLASS cls;
  1337. HWND hWnd;
  1338. MSG msg;
  1339. init_server_name(__argc, __argv);
  1340. memset(&cls, 0, sizeof(cls));
  1341. cls.lpfnWndProc = (WNDPROC) WindowProc;
  1342. cls.hIcon = LoadIcon(NULL, IDI_APPLICATION);
  1343. cls.lpszClassName = server_base_name;
  1344. RegisterClass(&cls);
  1345. hWnd = CreateWindow(cls.lpszClassName, server_name, WS_OVERLAPPEDWINDOW,
  1346. 0, 0, 0, 0, NULL, NULL, NULL, NULL);
  1347. ShowWindow(hWnd, SW_HIDE);
  1348. if (icon_name) {
  1349. hIcon = LoadImage(NULL, icon_name, IMAGE_ICON, 16, 16, LR_LOADFROMFILE);
  1350. } else {
  1351. hIcon = LoadImage(GetModuleHandle(NULL), MAKEINTRESOURCE(ID_ICON), IMAGE_ICON, 16, 16, 0);
  1352. }
  1353. TrayIcon.cbSize = sizeof(TrayIcon);
  1354. TrayIcon.uID = ID_ICON;
  1355. TrayIcon.uFlags = NIF_ICON | NIF_MESSAGE | NIF_TIP;
  1356. TrayIcon.hIcon = hIcon;
  1357. TrayIcon.hWnd = hWnd;
  1358. snprintf(TrayIcon.szTip, sizeof(TrayIcon.szTip), "%s", server_name);
  1359. TrayIcon.uCallbackMessage = WM_USER;
  1360. Shell_NotifyIcon(NIM_ADD, &TrayIcon);
  1361. while (GetMessage(&msg, hWnd, 0, 0) > 0) {
  1362. TranslateMessage(&msg);
  1363. DispatchMessage(&msg);
  1364. }
  1365. /* Return the WM_QUIT value. */
  1366. return (int) msg.wParam;
  1367. }
  1368. #if defined(CONSOLE)
  1369. void main(void)
  1370. {
  1371. WinMain(0, 0, 0, 0);
  1372. }
  1373. #endif
  1374. #elif defined(USE_COCOA)
  1375. #import <Cocoa/Cocoa.h>
  1376. @interface Civetweb :
  1377. NSObject<NSApplicationDelegate>
  1378. - (void) openBrowser;
  1379. - (void) shutDown;
  1380. @end
  1381. @implementation Civetweb
  1382. - (void) openBrowser {
  1383. [[NSWorkspace sharedWorkspace]
  1384. openURL:[NSURL URLWithString:
  1385. [NSString stringWithUTF8String:get_url_to_first_open_port(ctx)]]];
  1386. }
  1387. - (void) editConfig {
  1388. create_config_file(config_file);
  1389. [[NSWorkspace sharedWorkspace]
  1390. openFile:[NSString stringWithUTF8String:config_file]
  1391. withApplication:@"TextEdit"];
  1392. }
  1393. - (void)shutDown {
  1394. [NSApp terminate:nil];
  1395. }
  1396. @end
  1397. int main(int argc, char *argv[])
  1398. {
  1399. init_server_name(argc, (const char **)argv);
  1400. start_civetweb(argc, argv);
  1401. [NSAutoreleasePool new];
  1402. [NSApplication sharedApplication];
  1403. /* Add delegate to process menu item actions */
  1404. Civetweb *myDelegate = [[Civetweb alloc] autorelease];
  1405. [NSApp setDelegate: myDelegate];
  1406. /* Run this app as agent */
  1407. ProcessSerialNumber psn = { 0, kCurrentProcess };
  1408. TransformProcessType(&psn, kProcessTransformToBackgroundApplication);
  1409. SetFrontProcess(&psn);
  1410. /* Add status bar menu */
  1411. id menu = [[NSMenu new] autorelease];
  1412. /* Add version menu item */
  1413. [menu addItem:[[[NSMenuItem alloc]
  1414. /*initWithTitle:[NSString stringWithFormat:@"%s", server_name]*/
  1415. initWithTitle:[NSString stringWithUTF8String:server_name]
  1416. action:@selector(noexist) keyEquivalent:@""] autorelease]];
  1417. /* Add configuration menu item */
  1418. [menu addItem:[[[NSMenuItem alloc]
  1419. initWithTitle:@"Edit configuration"
  1420. action:@selector(editConfig) keyEquivalent:@""] autorelease]];
  1421. /* Add connect menu item */
  1422. [menu addItem:[[[NSMenuItem alloc]
  1423. initWithTitle:@"Open web root in a browser"
  1424. action:@selector(openBrowser) keyEquivalent:@""] autorelease]];
  1425. /* Separator */
  1426. [menu addItem:[NSMenuItem separatorItem]];
  1427. /* Add quit menu item */
  1428. [menu addItem:[[[NSMenuItem alloc]
  1429. initWithTitle:@"Quit"
  1430. action:@selector(shutDown) keyEquivalent:@"q"] autorelease]];
  1431. /* Attach menu to the status bar */
  1432. id item = [[[NSStatusBar systemStatusBar]
  1433. statusItemWithLength:NSVariableStatusItemLength] retain];
  1434. [item setHighlightMode:YES];
  1435. [item setImage:[NSImage imageNamed:@"civetweb_22x22.png"]];
  1436. [item setMenu:menu];
  1437. /* Run the app */
  1438. [NSApp activateIgnoringOtherApps:YES];
  1439. [NSApp run];
  1440. mg_stop(ctx);
  1441. return EXIT_SUCCESS;
  1442. }
  1443. #else
  1444. int main(int argc, char *argv[])
  1445. {
  1446. init_server_name(argc, (const char **)argv);
  1447. start_civetweb(argc, argv);
  1448. printf("%s started on port(s) %s with web root [%s]\n",
  1449. server_name, mg_get_option(ctx, "listening_ports"),
  1450. mg_get_option(ctx, "document_root"));
  1451. while (exit_flag == 0) {
  1452. sleep(1);
  1453. }
  1454. printf("Exiting on signal %d, waiting for all threads to finish...",
  1455. exit_flag);
  1456. fflush(stdout);
  1457. mg_stop(ctx);
  1458. printf("%s", " done.\n");
  1459. return EXIT_SUCCESS;
  1460. }
  1461. #endif /* _WIN32 */