main.c 84 KB

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