main.c 61 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475
  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_lua.h"
  646. #include "civetweb_private_lua.h"
  647. static int
  648. run_lua(const char *file_name)
  649. {
  650. struct lua_State *L;
  651. int lua_ret;
  652. int func_ret = EXIT_FAILURE;
  653. const char *lua_err_txt;
  654. #ifdef WIN32
  655. (void)MakeConsole();
  656. #endif
  657. L = luaL_newstate();
  658. if (L == NULL) {
  659. fprintf(stderr, "Error: Cannot create Lua state\n");
  660. return EXIT_FAILURE;
  661. }
  662. civetweb_open_lua_libs(L);
  663. lua_ret = luaL_loadfile(L, file_name);
  664. if (lua_ret != LUA_OK) {
  665. /* Error when loading the file (e.g. file not found, out of memory, ...)
  666. */
  667. lua_err_txt = lua_tostring(L, -1);
  668. fprintf(stderr, "Error loading file %s: %s\n", file_name, lua_err_txt);
  669. } else {
  670. /* The script file is loaded, now call it */
  671. lua_ret = lua_pcall(L,
  672. /* no arguments */ 0,
  673. /* zero or one return value */ 1,
  674. /* errors as strint return value */ 0);
  675. if (lua_ret != LUA_OK) {
  676. /* Error when executing the script */
  677. lua_err_txt = lua_tostring(L, -1);
  678. fprintf(stderr,
  679. "Error running file %s: %s\n",
  680. file_name,
  681. lua_err_txt);
  682. } else {
  683. /* Script executed */
  684. if (lua_type(L, -1) == LUA_TNUMBER) {
  685. func_ret = (int)lua_tonumber(L, -1);
  686. } else {
  687. func_ret = EXIT_SUCCESS;
  688. }
  689. }
  690. }
  691. lua_close(L);
  692. return func_ret;
  693. }
  694. #endif
  695. #ifdef USE_DUKTAPE
  696. #include "duktape.h"
  697. static int
  698. run_duktape(const char *file_name)
  699. {
  700. duk_context *ctx = NULL;
  701. #ifdef WIN32
  702. (void)MakeConsole();
  703. #endif
  704. ctx = duk_create_heap_default();
  705. if (!ctx) {
  706. fprintf(stderr, "Failed to create a Duktape heap.\n");
  707. goto finished;
  708. }
  709. if (duk_peval_file(ctx, file_name) != 0) {
  710. fprintf(stderr, "%s\n", duk_safe_to_string(ctx, -1));
  711. goto finished;
  712. }
  713. duk_pop(ctx); /* ignore result */
  714. finished:
  715. duk_destroy_heap(ctx);
  716. return 0;
  717. }
  718. #endif
  719. #if defined(__MINGW32__) || defined(__MINGW64__)
  720. /* For __MINGW32/64_MAJOR/MINOR_VERSION define */
  721. #include <_mingw.h>
  722. #endif
  723. static void
  724. start_civetweb(int argc, char *argv[])
  725. {
  726. struct mg_callbacks callbacks;
  727. char *options[2 * MAX_OPTIONS + 1];
  728. int i;
  729. /* Start option -I:
  730. * Show system information and exit
  731. * This is very useful for diagnosis. */
  732. if (argc > 1 && !strcmp(argv[1], "-I")) {
  733. (void)MakeConsole();
  734. fprintf(stdout, "\n%s (%s)\n", g_server_base_name, g_server_name);
  735. (void)mg_print_system_info(0, 0);
  736. exit(EXIT_SUCCESS);
  737. }
  738. /* Edit passwords file: Add user or change password, if -A option is
  739. * specified */
  740. if (argc > 1 && !strcmp(argv[1], "-A")) {
  741. if (argc != 6) {
  742. show_usage_and_exit(argv[0]);
  743. }
  744. exit(mg_modify_passwords_file(argv[2], argv[3], argv[4], argv[5])
  745. ? EXIT_SUCCESS
  746. : EXIT_FAILURE);
  747. }
  748. /* Edit passwords file: Remove user, if -R option is specified */
  749. if (argc > 1 && !strcmp(argv[1], "-R")) {
  750. if (argc != 5) {
  751. show_usage_and_exit(argv[0]);
  752. }
  753. exit(mg_modify_passwords_file(argv[2], argv[3], argv[4], NULL)
  754. ? EXIT_SUCCESS
  755. : EXIT_FAILURE);
  756. }
  757. /* Call Lua with additional CivetWeb specific Lua functions, if -L option
  758. * is specified */
  759. if (argc > 1 && !strcmp(argv[1], "-L")) {
  760. #ifdef USE_LUA
  761. if (argc != 3) {
  762. show_usage_and_exit(argv[0]);
  763. }
  764. exit(run_lua(argv[2]));
  765. #else
  766. show_server_name();
  767. fprintf(stderr, "\nError: Lua support not enabled\n");
  768. exit(EXIT_FAILURE);
  769. #endif
  770. }
  771. /* Call Duktape, if -E option is specified */
  772. if (argc > 1 && !strcmp(argv[1], "-E")) {
  773. #ifdef USE_DUKTAPE
  774. if (argc != 3) {
  775. show_usage_and_exit(argv[0]);
  776. }
  777. exit(run_duktape(argv[2]));
  778. #else
  779. show_server_name();
  780. fprintf(stderr, "\nError: Ecmascript 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(argc, 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. verify_existence(options, "ssl_ca_path", 1);
  809. verify_existence(options, "ssl_ca_file", 0);
  810. #ifdef USE_LUA
  811. verify_existence(options, "lua_preload_file", 0);
  812. #endif
  813. /* Setup signal handler: quit on Ctrl-C */
  814. signal(SIGTERM, signal_handler);
  815. signal(SIGINT, signal_handler);
  816. /* Initialize user data */
  817. memset(&g_user_data, 0, sizeof(g_user_data));
  818. /* Start Civetweb */
  819. memset(&callbacks, 0, sizeof(callbacks));
  820. callbacks.log_message = &log_message;
  821. g_ctx = mg_start(&callbacks, &g_user_data, (const char **)options);
  822. /* mg_start copies all options to an internal buffer.
  823. * The options data field here is not required anymore. */
  824. for (i = 0; options[i] != NULL; i++) {
  825. free(options[i]);
  826. }
  827. /* If mg_start fails, it returns NULL */
  828. if (g_ctx == NULL) {
  829. die("Failed to start %s:\n%s",
  830. g_server_name,
  831. ((g_user_data.first_message == NULL) ? "unknown reason"
  832. : g_user_data.first_message));
  833. }
  834. }
  835. static void
  836. stop_civetweb(void)
  837. {
  838. mg_stop(g_ctx);
  839. free(g_user_data.first_message);
  840. g_user_data.first_message = NULL;
  841. }
  842. #ifdef _WIN32
  843. /* Win32 has a small GUI.
  844. * Define some GUI elements and Windows message handlers. */
  845. enum {
  846. ID_ICON = 100,
  847. ID_QUIT,
  848. ID_SETTINGS,
  849. ID_SEPARATOR,
  850. ID_INSTALL_SERVICE,
  851. ID_REMOVE_SERVICE,
  852. ID_STATIC,
  853. ID_GROUP,
  854. ID_PASSWORD,
  855. ID_SAVE,
  856. ID_RESET_DEFAULTS,
  857. ID_RESET_FILE,
  858. ID_RESET_ACTIVE,
  859. ID_STATUS,
  860. ID_CONNECT,
  861. ID_ADD_USER,
  862. ID_ADD_USER_NAME,
  863. ID_ADD_USER_REALM,
  864. ID_INPUT_LINE,
  865. ID_SYSINFO,
  866. /* All dynamically created text boxes for options have IDs starting from
  867. ID_CONTROLS, incremented by one. */
  868. ID_CONTROLS = 200,
  869. /* Text boxes for files have "..." buttons to open file browser. These
  870. buttons have IDs that are ID_FILE_BUTTONS_DELTA higher than associated
  871. text box ID. */
  872. ID_FILE_BUTTONS_DELTA = 1000
  873. };
  874. static HICON hIcon;
  875. static SERVICE_STATUS ss;
  876. static SERVICE_STATUS_HANDLE hStatus;
  877. static const char *service_magic_argument = "--";
  878. static NOTIFYICONDATA TrayIcon;
  879. static void WINAPI
  880. ControlHandler(DWORD code)
  881. {
  882. if (code == SERVICE_CONTROL_STOP || code == SERVICE_CONTROL_SHUTDOWN) {
  883. ss.dwWin32ExitCode = 0;
  884. ss.dwCurrentState = SERVICE_STOPPED;
  885. }
  886. SetServiceStatus(hStatus, &ss);
  887. }
  888. static void WINAPI
  889. ServiceMain(void)
  890. {
  891. ss.dwServiceType = SERVICE_WIN32;
  892. ss.dwCurrentState = SERVICE_RUNNING;
  893. ss.dwControlsAccepted = SERVICE_ACCEPT_STOP | SERVICE_ACCEPT_SHUTDOWN;
  894. hStatus = RegisterServiceCtrlHandler(g_server_name, ControlHandler);
  895. SetServiceStatus(hStatus, &ss);
  896. while (ss.dwCurrentState == SERVICE_RUNNING) {
  897. Sleep(1000);
  898. }
  899. stop_civetweb();
  900. ss.dwCurrentState = SERVICE_STOPPED;
  901. ss.dwWin32ExitCode = (DWORD)-1;
  902. SetServiceStatus(hStatus, &ss);
  903. }
  904. static void
  905. show_error(void)
  906. {
  907. char buf[256];
  908. FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
  909. NULL,
  910. GetLastError(),
  911. MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
  912. buf,
  913. sizeof(buf),
  914. NULL);
  915. MessageBox(NULL, buf, "Error", MB_OK);
  916. }
  917. static void *
  918. align(void *ptr, uintptr_t alig)
  919. {
  920. uintptr_t ul = (uintptr_t)ptr;
  921. ul += alig;
  922. ul &= ~alig;
  923. return ((void *)ul);
  924. }
  925. static void
  926. save_config(HWND hDlg, FILE *fp)
  927. {
  928. char value[2000] = "";
  929. const char *default_value;
  930. const struct mg_option *options;
  931. int i, id;
  932. fprintf(fp, "%s", config_file_top_comment);
  933. options = mg_get_valid_options();
  934. for (i = 0; options[i].name != NULL; i++) {
  935. id = ID_CONTROLS + i;
  936. if (options[i].type == CONFIG_TYPE_BOOLEAN) {
  937. snprintf(value,
  938. sizeof(value) - 1,
  939. "%s",
  940. IsDlgButtonChecked(hDlg, id) ? "yes" : "no");
  941. value[sizeof(value) - 1] = 0;
  942. } else {
  943. GetDlgItemText(hDlg, id, value, sizeof(value));
  944. }
  945. default_value =
  946. options[i].default_value == NULL ? "" : options[i].default_value;
  947. /* If value is the same as default, skip it */
  948. if (strcmp(value, default_value) != 0) {
  949. fprintf(fp, "%s %s\n", options[i].name, value);
  950. }
  951. }
  952. }
  953. static INT_PTR CALLBACK
  954. SettingsDlgProc(HWND hDlg, UINT msg, WPARAM wParam, LPARAM lParam)
  955. {
  956. FILE *fp;
  957. int i, j;
  958. const char *name, *value;
  959. const struct mg_option *default_options = mg_get_valid_options();
  960. char *file_options[MAX_OPTIONS * 2 + 1] = {0};
  961. char *title;
  962. (void)lParam;
  963. switch (msg) {
  964. case WM_CLOSE:
  965. DestroyWindow(hDlg);
  966. break;
  967. case WM_COMMAND:
  968. switch (LOWORD(wParam)) {
  969. case ID_SAVE:
  970. EnableWindow(GetDlgItem(hDlg, ID_SAVE), FALSE);
  971. if ((fp = fopen(g_config_file_name, "w+")) != NULL) {
  972. save_config(hDlg, fp);
  973. fclose(fp);
  974. stop_civetweb();
  975. start_civetweb(__argc, __argv);
  976. }
  977. EnableWindow(GetDlgItem(hDlg, ID_SAVE), TRUE);
  978. break;
  979. case ID_RESET_DEFAULTS:
  980. for (i = 0; default_options[i].name != NULL; i++) {
  981. name = default_options[i].name;
  982. value = default_options[i].default_value == NULL
  983. ? ""
  984. : default_options[i].default_value;
  985. if (default_options[i].type == CONFIG_TYPE_BOOLEAN) {
  986. CheckDlgButton(hDlg,
  987. ID_CONTROLS + i,
  988. !strcmp(value, "yes") ? BST_CHECKED
  989. : BST_UNCHECKED);
  990. } else {
  991. SetWindowText(GetDlgItem(hDlg, ID_CONTROLS + i), value);
  992. }
  993. }
  994. break;
  995. case ID_RESET_FILE:
  996. read_config_file(g_config_file_name, file_options);
  997. for (i = 0; default_options[i].name != NULL; i++) {
  998. name = default_options[i].name;
  999. value = default_options[i].default_value;
  1000. for (j = 0; file_options[j * 2] != NULL; j++) {
  1001. if (!strcmp(name, file_options[j * 2])) {
  1002. value = file_options[j * 2 + 1];
  1003. }
  1004. }
  1005. if (value == NULL) {
  1006. value = "";
  1007. }
  1008. if (default_options[i].type == CONFIG_TYPE_BOOLEAN) {
  1009. CheckDlgButton(hDlg,
  1010. ID_CONTROLS + i,
  1011. !strcmp(value, "yes") ? BST_CHECKED
  1012. : BST_UNCHECKED);
  1013. } else {
  1014. SetWindowText(GetDlgItem(hDlg, ID_CONTROLS + i), value);
  1015. }
  1016. }
  1017. for (i = 0; i < MAX_OPTIONS; i++) {
  1018. free(file_options[2 * i]);
  1019. free(file_options[2 * i + 1]);
  1020. }
  1021. break;
  1022. case ID_RESET_ACTIVE:
  1023. for (i = 0; default_options[i].name != NULL; i++) {
  1024. name = default_options[i].name;
  1025. value = mg_get_option(g_ctx, name);
  1026. if (default_options[i].type == CONFIG_TYPE_BOOLEAN) {
  1027. CheckDlgButton(hDlg,
  1028. ID_CONTROLS + i,
  1029. !strcmp(value, "yes") ? BST_CHECKED
  1030. : BST_UNCHECKED);
  1031. } else {
  1032. SetDlgItemText(hDlg,
  1033. ID_CONTROLS + i,
  1034. value == NULL ? "" : value);
  1035. }
  1036. }
  1037. break;
  1038. }
  1039. for (i = 0; default_options[i].name != NULL; i++) {
  1040. name = default_options[i].name;
  1041. if (((default_options[i].type == CONFIG_TYPE_FILE)
  1042. || (default_options[i].type == CONFIG_TYPE_DIRECTORY))
  1043. && LOWORD(wParam) == ID_CONTROLS + i + ID_FILE_BUTTONS_DELTA) {
  1044. OPENFILENAME of;
  1045. BROWSEINFO bi;
  1046. char path[PATH_MAX] = "";
  1047. memset(&of, 0, sizeof(of));
  1048. of.lStructSize = sizeof(of);
  1049. of.hwndOwner = (HWND)hDlg;
  1050. of.lpstrFile = path;
  1051. of.nMaxFile = sizeof(path);
  1052. of.lpstrInitialDir = mg_get_option(g_ctx, "document_root");
  1053. of.Flags =
  1054. OFN_CREATEPROMPT | OFN_NOCHANGEDIR | OFN_HIDEREADONLY;
  1055. memset(&bi, 0, sizeof(bi));
  1056. bi.hwndOwner = (HWND)hDlg;
  1057. bi.lpszTitle = "Choose WWW root directory:";
  1058. bi.ulFlags = BIF_RETURNONLYFSDIRS;
  1059. if (default_options[i].type == CONFIG_TYPE_DIRECTORY) {
  1060. SHGetPathFromIDList(SHBrowseForFolder(&bi), path);
  1061. } else {
  1062. GetOpenFileName(&of);
  1063. }
  1064. if (path[0] != '\0') {
  1065. SetWindowText(GetDlgItem(hDlg, ID_CONTROLS + i), path);
  1066. }
  1067. }
  1068. }
  1069. break;
  1070. case WM_INITDIALOG:
  1071. /* Store hWnd in a parameter accessible by the parent, so we can
  1072. * bring this window to front if required. */
  1073. *((HWND *)lParam) = hDlg;
  1074. /* Initialize the dialog elements */
  1075. SendMessage(hDlg, WM_SETICON, (WPARAM)ICON_SMALL, (LPARAM)hIcon);
  1076. SendMessage(hDlg, WM_SETICON, (WPARAM)ICON_BIG, (LPARAM)hIcon);
  1077. title = malloc(strlen(g_server_name) + 16);
  1078. if (title) {
  1079. strcpy(title, g_server_name);
  1080. strcat(title, " settings");
  1081. SetWindowText(hDlg, title);
  1082. free(title);
  1083. }
  1084. SetFocus(GetDlgItem(hDlg, ID_SAVE));
  1085. /* Init dialog with active settings */
  1086. SendMessage(hDlg, WM_COMMAND, ID_RESET_ACTIVE, 0);
  1087. /* alternative: SendMessage(hDlg, WM_COMMAND, ID_RESET_FILE, 0); */
  1088. break;
  1089. default:
  1090. break;
  1091. }
  1092. return FALSE;
  1093. }
  1094. struct tstring_input_buf {
  1095. unsigned buflen;
  1096. char *buffer;
  1097. };
  1098. static INT_PTR CALLBACK
  1099. InputDlgProc(HWND hDlg, UINT msg, WPARAM wParam, LPARAM lP)
  1100. {
  1101. static struct tstring_input_buf *inBuf = 0;
  1102. WORD ctrlId;
  1103. switch (msg) {
  1104. case WM_CLOSE:
  1105. inBuf = 0;
  1106. DestroyWindow(hDlg);
  1107. break;
  1108. case WM_COMMAND:
  1109. ctrlId = LOWORD(wParam);
  1110. if (ctrlId == IDOK) {
  1111. /* Add user */
  1112. GetWindowText(GetDlgItem(hDlg, ID_INPUT_LINE),
  1113. inBuf->buffer,
  1114. (int)inBuf->buflen);
  1115. if (strlen(inBuf->buffer) > 0) {
  1116. EndDialog(hDlg, IDOK);
  1117. }
  1118. } else if (ctrlId == IDCANCEL) {
  1119. EndDialog(hDlg, IDCANCEL);
  1120. }
  1121. break;
  1122. case WM_INITDIALOG:
  1123. inBuf = (struct tstring_input_buf *)lP;
  1124. assert(inBuf != NULL);
  1125. assert((inBuf->buffer != NULL) && (inBuf->buflen != 0));
  1126. assert(strlen(inBuf->buffer) < inBuf->buflen);
  1127. SendMessage(hDlg, WM_SETICON, (WPARAM)ICON_SMALL, (LPARAM)hIcon);
  1128. SendMessage(hDlg, WM_SETICON, (WPARAM)ICON_BIG, (LPARAM)hIcon);
  1129. SendDlgItemMessage(
  1130. hDlg, ID_INPUT_LINE, EM_LIMITTEXT, inBuf->buflen - 1, 0);
  1131. SetWindowText(GetDlgItem(hDlg, ID_INPUT_LINE), inBuf->buffer);
  1132. SetWindowText(hDlg, "Modify password");
  1133. SetFocus(GetDlgItem(hDlg, ID_INPUT_LINE));
  1134. break;
  1135. default:
  1136. break;
  1137. }
  1138. return FALSE;
  1139. }
  1140. static void
  1141. suggest_passwd(char *passwd)
  1142. {
  1143. unsigned u;
  1144. char *p;
  1145. union {
  1146. FILETIME ft;
  1147. LARGE_INTEGER li;
  1148. } num;
  1149. /* valid characters are 32 to 126 */
  1150. GetSystemTimeAsFileTime(&num.ft);
  1151. num.li.HighPart |= (LONG)GetCurrentProcessId();
  1152. p = passwd;
  1153. while (num.li.QuadPart) {
  1154. u = (unsigned)(num.li.QuadPart % 95);
  1155. num.li.QuadPart -= u;
  1156. num.li.QuadPart /= 95;
  1157. *p = (char)(u + 32);
  1158. p++;
  1159. }
  1160. }
  1161. static void add_control(unsigned char **mem,
  1162. DLGTEMPLATE *dia,
  1163. WORD type,
  1164. WORD id,
  1165. DWORD style,
  1166. short x,
  1167. short y,
  1168. short cx,
  1169. short cy,
  1170. const char *caption);
  1171. static int
  1172. get_password(const char *user,
  1173. const char *realm,
  1174. char *passwd,
  1175. unsigned passwd_len)
  1176. {
  1177. #define HEIGHT (15)
  1178. #define WIDTH (280)
  1179. #define LABEL_WIDTH (90)
  1180. unsigned char mem[4096], *p;
  1181. DLGTEMPLATE *dia = (DLGTEMPLATE *)mem;
  1182. int ok;
  1183. short y;
  1184. struct tstring_input_buf dlgprms;
  1185. static struct {
  1186. DLGTEMPLATE template; /* 18 bytes */
  1187. WORD menu, class;
  1188. wchar_t caption[1];
  1189. WORD fontsiz;
  1190. wchar_t fontface[7];
  1191. } dialog_header = {{WS_CAPTION | WS_POPUP | WS_SYSMENU | WS_VISIBLE
  1192. | DS_SETFONT | WS_DLGFRAME,
  1193. WS_EX_TOOLWINDOW,
  1194. 0,
  1195. 200,
  1196. 200,
  1197. WIDTH,
  1198. 0},
  1199. 0,
  1200. 0,
  1201. L"",
  1202. 8,
  1203. L"Tahoma"};
  1204. dlgprms.buffer = passwd;
  1205. dlgprms.buflen = passwd_len;
  1206. assert((user != NULL) && (realm != NULL) && (passwd != NULL));
  1207. if (sGuard < 100) {
  1208. sGuard += 100;
  1209. } else {
  1210. return 0;
  1211. }
  1212. /* Create a password suggestion */
  1213. memset(passwd, 0, passwd_len);
  1214. suggest_passwd(passwd);
  1215. /* Create the dialog */
  1216. (void)memset(mem, 0, sizeof(mem));
  1217. (void)memcpy(mem, &dialog_header, sizeof(dialog_header));
  1218. p = mem + sizeof(dialog_header);
  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. "User:");
  1230. add_control(&p,
  1231. dia,
  1232. 0x81,
  1233. ID_CONTROLS + 1,
  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. user);
  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. "Realm:");
  1252. add_control(&p,
  1253. dia,
  1254. 0x81,
  1255. ID_CONTROLS + 2,
  1256. WS_CHILD | WS_VISIBLE | WS_BORDER | ES_AUTOHSCROLL
  1257. | WS_DISABLED,
  1258. 15 + LABEL_WIDTH,
  1259. y,
  1260. WIDTH - LABEL_WIDTH - 25,
  1261. HEIGHT,
  1262. realm);
  1263. y += HEIGHT;
  1264. add_control(&p,
  1265. dia,
  1266. 0x82,
  1267. ID_STATIC,
  1268. WS_VISIBLE | WS_CHILD,
  1269. 10,
  1270. y,
  1271. LABEL_WIDTH,
  1272. HEIGHT,
  1273. "Password:");
  1274. add_control(&p,
  1275. dia,
  1276. 0x81,
  1277. ID_INPUT_LINE,
  1278. WS_CHILD | WS_VISIBLE | WS_BORDER | ES_AUTOHSCROLL | WS_TABSTOP,
  1279. 15 + LABEL_WIDTH,
  1280. y,
  1281. WIDTH - LABEL_WIDTH - 25,
  1282. HEIGHT,
  1283. "");
  1284. y += (WORD)(HEIGHT * 2);
  1285. add_control(&p,
  1286. dia,
  1287. 0x80,
  1288. IDOK,
  1289. WS_CHILD | WS_VISIBLE | BS_PUSHBUTTON | WS_TABSTOP,
  1290. 80,
  1291. y,
  1292. 55,
  1293. 12,
  1294. "Ok");
  1295. add_control(&p,
  1296. dia,
  1297. 0x80,
  1298. IDCANCEL,
  1299. WS_CHILD | WS_VISIBLE | BS_PUSHBUTTON | WS_TABSTOP,
  1300. 140,
  1301. y,
  1302. 55,
  1303. 12,
  1304. "Cancel");
  1305. assert((intptr_t)p - (intptr_t)mem < (intptr_t)sizeof(mem));
  1306. dia->cy = y + (WORD)(HEIGHT * 1.5);
  1307. ok = (IDOK == DialogBoxIndirectParam(
  1308. NULL, dia, NULL, InputDlgProc, (LPARAM)&dlgprms));
  1309. sGuard -= 100;
  1310. return ok;
  1311. #undef HEIGHT
  1312. #undef WIDTH
  1313. #undef LABEL_WIDTH
  1314. }
  1315. static INT_PTR CALLBACK
  1316. PasswordDlgProc(HWND hDlg, UINT msg, WPARAM wParam, LPARAM lP)
  1317. {
  1318. static const char *passfile = 0;
  1319. char domain[256], user[256], password[256];
  1320. WORD ctrlId;
  1321. switch (msg) {
  1322. case WM_CLOSE:
  1323. passfile = 0;
  1324. DestroyWindow(hDlg);
  1325. break;
  1326. case WM_COMMAND:
  1327. ctrlId = LOWORD(wParam);
  1328. if (ctrlId == ID_ADD_USER) {
  1329. /* Add user */
  1330. GetWindowText(GetDlgItem(hDlg, ID_ADD_USER_NAME),
  1331. user,
  1332. sizeof(user));
  1333. GetWindowText(GetDlgItem(hDlg, ID_ADD_USER_REALM),
  1334. domain,
  1335. sizeof(domain));
  1336. if (get_password(user, domain, password, sizeof(password))) {
  1337. mg_modify_passwords_file(passfile, domain, user, password);
  1338. EndDialog(hDlg, IDOK);
  1339. }
  1340. } else if ((ctrlId >= (ID_CONTROLS + ID_FILE_BUTTONS_DELTA * 3))
  1341. && (ctrlId < (ID_CONTROLS + ID_FILE_BUTTONS_DELTA * 4))) {
  1342. /* Modify password */
  1343. GetWindowText(GetDlgItem(hDlg, ctrlId - ID_FILE_BUTTONS_DELTA * 3),
  1344. user,
  1345. sizeof(user));
  1346. GetWindowText(GetDlgItem(hDlg, ctrlId - ID_FILE_BUTTONS_DELTA * 2),
  1347. domain,
  1348. sizeof(domain));
  1349. if (get_password(user, domain, password, sizeof(password))) {
  1350. mg_modify_passwords_file(passfile, domain, user, password);
  1351. EndDialog(hDlg, IDOK);
  1352. }
  1353. } else if ((ctrlId >= (ID_CONTROLS + ID_FILE_BUTTONS_DELTA * 2))
  1354. && (ctrlId < (ID_CONTROLS + ID_FILE_BUTTONS_DELTA * 3))) {
  1355. /* Remove user */
  1356. GetWindowText(GetDlgItem(hDlg, ctrlId - ID_FILE_BUTTONS_DELTA * 2),
  1357. user,
  1358. sizeof(user));
  1359. GetWindowText(GetDlgItem(hDlg, ctrlId - ID_FILE_BUTTONS_DELTA),
  1360. domain,
  1361. sizeof(domain));
  1362. mg_modify_passwords_file(passfile, domain, user, NULL);
  1363. EndDialog(hDlg, IDOK);
  1364. }
  1365. break;
  1366. case WM_INITDIALOG:
  1367. passfile = (const char *)lP;
  1368. SendMessage(hDlg, WM_SETICON, (WPARAM)ICON_SMALL, (LPARAM)hIcon);
  1369. SendMessage(hDlg, WM_SETICON, (WPARAM)ICON_BIG, (LPARAM)hIcon);
  1370. SetWindowText(hDlg, passfile);
  1371. SetFocus(GetDlgItem(hDlg, ID_ADD_USER_NAME));
  1372. break;
  1373. default:
  1374. break;
  1375. }
  1376. return FALSE;
  1377. }
  1378. static void
  1379. add_control(unsigned char **mem,
  1380. DLGTEMPLATE *dia,
  1381. WORD type,
  1382. WORD id,
  1383. DWORD style,
  1384. short x,
  1385. short y,
  1386. short cx,
  1387. short cy,
  1388. const char *caption)
  1389. {
  1390. DLGITEMTEMPLATE *tp;
  1391. LPWORD p;
  1392. dia->cdit++;
  1393. *mem = align(*mem, 3);
  1394. tp = (DLGITEMTEMPLATE *)*mem;
  1395. tp->id = id;
  1396. tp->style = style;
  1397. tp->dwExtendedStyle = 0;
  1398. tp->x = x;
  1399. tp->y = y;
  1400. tp->cx = cx;
  1401. tp->cy = cy;
  1402. p = align(*mem + sizeof(*tp), 1);
  1403. *p++ = 0xffff;
  1404. *p++ = type;
  1405. while (*caption != '\0') {
  1406. *p++ = (WCHAR)*caption++;
  1407. }
  1408. *p++ = 0;
  1409. p = align(p, 1);
  1410. *p++ = 0;
  1411. *mem = (unsigned char *)p;
  1412. }
  1413. static void
  1414. show_settings_dialog()
  1415. {
  1416. #define HEIGHT (15)
  1417. #define WIDTH (460)
  1418. #define LABEL_WIDTH (90)
  1419. unsigned char mem[16 * 1024], *p;
  1420. const struct mg_option *options;
  1421. DWORD style;
  1422. DLGTEMPLATE *dia = (DLGTEMPLATE *)mem;
  1423. WORD i, cl, nelems = 0;
  1424. short width, x, y;
  1425. static HWND sDlgHWnd;
  1426. static struct {
  1427. DLGTEMPLATE template; /* 18 bytes */
  1428. WORD menu, class;
  1429. wchar_t caption[1];
  1430. WORD fontsiz;
  1431. wchar_t fontface[7];
  1432. } dialog_header = {{WS_CAPTION | WS_POPUP | WS_SYSMENU | WS_VISIBLE
  1433. | DS_SETFONT | WS_DLGFRAME,
  1434. WS_EX_TOOLWINDOW,
  1435. 0,
  1436. 200,
  1437. 200,
  1438. WIDTH,
  1439. 0},
  1440. 0,
  1441. 0,
  1442. L"",
  1443. 8,
  1444. L"Tahoma"};
  1445. if (sGuard == 0) {
  1446. sGuard++;
  1447. } else {
  1448. SetForegroundWindow(sDlgHWnd);
  1449. return;
  1450. }
  1451. (void)memset(mem, 0, sizeof(mem));
  1452. (void)memcpy(mem, &dialog_header, sizeof(dialog_header));
  1453. p = mem + sizeof(dialog_header);
  1454. options = mg_get_valid_options();
  1455. for (i = 0; options[i].name != NULL; i++) {
  1456. style = WS_CHILD | WS_VISIBLE | WS_TABSTOP;
  1457. x = 10 + (WIDTH / 2) * (nelems % 2);
  1458. y = (nelems / 2 + 1) * HEIGHT + 5;
  1459. width = WIDTH / 2 - 20 - LABEL_WIDTH;
  1460. if (options[i].type == CONFIG_TYPE_NUMBER) {
  1461. style |= ES_NUMBER;
  1462. cl = 0x81;
  1463. style |= WS_BORDER | ES_AUTOHSCROLL;
  1464. } else if (options[i].type == CONFIG_TYPE_BOOLEAN) {
  1465. cl = 0x80;
  1466. style |= BS_AUTOCHECKBOX;
  1467. } else if ((options[i].type == CONFIG_TYPE_FILE)
  1468. || (options[i].type == CONFIG_TYPE_DIRECTORY)) {
  1469. style |= WS_BORDER | ES_AUTOHSCROLL;
  1470. width -= 20;
  1471. cl = 0x81;
  1472. add_control(&p,
  1473. dia,
  1474. 0x80,
  1475. ID_CONTROLS + i + ID_FILE_BUTTONS_DELTA,
  1476. WS_VISIBLE | WS_CHILD | BS_PUSHBUTTON,
  1477. x + width + LABEL_WIDTH + 5,
  1478. y,
  1479. 15,
  1480. 12,
  1481. "...");
  1482. } else {
  1483. cl = 0x81;
  1484. style |= WS_BORDER | ES_AUTOHSCROLL;
  1485. }
  1486. add_control(&p,
  1487. dia,
  1488. 0x82,
  1489. ID_STATIC,
  1490. WS_VISIBLE | WS_CHILD,
  1491. x,
  1492. y,
  1493. LABEL_WIDTH,
  1494. HEIGHT,
  1495. options[i].name);
  1496. add_control(&p,
  1497. dia,
  1498. cl,
  1499. ID_CONTROLS + i,
  1500. style,
  1501. x + LABEL_WIDTH,
  1502. y,
  1503. width,
  1504. 12,
  1505. "");
  1506. nelems++;
  1507. assert(((intptr_t)p - (intptr_t)mem) < (intptr_t)sizeof(mem));
  1508. }
  1509. y = (((nelems + 1) / 2 + 1) * HEIGHT + 5);
  1510. add_control(&p,
  1511. dia,
  1512. 0x80,
  1513. ID_GROUP,
  1514. WS_CHILD | WS_VISIBLE | BS_GROUPBOX,
  1515. 5,
  1516. 5,
  1517. WIDTH - 10,
  1518. y,
  1519. " Settings ");
  1520. y += 10;
  1521. add_control(&p,
  1522. dia,
  1523. 0x80,
  1524. ID_SAVE,
  1525. WS_CHILD | WS_VISIBLE | BS_PUSHBUTTON | WS_TABSTOP,
  1526. WIDTH - 70,
  1527. y,
  1528. 65,
  1529. 12,
  1530. "Save Settings");
  1531. add_control(&p,
  1532. dia,
  1533. 0x80,
  1534. ID_RESET_DEFAULTS,
  1535. WS_CHILD | WS_VISIBLE | BS_PUSHBUTTON | WS_TABSTOP,
  1536. WIDTH - 140,
  1537. y,
  1538. 65,
  1539. 12,
  1540. "Reset to defaults");
  1541. add_control(&p,
  1542. dia,
  1543. 0x80,
  1544. ID_RESET_FILE,
  1545. WS_CHILD | WS_VISIBLE | BS_PUSHBUTTON | WS_TABSTOP,
  1546. WIDTH - 210,
  1547. y,
  1548. 65,
  1549. 12,
  1550. "Reload from file");
  1551. add_control(&p,
  1552. dia,
  1553. 0x80,
  1554. ID_RESET_ACTIVE,
  1555. WS_CHILD | WS_VISIBLE | BS_PUSHBUTTON | WS_TABSTOP,
  1556. WIDTH - 280,
  1557. y,
  1558. 65,
  1559. 12,
  1560. "Reload active");
  1561. add_control(&p,
  1562. dia,
  1563. 0x82,
  1564. ID_STATIC,
  1565. WS_CHILD | WS_VISIBLE | WS_DISABLED,
  1566. 5,
  1567. y,
  1568. 100,
  1569. 12,
  1570. g_server_base_name);
  1571. assert(((intptr_t)p - (intptr_t)mem) < (intptr_t)sizeof(mem));
  1572. dia->cy = ((nelems + 1) / 2 + 1) * HEIGHT + 30;
  1573. DialogBoxIndirectParam(NULL, dia, NULL, SettingsDlgProc, (LPARAM)&sDlgHWnd);
  1574. sGuard--;
  1575. sDlgHWnd = NULL;
  1576. #undef HEIGHT
  1577. #undef WIDTH
  1578. #undef LABEL_WIDTH
  1579. }
  1580. static void
  1581. change_password_file()
  1582. {
  1583. #define HEIGHT (15)
  1584. #define WIDTH (320)
  1585. #define LABEL_WIDTH (90)
  1586. OPENFILENAME of;
  1587. char path[PATH_MAX] = PASSWORDS_FILE_NAME;
  1588. char strbuf[256], u[256], d[256];
  1589. HWND hDlg = NULL;
  1590. FILE *f;
  1591. short y, nelems;
  1592. unsigned char mem[4096], *p;
  1593. DLGTEMPLATE *dia = (DLGTEMPLATE *)mem;
  1594. const char *domain = mg_get_option(g_ctx, "authentication_domain");
  1595. static struct {
  1596. DLGTEMPLATE template; /* 18 bytes */
  1597. WORD menu, class;
  1598. wchar_t caption[1];
  1599. WORD fontsiz;
  1600. wchar_t fontface[7];
  1601. } dialog_header = {{WS_CAPTION | WS_POPUP | WS_SYSMENU | WS_VISIBLE
  1602. | DS_SETFONT | WS_DLGFRAME,
  1603. WS_EX_TOOLWINDOW,
  1604. 0,
  1605. 200,
  1606. 200,
  1607. WIDTH,
  1608. 0},
  1609. 0,
  1610. 0,
  1611. L"",
  1612. 8,
  1613. L"Tahoma"};
  1614. if (sGuard == 0) {
  1615. sGuard++;
  1616. } else {
  1617. return;
  1618. }
  1619. memset(&of, 0, sizeof(of));
  1620. of.lStructSize = sizeof(of);
  1621. of.hwndOwner = (HWND)hDlg;
  1622. of.lpstrFile = path;
  1623. of.nMaxFile = sizeof(path);
  1624. of.lpstrInitialDir = mg_get_option(g_ctx, "document_root");
  1625. of.Flags = OFN_CREATEPROMPT | OFN_NOCHANGEDIR | OFN_HIDEREADONLY;
  1626. if (IDOK != GetSaveFileName(&of)) {
  1627. sGuard--;
  1628. return;
  1629. }
  1630. f = fopen(path, "a+");
  1631. if (f) {
  1632. fclose(f);
  1633. } else {
  1634. MessageBox(NULL, path, "Can not open file", MB_ICONERROR);
  1635. sGuard--;
  1636. return;
  1637. }
  1638. do {
  1639. (void)memset(mem, 0, sizeof(mem));
  1640. (void)memcpy(mem, &dialog_header, sizeof(dialog_header));
  1641. p = mem + sizeof(dialog_header);
  1642. f = fopen(path, "r+");
  1643. if (!f) {
  1644. MessageBox(NULL, path, "Can not open file", MB_ICONERROR);
  1645. sGuard--;
  1646. return;
  1647. }
  1648. nelems = 0;
  1649. while (fgets(strbuf, sizeof(strbuf), f)) {
  1650. if (sscanf(strbuf, "%255[^:]:%255[^:]:%*s", u, d) != 2) {
  1651. continue;
  1652. }
  1653. u[255] = 0;
  1654. d[255] = 0;
  1655. y = (nelems + 1) * HEIGHT + 5;
  1656. add_control(&p,
  1657. dia,
  1658. 0x80,
  1659. ID_CONTROLS + nelems + ID_FILE_BUTTONS_DELTA * 3,
  1660. WS_CHILD | WS_VISIBLE | BS_PUSHBUTTON | WS_TABSTOP,
  1661. 10,
  1662. y,
  1663. 65,
  1664. 12,
  1665. "Modify password");
  1666. add_control(&p,
  1667. dia,
  1668. 0x80,
  1669. ID_CONTROLS + nelems + ID_FILE_BUTTONS_DELTA * 2,
  1670. WS_CHILD | WS_VISIBLE | BS_PUSHBUTTON | WS_TABSTOP,
  1671. 80,
  1672. y,
  1673. 55,
  1674. 12,
  1675. "Remove user");
  1676. add_control(&p,
  1677. dia,
  1678. 0x81,
  1679. ID_CONTROLS + nelems + ID_FILE_BUTTONS_DELTA,
  1680. WS_CHILD | WS_VISIBLE | WS_BORDER | ES_AUTOHSCROLL
  1681. | WS_DISABLED,
  1682. 245,
  1683. y,
  1684. 60,
  1685. 12,
  1686. d);
  1687. add_control(&p,
  1688. dia,
  1689. 0x81,
  1690. ID_CONTROLS + nelems,
  1691. WS_CHILD | WS_VISIBLE | WS_BORDER | ES_AUTOHSCROLL
  1692. | WS_DISABLED,
  1693. 140,
  1694. y,
  1695. 100,
  1696. 12,
  1697. u);
  1698. nelems++;
  1699. assert(((intptr_t)p - (intptr_t)mem) < (intptr_t)sizeof(mem));
  1700. }
  1701. fclose(f);
  1702. y = (nelems + 1) * HEIGHT + 10;
  1703. add_control(&p,
  1704. dia,
  1705. 0x80,
  1706. ID_ADD_USER,
  1707. WS_CHILD | WS_VISIBLE | BS_PUSHBUTTON | WS_TABSTOP,
  1708. 80,
  1709. y,
  1710. 55,
  1711. 12,
  1712. "Add user");
  1713. add_control(&p,
  1714. dia,
  1715. 0x81,
  1716. ID_ADD_USER_NAME,
  1717. WS_CHILD | WS_VISIBLE | WS_BORDER | ES_AUTOHSCROLL
  1718. | WS_TABSTOP,
  1719. 140,
  1720. y,
  1721. 100,
  1722. 12,
  1723. "");
  1724. add_control(&p,
  1725. dia,
  1726. 0x81,
  1727. ID_ADD_USER_REALM,
  1728. WS_CHILD | WS_VISIBLE | WS_BORDER | ES_AUTOHSCROLL
  1729. | WS_TABSTOP,
  1730. 245,
  1731. y,
  1732. 60,
  1733. 12,
  1734. domain);
  1735. y = (nelems + 2) * HEIGHT + 10;
  1736. add_control(&p,
  1737. dia,
  1738. 0x80,
  1739. ID_GROUP,
  1740. WS_CHILD | WS_VISIBLE | BS_GROUPBOX,
  1741. 5,
  1742. 5,
  1743. WIDTH - 10,
  1744. y,
  1745. " Users ");
  1746. y += HEIGHT;
  1747. add_control(&p,
  1748. dia,
  1749. 0x82,
  1750. ID_STATIC,
  1751. WS_CHILD | WS_VISIBLE | WS_DISABLED,
  1752. 5,
  1753. y,
  1754. 100,
  1755. 12,
  1756. g_server_base_name);
  1757. assert(((intptr_t)p - (intptr_t)mem) < (intptr_t)sizeof(mem));
  1758. dia->cy = y + 20;
  1759. } while ((IDOK == DialogBoxIndirectParam(
  1760. NULL, dia, NULL, PasswordDlgProc, (LPARAM)path))
  1761. && (!g_exit_flag));
  1762. sGuard--;
  1763. #undef HEIGHT
  1764. #undef WIDTH
  1765. #undef LABEL_WIDTH
  1766. }
  1767. static void
  1768. show_system_info()
  1769. {
  1770. if (sGuard == 0) {
  1771. sGuard++;
  1772. } else {
  1773. return;
  1774. }
  1775. /* TODO */
  1776. sGuard--;
  1777. }
  1778. static int
  1779. manage_service(int action)
  1780. {
  1781. const char *service_name = g_server_name;
  1782. SC_HANDLE hSCM = NULL, hService = NULL;
  1783. SERVICE_DESCRIPTION descr;
  1784. char path[PATH_MAX + 20] = ""; /* Path to executable plus magic argument */
  1785. int success = 1;
  1786. descr.lpDescription = (LPSTR)g_server_name;
  1787. if ((hSCM = OpenSCManager(NULL,
  1788. NULL,
  1789. action == ID_INSTALL_SERVICE ? GENERIC_WRITE
  1790. : GENERIC_READ))
  1791. == NULL) {
  1792. success = 0;
  1793. show_error();
  1794. } else if (action == ID_INSTALL_SERVICE) {
  1795. path[sizeof(path) - 1] = 0;
  1796. GetModuleFileName(NULL, path, sizeof(path) - 1);
  1797. strncat(path, " ", sizeof(path) - 1);
  1798. strncat(path, service_magic_argument, sizeof(path) - 1);
  1799. hService = CreateService(hSCM,
  1800. service_name,
  1801. service_name,
  1802. SERVICE_ALL_ACCESS,
  1803. SERVICE_WIN32_OWN_PROCESS,
  1804. SERVICE_AUTO_START,
  1805. SERVICE_ERROR_NORMAL,
  1806. path,
  1807. NULL,
  1808. NULL,
  1809. NULL,
  1810. NULL,
  1811. NULL);
  1812. if (hService) {
  1813. ChangeServiceConfig2(hService, SERVICE_CONFIG_DESCRIPTION, &descr);
  1814. } else {
  1815. show_error();
  1816. }
  1817. } else if (action == ID_REMOVE_SERVICE) {
  1818. if ((hService = OpenService(hSCM, service_name, DELETE)) == NULL
  1819. || !DeleteService(hService)) {
  1820. show_error();
  1821. }
  1822. } else if ((hService =
  1823. OpenService(hSCM, service_name, SERVICE_QUERY_STATUS))
  1824. == NULL) {
  1825. success = 0;
  1826. }
  1827. if (hService)
  1828. CloseServiceHandle(hService);
  1829. if (hSCM)
  1830. CloseServiceHandle(hSCM);
  1831. return success;
  1832. }
  1833. static LRESULT CALLBACK
  1834. WindowProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam)
  1835. {
  1836. static SERVICE_TABLE_ENTRY service_table[2];
  1837. int service_installed;
  1838. char buf[200], *service_argv[2];
  1839. POINT pt;
  1840. HMENU hMenu;
  1841. static UINT s_uTaskbarRestart; /* for taskbar creation */
  1842. service_argv[0] = __argv[0];
  1843. service_argv[1] = NULL;
  1844. memset(service_table, 0, sizeof(service_table));
  1845. service_table[0].lpServiceName = (LPSTR)g_server_name;
  1846. service_table[0].lpServiceProc = (LPSERVICE_MAIN_FUNCTION)ServiceMain;
  1847. switch (msg) {
  1848. case WM_CREATE:
  1849. if (__argv[1] != NULL && !strcmp(__argv[1], service_magic_argument)) {
  1850. start_civetweb(1, service_argv);
  1851. StartServiceCtrlDispatcher(service_table);
  1852. exit(EXIT_SUCCESS);
  1853. } else {
  1854. start_civetweb(__argc, __argv);
  1855. s_uTaskbarRestart = RegisterWindowMessage(TEXT("TaskbarCreated"));
  1856. }
  1857. break;
  1858. case WM_COMMAND:
  1859. switch (LOWORD(wParam)) {
  1860. case ID_QUIT:
  1861. stop_civetweb();
  1862. Shell_NotifyIcon(NIM_DELETE, &TrayIcon);
  1863. g_exit_flag = 1;
  1864. PostQuitMessage(0);
  1865. return 0;
  1866. case ID_SETTINGS:
  1867. show_settings_dialog();
  1868. break;
  1869. case ID_PASSWORD:
  1870. change_password_file();
  1871. break;
  1872. case ID_SYSINFO:
  1873. show_system_info();
  1874. break;
  1875. case ID_INSTALL_SERVICE:
  1876. case ID_REMOVE_SERVICE:
  1877. manage_service(LOWORD(wParam));
  1878. break;
  1879. case ID_CONNECT:
  1880. fprintf(stdout, "[%s]\n", get_url_to_first_open_port(g_ctx));
  1881. ShellExecute(NULL,
  1882. "open",
  1883. get_url_to_first_open_port(g_ctx),
  1884. NULL,
  1885. NULL,
  1886. SW_SHOW);
  1887. break;
  1888. }
  1889. break;
  1890. case WM_USER:
  1891. switch (lParam) {
  1892. case WM_RBUTTONUP:
  1893. case WM_LBUTTONUP:
  1894. case WM_LBUTTONDBLCLK:
  1895. hMenu = CreatePopupMenu();
  1896. AppendMenu(hMenu,
  1897. MF_STRING | MF_GRAYED,
  1898. ID_SEPARATOR,
  1899. g_server_name);
  1900. AppendMenu(hMenu, MF_SEPARATOR, ID_SEPARATOR, "");
  1901. service_installed = manage_service(0);
  1902. snprintf(buf,
  1903. sizeof(buf) - 1,
  1904. "NT service: %s installed",
  1905. service_installed ? "" : "not");
  1906. buf[sizeof(buf) - 1] = 0;
  1907. AppendMenu(hMenu, MF_STRING | MF_GRAYED, ID_SEPARATOR, buf);
  1908. AppendMenu(hMenu,
  1909. MF_STRING | (service_installed ? MF_GRAYED : 0),
  1910. ID_INSTALL_SERVICE,
  1911. "Install service");
  1912. AppendMenu(hMenu,
  1913. MF_STRING | (!service_installed ? MF_GRAYED : 0),
  1914. ID_REMOVE_SERVICE,
  1915. "Deinstall service");
  1916. AppendMenu(hMenu, MF_SEPARATOR, ID_SEPARATOR, "");
  1917. AppendMenu(hMenu, MF_STRING, ID_CONNECT, "Start browser");
  1918. AppendMenu(hMenu, MF_STRING, ID_SETTINGS, "Edit settings");
  1919. AppendMenu(hMenu, MF_STRING, ID_PASSWORD, "Modify password file");
  1920. AppendMenu(hMenu, MF_STRING, ID_SYSINFO, "Show system info");
  1921. AppendMenu(hMenu, MF_SEPARATOR, ID_SEPARATOR, "");
  1922. AppendMenu(hMenu, MF_STRING, ID_QUIT, "Exit");
  1923. GetCursorPos(&pt);
  1924. SetForegroundWindow(hWnd);
  1925. TrackPopupMenu(hMenu, 0, pt.x, pt.y, 0, hWnd, NULL);
  1926. PostMessage(hWnd, WM_NULL, 0, 0);
  1927. DestroyMenu(hMenu);
  1928. break;
  1929. }
  1930. break;
  1931. case WM_CLOSE:
  1932. stop_civetweb();
  1933. Shell_NotifyIcon(NIM_DELETE, &TrayIcon);
  1934. g_exit_flag = 1;
  1935. PostQuitMessage(0);
  1936. return 0; /* We've just sent our own quit message, with proper hwnd. */
  1937. default:
  1938. if (msg == s_uTaskbarRestart)
  1939. Shell_NotifyIcon(NIM_ADD, &TrayIcon);
  1940. }
  1941. return DefWindowProc(hWnd, msg, wParam, lParam);
  1942. }
  1943. static int
  1944. MakeConsole(void)
  1945. {
  1946. DWORD err;
  1947. int ok = (GetConsoleWindow() != NULL);
  1948. if (!ok) {
  1949. if (!AttachConsole(ATTACH_PARENT_PROCESS)) {
  1950. FreeConsole();
  1951. if (!AllocConsole()) {
  1952. err = GetLastError();
  1953. if (err == ERROR_ACCESS_DENIED) {
  1954. MessageBox(NULL,
  1955. "Insufficient rights to create a console window",
  1956. "Error",
  1957. MB_ICONERROR);
  1958. }
  1959. }
  1960. AttachConsole(GetCurrentProcessId());
  1961. }
  1962. ok = (GetConsoleWindow() != NULL);
  1963. if (ok) {
  1964. freopen("CONIN$", "r", stdin);
  1965. freopen("CONOUT$", "w", stdout);
  1966. freopen("CONOUT$", "w", stderr);
  1967. }
  1968. }
  1969. if (ok) {
  1970. SetConsoleTitle(g_server_name);
  1971. }
  1972. return ok;
  1973. }
  1974. int WINAPI
  1975. WinMain(HINSTANCE hInst, HINSTANCE hPrev, LPSTR cmdline, int show)
  1976. {
  1977. WNDCLASS cls;
  1978. HWND hWnd;
  1979. MSG msg;
  1980. #if defined(DEBUG)
  1981. (void)MakeConsole();
  1982. #endif
  1983. (void)hInst;
  1984. (void)hPrev;
  1985. (void)cmdline;
  1986. (void)show;
  1987. init_server_name((int)__argc, (const char **)__argv);
  1988. memset(&cls, 0, sizeof(cls));
  1989. cls.lpfnWndProc = (WNDPROC)WindowProc;
  1990. cls.hIcon = LoadIcon(NULL, IDI_APPLICATION);
  1991. cls.lpszClassName = g_server_base_name;
  1992. RegisterClass(&cls);
  1993. hWnd = CreateWindow(cls.lpszClassName,
  1994. g_server_name,
  1995. WS_OVERLAPPEDWINDOW,
  1996. 0,
  1997. 0,
  1998. 0,
  1999. 0,
  2000. NULL,
  2001. NULL,
  2002. NULL,
  2003. NULL);
  2004. ShowWindow(hWnd, SW_HIDE);
  2005. if (g_icon_name) {
  2006. hIcon =
  2007. LoadImage(NULL, g_icon_name, IMAGE_ICON, 16, 16, LR_LOADFROMFILE);
  2008. } else {
  2009. hIcon = LoadImage(GetModuleHandle(NULL),
  2010. MAKEINTRESOURCE(ID_ICON),
  2011. IMAGE_ICON,
  2012. 16,
  2013. 16,
  2014. 0);
  2015. }
  2016. TrayIcon.cbSize = sizeof(TrayIcon);
  2017. TrayIcon.uID = ID_ICON;
  2018. TrayIcon.uFlags = NIF_ICON | NIF_MESSAGE | NIF_TIP;
  2019. TrayIcon.hIcon = hIcon;
  2020. TrayIcon.hWnd = hWnd;
  2021. snprintf(TrayIcon.szTip, sizeof(TrayIcon.szTip), "%s", g_server_name);
  2022. TrayIcon.uCallbackMessage = WM_USER;
  2023. Shell_NotifyIcon(NIM_ADD, &TrayIcon);
  2024. while (GetMessage(&msg, hWnd, 0, 0) > 0) {
  2025. TranslateMessage(&msg);
  2026. DispatchMessage(&msg);
  2027. }
  2028. /* Return the WM_QUIT value. */
  2029. return (int)msg.wParam;
  2030. }
  2031. int
  2032. main(int argc, char *argv[])
  2033. {
  2034. (void)argc;
  2035. (void)argv;
  2036. return WinMain(0, 0, 0, 0);
  2037. }
  2038. #elif defined(USE_COCOA)
  2039. #import <Cocoa/Cocoa.h>
  2040. @interface Civetweb : NSObject <NSApplicationDelegate>
  2041. - (void)openBrowser;
  2042. - (void)shutDown;
  2043. @end
  2044. @implementation Civetweb
  2045. - (void)openBrowser
  2046. {
  2047. [[NSWorkspace sharedWorkspace]
  2048. openURL:[NSURL URLWithString:[NSString stringWithUTF8String:
  2049. get_url_to_first_open_port(
  2050. g_ctx)]]];
  2051. }
  2052. - (void)editConfig
  2053. {
  2054. create_config_file(g_ctx, g_config_file_name);
  2055. NSString *path = [NSString stringWithUTF8String:g_config_file_name];
  2056. if (![[NSWorkspace sharedWorkspace] openFile:path
  2057. withApplication:@"TextEdit"]) {
  2058. NSAlert *alert = [[[NSAlert alloc] init] autorelease];
  2059. [alert setAlertStyle:NSWarningAlertStyle];
  2060. [alert setMessageText:NSLocalizedString(@"Unable to open config file.",
  2061. "")];
  2062. [alert setInformativeText:path];
  2063. (void)[alert runModal];
  2064. }
  2065. }
  2066. - (void)shutDown
  2067. {
  2068. [NSApp terminate:nil];
  2069. }
  2070. @end
  2071. int
  2072. main(int argc, char *argv[])
  2073. {
  2074. init_server_name(argc, (const char **)argv);
  2075. start_civetweb(argc, argv);
  2076. [NSAutoreleasePool new];
  2077. [NSApplication sharedApplication];
  2078. /* Add delegate to process menu item actions */
  2079. Civetweb *myDelegate = [[Civetweb alloc] autorelease];
  2080. [NSApp setDelegate:myDelegate];
  2081. /* Run this app as agent */
  2082. ProcessSerialNumber psn = {0, kCurrentProcess};
  2083. TransformProcessType(&psn, kProcessTransformToBackgroundApplication);
  2084. SetFrontProcess(&psn);
  2085. /* Add status bar menu */
  2086. id menu = [[NSMenu new] autorelease];
  2087. /* Add version menu item */
  2088. [menu
  2089. addItem:
  2090. [[[NSMenuItem alloc]
  2091. /*initWithTitle:[NSString stringWithFormat:@"%s", server_name]*/
  2092. initWithTitle:[NSString stringWithUTF8String:g_server_name]
  2093. action:@selector(noexist)
  2094. keyEquivalent:@""] autorelease]];
  2095. /* Add configuration menu item */
  2096. [menu addItem:[[[NSMenuItem alloc] initWithTitle:@"Edit configuration"
  2097. action:@selector(editConfig)
  2098. keyEquivalent:@""] autorelease]];
  2099. /* Add connect menu item */
  2100. [menu
  2101. addItem:[[[NSMenuItem alloc] initWithTitle:@"Open web root in a browser"
  2102. action:@selector(openBrowser)
  2103. keyEquivalent:@""] autorelease]];
  2104. /* Separator */
  2105. [menu addItem:[NSMenuItem separatorItem]];
  2106. /* Add quit menu item */
  2107. [menu addItem:[[[NSMenuItem alloc] initWithTitle:@"Quit"
  2108. action:@selector(shutDown)
  2109. keyEquivalent:@"q"] autorelease]];
  2110. /* Attach menu to the status bar */
  2111. id item = [[[NSStatusBar systemStatusBar]
  2112. statusItemWithLength:NSVariableStatusItemLength] retain];
  2113. [item setHighlightMode:YES];
  2114. [item setImage:[NSImage imageNamed:@"civetweb_22x22.png"]];
  2115. [item setMenu:menu];
  2116. /* Run the app */
  2117. [NSApp activateIgnoringOtherApps:YES];
  2118. [NSApp run];
  2119. stop_civetweb();
  2120. return EXIT_SUCCESS;
  2121. }
  2122. #else
  2123. int
  2124. main(int argc, char *argv[])
  2125. {
  2126. init_server_name(argc, (const char **)argv);
  2127. start_civetweb(argc, argv);
  2128. fprintf(stdout,
  2129. "%s started on port(s) %s with web root [%s]\n",
  2130. g_server_name,
  2131. mg_get_option(g_ctx, "listening_ports"),
  2132. mg_get_option(g_ctx, "document_root"));
  2133. while (g_exit_flag == 0) {
  2134. sleep(1);
  2135. }
  2136. fprintf(stdout,
  2137. "Exiting on signal %d, waiting for all threads to finish...",
  2138. g_exit_flag);
  2139. fflush(stdout);
  2140. stop_civetweb();
  2141. fprintf(stdout, "%s", " done.\n");
  2142. return EXIT_SUCCESS;
  2143. }
  2144. #endif /* _WIN32 */