main.c 71 KB

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