main.c 82 KB

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