main.c 82 KB

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