main.c 65 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640
  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. #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(int argc, 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 ((argc > 1) && (argv[1] != NULL) && (argv[1][0] != '-')
  441. && (argv[1][0] != 0)) {
  442. /* The first command line parameter is a config file name. */
  443. snprintf(g_config_file_name,
  444. sizeof(g_config_file_name) - 1,
  445. "%s",
  446. argv[1]);
  447. cmd_line_opts_start = 2;
  448. } else if ((p = strrchr(argv[0], DIRSEP)) == NULL) {
  449. /* No config file set. No path in arg[0] found.
  450. * Use default file name in the current path. */
  451. snprintf(g_config_file_name,
  452. sizeof(g_config_file_name) - 1,
  453. "%s",
  454. CONFIG_FILE);
  455. } else {
  456. /* No config file set. Path to exe found in arg[0].
  457. * Use default file name next to the executable. */
  458. snprintf(g_config_file_name,
  459. sizeof(g_config_file_name) - 1,
  460. "%.*s%c%s",
  461. (int)(p - argv[0]),
  462. argv[0],
  463. DIRSEP,
  464. CONFIG_FILE);
  465. }
  466. g_config_file_name[sizeof(g_config_file_name) - 1] = 0;
  467. #ifdef CONFIG_FILE2
  468. fp = fopen(g_config_file_name, "r");
  469. /* try alternate config file */
  470. if (fp == NULL) {
  471. fp = fopen(CONFIG_FILE2, "r");
  472. if (fp != NULL) {
  473. strcpy(g_config_file_name, CONFIG_FILE2);
  474. }
  475. }
  476. if (fp != NULL) {
  477. fclose(fp);
  478. }
  479. #endif
  480. /* read all configurations from a config file */
  481. if (0 == read_config_file(g_config_file_name, options)) {
  482. if (cmd_line_opts_start == 2) {
  483. /* If config file was set in command line and open failed, die. */
  484. /* Errno will still hold the error from fopen. */
  485. die("Cannot open config file %s: %s",
  486. g_config_file_name,
  487. strerror(errno));
  488. }
  489. /* Otherwise: CivetWeb can work without a config file */
  490. }
  491. /* If we're under MacOS and started by launchd, then the second
  492. argument is process serial number, -psn_.....
  493. In this case, don't process arguments at all. */
  494. if (argv[1] == NULL || memcmp(argv[1], "-psn_", 5) != 0) {
  495. /* Handle command line flags.
  496. They override config file and default settings. */
  497. for (i = cmd_line_opts_start; argv[i] != NULL; i += 2) {
  498. if (argv[i][0] != '-' || argv[i + 1] == NULL) {
  499. show_usage_and_exit(argv[0]);
  500. }
  501. if (!set_option(options, &argv[i][1], argv[i + 1])) {
  502. fprintf(
  503. stderr,
  504. "command line option is invalid, ignoring it:\n %s %s\n",
  505. argv[i],
  506. argv[i + 1]);
  507. }
  508. }
  509. }
  510. }
  511. static void
  512. init_server_name(int argc, const char *argv[])
  513. {
  514. int i;
  515. assert(sizeof(main_config_options) / sizeof(main_config_options[0])
  516. == NUM_MAIN_OPTIONS + 1);
  517. assert((strlen(mg_version()) + 12) < sizeof(g_server_base_name));
  518. snprintf(g_server_base_name,
  519. sizeof(g_server_base_name),
  520. "CivetWeb V%s",
  521. mg_version());
  522. g_server_name = g_server_base_name;
  523. for (i = 0; i < argc - 1; i++) {
  524. if ((argv[i][0] == '-')
  525. && (0 == strcmp(argv[i] + 1,
  526. main_config_options[OPTION_TITLE].name))) {
  527. g_server_name = (const char *)(argv[i + 1]);
  528. }
  529. }
  530. g_icon_name = NULL;
  531. for (i = 0; i < argc - 1; i++) {
  532. if ((argv[i][0] == '-')
  533. && (0 == strcmp(argv[i] + 1,
  534. main_config_options[OPTION_ICON].name))) {
  535. g_icon_name = (const char *)(argv[i + 1]);
  536. }
  537. }
  538. }
  539. static int
  540. log_message(const struct mg_connection *conn, const char *message)
  541. {
  542. const struct mg_context *ctx = mg_get_context(conn);
  543. struct tuser_data *ud = (struct tuser_data *)mg_get_user_data(ctx);
  544. fprintf(stderr, "%s\n", message);
  545. if (ud->first_message == NULL) {
  546. ud->first_message = sdup(message);
  547. }
  548. return 0;
  549. }
  550. static int
  551. is_path_absolute(const char *path)
  552. {
  553. #ifdef _WIN32
  554. return path != NULL
  555. && ((path[0] == '\\' && path[1] == '\\') || /* UNC path, e.g.
  556. \\server\dir */
  557. (isalpha(path[0]) && path[1] == ':'
  558. && path[2] == '\\')); /* E.g. X:\dir */
  559. #else
  560. return path != NULL && path[0] == '/';
  561. #endif
  562. }
  563. static void
  564. verify_existence(char **options, const char *option_name, int must_be_dir)
  565. {
  566. struct stat st;
  567. const char *path = get_option(options, option_name);
  568. #ifdef _WIN32
  569. wchar_t wbuf[1024];
  570. char mbbuf[1024];
  571. int len;
  572. if (path) {
  573. memset(wbuf, 0, sizeof(wbuf));
  574. memset(mbbuf, 0, sizeof(mbbuf));
  575. len = MultiByteToWideChar(CP_UTF8,
  576. 0,
  577. path,
  578. -1,
  579. wbuf,
  580. (int)sizeof(wbuf) / sizeof(wbuf[0]) - 1);
  581. wcstombs(mbbuf, wbuf, sizeof(mbbuf) - 1);
  582. path = mbbuf;
  583. (void)len;
  584. }
  585. #endif
  586. if (path != NULL && (stat(path, &st) != 0
  587. || ((S_ISDIR(st.st_mode) ? 1 : 0) != must_be_dir))) {
  588. die("Invalid path for %s: [%s]: (%s). Make sure that path is either "
  589. "absolute, or it is relative to civetweb executable.",
  590. option_name,
  591. path,
  592. strerror(errno));
  593. }
  594. }
  595. static void
  596. set_absolute_path(char *options[],
  597. const char *option_name,
  598. const char *path_to_civetweb_exe)
  599. {
  600. char path[PATH_MAX] = "", absolute[PATH_MAX] = "";
  601. const char *option_value;
  602. const char *p;
  603. /* Check whether option is already set */
  604. option_value = get_option(options, option_name);
  605. /* If option is already set and it is an absolute path,
  606. leave it as it is -- it's already absolute. */
  607. if (option_value != NULL && !is_path_absolute(option_value)) {
  608. /* Not absolute. Use the directory where civetweb executable lives
  609. be the relative directory for everything.
  610. Extract civetweb executable directory into path. */
  611. if ((p = strrchr(path_to_civetweb_exe, DIRSEP)) == NULL) {
  612. IGNORE_UNUSED_RESULT(getcwd(path, sizeof(path)));
  613. } else {
  614. snprintf(path,
  615. sizeof(path) - 1,
  616. "%.*s",
  617. (int)(p - path_to_civetweb_exe),
  618. path_to_civetweb_exe);
  619. path[sizeof(path) - 1] = 0;
  620. }
  621. strncat(path, "/", sizeof(path) - strlen(path) - 1);
  622. strncat(path, option_value, sizeof(path) - strlen(path) - 1);
  623. /* Absolutize the path, and set the option */
  624. IGNORE_UNUSED_RESULT(abs_path(path, absolute, sizeof(absolute)));
  625. set_option(options, option_name, absolute);
  626. }
  627. }
  628. #ifdef USE_LUA
  629. #include "civetweb_lua.h"
  630. #include "civetweb_private_lua.h"
  631. static int
  632. run_lua(const char *file_name)
  633. {
  634. struct lua_State *L;
  635. int lua_ret;
  636. int func_ret = EXIT_FAILURE;
  637. const char *lua_err_txt;
  638. #ifdef WIN32
  639. (void)MakeConsole();
  640. #endif
  641. L = luaL_newstate();
  642. if (L == NULL) {
  643. fprintf(stderr, "Error: Cannot create Lua state\n");
  644. return EXIT_FAILURE;
  645. }
  646. civetweb_open_lua_libs(L);
  647. lua_ret = luaL_loadfile(L, file_name);
  648. if (lua_ret != LUA_OK) {
  649. /* Error when loading the file (e.g. file not found, out of memory, ...)
  650. */
  651. lua_err_txt = lua_tostring(L, -1);
  652. fprintf(stderr, "Error loading file %s: %s\n", file_name, lua_err_txt);
  653. } else {
  654. /* The script file is loaded, now call it */
  655. lua_ret = lua_pcall(L,
  656. /* no arguments */ 0,
  657. /* zero or one return value */ 1,
  658. /* errors as strint return value */ 0);
  659. if (lua_ret != LUA_OK) {
  660. /* Error when executing the script */
  661. lua_err_txt = lua_tostring(L, -1);
  662. fprintf(stderr,
  663. "Error running file %s: %s\n",
  664. file_name,
  665. lua_err_txt);
  666. } else {
  667. /* Script executed */
  668. if (lua_type(L, -1) == LUA_TNUMBER) {
  669. func_ret = (int)lua_tonumber(L, -1);
  670. } else {
  671. func_ret = EXIT_SUCCESS;
  672. }
  673. }
  674. }
  675. lua_close(L);
  676. return func_ret;
  677. }
  678. #endif
  679. #ifdef USE_DUKTAPE
  680. #include "duktape.h"
  681. static int
  682. run_duktape(const char *file_name)
  683. {
  684. duk_context *ctx = NULL;
  685. #ifdef WIN32
  686. (void)MakeConsole();
  687. #endif
  688. ctx = duk_create_heap_default();
  689. if (!ctx) {
  690. fprintf(stderr, "Failed to create a Duktape heap.\n");
  691. goto finished;
  692. }
  693. if (duk_peval_file(ctx, file_name) != 0) {
  694. fprintf(stderr, "%s\n", duk_safe_to_string(ctx, -1));
  695. goto finished;
  696. }
  697. duk_pop(ctx); /* ignore result */
  698. finished:
  699. duk_destroy_heap(ctx);
  700. return 0;
  701. }
  702. #endif
  703. #if defined(__MINGW32__) || defined(__MINGW64__)
  704. /* For __MINGW32/64_MAJOR/MINOR_VERSION define */
  705. #include <_mingw.h>
  706. #endif
  707. static void
  708. start_civetweb(int argc, char *argv[])
  709. {
  710. struct mg_callbacks callbacks;
  711. char *options[2 * MAX_OPTIONS + 1];
  712. int i;
  713. /* Start option -I:
  714. * Show system information and exit
  715. * This is very useful for diagnosis. */
  716. if (argc > 1 && !strcmp(argv[1], "-I")) {
  717. const char *version = mg_version();
  718. #if defined(_WIN32)
  719. #if !defined(__SYMBIAN32__)
  720. DWORD dwVersion = 0;
  721. DWORD dwMajorVersion = 0;
  722. DWORD dwMinorVersion = 0;
  723. SYSTEM_INFO si;
  724. GetSystemInfo(&si);
  725. #ifdef _MSC_VER
  726. #pragma warning(push)
  727. // GetVersion was declared deprecated
  728. #pragma warning(disable : 4996)
  729. #endif
  730. dwVersion = GetVersion();
  731. #ifdef _MSC_VER
  732. #pragma warning(pop)
  733. #endif
  734. dwMajorVersion = (DWORD)(LOBYTE(LOWORD(dwVersion)));
  735. dwMinorVersion = (DWORD)(HIBYTE(LOWORD(dwVersion)));
  736. (void)MakeConsole();
  737. fprintf(stdout, "\n%s\n", g_server_name);
  738. fprintf(stdout,
  739. "%s - Windows %u.%u\n",
  740. g_server_base_name,
  741. (unsigned)dwMajorVersion,
  742. (unsigned)dwMinorVersion);
  743. fprintf(stdout,
  744. "CPU: type %u, cores %u, mask %x\n",
  745. (unsigned)si.wProcessorArchitecture,
  746. (unsigned)si.dwNumberOfProcessors,
  747. (unsigned)si.dwActiveProcessorMask);
  748. #else
  749. fprintf(stdout, "\n%s\n", g_server_name);
  750. fprintf(stdout, "%s - Symbian\n", g_server_base_name);
  751. #endif
  752. #else
  753. struct utsname name;
  754. memset(&name, 0, sizeof(name));
  755. uname(&name);
  756. fprintf(stdout, "\n%s\n", g_server_name);
  757. fprintf(stdout,
  758. "%s - %s %s (%s) - %s\n",
  759. g_server_base_name,
  760. name.sysname,
  761. name.version,
  762. name.release,
  763. name.machine);
  764. #endif
  765. fprintf(stdout, "Features:");
  766. if (mg_check_feature(1)) {
  767. fprintf(stdout, " Files");
  768. }
  769. if (mg_check_feature(2)) {
  770. fprintf(stdout, " HTTPS");
  771. }
  772. if (mg_check_feature(4)) {
  773. fprintf(stdout, " CGI");
  774. }
  775. if (mg_check_feature(8)) {
  776. fprintf(stdout, " IPv6");
  777. }
  778. if (mg_check_feature(16)) {
  779. fprintf(stdout, " WebSockets");
  780. }
  781. if (mg_check_feature(32)) {
  782. fprintf(stdout, " Lua");
  783. }
  784. fprintf(stdout, "\n");
  785. #ifdef USE_LUA
  786. fprintf(stdout,
  787. "Lua Version: %u (%s)\n",
  788. (unsigned)LUA_VERSION_NUM,
  789. LUA_RELEASE);
  790. #endif
  791. fprintf(stdout, "Version: %s\n", version);
  792. fprintf(stdout, "Build: %s\n", __DATE__);
  793. /* http://sourceforge.net/p/predef/wiki/Compilers/ */
  794. #if defined(_MSC_VER)
  795. fprintf(stdout,
  796. "MSC: %u (%u)\n",
  797. (unsigned)_MSC_VER,
  798. (unsigned)_MSC_FULL_VER);
  799. #elif defined(__MINGW64__)
  800. fprintf(stdout,
  801. "MinGW64: %u.%u\n",
  802. (unsigned)__MINGW64_VERSION_MAJOR,
  803. (unsigned)__MINGW64_VERSION_MINOR);
  804. fprintf(stdout,
  805. "MinGW32: %u.%u\n",
  806. (unsigned)__MINGW32_MAJOR_VERSION,
  807. (unsigned)__MINGW32_MINOR_VERSION);
  808. #elif defined(__MINGW32__)
  809. fprintf(stdout,
  810. "MinGW32: %u.%u\n",
  811. (unsigned)__MINGW32_MAJOR_VERSION,
  812. (unsigned)__MINGW32_MINOR_VERSION);
  813. #elif defined(__clang__)
  814. fprintf(stdout,
  815. "clang: %u.%u.%u (%s)\n",
  816. __clang_major__,
  817. __clang_minor__,
  818. __clang_patchlevel__,
  819. __clang_version__);
  820. #elif defined(__GNUC__)
  821. fprintf(stdout,
  822. "gcc: %u.%u.%u\n",
  823. (unsigned)__GNUC__,
  824. (unsigned)__GNUC_MINOR__,
  825. (unsigned)__GNUC_PATCHLEVEL__);
  826. #elif defined(__INTEL_COMPILER)
  827. fprintf(stdout, "Intel C/C++: %u\n", (unsigned)__INTEL_COMPILER);
  828. #elif defined(__BORLANDC__)
  829. fprintf(stdout, "Borland C: 0x%x\n", (unsigned)__BORLANDC__);
  830. #elif defined(__SUNPRO_C)
  831. fprintf(stdout, "Solaris: 0x%x\n", (unsigned)__SUNPRO_C);
  832. #else
  833. fprintf(stdout, "Other\n");
  834. #endif
  835. /* Determine 32/64 bit data mode.
  836. * see https://en.wikipedia.org/wiki/64-bit_computing */
  837. fprintf(stdout,
  838. "Data model: i:%u/%u/%u/%u, f:%u/%u/%u, c:%u/%u, "
  839. "p:%u, s:%u, t:%u\n",
  840. (unsigned)sizeof(short),
  841. (unsigned)sizeof(int),
  842. (unsigned)sizeof(long),
  843. (unsigned)sizeof(long long),
  844. (unsigned)sizeof(float),
  845. (unsigned)sizeof(double),
  846. (unsigned)sizeof(long double),
  847. (unsigned)sizeof(char),
  848. (unsigned)sizeof(wchar_t),
  849. (unsigned)sizeof(void *),
  850. (unsigned)sizeof(size_t),
  851. (unsigned)sizeof(time_t));
  852. exit(EXIT_SUCCESS);
  853. }
  854. /* Edit passwords file: Add user or change password, if -A option is
  855. * specified */
  856. if (argc > 1 && !strcmp(argv[1], "-A")) {
  857. if (argc != 6) {
  858. show_usage_and_exit(argv[0]);
  859. }
  860. exit(mg_modify_passwords_file(argv[2], argv[3], argv[4], argv[5])
  861. ? EXIT_SUCCESS
  862. : EXIT_FAILURE);
  863. }
  864. /* Edit passwords file: Remove user, if -R option is specified */
  865. if (argc > 1 && !strcmp(argv[1], "-R")) {
  866. if (argc != 5) {
  867. show_usage_and_exit(argv[0]);
  868. }
  869. exit(mg_modify_passwords_file(argv[2], argv[3], argv[4], NULL)
  870. ? EXIT_SUCCESS
  871. : EXIT_FAILURE);
  872. }
  873. /* Call Lua with additional CivetWeb specific Lua functions, if -L option
  874. * is specified */
  875. if (argc > 1 && !strcmp(argv[1], "-L")) {
  876. #ifdef USE_LUA
  877. if (argc != 3) {
  878. show_usage_and_exit(argv[0]);
  879. }
  880. exit(run_lua(argv[2]));
  881. #else
  882. show_server_name();
  883. fprintf(stderr, "\nError: Lua support not enabled\n");
  884. exit(EXIT_FAILURE);
  885. #endif
  886. }
  887. /* Call Duktape, if -E option is specified */
  888. if (argc > 1 && !strcmp(argv[1], "-E")) {
  889. #ifdef USE_DUKTAPE
  890. if (argc != 3) {
  891. show_usage_and_exit(argv[0]);
  892. }
  893. exit(run_duktape(argv[2]));
  894. #else
  895. show_server_name();
  896. fprintf(stderr, "\nError: Ecmascript support not enabled\n");
  897. exit(EXIT_FAILURE);
  898. #endif
  899. }
  900. /* Show usage if -h or --help options are specified */
  901. if (argc == 2 && (!strcmp(argv[1], "-h") || !strcmp(argv[1], "-H")
  902. || !strcmp(argv[1], "--help"))) {
  903. show_usage_and_exit(argv[0]);
  904. }
  905. options[0] = NULL;
  906. set_option(options, "document_root", ".");
  907. /* Update config based on command line arguments */
  908. process_command_line_arguments(argc, argv, options);
  909. /* Make sure we have absolute paths for files and directories */
  910. set_absolute_path(options, "document_root", argv[0]);
  911. set_absolute_path(options, "put_delete_auth_file", argv[0]);
  912. set_absolute_path(options, "cgi_interpreter", argv[0]);
  913. set_absolute_path(options, "access_log_file", argv[0]);
  914. set_absolute_path(options, "error_log_file", argv[0]);
  915. set_absolute_path(options, "global_auth_file", argv[0]);
  916. #ifdef USE_LUA
  917. set_absolute_path(options, "lua_preload_file", argv[0]);
  918. #endif
  919. set_absolute_path(options, "ssl_certificate", argv[0]);
  920. /* Make extra verification for certain options */
  921. verify_existence(options, "document_root", 1);
  922. verify_existence(options, "cgi_interpreter", 0);
  923. verify_existence(options, "ssl_certificate", 0);
  924. verify_existence(options, "ssl_ca_path", 1);
  925. verify_existence(options, "ssl_ca_file", 0);
  926. #ifdef USE_LUA
  927. verify_existence(options, "lua_preload_file", 0);
  928. #endif
  929. /* Setup signal handler: quit on Ctrl-C */
  930. signal(SIGTERM, signal_handler);
  931. signal(SIGINT, signal_handler);
  932. /* Initialize user data */
  933. memset(&g_user_data, 0, sizeof(g_user_data));
  934. /* Start Civetweb */
  935. memset(&callbacks, 0, sizeof(callbacks));
  936. callbacks.log_message = &log_message;
  937. g_ctx = mg_start(&callbacks, &g_user_data, (const char **)options);
  938. /* mg_start copies all options to an internal buffer.
  939. * The options data field here is not required anymore. */
  940. for (i = 0; options[i] != NULL; i++) {
  941. free(options[i]);
  942. }
  943. /* If mg_start fails, it returns NULL */
  944. if (g_ctx == NULL) {
  945. die("Failed to start %s:\n%s",
  946. g_server_name,
  947. ((g_user_data.first_message == NULL) ? "unknown reason"
  948. : g_user_data.first_message));
  949. }
  950. }
  951. static void
  952. stop_civetweb(void)
  953. {
  954. mg_stop(g_ctx);
  955. free(g_user_data.first_message);
  956. g_user_data.first_message = NULL;
  957. }
  958. #ifdef _WIN32
  959. /* Win32 has a small GUI.
  960. * Define some GUI elements and Windows message handlers. */
  961. enum {
  962. ID_ICON = 100,
  963. ID_QUIT,
  964. ID_SETTINGS,
  965. ID_SEPARATOR,
  966. ID_INSTALL_SERVICE,
  967. ID_REMOVE_SERVICE,
  968. ID_STATIC,
  969. ID_GROUP,
  970. ID_PASSWORD,
  971. ID_SAVE,
  972. ID_RESET_DEFAULTS,
  973. ID_RESET_FILE,
  974. ID_RESET_ACTIVE,
  975. ID_STATUS,
  976. ID_CONNECT,
  977. ID_ADD_USER,
  978. ID_ADD_USER_NAME,
  979. ID_ADD_USER_REALM,
  980. ID_INPUT_LINE,
  981. /* All dynamically created text boxes for options have IDs starting from
  982. ID_CONTROLS, incremented by one. */
  983. ID_CONTROLS = 200,
  984. /* Text boxes for files have "..." buttons to open file browser. These
  985. buttons have IDs that are ID_FILE_BUTTONS_DELTA higher than associated
  986. text box ID. */
  987. ID_FILE_BUTTONS_DELTA = 1000
  988. };
  989. static HICON hIcon;
  990. static SERVICE_STATUS ss;
  991. static SERVICE_STATUS_HANDLE hStatus;
  992. static const char *service_magic_argument = "--";
  993. static NOTIFYICONDATA TrayIcon;
  994. static void WINAPI
  995. ControlHandler(DWORD code)
  996. {
  997. if (code == SERVICE_CONTROL_STOP || code == SERVICE_CONTROL_SHUTDOWN) {
  998. ss.dwWin32ExitCode = 0;
  999. ss.dwCurrentState = SERVICE_STOPPED;
  1000. }
  1001. SetServiceStatus(hStatus, &ss);
  1002. }
  1003. static void WINAPI
  1004. ServiceMain(void)
  1005. {
  1006. ss.dwServiceType = SERVICE_WIN32;
  1007. ss.dwCurrentState = SERVICE_RUNNING;
  1008. ss.dwControlsAccepted = SERVICE_ACCEPT_STOP | SERVICE_ACCEPT_SHUTDOWN;
  1009. hStatus = RegisterServiceCtrlHandler(g_server_name, ControlHandler);
  1010. SetServiceStatus(hStatus, &ss);
  1011. while (ss.dwCurrentState == SERVICE_RUNNING) {
  1012. Sleep(1000);
  1013. }
  1014. stop_civetweb();
  1015. ss.dwCurrentState = SERVICE_STOPPED;
  1016. ss.dwWin32ExitCode = (DWORD)-1;
  1017. SetServiceStatus(hStatus, &ss);
  1018. }
  1019. static void
  1020. show_error(void)
  1021. {
  1022. char buf[256];
  1023. FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
  1024. NULL,
  1025. GetLastError(),
  1026. MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
  1027. buf,
  1028. sizeof(buf),
  1029. NULL);
  1030. MessageBox(NULL, buf, "Error", MB_OK);
  1031. }
  1032. static void *
  1033. align(void *ptr, uintptr_t alig)
  1034. {
  1035. uintptr_t ul = (uintptr_t)ptr;
  1036. ul += alig;
  1037. ul &= ~alig;
  1038. return ((void *)ul);
  1039. }
  1040. static void
  1041. save_config(HWND hDlg, FILE *fp)
  1042. {
  1043. char value[2000] = "";
  1044. const char *default_value;
  1045. const struct mg_option *options;
  1046. int i, id;
  1047. fprintf(fp, "%s", config_file_top_comment);
  1048. options = mg_get_valid_options();
  1049. for (i = 0; options[i].name != NULL; i++) {
  1050. id = ID_CONTROLS + i;
  1051. if (options[i].type == CONFIG_TYPE_BOOLEAN) {
  1052. snprintf(value,
  1053. sizeof(value) - 1,
  1054. "%s",
  1055. IsDlgButtonChecked(hDlg, id) ? "yes" : "no");
  1056. value[sizeof(value) - 1] = 0;
  1057. } else {
  1058. GetDlgItemText(hDlg, id, value, sizeof(value));
  1059. }
  1060. default_value =
  1061. options[i].default_value == NULL ? "" : options[i].default_value;
  1062. /* If value is the same as default, skip it */
  1063. if (strcmp(value, default_value) != 0) {
  1064. fprintf(fp, "%s %s\n", options[i].name, value);
  1065. }
  1066. }
  1067. }
  1068. static INT_PTR CALLBACK
  1069. SettingsDlgProc(HWND hDlg, UINT msg, WPARAM wParam, LPARAM lParam)
  1070. {
  1071. FILE *fp;
  1072. int i, j;
  1073. const char *name, *value;
  1074. const struct mg_option *default_options = mg_get_valid_options();
  1075. char *file_options[MAX_OPTIONS * 2 + 1] = {0};
  1076. char *title;
  1077. (void)lParam;
  1078. switch (msg) {
  1079. case WM_CLOSE:
  1080. DestroyWindow(hDlg);
  1081. break;
  1082. case WM_COMMAND:
  1083. switch (LOWORD(wParam)) {
  1084. case ID_SAVE:
  1085. EnableWindow(GetDlgItem(hDlg, ID_SAVE), FALSE);
  1086. if ((fp = fopen(g_config_file_name, "w+")) != NULL) {
  1087. save_config(hDlg, fp);
  1088. fclose(fp);
  1089. stop_civetweb();
  1090. start_civetweb(__argc, __argv);
  1091. }
  1092. EnableWindow(GetDlgItem(hDlg, ID_SAVE), TRUE);
  1093. break;
  1094. case ID_RESET_DEFAULTS:
  1095. for (i = 0; default_options[i].name != NULL; i++) {
  1096. name = default_options[i].name;
  1097. value = default_options[i].default_value == NULL
  1098. ? ""
  1099. : default_options[i].default_value;
  1100. if (default_options[i].type == CONFIG_TYPE_BOOLEAN) {
  1101. CheckDlgButton(hDlg,
  1102. ID_CONTROLS + i,
  1103. !strcmp(value, "yes") ? BST_CHECKED
  1104. : BST_UNCHECKED);
  1105. } else {
  1106. SetWindowText(GetDlgItem(hDlg, ID_CONTROLS + i), value);
  1107. }
  1108. }
  1109. break;
  1110. case ID_RESET_FILE:
  1111. read_config_file(g_config_file_name, file_options);
  1112. for (i = 0; default_options[i].name != NULL; i++) {
  1113. name = default_options[i].name;
  1114. value = default_options[i].default_value;
  1115. for (j = 0; file_options[j * 2] != NULL; j++) {
  1116. if (!strcmp(name, file_options[j * 2])) {
  1117. value = file_options[j * 2 + 1];
  1118. }
  1119. }
  1120. if (value == NULL) {
  1121. value = "";
  1122. }
  1123. if (default_options[i].type == CONFIG_TYPE_BOOLEAN) {
  1124. CheckDlgButton(hDlg,
  1125. ID_CONTROLS + i,
  1126. !strcmp(value, "yes") ? BST_CHECKED
  1127. : BST_UNCHECKED);
  1128. } else {
  1129. SetWindowText(GetDlgItem(hDlg, ID_CONTROLS + i), value);
  1130. }
  1131. }
  1132. for (i = 0; i < MAX_OPTIONS; i++) {
  1133. free(file_options[2 * i]);
  1134. free(file_options[2 * i + 1]);
  1135. }
  1136. break;
  1137. case ID_RESET_ACTIVE:
  1138. for (i = 0; default_options[i].name != NULL; i++) {
  1139. name = default_options[i].name;
  1140. value = mg_get_option(g_ctx, name);
  1141. if (default_options[i].type == CONFIG_TYPE_BOOLEAN) {
  1142. CheckDlgButton(hDlg,
  1143. ID_CONTROLS + i,
  1144. !strcmp(value, "yes") ? BST_CHECKED
  1145. : BST_UNCHECKED);
  1146. } else {
  1147. SetDlgItemText(hDlg,
  1148. ID_CONTROLS + i,
  1149. value == NULL ? "" : value);
  1150. }
  1151. }
  1152. break;
  1153. }
  1154. for (i = 0; default_options[i].name != NULL; i++) {
  1155. name = default_options[i].name;
  1156. if (((default_options[i].type == CONFIG_TYPE_FILE)
  1157. || (default_options[i].type == CONFIG_TYPE_DIRECTORY))
  1158. && LOWORD(wParam) == ID_CONTROLS + i + ID_FILE_BUTTONS_DELTA) {
  1159. OPENFILENAME of;
  1160. BROWSEINFO bi;
  1161. char path[PATH_MAX] = "";
  1162. memset(&of, 0, sizeof(of));
  1163. of.lStructSize = sizeof(of);
  1164. of.hwndOwner = (HWND)hDlg;
  1165. of.lpstrFile = path;
  1166. of.nMaxFile = sizeof(path);
  1167. of.lpstrInitialDir = mg_get_option(g_ctx, "document_root");
  1168. of.Flags =
  1169. OFN_CREATEPROMPT | OFN_NOCHANGEDIR | OFN_HIDEREADONLY;
  1170. memset(&bi, 0, sizeof(bi));
  1171. bi.hwndOwner = (HWND)hDlg;
  1172. bi.lpszTitle = "Choose WWW root directory:";
  1173. bi.ulFlags = BIF_RETURNONLYFSDIRS;
  1174. if (default_options[i].type == CONFIG_TYPE_DIRECTORY) {
  1175. SHGetPathFromIDList(SHBrowseForFolder(&bi), path);
  1176. } else {
  1177. GetOpenFileName(&of);
  1178. }
  1179. if (path[0] != '\0') {
  1180. SetWindowText(GetDlgItem(hDlg, ID_CONTROLS + i), path);
  1181. }
  1182. }
  1183. }
  1184. break;
  1185. case WM_INITDIALOG:
  1186. SendMessage(hDlg, WM_SETICON, (WPARAM)ICON_SMALL, (LPARAM)hIcon);
  1187. SendMessage(hDlg, WM_SETICON, (WPARAM)ICON_BIG, (LPARAM)hIcon);
  1188. title = malloc(strlen(g_server_name) + 16);
  1189. if (title) {
  1190. strcpy(title, g_server_name);
  1191. strcat(title, " settings");
  1192. SetWindowText(hDlg, title);
  1193. free(title);
  1194. }
  1195. SetFocus(GetDlgItem(hDlg, ID_SAVE));
  1196. /* Init dialog with active settings */
  1197. SendMessage(hDlg, WM_COMMAND, ID_RESET_ACTIVE, 0);
  1198. /* alternative: SendMessage(hDlg, WM_COMMAND, ID_RESET_FILE, 0); */
  1199. break;
  1200. default:
  1201. break;
  1202. }
  1203. return FALSE;
  1204. }
  1205. struct tstring_input_buf {
  1206. unsigned buflen;
  1207. char *buffer;
  1208. };
  1209. static INT_PTR CALLBACK
  1210. InputDlgProc(HWND hDlg, UINT msg, WPARAM wParam, LPARAM lP)
  1211. {
  1212. static struct tstring_input_buf *inBuf = 0;
  1213. WORD ctrlId;
  1214. switch (msg) {
  1215. case WM_CLOSE:
  1216. inBuf = 0;
  1217. DestroyWindow(hDlg);
  1218. break;
  1219. case WM_COMMAND:
  1220. ctrlId = LOWORD(wParam);
  1221. if (ctrlId == IDOK) {
  1222. /* Add user */
  1223. GetWindowText(GetDlgItem(hDlg, ID_INPUT_LINE),
  1224. inBuf->buffer,
  1225. (int)inBuf->buflen);
  1226. if (strlen(inBuf->buffer) > 0) {
  1227. EndDialog(hDlg, IDOK);
  1228. }
  1229. } else if (ctrlId == IDCANCEL) {
  1230. EndDialog(hDlg, IDCANCEL);
  1231. }
  1232. break;
  1233. case WM_INITDIALOG:
  1234. inBuf = (struct tstring_input_buf *)lP;
  1235. assert(inBuf != NULL);
  1236. assert((inBuf->buffer != NULL) && (inBuf->buflen != 0));
  1237. assert(strlen(inBuf->buffer) < inBuf->buflen);
  1238. SendMessage(hDlg, WM_SETICON, (WPARAM)ICON_SMALL, (LPARAM)hIcon);
  1239. SendMessage(hDlg, WM_SETICON, (WPARAM)ICON_BIG, (LPARAM)hIcon);
  1240. SendDlgItemMessage(
  1241. hDlg, ID_INPUT_LINE, EM_LIMITTEXT, inBuf->buflen - 1, 0);
  1242. SetWindowText(GetDlgItem(hDlg, ID_INPUT_LINE), inBuf->buffer);
  1243. SetWindowText(hDlg, "Modify password");
  1244. SetFocus(GetDlgItem(hDlg, ID_INPUT_LINE));
  1245. break;
  1246. default:
  1247. break;
  1248. }
  1249. return FALSE;
  1250. }
  1251. static void
  1252. suggest_passwd(char *passwd)
  1253. {
  1254. unsigned u;
  1255. char *p;
  1256. union {
  1257. FILETIME ft;
  1258. LARGE_INTEGER li;
  1259. } num;
  1260. /* valid characters are 32 to 126 */
  1261. GetSystemTimeAsFileTime(&num.ft);
  1262. num.li.HighPart |= (LONG)GetCurrentProcessId();
  1263. p = passwd;
  1264. while (num.li.QuadPart) {
  1265. u = (unsigned)(num.li.QuadPart % 95);
  1266. num.li.QuadPart -= u;
  1267. num.li.QuadPart /= 95;
  1268. *p = (char)(u + 32);
  1269. p++;
  1270. }
  1271. }
  1272. static void add_control(unsigned char **mem,
  1273. DLGTEMPLATE *dia,
  1274. WORD type,
  1275. WORD id,
  1276. DWORD style,
  1277. short x,
  1278. short y,
  1279. short cx,
  1280. short cy,
  1281. const char *caption);
  1282. static int
  1283. get_password(const char *user,
  1284. const char *realm,
  1285. char *passwd,
  1286. unsigned passwd_len)
  1287. {
  1288. #define HEIGHT (15)
  1289. #define WIDTH (280)
  1290. #define LABEL_WIDTH (90)
  1291. unsigned char mem[4096], *p;
  1292. DLGTEMPLATE *dia = (DLGTEMPLATE *)mem;
  1293. int ok;
  1294. short y;
  1295. struct tstring_input_buf dlgprms;
  1296. static struct {
  1297. DLGTEMPLATE template; /* 18 bytes */
  1298. WORD menu, class;
  1299. wchar_t caption[1];
  1300. WORD fontsiz;
  1301. wchar_t fontface[7];
  1302. } dialog_header = {{WS_CAPTION | WS_POPUP | WS_SYSMENU | WS_VISIBLE
  1303. | DS_SETFONT | WS_DLGFRAME,
  1304. WS_EX_TOOLWINDOW,
  1305. 0,
  1306. 200,
  1307. 200,
  1308. WIDTH,
  1309. 0},
  1310. 0,
  1311. 0,
  1312. L"",
  1313. 8,
  1314. L"Tahoma"};
  1315. dlgprms.buffer = passwd;
  1316. dlgprms.buflen = passwd_len;
  1317. assert((user != NULL) && (realm != NULL) && (passwd != NULL));
  1318. if (guard < 100) {
  1319. guard += 100;
  1320. } else {
  1321. return 0;
  1322. }
  1323. /* Create a password suggestion */
  1324. memset(passwd, 0, passwd_len);
  1325. suggest_passwd(passwd);
  1326. /* Create the dialog */
  1327. (void)memset(mem, 0, sizeof(mem));
  1328. (void)memcpy(mem, &dialog_header, sizeof(dialog_header));
  1329. p = mem + sizeof(dialog_header);
  1330. y = HEIGHT;
  1331. add_control(&p,
  1332. dia,
  1333. 0x82,
  1334. ID_STATIC,
  1335. WS_VISIBLE | WS_CHILD,
  1336. 10,
  1337. y,
  1338. LABEL_WIDTH,
  1339. HEIGHT,
  1340. "User:");
  1341. add_control(&p,
  1342. dia,
  1343. 0x81,
  1344. ID_CONTROLS + 1,
  1345. WS_CHILD | WS_VISIBLE | WS_BORDER | ES_AUTOHSCROLL
  1346. | WS_DISABLED,
  1347. 15 + LABEL_WIDTH,
  1348. y,
  1349. WIDTH - LABEL_WIDTH - 25,
  1350. HEIGHT,
  1351. user);
  1352. y += HEIGHT;
  1353. add_control(&p,
  1354. dia,
  1355. 0x82,
  1356. ID_STATIC,
  1357. WS_VISIBLE | WS_CHILD,
  1358. 10,
  1359. y,
  1360. LABEL_WIDTH,
  1361. HEIGHT,
  1362. "Realm:");
  1363. add_control(&p,
  1364. dia,
  1365. 0x81,
  1366. ID_CONTROLS + 2,
  1367. WS_CHILD | WS_VISIBLE | WS_BORDER | ES_AUTOHSCROLL
  1368. | WS_DISABLED,
  1369. 15 + LABEL_WIDTH,
  1370. y,
  1371. WIDTH - LABEL_WIDTH - 25,
  1372. HEIGHT,
  1373. realm);
  1374. y += HEIGHT;
  1375. add_control(&p,
  1376. dia,
  1377. 0x82,
  1378. ID_STATIC,
  1379. WS_VISIBLE | WS_CHILD,
  1380. 10,
  1381. y,
  1382. LABEL_WIDTH,
  1383. HEIGHT,
  1384. "Password:");
  1385. add_control(&p,
  1386. dia,
  1387. 0x81,
  1388. ID_INPUT_LINE,
  1389. WS_CHILD | WS_VISIBLE | WS_BORDER | ES_AUTOHSCROLL | WS_TABSTOP,
  1390. 15 + LABEL_WIDTH,
  1391. y,
  1392. WIDTH - LABEL_WIDTH - 25,
  1393. HEIGHT,
  1394. "");
  1395. y += (WORD)(HEIGHT * 2);
  1396. add_control(&p,
  1397. dia,
  1398. 0x80,
  1399. IDOK,
  1400. WS_CHILD | WS_VISIBLE | BS_PUSHBUTTON | WS_TABSTOP,
  1401. 80,
  1402. y,
  1403. 55,
  1404. 12,
  1405. "Ok");
  1406. add_control(&p,
  1407. dia,
  1408. 0x80,
  1409. IDCANCEL,
  1410. WS_CHILD | WS_VISIBLE | BS_PUSHBUTTON | WS_TABSTOP,
  1411. 140,
  1412. y,
  1413. 55,
  1414. 12,
  1415. "Cancel");
  1416. assert((intptr_t)p - (intptr_t)mem < (intptr_t)sizeof(mem));
  1417. dia->cy = y + (WORD)(HEIGHT * 1.5);
  1418. ok = (IDOK == DialogBoxIndirectParam(
  1419. NULL, dia, NULL, InputDlgProc, (LPARAM)&dlgprms));
  1420. guard -= 100;
  1421. return ok;
  1422. #undef HEIGHT
  1423. #undef WIDTH
  1424. #undef LABEL_WIDTH
  1425. }
  1426. static INT_PTR CALLBACK
  1427. PasswordDlgProc(HWND hDlg, UINT msg, WPARAM wParam, LPARAM lP)
  1428. {
  1429. static const char *passfile = 0;
  1430. char domain[256], user[256], password[256];
  1431. WORD ctrlId;
  1432. switch (msg) {
  1433. case WM_CLOSE:
  1434. passfile = 0;
  1435. DestroyWindow(hDlg);
  1436. break;
  1437. case WM_COMMAND:
  1438. ctrlId = LOWORD(wParam);
  1439. if (ctrlId == ID_ADD_USER) {
  1440. /* Add user */
  1441. GetWindowText(GetDlgItem(hDlg, ID_ADD_USER_NAME),
  1442. user,
  1443. sizeof(user));
  1444. GetWindowText(GetDlgItem(hDlg, ID_ADD_USER_REALM),
  1445. domain,
  1446. sizeof(domain));
  1447. if (get_password(user, domain, password, sizeof(password))) {
  1448. mg_modify_passwords_file(passfile, domain, user, password);
  1449. EndDialog(hDlg, IDOK);
  1450. }
  1451. } else if ((ctrlId >= (ID_CONTROLS + ID_FILE_BUTTONS_DELTA * 3))
  1452. && (ctrlId < (ID_CONTROLS + ID_FILE_BUTTONS_DELTA * 4))) {
  1453. /* Modify password */
  1454. GetWindowText(GetDlgItem(hDlg, ctrlId - ID_FILE_BUTTONS_DELTA * 3),
  1455. user,
  1456. sizeof(user));
  1457. GetWindowText(GetDlgItem(hDlg, ctrlId - ID_FILE_BUTTONS_DELTA * 2),
  1458. domain,
  1459. sizeof(domain));
  1460. if (get_password(user, domain, password, sizeof(password))) {
  1461. mg_modify_passwords_file(passfile, domain, user, password);
  1462. EndDialog(hDlg, IDOK);
  1463. }
  1464. } else if ((ctrlId >= (ID_CONTROLS + ID_FILE_BUTTONS_DELTA * 2))
  1465. && (ctrlId < (ID_CONTROLS + ID_FILE_BUTTONS_DELTA * 3))) {
  1466. /* Remove user */
  1467. GetWindowText(GetDlgItem(hDlg, ctrlId - ID_FILE_BUTTONS_DELTA * 2),
  1468. user,
  1469. sizeof(user));
  1470. GetWindowText(GetDlgItem(hDlg, ctrlId - ID_FILE_BUTTONS_DELTA),
  1471. domain,
  1472. sizeof(domain));
  1473. mg_modify_passwords_file(passfile, domain, user, NULL);
  1474. EndDialog(hDlg, IDOK);
  1475. }
  1476. break;
  1477. case WM_INITDIALOG:
  1478. passfile = (const char *)lP;
  1479. SendMessage(hDlg, WM_SETICON, (WPARAM)ICON_SMALL, (LPARAM)hIcon);
  1480. SendMessage(hDlg, WM_SETICON, (WPARAM)ICON_BIG, (LPARAM)hIcon);
  1481. SetWindowText(hDlg, passfile);
  1482. SetFocus(GetDlgItem(hDlg, ID_ADD_USER_NAME));
  1483. break;
  1484. default:
  1485. break;
  1486. }
  1487. return FALSE;
  1488. }
  1489. static void
  1490. add_control(unsigned char **mem,
  1491. DLGTEMPLATE *dia,
  1492. WORD type,
  1493. WORD id,
  1494. DWORD style,
  1495. short x,
  1496. short y,
  1497. short cx,
  1498. short cy,
  1499. const char *caption)
  1500. {
  1501. DLGITEMTEMPLATE *tp;
  1502. LPWORD p;
  1503. dia->cdit++;
  1504. *mem = align(*mem, 3);
  1505. tp = (DLGITEMTEMPLATE *)*mem;
  1506. tp->id = id;
  1507. tp->style = style;
  1508. tp->dwExtendedStyle = 0;
  1509. tp->x = x;
  1510. tp->y = y;
  1511. tp->cx = cx;
  1512. tp->cy = cy;
  1513. p = align(*mem + sizeof(*tp), 1);
  1514. *p++ = 0xffff;
  1515. *p++ = type;
  1516. while (*caption != '\0') {
  1517. *p++ = (WCHAR)*caption++;
  1518. }
  1519. *p++ = 0;
  1520. p = align(p, 1);
  1521. *p++ = 0;
  1522. *mem = (unsigned char *)p;
  1523. }
  1524. static void
  1525. show_settings_dialog()
  1526. {
  1527. #define HEIGHT (15)
  1528. #define WIDTH (460)
  1529. #define LABEL_WIDTH (90)
  1530. unsigned char mem[16 * 1024], *p;
  1531. const struct mg_option *options;
  1532. DWORD style;
  1533. DLGTEMPLATE *dia = (DLGTEMPLATE *)mem;
  1534. WORD i, cl, nelems = 0;
  1535. short width, x, y;
  1536. static struct {
  1537. DLGTEMPLATE template; /* 18 bytes */
  1538. WORD menu, class;
  1539. wchar_t caption[1];
  1540. WORD fontsiz;
  1541. wchar_t fontface[7];
  1542. } dialog_header = {{WS_CAPTION | WS_POPUP | WS_SYSMENU | WS_VISIBLE
  1543. | DS_SETFONT | WS_DLGFRAME,
  1544. WS_EX_TOOLWINDOW,
  1545. 0,
  1546. 200,
  1547. 200,
  1548. WIDTH,
  1549. 0},
  1550. 0,
  1551. 0,
  1552. L"",
  1553. 8,
  1554. L"Tahoma"};
  1555. if (guard == 0) {
  1556. guard++;
  1557. } else {
  1558. return;
  1559. }
  1560. (void)memset(mem, 0, sizeof(mem));
  1561. (void)memcpy(mem, &dialog_header, sizeof(dialog_header));
  1562. p = mem + sizeof(dialog_header);
  1563. options = mg_get_valid_options();
  1564. for (i = 0; options[i].name != NULL; i++) {
  1565. style = WS_CHILD | WS_VISIBLE | WS_TABSTOP;
  1566. x = 10 + (WIDTH / 2) * (nelems % 2);
  1567. y = (nelems / 2 + 1) * HEIGHT + 5;
  1568. width = WIDTH / 2 - 20 - LABEL_WIDTH;
  1569. if (options[i].type == CONFIG_TYPE_NUMBER) {
  1570. style |= ES_NUMBER;
  1571. cl = 0x81;
  1572. style |= WS_BORDER | ES_AUTOHSCROLL;
  1573. } else if (options[i].type == CONFIG_TYPE_BOOLEAN) {
  1574. cl = 0x80;
  1575. style |= BS_AUTOCHECKBOX;
  1576. } else if ((options[i].type == CONFIG_TYPE_FILE)
  1577. || (options[i].type == CONFIG_TYPE_DIRECTORY)) {
  1578. style |= WS_BORDER | ES_AUTOHSCROLL;
  1579. width -= 20;
  1580. cl = 0x81;
  1581. add_control(&p,
  1582. dia,
  1583. 0x80,
  1584. ID_CONTROLS + i + ID_FILE_BUTTONS_DELTA,
  1585. WS_VISIBLE | WS_CHILD | BS_PUSHBUTTON,
  1586. x + width + LABEL_WIDTH + 5,
  1587. y,
  1588. 15,
  1589. 12,
  1590. "...");
  1591. } else {
  1592. cl = 0x81;
  1593. style |= WS_BORDER | ES_AUTOHSCROLL;
  1594. }
  1595. add_control(&p,
  1596. dia,
  1597. 0x82,
  1598. ID_STATIC,
  1599. WS_VISIBLE | WS_CHILD,
  1600. x,
  1601. y,
  1602. LABEL_WIDTH,
  1603. HEIGHT,
  1604. options[i].name);
  1605. add_control(&p,
  1606. dia,
  1607. cl,
  1608. ID_CONTROLS + i,
  1609. style,
  1610. x + LABEL_WIDTH,
  1611. y,
  1612. width,
  1613. 12,
  1614. "");
  1615. nelems++;
  1616. assert(((intptr_t)p - (intptr_t)mem) < (intptr_t)sizeof(mem));
  1617. }
  1618. y = (((nelems + 1) / 2 + 1) * HEIGHT + 5);
  1619. add_control(&p,
  1620. dia,
  1621. 0x80,
  1622. ID_GROUP,
  1623. WS_CHILD | WS_VISIBLE | BS_GROUPBOX,
  1624. 5,
  1625. 5,
  1626. WIDTH - 10,
  1627. y,
  1628. " Settings ");
  1629. y += 10;
  1630. add_control(&p,
  1631. dia,
  1632. 0x80,
  1633. ID_SAVE,
  1634. WS_CHILD | WS_VISIBLE | BS_PUSHBUTTON | WS_TABSTOP,
  1635. WIDTH - 70,
  1636. y,
  1637. 65,
  1638. 12,
  1639. "Save Settings");
  1640. add_control(&p,
  1641. dia,
  1642. 0x80,
  1643. ID_RESET_DEFAULTS,
  1644. WS_CHILD | WS_VISIBLE | BS_PUSHBUTTON | WS_TABSTOP,
  1645. WIDTH - 140,
  1646. y,
  1647. 65,
  1648. 12,
  1649. "Reset to defaults");
  1650. add_control(&p,
  1651. dia,
  1652. 0x80,
  1653. ID_RESET_FILE,
  1654. WS_CHILD | WS_VISIBLE | BS_PUSHBUTTON | WS_TABSTOP,
  1655. WIDTH - 210,
  1656. y,
  1657. 65,
  1658. 12,
  1659. "Reload from file");
  1660. add_control(&p,
  1661. dia,
  1662. 0x80,
  1663. ID_RESET_ACTIVE,
  1664. WS_CHILD | WS_VISIBLE | BS_PUSHBUTTON | WS_TABSTOP,
  1665. WIDTH - 280,
  1666. y,
  1667. 65,
  1668. 12,
  1669. "Reload active");
  1670. add_control(&p,
  1671. dia,
  1672. 0x82,
  1673. ID_STATIC,
  1674. WS_CHILD | WS_VISIBLE | WS_DISABLED,
  1675. 5,
  1676. y,
  1677. 100,
  1678. 12,
  1679. g_server_base_name);
  1680. assert(((intptr_t)p - (intptr_t)mem) < (intptr_t)sizeof(mem));
  1681. dia->cy = ((nelems + 1) / 2 + 1) * HEIGHT + 30;
  1682. DialogBoxIndirectParam(NULL, dia, NULL, SettingsDlgProc, (LPARAM)NULL);
  1683. guard--;
  1684. #undef HEIGHT
  1685. #undef WIDTH
  1686. #undef LABEL_WIDTH
  1687. }
  1688. static void
  1689. change_password_file()
  1690. {
  1691. #define HEIGHT (15)
  1692. #define WIDTH (320)
  1693. #define LABEL_WIDTH (90)
  1694. OPENFILENAME of;
  1695. char path[PATH_MAX] = PASSWORDS_FILE_NAME;
  1696. char strbuf[256], u[256], d[256];
  1697. HWND hDlg = NULL;
  1698. FILE *f;
  1699. short y, nelems;
  1700. unsigned char mem[4096], *p;
  1701. DLGTEMPLATE *dia = (DLGTEMPLATE *)mem;
  1702. const char *domain = mg_get_option(g_ctx, "authentication_domain");
  1703. static struct {
  1704. DLGTEMPLATE template; /* 18 bytes */
  1705. WORD menu, class;
  1706. wchar_t caption[1];
  1707. WORD fontsiz;
  1708. wchar_t fontface[7];
  1709. } dialog_header = {{WS_CAPTION | WS_POPUP | WS_SYSMENU | WS_VISIBLE
  1710. | DS_SETFONT | WS_DLGFRAME,
  1711. WS_EX_TOOLWINDOW,
  1712. 0,
  1713. 200,
  1714. 200,
  1715. WIDTH,
  1716. 0},
  1717. 0,
  1718. 0,
  1719. L"",
  1720. 8,
  1721. L"Tahoma"};
  1722. if (guard == 0) {
  1723. guard++;
  1724. } else {
  1725. return;
  1726. }
  1727. memset(&of, 0, sizeof(of));
  1728. of.lStructSize = sizeof(of);
  1729. of.hwndOwner = (HWND)hDlg;
  1730. of.lpstrFile = path;
  1731. of.nMaxFile = sizeof(path);
  1732. of.lpstrInitialDir = mg_get_option(g_ctx, "document_root");
  1733. of.Flags = OFN_CREATEPROMPT | OFN_NOCHANGEDIR | OFN_HIDEREADONLY;
  1734. if (IDOK != GetSaveFileName(&of)) {
  1735. guard--;
  1736. return;
  1737. }
  1738. f = fopen(path, "a+");
  1739. if (f) {
  1740. fclose(f);
  1741. } else {
  1742. MessageBox(NULL, path, "Can not open file", MB_ICONERROR);
  1743. guard--;
  1744. return;
  1745. }
  1746. do {
  1747. (void)memset(mem, 0, sizeof(mem));
  1748. (void)memcpy(mem, &dialog_header, sizeof(dialog_header));
  1749. p = mem + sizeof(dialog_header);
  1750. f = fopen(path, "r+");
  1751. if (!f) {
  1752. MessageBox(NULL, path, "Can not open file", MB_ICONERROR);
  1753. guard--;
  1754. return;
  1755. }
  1756. nelems = 0;
  1757. while (fgets(strbuf, sizeof(strbuf), f)) {
  1758. if (sscanf(strbuf, "%255[^:]:%255[^:]:%*s", u, d) != 2) {
  1759. continue;
  1760. }
  1761. u[255] = 0;
  1762. d[255] = 0;
  1763. y = (nelems + 1) * HEIGHT + 5;
  1764. add_control(&p,
  1765. dia,
  1766. 0x80,
  1767. ID_CONTROLS + nelems + ID_FILE_BUTTONS_DELTA * 3,
  1768. WS_CHILD | WS_VISIBLE | BS_PUSHBUTTON | WS_TABSTOP,
  1769. 10,
  1770. y,
  1771. 65,
  1772. 12,
  1773. "Modify password");
  1774. add_control(&p,
  1775. dia,
  1776. 0x80,
  1777. ID_CONTROLS + nelems + ID_FILE_BUTTONS_DELTA * 2,
  1778. WS_CHILD | WS_VISIBLE | BS_PUSHBUTTON | WS_TABSTOP,
  1779. 80,
  1780. y,
  1781. 55,
  1782. 12,
  1783. "Remove user");
  1784. add_control(&p,
  1785. dia,
  1786. 0x81,
  1787. ID_CONTROLS + nelems + ID_FILE_BUTTONS_DELTA,
  1788. WS_CHILD | WS_VISIBLE | WS_BORDER | ES_AUTOHSCROLL
  1789. | WS_DISABLED,
  1790. 245,
  1791. y,
  1792. 60,
  1793. 12,
  1794. d);
  1795. add_control(&p,
  1796. dia,
  1797. 0x81,
  1798. ID_CONTROLS + nelems,
  1799. WS_CHILD | WS_VISIBLE | WS_BORDER | ES_AUTOHSCROLL
  1800. | WS_DISABLED,
  1801. 140,
  1802. y,
  1803. 100,
  1804. 12,
  1805. u);
  1806. nelems++;
  1807. assert(((intptr_t)p - (intptr_t)mem) < (intptr_t)sizeof(mem));
  1808. }
  1809. fclose(f);
  1810. y = (nelems + 1) * HEIGHT + 10;
  1811. add_control(&p,
  1812. dia,
  1813. 0x80,
  1814. ID_ADD_USER,
  1815. WS_CHILD | WS_VISIBLE | BS_PUSHBUTTON | WS_TABSTOP,
  1816. 80,
  1817. y,
  1818. 55,
  1819. 12,
  1820. "Add user");
  1821. add_control(&p,
  1822. dia,
  1823. 0x81,
  1824. ID_ADD_USER_NAME,
  1825. WS_CHILD | WS_VISIBLE | WS_BORDER | ES_AUTOHSCROLL
  1826. | WS_TABSTOP,
  1827. 140,
  1828. y,
  1829. 100,
  1830. 12,
  1831. "");
  1832. add_control(&p,
  1833. dia,
  1834. 0x81,
  1835. ID_ADD_USER_REALM,
  1836. WS_CHILD | WS_VISIBLE | WS_BORDER | ES_AUTOHSCROLL
  1837. | WS_TABSTOP,
  1838. 245,
  1839. y,
  1840. 60,
  1841. 12,
  1842. domain);
  1843. y = (nelems + 2) * HEIGHT + 10;
  1844. add_control(&p,
  1845. dia,
  1846. 0x80,
  1847. ID_GROUP,
  1848. WS_CHILD | WS_VISIBLE | BS_GROUPBOX,
  1849. 5,
  1850. 5,
  1851. WIDTH - 10,
  1852. y,
  1853. " Users ");
  1854. y += HEIGHT;
  1855. add_control(&p,
  1856. dia,
  1857. 0x82,
  1858. ID_STATIC,
  1859. WS_CHILD | WS_VISIBLE | WS_DISABLED,
  1860. 5,
  1861. y,
  1862. 100,
  1863. 12,
  1864. g_server_base_name);
  1865. assert(((intptr_t)p - (intptr_t)mem) < (intptr_t)sizeof(mem));
  1866. dia->cy = y + 20;
  1867. } while ((IDOK == DialogBoxIndirectParam(
  1868. NULL, dia, NULL, PasswordDlgProc, (LPARAM)path))
  1869. && (!g_exit_flag));
  1870. guard--;
  1871. #undef HEIGHT
  1872. #undef WIDTH
  1873. #undef LABEL_WIDTH
  1874. }
  1875. static int
  1876. manage_service(int action)
  1877. {
  1878. const char *service_name = g_server_name;
  1879. SC_HANDLE hSCM = NULL, hService = NULL;
  1880. SERVICE_DESCRIPTION descr;
  1881. char path[PATH_MAX + 20] = ""; /* Path to executable plus magic argument */
  1882. int success = 1;
  1883. descr.lpDescription = (LPSTR)g_server_name;
  1884. if ((hSCM = OpenSCManager(NULL,
  1885. NULL,
  1886. action == ID_INSTALL_SERVICE ? GENERIC_WRITE
  1887. : GENERIC_READ))
  1888. == NULL) {
  1889. success = 0;
  1890. show_error();
  1891. } else if (action == ID_INSTALL_SERVICE) {
  1892. path[sizeof(path) - 1] = 0;
  1893. GetModuleFileName(NULL, path, sizeof(path) - 1);
  1894. strncat(path, " ", sizeof(path) - 1);
  1895. strncat(path, service_magic_argument, sizeof(path) - 1);
  1896. hService = CreateService(hSCM,
  1897. service_name,
  1898. service_name,
  1899. SERVICE_ALL_ACCESS,
  1900. SERVICE_WIN32_OWN_PROCESS,
  1901. SERVICE_AUTO_START,
  1902. SERVICE_ERROR_NORMAL,
  1903. path,
  1904. NULL,
  1905. NULL,
  1906. NULL,
  1907. NULL,
  1908. NULL);
  1909. if (hService) {
  1910. ChangeServiceConfig2(hService, SERVICE_CONFIG_DESCRIPTION, &descr);
  1911. } else {
  1912. show_error();
  1913. }
  1914. } else if (action == ID_REMOVE_SERVICE) {
  1915. if ((hService = OpenService(hSCM, service_name, DELETE)) == NULL
  1916. || !DeleteService(hService)) {
  1917. show_error();
  1918. }
  1919. } else if ((hService =
  1920. OpenService(hSCM, service_name, SERVICE_QUERY_STATUS))
  1921. == NULL) {
  1922. success = 0;
  1923. }
  1924. if (hService)
  1925. CloseServiceHandle(hService);
  1926. if (hSCM)
  1927. CloseServiceHandle(hSCM);
  1928. return success;
  1929. }
  1930. static LRESULT CALLBACK
  1931. WindowProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam)
  1932. {
  1933. static SERVICE_TABLE_ENTRY service_table[2];
  1934. int service_installed;
  1935. char buf[200], *service_argv[2];
  1936. POINT pt;
  1937. HMENU hMenu;
  1938. static UINT s_uTaskbarRestart; /* for taskbar creation */
  1939. service_argv[0] = __argv[0];
  1940. service_argv[1] = NULL;
  1941. memset(service_table, 0, sizeof(service_table));
  1942. service_table[0].lpServiceName = (LPSTR)g_server_name;
  1943. service_table[0].lpServiceProc = (LPSERVICE_MAIN_FUNCTION)ServiceMain;
  1944. switch (msg) {
  1945. case WM_CREATE:
  1946. if (__argv[1] != NULL && !strcmp(__argv[1], service_magic_argument)) {
  1947. start_civetweb(1, service_argv);
  1948. StartServiceCtrlDispatcher(service_table);
  1949. exit(EXIT_SUCCESS);
  1950. } else {
  1951. start_civetweb(__argc, __argv);
  1952. s_uTaskbarRestart = RegisterWindowMessage(TEXT("TaskbarCreated"));
  1953. }
  1954. break;
  1955. case WM_COMMAND:
  1956. switch (LOWORD(wParam)) {
  1957. case ID_QUIT:
  1958. stop_civetweb();
  1959. Shell_NotifyIcon(NIM_DELETE, &TrayIcon);
  1960. g_exit_flag = 1;
  1961. PostQuitMessage(0);
  1962. return 0;
  1963. case ID_SETTINGS:
  1964. show_settings_dialog();
  1965. break;
  1966. case ID_PASSWORD:
  1967. change_password_file();
  1968. break;
  1969. case ID_INSTALL_SERVICE:
  1970. case ID_REMOVE_SERVICE:
  1971. manage_service(LOWORD(wParam));
  1972. break;
  1973. case ID_CONNECT:
  1974. fprintf(stdout, "[%s]\n", get_url_to_first_open_port(g_ctx));
  1975. ShellExecute(NULL,
  1976. "open",
  1977. get_url_to_first_open_port(g_ctx),
  1978. NULL,
  1979. NULL,
  1980. SW_SHOW);
  1981. break;
  1982. }
  1983. break;
  1984. case WM_USER:
  1985. switch (lParam) {
  1986. case WM_RBUTTONUP:
  1987. case WM_LBUTTONUP:
  1988. case WM_LBUTTONDBLCLK:
  1989. hMenu = CreatePopupMenu();
  1990. AppendMenu(hMenu,
  1991. MF_STRING | MF_GRAYED,
  1992. ID_SEPARATOR,
  1993. g_server_name);
  1994. AppendMenu(hMenu, MF_SEPARATOR, ID_SEPARATOR, "");
  1995. service_installed = manage_service(0);
  1996. snprintf(buf,
  1997. sizeof(buf) - 1,
  1998. "NT service: %s installed",
  1999. service_installed ? "" : "not");
  2000. buf[sizeof(buf) - 1] = 0;
  2001. AppendMenu(hMenu, MF_STRING | MF_GRAYED, ID_SEPARATOR, buf);
  2002. AppendMenu(hMenu,
  2003. MF_STRING | (service_installed ? MF_GRAYED : 0),
  2004. ID_INSTALL_SERVICE,
  2005. "Install service");
  2006. AppendMenu(hMenu,
  2007. MF_STRING | (!service_installed ? MF_GRAYED : 0),
  2008. ID_REMOVE_SERVICE,
  2009. "Deinstall service");
  2010. AppendMenu(hMenu, MF_SEPARATOR, ID_SEPARATOR, "");
  2011. AppendMenu(hMenu, MF_STRING, ID_CONNECT, "Start browser");
  2012. AppendMenu(hMenu, MF_STRING, ID_SETTINGS, "Edit settings");
  2013. AppendMenu(hMenu, MF_STRING, ID_PASSWORD, "Modify password file");
  2014. AppendMenu(hMenu, MF_SEPARATOR, ID_SEPARATOR, "");
  2015. AppendMenu(hMenu, MF_STRING, ID_QUIT, "Exit");
  2016. GetCursorPos(&pt);
  2017. SetForegroundWindow(hWnd);
  2018. TrackPopupMenu(hMenu, 0, pt.x, pt.y, 0, hWnd, NULL);
  2019. PostMessage(hWnd, WM_NULL, 0, 0);
  2020. DestroyMenu(hMenu);
  2021. break;
  2022. }
  2023. break;
  2024. case WM_CLOSE:
  2025. stop_civetweb();
  2026. Shell_NotifyIcon(NIM_DELETE, &TrayIcon);
  2027. g_exit_flag = 1;
  2028. PostQuitMessage(0);
  2029. return 0; /* We've just sent our own quit message, with proper hwnd. */
  2030. default:
  2031. if (msg == s_uTaskbarRestart)
  2032. Shell_NotifyIcon(NIM_ADD, &TrayIcon);
  2033. }
  2034. return DefWindowProc(hWnd, msg, wParam, lParam);
  2035. }
  2036. static int
  2037. MakeConsole(void)
  2038. {
  2039. DWORD err;
  2040. int ok = (GetConsoleWindow() != NULL);
  2041. if (!ok) {
  2042. if (!AttachConsole(ATTACH_PARENT_PROCESS)) {
  2043. FreeConsole();
  2044. if (!AllocConsole()) {
  2045. err = GetLastError();
  2046. if (err == ERROR_ACCESS_DENIED) {
  2047. MessageBox(NULL,
  2048. "Insufficient rights to create a console window",
  2049. "Error",
  2050. MB_ICONERROR);
  2051. }
  2052. }
  2053. AttachConsole(GetCurrentProcessId());
  2054. }
  2055. ok = (GetConsoleWindow() != NULL);
  2056. if (ok) {
  2057. freopen("CONIN$", "r", stdin);
  2058. freopen("CONOUT$", "w", stdout);
  2059. freopen("CONOUT$", "w", stderr);
  2060. }
  2061. }
  2062. if (ok) {
  2063. SetConsoleTitle(g_server_name);
  2064. }
  2065. return ok;
  2066. }
  2067. int WINAPI
  2068. WinMain(HINSTANCE hInst, HINSTANCE hPrev, LPSTR cmdline, int show)
  2069. {
  2070. WNDCLASS cls;
  2071. HWND hWnd;
  2072. MSG msg;
  2073. int i;
  2074. int dataLen = 4;
  2075. char data[256] = {0};
  2076. char masked_data[256] = {0};
  2077. uint32_t masking_key = 0x01020304;
  2078. for (i = 0; i < dataLen - 3; i += 4) {
  2079. *(uint32_t *)(void *)(masked_data + i) =
  2080. *(uint32_t *)(void *)(data + i) ^ masking_key;
  2081. }
  2082. if (i != dataLen) {
  2083. /* convert 1-3 remaining bytes */
  2084. i -= 4;
  2085. while (i < dataLen) {
  2086. *(uint8_t *)(void *)(masked_data + i) =
  2087. *(uint8_t *)(void *)(data + i)
  2088. ^ *(((uint8_t *)&masking_key) + (i % 4));
  2089. i++;
  2090. }
  2091. }
  2092. #if 0
  2093. /* http://lomont.org/Math/Papers/2008/Lomont_PRNG_2008.pdf */
  2094. /* initialize state to random bits
  2095. */
  2096. static unsigned long state[16];
  2097. /* init should also reset this to 0 */
  2098. static unsigned int index = 0;
  2099. /* return 32 bit random number
  2100. */
  2101. unsigned long WELLRN G512(void)
  2102. {
  2103. unsigned long a, b, c, d;
  2104. a = state[index];
  2105. c = state[(index + 13) & 15];
  2106. b = a ^ c ^ (a << 16) ^ (c << 15);
  2107. c = state[(index + 9) & 15];
  2108. c ^= (c >> 11);
  2109. a = state[index] = b ^ c;
  2110. d = a ^ ((a << 5) & 0xDA442D24 UL);
  2111. index = (index + 15) & 15;
  2112. a = state[index];
  2113. state[index] = a ^ b ^ d ^ (a << 2) ^ (b << 18) ^ (c << 28);
  2114. return state[index];
  2115. }
  2116. uint32_t x, y, z, w;
  2117. uint32_t xorshift128(void)
  2118. {
  2119. uint32_t t = x ^ (x << 11);
  2120. x = y;
  2121. y = z;
  2122. z = w;
  2123. return w = w ^ (w >> 19) ^ t ^ (t >> 8);
  2124. }
  2125. static uint64_t lfsr = 1;
  2126. static uint64_t lcg = 0;
  2127. uint64_t r = 0;
  2128. do {
  2129. lfsr = (lfsr >> 1)
  2130. | ((((lfsr >> 0) ^ (lfsr >> 1) ^ (lfsr >> 3) ^ (lfsr >> 4)) & 1)
  2131. << 63);
  2132. lcg = lcg * 6364136223846793005 + 1442695040888963407;
  2133. ++r;
  2134. } while (lcg != 0);
  2135. fprintf(stdout, "lfsr = %I64u, lcg = %i64u, r = %i64u\n", lfsr, lcg, r);
  2136. #endif
  2137. (void)hInst;
  2138. (void)hPrev;
  2139. (void)cmdline;
  2140. (void)show;
  2141. init_server_name((int)__argc, (const char **)__argv);
  2142. memset(&cls, 0, sizeof(cls));
  2143. cls.lpfnWndProc = (WNDPROC)WindowProc;
  2144. cls.hIcon = LoadIcon(NULL, IDI_APPLICATION);
  2145. cls.lpszClassName = g_server_base_name;
  2146. RegisterClass(&cls);
  2147. hWnd = CreateWindow(cls.lpszClassName,
  2148. g_server_name,
  2149. WS_OVERLAPPEDWINDOW,
  2150. 0,
  2151. 0,
  2152. 0,
  2153. 0,
  2154. NULL,
  2155. NULL,
  2156. NULL,
  2157. NULL);
  2158. ShowWindow(hWnd, SW_HIDE);
  2159. if (g_icon_name) {
  2160. hIcon =
  2161. LoadImage(NULL, g_icon_name, IMAGE_ICON, 16, 16, LR_LOADFROMFILE);
  2162. } else {
  2163. hIcon = LoadImage(GetModuleHandle(NULL),
  2164. MAKEINTRESOURCE(ID_ICON),
  2165. IMAGE_ICON,
  2166. 16,
  2167. 16,
  2168. 0);
  2169. }
  2170. TrayIcon.cbSize = sizeof(TrayIcon);
  2171. TrayIcon.uID = ID_ICON;
  2172. TrayIcon.uFlags = NIF_ICON | NIF_MESSAGE | NIF_TIP;
  2173. TrayIcon.hIcon = hIcon;
  2174. TrayIcon.hWnd = hWnd;
  2175. snprintf(TrayIcon.szTip, sizeof(TrayIcon.szTip), "%s", g_server_name);
  2176. TrayIcon.uCallbackMessage = WM_USER;
  2177. Shell_NotifyIcon(NIM_ADD, &TrayIcon);
  2178. while (GetMessage(&msg, hWnd, 0, 0) > 0) {
  2179. TranslateMessage(&msg);
  2180. DispatchMessage(&msg);
  2181. }
  2182. /* Return the WM_QUIT value. */
  2183. return (int)msg.wParam;
  2184. }
  2185. int
  2186. main(int argc, char *argv[])
  2187. {
  2188. (void)argc;
  2189. (void)argv;
  2190. return WinMain(0, 0, 0, 0);
  2191. }
  2192. #elif defined(USE_COCOA)
  2193. #import <Cocoa/Cocoa.h>
  2194. @interface Civetweb : NSObject <NSApplicationDelegate>
  2195. - (void)openBrowser;
  2196. - (void)shutDown;
  2197. @end
  2198. @implementation Civetweb
  2199. - (void)openBrowser
  2200. {
  2201. [[NSWorkspace sharedWorkspace]
  2202. openURL:[NSURL URLWithString:[NSString stringWithUTF8String:
  2203. get_url_to_first_open_port(
  2204. g_ctx)]]];
  2205. }
  2206. - (void)editConfig
  2207. {
  2208. create_config_file(g_ctx, g_config_file_name);
  2209. NSString *path = [NSString stringWithUTF8String:g_config_file_name];
  2210. if (![[NSWorkspace sharedWorkspace] openFile:path
  2211. withApplication:@"TextEdit"]) {
  2212. NSAlert *alert = [[[NSAlert alloc] init] autorelease];
  2213. [alert setAlertStyle:NSWarningAlertStyle];
  2214. [alert setMessageText:NSLocalizedString(@"Unable to open config file.",
  2215. "")];
  2216. [alert setInformativeText:path];
  2217. (void)[alert runModal];
  2218. }
  2219. }
  2220. - (void)shutDown
  2221. {
  2222. [NSApp terminate:nil];
  2223. }
  2224. @end
  2225. int
  2226. main(int argc, char *argv[])
  2227. {
  2228. init_server_name(argc, (const char **)argv);
  2229. start_civetweb(argc, argv);
  2230. [NSAutoreleasePool new];
  2231. [NSApplication sharedApplication];
  2232. /* Add delegate to process menu item actions */
  2233. Civetweb *myDelegate = [[Civetweb alloc] autorelease];
  2234. [NSApp setDelegate:myDelegate];
  2235. /* Run this app as agent */
  2236. ProcessSerialNumber psn = {0, kCurrentProcess};
  2237. TransformProcessType(&psn, kProcessTransformToBackgroundApplication);
  2238. SetFrontProcess(&psn);
  2239. /* Add status bar menu */
  2240. id menu = [[NSMenu new] autorelease];
  2241. /* Add version menu item */
  2242. [menu
  2243. addItem:
  2244. [[[NSMenuItem alloc]
  2245. /*initWithTitle:[NSString stringWithFormat:@"%s", server_name]*/
  2246. initWithTitle:[NSString stringWithUTF8String:g_server_name]
  2247. action:@selector(noexist)
  2248. keyEquivalent:@""] autorelease]];
  2249. /* Add configuration menu item */
  2250. [menu addItem:[[[NSMenuItem alloc] initWithTitle:@"Edit configuration"
  2251. action:@selector(editConfig)
  2252. keyEquivalent:@""] autorelease]];
  2253. /* Add connect menu item */
  2254. [menu
  2255. addItem:[[[NSMenuItem alloc] initWithTitle:@"Open web root in a browser"
  2256. action:@selector(openBrowser)
  2257. keyEquivalent:@""] autorelease]];
  2258. /* Separator */
  2259. [menu addItem:[NSMenuItem separatorItem]];
  2260. /* Add quit menu item */
  2261. [menu addItem:[[[NSMenuItem alloc] initWithTitle:@"Quit"
  2262. action:@selector(shutDown)
  2263. keyEquivalent:@"q"] autorelease]];
  2264. /* Attach menu to the status bar */
  2265. id item = [[[NSStatusBar systemStatusBar]
  2266. statusItemWithLength:NSVariableStatusItemLength] retain];
  2267. [item setHighlightMode:YES];
  2268. [item setImage:[NSImage imageNamed:@"civetweb_22x22.png"]];
  2269. [item setMenu:menu];
  2270. /* Run the app */
  2271. [NSApp activateIgnoringOtherApps:YES];
  2272. [NSApp run];
  2273. stop_civetweb();
  2274. return EXIT_SUCCESS;
  2275. }
  2276. #else
  2277. int
  2278. main(int argc, char *argv[])
  2279. {
  2280. init_server_name(argc, (const char **)argv);
  2281. start_civetweb(argc, argv);
  2282. fprintf(stdout,
  2283. "%s started on port(s) %s with web root [%s]\n",
  2284. g_server_name,
  2285. mg_get_option(g_ctx, "listening_ports"),
  2286. mg_get_option(g_ctx, "document_root"));
  2287. while (g_exit_flag == 0) {
  2288. sleep(1);
  2289. }
  2290. fprintf(stdout,
  2291. "Exiting on signal %d, waiting for all threads to finish...",
  2292. g_exit_flag);
  2293. fflush(stdout);
  2294. stop_civetweb();
  2295. fprintf(stdout, "%s", " done.\n");
  2296. return EXIT_SUCCESS;
  2297. }
  2298. #endif /* _WIN32 */