main.c 82 KB

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