main.c 56 KB

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