main.c 81 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262
  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, "put_delete_auth_file", arg0);
  968. set_absolute_path(options, "cgi_interpreter", arg0);
  969. set_absolute_path(options, "access_log_file", arg0);
  970. set_absolute_path(options, "error_log_file", arg0);
  971. set_absolute_path(options, "global_auth_file", arg0);
  972. #if defined(USE_LUA)
  973. set_absolute_path(options, "lua_preload_file", arg0);
  974. #endif
  975. set_absolute_path(options, "ssl_certificate", arg0);
  976. /* Make extra verification for certain options */
  977. if (!verify_existence(options, "document_root", 1))
  978. ok = 0;
  979. if (!verify_existence(options, "cgi_interpreter", 0))
  980. ok = 0;
  981. if (!verify_existence(options, "ssl_certificate", 0))
  982. ok = 0;
  983. if (!verify_existence(options, "ssl_ca_path", 1))
  984. ok = 0;
  985. if (!verify_existence(options, "ssl_ca_file", 0))
  986. ok = 0;
  987. #if defined(USE_LUA)
  988. if (!verify_existence(options, "lua_preload_file", 0))
  989. ok = 0;
  990. #endif
  991. return ok;
  992. }
  993. #ifdef _WIN32
  994. /* Forward declaration for Windows only */
  995. static void show_settings_dialog(void);
  996. #endif
  997. static void
  998. start_civetweb(int argc, char *argv[])
  999. {
  1000. struct mg_callbacks callbacks;
  1001. const char *options[2 * MAX_OPTIONS + 1];
  1002. struct mg_init_data init;
  1003. struct mg_error_data error;
  1004. char error_text[256];
  1005. int i;
  1006. /* Start option -I:
  1007. * Show system information and exit
  1008. * This is very useful for diagnosis. */
  1009. if (argc > 1 && !strcmp(argv[1], "-I")) {
  1010. #if defined(WIN32)
  1011. (void)MakeConsole();
  1012. #endif
  1013. fprintf(stdout,
  1014. "\n%s (%s)\n%s\n",
  1015. g_server_base_name,
  1016. g_server_name,
  1017. g_system_info);
  1018. exit(EXIT_SUCCESS);
  1019. }
  1020. /* Edit passwords file: Add user or change password, if -A option is
  1021. * specified */
  1022. if (argc > 1 && !strcmp(argv[1], "-A")) {
  1023. if (argc != 6) {
  1024. show_usage_and_exit(argv[0]);
  1025. }
  1026. exit(mg_modify_passwords_file(argv[2], argv[3], argv[4], argv[5])
  1027. ? EXIT_SUCCESS
  1028. : EXIT_FAILURE);
  1029. }
  1030. /* Edit passwords file: Remove user, if -R option is specified */
  1031. if (argc > 1 && !strcmp(argv[1], "-R")) {
  1032. if (argc != 5) {
  1033. show_usage_and_exit(argv[0]);
  1034. }
  1035. exit(mg_modify_passwords_file(argv[2], argv[3], argv[4], NULL)
  1036. ? EXIT_SUCCESS
  1037. : EXIT_FAILURE);
  1038. }
  1039. /* Client mode */
  1040. if (argc > 1 && !strcmp(argv[1], "-C")) {
  1041. if (argc != 3) {
  1042. show_usage_and_exit(argv[0]);
  1043. }
  1044. exit(run_client(argv[2]) ? EXIT_SUCCESS : EXIT_FAILURE);
  1045. }
  1046. /* Call Lua with additional CivetWeb specific Lua functions, if -L option
  1047. * is specified */
  1048. if (argc > 1 && !strcmp(argv[1], "-L")) {
  1049. #if defined(USE_LUA)
  1050. if (argc != 3) {
  1051. show_usage_and_exit(argv[0]);
  1052. }
  1053. #if defined(WIN32)
  1054. (void)MakeConsole();
  1055. #endif
  1056. exit(run_lua(argv[2]));
  1057. #else
  1058. show_server_name();
  1059. fprintf(stderr, "\nError: Lua support not enabled\n");
  1060. exit(EXIT_FAILURE);
  1061. #endif
  1062. }
  1063. /* Call Duktape, if -E option is specified */
  1064. if (argc > 1 && !strcmp(argv[1], "-E")) {
  1065. #if defined(USE_DUKTAPE)
  1066. if (argc != 3) {
  1067. show_usage_and_exit(argv[0]);
  1068. }
  1069. #if defined(WIN32)
  1070. (void)MakeConsole();
  1071. #endif
  1072. exit(run_duktape(argv[2]));
  1073. #else
  1074. show_server_name();
  1075. fprintf(stderr, "\nError: Ecmascript support not enabled\n");
  1076. exit(EXIT_FAILURE);
  1077. #endif
  1078. }
  1079. /* Show usage if -h or --help options are specified */
  1080. if (argc == 2
  1081. && (!strcmp(argv[1], "-h") || !strcmp(argv[1], "-H")
  1082. || !strcmp(argv[1], "--help"))) {
  1083. show_usage_and_exit(argv[0]);
  1084. }
  1085. /* Initialize options structure */
  1086. memset((void *)options, 0, sizeof(options));
  1087. set_option(options, "document_root", ".");
  1088. /* Update config based on command line arguments */
  1089. process_command_line_arguments(argc, argv, options);
  1090. i = sanitize_options(options, argv[0]);
  1091. if (!i) {
  1092. die("Invalid options");
  1093. }
  1094. /* Setup signal handler: quit on Ctrl-C */
  1095. signal(SIGTERM, signal_handler);
  1096. signal(SIGINT, signal_handler);
  1097. #if defined(DAEMONIZE)
  1098. /* Daemonize */
  1099. for (i = 0; options[i] != NULL; i++) {
  1100. if (strcmp(options[i], "daemonize") == 0) {
  1101. if (options[i + 1] != NULL) {
  1102. if (mg_strcasecmp(options[i + 1], "yes") == 0) {
  1103. fprintf(stdout, "daemonize.\n");
  1104. if (daemon(0, 0) != 0) {
  1105. fprintf(stdout, "Faild to daemonize main process.\n");
  1106. exit(EXIT_FAILURE);
  1107. }
  1108. FILE *fp;
  1109. if ((fp = fopen(PID_FILE, "w")) == 0) {
  1110. fprintf(stdout, "Can not open %s.\n", PID_FILE);
  1111. exit(EXIT_FAILURE);
  1112. }
  1113. fprintf(fp, "%d", getpid());
  1114. fclose(fp);
  1115. }
  1116. }
  1117. break;
  1118. }
  1119. }
  1120. #endif
  1121. /* Initialize user data */
  1122. memset(&g_user_data, 0, sizeof(g_user_data));
  1123. memset(&callbacks, 0, sizeof(callbacks));
  1124. memset(&init, 0, sizeof(init));
  1125. init.callbacks = &callbacks;
  1126. init.configuration_options = options;
  1127. init.user_data = &g_user_data;
  1128. memset(&error, 0, sizeof(error));
  1129. error.text = error_text;
  1130. error.text_buffer_size = sizeof(error_text);
  1131. /* Start Civetweb */
  1132. g_ctx = mg_start2(&init, &error);
  1133. /* mg_start copies all options to an internal buffer.
  1134. * The options data field here is not required anymore. */
  1135. for (i = 0; options[i] != NULL; i++) {
  1136. free((char *)options[i]);
  1137. }
  1138. /* If mg_start fails, it returns NULL */
  1139. if (g_ctx == NULL) {
  1140. #ifdef _WIN32
  1141. /* On Windows: provide option to edit configuration file. */
  1142. char msgboxtxt[1024];
  1143. int ret;
  1144. sprintf(msgboxtxt,
  1145. "Failed to start %s with code %u:\n%s\n\nEdit settings?",
  1146. g_server_name,
  1147. error.code,
  1148. error_text);
  1149. ret =
  1150. MessageBox(NULL, msgboxtxt, "Error", MB_ICONERROR | MB_YESNOCANCEL);
  1151. if (ret == IDYES) {
  1152. show_settings_dialog();
  1153. /* Hitting "save" will also restart the server. */
  1154. if (g_ctx != NULL) {
  1155. return;
  1156. }
  1157. }
  1158. exit(EXIT_FAILURE);
  1159. #else
  1160. die("Failed to start %s with code %u:\n%s",
  1161. g_server_name,
  1162. error.code,
  1163. error_text);
  1164. #endif
  1165. }
  1166. #if defined(MG_EXPERIMENTAL_INTERFACES)
  1167. for (i = 0; i < g_num_add_domains; i++) {
  1168. int j;
  1169. memset(options, 0, sizeof(options));
  1170. set_option(options, "document_root", ".");
  1171. if (0 == read_config_file(g_add_domain[i], options)) {
  1172. die("Cannot open config file %s: %s",
  1173. g_add_domain[i],
  1174. strerror(errno));
  1175. }
  1176. j = sanitize_options(options, argv[0]);
  1177. if (!j) {
  1178. die("Invalid options");
  1179. }
  1180. j = mg_start_domain(g_ctx, (const char **)options);
  1181. if (j < 0) {
  1182. die("Error loading domain file %s: %i", g_add_domain[i], j);
  1183. } else {
  1184. fprintf(stdout, "Domain file %s loaded\n", g_add_domain[i]);
  1185. }
  1186. for (j = 0; options[j] != NULL; j++) {
  1187. free(options[j]);
  1188. }
  1189. }
  1190. #endif
  1191. }
  1192. static void
  1193. stop_civetweb(void)
  1194. {
  1195. mg_stop(g_ctx);
  1196. }
  1197. #if defined(_WIN32)
  1198. /* Win32 has a small GUI.
  1199. * Define some GUI elements and Windows message handlers. */
  1200. enum {
  1201. ID_ICON = 100,
  1202. ID_QUIT,
  1203. ID_SETTINGS,
  1204. ID_SEPARATOR,
  1205. ID_INSTALL_SERVICE,
  1206. ID_REMOVE_SERVICE,
  1207. ID_STATIC,
  1208. ID_GROUP,
  1209. ID_PASSWORD,
  1210. ID_SAVE,
  1211. ID_RESET_DEFAULTS,
  1212. ID_RESET_FILE,
  1213. ID_RESET_ACTIVE,
  1214. ID_STATUS,
  1215. ID_CONNECT,
  1216. ID_ADD_USER,
  1217. ID_ADD_USER_NAME,
  1218. ID_ADD_USER_REALM,
  1219. ID_INPUT_LINE,
  1220. ID_SYSINFO,
  1221. ID_WEBSITE,
  1222. /* All dynamically created text boxes for options have IDs starting from
  1223. ID_CONTROLS, incremented by one. */
  1224. ID_CONTROLS = 200,
  1225. /* Text boxes for files have "..." buttons to open file browser. These
  1226. buttons have IDs that are ID_FILE_BUTTONS_DELTA higher than associated
  1227. text box ID. */
  1228. ID_FILE_BUTTONS_DELTA = 1000
  1229. };
  1230. static HICON hIcon;
  1231. static SERVICE_STATUS ss;
  1232. static SERVICE_STATUS_HANDLE hStatus;
  1233. static const char *service_magic_argument = "--";
  1234. static NOTIFYICONDATA TrayIcon;
  1235. static UINT msg_taskbar_created;
  1236. static void WINAPI
  1237. ControlHandler(DWORD code)
  1238. {
  1239. if (code == SERVICE_CONTROL_STOP || code == SERVICE_CONTROL_SHUTDOWN) {
  1240. ss.dwWin32ExitCode = 0;
  1241. ss.dwCurrentState = SERVICE_STOPPED;
  1242. }
  1243. SetServiceStatus(hStatus, &ss);
  1244. }
  1245. static void WINAPI
  1246. ServiceMain(void)
  1247. {
  1248. ss.dwServiceType = SERVICE_WIN32;
  1249. ss.dwCurrentState = SERVICE_RUNNING;
  1250. ss.dwControlsAccepted = SERVICE_ACCEPT_STOP | SERVICE_ACCEPT_SHUTDOWN;
  1251. hStatus = RegisterServiceCtrlHandler(g_server_name, ControlHandler);
  1252. SetServiceStatus(hStatus, &ss);
  1253. while (ss.dwCurrentState == SERVICE_RUNNING) {
  1254. Sleep(1000);
  1255. }
  1256. stop_civetweb();
  1257. ss.dwCurrentState = SERVICE_STOPPED;
  1258. ss.dwWin32ExitCode = (DWORD)-1;
  1259. SetServiceStatus(hStatus, &ss);
  1260. }
  1261. static void
  1262. show_error(void)
  1263. {
  1264. char buf[256];
  1265. FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
  1266. NULL,
  1267. GetLastError(),
  1268. MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
  1269. buf,
  1270. sizeof(buf),
  1271. NULL);
  1272. MessageBox(NULL, buf, "Error", MB_OK);
  1273. }
  1274. static void
  1275. save_config(HWND hDlg, FILE *fp)
  1276. {
  1277. char value[2000] = "";
  1278. const char *default_value;
  1279. const struct mg_option *options;
  1280. int i, id;
  1281. fprintf(fp, "%s", config_file_top_comment);
  1282. options = mg_get_valid_options();
  1283. for (i = 0; options[i].name != NULL; i++) {
  1284. id = ID_CONTROLS + i;
  1285. if (options[i].type == MG_CONFIG_TYPE_BOOLEAN) {
  1286. snprintf(value,
  1287. sizeof(value) - 1,
  1288. "%s",
  1289. IsDlgButtonChecked(hDlg, id) ? "yes" : "no");
  1290. value[sizeof(value) - 1] = 0;
  1291. } else {
  1292. GetDlgItemText(hDlg, id, value, sizeof(value));
  1293. }
  1294. default_value =
  1295. options[i].default_value == NULL ? "" : options[i].default_value;
  1296. /* If value is the same as default, skip it */
  1297. if (strcmp(value, default_value) != 0) {
  1298. fprintf(fp, "%s %s\n", options[i].name, value);
  1299. }
  1300. }
  1301. }
  1302. /* LPARAM pointer passed to WM_INITDIALOG */
  1303. struct dlg_proc_param {
  1304. int guard;
  1305. HWND hWnd;
  1306. const char *name;
  1307. char *buffer;
  1308. unsigned buflen;
  1309. int idRetry;
  1310. BOOL (*fRetry)(struct dlg_proc_param *data);
  1311. };
  1312. struct dlg_header_param {
  1313. /* https://docs.microsoft.com/en-us/windows/win32/api/winuser/ns-winuser-dlgtemplate
  1314. */
  1315. DLGTEMPLATE dlg_template; /* 18 bytes */
  1316. WORD menu, dlg_class;
  1317. wchar_t caption[1];
  1318. WORD fontsize;
  1319. wchar_t fontface[7]; /* L"Tahoma" = 6 characters + terminating zero */
  1320. };
  1321. /* complete data required to create a dialog including child elements */
  1322. struct dlg_complete {
  1323. struct dlg_header_param header;
  1324. /* TODO: if sizeof(header)%4 is not 0, add some filling bytes here */
  1325. BYTE elements[4096 * 2];
  1326. int used;
  1327. };
  1328. static void
  1329. FillDialogHeader(struct dlg_complete *dlg, const short width)
  1330. {
  1331. memset(dlg, 0, sizeof(*dlg));
  1332. dlg->header.dlg_template.style = WS_CAPTION | WS_POPUP | WS_SYSMENU
  1333. | WS_VISIBLE | DS_SETFONT | DS_CENTER
  1334. | WS_DLGFRAME;
  1335. dlg->header.dlg_template.dwExtendedStyle = WS_EX_TOOLWINDOW;
  1336. dlg->header.dlg_template.cdit = 0;
  1337. dlg->header.dlg_template.x = 0; /* ignored by DS_CENTER */
  1338. dlg->header.dlg_template.y = 0; /* ignored by DS_CENTER */
  1339. dlg->header.dlg_template.cx = width;
  1340. dlg->header.dlg_template.cy =
  1341. 0; /* to be calculated after adding elements */
  1342. dlg->header.menu = 0;
  1343. dlg->header.dlg_class = 0;
  1344. dlg->header.caption[0] = (wchar_t)0;
  1345. dlg->header.fontsize = 8;
  1346. wcscpy(dlg->header.fontface, L"Tahoma");
  1347. /* counting used bytes */
  1348. dlg->used = 0;
  1349. }
  1350. /* Dialog proc for settings dialog */
  1351. static INT_PTR CALLBACK
  1352. SettingsDlgProc(HWND hDlg, UINT msg, WPARAM wParam, LPARAM lParam)
  1353. {
  1354. FILE *fp;
  1355. int i, j;
  1356. const char *name, *value;
  1357. const struct mg_option *default_options = mg_get_valid_options();
  1358. char *file_options[MAX_OPTIONS * 2 + 1] = {0};
  1359. char *title;
  1360. struct dlg_proc_param *pdlg_proc_param;
  1361. switch (msg) {
  1362. case WM_CLOSE:
  1363. DestroyWindow(hDlg);
  1364. break;
  1365. case WM_COMMAND:
  1366. switch (LOWORD(wParam)) {
  1367. case ID_SAVE:
  1368. EnableWindow(GetDlgItem(hDlg, ID_SAVE), FALSE);
  1369. if ((fp = fopen(g_config_file_name, "w+")) != NULL) {
  1370. save_config(hDlg, fp);
  1371. fclose(fp);
  1372. stop_civetweb();
  1373. start_civetweb(__argc, __argv);
  1374. }
  1375. EnableWindow(GetDlgItem(hDlg, ID_SAVE), TRUE);
  1376. break;
  1377. case ID_RESET_DEFAULTS:
  1378. for (i = 0; default_options[i].name != NULL; i++) {
  1379. name = default_options[i].name;
  1380. value = default_options[i].default_value == NULL
  1381. ? ""
  1382. : default_options[i].default_value;
  1383. if (default_options[i].type == MG_CONFIG_TYPE_BOOLEAN) {
  1384. CheckDlgButton(hDlg,
  1385. ID_CONTROLS + i,
  1386. !strcmp(value, "yes") ? BST_CHECKED
  1387. : BST_UNCHECKED);
  1388. } else {
  1389. SetWindowText(GetDlgItem(hDlg, ID_CONTROLS + i), value);
  1390. }
  1391. }
  1392. break;
  1393. case ID_RESET_FILE:
  1394. read_config_file(g_config_file_name, file_options);
  1395. for (i = 0; default_options[i].name != NULL; i++) {
  1396. name = default_options[i].name;
  1397. value = default_options[i].default_value;
  1398. for (j = 0; file_options[j * 2] != NULL; j++) {
  1399. if (!strcmp(name, file_options[j * 2])) {
  1400. value = file_options[j * 2 + 1];
  1401. }
  1402. }
  1403. if (value == NULL) {
  1404. value = "";
  1405. }
  1406. if (default_options[i].type == MG_CONFIG_TYPE_BOOLEAN) {
  1407. CheckDlgButton(hDlg,
  1408. ID_CONTROLS + i,
  1409. !strcmp(value, "yes") ? BST_CHECKED
  1410. : BST_UNCHECKED);
  1411. } else {
  1412. SetWindowText(GetDlgItem(hDlg, ID_CONTROLS + i), value);
  1413. }
  1414. }
  1415. for (i = 0; i < MAX_OPTIONS; i++) {
  1416. free(file_options[2 * i]);
  1417. free(file_options[2 * i + 1]);
  1418. }
  1419. break;
  1420. case ID_RESET_ACTIVE:
  1421. for (i = 0; default_options[i].name != NULL; i++) {
  1422. name = default_options[i].name;
  1423. value = mg_get_option(g_ctx, name);
  1424. if (default_options[i].type == MG_CONFIG_TYPE_BOOLEAN) {
  1425. CheckDlgButton(hDlg,
  1426. ID_CONTROLS + i,
  1427. !strcmp(value, "yes") ? BST_CHECKED
  1428. : BST_UNCHECKED);
  1429. } else {
  1430. SetDlgItemText(hDlg,
  1431. ID_CONTROLS + i,
  1432. value == NULL ? "" : value);
  1433. }
  1434. }
  1435. break;
  1436. }
  1437. for (i = 0; default_options[i].name != NULL; i++) {
  1438. name = default_options[i].name;
  1439. if (((default_options[i].type == MG_CONFIG_TYPE_FILE)
  1440. || (default_options[i].type == MG_CONFIG_TYPE_DIRECTORY))
  1441. && LOWORD(wParam) == ID_CONTROLS + i + ID_FILE_BUTTONS_DELTA) {
  1442. /* Result of the Dialog: File/Folder selected by user */
  1443. char path[PATH_MAX] = "";
  1444. if (default_options[i].type == MG_CONFIG_TYPE_DIRECTORY) {
  1445. BROWSEINFO bi;
  1446. memset(&bi, 0, sizeof(bi));
  1447. bi.hwndOwner = (HWND)hDlg;
  1448. bi.ulFlags = BIF_RETURNONLYFSDIRS;
  1449. /* Use option name as Window title */
  1450. bi.lpszTitle = name;
  1451. SHGetPathFromIDList(SHBrowseForFolder(&bi), path);
  1452. } else {
  1453. OPENFILENAME of;
  1454. memset(&of, 0, sizeof(of));
  1455. of.lStructSize = sizeof(of);
  1456. of.hwndOwner = (HWND)hDlg;
  1457. of.lpstrFile = path;
  1458. of.nMaxFile = sizeof(path);
  1459. of.lpstrInitialDir = mg_get_option(g_ctx, "document_root");
  1460. of.Flags =
  1461. OFN_CREATEPROMPT | OFN_NOCHANGEDIR | OFN_HIDEREADONLY;
  1462. /* Use option name as Window title */
  1463. of.lpstrTitle = name;
  1464. GetOpenFileName(&of);
  1465. }
  1466. if (path[0] != '\0') {
  1467. /* Something has been choosen */
  1468. SetWindowText(GetDlgItem(hDlg, ID_CONTROLS + i), path);
  1469. }
  1470. }
  1471. }
  1472. break;
  1473. case WM_INITDIALOG:
  1474. /* Store hWnd in a parameter accessible by the parent, so we can
  1475. * bring this window to front if required. */
  1476. pdlg_proc_param = (struct dlg_proc_param *)lParam;
  1477. pdlg_proc_param->hWnd = hDlg;
  1478. /* Initialize the dialog elements */
  1479. SendMessage(hDlg, WM_SETICON, (WPARAM)ICON_SMALL, (LPARAM)hIcon);
  1480. SendMessage(hDlg, WM_SETICON, (WPARAM)ICON_BIG, (LPARAM)hIcon);
  1481. title = (char *)malloc(strlen(g_server_name) + 16);
  1482. if (title) {
  1483. strcpy(title, g_server_name);
  1484. strcat(title, " settings");
  1485. SetWindowText(hDlg, title);
  1486. free(title);
  1487. }
  1488. SetFocus(GetDlgItem(hDlg, ID_SAVE));
  1489. /* Init dialog with active settings */
  1490. SendMessage(hDlg, WM_COMMAND, ID_RESET_ACTIVE, 0);
  1491. /* alternative: SendMessage(hDlg, WM_COMMAND, ID_RESET_FILE, 0); */
  1492. break;
  1493. default:
  1494. break;
  1495. }
  1496. return FALSE;
  1497. }
  1498. /* Dialog proc for input dialog */
  1499. static INT_PTR CALLBACK
  1500. InputDlgProc(HWND hDlg, UINT msg, WPARAM wParam, LPARAM lParam)
  1501. {
  1502. static struct dlg_proc_param *inBuf = 0;
  1503. WORD ctrlId;
  1504. HWND hIn;
  1505. switch (msg) {
  1506. case WM_CLOSE:
  1507. inBuf = 0;
  1508. DestroyWindow(hDlg);
  1509. break;
  1510. case WM_COMMAND:
  1511. ctrlId = LOWORD(wParam);
  1512. if (ctrlId == IDOK) {
  1513. /* Get handle of input line */
  1514. hIn = GetDlgItem(hDlg, ID_INPUT_LINE);
  1515. if (hIn) {
  1516. /* Get content of input line */
  1517. GetWindowText(hIn, inBuf->buffer, (int)inBuf->buflen);
  1518. if (inBuf->buffer[0] != 0) {
  1519. /* Input dialog is not empty. */
  1520. EndDialog(hDlg, IDOK);
  1521. }
  1522. } else {
  1523. /* There is no input line in this dialog. */
  1524. EndDialog(hDlg, IDOK);
  1525. }
  1526. } else if (ctrlId == IDRETRY) {
  1527. /* Get handle of input line */
  1528. hIn = GetDlgItem(hDlg, inBuf->idRetry);
  1529. if (hIn) {
  1530. /* Load current string */
  1531. GetWindowText(hIn, inBuf->buffer, (int)inBuf->buflen);
  1532. if (inBuf->fRetry) {
  1533. if (inBuf->fRetry(inBuf)) {
  1534. SetWindowText(hIn, inBuf->buffer);
  1535. }
  1536. }
  1537. }
  1538. } else if (ctrlId == IDCANCEL) {
  1539. EndDialog(hDlg, IDCANCEL);
  1540. }
  1541. break;
  1542. case WM_INITDIALOG:
  1543. /* Get handle of input line */
  1544. hIn = GetDlgItem(hDlg, ID_INPUT_LINE);
  1545. /* Get dialog parameters */
  1546. inBuf = (struct dlg_proc_param *)lParam;
  1547. /* Set dialog handle for the caller */
  1548. inBuf->hWnd = hDlg;
  1549. /* Set dialog name */
  1550. SetWindowText(hDlg, inBuf->name);
  1551. if (hIn) {
  1552. /* This is an input dialog */
  1553. DEBUG_ASSERT(inBuf != NULL);
  1554. DEBUG_ASSERT((inBuf->buffer != NULL) && (inBuf->buflen != 0));
  1555. DEBUG_ASSERT(strlen(inBuf->buffer) < inBuf->buflen);
  1556. SendMessage(hDlg, WM_SETICON, (WPARAM)ICON_SMALL, (LPARAM)hIcon);
  1557. SendMessage(hDlg, WM_SETICON, (WPARAM)ICON_BIG, (LPARAM)hIcon);
  1558. SendMessage(hIn, EM_LIMITTEXT, inBuf->buflen - 1, 0);
  1559. SetWindowText(hIn, inBuf->buffer);
  1560. SetFocus(hIn);
  1561. }
  1562. break;
  1563. default:
  1564. break;
  1565. }
  1566. return FALSE;
  1567. }
  1568. static void
  1569. suggest_passwd(char *passwd)
  1570. {
  1571. unsigned u;
  1572. char *p;
  1573. union {
  1574. FILETIME ft;
  1575. LARGE_INTEGER li;
  1576. } num;
  1577. /* valid characters are 32 to 126 */
  1578. GetSystemTimeAsFileTime(&num.ft);
  1579. num.li.HighPart |= (LONG)GetCurrentProcessId();
  1580. p = passwd;
  1581. while (num.li.QuadPart) {
  1582. u = (unsigned)(num.li.QuadPart % 95);
  1583. num.li.QuadPart -= u;
  1584. num.li.QuadPart /= 95;
  1585. *p = (char)(u + 32);
  1586. p++;
  1587. }
  1588. }
  1589. static void add_control(struct dlg_complete *dlg,
  1590. WORD type,
  1591. WORD id,
  1592. DWORD style,
  1593. short x,
  1594. short y,
  1595. short cx,
  1596. short cy,
  1597. const char *caption);
  1598. static int
  1599. get_password(const char *user,
  1600. const char *realm,
  1601. char *passwd,
  1602. unsigned passwd_len)
  1603. {
  1604. /* Parameter for size/format tuning of the dialog */
  1605. short HEIGHT = 15;
  1606. short WIDTH = 280;
  1607. short LABEL_WIDTH = 90;
  1608. /* Other variables */
  1609. struct dlg_complete dlg;
  1610. static struct dlg_proc_param s_dlg_proc_param;
  1611. int ok;
  1612. short y;
  1613. DEBUG_ASSERT((user != NULL) && (realm != NULL) && (passwd != NULL));
  1614. /* Only allow one instance of this dialog to be open. */
  1615. if (s_dlg_proc_param.guard == 0) {
  1616. memset(&s_dlg_proc_param, 0, sizeof(s_dlg_proc_param));
  1617. s_dlg_proc_param.guard = 1;
  1618. } else {
  1619. SetForegroundWindow(s_dlg_proc_param.hWnd);
  1620. return 0;
  1621. }
  1622. FillDialogHeader(&dlg, WIDTH);
  1623. /* Do not open a password dialog, if the username is empty */
  1624. if (user[0] == 0) {
  1625. s_dlg_proc_param.guard = 0;
  1626. return 0;
  1627. }
  1628. /* Create a password suggestion */
  1629. memset(passwd, 0, passwd_len);
  1630. suggest_passwd(passwd);
  1631. /* Make buffer available for input dialog */
  1632. s_dlg_proc_param.buffer = passwd;
  1633. s_dlg_proc_param.buflen = passwd_len;
  1634. /* Create the dialog */
  1635. y = HEIGHT;
  1636. add_control(&dlg,
  1637. 0x82,
  1638. ID_STATIC,
  1639. WS_VISIBLE | WS_CHILD,
  1640. 10,
  1641. y,
  1642. LABEL_WIDTH,
  1643. HEIGHT,
  1644. "User:");
  1645. add_control(&dlg,
  1646. 0x81,
  1647. ID_CONTROLS + 1,
  1648. WS_CHILD | WS_VISIBLE | WS_BORDER | ES_AUTOHSCROLL
  1649. | ES_READONLY,
  1650. 15 + LABEL_WIDTH,
  1651. y,
  1652. WIDTH - LABEL_WIDTH - 25,
  1653. HEIGHT,
  1654. user);
  1655. y += HEIGHT;
  1656. add_control(&dlg,
  1657. 0x82,
  1658. ID_STATIC,
  1659. WS_VISIBLE | WS_CHILD,
  1660. 10,
  1661. y,
  1662. LABEL_WIDTH,
  1663. HEIGHT,
  1664. "Realm:");
  1665. add_control(&dlg,
  1666. 0x81,
  1667. ID_CONTROLS + 2,
  1668. WS_CHILD | WS_VISIBLE | WS_BORDER | ES_AUTOHSCROLL
  1669. | ES_READONLY,
  1670. 15 + LABEL_WIDTH,
  1671. y,
  1672. WIDTH - LABEL_WIDTH - 25,
  1673. HEIGHT,
  1674. realm);
  1675. y += HEIGHT;
  1676. add_control(&dlg,
  1677. 0x82,
  1678. ID_STATIC,
  1679. WS_VISIBLE | WS_CHILD,
  1680. 10,
  1681. y,
  1682. LABEL_WIDTH,
  1683. HEIGHT,
  1684. "Password:");
  1685. add_control(&dlg,
  1686. 0x81,
  1687. ID_INPUT_LINE,
  1688. WS_CHILD | WS_VISIBLE | WS_BORDER | ES_AUTOHSCROLL | WS_TABSTOP,
  1689. 15 + LABEL_WIDTH,
  1690. y,
  1691. WIDTH - LABEL_WIDTH - 25,
  1692. HEIGHT,
  1693. "");
  1694. y += (WORD)(HEIGHT * 2);
  1695. add_control(&dlg,
  1696. 0x80,
  1697. IDOK,
  1698. WS_CHILD | WS_VISIBLE | BS_PUSHBUTTON | WS_TABSTOP,
  1699. 80,
  1700. y,
  1701. 55,
  1702. 12,
  1703. "Ok");
  1704. add_control(&dlg,
  1705. 0x80,
  1706. IDCANCEL,
  1707. WS_CHILD | WS_VISIBLE | BS_PUSHBUTTON | WS_TABSTOP,
  1708. 140,
  1709. y,
  1710. 55,
  1711. 12,
  1712. "Cancel");
  1713. dlg.header.dlg_template.cy = y + (WORD)(HEIGHT * 1.5);
  1714. s_dlg_proc_param.name = "Modify password";
  1715. s_dlg_proc_param.fRetry = NULL;
  1716. ok = (IDOK
  1717. == DialogBoxIndirectParam(NULL,
  1718. &dlg.header.dlg_template,
  1719. NULL,
  1720. InputDlgProc,
  1721. (LPARAM)&s_dlg_proc_param));
  1722. s_dlg_proc_param.hWnd = NULL;
  1723. s_dlg_proc_param.guard = 0;
  1724. return ok;
  1725. }
  1726. /* Dialog proc for password dialog */
  1727. static INT_PTR CALLBACK
  1728. PasswordDlgProc(HWND hDlg, UINT msg, WPARAM wParam, LPARAM lParam)
  1729. {
  1730. static const char *passfile = 0;
  1731. char domain[256], user[256], password[256];
  1732. WORD ctrlId;
  1733. struct dlg_proc_param *pdlg_proc_param;
  1734. switch (msg) {
  1735. case WM_CLOSE:
  1736. passfile = 0;
  1737. DestroyWindow(hDlg);
  1738. break;
  1739. case WM_COMMAND:
  1740. ctrlId = LOWORD(wParam);
  1741. if (ctrlId == ID_ADD_USER) {
  1742. /* Add user */
  1743. GetWindowText(GetDlgItem(hDlg, ID_ADD_USER_NAME),
  1744. user,
  1745. sizeof(user));
  1746. GetWindowText(GetDlgItem(hDlg, ID_ADD_USER_REALM),
  1747. domain,
  1748. sizeof(domain));
  1749. if (get_password(user, domain, password, sizeof(password))) {
  1750. mg_modify_passwords_file(passfile, domain, user, password);
  1751. EndDialog(hDlg, IDOK);
  1752. }
  1753. } else if ((ctrlId >= (ID_CONTROLS + ID_FILE_BUTTONS_DELTA * 3))
  1754. && (ctrlId < (ID_CONTROLS + ID_FILE_BUTTONS_DELTA * 4))) {
  1755. /* Modify password */
  1756. GetWindowText(GetDlgItem(hDlg, ctrlId - ID_FILE_BUTTONS_DELTA * 3),
  1757. user,
  1758. sizeof(user));
  1759. GetWindowText(GetDlgItem(hDlg, ctrlId - ID_FILE_BUTTONS_DELTA * 2),
  1760. domain,
  1761. sizeof(domain));
  1762. if (get_password(user, domain, password, sizeof(password))) {
  1763. mg_modify_passwords_file(passfile, domain, user, password);
  1764. EndDialog(hDlg, IDOK);
  1765. }
  1766. } else if ((ctrlId >= (ID_CONTROLS + ID_FILE_BUTTONS_DELTA * 2))
  1767. && (ctrlId < (ID_CONTROLS + ID_FILE_BUTTONS_DELTA * 3))) {
  1768. /* Remove user */
  1769. GetWindowText(GetDlgItem(hDlg, ctrlId - ID_FILE_BUTTONS_DELTA * 2),
  1770. user,
  1771. sizeof(user));
  1772. GetWindowText(GetDlgItem(hDlg, ctrlId - ID_FILE_BUTTONS_DELTA),
  1773. domain,
  1774. sizeof(domain));
  1775. mg_modify_passwords_file(passfile, domain, user, NULL);
  1776. EndDialog(hDlg, IDOK);
  1777. }
  1778. break;
  1779. case WM_INITDIALOG:
  1780. pdlg_proc_param = (struct dlg_proc_param *)lParam;
  1781. pdlg_proc_param->hWnd = hDlg;
  1782. passfile = pdlg_proc_param->name;
  1783. SendMessage(hDlg, WM_SETICON, (WPARAM)ICON_SMALL, (LPARAM)hIcon);
  1784. SendMessage(hDlg, WM_SETICON, (WPARAM)ICON_BIG, (LPARAM)hIcon);
  1785. SetWindowText(hDlg, passfile);
  1786. SetFocus(GetDlgItem(hDlg, ID_ADD_USER_NAME));
  1787. break;
  1788. default:
  1789. break;
  1790. }
  1791. return FALSE;
  1792. }
  1793. static void
  1794. add_control(struct dlg_complete *dlg,
  1795. WORD type,
  1796. WORD id,
  1797. DWORD style,
  1798. short x,
  1799. short y,
  1800. short cx,
  1801. short cy,
  1802. const char *caption)
  1803. {
  1804. DLGITEMTEMPLATE *tp;
  1805. LPWORD p;
  1806. WORD cap_len = caption ? (WORD)strlen(caption) : 0;
  1807. int i;
  1808. DWORD expected_size = sizeof(DLGITEMTEMPLATE) + 4 + (cap_len + 1) * 2 + 2;
  1809. if ((dlg->used + expected_size + /* alignment */ 16)
  1810. >= sizeof(dlg->elements)) {
  1811. /* out if memory protection */
  1812. return;
  1813. }
  1814. /* Add one child element */
  1815. dlg->header.dlg_template.cdit++;
  1816. /* align to 4 bytes */
  1817. while (dlg->used % 4) {
  1818. dlg->used++;
  1819. }
  1820. /* start with DLGITEMTEMPLATE structure */
  1821. tp = (DLGITEMTEMPLATE *)(dlg->elements + dlg->used);
  1822. tp->id = id;
  1823. tp->style = style;
  1824. tp->dwExtendedStyle = 0;
  1825. tp->x = x;
  1826. tp->y = y;
  1827. tp->cx = cx;
  1828. tp->cy = cy;
  1829. dlg->used += sizeof(*tp);
  1830. /* add class */
  1831. p = (LPWORD)(dlg->elements + dlg->used);
  1832. p[0] = 0xffff;
  1833. p[1] = type;
  1834. dlg->used += 2 * sizeof(*p);
  1835. /* add title */
  1836. p = (LPWORD)(dlg->elements + dlg->used);
  1837. for (i = 0; i < cap_len; i++) {
  1838. p[i] = (WCHAR)caption[i];
  1839. }
  1840. p[cap_len] = 0;
  1841. dlg->used += (cap_len + 1) * sizeof(*p);
  1842. /* align to 2 bytes */
  1843. while (dlg->used % 2) {
  1844. dlg->used++;
  1845. }
  1846. /* add creation data */
  1847. p = (LPWORD)(dlg->elements + dlg->used);
  1848. *p = 0;
  1849. dlg->used += sizeof(*p);
  1850. }
  1851. static int
  1852. optioncmp(const char *o1, const char *o2)
  1853. {
  1854. /* string compare for option names */
  1855. while (*o1 || *o2) {
  1856. int c1 = 256 * (int)*o1;
  1857. int c2 = 256 * (int)*o2;
  1858. if (isalpha(*o1))
  1859. c1 = toupper(*o1);
  1860. else if (*o1 == '_')
  1861. c1 = 1;
  1862. if (isalpha(*o2))
  1863. c2 = toupper(*o2);
  1864. else if (*o2 == '_')
  1865. c2 = 1;
  1866. if (c1 < c2)
  1867. return -1;
  1868. if (c1 > c2)
  1869. return +1;
  1870. o1++;
  1871. o2++;
  1872. }
  1873. return 0;
  1874. }
  1875. static void
  1876. show_settings_dialog(void)
  1877. {
  1878. /* Parameter for size/format tuning of the dialog */
  1879. short HEIGHT = 15;
  1880. short BORDER_WIDTH = 10;
  1881. short BORDER_HEIGTH = BORDER_WIDTH / 2;
  1882. short CELL_WIDTH = 125;
  1883. short LABEL_WIDTH = 115;
  1884. short FILE_DIALOG_BUTTON_WIDTH = 15;
  1885. short NO_OF_COLUMNS = 3;
  1886. short NO_OF_OPTIONS = 0; /* to be calculated */
  1887. short NO_OF_OPTION_SPACES = 0; /* to be calculated */
  1888. short NO_OF_ROWS = 0; /* to be calculated */
  1889. /* Calculates size */
  1890. short COLUMN_WIDTH = LABEL_WIDTH + CELL_WIDTH + BORDER_WIDTH;
  1891. short DIALOG_WIDTH = BORDER_WIDTH + NO_OF_COLUMNS * COLUMN_WIDTH;
  1892. /* All other variables */
  1893. const struct mg_option *cv_options;
  1894. DWORD style;
  1895. WORD i, cl, nelems = 0;
  1896. short x, y, next_cell_width, next_cell_height;
  1897. static struct dlg_proc_param s_dlg_proc_param;
  1898. short *option_index, *option_top, *option_bottom;
  1899. char text[64];
  1900. struct dlg_complete dlg;
  1901. if (s_dlg_proc_param.guard == 0) {
  1902. memset(&s_dlg_proc_param, 0, sizeof(s_dlg_proc_param));
  1903. s_dlg_proc_param.guard = 1;
  1904. } else {
  1905. SetForegroundWindow(s_dlg_proc_param.hWnd);
  1906. return;
  1907. }
  1908. FillDialogHeader(&dlg, DIALOG_WIDTH);
  1909. /* Determine space required for input fields */
  1910. cv_options = mg_get_valid_options();
  1911. for (i = 0; cv_options[i].name != NULL; i++) {
  1912. NO_OF_OPTIONS++;
  1913. if (cv_options[i].type == MG_CONFIG_TYPE_STRING_MULTILINE) {
  1914. /* Multiline input fields require double space */
  1915. NO_OF_OPTION_SPACES += 2;
  1916. } else {
  1917. /* All other option types require single space */
  1918. NO_OF_OPTION_SPACES++;
  1919. }
  1920. }
  1921. NO_OF_ROWS = (NO_OF_OPTION_SPACES + NO_OF_COLUMNS - 1) / NO_OF_COLUMNS;
  1922. /* All options should be displayed sorted. */
  1923. /* First allocate some memory to store option order: The array should store
  1924. * 1) the option order of all options (NO_OF_OPTIONS), followed by
  1925. * 2) the option index for the option name displayed on top of a column
  1926. * 3) the option index for the option name displayed on bottom of a column
  1927. */
  1928. option_index = (short *)calloc(NO_OF_OPTIONS + 2 * NO_OF_COLUMNS,
  1929. sizeof(short)); /* 1 */
  1930. if (!option_index) {
  1931. /* unlikely case of "out of memory" */
  1932. return;
  1933. }
  1934. option_top = option_index + NO_OF_OPTIONS; /* 2 */
  1935. option_bottom = option_top + NO_OF_COLUMNS; /* 3 */
  1936. /* Initialize option order */
  1937. for (i = 0; i < NO_OF_OPTIONS; i++) {
  1938. option_index[i] = i;
  1939. }
  1940. /* Sort all options */
  1941. for (;;) {
  1942. int swapped = 0;
  1943. for (i = 1; i < NO_OF_OPTIONS; i++) {
  1944. if (optioncmp(cv_options[option_index[i - 1]].name,
  1945. cv_options[option_index[i]].name)
  1946. > 0) {
  1947. short swap = option_index[i];
  1948. option_index[i] = option_index[i - 1];
  1949. option_index[i - 1] = swap;
  1950. swapped = 1;
  1951. }
  1952. }
  1953. if (!swapped) {
  1954. break;
  1955. }
  1956. }
  1957. /* Create input fields for all options */
  1958. for (i = 0; i < NO_OF_OPTIONS; i++) {
  1959. /* Get option according to option order */
  1960. const struct mg_option *opt = &cv_options[option_index[i]];
  1961. /* Template style for all input fields (will be modified for specific
  1962. * field types) */
  1963. style = WS_CHILD | WS_VISIBLE | WS_TABSTOP;
  1964. /* TODO: Bottom of a column must not be a MULTILINE input field.
  1965. * If the last input field in a column would of multi-line type
  1966. * (opt->type == MG_CONFIG_TYPE_STRING_MULTILINE), then
  1967. * skip one field (nelems++).
  1968. * But in this case, maybe one more ROW might be required. */
  1969. /* Position and size of the input field (will be modified) */
  1970. x = BORDER_WIDTH + COLUMN_WIDTH * (nelems / NO_OF_ROWS);
  1971. y = BORDER_HEIGTH + HEIGHT + HEIGHT * (nelems % NO_OF_ROWS);
  1972. next_cell_width = CELL_WIDTH;
  1973. next_cell_height = HEIGHT - 3;
  1974. /* Determine top/bottom option for every column */
  1975. if ((nelems % NO_OF_ROWS) == 0) {
  1976. /* Set option on top of a new column once */
  1977. option_top[nelems / NO_OF_ROWS] = option_index[i];
  1978. }
  1979. /* Set/overwrite option on bottom of a column */
  1980. option_bottom[nelems / NO_OF_ROWS] = option_index[i];
  1981. /* Depending on option type: create suitable input field */
  1982. if (opt->type == MG_CONFIG_TYPE_NUMBER) {
  1983. style |= ES_NUMBER;
  1984. cl = 0x81;
  1985. style |= WS_BORDER | ES_AUTOHSCROLL;
  1986. } else if (opt->type == MG_CONFIG_TYPE_BOOLEAN) {
  1987. cl = 0x80;
  1988. style |= BS_AUTOCHECKBOX;
  1989. } else if ((opt->type == MG_CONFIG_TYPE_FILE)
  1990. || (opt->type == MG_CONFIG_TYPE_DIRECTORY)) {
  1991. style |= WS_BORDER | ES_AUTOHSCROLL;
  1992. cl = 0x81;
  1993. /* Additional button for file dialog */
  1994. add_control(&dlg,
  1995. 0x80,
  1996. ID_CONTROLS + option_index[i] + ID_FILE_BUTTONS_DELTA,
  1997. WS_VISIBLE | WS_CHILD | BS_PUSHBUTTON,
  1998. x + LABEL_WIDTH + CELL_WIDTH - FILE_DIALOG_BUTTON_WIDTH,
  1999. y,
  2000. FILE_DIALOG_BUTTON_WIDTH,
  2001. HEIGHT - 3,
  2002. "...");
  2003. next_cell_width -= FILE_DIALOG_BUTTON_WIDTH + BORDER_WIDTH / 2;
  2004. } else if (opt->type == MG_CONFIG_TYPE_STRING_MULTILINE) {
  2005. /* Multiline input */
  2006. cl = 0x81;
  2007. style |= WS_BORDER | ES_AUTOHSCROLL | ES_MULTILINE | ES_WANTRETURN
  2008. | WS_VSCROLL | ES_AUTOVSCROLL;
  2009. /* Add more space below */
  2010. nelems += 1;
  2011. next_cell_height += HEIGHT;
  2012. } else {
  2013. /* Standard text input field */
  2014. cl = 0x81;
  2015. style |= WS_BORDER | ES_AUTOHSCROLL;
  2016. }
  2017. /* Add label (static text) */
  2018. add_control(&dlg,
  2019. 0x82,
  2020. ID_STATIC,
  2021. WS_VISIBLE | WS_CHILD,
  2022. x,
  2023. y,
  2024. LABEL_WIDTH,
  2025. HEIGHT,
  2026. opt->name);
  2027. /* Add input field */
  2028. add_control(&dlg,
  2029. cl,
  2030. ID_CONTROLS + option_index[i],
  2031. style,
  2032. x + LABEL_WIDTH,
  2033. y,
  2034. next_cell_width,
  2035. next_cell_height,
  2036. "");
  2037. nelems++;
  2038. }
  2039. /* "Settings" frame around all options */
  2040. y = ((nelems + NO_OF_COLUMNS - 1) / NO_OF_COLUMNS + 1) * HEIGHT;
  2041. for (i = 0; i < NO_OF_COLUMNS; i++) {
  2042. sprintf(text,
  2043. " Settings %c - %c ",
  2044. cv_options[option_top[i]].name[0],
  2045. cv_options[option_bottom[i]].name[0]);
  2046. add_control(&dlg,
  2047. 0x80,
  2048. ID_GROUP,
  2049. WS_CHILD | WS_VISIBLE | BS_GROUPBOX,
  2050. BORDER_WIDTH / 2
  2051. + i * (DIALOG_WIDTH - BORDER_WIDTH) / NO_OF_COLUMNS,
  2052. BORDER_WIDTH / 2,
  2053. (DIALOG_WIDTH - BORDER_WIDTH) / NO_OF_COLUMNS,
  2054. y + 2,
  2055. text);
  2056. }
  2057. /* Buttons below "Settings" frame */
  2058. y += HEIGHT;
  2059. add_control(&dlg,
  2060. 0x80,
  2061. ID_SAVE,
  2062. WS_CHILD | WS_VISIBLE | BS_PUSHBUTTON | WS_TABSTOP,
  2063. DIALOG_WIDTH - 70,
  2064. y,
  2065. 65,
  2066. 12,
  2067. "Save Settings");
  2068. add_control(&dlg,
  2069. 0x80,
  2070. ID_RESET_DEFAULTS,
  2071. WS_CHILD | WS_VISIBLE | BS_PUSHBUTTON | WS_TABSTOP,
  2072. DIALOG_WIDTH - 140,
  2073. y,
  2074. 65,
  2075. 12,
  2076. "Reset to defaults");
  2077. add_control(&dlg,
  2078. 0x80,
  2079. ID_RESET_FILE,
  2080. WS_CHILD | WS_VISIBLE | BS_PUSHBUTTON | WS_TABSTOP,
  2081. DIALOG_WIDTH - 210,
  2082. y,
  2083. 65,
  2084. 12,
  2085. "Reload from file");
  2086. add_control(&dlg,
  2087. 0x80,
  2088. ID_RESET_ACTIVE,
  2089. WS_CHILD | WS_VISIBLE | BS_PUSHBUTTON | WS_TABSTOP,
  2090. DIALOG_WIDTH - 280,
  2091. y,
  2092. 65,
  2093. 12,
  2094. "Reload active");
  2095. add_control(&dlg,
  2096. 0x82,
  2097. ID_STATIC,
  2098. WS_CHILD | WS_VISIBLE | WS_DISABLED,
  2099. 5,
  2100. y,
  2101. 100,
  2102. 12,
  2103. g_server_base_name);
  2104. /* Calculate total height of the dialog */
  2105. dlg.header.dlg_template.cy = y + HEIGHT;
  2106. s_dlg_proc_param.fRetry = NULL;
  2107. DialogBoxIndirectParam(NULL,
  2108. &dlg.header.dlg_template,
  2109. NULL,
  2110. SettingsDlgProc,
  2111. (LPARAM)&s_dlg_proc_param);
  2112. free(option_index);
  2113. s_dlg_proc_param.hWnd = NULL;
  2114. s_dlg_proc_param.guard = 0;
  2115. }
  2116. static void
  2117. change_password_file()
  2118. {
  2119. /* Parameter for size/format tuning of the dialog */
  2120. short HEIGHT = 15;
  2121. short WIDTH = 320;
  2122. short LABEL_WIDTH = 90;
  2123. /* Other variables */
  2124. OPENFILENAME of;
  2125. char path[PATH_MAX] = PASSWORDS_FILE_NAME;
  2126. char strbuf[256], u[256], d[256];
  2127. HWND hDlg = NULL;
  2128. FILE *f;
  2129. short y, nelems;
  2130. const char *domain = mg_get_option(g_ctx, "authentication_domain");
  2131. static struct dlg_proc_param s_dlg_proc_param;
  2132. struct dlg_complete dlg;
  2133. if (s_dlg_proc_param.guard == 0) {
  2134. memset(&s_dlg_proc_param, 0, sizeof(s_dlg_proc_param));
  2135. s_dlg_proc_param.guard = 1;
  2136. } else {
  2137. SetForegroundWindow(s_dlg_proc_param.hWnd);
  2138. return;
  2139. }
  2140. memset(&of, 0, sizeof(of));
  2141. of.lStructSize = sizeof(of);
  2142. of.hwndOwner = (HWND)hDlg;
  2143. of.lpstrFile = path;
  2144. of.nMaxFile = sizeof(path);
  2145. of.lpstrInitialDir = mg_get_option(g_ctx, "document_root");
  2146. of.Flags = OFN_CREATEPROMPT | OFN_NOCHANGEDIR | OFN_HIDEREADONLY;
  2147. if (!GetSaveFileName(&of)) {
  2148. /* Cancel/Close by user */
  2149. s_dlg_proc_param.guard = 0;
  2150. return;
  2151. }
  2152. f = fopen(path, "a+");
  2153. if (f) {
  2154. fclose(f);
  2155. } else {
  2156. MessageBox(NULL, path, "Can not open file", MB_ICONERROR);
  2157. s_dlg_proc_param.guard = 0;
  2158. return;
  2159. }
  2160. do {
  2161. s_dlg_proc_param.hWnd = NULL;
  2162. FillDialogHeader(&dlg, WIDTH);
  2163. f = fopen(path, "r+");
  2164. if (!f) {
  2165. MessageBox(NULL, path, "Can not open file", MB_ICONERROR);
  2166. s_dlg_proc_param.guard = 0;
  2167. return;
  2168. }
  2169. nelems = 0;
  2170. while (fgets(strbuf, sizeof(strbuf), f)) {
  2171. if (sscanf(strbuf, "%255[^:]:%255[^:]:%*s", u, d) != 2) {
  2172. continue;
  2173. }
  2174. u[255] = 0;
  2175. d[255] = 0;
  2176. y = (nelems + 1) * HEIGHT + 5;
  2177. add_control(&dlg,
  2178. 0x80,
  2179. ID_CONTROLS + nelems + ID_FILE_BUTTONS_DELTA * 3,
  2180. WS_CHILD | WS_VISIBLE | BS_PUSHBUTTON | WS_TABSTOP,
  2181. 10,
  2182. y,
  2183. 65,
  2184. 12,
  2185. "Modify password");
  2186. add_control(&dlg,
  2187. 0x80,
  2188. ID_CONTROLS + nelems + ID_FILE_BUTTONS_DELTA * 2,
  2189. WS_CHILD | WS_VISIBLE | BS_PUSHBUTTON | WS_TABSTOP,
  2190. 80,
  2191. y,
  2192. 55,
  2193. 12,
  2194. "Remove user");
  2195. add_control(&dlg,
  2196. 0x81,
  2197. ID_CONTROLS + nelems + ID_FILE_BUTTONS_DELTA,
  2198. WS_CHILD | WS_VISIBLE | WS_BORDER | ES_AUTOHSCROLL
  2199. | ES_READONLY,
  2200. 245,
  2201. y,
  2202. 60,
  2203. 12,
  2204. d);
  2205. add_control(&dlg,
  2206. 0x81,
  2207. ID_CONTROLS + nelems,
  2208. WS_CHILD | WS_VISIBLE | WS_BORDER | ES_AUTOHSCROLL
  2209. | ES_READONLY,
  2210. 140,
  2211. y,
  2212. 100,
  2213. 12,
  2214. u);
  2215. nelems++;
  2216. }
  2217. fclose(f);
  2218. y = (nelems + 1) * HEIGHT + 10;
  2219. add_control(&dlg,
  2220. 0x80,
  2221. ID_ADD_USER,
  2222. WS_CHILD | WS_VISIBLE | BS_PUSHBUTTON | WS_TABSTOP,
  2223. 80,
  2224. y,
  2225. 55,
  2226. 12,
  2227. "Add user");
  2228. add_control(&dlg,
  2229. 0x81,
  2230. ID_ADD_USER_NAME,
  2231. WS_CHILD | WS_VISIBLE | WS_BORDER | ES_AUTOHSCROLL
  2232. | WS_TABSTOP,
  2233. 140,
  2234. y,
  2235. 100,
  2236. 12,
  2237. "");
  2238. add_control(&dlg,
  2239. 0x81,
  2240. ID_ADD_USER_REALM,
  2241. WS_CHILD | WS_VISIBLE | WS_BORDER | ES_AUTOHSCROLL
  2242. | WS_TABSTOP,
  2243. 245,
  2244. y,
  2245. 60,
  2246. 12,
  2247. domain);
  2248. y = (nelems + 2) * HEIGHT + 10;
  2249. add_control(&dlg,
  2250. 0x80,
  2251. ID_GROUP,
  2252. WS_CHILD | WS_VISIBLE | BS_GROUPBOX,
  2253. 5,
  2254. 5,
  2255. WIDTH - 10,
  2256. y,
  2257. " Users ");
  2258. y += HEIGHT;
  2259. add_control(&dlg,
  2260. 0x82,
  2261. ID_STATIC,
  2262. WS_CHILD | WS_VISIBLE | WS_DISABLED,
  2263. 5,
  2264. y,
  2265. 100,
  2266. 12,
  2267. g_server_base_name);
  2268. dlg.header.dlg_template.cy = y + 20;
  2269. s_dlg_proc_param.name = path;
  2270. s_dlg_proc_param.fRetry = NULL;
  2271. } while ((IDOK
  2272. == DialogBoxIndirectParam(NULL,
  2273. &dlg.header.dlg_template,
  2274. NULL,
  2275. PasswordDlgProc,
  2276. (LPARAM)&s_dlg_proc_param))
  2277. && (!g_exit_flag));
  2278. s_dlg_proc_param.hWnd = NULL;
  2279. s_dlg_proc_param.guard = 0;
  2280. }
  2281. static BOOL
  2282. sysinfo_reload(struct dlg_proc_param *prm)
  2283. {
  2284. static char *buf = 0;
  2285. int cl, rl;
  2286. cl = mg_get_context_info(g_ctx, NULL, 0);
  2287. free(buf);
  2288. cl += 510;
  2289. buf = (char *)malloc(cl + 1);
  2290. rl = mg_get_context_info(g_ctx, buf, cl);
  2291. if ((rl > cl) || (rl <= 0)) {
  2292. if (g_ctx == NULL) {
  2293. prm->buffer = "Server not running";
  2294. } else if (rl <= 0) {
  2295. prm->buffer = "No server statistics available";
  2296. } else {
  2297. prm->buffer = "Please retry";
  2298. }
  2299. } else {
  2300. prm->buffer = buf;
  2301. }
  2302. return TRUE;
  2303. }
  2304. int
  2305. show_system_info()
  2306. {
  2307. /* Parameter for size/format tuning of the dialog */
  2308. short HEIGHT = 15;
  2309. short WIDTH = 320;
  2310. short LABEL_WIDTH = 50;
  2311. /* Other parameters */
  2312. int ok;
  2313. short y;
  2314. static struct dlg_proc_param s_dlg_proc_param;
  2315. struct dlg_complete dlg;
  2316. /* Only allow one instance of this dialog to be open. */
  2317. if (s_dlg_proc_param.guard == 0) {
  2318. memset(&s_dlg_proc_param, 0, sizeof(s_dlg_proc_param));
  2319. s_dlg_proc_param.guard = 1;
  2320. } else {
  2321. SetForegroundWindow(s_dlg_proc_param.hWnd);
  2322. return 0;
  2323. }
  2324. /* Create the dialog */
  2325. FillDialogHeader(&dlg, WIDTH);
  2326. y = HEIGHT;
  2327. add_control(&dlg,
  2328. 0x82,
  2329. ID_STATIC,
  2330. WS_VISIBLE | WS_CHILD,
  2331. 10,
  2332. y,
  2333. LABEL_WIDTH,
  2334. HEIGHT,
  2335. "System Information:");
  2336. add_control(&dlg,
  2337. 0x81,
  2338. ID_CONTROLS + 1,
  2339. WS_CHILD | WS_VISIBLE | WS_BORDER | ES_AUTOHSCROLL
  2340. | ES_AUTOVSCROLL | ES_MULTILINE | ES_READONLY,
  2341. 15 + LABEL_WIDTH,
  2342. y,
  2343. WIDTH - LABEL_WIDTH - 25,
  2344. HEIGHT * 7,
  2345. g_system_info);
  2346. y += (WORD)(HEIGHT * 8);
  2347. add_control(&dlg,
  2348. 0x80,
  2349. IDRETRY,
  2350. WS_CHILD | WS_VISIBLE | BS_PUSHBUTTON | WS_TABSTOP,
  2351. WIDTH - 10 - 55 - 10 - 55,
  2352. y,
  2353. 55,
  2354. 12,
  2355. "Reload");
  2356. add_control(&dlg,
  2357. 0x80,
  2358. IDOK,
  2359. WS_CHILD | WS_VISIBLE | BS_PUSHBUTTON | WS_TABSTOP,
  2360. WIDTH - 10 - 55,
  2361. y,
  2362. 55,
  2363. 12,
  2364. "Close");
  2365. dlg.header.dlg_template.cy = y + (WORD)(HEIGHT * 1.5);
  2366. s_dlg_proc_param.name = "System information";
  2367. s_dlg_proc_param.fRetry = sysinfo_reload;
  2368. s_dlg_proc_param.idRetry = ID_CONTROLS + 1; /* Reload field with this ID */
  2369. ok = (IDOK
  2370. == DialogBoxIndirectParam(NULL,
  2371. &dlg.header.dlg_template,
  2372. NULL,
  2373. InputDlgProc,
  2374. (LPARAM)&s_dlg_proc_param));
  2375. s_dlg_proc_param.hWnd = NULL;
  2376. s_dlg_proc_param.guard = 0;
  2377. return ok;
  2378. }
  2379. static int
  2380. manage_service(int action)
  2381. {
  2382. const char *service_name = g_server_name;
  2383. SC_HANDLE hSCM = NULL, hService = NULL;
  2384. SERVICE_DESCRIPTION descr;
  2385. char path[PATH_MAX + 20] = ""; /* Path to executable plus magic argument */
  2386. int success = 1;
  2387. descr.lpDescription = (LPSTR)g_server_name;
  2388. if ((hSCM = OpenSCManager(NULL,
  2389. NULL,
  2390. action == ID_INSTALL_SERVICE ? GENERIC_WRITE
  2391. : GENERIC_READ))
  2392. == NULL) {
  2393. success = 0;
  2394. show_error();
  2395. } else if (action == ID_INSTALL_SERVICE) {
  2396. path[sizeof(path) - 1] = 0;
  2397. GetModuleFileName(NULL, path, sizeof(path) - 1);
  2398. strncat(path, " ", sizeof(path) - 1 - strlen(path));
  2399. strncat(path, service_magic_argument, sizeof(path) - 1 - strlen(path));
  2400. hService = CreateService(hSCM,
  2401. service_name,
  2402. service_name,
  2403. SERVICE_ALL_ACCESS,
  2404. SERVICE_WIN32_OWN_PROCESS,
  2405. SERVICE_AUTO_START,
  2406. SERVICE_ERROR_NORMAL,
  2407. path,
  2408. NULL,
  2409. NULL,
  2410. NULL,
  2411. NULL,
  2412. NULL);
  2413. if (hService) {
  2414. ChangeServiceConfig2(hService, SERVICE_CONFIG_DESCRIPTION, &descr);
  2415. } else {
  2416. show_error();
  2417. }
  2418. } else if (action == ID_REMOVE_SERVICE) {
  2419. if ((hService = OpenService(hSCM, service_name, DELETE)) == NULL
  2420. || !DeleteService(hService)) {
  2421. show_error();
  2422. }
  2423. } else if ((hService =
  2424. OpenService(hSCM, service_name, SERVICE_QUERY_STATUS))
  2425. == NULL) {
  2426. success = 0;
  2427. }
  2428. if (hService)
  2429. CloseServiceHandle(hService);
  2430. if (hSCM)
  2431. CloseServiceHandle(hSCM);
  2432. return success;
  2433. }
  2434. static void
  2435. add_icon_to_systray(HWND hWnd)
  2436. {
  2437. /* tray icon is entry point to the menu */
  2438. if (!g_hide_tray) {
  2439. TrayIcon.cbSize = sizeof(TrayIcon);
  2440. TrayIcon.uID = ID_ICON;
  2441. TrayIcon.uFlags = NIF_ICON | NIF_MESSAGE | NIF_TIP;
  2442. TrayIcon.hIcon = hIcon;
  2443. TrayIcon.hWnd = hWnd;
  2444. snprintf(TrayIcon.szTip, sizeof(TrayIcon.szTip), "%s", g_server_name);
  2445. TrayIcon.uCallbackMessage = WM_USER;
  2446. Shell_NotifyIcon(NIM_ADD, &TrayIcon);
  2447. } else {
  2448. TrayIcon.cbSize = 0;
  2449. }
  2450. }
  2451. /* Window proc for taskbar icon */
  2452. static LRESULT CALLBACK
  2453. WindowProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam)
  2454. {
  2455. int service_installed;
  2456. char buf[200];
  2457. POINT pt;
  2458. HMENU hMenu;
  2459. switch (msg) {
  2460. case WM_CREATE:
  2461. if ((__argv[1] != NULL) && !strcmp(__argv[1], service_magic_argument)) {
  2462. static SERVICE_TABLE_ENTRY service_table[2];
  2463. char *service_argv[2];
  2464. service_argv[0] = __argv[0];
  2465. service_argv[1] = NULL;
  2466. start_civetweb(1, service_argv);
  2467. memset(service_table, 0, sizeof(service_table));
  2468. service_table[0].lpServiceName = (LPSTR)g_server_name;
  2469. service_table[0].lpServiceProc =
  2470. (LPSERVICE_MAIN_FUNCTION)ServiceMain;
  2471. StartServiceCtrlDispatcher(service_table);
  2472. exit(EXIT_SUCCESS);
  2473. } else {
  2474. start_civetweb(__argc, __argv);
  2475. }
  2476. break;
  2477. case WM_COMMAND:
  2478. switch (LOWORD(wParam)) {
  2479. case ID_QUIT:
  2480. stop_civetweb();
  2481. if (TrayIcon.cbSize) {
  2482. Shell_NotifyIcon(NIM_DELETE, &TrayIcon);
  2483. }
  2484. g_exit_flag = 1;
  2485. PostQuitMessage(0);
  2486. return 0;
  2487. case ID_SETTINGS:
  2488. show_settings_dialog();
  2489. break;
  2490. case ID_PASSWORD:
  2491. change_password_file();
  2492. break;
  2493. case ID_SYSINFO:
  2494. show_system_info();
  2495. break;
  2496. case ID_INSTALL_SERVICE:
  2497. case ID_REMOVE_SERVICE:
  2498. manage_service(LOWORD(wParam));
  2499. break;
  2500. case ID_CONNECT: {
  2501. /* Get port from server configuration (listening_ports) and build
  2502. * URL from port. */
  2503. const char *url = get_url_to_first_open_port(g_ctx);
  2504. /* Open URL with Windows default browser */
  2505. ShellExecute(NULL, "open", url, NULL, NULL, SW_SHOW);
  2506. } break;
  2507. case ID_WEBSITE:
  2508. fprintf(stdout, "[%s]\n", g_website);
  2509. ShellExecute(NULL, "open", g_website, NULL, NULL, SW_SHOW);
  2510. break;
  2511. }
  2512. break;
  2513. case WM_USER:
  2514. switch (lParam) {
  2515. case WM_RBUTTONUP:
  2516. case WM_LBUTTONUP:
  2517. case WM_LBUTTONDBLCLK:
  2518. hMenu = CreatePopupMenu();
  2519. AppendMenu(hMenu,
  2520. MF_STRING | MF_GRAYED,
  2521. ID_SEPARATOR,
  2522. g_server_name);
  2523. AppendMenu(hMenu, MF_SEPARATOR, ID_SEPARATOR, "");
  2524. service_installed = manage_service(0);
  2525. snprintf(buf,
  2526. sizeof(buf) - 1,
  2527. "NT service: %s installed",
  2528. service_installed ? "" : "not");
  2529. buf[sizeof(buf) - 1] = 0;
  2530. AppendMenu(hMenu, MF_STRING | MF_GRAYED, ID_SEPARATOR, buf);
  2531. AppendMenu(hMenu,
  2532. MF_STRING | (service_installed ? MF_GRAYED : 0),
  2533. ID_INSTALL_SERVICE,
  2534. "Install service");
  2535. AppendMenu(hMenu,
  2536. MF_STRING | (!service_installed ? MF_GRAYED : 0),
  2537. ID_REMOVE_SERVICE,
  2538. "Deinstall service");
  2539. AppendMenu(hMenu, MF_SEPARATOR, ID_SEPARATOR, "");
  2540. AppendMenu(hMenu, MF_STRING, ID_CONNECT, "Start browser");
  2541. AppendMenu(hMenu, MF_STRING, ID_SETTINGS, "Edit settings");
  2542. AppendMenu(hMenu, MF_STRING, ID_PASSWORD, "Modify password file");
  2543. AppendMenu(hMenu, MF_STRING, ID_SYSINFO, "Show system info");
  2544. AppendMenu(hMenu, MF_STRING, ID_WEBSITE, "Visit website");
  2545. AppendMenu(hMenu, MF_SEPARATOR, ID_SEPARATOR, "");
  2546. AppendMenu(hMenu, MF_STRING, ID_QUIT, "Exit");
  2547. GetCursorPos(&pt);
  2548. SetForegroundWindow(hWnd);
  2549. TrackPopupMenu(hMenu, 0, pt.x, pt.y, 0, hWnd, NULL);
  2550. PostMessage(hWnd, WM_NULL, 0, 0);
  2551. DestroyMenu(hMenu);
  2552. break;
  2553. }
  2554. break;
  2555. case WM_CLOSE:
  2556. stop_civetweb();
  2557. if (TrayIcon.cbSize) {
  2558. Shell_NotifyIcon(NIM_DELETE, &TrayIcon);
  2559. }
  2560. g_exit_flag = 1;
  2561. PostQuitMessage(0);
  2562. return 0; /* We've just sent our own quit message, with proper hwnd. */
  2563. default:
  2564. if (msg == msg_taskbar_created) {
  2565. add_icon_to_systray(hWnd);
  2566. }
  2567. break;
  2568. }
  2569. return DefWindowProc(hWnd, msg, wParam, lParam);
  2570. }
  2571. /* An executable with "Subsystem: Windows" does not have a Console.
  2572. * Create one manually, if required. */
  2573. static int
  2574. MakeConsole(void)
  2575. {
  2576. DWORD err;
  2577. HANDLE hConWnd = GetConsoleWindow();
  2578. int ok = 1;
  2579. if (hConWnd == NULL) {
  2580. if (!AttachConsole(ATTACH_PARENT_PROCESS)) {
  2581. FreeConsole();
  2582. if (!AllocConsole()) {
  2583. err = GetLastError();
  2584. if (err == ERROR_ACCESS_DENIED) {
  2585. ok = 0;
  2586. MessageBox(NULL,
  2587. "Insufficient rights to create a console window",
  2588. "Error",
  2589. MB_ICONERROR);
  2590. }
  2591. }
  2592. AttachConsole(GetCurrentProcessId());
  2593. }
  2594. /* Retry to get a console handle */
  2595. hConWnd = GetConsoleWindow();
  2596. if (hConWnd == NULL) {
  2597. ok = 0;
  2598. } else {
  2599. /* Reopen console handles according to
  2600. * https://stackoverflow.com/questions/9020790/using-stdin-with-an-allocconsole
  2601. */
  2602. if (NULL == freopen("CONIN$", "r", stdin)) {
  2603. ok = 0;
  2604. }
  2605. if (NULL == freopen("CONOUT$", "w", stdout)) {
  2606. ok = 0;
  2607. }
  2608. if (NULL == freopen("CONOUT$", "w", stderr)) {
  2609. ok = 0;
  2610. }
  2611. }
  2612. }
  2613. if (hConWnd == NULL) {
  2614. ok = 0;
  2615. } else {
  2616. SetConsoleTitle(g_server_name);
  2617. }
  2618. return ok;
  2619. }
  2620. /* main() for Windows (Subsystem: Windows). */
  2621. int WINAPI
  2622. WinMain(HINSTANCE hInst, HINSTANCE hPrev, LPSTR cmdline, int show)
  2623. {
  2624. WNDCLASS cls;
  2625. HWND hWnd;
  2626. MSG msg;
  2627. #if defined(DEBUG)
  2628. (void)MakeConsole();
  2629. #endif
  2630. (void)hInst;
  2631. (void)hPrev;
  2632. (void)cmdline;
  2633. (void)show;
  2634. init_server_name();
  2635. init_system_info();
  2636. msg_taskbar_created = RegisterWindowMessage("TaskbarCreated");
  2637. memset(&cls, 0, sizeof(cls));
  2638. cls.lpfnWndProc = WindowProc;
  2639. cls.hInstance = GetModuleHandle(NULL);
  2640. cls.hIcon = LoadIcon(NULL, IDI_APPLICATION);
  2641. cls.lpszClassName = g_server_base_name;
  2642. RegisterClass(&cls);
  2643. hWnd = CreateWindow(cls.lpszClassName,
  2644. g_server_name,
  2645. WS_OVERLAPPEDWINDOW,
  2646. 0,
  2647. 0,
  2648. 0,
  2649. 0,
  2650. NULL,
  2651. NULL,
  2652. cls.hInstance,
  2653. NULL);
  2654. ShowWindow(hWnd, SW_HIDE);
  2655. /* Load icon for systray and other dialogs */
  2656. if (g_icon_name) {
  2657. hIcon = (HICON)
  2658. LoadImage(NULL, g_icon_name, IMAGE_ICON, 16, 16, LR_LOADFROMFILE);
  2659. } else {
  2660. hIcon = (HICON)LoadImage(GetModuleHandle(NULL),
  2661. MAKEINTRESOURCE(ID_ICON),
  2662. IMAGE_ICON,
  2663. 16,
  2664. 16,
  2665. 0);
  2666. }
  2667. add_icon_to_systray(hWnd);
  2668. /* Message loop */
  2669. while (GetMessage(&msg, hWnd, 0, 0) > 0) {
  2670. TranslateMessage(&msg);
  2671. DispatchMessage(&msg);
  2672. }
  2673. free_system_info();
  2674. /* Return the WM_QUIT value. */
  2675. return (int)msg.wParam;
  2676. }
  2677. /* main() for Windows (Subsystem: Console). */
  2678. int
  2679. main(int argc, char *argv[])
  2680. {
  2681. (void)argc;
  2682. (void)argv;
  2683. return WinMain(0, 0, 0, 0);
  2684. }
  2685. #elif defined(USE_COCOA)
  2686. #import <Cocoa/Cocoa.h>
  2687. @interface Civetweb : NSObject <NSApplicationDelegate>
  2688. - (void)openBrowser;
  2689. - (void)shutDown;
  2690. @end
  2691. @implementation Civetweb
  2692. - (void)openBrowser
  2693. {
  2694. [[NSWorkspace sharedWorkspace]
  2695. openURL:[NSURL URLWithString:[NSString stringWithUTF8String:
  2696. get_url_to_first_open_port(
  2697. g_ctx)]]];
  2698. }
  2699. - (void)editConfig
  2700. {
  2701. create_config_file(g_ctx, g_config_file_name);
  2702. NSString *path = [NSString stringWithUTF8String:g_config_file_name];
  2703. if (![[NSWorkspace sharedWorkspace] openFile:path
  2704. withApplication:@"TextEdit"]) {
  2705. NSAlert *alert = [[[NSAlert alloc] init] autorelease];
  2706. [alert setAlertStyle:NSWarningAlertStyle];
  2707. [alert setMessageText:NSLocalizedString(@"Unable to open config file.",
  2708. "")];
  2709. [alert setInformativeText:path];
  2710. (void)[alert runModal];
  2711. }
  2712. }
  2713. - (void)shutDown
  2714. {
  2715. [NSApp terminate:nil];
  2716. }
  2717. @end
  2718. int
  2719. main(int argc, char *argv[])
  2720. {
  2721. init_server_name();
  2722. init_system_info();
  2723. start_civetweb(argc, argv);
  2724. [NSAutoreleasePool new];
  2725. [NSApplication sharedApplication];
  2726. /* Add delegate to process menu item actions */
  2727. Civetweb *myDelegate = [[Civetweb alloc] autorelease];
  2728. [NSApp setDelegate:myDelegate];
  2729. /* Run this app as agent */
  2730. ProcessSerialNumber psn = {0, kCurrentProcess};
  2731. TransformProcessType(&psn, kProcessTransformToBackgroundApplication);
  2732. SetFrontProcess(&psn);
  2733. /* Add status bar menu */
  2734. id menu = [[NSMenu new] autorelease];
  2735. /* Add version menu item */
  2736. [menu
  2737. addItem:[[[NSMenuItem alloc]
  2738. /*initWithTitle:[NSString stringWithFormat:@"%s",
  2739. server_name]*/
  2740. initWithTitle:[NSString stringWithUTF8String:g_server_name]
  2741. action:@selector(noexist)
  2742. keyEquivalent:@""] autorelease]];
  2743. /* Add configuration menu item */
  2744. [menu addItem:[[[NSMenuItem alloc] initWithTitle:@"Edit configuration"
  2745. action:@selector(editConfig)
  2746. keyEquivalent:@""] autorelease]];
  2747. /* Add connect menu item */
  2748. [menu
  2749. addItem:[[[NSMenuItem alloc] initWithTitle:@"Open web root in a browser"
  2750. action:@selector(openBrowser)
  2751. keyEquivalent:@""] autorelease]];
  2752. /* Separator */
  2753. [menu addItem:[NSMenuItem separatorItem]];
  2754. /* Add quit menu item */
  2755. [menu addItem:[[[NSMenuItem alloc] initWithTitle:@"Quit"
  2756. action:@selector(shutDown)
  2757. keyEquivalent:@"q"] autorelease]];
  2758. /* Attach menu to the status bar */
  2759. id item = [[[NSStatusBar systemStatusBar]
  2760. statusItemWithLength:NSVariableStatusItemLength] retain];
  2761. [item setHighlightMode:YES];
  2762. [item setImage:[NSImage imageNamed:@"civetweb_22x22.png"]];
  2763. [item setMenu:menu];
  2764. /* Run the app */
  2765. [NSApp activateIgnoringOtherApps:YES];
  2766. [NSApp run];
  2767. stop_civetweb();
  2768. free_system_info();
  2769. return EXIT_SUCCESS;
  2770. }
  2771. #else
  2772. /* main for Linux (and others) */
  2773. int
  2774. main(int argc, char *argv[])
  2775. {
  2776. init_server_name();
  2777. init_system_info();
  2778. start_civetweb(argc, argv);
  2779. fprintf(stdout,
  2780. "%s started on port(s) %s with web root [%s]\n",
  2781. g_server_name,
  2782. mg_get_option(g_ctx, "listening_ports"),
  2783. mg_get_option(g_ctx, "document_root"));
  2784. while (g_exit_flag == 0) {
  2785. sleep(1);
  2786. }
  2787. fprintf(stdout,
  2788. "Exiting on signal %d, waiting for all threads to finish...",
  2789. g_exit_flag);
  2790. fflush(stdout);
  2791. stop_civetweb();
  2792. fprintf(stdout, "%s", " done.\n");
  2793. free_system_info();
  2794. return EXIT_SUCCESS;
  2795. }
  2796. #endif /* _WIN32 */
  2797. #undef printf