main.c 60 KB

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