main.c 56 KB

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