main.c 82 KB

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