main.c 65 KB

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