main.c 64 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596
  1. /* Copyright (c) 2013-2015 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. #ifndef _CRT_SECURE_NO_WARNINGS
  24. #define _CRT_SECURE_NO_WARNINGS /* Disable deprecation warning in VS2005 */
  25. #endif
  26. #ifndef _CRT_SECURE_NO_DEPRECATE
  27. #define _CRT_SECURE_NO_DEPRECATE
  28. #endif
  29. #else
  30. #define _XOPEN_SOURCE 600 /* For PATH_MAX on linux */
  31. /* This should also be sufficient for "realpath", according to
  32. * http://man7.org/linux/man-pages/man3/realpath.3.html, but in
  33. * reality it does not seem to work. */
  34. /* In case this causes a problem, disable the warning:
  35. * #pragma GCC diagnostic ignored "-Wimplicit-function-declaration"
  36. * #pragma clang diagnostic ignored "-Wimplicit-function-declaration"
  37. */
  38. #endif
  39. #ifndef IGNORE_UNUSED_RESULT
  40. #define IGNORE_UNUSED_RESULT(a) ((void)((a) && 1))
  41. #endif
  42. #if defined(__cplusplus) && (__cplusplus >= 201103L)
  43. #define NO_RETURN [[noreturn]]
  44. #elif defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 201112L)
  45. #define NO_RETURN _Noreturn
  46. #else
  47. #define NO_RETURN
  48. #endif
  49. #include <sys/stat.h>
  50. #include <stdio.h>
  51. #include <stdint.h>
  52. #include <limits.h>
  53. #include <stdlib.h>
  54. #include <signal.h>
  55. #include <string.h>
  56. #include <errno.h>
  57. #include <stddef.h>
  58. #include <stdarg.h>
  59. #include <ctype.h>
  60. #include <assert.h>
  61. #include "civetweb.h"
  62. #define printf \
  63. DO_NOT_USE_THIS_FUNCTION__USE_fprintf /* Required for unit testing */
  64. #if defined(_WIN32) \
  65. && !defined(__SYMBIAN32__) /* WINDOWS / UNIX include block */
  66. #ifndef _WIN32_WINNT
  67. #define _WIN32_WINNT 0x0501 /* for tdm-gcc so we can use getconsolewindow */
  68. #endif
  69. #undef UNICODE
  70. #include <windows.h>
  71. #include <winsvc.h>
  72. #include <shlobj.h>
  73. #include <io.h>
  74. #define getcwd(a, b) (_getcwd(a, b))
  75. #if !defined(__MINGW32__)
  76. extern char *_getcwd(char *buf, size_t size);
  77. #endif
  78. static int guard = 0; /* test if any dialog is already open */
  79. #ifndef PATH_MAX
  80. #define PATH_MAX MAX_PATH
  81. #endif
  82. #ifndef S_ISDIR
  83. #define S_ISDIR(x) ((x)&_S_IFDIR)
  84. #endif
  85. #define DIRSEP '\\'
  86. #define snprintf _snprintf
  87. #define vsnprintf _vsnprintf
  88. #define sleep(x) (Sleep((x)*1000))
  89. #define WINCDECL __cdecl
  90. #define abs_path(rel, abs, abs_size) (_fullpath((abs), (rel), (abs_size)))
  91. #else /* defined(_WIN32) && !defined(__SYMBIAN32__) - WINDOWS / UNIX include \
  92. block */
  93. #include <sys/utsname.h>
  94. #include <sys/wait.h>
  95. #include <unistd.h>
  96. #define DIRSEP '/'
  97. #define WINCDECL
  98. #define abs_path(rel, abs, abs_size) (realpath((rel), (abs)))
  99. #endif /* defined(_WIN32) && !defined(__SYMBIAN32__) - WINDOWS / UNIX include \
  100. block */
  101. #ifndef PATH_MAX
  102. #define PATH_MAX (1024)
  103. #endif
  104. #define MAX_OPTIONS (50)
  105. #define MAX_CONF_FILE_LINE_SIZE (8 * 1024)
  106. struct tuser_data {
  107. char *first_message;
  108. };
  109. static int g_exit_flag = 0; /* Main loop should exit */
  110. static char g_server_base_name[40]; /* Set by init_server_name() */
  111. static char *g_server_name; /* Set by init_server_name() */
  112. static char *g_icon_name; /* Set by init_server_name() */
  113. static char g_config_file_name[PATH_MAX] =
  114. ""; /* Set by process_command_line_arguments() */
  115. static struct mg_context *g_ctx; /* Set by start_civetweb() */
  116. static struct tuser_data
  117. g_user_data; /* Passed to mg_start() by start_civetweb() */
  118. #if !defined(CONFIG_FILE)
  119. #define CONFIG_FILE "civetweb.conf"
  120. #endif /* !CONFIG_FILE */
  121. #if !defined(PASSWORDS_FILE_NAME)
  122. #define PASSWORDS_FILE_NAME ".htpasswd"
  123. #endif
  124. /* backup config file */
  125. #if !defined(CONFIG_FILE2) && defined(__linux__)
  126. #define CONFIG_FILE2 "/usr/local/etc/civetweb.conf"
  127. #endif
  128. enum { OPTION_TITLE, OPTION_ICON, NUM_MAIN_OPTIONS };
  129. static struct mg_option main_config_options[] = {
  130. {"title", CONFIG_TYPE_STRING, NULL},
  131. {"icon", CONFIG_TYPE_STRING, NULL},
  132. {NULL, CONFIG_TYPE_UNKNOWN, NULL}};
  133. static void WINCDECL
  134. signal_handler(int sig_num)
  135. {
  136. g_exit_flag = sig_num;
  137. }
  138. static NO_RETURN void
  139. die(const char *fmt, ...)
  140. {
  141. va_list ap;
  142. char msg[200] = "";
  143. va_start(ap, fmt);
  144. (void)vsnprintf(msg, sizeof(msg) - 1, fmt, ap);
  145. msg[sizeof(msg) - 1] = 0;
  146. va_end(ap);
  147. #if defined(_WIN32)
  148. MessageBox(NULL, msg, "Error", MB_OK);
  149. #else
  150. fprintf(stderr, "%s\n", msg);
  151. #endif
  152. exit(EXIT_FAILURE);
  153. }
  154. #ifdef WIN32
  155. static int MakeConsole(void);
  156. #endif
  157. static void
  158. show_server_name(void)
  159. {
  160. #ifdef WIN32
  161. (void)MakeConsole();
  162. #endif
  163. fprintf(stderr, "CivetWeb v%s, built on %s\n", mg_version(), __DATE__);
  164. }
  165. static NO_RETURN void
  166. show_usage_and_exit(const char *exeName)
  167. {
  168. const struct mg_option *options;
  169. int i;
  170. if (exeName == 0 || *exeName == 0) {
  171. exeName = "civetweb";
  172. }
  173. show_server_name();
  174. fprintf(stderr, "\nUsage:\n");
  175. fprintf(stderr, " Start server with a set of options:\n");
  176. fprintf(stderr, " %s [config_file]\n", exeName);
  177. fprintf(stderr, " %s [-option value ...]\n", exeName);
  178. fprintf(stderr, " Show system information:\n");
  179. fprintf(stderr, " %s -I\n", exeName);
  180. fprintf(stderr, " Add user/change password:\n");
  181. fprintf(stderr,
  182. " %s -A <htpasswd_file> <realm> <user> <passwd>\n",
  183. exeName);
  184. fprintf(stderr, " Remove user:\n");
  185. fprintf(stderr, " %s -R <htpasswd_file> <realm> <user>\n", exeName);
  186. fprintf(stderr, "\nOPTIONS:\n");
  187. options = mg_get_valid_options();
  188. for (i = 0; options[i].name != NULL; i++) {
  189. fprintf(stderr,
  190. " -%s %s\n",
  191. options[i].name,
  192. ((options[i].default_value == NULL)
  193. ? "<empty>"
  194. : options[i].default_value));
  195. }
  196. options = main_config_options;
  197. for (i = 0; options[i].name != NULL; i++) {
  198. fprintf(stderr,
  199. " -%s %s\n",
  200. options[i].name,
  201. ((options[i].default_value == NULL)
  202. ? "<empty>"
  203. : options[i].default_value));
  204. }
  205. exit(EXIT_FAILURE);
  206. }
  207. #if defined(_WIN32) || defined(USE_COCOA)
  208. static const char *config_file_top_comment =
  209. "# Civetweb web server configuration file.\n"
  210. "# For detailed description of every option, visit\n"
  211. "# https://github.com/civetweb/civetweb/blob/master/docs/UserManual.md\n"
  212. "# Lines starting with '#' and empty lines are ignored.\n"
  213. "# To make a change, remove leading '#', modify option's value,\n"
  214. "# save this file and then restart Civetweb.\n\n";
  215. static const char *
  216. get_url_to_first_open_port(const struct mg_context *ctx)
  217. {
  218. static char url[100];
  219. const char *open_ports = mg_get_option(ctx, "listening_ports");
  220. int a, b, c, d, port, n;
  221. if (sscanf(open_ports, "%d.%d.%d.%d:%d%n", &a, &b, &c, &d, &port, &n)
  222. == 5) {
  223. snprintf(url,
  224. sizeof(url),
  225. "%s://%d.%d.%d.%d:%d",
  226. open_ports[n] == 's' ? "https" : "http",
  227. a,
  228. b,
  229. c,
  230. d,
  231. port);
  232. } else if (sscanf(open_ports, "%d%n", &port, &n) == 1) {
  233. snprintf(url,
  234. sizeof(url),
  235. "%s://localhost:%d",
  236. open_ports[n] == 's' ? "https" : "http",
  237. port);
  238. } else {
  239. snprintf(url, sizeof(url), "%s", "http://localhost:8080");
  240. }
  241. return url;
  242. }
  243. #ifdef ENABLE_CREATE_CONFIG_FILE
  244. static void
  245. create_config_file(const struct mg_context *ctx, const char *path)
  246. {
  247. const struct mg_option *options;
  248. const char *value;
  249. FILE *fp;
  250. int i;
  251. /* Create config file if it is not present yet */
  252. if ((fp = fopen(path, "r")) != NULL) {
  253. fclose(fp);
  254. } else if ((fp = fopen(path, "a+")) != NULL) {
  255. fprintf(fp, "%s", config_file_top_comment);
  256. options = mg_get_valid_options();
  257. for (i = 0; options[i].name != NULL; i++) {
  258. value = mg_get_option(ctx, options[i].name);
  259. fprintf(fp,
  260. "# %s %s\n",
  261. options[i].name,
  262. value ? value : "<value>");
  263. }
  264. fclose(fp);
  265. }
  266. }
  267. #endif
  268. #endif
  269. static char *
  270. sdup(const char *str)
  271. {
  272. size_t len;
  273. char *p;
  274. len = strlen(str) + 1;
  275. if ((p = (char *)malloc(len)) != NULL) {
  276. memcpy(p, str, len);
  277. }
  278. return p;
  279. }
  280. static const char *
  281. get_option(char **options, const char *option_name)
  282. {
  283. int i = 0;
  284. const char *opt_value = NULL;
  285. /* TODO (low, api makeover): options should be an array of key-value-pairs,
  286. * like
  287. * struct {const char * key, const char * value} options[]
  288. * but it currently is an array with
  289. * options[2*i] = key, options[2*i + 1] = value
  290. * (probably with a MG_LEGACY_INTERFACE definition)
  291. */
  292. while (options[2 * i] != NULL) {
  293. if (strcmp(options[2 * i], option_name) == 0) {
  294. opt_value = options[2 * i + 1];
  295. break;
  296. }
  297. i++;
  298. }
  299. return opt_value;
  300. }
  301. static int
  302. set_option(char **options, const char *name, const char *value)
  303. {
  304. int i, type;
  305. const struct mg_option *default_options = mg_get_valid_options();
  306. for (i = 0; main_config_options[i].name != NULL; i++) {
  307. if (0 == strcmp(name, main_config_options[i].name)) {
  308. /* This option is evaluated by main.c, not civetweb.c - just skip it
  309. * and return OK */
  310. return 1;
  311. }
  312. }
  313. type = CONFIG_TYPE_UNKNOWN;
  314. for (i = 0; default_options[i].name != NULL; i++) {
  315. if (!strcmp(default_options[i].name, name)) {
  316. type = default_options[i].type;
  317. }
  318. }
  319. switch (type) {
  320. case CONFIG_TYPE_UNKNOWN:
  321. /* unknown option */
  322. return 0;
  323. case CONFIG_TYPE_NUMBER:
  324. /* integer number > 0, e.g. number of threads */
  325. if (atol(value) < 0) {
  326. /* invalid number */
  327. return 0;
  328. }
  329. break;
  330. case CONFIG_TYPE_STRING:
  331. /* any text */
  332. break;
  333. case CONFIG_TYPE_BOOLEAN:
  334. /* boolean value, yes or no */
  335. if ((0 != strcmp(value, "yes")) && (0 != strcmp(value, "no"))) {
  336. /* invalid boolean */
  337. return 0;
  338. }
  339. break;
  340. case CONFIG_TYPE_FILE:
  341. case CONFIG_TYPE_DIRECTORY:
  342. /* TODO (low): check this option when it is set, instead of calling
  343. * verify_existence later */
  344. break;
  345. case CONFIG_TYPE_EXT_PATTERN:
  346. /* list of file extentions */
  347. break;
  348. default:
  349. die("Unknown option type - option %s", name);
  350. }
  351. for (i = 0; i < MAX_OPTIONS; i++) {
  352. if (options[2 * i] == NULL) {
  353. options[2 * i] = sdup(name);
  354. options[2 * i + 1] = sdup(value);
  355. options[2 * i + 2] = NULL;
  356. break;
  357. } else if (!strcmp(options[2 * i], name)) {
  358. free(options[2 * i + 1]);
  359. options[2 * i + 1] = sdup(value);
  360. break;
  361. }
  362. }
  363. if (i == MAX_OPTIONS) {
  364. die("Too many options specified");
  365. }
  366. if (options[2 * i] == NULL || options[2 * i + 1] == NULL) {
  367. die("Out of memory");
  368. }
  369. /* option set correctly */
  370. return 1;
  371. }
  372. static int
  373. read_config_file(const char *config_file, char **options)
  374. {
  375. char line[MAX_CONF_FILE_LINE_SIZE], *p;
  376. FILE *fp = NULL;
  377. size_t i, j, line_no = 0;
  378. /* Open the config file */
  379. fp = fopen(config_file, "r");
  380. if (fp == NULL) {
  381. /* Failed to open the file. Keep errno for the caller. */
  382. return 0;
  383. }
  384. /* Load config file settings first */
  385. if (fp != NULL) {
  386. fprintf(stderr, "Loading config file %s\n", config_file);
  387. /* Loop over the lines in config file */
  388. while (fgets(line, sizeof(line), fp) != NULL) {
  389. if (!line_no && !memcmp(line, "\xEF\xBB\xBF", 3)) {
  390. /* strip UTF-8 BOM */
  391. p = line + 3;
  392. } else {
  393. p = line;
  394. }
  395. line_no++;
  396. /* Ignore empty lines and comments */
  397. for (i = 0; isspace(*(unsigned char *)&line[i]);)
  398. i++;
  399. if (p[i] == '#' || p[i] == '\0') {
  400. continue;
  401. }
  402. /* Skip spaces, \r and \n at the end of the line */
  403. for (j = strlen(line) - 1;
  404. isspace(*(unsigned char *)&line[j])
  405. || iscntrl(*(unsigned char *)&line[j]);)
  406. line[j--] = 0;
  407. /* Find the space character between option name and value */
  408. for (j = i; !isspace(*(unsigned char *)&line[j]) && (line[j] != 0);)
  409. j++;
  410. /* Terminate the string - then the string at (line+i) contains the
  411. * option name */
  412. line[j] = 0;
  413. j++;
  414. /* Trim additional spaces between option name and value - then
  415. * (line+j) contains the option value */
  416. while (isspace(line[j]))
  417. j++;
  418. /* Set option */
  419. if (!set_option(options, line + i, line + j)) {
  420. fprintf(stderr,
  421. "%s: line %d is invalid, ignoring it:\n %s",
  422. config_file,
  423. (int)line_no,
  424. p);
  425. }
  426. }
  427. (void)fclose(fp);
  428. }
  429. return 1;
  430. }
  431. static void
  432. process_command_line_arguments(char *argv[], char **options)
  433. {
  434. char *p;
  435. size_t i, cmd_line_opts_start = 1;
  436. #ifdef CONFIG_FILE2
  437. FILE *fp = NULL;
  438. #endif
  439. /* Should we use a config file ? */
  440. if (argv[1] != NULL && argv[1][0] != '-') {
  441. /* A config file was set */
  442. snprintf(g_config_file_name,
  443. sizeof(g_config_file_name) - 1,
  444. "%s",
  445. argv[1]);
  446. cmd_line_opts_start = 2;
  447. } else if ((p = strrchr(argv[0], DIRSEP)) == NULL) {
  448. /* No config file set. Use default file name in the current path. */
  449. snprintf(g_config_file_name,
  450. sizeof(g_config_file_name) - 1,
  451. "%s",
  452. CONFIG_FILE);
  453. } else {
  454. /* No config file set. Use default file name next to the executable. */
  455. snprintf(g_config_file_name,
  456. sizeof(g_config_file_name) - 1,
  457. "%.*s%c%s",
  458. (int)(p - argv[0]),
  459. argv[0],
  460. DIRSEP,
  461. CONFIG_FILE);
  462. }
  463. g_config_file_name[sizeof(g_config_file_name) - 1] = 0;
  464. #ifdef CONFIG_FILE2
  465. fp = fopen(g_config_file_name, "r");
  466. /* try alternate config file */
  467. if (fp == NULL) {
  468. fp = fopen(CONFIG_FILE2, "r");
  469. if (fp != NULL) {
  470. strcpy(g_config_file_name, CONFIG_FILE2);
  471. }
  472. }
  473. if (fp != NULL) {
  474. fclose(fp);
  475. }
  476. #endif
  477. /* read all configurations from a config file */
  478. if (0 == read_config_file(g_config_file_name, options)) {
  479. if (cmd_line_opts_start == 2) {
  480. /* If config file was set in command line and open failed, die. */
  481. /* Errno will still hold the error from fopen. */
  482. die("Cannot open config file %s: %s",
  483. g_config_file_name,
  484. strerror(errno));
  485. }
  486. /* Otherwise: CivetWeb can work without a config file */
  487. }
  488. /* If we're under MacOS and started by launchd, then the second
  489. argument is process serial number, -psn_.....
  490. In this case, don't process arguments at all. */
  491. if (argv[1] == NULL || memcmp(argv[1], "-psn_", 5) != 0) {
  492. /* Handle command line flags.
  493. They override config file and default settings. */
  494. for (i = cmd_line_opts_start; argv[i] != NULL; i += 2) {
  495. if (argv[i][0] != '-' || argv[i + 1] == NULL) {
  496. show_usage_and_exit(argv[0]);
  497. }
  498. if (!set_option(options, &argv[i][1], argv[i + 1])) {
  499. fprintf(
  500. stderr,
  501. "command line option is invalid, ignoring it:\n %s %s\n",
  502. argv[i],
  503. argv[i + 1]);
  504. }
  505. }
  506. }
  507. }
  508. static void
  509. init_server_name(int argc, const char *argv[])
  510. {
  511. int i;
  512. assert(sizeof(main_config_options) / sizeof(main_config_options[0])
  513. == NUM_MAIN_OPTIONS + 1);
  514. assert((strlen(mg_version()) + 12) < sizeof(g_server_base_name));
  515. snprintf(g_server_base_name,
  516. sizeof(g_server_base_name),
  517. "CivetWeb V%s",
  518. mg_version());
  519. g_server_name = g_server_base_name;
  520. for (i = 0; i < argc - 1; i++) {
  521. if ((argv[i][0] == '-')
  522. && (0 == strcmp(argv[i] + 1,
  523. main_config_options[OPTION_TITLE].name))) {
  524. g_server_name = (char *)(argv[i + 1]);
  525. }
  526. }
  527. g_icon_name = NULL;
  528. for (i = 0; i < argc - 1; i++) {
  529. if ((argv[i][0] == '-')
  530. && (0 == strcmp(argv[i] + 1,
  531. main_config_options[OPTION_ICON].name))) {
  532. g_icon_name = (char *)(argv[i + 1]);
  533. }
  534. }
  535. }
  536. static int
  537. log_message(const struct mg_connection *conn, const char *message)
  538. {
  539. const struct mg_context *ctx = mg_get_context(conn);
  540. struct tuser_data *ud = (struct tuser_data *)mg_get_user_data(ctx);
  541. fprintf(stderr, "%s\n", message);
  542. if (ud->first_message == NULL) {
  543. ud->first_message = sdup(message);
  544. }
  545. return 0;
  546. }
  547. static int
  548. is_path_absolute(const char *path)
  549. {
  550. #ifdef _WIN32
  551. return path != NULL
  552. && ((path[0] == '\\' && path[1] == '\\') || /* UNC path, e.g.
  553. \\server\dir */
  554. (isalpha(path[0]) && path[1] == ':'
  555. && path[2] == '\\')); /* E.g. X:\dir */
  556. #else
  557. return path != NULL && path[0] == '/';
  558. #endif
  559. }
  560. static void
  561. verify_existence(char **options, const char *option_name, int must_be_dir)
  562. {
  563. struct stat st;
  564. const char *path = get_option(options, option_name);
  565. #ifdef _WIN32
  566. wchar_t wbuf[1024];
  567. char mbbuf[1024];
  568. int len;
  569. if (path) {
  570. memset(wbuf, 0, sizeof(wbuf));
  571. memset(mbbuf, 0, sizeof(mbbuf));
  572. len = MultiByteToWideChar(CP_UTF8,
  573. 0,
  574. path,
  575. -1,
  576. wbuf,
  577. (int)sizeof(wbuf) / sizeof(wbuf[0]) - 1);
  578. wcstombs(mbbuf, wbuf, sizeof(mbbuf) - 1);
  579. path = mbbuf;
  580. (void)len;
  581. }
  582. #endif
  583. if (path != NULL && (stat(path, &st) != 0
  584. || ((S_ISDIR(st.st_mode) ? 1 : 0) != must_be_dir))) {
  585. die("Invalid path for %s: [%s]: (%s). Make sure that path is either "
  586. "absolute, or it is relative to civetweb executable.",
  587. option_name,
  588. path,
  589. strerror(errno));
  590. }
  591. }
  592. static void
  593. set_absolute_path(char *options[],
  594. const char *option_name,
  595. const char *path_to_civetweb_exe)
  596. {
  597. char path[PATH_MAX] = "", absolute[PATH_MAX] = "";
  598. const char *option_value;
  599. const char *p;
  600. /* Check whether option is already set */
  601. option_value = get_option(options, option_name);
  602. /* If option is already set and it is an absolute path,
  603. leave it as it is -- it's already absolute. */
  604. if (option_value != NULL && !is_path_absolute(option_value)) {
  605. /* Not absolute. Use the directory where civetweb executable lives
  606. be the relative directory for everything.
  607. Extract civetweb executable directory into path. */
  608. if ((p = strrchr(path_to_civetweb_exe, DIRSEP)) == NULL) {
  609. IGNORE_UNUSED_RESULT(getcwd(path, sizeof(path)));
  610. } else {
  611. snprintf(path,
  612. sizeof(path) - 1,
  613. "%.*s",
  614. (int)(p - path_to_civetweb_exe),
  615. path_to_civetweb_exe);
  616. path[sizeof(path) - 1] = 0;
  617. }
  618. strncat(path, "/", sizeof(path) - strlen(path) - 1);
  619. strncat(path, option_value, sizeof(path) - strlen(path) - 1);
  620. /* Absolutize the path, and set the option */
  621. IGNORE_UNUSED_RESULT(abs_path(path, absolute, sizeof(absolute)));
  622. set_option(options, option_name, absolute);
  623. }
  624. }
  625. #ifdef USE_LUA
  626. #include "civetweb_lua.h"
  627. #include "civetweb_private_lua.h"
  628. static int
  629. run_lua(const char *file_name)
  630. {
  631. struct lua_State *L;
  632. int lua_ret;
  633. int func_ret = EXIT_FAILURE;
  634. const char *lua_err_txt;
  635. #ifdef WIN32
  636. (void)MakeConsole();
  637. #endif
  638. L = luaL_newstate();
  639. if (L == NULL) {
  640. fprintf(stderr, "Error: Cannot create Lua state\n");
  641. return EXIT_FAILURE;
  642. }
  643. civetweb_open_lua_libs(L);
  644. lua_ret = luaL_loadfile(L, file_name);
  645. if (lua_ret != LUA_OK) {
  646. /* Error when loading the file (e.g. file not found, out of memory, ...)
  647. */
  648. lua_err_txt = lua_tostring(L, -1);
  649. fprintf(stderr, "Error loading file %s: %s\n", file_name, lua_err_txt);
  650. } else {
  651. /* The script file is loaded, now call it */
  652. lua_ret = lua_pcall(L,
  653. /* no arguments */ 0,
  654. /* zero or one return value */ 1,
  655. /* errors as strint return value */ 0);
  656. if (lua_ret != LUA_OK) {
  657. /* Error when executing the script */
  658. lua_err_txt = lua_tostring(L, -1);
  659. fprintf(stderr,
  660. "Error running file %s: %s\n",
  661. file_name,
  662. lua_err_txt);
  663. } else {
  664. /* Script executed */
  665. if (lua_type(L, -1) == LUA_TNUMBER) {
  666. func_ret = (int)lua_tonumber(L, -1);
  667. } else {
  668. func_ret = EXIT_SUCCESS;
  669. }
  670. }
  671. }
  672. lua_close(L);
  673. return func_ret;
  674. }
  675. #endif
  676. #ifdef USE_DUKTAPE
  677. #include "duktape.h"
  678. static int
  679. run_duktape(const char *file_name)
  680. {
  681. duk_context *ctx = NULL;
  682. #ifdef WIN32
  683. (void)MakeConsole();
  684. #endif
  685. ctx = duk_create_heap_default();
  686. if (!ctx) {
  687. fprintf(stderr, "Failed to create a Duktape heap.\n");
  688. goto finished;
  689. }
  690. if (duk_peval_file(ctx, file_name) != 0) {
  691. fprintf(stderr, "%s\n", duk_safe_to_string(ctx, -1));
  692. goto finished;
  693. }
  694. duk_pop(ctx); /* ignore result */
  695. finished:
  696. duk_destroy_heap(ctx);
  697. return 0;
  698. }
  699. #endif
  700. #if defined(__MINGW32__) || defined(__MINGW64__)
  701. /* For __MINGW32/64_MAJOR/MINOR_VERSION define */
  702. #include <_mingw.h>
  703. #endif
  704. static void
  705. start_civetweb(int argc, char *argv[])
  706. {
  707. struct mg_callbacks callbacks;
  708. char *options[2 * MAX_OPTIONS + 1];
  709. int i;
  710. /* Show system information and exit */
  711. if (argc > 1 && !strcmp(argv[1], "-I")) {
  712. const char *version = mg_version();
  713. #if defined(_WIN32)
  714. #if !defined(__SYMBIAN32__)
  715. DWORD dwVersion = 0;
  716. DWORD dwMajorVersion = 0;
  717. DWORD dwMinorVersion = 0;
  718. SYSTEM_INFO si;
  719. GetSystemInfo(&si);
  720. #ifdef _MSC_VER
  721. #pragma warning(push)
  722. // GetVersion was declared deprecated
  723. #pragma warning(disable : 4996)
  724. #endif
  725. dwVersion = GetVersion();
  726. #ifdef _MSC_VER
  727. #pragma warning(pop)
  728. #endif
  729. dwMajorVersion = (DWORD)(LOBYTE(LOWORD(dwVersion)));
  730. dwMinorVersion = (DWORD)(HIBYTE(LOWORD(dwVersion)));
  731. (void)MakeConsole();
  732. fprintf(stdout, "\n%s\n", g_server_name);
  733. fprintf(stdout,
  734. "%s - Windows %u.%u\n",
  735. g_server_base_name,
  736. (unsigned)dwMajorVersion,
  737. (unsigned)dwMinorVersion);
  738. fprintf(stdout,
  739. "CPU: type %u, cores %u, mask %x\n",
  740. (unsigned)si.wProcessorArchitecture,
  741. (unsigned)si.dwNumberOfProcessors,
  742. (unsigned)si.dwActiveProcessorMask);
  743. #else
  744. fprintf(stdout, "\n%s\n", g_server_name);
  745. fprintf(stdout, "%s - Symbian\n", g_server_base_name);
  746. #endif
  747. #else
  748. struct utsname name;
  749. memset(&name, 0, sizeof(name));
  750. uname(&name);
  751. fprintf(stdout, "\n%s\n", g_server_name);
  752. fprintf(stdout,
  753. "%s - %s %s (%s) - %s\n",
  754. g_server_base_name,
  755. name.sysname,
  756. name.version,
  757. name.release,
  758. name.machine);
  759. #endif
  760. fprintf(stdout, "Features:");
  761. if (mg_check_feature(1)) {
  762. fprintf(stdout, " Files");
  763. }
  764. if (mg_check_feature(2)) {
  765. fprintf(stdout, " HTTPS");
  766. }
  767. if (mg_check_feature(4)) {
  768. fprintf(stdout, " CGI");
  769. }
  770. if (mg_check_feature(8)) {
  771. fprintf(stdout, " IPv6");
  772. }
  773. if (mg_check_feature(16)) {
  774. fprintf(stdout, " WebSockets");
  775. }
  776. if (mg_check_feature(32)) {
  777. fprintf(stdout, " Lua");
  778. }
  779. fprintf(stdout, "\n");
  780. #ifdef USE_LUA
  781. fprintf(stdout,
  782. "Lua Version: %u (%s)\n",
  783. (unsigned)LUA_VERSION_NUM,
  784. LUA_RELEASE);
  785. #endif
  786. fprintf(stdout, "Version: %s\n", version);
  787. fprintf(stdout, "Build: %s\n", __DATE__);
  788. /* http://sourceforge.net/p/predef/wiki/Compilers/ */
  789. #if defined(_MSC_VER)
  790. fprintf(stdout,
  791. "MSC: %u (%u)\n",
  792. (unsigned)_MSC_VER,
  793. (unsigned)_MSC_FULL_VER);
  794. #elif defined(__MINGW64__)
  795. fprintf(stdout,
  796. "MinGW64: %u.%u\n",
  797. (unsigned)__MINGW64_VERSION_MAJOR,
  798. (unsigned)__MINGW64_VERSION_MINOR);
  799. fprintf(stdout,
  800. "MinGW32: %u.%u\n",
  801. (unsigned)__MINGW32_MAJOR_VERSION,
  802. (unsigned)__MINGW32_MINOR_VERSION);
  803. #elif defined(__MINGW32__)
  804. fprintf(stdout,
  805. "MinGW32: %u.%u\n",
  806. (unsigned)__MINGW32_MAJOR_VERSION,
  807. (unsigned)__MINGW32_MINOR_VERSION);
  808. #elif defined(__clang__)
  809. fprintf(stdout,
  810. "clang: %u.%u.%u (%s)\n",
  811. __clang_major__,
  812. __clang_minor__,
  813. __clang_patchlevel__,
  814. __clang_version__);
  815. #elif defined(__GNUC__)
  816. fprintf(stdout,
  817. "gcc: %u.%u.%u\n",
  818. (unsigned)__GNUC__,
  819. (unsigned)__GNUC_MINOR__,
  820. (unsigned)__GNUC_PATCHLEVEL__);
  821. #elif defined(__INTEL_COMPILER)
  822. fprintf(stdout, "Intel C/C++: %u\n", (unsigned)__INTEL_COMPILER);
  823. #elif defined(__BORLANDC__)
  824. fprintf(stdout, "Borland C: 0x%x\n", (unsigned)__BORLANDC__);
  825. #elif defined(__SUNPRO_C)
  826. fprintf(stdout, "Solaris: 0x%x\n", (unsigned)__SUNPRO_C);
  827. #else
  828. fprintf(stdout, "Other\n");
  829. #endif
  830. exit(EXIT_SUCCESS);
  831. }
  832. /* Edit passwords file: Add user or change password, if -A option is
  833. * specified */
  834. if (argc > 1 && !strcmp(argv[1], "-A")) {
  835. if (argc != 6) {
  836. show_usage_and_exit(argv[0]);
  837. }
  838. exit(mg_modify_passwords_file(argv[2], argv[3], argv[4], argv[5])
  839. ? EXIT_SUCCESS
  840. : EXIT_FAILURE);
  841. }
  842. /* Edit passwords file: Remove user, if -R option is specified */
  843. if (argc > 1 && !strcmp(argv[1], "-R")) {
  844. if (argc != 5) {
  845. show_usage_and_exit(argv[0]);
  846. }
  847. exit(mg_modify_passwords_file(argv[2], argv[3], argv[4], NULL)
  848. ? EXIT_SUCCESS
  849. : EXIT_FAILURE);
  850. }
  851. /* Call Lua with additional CivetWeb specific Lua functions, if -L option
  852. * is specified */
  853. if (argc > 1 && !strcmp(argv[1], "-L")) {
  854. #ifdef USE_LUA
  855. if (argc != 3) {
  856. show_usage_and_exit(argv[0]);
  857. }
  858. exit(run_lua(argv[2]));
  859. #else
  860. show_server_name();
  861. fprintf(stderr, "\nError: Lua support not enabled\n");
  862. exit(EXIT_FAILURE);
  863. #endif
  864. }
  865. /* Call Duktape, if -E option is specified */
  866. if (argc > 1 && !strcmp(argv[1], "-E")) {
  867. #ifdef USE_DUKTAPE
  868. if (argc != 3) {
  869. show_usage_and_exit(argv[0]);
  870. }
  871. exit(run_duktape(argv[2]));
  872. #else
  873. show_server_name();
  874. fprintf(stderr, "\nError: Ecmascript support not enabled\n");
  875. exit(EXIT_FAILURE);
  876. #endif
  877. }
  878. /* Show usage if -h or --help options are specified */
  879. if (argc == 2 && (!strcmp(argv[1], "-h") || !strcmp(argv[1], "-H")
  880. || !strcmp(argv[1], "--help"))) {
  881. show_usage_and_exit(argv[0]);
  882. }
  883. options[0] = NULL;
  884. set_option(options, "document_root", ".");
  885. /* Update config based on command line arguments */
  886. process_command_line_arguments(argv, options);
  887. /* Make sure we have absolute paths for files and directories */
  888. set_absolute_path(options, "document_root", argv[0]);
  889. set_absolute_path(options, "put_delete_auth_file", argv[0]);
  890. set_absolute_path(options, "cgi_interpreter", argv[0]);
  891. set_absolute_path(options, "access_log_file", argv[0]);
  892. set_absolute_path(options, "error_log_file", argv[0]);
  893. set_absolute_path(options, "global_auth_file", argv[0]);
  894. #ifdef USE_LUA
  895. set_absolute_path(options, "lua_preload_file", argv[0]);
  896. #endif
  897. set_absolute_path(options, "ssl_certificate", argv[0]);
  898. /* Make extra verification for certain options */
  899. verify_existence(options, "document_root", 1);
  900. verify_existence(options, "cgi_interpreter", 0);
  901. verify_existence(options, "ssl_certificate", 0);
  902. verify_existence(options, "ssl_ca_path", 1);
  903. verify_existence(options, "ssl_ca_file", 0);
  904. #ifdef USE_LUA
  905. verify_existence(options, "lua_preload_file", 0);
  906. #endif
  907. /* Setup signal handler: quit on Ctrl-C */
  908. signal(SIGTERM, signal_handler);
  909. signal(SIGINT, signal_handler);
  910. /* Initialize user data */
  911. memset(&g_user_data, 0, sizeof(g_user_data));
  912. /* Start Civetweb */
  913. memset(&callbacks, 0, sizeof(callbacks));
  914. callbacks.log_message = &log_message;
  915. g_ctx = mg_start(&callbacks, &g_user_data, (const char **)options);
  916. for (i = 0; options[i] != NULL; i++) {
  917. free(options[i]);
  918. }
  919. if (g_ctx == NULL) {
  920. die("Failed to start Civetweb:\n%s",
  921. (g_user_data.first_message == NULL) ? "unknown reason"
  922. : g_user_data.first_message);
  923. }
  924. }
  925. static void
  926. stop_civetweb(void)
  927. {
  928. mg_stop(g_ctx);
  929. free(g_user_data.first_message);
  930. g_user_data.first_message = NULL;
  931. }
  932. #ifdef _WIN32
  933. enum {
  934. ID_ICON = 100,
  935. ID_QUIT,
  936. ID_SETTINGS,
  937. ID_SEPARATOR,
  938. ID_INSTALL_SERVICE,
  939. ID_REMOVE_SERVICE,
  940. ID_STATIC,
  941. ID_GROUP,
  942. ID_PASSWORD,
  943. ID_SAVE,
  944. ID_RESET_DEFAULTS,
  945. ID_RESET_FILE,
  946. ID_RESET_ACTIVE,
  947. ID_STATUS,
  948. ID_CONNECT,
  949. ID_ADD_USER,
  950. ID_ADD_USER_NAME,
  951. ID_ADD_USER_REALM,
  952. ID_INPUT_LINE,
  953. /* All dynamically created text boxes for options have IDs starting from
  954. ID_CONTROLS, incremented by one. */
  955. ID_CONTROLS = 200,
  956. /* Text boxes for files have "..." buttons to open file browser. These
  957. buttons have IDs that are ID_FILE_BUTTONS_DELTA higher than associated
  958. text box ID. */
  959. ID_FILE_BUTTONS_DELTA = 1000
  960. };
  961. static HICON hIcon;
  962. static SERVICE_STATUS ss;
  963. static SERVICE_STATUS_HANDLE hStatus;
  964. static const char *service_magic_argument = "--";
  965. static NOTIFYICONDATA TrayIcon;
  966. static void WINAPI
  967. ControlHandler(DWORD code)
  968. {
  969. if (code == SERVICE_CONTROL_STOP || code == SERVICE_CONTROL_SHUTDOWN) {
  970. ss.dwWin32ExitCode = 0;
  971. ss.dwCurrentState = SERVICE_STOPPED;
  972. }
  973. SetServiceStatus(hStatus, &ss);
  974. }
  975. static void WINAPI
  976. ServiceMain(void)
  977. {
  978. ss.dwServiceType = SERVICE_WIN32;
  979. ss.dwCurrentState = SERVICE_RUNNING;
  980. ss.dwControlsAccepted = SERVICE_ACCEPT_STOP | SERVICE_ACCEPT_SHUTDOWN;
  981. hStatus = RegisterServiceCtrlHandler(g_server_name, ControlHandler);
  982. SetServiceStatus(hStatus, &ss);
  983. while (ss.dwCurrentState == SERVICE_RUNNING) {
  984. Sleep(1000);
  985. }
  986. stop_civetweb();
  987. ss.dwCurrentState = SERVICE_STOPPED;
  988. ss.dwWin32ExitCode = (DWORD)-1;
  989. SetServiceStatus(hStatus, &ss);
  990. }
  991. static void
  992. show_error(void)
  993. {
  994. char buf[256];
  995. FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
  996. NULL,
  997. GetLastError(),
  998. MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
  999. buf,
  1000. sizeof(buf),
  1001. NULL);
  1002. MessageBox(NULL, buf, "Error", MB_OK);
  1003. }
  1004. static void *
  1005. align(void *ptr, DWORD alig)
  1006. {
  1007. uintptr_t ul = (uintptr_t)ptr;
  1008. ul += alig;
  1009. ul &= ~alig;
  1010. return ((void *)ul);
  1011. }
  1012. static void
  1013. save_config(HWND hDlg, FILE *fp)
  1014. {
  1015. char value[2000] = "";
  1016. const char *default_value;
  1017. const struct mg_option *options;
  1018. int i, id;
  1019. fprintf(fp, "%s", config_file_top_comment);
  1020. options = mg_get_valid_options();
  1021. for (i = 0; options[i].name != NULL; i++) {
  1022. id = ID_CONTROLS + i;
  1023. if (options[i].type == CONFIG_TYPE_BOOLEAN) {
  1024. snprintf(value,
  1025. sizeof(value) - 1,
  1026. "%s",
  1027. IsDlgButtonChecked(hDlg, id) ? "yes" : "no");
  1028. value[sizeof(value) - 1] = 0;
  1029. } else {
  1030. GetDlgItemText(hDlg, id, value, sizeof(value));
  1031. }
  1032. default_value =
  1033. options[i].default_value == NULL ? "" : options[i].default_value;
  1034. /* If value is the same as default, skip it */
  1035. if (strcmp(value, default_value) != 0) {
  1036. fprintf(fp, "%s %s\n", options[i].name, value);
  1037. }
  1038. }
  1039. }
  1040. static INT_PTR CALLBACK
  1041. SettingsDlgProc(HWND hDlg, UINT msg, WPARAM wParam, LPARAM lParam)
  1042. {
  1043. FILE *fp;
  1044. int i, j;
  1045. const char *name, *value;
  1046. const struct mg_option *default_options = mg_get_valid_options();
  1047. char *file_options[MAX_OPTIONS * 2 + 1] = {0};
  1048. char *title;
  1049. (void)lParam;
  1050. switch (msg) {
  1051. case WM_CLOSE:
  1052. DestroyWindow(hDlg);
  1053. break;
  1054. case WM_COMMAND:
  1055. switch (LOWORD(wParam)) {
  1056. case ID_SAVE:
  1057. EnableWindow(GetDlgItem(hDlg, ID_SAVE), FALSE);
  1058. if ((fp = fopen(g_config_file_name, "w+")) != NULL) {
  1059. save_config(hDlg, fp);
  1060. fclose(fp);
  1061. stop_civetweb();
  1062. start_civetweb(__argc, __argv);
  1063. }
  1064. EnableWindow(GetDlgItem(hDlg, ID_SAVE), TRUE);
  1065. break;
  1066. case ID_RESET_DEFAULTS:
  1067. for (i = 0; default_options[i].name != NULL; i++) {
  1068. name = default_options[i].name;
  1069. value = default_options[i].default_value == NULL
  1070. ? ""
  1071. : default_options[i].default_value;
  1072. if (default_options[i].type == CONFIG_TYPE_BOOLEAN) {
  1073. CheckDlgButton(hDlg,
  1074. ID_CONTROLS + i,
  1075. !strcmp(value, "yes") ? BST_CHECKED
  1076. : BST_UNCHECKED);
  1077. } else {
  1078. SetWindowText(GetDlgItem(hDlg, ID_CONTROLS + i), value);
  1079. }
  1080. }
  1081. break;
  1082. case ID_RESET_FILE:
  1083. read_config_file(g_config_file_name, file_options);
  1084. for (i = 0; default_options[i].name != NULL; i++) {
  1085. name = default_options[i].name;
  1086. value = default_options[i].default_value;
  1087. for (j = 0; file_options[j * 2] != NULL; j++) {
  1088. if (!strcmp(name, file_options[j * 2])) {
  1089. value = file_options[j * 2 + 1];
  1090. }
  1091. }
  1092. if (value == NULL) {
  1093. value = "";
  1094. }
  1095. if (default_options[i].type == CONFIG_TYPE_BOOLEAN) {
  1096. CheckDlgButton(hDlg,
  1097. ID_CONTROLS + i,
  1098. !strcmp(value, "yes") ? BST_CHECKED
  1099. : BST_UNCHECKED);
  1100. } else {
  1101. SetWindowText(GetDlgItem(hDlg, ID_CONTROLS + i), value);
  1102. }
  1103. }
  1104. for (i = 0; i < MAX_OPTIONS; i++) {
  1105. free(file_options[2 * i]);
  1106. free(file_options[2 * i + 1]);
  1107. }
  1108. break;
  1109. case ID_RESET_ACTIVE:
  1110. for (i = 0; default_options[i].name != NULL; i++) {
  1111. name = default_options[i].name;
  1112. value = mg_get_option(g_ctx, name);
  1113. if (default_options[i].type == CONFIG_TYPE_BOOLEAN) {
  1114. CheckDlgButton(hDlg,
  1115. ID_CONTROLS + i,
  1116. !strcmp(value, "yes") ? BST_CHECKED
  1117. : BST_UNCHECKED);
  1118. } else {
  1119. SetDlgItemText(hDlg,
  1120. ID_CONTROLS + i,
  1121. value == NULL ? "" : value);
  1122. }
  1123. }
  1124. break;
  1125. }
  1126. for (i = 0; default_options[i].name != NULL; i++) {
  1127. name = default_options[i].name;
  1128. if (((default_options[i].type == CONFIG_TYPE_FILE)
  1129. || (default_options[i].type == CONFIG_TYPE_DIRECTORY))
  1130. && LOWORD(wParam) == ID_CONTROLS + i + ID_FILE_BUTTONS_DELTA) {
  1131. OPENFILENAME of;
  1132. BROWSEINFO bi;
  1133. char path[PATH_MAX] = "";
  1134. memset(&of, 0, sizeof(of));
  1135. of.lStructSize = sizeof(of);
  1136. of.hwndOwner = (HWND)hDlg;
  1137. of.lpstrFile = path;
  1138. of.nMaxFile = sizeof(path);
  1139. of.lpstrInitialDir = mg_get_option(g_ctx, "document_root");
  1140. of.Flags =
  1141. OFN_CREATEPROMPT | OFN_NOCHANGEDIR | OFN_HIDEREADONLY;
  1142. memset(&bi, 0, sizeof(bi));
  1143. bi.hwndOwner = (HWND)hDlg;
  1144. bi.lpszTitle = "Choose WWW root directory:";
  1145. bi.ulFlags = BIF_RETURNONLYFSDIRS;
  1146. if (default_options[i].type == CONFIG_TYPE_DIRECTORY) {
  1147. SHGetPathFromIDList(SHBrowseForFolder(&bi), path);
  1148. } else {
  1149. GetOpenFileName(&of);
  1150. }
  1151. if (path[0] != '\0') {
  1152. SetWindowText(GetDlgItem(hDlg, ID_CONTROLS + i), path);
  1153. }
  1154. }
  1155. }
  1156. break;
  1157. case WM_INITDIALOG:
  1158. SendMessage(hDlg, WM_SETICON, (WPARAM)ICON_SMALL, (LPARAM)hIcon);
  1159. SendMessage(hDlg, WM_SETICON, (WPARAM)ICON_BIG, (LPARAM)hIcon);
  1160. title = malloc(strlen(g_server_name) + 16);
  1161. if (title) {
  1162. strcpy(title, g_server_name);
  1163. strcat(title, " settings");
  1164. SetWindowText(hDlg, title);
  1165. free(title);
  1166. }
  1167. SetFocus(GetDlgItem(hDlg, ID_SAVE));
  1168. /* Init dialog with active settings */
  1169. SendMessage(hDlg, WM_COMMAND, ID_RESET_ACTIVE, 0);
  1170. /* alternative: SendMessage(hDlg, WM_COMMAND, ID_RESET_FILE, 0); */
  1171. break;
  1172. default:
  1173. break;
  1174. }
  1175. return FALSE;
  1176. }
  1177. struct tstring_input_buf {
  1178. unsigned buflen;
  1179. char *buffer;
  1180. };
  1181. static INT_PTR CALLBACK
  1182. InputDlgProc(HWND hDlg, UINT msg, WPARAM wParam, LPARAM lP)
  1183. {
  1184. static struct tstring_input_buf *inBuf = 0;
  1185. WORD ctrlId;
  1186. switch (msg) {
  1187. case WM_CLOSE:
  1188. inBuf = 0;
  1189. DestroyWindow(hDlg);
  1190. break;
  1191. case WM_COMMAND:
  1192. ctrlId = LOWORD(wParam);
  1193. if (ctrlId == IDOK) {
  1194. /* Add user */
  1195. GetWindowText(GetDlgItem(hDlg, ID_INPUT_LINE),
  1196. inBuf->buffer,
  1197. (int)inBuf->buflen);
  1198. if (strlen(inBuf->buffer) > 0) {
  1199. EndDialog(hDlg, IDOK);
  1200. }
  1201. } else if (ctrlId == IDCANCEL) {
  1202. EndDialog(hDlg, IDCANCEL);
  1203. }
  1204. break;
  1205. case WM_INITDIALOG:
  1206. inBuf = (struct tstring_input_buf *)lP;
  1207. assert(inBuf != NULL);
  1208. assert((inBuf->buffer != NULL) && (inBuf->buflen != 0));
  1209. assert(strlen(inBuf->buffer) < inBuf->buflen);
  1210. SendMessage(hDlg, WM_SETICON, (WPARAM)ICON_SMALL, (LPARAM)hIcon);
  1211. SendMessage(hDlg, WM_SETICON, (WPARAM)ICON_BIG, (LPARAM)hIcon);
  1212. SendDlgItemMessage(
  1213. hDlg, ID_INPUT_LINE, EM_LIMITTEXT, inBuf->buflen - 1, 0);
  1214. SetWindowText(GetDlgItem(hDlg, ID_INPUT_LINE), inBuf->buffer);
  1215. SetWindowText(hDlg, "Modify password");
  1216. SetFocus(GetDlgItem(hDlg, ID_INPUT_LINE));
  1217. break;
  1218. default:
  1219. break;
  1220. }
  1221. return FALSE;
  1222. }
  1223. static void
  1224. suggest_passwd(char *passwd)
  1225. {
  1226. unsigned u;
  1227. char *p;
  1228. union {
  1229. FILETIME ft;
  1230. LARGE_INTEGER li;
  1231. } num;
  1232. /* valid characters are 32 to 126 */
  1233. GetSystemTimeAsFileTime(&num.ft);
  1234. num.li.HighPart |= (LONG)GetCurrentProcessId();
  1235. p = passwd;
  1236. while (num.li.QuadPart) {
  1237. u = (unsigned)(num.li.QuadPart % 95);
  1238. num.li.QuadPart -= u;
  1239. num.li.QuadPart /= 95;
  1240. *p = (char)(u + 32);
  1241. p++;
  1242. }
  1243. }
  1244. static void add_control(unsigned char **mem,
  1245. DLGTEMPLATE *dia,
  1246. WORD type,
  1247. WORD id,
  1248. DWORD style,
  1249. short x,
  1250. short y,
  1251. short cx,
  1252. short cy,
  1253. const char *caption);
  1254. static int
  1255. get_password(const char *user,
  1256. const char *realm,
  1257. char *passwd,
  1258. unsigned passwd_len)
  1259. {
  1260. #define HEIGHT (15)
  1261. #define WIDTH (280)
  1262. #define LABEL_WIDTH (90)
  1263. unsigned char mem[4096], *p;
  1264. DLGTEMPLATE *dia = (DLGTEMPLATE *)mem;
  1265. int ok;
  1266. short y;
  1267. struct tstring_input_buf dlgprms;
  1268. static struct {
  1269. DLGTEMPLATE template; /* 18 bytes */
  1270. WORD menu, class;
  1271. wchar_t caption[1];
  1272. WORD fontsiz;
  1273. wchar_t fontface[7];
  1274. } dialog_header = {{WS_CAPTION | WS_POPUP | WS_SYSMENU | WS_VISIBLE
  1275. | DS_SETFONT | WS_DLGFRAME,
  1276. WS_EX_TOOLWINDOW,
  1277. 0,
  1278. 200,
  1279. 200,
  1280. WIDTH,
  1281. 0},
  1282. 0,
  1283. 0,
  1284. L"",
  1285. 8,
  1286. L"Tahoma"};
  1287. dlgprms.buffer = passwd;
  1288. dlgprms.buflen = passwd_len;
  1289. assert((user != NULL) && (realm != NULL) && (passwd != NULL));
  1290. if (guard < 100) {
  1291. guard += 100;
  1292. } else {
  1293. return 0;
  1294. }
  1295. /* Create a password suggestion */
  1296. memset(passwd, 0, passwd_len);
  1297. suggest_passwd(passwd);
  1298. /* Create the dialog */
  1299. (void)memset(mem, 0, sizeof(mem));
  1300. (void)memcpy(mem, &dialog_header, sizeof(dialog_header));
  1301. p = mem + sizeof(dialog_header);
  1302. y = HEIGHT;
  1303. add_control(&p,
  1304. dia,
  1305. 0x82,
  1306. ID_STATIC,
  1307. WS_VISIBLE | WS_CHILD,
  1308. 10,
  1309. y,
  1310. LABEL_WIDTH,
  1311. HEIGHT,
  1312. "User:");
  1313. add_control(&p,
  1314. dia,
  1315. 0x81,
  1316. ID_CONTROLS + 1,
  1317. WS_CHILD | WS_VISIBLE | WS_BORDER | ES_AUTOHSCROLL
  1318. | WS_DISABLED,
  1319. 15 + LABEL_WIDTH,
  1320. y,
  1321. WIDTH - LABEL_WIDTH - 25,
  1322. HEIGHT,
  1323. user);
  1324. y += HEIGHT;
  1325. add_control(&p,
  1326. dia,
  1327. 0x82,
  1328. ID_STATIC,
  1329. WS_VISIBLE | WS_CHILD,
  1330. 10,
  1331. y,
  1332. LABEL_WIDTH,
  1333. HEIGHT,
  1334. "Realm:");
  1335. add_control(&p,
  1336. dia,
  1337. 0x81,
  1338. ID_CONTROLS + 2,
  1339. WS_CHILD | WS_VISIBLE | WS_BORDER | ES_AUTOHSCROLL
  1340. | WS_DISABLED,
  1341. 15 + LABEL_WIDTH,
  1342. y,
  1343. WIDTH - LABEL_WIDTH - 25,
  1344. HEIGHT,
  1345. realm);
  1346. y += HEIGHT;
  1347. add_control(&p,
  1348. dia,
  1349. 0x82,
  1350. ID_STATIC,
  1351. WS_VISIBLE | WS_CHILD,
  1352. 10,
  1353. y,
  1354. LABEL_WIDTH,
  1355. HEIGHT,
  1356. "Password:");
  1357. add_control(&p,
  1358. dia,
  1359. 0x81,
  1360. ID_INPUT_LINE,
  1361. WS_CHILD | WS_VISIBLE | WS_BORDER | ES_AUTOHSCROLL | WS_TABSTOP,
  1362. 15 + LABEL_WIDTH,
  1363. y,
  1364. WIDTH - LABEL_WIDTH - 25,
  1365. HEIGHT,
  1366. "");
  1367. y += (WORD)(HEIGHT * 2);
  1368. add_control(&p,
  1369. dia,
  1370. 0x80,
  1371. IDOK,
  1372. WS_CHILD | WS_VISIBLE | BS_PUSHBUTTON | WS_TABSTOP,
  1373. 80,
  1374. y,
  1375. 55,
  1376. 12,
  1377. "Ok");
  1378. add_control(&p,
  1379. dia,
  1380. 0x80,
  1381. IDCANCEL,
  1382. WS_CHILD | WS_VISIBLE | BS_PUSHBUTTON | WS_TABSTOP,
  1383. 140,
  1384. y,
  1385. 55,
  1386. 12,
  1387. "Cancel");
  1388. assert((intptr_t)p - (intptr_t)mem < (intptr_t)sizeof(mem));
  1389. dia->cy = y + (WORD)(HEIGHT * 1.5);
  1390. ok = (IDOK == DialogBoxIndirectParam(
  1391. NULL, dia, NULL, InputDlgProc, (LPARAM)&dlgprms));
  1392. guard -= 100;
  1393. return ok;
  1394. #undef HEIGHT
  1395. #undef WIDTH
  1396. #undef LABEL_WIDTH
  1397. }
  1398. static INT_PTR CALLBACK
  1399. PasswordDlgProc(HWND hDlg, UINT msg, WPARAM wParam, LPARAM lP)
  1400. {
  1401. static const char *passfile = 0;
  1402. char domain[256], user[256], password[256];
  1403. WORD ctrlId;
  1404. switch (msg) {
  1405. case WM_CLOSE:
  1406. passfile = 0;
  1407. DestroyWindow(hDlg);
  1408. break;
  1409. case WM_COMMAND:
  1410. ctrlId = LOWORD(wParam);
  1411. if (ctrlId == ID_ADD_USER) {
  1412. /* Add user */
  1413. GetWindowText(GetDlgItem(hDlg, ID_ADD_USER_NAME),
  1414. user,
  1415. sizeof(user));
  1416. GetWindowText(GetDlgItem(hDlg, ID_ADD_USER_REALM),
  1417. domain,
  1418. sizeof(domain));
  1419. if (get_password(user, domain, password, sizeof(password))) {
  1420. mg_modify_passwords_file(passfile, domain, user, password);
  1421. EndDialog(hDlg, IDOK);
  1422. }
  1423. } else if ((ctrlId >= (ID_CONTROLS + ID_FILE_BUTTONS_DELTA * 3))
  1424. && (ctrlId < (ID_CONTROLS + ID_FILE_BUTTONS_DELTA * 4))) {
  1425. /* Modify password */
  1426. GetWindowText(GetDlgItem(hDlg, ctrlId - ID_FILE_BUTTONS_DELTA * 3),
  1427. user,
  1428. sizeof(user));
  1429. GetWindowText(GetDlgItem(hDlg, ctrlId - ID_FILE_BUTTONS_DELTA * 2),
  1430. domain,
  1431. sizeof(domain));
  1432. if (get_password(user, domain, password, sizeof(password))) {
  1433. mg_modify_passwords_file(passfile, domain, user, password);
  1434. EndDialog(hDlg, IDOK);
  1435. }
  1436. } else if ((ctrlId >= (ID_CONTROLS + ID_FILE_BUTTONS_DELTA * 2))
  1437. && (ctrlId < (ID_CONTROLS + ID_FILE_BUTTONS_DELTA * 3))) {
  1438. /* Remove user */
  1439. GetWindowText(GetDlgItem(hDlg, ctrlId - ID_FILE_BUTTONS_DELTA * 2),
  1440. user,
  1441. sizeof(user));
  1442. GetWindowText(GetDlgItem(hDlg, ctrlId - ID_FILE_BUTTONS_DELTA),
  1443. domain,
  1444. sizeof(domain));
  1445. mg_modify_passwords_file(passfile, domain, user, NULL);
  1446. EndDialog(hDlg, IDOK);
  1447. }
  1448. break;
  1449. case WM_INITDIALOG:
  1450. passfile = (const char *)lP;
  1451. SendMessage(hDlg, WM_SETICON, (WPARAM)ICON_SMALL, (LPARAM)hIcon);
  1452. SendMessage(hDlg, WM_SETICON, (WPARAM)ICON_BIG, (LPARAM)hIcon);
  1453. SetWindowText(hDlg, passfile);
  1454. SetFocus(GetDlgItem(hDlg, ID_ADD_USER_NAME));
  1455. break;
  1456. default:
  1457. break;
  1458. }
  1459. return FALSE;
  1460. }
  1461. static void
  1462. add_control(unsigned char **mem,
  1463. DLGTEMPLATE *dia,
  1464. WORD type,
  1465. WORD id,
  1466. DWORD style,
  1467. short x,
  1468. short y,
  1469. short cx,
  1470. short cy,
  1471. const char *caption)
  1472. {
  1473. DLGITEMTEMPLATE *tp;
  1474. LPWORD p;
  1475. dia->cdit++;
  1476. *mem = align(*mem, 3);
  1477. tp = (DLGITEMTEMPLATE *)*mem;
  1478. tp->id = id;
  1479. tp->style = style;
  1480. tp->dwExtendedStyle = 0;
  1481. tp->x = x;
  1482. tp->y = y;
  1483. tp->cx = cx;
  1484. tp->cy = cy;
  1485. p = align(*mem + sizeof(*tp), 1);
  1486. *p++ = 0xffff;
  1487. *p++ = type;
  1488. while (*caption != '\0') {
  1489. *p++ = (WCHAR)*caption++;
  1490. }
  1491. *p++ = 0;
  1492. p = align(p, 1);
  1493. *p++ = 0;
  1494. *mem = (unsigned char *)p;
  1495. }
  1496. static void
  1497. show_settings_dialog()
  1498. {
  1499. #define HEIGHT (15)
  1500. #define WIDTH (460)
  1501. #define LABEL_WIDTH (90)
  1502. unsigned char mem[8192], *p;
  1503. const struct mg_option *options;
  1504. DWORD style;
  1505. DLGTEMPLATE *dia = (DLGTEMPLATE *)mem;
  1506. WORD i, cl, nelems = 0;
  1507. short width, x, y;
  1508. static struct {
  1509. DLGTEMPLATE template; /* 18 bytes */
  1510. WORD menu, class;
  1511. wchar_t caption[1];
  1512. WORD fontsiz;
  1513. wchar_t fontface[7];
  1514. } dialog_header = {{WS_CAPTION | WS_POPUP | WS_SYSMENU | WS_VISIBLE
  1515. | DS_SETFONT | WS_DLGFRAME,
  1516. WS_EX_TOOLWINDOW,
  1517. 0,
  1518. 200,
  1519. 200,
  1520. WIDTH,
  1521. 0},
  1522. 0,
  1523. 0,
  1524. L"",
  1525. 8,
  1526. L"Tahoma"};
  1527. if (guard == 0) {
  1528. guard++;
  1529. } else {
  1530. return;
  1531. }
  1532. (void)memset(mem, 0, sizeof(mem));
  1533. (void)memcpy(mem, &dialog_header, sizeof(dialog_header));
  1534. p = mem + sizeof(dialog_header);
  1535. options = mg_get_valid_options();
  1536. for (i = 0; options[i].name != NULL; i++) {
  1537. style = WS_CHILD | WS_VISIBLE | WS_TABSTOP;
  1538. x = 10 + (WIDTH / 2) * (nelems % 2);
  1539. y = (nelems / 2 + 1) * HEIGHT + 5;
  1540. width = WIDTH / 2 - 20 - LABEL_WIDTH;
  1541. if (options[i].type == CONFIG_TYPE_NUMBER) {
  1542. style |= ES_NUMBER;
  1543. cl = 0x81;
  1544. style |= WS_BORDER | ES_AUTOHSCROLL;
  1545. } else if (options[i].type == CONFIG_TYPE_BOOLEAN) {
  1546. cl = 0x80;
  1547. style |= BS_AUTOCHECKBOX;
  1548. } else if ((options[i].type == CONFIG_TYPE_FILE)
  1549. || (options[i].type == CONFIG_TYPE_DIRECTORY)) {
  1550. style |= WS_BORDER | ES_AUTOHSCROLL;
  1551. width -= 20;
  1552. cl = 0x81;
  1553. add_control(&p,
  1554. dia,
  1555. 0x80,
  1556. ID_CONTROLS + i + ID_FILE_BUTTONS_DELTA,
  1557. WS_VISIBLE | WS_CHILD | BS_PUSHBUTTON,
  1558. x + width + LABEL_WIDTH + 5,
  1559. y,
  1560. 15,
  1561. 12,
  1562. "...");
  1563. } else {
  1564. cl = 0x81;
  1565. style |= WS_BORDER | ES_AUTOHSCROLL;
  1566. }
  1567. add_control(&p,
  1568. dia,
  1569. 0x82,
  1570. ID_STATIC,
  1571. WS_VISIBLE | WS_CHILD,
  1572. x,
  1573. y,
  1574. LABEL_WIDTH,
  1575. HEIGHT,
  1576. options[i].name);
  1577. add_control(&p,
  1578. dia,
  1579. cl,
  1580. ID_CONTROLS + i,
  1581. style,
  1582. x + LABEL_WIDTH,
  1583. y,
  1584. width,
  1585. 12,
  1586. "");
  1587. nelems++;
  1588. assert(((intptr_t)p - (intptr_t)mem) < (intptr_t)sizeof(mem));
  1589. }
  1590. y = (((nelems + 1) / 2 + 1) * HEIGHT + 5);
  1591. add_control(&p,
  1592. dia,
  1593. 0x80,
  1594. ID_GROUP,
  1595. WS_CHILD | WS_VISIBLE | BS_GROUPBOX,
  1596. 5,
  1597. 5,
  1598. WIDTH - 10,
  1599. y,
  1600. " Settings ");
  1601. y += 10;
  1602. add_control(&p,
  1603. dia,
  1604. 0x80,
  1605. ID_SAVE,
  1606. WS_CHILD | WS_VISIBLE | BS_PUSHBUTTON | WS_TABSTOP,
  1607. WIDTH - 70,
  1608. y,
  1609. 65,
  1610. 12,
  1611. "Save Settings");
  1612. add_control(&p,
  1613. dia,
  1614. 0x80,
  1615. ID_RESET_DEFAULTS,
  1616. WS_CHILD | WS_VISIBLE | BS_PUSHBUTTON | WS_TABSTOP,
  1617. WIDTH - 140,
  1618. y,
  1619. 65,
  1620. 12,
  1621. "Reset to defaults");
  1622. add_control(&p,
  1623. dia,
  1624. 0x80,
  1625. ID_RESET_FILE,
  1626. WS_CHILD | WS_VISIBLE | BS_PUSHBUTTON | WS_TABSTOP,
  1627. WIDTH - 210,
  1628. y,
  1629. 65,
  1630. 12,
  1631. "Reload from file");
  1632. add_control(&p,
  1633. dia,
  1634. 0x80,
  1635. ID_RESET_ACTIVE,
  1636. WS_CHILD | WS_VISIBLE | BS_PUSHBUTTON | WS_TABSTOP,
  1637. WIDTH - 280,
  1638. y,
  1639. 65,
  1640. 12,
  1641. "Reload active");
  1642. add_control(&p,
  1643. dia,
  1644. 0x82,
  1645. ID_STATIC,
  1646. WS_CHILD | WS_VISIBLE | WS_DISABLED,
  1647. 5,
  1648. y,
  1649. 100,
  1650. 12,
  1651. g_server_base_name);
  1652. assert(((intptr_t)p - (intptr_t)mem) < (intptr_t)sizeof(mem));
  1653. dia->cy = ((nelems + 1) / 2 + 1) * HEIGHT + 30;
  1654. DialogBoxIndirectParam(NULL, dia, NULL, SettingsDlgProc, (LPARAM)NULL);
  1655. guard--;
  1656. #undef HEIGHT
  1657. #undef WIDTH
  1658. #undef LABEL_WIDTH
  1659. }
  1660. static void
  1661. change_password_file()
  1662. {
  1663. #define HEIGHT (15)
  1664. #define WIDTH (320)
  1665. #define LABEL_WIDTH (90)
  1666. OPENFILENAME of;
  1667. char path[PATH_MAX] = PASSWORDS_FILE_NAME;
  1668. char strbuf[256], u[256], d[256];
  1669. HWND hDlg = NULL;
  1670. FILE *f;
  1671. short y, nelems;
  1672. unsigned char mem[4096], *p;
  1673. DLGTEMPLATE *dia = (DLGTEMPLATE *)mem;
  1674. const char *domain = mg_get_option(g_ctx, "authentication_domain");
  1675. static struct {
  1676. DLGTEMPLATE template; /* 18 bytes */
  1677. WORD menu, class;
  1678. wchar_t caption[1];
  1679. WORD fontsiz;
  1680. wchar_t fontface[7];
  1681. } dialog_header = {{WS_CAPTION | WS_POPUP | WS_SYSMENU | WS_VISIBLE
  1682. | DS_SETFONT | WS_DLGFRAME,
  1683. WS_EX_TOOLWINDOW,
  1684. 0,
  1685. 200,
  1686. 200,
  1687. WIDTH,
  1688. 0},
  1689. 0,
  1690. 0,
  1691. L"",
  1692. 8,
  1693. L"Tahoma"};
  1694. if (guard == 0) {
  1695. guard++;
  1696. } else {
  1697. return;
  1698. }
  1699. memset(&of, 0, sizeof(of));
  1700. of.lStructSize = sizeof(of);
  1701. of.hwndOwner = (HWND)hDlg;
  1702. of.lpstrFile = path;
  1703. of.nMaxFile = sizeof(path);
  1704. of.lpstrInitialDir = mg_get_option(g_ctx, "document_root");
  1705. of.Flags = OFN_CREATEPROMPT | OFN_NOCHANGEDIR | OFN_HIDEREADONLY;
  1706. if (IDOK != GetSaveFileName(&of)) {
  1707. guard--;
  1708. return;
  1709. }
  1710. f = fopen(path, "a+");
  1711. if (f) {
  1712. fclose(f);
  1713. } else {
  1714. MessageBox(NULL, path, "Can not open file", MB_ICONERROR);
  1715. guard--;
  1716. return;
  1717. }
  1718. do {
  1719. (void)memset(mem, 0, sizeof(mem));
  1720. (void)memcpy(mem, &dialog_header, sizeof(dialog_header));
  1721. p = mem + sizeof(dialog_header);
  1722. f = fopen(path, "r+");
  1723. if (!f) {
  1724. MessageBox(NULL, path, "Can not open file", MB_ICONERROR);
  1725. guard--;
  1726. return;
  1727. }
  1728. nelems = 0;
  1729. while (fgets(strbuf, sizeof(strbuf), f)) {
  1730. if (sscanf(strbuf, "%255[^:]:%255[^:]:%*s", u, d) != 2) {
  1731. continue;
  1732. }
  1733. u[255] = 0;
  1734. d[255] = 0;
  1735. y = (nelems + 1) * HEIGHT + 5;
  1736. add_control(&p,
  1737. dia,
  1738. 0x80,
  1739. ID_CONTROLS + nelems + ID_FILE_BUTTONS_DELTA * 3,
  1740. WS_CHILD | WS_VISIBLE | BS_PUSHBUTTON | WS_TABSTOP,
  1741. 10,
  1742. y,
  1743. 65,
  1744. 12,
  1745. "Modify password");
  1746. add_control(&p,
  1747. dia,
  1748. 0x80,
  1749. ID_CONTROLS + nelems + ID_FILE_BUTTONS_DELTA * 2,
  1750. WS_CHILD | WS_VISIBLE | BS_PUSHBUTTON | WS_TABSTOP,
  1751. 80,
  1752. y,
  1753. 55,
  1754. 12,
  1755. "Remove user");
  1756. add_control(&p,
  1757. dia,
  1758. 0x81,
  1759. ID_CONTROLS + nelems + ID_FILE_BUTTONS_DELTA,
  1760. WS_CHILD | WS_VISIBLE | WS_BORDER | ES_AUTOHSCROLL
  1761. | WS_DISABLED,
  1762. 245,
  1763. y,
  1764. 60,
  1765. 12,
  1766. d);
  1767. add_control(&p,
  1768. dia,
  1769. 0x81,
  1770. ID_CONTROLS + nelems,
  1771. WS_CHILD | WS_VISIBLE | WS_BORDER | ES_AUTOHSCROLL
  1772. | WS_DISABLED,
  1773. 140,
  1774. y,
  1775. 100,
  1776. 12,
  1777. u);
  1778. nelems++;
  1779. assert(((intptr_t)p - (intptr_t)mem) < (intptr_t)sizeof(mem));
  1780. }
  1781. fclose(f);
  1782. y = (nelems + 1) * HEIGHT + 10;
  1783. add_control(&p,
  1784. dia,
  1785. 0x80,
  1786. ID_ADD_USER,
  1787. WS_CHILD | WS_VISIBLE | BS_PUSHBUTTON | WS_TABSTOP,
  1788. 80,
  1789. y,
  1790. 55,
  1791. 12,
  1792. "Add user");
  1793. add_control(&p,
  1794. dia,
  1795. 0x81,
  1796. ID_ADD_USER_NAME,
  1797. WS_CHILD | WS_VISIBLE | WS_BORDER | ES_AUTOHSCROLL
  1798. | WS_TABSTOP,
  1799. 140,
  1800. y,
  1801. 100,
  1802. 12,
  1803. "");
  1804. add_control(&p,
  1805. dia,
  1806. 0x81,
  1807. ID_ADD_USER_REALM,
  1808. WS_CHILD | WS_VISIBLE | WS_BORDER | ES_AUTOHSCROLL
  1809. | WS_TABSTOP,
  1810. 245,
  1811. y,
  1812. 60,
  1813. 12,
  1814. domain);
  1815. y = (nelems + 2) * HEIGHT + 10;
  1816. add_control(&p,
  1817. dia,
  1818. 0x80,
  1819. ID_GROUP,
  1820. WS_CHILD | WS_VISIBLE | BS_GROUPBOX,
  1821. 5,
  1822. 5,
  1823. WIDTH - 10,
  1824. y,
  1825. " Users ");
  1826. y += HEIGHT;
  1827. add_control(&p,
  1828. dia,
  1829. 0x82,
  1830. ID_STATIC,
  1831. WS_CHILD | WS_VISIBLE | WS_DISABLED,
  1832. 5,
  1833. y,
  1834. 100,
  1835. 12,
  1836. g_server_base_name);
  1837. assert(((intptr_t)p - (intptr_t)mem) < (intptr_t)sizeof(mem));
  1838. dia->cy = y + 20;
  1839. } while ((IDOK == DialogBoxIndirectParam(
  1840. NULL, dia, NULL, PasswordDlgProc, (LPARAM)path))
  1841. && (!g_exit_flag));
  1842. guard--;
  1843. #undef HEIGHT
  1844. #undef WIDTH
  1845. #undef LABEL_WIDTH
  1846. }
  1847. static int
  1848. manage_service(int action)
  1849. {
  1850. const char *service_name = g_server_name;
  1851. SC_HANDLE hSCM = NULL, hService = NULL;
  1852. SERVICE_DESCRIPTION descr;
  1853. char path[PATH_MAX + 20] = ""; /* Path to executable plus magic argument */
  1854. int success = 1;
  1855. descr.lpDescription = g_server_name;
  1856. if ((hSCM = OpenSCManager(NULL,
  1857. NULL,
  1858. action == ID_INSTALL_SERVICE ? GENERIC_WRITE
  1859. : GENERIC_READ))
  1860. == NULL) {
  1861. success = 0;
  1862. show_error();
  1863. } else if (action == ID_INSTALL_SERVICE) {
  1864. path[sizeof(path) - 1] = 0;
  1865. GetModuleFileName(NULL, path, sizeof(path) - 1);
  1866. strncat(path, " ", sizeof(path) - 1);
  1867. strncat(path, service_magic_argument, sizeof(path) - 1);
  1868. hService = CreateService(hSCM,
  1869. service_name,
  1870. service_name,
  1871. SERVICE_ALL_ACCESS,
  1872. SERVICE_WIN32_OWN_PROCESS,
  1873. SERVICE_AUTO_START,
  1874. SERVICE_ERROR_NORMAL,
  1875. path,
  1876. NULL,
  1877. NULL,
  1878. NULL,
  1879. NULL,
  1880. NULL);
  1881. if (hService) {
  1882. ChangeServiceConfig2(hService, SERVICE_CONFIG_DESCRIPTION, &descr);
  1883. } else {
  1884. show_error();
  1885. }
  1886. } else if (action == ID_REMOVE_SERVICE) {
  1887. if ((hService = OpenService(hSCM, service_name, DELETE)) == NULL
  1888. || !DeleteService(hService)) {
  1889. show_error();
  1890. }
  1891. } else if ((hService =
  1892. OpenService(hSCM, service_name, SERVICE_QUERY_STATUS))
  1893. == NULL) {
  1894. success = 0;
  1895. }
  1896. if (hService)
  1897. CloseServiceHandle(hService);
  1898. if (hSCM)
  1899. CloseServiceHandle(hSCM);
  1900. return success;
  1901. }
  1902. static LRESULT CALLBACK
  1903. WindowProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam)
  1904. {
  1905. static SERVICE_TABLE_ENTRY service_table[2];
  1906. int service_installed;
  1907. char buf[200], *service_argv[2];
  1908. POINT pt;
  1909. HMENU hMenu;
  1910. static UINT s_uTaskbarRestart; /* for taskbar creation */
  1911. service_argv[0] = __argv[0];
  1912. service_argv[1] = NULL;
  1913. memset(service_table, 0, sizeof(service_table));
  1914. service_table[0].lpServiceName = g_server_name;
  1915. service_table[0].lpServiceProc = (LPSERVICE_MAIN_FUNCTION)ServiceMain;
  1916. switch (msg) {
  1917. case WM_CREATE:
  1918. if (__argv[1] != NULL && !strcmp(__argv[1], service_magic_argument)) {
  1919. start_civetweb(1, service_argv);
  1920. StartServiceCtrlDispatcher(service_table);
  1921. exit(EXIT_SUCCESS);
  1922. } else {
  1923. start_civetweb(__argc, __argv);
  1924. s_uTaskbarRestart = RegisterWindowMessage(TEXT("TaskbarCreated"));
  1925. }
  1926. break;
  1927. case WM_COMMAND:
  1928. switch (LOWORD(wParam)) {
  1929. case ID_QUIT:
  1930. stop_civetweb();
  1931. Shell_NotifyIcon(NIM_DELETE, &TrayIcon);
  1932. g_exit_flag = 1;
  1933. PostQuitMessage(0);
  1934. return 0;
  1935. case ID_SETTINGS:
  1936. show_settings_dialog();
  1937. break;
  1938. case ID_PASSWORD:
  1939. change_password_file();
  1940. break;
  1941. case ID_INSTALL_SERVICE:
  1942. case ID_REMOVE_SERVICE:
  1943. manage_service(LOWORD(wParam));
  1944. break;
  1945. case ID_CONNECT:
  1946. fprintf(stdout, "[%s]\n", get_url_to_first_open_port(g_ctx));
  1947. ShellExecute(NULL,
  1948. "open",
  1949. get_url_to_first_open_port(g_ctx),
  1950. NULL,
  1951. NULL,
  1952. SW_SHOW);
  1953. break;
  1954. }
  1955. break;
  1956. case WM_USER:
  1957. switch (lParam) {
  1958. case WM_RBUTTONUP:
  1959. case WM_LBUTTONUP:
  1960. case WM_LBUTTONDBLCLK:
  1961. hMenu = CreatePopupMenu();
  1962. AppendMenu(hMenu,
  1963. MF_STRING | MF_GRAYED,
  1964. ID_SEPARATOR,
  1965. g_server_name);
  1966. AppendMenu(hMenu, MF_SEPARATOR, ID_SEPARATOR, "");
  1967. service_installed = manage_service(0);
  1968. snprintf(buf,
  1969. sizeof(buf) - 1,
  1970. "NT service: %s installed",
  1971. service_installed ? "" : "not");
  1972. buf[sizeof(buf) - 1] = 0;
  1973. AppendMenu(hMenu, MF_STRING | MF_GRAYED, ID_SEPARATOR, buf);
  1974. AppendMenu(hMenu,
  1975. MF_STRING | (service_installed ? MF_GRAYED : 0),
  1976. ID_INSTALL_SERVICE,
  1977. "Install service");
  1978. AppendMenu(hMenu,
  1979. MF_STRING | (!service_installed ? MF_GRAYED : 0),
  1980. ID_REMOVE_SERVICE,
  1981. "Deinstall service");
  1982. AppendMenu(hMenu, MF_SEPARATOR, ID_SEPARATOR, "");
  1983. AppendMenu(hMenu, MF_STRING, ID_CONNECT, "Start browser");
  1984. AppendMenu(hMenu, MF_STRING, ID_SETTINGS, "Edit settings");
  1985. AppendMenu(hMenu, MF_STRING, ID_PASSWORD, "Modify password file");
  1986. AppendMenu(hMenu, MF_SEPARATOR, ID_SEPARATOR, "");
  1987. AppendMenu(hMenu, MF_STRING, ID_QUIT, "Exit");
  1988. GetCursorPos(&pt);
  1989. SetForegroundWindow(hWnd);
  1990. TrackPopupMenu(hMenu, 0, pt.x, pt.y, 0, hWnd, NULL);
  1991. PostMessage(hWnd, WM_NULL, 0, 0);
  1992. DestroyMenu(hMenu);
  1993. break;
  1994. }
  1995. break;
  1996. case WM_CLOSE:
  1997. stop_civetweb();
  1998. Shell_NotifyIcon(NIM_DELETE, &TrayIcon);
  1999. g_exit_flag = 1;
  2000. PostQuitMessage(0);
  2001. return 0; /* We've just sent our own quit message, with proper hwnd. */
  2002. default:
  2003. if (msg == s_uTaskbarRestart)
  2004. Shell_NotifyIcon(NIM_ADD, &TrayIcon);
  2005. }
  2006. return DefWindowProc(hWnd, msg, wParam, lParam);
  2007. }
  2008. static int
  2009. MakeConsole(void)
  2010. {
  2011. DWORD err;
  2012. int ok = (GetConsoleWindow() != NULL);
  2013. if (!ok) {
  2014. if (!AttachConsole(ATTACH_PARENT_PROCESS)) {
  2015. FreeConsole();
  2016. if (!AllocConsole()) {
  2017. err = GetLastError();
  2018. if (err == ERROR_ACCESS_DENIED) {
  2019. MessageBox(NULL,
  2020. "Insufficient rights to create a console window",
  2021. "Error",
  2022. MB_ICONERROR);
  2023. }
  2024. }
  2025. AttachConsole(GetCurrentProcessId());
  2026. }
  2027. ok = (GetConsoleWindow() != NULL);
  2028. if (ok) {
  2029. freopen("CONIN$", "r", stdin);
  2030. freopen("CONOUT$", "w", stdout);
  2031. freopen("CONOUT$", "w", stderr);
  2032. }
  2033. }
  2034. if (ok) {
  2035. SetConsoleTitle(g_server_name);
  2036. }
  2037. return ok;
  2038. }
  2039. int WINAPI
  2040. WinMain(HINSTANCE hInst, HINSTANCE hPrev, LPSTR cmdline, int show)
  2041. {
  2042. WNDCLASS cls;
  2043. HWND hWnd;
  2044. MSG msg;
  2045. int i;
  2046. int dataLen = 4;
  2047. char data[256] = {0};
  2048. char masked_data[256] = {0};
  2049. uint32_t masking_key = 0x01020304;
  2050. for (i = 0; i < dataLen - 3; i += 4) {
  2051. *(uint32_t *)(void *)(masked_data + i) =
  2052. *(uint32_t *)(void *)(data + i) ^ masking_key;
  2053. }
  2054. if (i != dataLen) {
  2055. /* convert 1-3 remaining bytes */
  2056. i -= 4;
  2057. while (i < dataLen) {
  2058. *(uint8_t *)(void *)(masked_data + i) =
  2059. *(uint8_t *)(void *)(data + i)
  2060. ^ *(((uint8_t *)&masking_key) + (i % 4));
  2061. i++;
  2062. }
  2063. }
  2064. #if 0
  2065. /* http://lomont.org/Math/Papers/2008/Lomont_PRNG_2008.pdf */
  2066. /* initialize state to random bits
  2067. */
  2068. static unsigned long state[16];
  2069. /* init should also reset this to 0 */
  2070. static unsigned int index = 0;
  2071. /* return 32 bit random number
  2072. */
  2073. unsigned long WELLRN G512(void)
  2074. {
  2075. unsigned long a, b, c, d;
  2076. a = state[index];
  2077. c = state[(index + 13) & 15];
  2078. b = a ^ c ^ (a << 16) ^ (c << 15);
  2079. c = state[(index + 9) & 15];
  2080. c ^= (c >> 11);
  2081. a = state[index] = b ^ c;
  2082. d = a ^ ((a << 5) & 0xDA442D24 UL);
  2083. index = (index + 15) & 15;
  2084. a = state[index];
  2085. state[index] = a ^ b ^ d ^ (a << 2) ^ (b << 18) ^ (c << 28);
  2086. return state[index];
  2087. }
  2088. uint32_t x, y, z, w;
  2089. uint32_t xorshift128(void)
  2090. {
  2091. uint32_t t = x ^ (x << 11);
  2092. x = y;
  2093. y = z;
  2094. z = w;
  2095. return w = w ^ (w >> 19) ^ t ^ (t >> 8);
  2096. }
  2097. static uint64_t lfsr = 1;
  2098. static uint64_t lcg = 0;
  2099. uint64_t r = 0;
  2100. do {
  2101. lfsr = (lfsr >> 1)
  2102. | ((((lfsr >> 0) ^ (lfsr >> 1) ^ (lfsr >> 3) ^ (lfsr >> 4)) & 1)
  2103. << 63);
  2104. lcg = lcg * 6364136223846793005 + 1442695040888963407;
  2105. ++r;
  2106. } while (lcg != 0);
  2107. fprintf(stdout, "lfsr = %I64u, lcg = %i64u, r = %i64u\n", lfsr, lcg, r);
  2108. #endif
  2109. (void)hInst;
  2110. (void)hPrev;
  2111. (void)cmdline;
  2112. (void)show;
  2113. init_server_name((int)__argc, (const char **)__argv);
  2114. memset(&cls, 0, sizeof(cls));
  2115. cls.lpfnWndProc = (WNDPROC)WindowProc;
  2116. cls.hIcon = LoadIcon(NULL, IDI_APPLICATION);
  2117. cls.lpszClassName = g_server_base_name;
  2118. RegisterClass(&cls);
  2119. hWnd = CreateWindow(cls.lpszClassName,
  2120. g_server_name,
  2121. WS_OVERLAPPEDWINDOW,
  2122. 0,
  2123. 0,
  2124. 0,
  2125. 0,
  2126. NULL,
  2127. NULL,
  2128. NULL,
  2129. NULL);
  2130. ShowWindow(hWnd, SW_HIDE);
  2131. if (g_icon_name) {
  2132. hIcon =
  2133. LoadImage(NULL, g_icon_name, IMAGE_ICON, 16, 16, LR_LOADFROMFILE);
  2134. } else {
  2135. hIcon = LoadImage(GetModuleHandle(NULL),
  2136. MAKEINTRESOURCE(ID_ICON),
  2137. IMAGE_ICON,
  2138. 16,
  2139. 16,
  2140. 0);
  2141. }
  2142. TrayIcon.cbSize = sizeof(TrayIcon);
  2143. TrayIcon.uID = ID_ICON;
  2144. TrayIcon.uFlags = NIF_ICON | NIF_MESSAGE | NIF_TIP;
  2145. TrayIcon.hIcon = hIcon;
  2146. TrayIcon.hWnd = hWnd;
  2147. snprintf(TrayIcon.szTip, sizeof(TrayIcon.szTip), "%s", g_server_name);
  2148. TrayIcon.uCallbackMessage = WM_USER;
  2149. Shell_NotifyIcon(NIM_ADD, &TrayIcon);
  2150. while (GetMessage(&msg, hWnd, 0, 0) > 0) {
  2151. TranslateMessage(&msg);
  2152. DispatchMessage(&msg);
  2153. }
  2154. /* Return the WM_QUIT value. */
  2155. return (int)msg.wParam;
  2156. }
  2157. int
  2158. main(int argc, char *argv[])
  2159. {
  2160. (void)argc;
  2161. (void)argv;
  2162. return WinMain(0, 0, 0, 0);
  2163. }
  2164. #elif defined(USE_COCOA)
  2165. #import <Cocoa/Cocoa.h>
  2166. @interface Civetweb : NSObject <NSApplicationDelegate>
  2167. - (void)openBrowser;
  2168. - (void)shutDown;
  2169. @end
  2170. @implementation Civetweb
  2171. - (void)openBrowser
  2172. {
  2173. [[NSWorkspace sharedWorkspace]
  2174. openURL:[NSURL URLWithString:[NSString stringWithUTF8String:
  2175. get_url_to_first_open_port(
  2176. g_ctx)]]];
  2177. }
  2178. - (void)editConfig
  2179. {
  2180. create_config_file(g_ctx, g_config_file);
  2181. [[NSWorkspace sharedWorkspace]
  2182. openFile:[NSString stringWithUTF8String:g_config_file]
  2183. withApplication:@"TextEdit"];
  2184. }
  2185. - (void)shutDown
  2186. {
  2187. [NSApp terminate:nil];
  2188. }
  2189. @end
  2190. int
  2191. main(int argc, char *argv[])
  2192. {
  2193. init_server_name(argc, (const char **)argv);
  2194. start_civetweb(argc, argv);
  2195. [NSAutoreleasePool new];
  2196. [NSApplication sharedApplication];
  2197. /* Add delegate to process menu item actions */
  2198. Civetweb *myDelegate = [[Civetweb alloc] autorelease];
  2199. [NSApp setDelegate:myDelegate];
  2200. /* Run this app as agent */
  2201. ProcessSerialNumber psn = {0, kCurrentProcess};
  2202. TransformProcessType(&psn, kProcessTransformToBackgroundApplication);
  2203. SetFrontProcess(&psn);
  2204. /* Add status bar menu */
  2205. id menu = [[NSMenu new] autorelease];
  2206. /* Add version menu item */
  2207. [menu
  2208. addItem:
  2209. [[[NSMenuItem alloc]
  2210. /*initWithTitle:[NSString stringWithFormat:@"%s", server_name]*/
  2211. initWithTitle:[NSString stringWithUTF8String:g_server_name]
  2212. action:@selector(noexist)
  2213. keyEquivalent:@""] autorelease]];
  2214. /* Add configuration menu item */
  2215. [menu addItem:[[[NSMenuItem alloc] initWithTitle:@"Edit configuration"
  2216. action:@selector(editConfig)
  2217. keyEquivalent:@""] autorelease]];
  2218. /* Add connect menu item */
  2219. [menu
  2220. addItem:[[[NSMenuItem alloc] initWithTitle:@"Open web root in a browser"
  2221. action:@selector(openBrowser)
  2222. keyEquivalent:@""] autorelease]];
  2223. /* Separator */
  2224. [menu addItem:[NSMenuItem separatorItem]];
  2225. /* Add quit menu item */
  2226. [menu addItem:[[[NSMenuItem alloc] initWithTitle:@"Quit"
  2227. action:@selector(shutDown)
  2228. keyEquivalent:@"q"] autorelease]];
  2229. /* Attach menu to the status bar */
  2230. id item = [[[NSStatusBar systemStatusBar]
  2231. statusItemWithLength:NSVariableStatusItemLength] retain];
  2232. [item setHighlightMode:YES];
  2233. [item setImage:[NSImage imageNamed:@"civetweb_22x22.png"]];
  2234. [item setMenu:menu];
  2235. /* Run the app */
  2236. [NSApp activateIgnoringOtherApps:YES];
  2237. [NSApp run];
  2238. stop_civetweb(g_ctx);
  2239. return EXIT_SUCCESS;
  2240. }
  2241. #else
  2242. int
  2243. main(int argc, char *argv[])
  2244. {
  2245. init_server_name(argc, (const char **)argv);
  2246. start_civetweb(argc, argv);
  2247. fprintf(stdout,
  2248. "%s started on port(s) %s with web root [%s]\n",
  2249. g_server_name,
  2250. mg_get_option(g_ctx, "listening_ports"),
  2251. mg_get_option(g_ctx, "document_root"));
  2252. while (g_exit_flag == 0) {
  2253. sleep(1);
  2254. }
  2255. fprintf(stdout,
  2256. "Exiting on signal %d, waiting for all threads to finish...",
  2257. g_exit_flag);
  2258. fflush(stdout);
  2259. stop_civetweb();
  2260. fprintf(stdout, "%s", " done.\n");
  2261. return EXIT_SUCCESS;
  2262. }
  2263. #endif /* _WIN32 */