main.c 84 KB

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