main.c 65 KB

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