main.c 77 KB

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