main.c 77 KB

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