main.c 55 KB

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