main.c 60 KB

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