main.c 52 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828
  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. #endif
  32. #ifndef IGNORE_UNUSED_RESULT
  33. #define IGNORE_UNUSED_RESULT(a) ((void)((a) && 1))
  34. #endif
  35. #include <sys/stat.h>
  36. #include <stdio.h>
  37. #include <stdlib.h>
  38. #include <signal.h>
  39. #include <string.h>
  40. #include <errno.h>
  41. #include <limits.h>
  42. #include <stddef.h>
  43. #include <stdarg.h>
  44. #include <ctype.h>
  45. #include <assert.h>
  46. #include "civetweb.h"
  47. #ifdef _WIN32
  48. #ifndef _WIN32_WINNT
  49. #define _WIN32_WINNT 0x0501 /* Target Windows XP or higher */
  50. #endif
  51. #undef UNICODE
  52. #include <windows.h>
  53. #include <winsvc.h>
  54. #include <shlobj.h>
  55. #include <io.h>
  56. #define getcwd(a, b) (_getcwd(a, b))
  57. #if !defined(__MINGW32__)
  58. extern char *_getcwd(char *buf, size_t size);
  59. #endif
  60. static int guard = 0; /* test if any dialog is already open */
  61. #if defined(_MSC_VER)
  62. #define strdup _strdup
  63. /* or #pragma warning (disable : 4996 ) */
  64. #endif
  65. #ifndef PATH_MAX
  66. #define PATH_MAX MAX_PATH
  67. #endif
  68. #ifndef S_ISDIR
  69. #define S_ISDIR(x) ((x)&_S_IFDIR)
  70. #endif
  71. #define DIRSEP '\\'
  72. #define snprintf _snprintf
  73. #define vsnprintf _vsnprintf
  74. #define sleep(x) (Sleep((x)*1000))
  75. #define WINCDECL __cdecl
  76. #define abs_path(rel, abs, abs_size) (_fullpath((abs), (rel), (abs_size)))
  77. #else
  78. #include <sys/wait.h>
  79. #include <unistd.h>
  80. #define DIRSEP '/'
  81. #define WINCDECL
  82. #define abs_path(rel, abs, abs_size) (realpath((rel), (abs)))
  83. #endif /* _WIN32 */
  84. #define MAX_OPTIONS (50)
  85. #define MAX_CONF_FILE_LINE_SIZE (8 * 1024)
  86. struct tuser_data {
  87. char *first_message;
  88. };
  89. static int g_exit_flag = 0; /* Main loop should exit */
  90. static char g_server_base_name[40]; /* Set by init_server_name() */
  91. static char *g_server_name; /* Set by init_server_name() */
  92. static char *g_icon_name; /* Set by init_server_name() */
  93. static char g_config_file[PATH_MAX] =
  94. ""; /* Set by process_command_line_arguments() */
  95. static struct mg_context *g_ctx; /* Set by start_civetweb() */
  96. static struct tuser_data
  97. g_user_data; /* Passed to mg_start() by start_civetweb() */
  98. #if !defined(CONFIG_FILE)
  99. #define CONFIG_FILE "civetweb.conf"
  100. #endif /* !CONFIG_FILE */
  101. #if !defined(PASSWORDS_FILE_NAME)
  102. #define PASSWORDS_FILE_NAME ".htpasswd"
  103. #endif
  104. /* backup config file */
  105. #if !defined(CONFIG_FILE2) && defined(LINUX)
  106. #define CONFIG_FILE2 "/usr/local/etc/civetweb.conf"
  107. #endif
  108. enum { OPTION_TITLE, OPTION_ICON, NUM_MAIN_OPTIONS };
  109. static struct mg_option main_config_options[] = {
  110. {"title", CONFIG_TYPE_STRING, NULL},
  111. {"icon", CONFIG_TYPE_STRING, NULL},
  112. {NULL, CONFIG_TYPE_UNKNOWN, NULL}};
  113. static void WINCDECL signal_handler(int sig_num) { g_exit_flag = sig_num; }
  114. static void die(const char *fmt, ...) {
  115. va_list ap;
  116. char msg[200] = "";
  117. va_start(ap, fmt);
  118. (void)vsnprintf(msg, sizeof(msg) - 1, fmt, ap);
  119. msg[sizeof(msg) - 1] = 0;
  120. va_end(ap);
  121. #if defined(_WIN32)
  122. MessageBox(NULL, msg, "Error", MB_OK);
  123. #else
  124. fprintf(stderr, "%s\n", msg);
  125. #endif
  126. exit(EXIT_FAILURE);
  127. }
  128. #ifdef WIN32
  129. static int MakeConsole();
  130. #endif
  131. static void show_server_name(void) {
  132. #ifdef WIN32
  133. MakeConsole();
  134. #endif
  135. fprintf(stderr, "CivetWeb v%s, built on %s\n", mg_version(), __DATE__);
  136. }
  137. static void show_usage_and_exit(const char *exeName) {
  138. const struct mg_option *options;
  139. int i;
  140. if (exeName == 0 || *exeName == 0) {
  141. exeName = "civetweb";
  142. }
  143. show_server_name();
  144. fprintf(stderr, "\nUsage:\n");
  145. fprintf(stderr, " Start server with a set of options:\n");
  146. fprintf(stderr, " %s [config_file]\n", exeName);
  147. fprintf(stderr, " %s [-option value ...]\n", exeName);
  148. fprintf(stderr, " Add user/change password:\n");
  149. fprintf(stderr, " %s -A <htpasswd_file> <realm> <user> <passwd>\n",
  150. exeName);
  151. fprintf(stderr, " Remove user:\n");
  152. fprintf(stderr, " %s -R <htpasswd_file> <realm> <user>\n", exeName);
  153. fprintf(stderr, "\nOPTIONS:\n");
  154. options = mg_get_valid_options();
  155. for (i = 0; options[i].name != NULL; i++) {
  156. fprintf(stderr, " -%s %s\n", options[i].name,
  157. ((options[i].default_value == NULL)
  158. ? "<empty>"
  159. : options[i].default_value));
  160. }
  161. options = main_config_options;
  162. for (i = 0; options[i].name != NULL; i++) {
  163. fprintf(stderr, " -%s %s\n", options[i].name,
  164. ((options[i].default_value == NULL)
  165. ? "<empty>"
  166. : options[i].default_value));
  167. }
  168. exit(EXIT_FAILURE);
  169. }
  170. #if defined(_WIN32) || defined(USE_COCOA)
  171. static const char *config_file_top_comment =
  172. "# Civetweb web server configuration file.\n"
  173. "# For detailed description of every option, visit\n"
  174. "# https://github.com/bel2125/civetweb/blob/master/docs/UserManual.md\n"
  175. "# Lines starting with '#' and empty lines are ignored.\n"
  176. "# To make a change, remove leading '#', modify option's value,\n"
  177. "# save this file and then restart Civetweb.\n\n";
  178. static const char *get_url_to_first_open_port(const struct mg_context *ctx) {
  179. static char url[100];
  180. const char *open_ports = mg_get_option(ctx, "listening_ports");
  181. int a, b, c, d, port, n;
  182. if (sscanf(open_ports, "%d.%d.%d.%d:%d%n", &a, &b, &c, &d, &port, &n) ==
  183. 5) {
  184. snprintf(url, sizeof(url), "%s://%d.%d.%d.%d:%d",
  185. open_ports[n] == 's' ? "https" : "http", a, b, c, d, port);
  186. } else if (sscanf(open_ports, "%d%n", &port, &n) == 1) {
  187. snprintf(url, sizeof(url), "%s://localhost:%d",
  188. open_ports[n] == 's' ? "https" : "http", port);
  189. } else {
  190. snprintf(url, sizeof(url), "%s", "http://localhost:8080");
  191. }
  192. return url;
  193. }
  194. static void create_config_file(const struct mg_context *ctx, const char *path) {
  195. const struct mg_option *options;
  196. const char *value;
  197. FILE *fp;
  198. int i;
  199. /* Create config file if it is not present yet */
  200. if ((fp = fopen(path, "r")) != NULL) {
  201. fclose(fp);
  202. } else if ((fp = fopen(path, "a+")) != NULL) {
  203. fprintf(fp, "%s", config_file_top_comment);
  204. options = mg_get_valid_options();
  205. for (i = 0; options[i].name != NULL; i++) {
  206. value = mg_get_option(ctx, options[i].name);
  207. fprintf(fp, "# %s %s\n", options[i].name,
  208. value ? value : "<value>");
  209. }
  210. fclose(fp);
  211. }
  212. }
  213. #endif
  214. static char *sdup(const char *str) {
  215. size_t len;
  216. char *p;
  217. len = strlen(str) + 1;
  218. if ((p = (char *)malloc(len)) != NULL) {
  219. memcpy(p, str, len);
  220. }
  221. return p;
  222. }
  223. static const char *get_option(char **options, const char *option_name) {
  224. int i = 0;
  225. const char *opt_value = NULL;
  226. /* TODO: options should be an array of key-value-pairs, like
  227. struct {const char * key, const char * value} options[]
  228. but it currently is an array with
  229. options[2*i] = key, options[2*i + 1] = value
  230. */
  231. while (options[2 * i] != NULL) {
  232. if (strcmp(options[2 * i], option_name) == 0) {
  233. opt_value = options[2 * i + 1];
  234. break;
  235. }
  236. i++;
  237. }
  238. return opt_value;
  239. }
  240. static int set_option(char **options, const char *name, const char *value) {
  241. int i, type;
  242. const struct mg_option *default_options = mg_get_valid_options();
  243. for (i = 0; main_config_options[i].name != NULL; i++) {
  244. if (0 == strcmp(name, main_config_options[i].name)) {
  245. /* This option is evaluated by main.c, not civetweb.c - just skip it
  246. * and return OK */
  247. return 1;
  248. }
  249. }
  250. type = CONFIG_TYPE_UNKNOWN;
  251. for (i = 0; default_options[i].name != NULL; i++) {
  252. if (!strcmp(default_options[i].name, name)) {
  253. type = default_options[i].type;
  254. }
  255. }
  256. switch (type) {
  257. case CONFIG_TYPE_UNKNOWN:
  258. /* unknown option */
  259. return 0;
  260. case CONFIG_TYPE_NUMBER:
  261. /* integer number > 0, e.g. number of threads */
  262. if (atol(value) < 1) {
  263. /* invalid number */
  264. return 0;
  265. }
  266. break;
  267. case CONFIG_TYPE_STRING:
  268. /* any text */
  269. break;
  270. case CONFIG_TYPE_BOOLEAN:
  271. /* boolean value, yes or no */
  272. if ((0 != strcmp(value, "yes")) && (0 != strcmp(value, "no"))) {
  273. /* invalid boolean */
  274. return 0;
  275. }
  276. break;
  277. case CONFIG_TYPE_FILE:
  278. case CONFIG_TYPE_DIRECTORY:
  279. /* TODO: check this option when it is set, instead of calling
  280. * verify_existence later */
  281. break;
  282. case CONFIG_TYPE_EXT_PATTERN:
  283. /* list of file extentions */
  284. break;
  285. default:
  286. die("Unknown option type - option %s", name);
  287. break;
  288. }
  289. for (i = 0; i < MAX_OPTIONS; i++) {
  290. if (options[2 * i] == NULL) {
  291. options[2 * i] = sdup(name);
  292. options[2 * i + 1] = sdup(value);
  293. options[2 * i + 2] = NULL;
  294. break;
  295. } else if (!strcmp(options[2 * i], name)) {
  296. free(options[2 * i + 1]);
  297. options[2 * i + 1] = sdup(value);
  298. break;
  299. }
  300. }
  301. if (i == MAX_OPTIONS) {
  302. die("Too many options specified");
  303. }
  304. if (options[2 * i] == NULL || options[2 * i + 1] == NULL) {
  305. die("Out of memory");
  306. }
  307. /* option set correctly */
  308. return 1;
  309. }
  310. static void read_config_file(const char *config_file, char **options) {
  311. char line[MAX_CONF_FILE_LINE_SIZE], *p;
  312. FILE *fp = NULL;
  313. size_t i, j, cmd_line_opts_start = 1, line_no = 0;
  314. fp = fopen(config_file, "r");
  315. /* If config file was set in command line and open failed, die */
  316. if (cmd_line_opts_start == 2 && fp == NULL) {
  317. die("Cannot open config file %s: %s", config_file, strerror(errno));
  318. }
  319. /* Load config file settings first */
  320. if (fp != NULL) {
  321. fprintf(stderr, "Loading config file %s\n", config_file);
  322. /* Loop over the lines in config file */
  323. while (fgets(line, sizeof(line), fp) != NULL) {
  324. if (!line_no && !memcmp(line, "\xEF\xBB\xBF", 3)) {
  325. /* strip UTF-8 BOM */
  326. p = line + 3;
  327. } else {
  328. p = line;
  329. }
  330. line_no++;
  331. /* Ignore empty lines and comments */
  332. for (i = 0; isspace(*(unsigned char *)&line[i]);)
  333. i++;
  334. if (p[i] == '#' || p[i] == '\0') {
  335. continue;
  336. }
  337. /* Skip spaces, \r and \n at the end of the line */
  338. for (j = strlen(line) - 1; isspace(*(unsigned char *)&line[j]) ||
  339. iscntrl(*(unsigned char *)&line[j]);)
  340. line[j--] = 0;
  341. /* Find the space character between option name and value */
  342. for (j = i; !isspace(*(unsigned char *)&line[j]) && (line[j] != 0);)
  343. j++;
  344. /* Terminate the string - then the string at (line+i) contains the
  345. * option name */
  346. line[j] = 0;
  347. j++;
  348. /* Trim additional spaces between option name and value - then
  349. * (line+j) contains the option value */
  350. while (isspace(line[j]))
  351. j++;
  352. /* Set option */
  353. if (!set_option(options, line + i, line + j)) {
  354. printf("%s: line %d is invalid, ignoring it:\n %s", config_file,
  355. (int)line_no, p);
  356. }
  357. }
  358. (void)fclose(fp);
  359. }
  360. }
  361. static void process_command_line_arguments(char *argv[], char **options) {
  362. char *p;
  363. size_t i, cmd_line_opts_start = 1;
  364. #ifdef CONFIG_FILE2
  365. FILE *fp = NULL;
  366. #endif
  367. /* Should we use a config file ? */
  368. if (argv[1] != NULL && argv[1][0] != '-') {
  369. snprintf(g_config_file, sizeof(g_config_file) - 1, "%s", argv[1]);
  370. cmd_line_opts_start = 2;
  371. } else if ((p = strrchr(argv[0], DIRSEP)) == NULL) {
  372. /* No command line flags specified. Look where binary lives */
  373. snprintf(g_config_file, sizeof(g_config_file) - 1, "%s", CONFIG_FILE);
  374. } else {
  375. snprintf(g_config_file, sizeof(g_config_file) - 1, "%.*s%c%s",
  376. (int)(p - argv[0]), argv[0], DIRSEP, CONFIG_FILE);
  377. }
  378. g_config_file[sizeof(g_config_file) - 1] = 0;
  379. #ifdef CONFIG_FILE2
  380. fp = fopen(g_config_file, "r");
  381. /* try alternate config file */
  382. if (fp == NULL) {
  383. fp = fopen(CONFIG_FILE2, "r");
  384. if (fp != NULL) {
  385. strcpy(g_config_file, CONFIG_FILE2);
  386. }
  387. }
  388. if (fp != NULL) {
  389. fclose(fp);
  390. }
  391. #endif
  392. /* read all configurations from a config file */
  393. (void)read_config_file(g_config_file, options);
  394. /* If we're under MacOS and started by launchd, then the second
  395. argument is process serial number, -psn_.....
  396. In this case, don't process arguments at all. */
  397. if (argv[1] == NULL || memcmp(argv[1], "-psn_", 5) != 0) {
  398. /* Handle command line flags.
  399. They override config file and default settings. */
  400. for (i = cmd_line_opts_start; argv[i] != NULL; i += 2) {
  401. if (argv[i][0] != '-' || argv[i + 1] == NULL) {
  402. show_usage_and_exit(argv[0]);
  403. }
  404. if (!set_option(options, &argv[i][1], argv[i + 1])) {
  405. printf("command line option is invalid, ignoring it:\n %s %s\n",
  406. argv[i], argv[i + 1]);
  407. }
  408. }
  409. }
  410. }
  411. static void init_server_name(int argc, const char *argv[]) {
  412. int i;
  413. assert(sizeof(main_config_options) / sizeof(main_config_options[0]) ==
  414. NUM_MAIN_OPTIONS + 1);
  415. assert((strlen(mg_version()) + 12) < sizeof(g_server_base_name));
  416. snprintf(g_server_base_name, sizeof(g_server_base_name), "Civetweb V%s",
  417. mg_version());
  418. g_server_name = g_server_base_name;
  419. for (i = 0; i < argc - 1; i++) {
  420. if ((argv[i][0] == '-') &&
  421. (0 ==
  422. strcmp(argv[i] + 1, main_config_options[OPTION_TITLE].name))) {
  423. g_server_name = (char *)(argv[i + 1]);
  424. }
  425. }
  426. g_icon_name = NULL;
  427. for (i = 0; i < argc - 1; i++) {
  428. if ((argv[i][0] == '-') &&
  429. (0 == strcmp(argv[i] + 1, main_config_options[OPTION_ICON].name))) {
  430. g_icon_name = (char *)(argv[i + 1]);
  431. }
  432. }
  433. }
  434. static int log_message(const struct mg_connection *conn, const char *message) {
  435. const struct mg_context *ctx = mg_get_context(conn);
  436. struct tuser_data *ud = (struct tuser_data *)mg_get_user_data(ctx);
  437. printf("%s\n", message);
  438. if (ud->first_message == NULL) {
  439. ud->first_message = strdup(message);
  440. }
  441. return 0;
  442. }
  443. static int is_path_absolute(const char *path) {
  444. #ifdef _WIN32
  445. return path != NULL &&
  446. ((path[0] == '\\' && path[1] == '\\') || /* UNC path, e.g.
  447. \\server\dir */
  448. (isalpha(path[0]) && path[1] == ':' &&
  449. path[2] == '\\')); /* E.g. X:\dir */
  450. #else
  451. return path != NULL && path[0] == '/';
  452. #endif
  453. }
  454. static void verify_existence(char **options, const char *option_name,
  455. int must_be_dir) {
  456. struct stat st;
  457. const char *path = get_option(options, option_name);
  458. #ifdef _WIN32
  459. wchar_t wbuf[1024];
  460. char mbbuf[1024];
  461. int len;
  462. if (path) {
  463. memset(wbuf, 0, sizeof(wbuf));
  464. memset(mbbuf, 0, sizeof(mbbuf));
  465. len = MultiByteToWideChar(CP_UTF8, 0, path, -1, wbuf,
  466. (int)sizeof(wbuf) / sizeof(wbuf[0]) - 1);
  467. wcstombs(mbbuf, wbuf, sizeof(mbbuf) - 1);
  468. path = mbbuf;
  469. (void)len;
  470. }
  471. #endif
  472. if (path != NULL && (stat(path, &st) != 0 ||
  473. ((S_ISDIR(st.st_mode) ? 1 : 0) != must_be_dir))) {
  474. die("Invalid path for %s: [%s]: (%s). Make sure that path is either "
  475. "absolute, or it is relative to civetweb executable.",
  476. option_name, path, strerror(errno));
  477. }
  478. }
  479. static void set_absolute_path(char *options[], const char *option_name,
  480. const char *path_to_civetweb_exe) {
  481. char path[PATH_MAX] = "", abs[PATH_MAX] = "";
  482. const char *option_value;
  483. const char *p;
  484. /* Check whether option is already set */
  485. option_value = get_option(options, option_name);
  486. /* If option is already set and it is an absolute path,
  487. leave it as it is -- it's already absolute. */
  488. if (option_value != NULL && !is_path_absolute(option_value)) {
  489. /* Not absolute. Use the directory where civetweb executable lives
  490. be the relative directory for everything.
  491. Extract civetweb executable directory into path. */
  492. if ((p = strrchr(path_to_civetweb_exe, DIRSEP)) == NULL) {
  493. IGNORE_UNUSED_RESULT(getcwd(path, sizeof(path)));
  494. } else {
  495. snprintf(path, sizeof(path) - 1, "%.*s",
  496. (int)(p - path_to_civetweb_exe), path_to_civetweb_exe);
  497. path[sizeof(path) - 1] = 0;
  498. }
  499. strncat(path, "/", sizeof(path) - strlen(path) - 1);
  500. strncat(path, option_value, sizeof(path) - strlen(path) - 1);
  501. /* Absolutize the path, and set the option */
  502. IGNORE_UNUSED_RESULT(abs_path(path, abs, sizeof(abs)));
  503. set_option(options, option_name, abs);
  504. }
  505. }
  506. #ifdef USE_LUA
  507. #include "lua.h"
  508. #include "lauxlib.h"
  509. extern void lua_civet_open_all_libs(lua_State *L);
  510. int run_lua(const char *file_name) {
  511. struct lua_State *L;
  512. int lua_ret;
  513. int func_ret = EXIT_FAILURE;
  514. const char *lua_err_txt;
  515. #ifdef WIN32
  516. MakeConsole();
  517. #endif
  518. L = luaL_newstate();
  519. if (L == NULL) {
  520. fprintf(stderr, "Error: Cannot create Lua state\n");
  521. return EXIT_FAILURE;
  522. }
  523. lua_civet_open_all_libs(L);
  524. lua_ret = luaL_loadfile(L, file_name);
  525. if (lua_ret != LUA_OK) {
  526. /* Error when loading the file (e.g. file not found, out of memory, ...)
  527. */
  528. lua_err_txt = lua_tostring(L, -1);
  529. fprintf(stderr, "Error loading file %s: %s\n", file_name, lua_err_txt);
  530. } else {
  531. /* The script file is loaded, now call it */
  532. lua_ret =
  533. lua_pcall(L, /* no arguments */ 0, /* zero or one return value */ 1,
  534. /* errors as strint return value */ 0);
  535. if (lua_ret != LUA_OK) {
  536. /* Error when executing the script */
  537. lua_err_txt = lua_tostring(L, -1);
  538. fprintf(stderr, "Error running file %s: %s\n", file_name,
  539. lua_err_txt);
  540. } else {
  541. /* Script executed */
  542. if (lua_type(L, -1) == LUA_TNUMBER) {
  543. func_ret = (int)lua_tonumber(L, -1);
  544. } else {
  545. func_ret = EXIT_SUCCESS;
  546. }
  547. }
  548. }
  549. lua_close(L);
  550. return func_ret;
  551. }
  552. #endif
  553. static void start_civetweb(int argc, char *argv[]) {
  554. struct mg_callbacks callbacks;
  555. char *options[2 * MAX_OPTIONS + 1];
  556. int i;
  557. /* Edit passwords file: Add user or change password, if -A option is
  558. * specified */
  559. if (argc > 1 && !strcmp(argv[1], "-A")) {
  560. if (argc != 6) {
  561. show_usage_and_exit(argv[0]);
  562. }
  563. exit(mg_modify_passwords_file(argv[2], argv[3], argv[4], argv[5])
  564. ? EXIT_SUCCESS
  565. : EXIT_FAILURE);
  566. }
  567. /* Edit passwords file: Remove user, if -R option is specified */
  568. if (argc > 1 && !strcmp(argv[1], "-R")) {
  569. if (argc != 5) {
  570. show_usage_and_exit(argv[0]);
  571. }
  572. exit(mg_modify_passwords_file(argv[2], argv[3], argv[4], NULL)
  573. ? EXIT_SUCCESS
  574. : EXIT_FAILURE);
  575. }
  576. /* Call Lua with additional Civetweb specific Lua functions, if -L option is
  577. * specified */
  578. if (argc > 1 && !strcmp(argv[1], "-L")) {
  579. #ifdef USE_LUA
  580. if (argc != 3) {
  581. show_usage_and_exit(argv[0]);
  582. }
  583. exit(run_lua(argv[2]));
  584. #else
  585. show_server_name();
  586. fprintf(stderr, "\nError: Lua support not enabled\n");
  587. exit(EXIT_FAILURE);
  588. #endif
  589. }
  590. /* Show usage if -h or --help options are specified */
  591. if (argc == 2 && (!strcmp(argv[1], "-h") || !strcmp(argv[1], "-H") ||
  592. !strcmp(argv[1], "--help"))) {
  593. show_usage_and_exit(argv[0]);
  594. }
  595. options[0] = NULL;
  596. set_option(options, "document_root", ".");
  597. /* Update config based on command line arguments */
  598. process_command_line_arguments(argv, options);
  599. /* Make sure we have absolute paths for files and directories */
  600. set_absolute_path(options, "document_root", argv[0]);
  601. set_absolute_path(options, "put_delete_auth_file", argv[0]);
  602. set_absolute_path(options, "cgi_interpreter", argv[0]);
  603. set_absolute_path(options, "access_log_file", argv[0]);
  604. set_absolute_path(options, "error_log_file", argv[0]);
  605. set_absolute_path(options, "global_auth_file", argv[0]);
  606. #ifdef USE_LUA
  607. set_absolute_path(options, "lua_preload_file", argv[0]);
  608. #endif
  609. set_absolute_path(options, "ssl_certificate", argv[0]);
  610. /* Make extra verification for certain options */
  611. verify_existence(options, "document_root", 1);
  612. verify_existence(options, "cgi_interpreter", 0);
  613. verify_existence(options, "ssl_certificate", 0);
  614. #ifdef USE_LUA
  615. verify_existence(options, "lua_preload_file", 0);
  616. #endif
  617. /* Setup signal handler: quit on Ctrl-C */
  618. signal(SIGTERM, signal_handler);
  619. signal(SIGINT, signal_handler);
  620. /* Initialize user data */
  621. memset(&g_user_data, 0, sizeof(g_user_data));
  622. /* Start Civetweb */
  623. memset(&callbacks, 0, sizeof(callbacks));
  624. callbacks.log_message = &log_message;
  625. g_ctx = mg_start(&callbacks, &g_user_data, (const char **)options);
  626. for (i = 0; options[i] != NULL; i++) {
  627. free(options[i]);
  628. }
  629. if (g_ctx == NULL) {
  630. die("Failed to start Civetweb:\n%s", (g_user_data.first_message == NULL)
  631. ? "unknown reason"
  632. : g_user_data.first_message);
  633. }
  634. }
  635. void stop_civetweb(void) {
  636. mg_stop(g_ctx);
  637. free(g_user_data.first_message);
  638. g_user_data.first_message = NULL;
  639. }
  640. #ifdef _WIN32
  641. enum {
  642. ID_ICON = 100,
  643. ID_QUIT,
  644. ID_SETTINGS,
  645. ID_SEPARATOR,
  646. ID_INSTALL_SERVICE,
  647. ID_REMOVE_SERVICE,
  648. ID_STATIC,
  649. ID_GROUP,
  650. ID_PASSWORD,
  651. ID_SAVE,
  652. ID_RESET_DEFAULTS,
  653. ID_RESET_FILE,
  654. ID_RESET_ACTIVE,
  655. ID_STATUS,
  656. ID_CONNECT,
  657. ID_ADD_USER,
  658. ID_ADD_USER_NAME,
  659. ID_ADD_USER_REALM,
  660. ID_INPUT_LINE,
  661. /* All dynamically created text boxes for options have IDs starting from
  662. ID_CONTROLS, incremented by one. */
  663. ID_CONTROLS = 200,
  664. /* Text boxes for files have "..." buttons to open file browser. These
  665. buttons have IDs that are ID_FILE_BUTTONS_DELTA higher than associated
  666. text box ID. */
  667. ID_FILE_BUTTONS_DELTA = 1000
  668. };
  669. static HICON hIcon;
  670. static SERVICE_STATUS ss;
  671. static SERVICE_STATUS_HANDLE hStatus;
  672. static const char *service_magic_argument = "--";
  673. static NOTIFYICONDATA TrayIcon;
  674. static void WINAPI ControlHandler(DWORD code) {
  675. if (code == SERVICE_CONTROL_STOP || code == SERVICE_CONTROL_SHUTDOWN) {
  676. ss.dwWin32ExitCode = 0;
  677. ss.dwCurrentState = SERVICE_STOPPED;
  678. }
  679. SetServiceStatus(hStatus, &ss);
  680. }
  681. static void WINAPI ServiceMain(void) {
  682. ss.dwServiceType = SERVICE_WIN32;
  683. ss.dwCurrentState = SERVICE_RUNNING;
  684. ss.dwControlsAccepted = SERVICE_ACCEPT_STOP | SERVICE_ACCEPT_SHUTDOWN;
  685. hStatus = RegisterServiceCtrlHandler(g_server_name, ControlHandler);
  686. SetServiceStatus(hStatus, &ss);
  687. while (ss.dwCurrentState == SERVICE_RUNNING) {
  688. Sleep(1000);
  689. }
  690. stop_civetweb();
  691. ss.dwCurrentState = SERVICE_STOPPED;
  692. ss.dwWin32ExitCode = (DWORD)-1;
  693. SetServiceStatus(hStatus, &ss);
  694. }
  695. static void show_error(void) {
  696. char buf[256];
  697. FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
  698. NULL, GetLastError(),
  699. MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), buf, sizeof(buf),
  700. NULL);
  701. MessageBox(NULL, buf, "Error", MB_OK);
  702. }
  703. static void *align(void *ptr, DWORD alig) {
  704. ULONG ul = (ULONG)ptr;
  705. ul += alig;
  706. ul &= ~alig;
  707. return ((void *)ul);
  708. }
  709. static void save_config(HWND hDlg, FILE *fp) {
  710. char value[2000] = "";
  711. const char *default_value;
  712. const struct mg_option *options;
  713. int i, id;
  714. fprintf(fp, "%s", config_file_top_comment);
  715. options = mg_get_valid_options();
  716. for (i = 0; options[i].name != NULL; i++) {
  717. id = ID_CONTROLS + i;
  718. if (options[i].type == CONFIG_TYPE_BOOLEAN) {
  719. snprintf(value, sizeof(value) - 1, "%s",
  720. IsDlgButtonChecked(hDlg, id) ? "yes" : "no");
  721. value[sizeof(value) - 1] = 0;
  722. } else {
  723. GetDlgItemText(hDlg, id, value, sizeof(value));
  724. }
  725. default_value =
  726. options[i].default_value == NULL ? "" : options[i].default_value;
  727. /* If value is the same as default, skip it */
  728. if (strcmp(value, default_value) != 0) {
  729. fprintf(fp, "%s %s\n", options[i].name, value);
  730. }
  731. }
  732. }
  733. static BOOL CALLBACK
  734. SettingsDlgProc(HWND hDlg, UINT msg, WPARAM wParam, LPARAM lParam) {
  735. FILE *fp;
  736. int i, j;
  737. const char *name, *value;
  738. const struct mg_option *default_options = mg_get_valid_options();
  739. char *file_options[MAX_OPTIONS * 2 + 1] = {0};
  740. char *title;
  741. (void)lParam;
  742. switch (msg) {
  743. case WM_CLOSE:
  744. DestroyWindow(hDlg);
  745. break;
  746. case WM_COMMAND:
  747. switch (LOWORD(wParam)) {
  748. case ID_SAVE:
  749. EnableWindow(GetDlgItem(hDlg, ID_SAVE), FALSE);
  750. if ((fp = fopen(g_config_file, "w+")) != NULL) {
  751. save_config(hDlg, fp);
  752. fclose(fp);
  753. stop_civetweb();
  754. start_civetweb(__argc, __argv);
  755. }
  756. EnableWindow(GetDlgItem(hDlg, ID_SAVE), TRUE);
  757. break;
  758. case ID_RESET_DEFAULTS:
  759. for (i = 0; default_options[i].name != NULL; i++) {
  760. name = default_options[i].name;
  761. value = default_options[i].default_value == NULL
  762. ? ""
  763. : default_options[i].default_value;
  764. if (default_options[i].type == CONFIG_TYPE_BOOLEAN) {
  765. CheckDlgButton(hDlg, ID_CONTROLS + i, !strcmp(value, "yes")
  766. ? BST_CHECKED
  767. : BST_UNCHECKED);
  768. } else {
  769. SetWindowText(GetDlgItem(hDlg, ID_CONTROLS + i), value);
  770. }
  771. }
  772. break;
  773. case ID_RESET_FILE:
  774. read_config_file(g_config_file, file_options);
  775. for (i = 0; default_options[i].name != NULL; i++) {
  776. name = default_options[i].name;
  777. value = default_options[i].default_value;
  778. for (j = 0; file_options[j * 2] != NULL; j++) {
  779. if (!strcmp(name, file_options[j * 2])) {
  780. value = file_options[j * 2 + 1];
  781. }
  782. }
  783. if (value == NULL) {
  784. value = "";
  785. }
  786. if (default_options[i].type == CONFIG_TYPE_BOOLEAN) {
  787. CheckDlgButton(hDlg, ID_CONTROLS + i, !strcmp(value, "yes")
  788. ? BST_CHECKED
  789. : BST_UNCHECKED);
  790. } else {
  791. SetWindowText(GetDlgItem(hDlg, ID_CONTROLS + i), value);
  792. }
  793. }
  794. for (i = 0; i < MAX_OPTIONS; i++) {
  795. free(file_options[2 * i]);
  796. free(file_options[2 * i + 1]);
  797. }
  798. break;
  799. case ID_RESET_ACTIVE:
  800. for (i = 0; default_options[i].name != NULL; i++) {
  801. name = default_options[i].name;
  802. value = mg_get_option(g_ctx, name);
  803. if (default_options[i].type == CONFIG_TYPE_BOOLEAN) {
  804. CheckDlgButton(hDlg, ID_CONTROLS + i, !strcmp(value, "yes")
  805. ? BST_CHECKED
  806. : BST_UNCHECKED);
  807. } else {
  808. SetDlgItemText(hDlg, ID_CONTROLS + i,
  809. value == NULL ? "" : value);
  810. }
  811. }
  812. break;
  813. }
  814. for (i = 0; default_options[i].name != NULL; i++) {
  815. name = default_options[i].name;
  816. if (((default_options[i].type == CONFIG_TYPE_FILE) ||
  817. (default_options[i].type == CONFIG_TYPE_DIRECTORY)) &&
  818. LOWORD(wParam) == ID_CONTROLS + i + ID_FILE_BUTTONS_DELTA) {
  819. OPENFILENAME of;
  820. BROWSEINFO bi;
  821. char path[PATH_MAX] = "";
  822. memset(&of, 0, sizeof(of));
  823. of.lStructSize = sizeof(of);
  824. of.hwndOwner = (HWND)hDlg;
  825. of.lpstrFile = path;
  826. of.nMaxFile = sizeof(path);
  827. of.lpstrInitialDir = mg_get_option(g_ctx, "document_root");
  828. of.Flags =
  829. OFN_CREATEPROMPT | OFN_NOCHANGEDIR | OFN_HIDEREADONLY;
  830. memset(&bi, 0, sizeof(bi));
  831. bi.hwndOwner = (HWND)hDlg;
  832. bi.lpszTitle = "Choose WWW root directory:";
  833. bi.ulFlags = BIF_RETURNONLYFSDIRS;
  834. if (default_options[i].type == CONFIG_TYPE_DIRECTORY) {
  835. SHGetPathFromIDList(SHBrowseForFolder(&bi), path);
  836. } else {
  837. GetOpenFileName(&of);
  838. }
  839. if (path[0] != '\0') {
  840. SetWindowText(GetDlgItem(hDlg, ID_CONTROLS + i), path);
  841. }
  842. }
  843. }
  844. break;
  845. case WM_INITDIALOG:
  846. SendMessage(hDlg, WM_SETICON, (WPARAM)ICON_SMALL, (LPARAM)hIcon);
  847. SendMessage(hDlg, WM_SETICON, (WPARAM)ICON_BIG, (LPARAM)hIcon);
  848. title = malloc(strlen(g_server_name) + 16);
  849. if (title) {
  850. strcpy(title, g_server_name);
  851. strcat(title, " settings");
  852. SetWindowText(hDlg, title);
  853. free(title);
  854. }
  855. SetFocus(GetDlgItem(hDlg, ID_SAVE));
  856. /* Init dialog with active settings */
  857. SendMessage(hDlg, WM_COMMAND, ID_RESET_ACTIVE, 0);
  858. /* alternative: SendMessage(hDlg, WM_COMMAND, ID_RESET_FILE, 0); */
  859. break;
  860. default:
  861. break;
  862. }
  863. return FALSE;
  864. }
  865. struct tstring_input_buf {
  866. unsigned buflen;
  867. char *buffer;
  868. };
  869. static BOOL CALLBACK
  870. InputDlgProc(HWND hDlg, UINT msg, WPARAM wParam, LPARAM lP) {
  871. static struct tstring_input_buf *inBuf = 0;
  872. WORD ctrlId;
  873. switch (msg) {
  874. case WM_CLOSE:
  875. inBuf = 0;
  876. DestroyWindow(hDlg);
  877. break;
  878. case WM_COMMAND:
  879. ctrlId = LOWORD(wParam);
  880. if (ctrlId == IDOK) {
  881. /* Add user */
  882. GetWindowText(GetDlgItem(hDlg, ID_INPUT_LINE), inBuf->buffer,
  883. inBuf->buflen);
  884. if (strlen(inBuf->buffer) > 0) {
  885. EndDialog(hDlg, IDOK);
  886. }
  887. } else if (ctrlId == IDCANCEL) {
  888. EndDialog(hDlg, IDCANCEL);
  889. }
  890. break;
  891. case WM_INITDIALOG:
  892. inBuf = (struct tstring_input_buf *)lP;
  893. assert(inBuf != NULL);
  894. assert((inBuf->buffer != NULL) && (inBuf->buflen != 0));
  895. assert(strlen(inBuf->buffer) < inBuf->buflen);
  896. SendMessage(hDlg, WM_SETICON, (WPARAM)ICON_SMALL, (LPARAM)hIcon);
  897. SendMessage(hDlg, WM_SETICON, (WPARAM)ICON_BIG, (LPARAM)hIcon);
  898. SendDlgItemMessage(hDlg, ID_INPUT_LINE, EM_LIMITTEXT, inBuf->buflen - 1,
  899. 0);
  900. SetWindowText(GetDlgItem(hDlg, ID_INPUT_LINE), inBuf->buffer);
  901. SetWindowText(hDlg, "Modify password");
  902. SetFocus(GetDlgItem(hDlg, ID_INPUT_LINE));
  903. break;
  904. default:
  905. break;
  906. }
  907. return FALSE;
  908. }
  909. void suggest_passwd(char *passwd) {
  910. unsigned u;
  911. char *p;
  912. union {
  913. FILETIME ft;
  914. LARGE_INTEGER li;
  915. } num;
  916. /* valid characters are 32 to 126 */
  917. GetSystemTimeAsFileTime(&num.ft);
  918. num.li.HighPart |= GetCurrentProcessId();
  919. p = passwd;
  920. while (num.li.QuadPart) {
  921. u = (unsigned)(num.li.QuadPart % 95);
  922. num.li.QuadPart -= u;
  923. num.li.QuadPart /= 95;
  924. *p = (char)(u + 32);
  925. p++;
  926. }
  927. }
  928. static void add_control(unsigned char **mem, DLGTEMPLATE *dia, WORD type,
  929. DWORD id, DWORD style, WORD x, WORD y, WORD cx, WORD cy,
  930. const char *caption);
  931. static int get_password(const char *user, const char *realm, char *passwd,
  932. unsigned passwd_len) {
  933. #define HEIGHT (15)
  934. #define WIDTH (280)
  935. #define LABEL_WIDTH (90)
  936. unsigned char mem[4096], *p;
  937. DLGTEMPLATE *dia = (DLGTEMPLATE *)mem;
  938. int ok, y;
  939. struct tstring_input_buf dlgprms = {passwd_len, passwd};
  940. static struct {
  941. DLGTEMPLATE template; /* 18 bytes */
  942. WORD menu, class;
  943. wchar_t caption[1];
  944. WORD fontsiz;
  945. wchar_t fontface[7];
  946. } dialog_header = {{WS_CAPTION | WS_POPUP | WS_SYSMENU | WS_VISIBLE |
  947. DS_SETFONT | WS_DLGFRAME,
  948. WS_EX_TOOLWINDOW, 0, 200, 200, WIDTH, 0},
  949. 0,
  950. 0,
  951. L"",
  952. 8,
  953. L"Tahoma"};
  954. assert((user != NULL) && (realm != NULL) && (passwd != NULL));
  955. if (guard < 100) {
  956. guard += 100;
  957. } else {
  958. return 0;
  959. }
  960. /* Create a password suggestion */
  961. memset(passwd, 0, passwd_len);
  962. suggest_passwd(passwd);
  963. /* Create the dialog */
  964. (void)memset(mem, 0, sizeof(mem));
  965. (void)memcpy(mem, &dialog_header, sizeof(dialog_header));
  966. p = mem + sizeof(dialog_header);
  967. y = HEIGHT;
  968. add_control(&p, dia, 0x82, ID_STATIC, WS_VISIBLE | WS_CHILD, 10, y,
  969. LABEL_WIDTH, HEIGHT, "User:");
  970. add_control(&p, dia, 0x81, ID_CONTROLS + 1,
  971. WS_CHILD | WS_VISIBLE | WS_BORDER | ES_AUTOHSCROLL |
  972. WS_DISABLED,
  973. 15 + LABEL_WIDTH, y, WIDTH - LABEL_WIDTH - 25, HEIGHT, user);
  974. y += HEIGHT;
  975. add_control(&p, dia, 0x82, ID_STATIC, WS_VISIBLE | WS_CHILD, 10, y,
  976. LABEL_WIDTH, HEIGHT, "Realm:");
  977. add_control(&p, dia, 0x81, ID_CONTROLS + 2,
  978. WS_CHILD | WS_VISIBLE | WS_BORDER | ES_AUTOHSCROLL |
  979. WS_DISABLED,
  980. 15 + LABEL_WIDTH, y, WIDTH - LABEL_WIDTH - 25, HEIGHT, realm);
  981. y += HEIGHT;
  982. add_control(&p, dia, 0x82, ID_STATIC, WS_VISIBLE | WS_CHILD, 10, y,
  983. LABEL_WIDTH, HEIGHT, "Password:");
  984. add_control(&p, dia, 0x81, ID_INPUT_LINE,
  985. WS_CHILD | WS_VISIBLE | WS_BORDER | ES_AUTOHSCROLL | WS_TABSTOP,
  986. 15 + LABEL_WIDTH, y, WIDTH - LABEL_WIDTH - 25, HEIGHT, "");
  987. y += (WORD)(HEIGHT * 2);
  988. add_control(&p, dia, 0x80, IDOK,
  989. WS_CHILD | WS_VISIBLE | BS_PUSHBUTTON | WS_TABSTOP, 80, y, 55,
  990. 12, "Ok");
  991. add_control(&p, dia, 0x80, IDCANCEL,
  992. WS_CHILD | WS_VISIBLE | BS_PUSHBUTTON | WS_TABSTOP, 140, y, 55,
  993. 12, "Cancel");
  994. assert((int)p - (int)mem < (int)sizeof(mem));
  995. dia->cy = y + (WORD)(HEIGHT * 1.5);
  996. ok = (IDOK == DialogBoxIndirectParam(NULL, dia, NULL, InputDlgProc,
  997. (LPARAM)&dlgprms));
  998. guard -= 100;
  999. return ok;
  1000. #undef HEIGHT
  1001. #undef WIDTH
  1002. #undef LABEL_WIDTH
  1003. }
  1004. static BOOL CALLBACK
  1005. PasswordDlgProc(HWND hDlg, UINT msg, WPARAM wParam, LPARAM lP) {
  1006. static const char *passfile = 0;
  1007. char domain[256], user[256], password[256];
  1008. WORD ctrlId;
  1009. switch (msg) {
  1010. case WM_CLOSE:
  1011. passfile = 0;
  1012. DestroyWindow(hDlg);
  1013. break;
  1014. case WM_COMMAND:
  1015. ctrlId = LOWORD(wParam);
  1016. if (ctrlId == ID_ADD_USER) {
  1017. /* Add user */
  1018. GetWindowText(GetDlgItem(hDlg, ID_ADD_USER_NAME), user,
  1019. sizeof(user));
  1020. GetWindowText(GetDlgItem(hDlg, ID_ADD_USER_REALM), domain,
  1021. sizeof(domain));
  1022. if (get_password(user, domain, password, sizeof(password))) {
  1023. mg_modify_passwords_file(passfile, domain, user, password);
  1024. EndDialog(hDlg, IDOK);
  1025. }
  1026. } else if ((ctrlId >= (ID_CONTROLS + ID_FILE_BUTTONS_DELTA * 3)) &&
  1027. (ctrlId < (ID_CONTROLS + ID_FILE_BUTTONS_DELTA * 4))) {
  1028. /* Modify password */
  1029. GetWindowText(GetDlgItem(hDlg, ctrlId - ID_FILE_BUTTONS_DELTA * 3),
  1030. user, sizeof(user));
  1031. GetWindowText(GetDlgItem(hDlg, ctrlId - ID_FILE_BUTTONS_DELTA * 2),
  1032. domain, sizeof(domain));
  1033. if (get_password(user, domain, password, sizeof(password))) {
  1034. mg_modify_passwords_file(passfile, domain, user, password);
  1035. EndDialog(hDlg, IDOK);
  1036. }
  1037. } else if ((ctrlId >= (ID_CONTROLS + ID_FILE_BUTTONS_DELTA * 2)) &&
  1038. (ctrlId < (ID_CONTROLS + ID_FILE_BUTTONS_DELTA * 3))) {
  1039. /* Remove user */
  1040. GetWindowText(GetDlgItem(hDlg, ctrlId - ID_FILE_BUTTONS_DELTA * 2),
  1041. user, sizeof(user));
  1042. GetWindowText(GetDlgItem(hDlg, ctrlId - ID_FILE_BUTTONS_DELTA),
  1043. domain, sizeof(domain));
  1044. mg_modify_passwords_file(passfile, domain, user, NULL);
  1045. EndDialog(hDlg, IDOK);
  1046. }
  1047. break;
  1048. case WM_INITDIALOG:
  1049. passfile = (const char *)lP;
  1050. SendMessage(hDlg, WM_SETICON, (WPARAM)ICON_SMALL, (LPARAM)hIcon);
  1051. SendMessage(hDlg, WM_SETICON, (WPARAM)ICON_BIG, (LPARAM)hIcon);
  1052. SetWindowText(hDlg, passfile);
  1053. SetFocus(GetDlgItem(hDlg, ID_ADD_USER_NAME));
  1054. break;
  1055. default:
  1056. break;
  1057. }
  1058. return FALSE;
  1059. }
  1060. static void add_control(unsigned char **mem, DLGTEMPLATE *dia, WORD type,
  1061. DWORD id, DWORD style, WORD x, WORD y, WORD cx, WORD cy,
  1062. const char *caption) {
  1063. DLGITEMTEMPLATE *tp;
  1064. LPWORD p;
  1065. dia->cdit++;
  1066. *mem = align(*mem, 3);
  1067. tp = (DLGITEMTEMPLATE *)*mem;
  1068. tp->id = (WORD)id;
  1069. tp->style = style;
  1070. tp->dwExtendedStyle = 0;
  1071. tp->x = x;
  1072. tp->y = y;
  1073. tp->cx = cx;
  1074. tp->cy = cy;
  1075. p = align(*mem + sizeof(*tp), 1);
  1076. *p++ = 0xffff;
  1077. *p++ = type;
  1078. while (*caption != '\0') {
  1079. *p++ = (WCHAR)*caption++;
  1080. }
  1081. *p++ = 0;
  1082. p = align(p, 1);
  1083. *p++ = 0;
  1084. *mem = (unsigned char *)p;
  1085. }
  1086. static void show_settings_dialog() {
  1087. #define HEIGHT (15)
  1088. #define WIDTH (460)
  1089. #define LABEL_WIDTH (90)
  1090. unsigned char mem[4096], *p;
  1091. const struct mg_option *options;
  1092. DWORD style;
  1093. DLGTEMPLATE *dia = (DLGTEMPLATE *)mem;
  1094. WORD i, cl, x, y, width, nelems = 0;
  1095. static struct {
  1096. DLGTEMPLATE template; /* 18 bytes */
  1097. WORD menu, class;
  1098. wchar_t caption[1];
  1099. WORD fontsiz;
  1100. wchar_t fontface[7];
  1101. } dialog_header = {{WS_CAPTION | WS_POPUP | WS_SYSMENU | WS_VISIBLE |
  1102. DS_SETFONT | WS_DLGFRAME,
  1103. WS_EX_TOOLWINDOW, 0, 200, 200, WIDTH, 0},
  1104. 0,
  1105. 0,
  1106. L"",
  1107. 8,
  1108. L"Tahoma"};
  1109. if (guard == 0) {
  1110. guard++;
  1111. } else {
  1112. return;
  1113. }
  1114. (void)memset(mem, 0, sizeof(mem));
  1115. (void)memcpy(mem, &dialog_header, sizeof(dialog_header));
  1116. p = mem + sizeof(dialog_header);
  1117. options = mg_get_valid_options();
  1118. for (i = 0; options[i].name != NULL; i++) {
  1119. style = WS_CHILD | WS_VISIBLE | WS_TABSTOP;
  1120. x = 10 + (WIDTH / 2) * (nelems % 2);
  1121. y = (nelems / 2 + 1) * HEIGHT + 5;
  1122. width = WIDTH / 2 - 20 - LABEL_WIDTH;
  1123. if (options[i].type == CONFIG_TYPE_NUMBER) {
  1124. style |= ES_NUMBER;
  1125. cl = 0x81;
  1126. style |= WS_BORDER | ES_AUTOHSCROLL;
  1127. } else if (options[i].type == CONFIG_TYPE_BOOLEAN) {
  1128. cl = 0x80;
  1129. style |= BS_AUTOCHECKBOX;
  1130. } else if ((options[i].type == CONFIG_TYPE_FILE) ||
  1131. (options[i].type == CONFIG_TYPE_DIRECTORY)) {
  1132. style |= WS_BORDER | ES_AUTOHSCROLL;
  1133. width -= 20;
  1134. cl = 0x81;
  1135. add_control(&p, dia, 0x80, ID_CONTROLS + i + ID_FILE_BUTTONS_DELTA,
  1136. WS_VISIBLE | WS_CHILD | BS_PUSHBUTTON,
  1137. (WORD)(x + width + LABEL_WIDTH + 5), y, 15, 12, "...");
  1138. } else {
  1139. cl = 0x81;
  1140. style |= WS_BORDER | ES_AUTOHSCROLL;
  1141. }
  1142. add_control(&p, dia, 0x82, ID_STATIC, WS_VISIBLE | WS_CHILD, x, y,
  1143. LABEL_WIDTH, HEIGHT, options[i].name);
  1144. add_control(&p, dia, cl, ID_CONTROLS + i, style,
  1145. (WORD)(x + LABEL_WIDTH), y, width, 12, "");
  1146. nelems++;
  1147. assert(((int)p - (int)mem) < (int)sizeof(mem));
  1148. }
  1149. y = (WORD)(((nelems + 1) / 2 + 1) * HEIGHT + 5);
  1150. add_control(&p, dia, 0x80, ID_GROUP, WS_CHILD | WS_VISIBLE | BS_GROUPBOX, 5,
  1151. 5, WIDTH - 10, y, " Settings ");
  1152. y += 10;
  1153. add_control(&p, dia, 0x80, ID_SAVE,
  1154. WS_CHILD | WS_VISIBLE | BS_PUSHBUTTON | WS_TABSTOP, WIDTH - 70,
  1155. y, 65, 12, "Save Settings");
  1156. add_control(&p, dia, 0x80, ID_RESET_DEFAULTS,
  1157. WS_CHILD | WS_VISIBLE | BS_PUSHBUTTON | WS_TABSTOP, WIDTH - 140,
  1158. y, 65, 12, "Reset to defaults");
  1159. add_control(&p, dia, 0x80, ID_RESET_FILE,
  1160. WS_CHILD | WS_VISIBLE | BS_PUSHBUTTON | WS_TABSTOP, WIDTH - 210,
  1161. y, 65, 12, "Reload from file");
  1162. add_control(&p, dia, 0x80, ID_RESET_ACTIVE,
  1163. WS_CHILD | WS_VISIBLE | BS_PUSHBUTTON | WS_TABSTOP, WIDTH - 280,
  1164. y, 65, 12, "Reload active");
  1165. add_control(&p, dia, 0x82, ID_STATIC, WS_CHILD | WS_VISIBLE | WS_DISABLED,
  1166. 5, y, 100, 12, g_server_base_name);
  1167. assert(((int)p - (int)mem) < (int)sizeof(mem));
  1168. dia->cy = ((nelems + 1) / 2 + 1) * HEIGHT + 30;
  1169. DialogBoxIndirectParam(NULL, dia, NULL, SettingsDlgProc, (LPARAM)NULL);
  1170. guard--;
  1171. #undef HEIGHT
  1172. #undef WIDTH
  1173. #undef LABEL_WIDTH
  1174. }
  1175. static void change_password_file() {
  1176. #define HEIGHT (15)
  1177. #define WIDTH (320)
  1178. #define LABEL_WIDTH (90)
  1179. OPENFILENAME of;
  1180. char path[PATH_MAX] = PASSWORDS_FILE_NAME;
  1181. char strbuf[256], u[256], d[256];
  1182. HWND hDlg = NULL;
  1183. FILE *f;
  1184. int y, nelems;
  1185. unsigned char mem[4096], *p;
  1186. DLGTEMPLATE *dia = (DLGTEMPLATE *)mem;
  1187. const char *domain = mg_get_option(g_ctx, "authentication_domain");
  1188. static struct {
  1189. DLGTEMPLATE template; /* 18 bytes */
  1190. WORD menu, class;
  1191. wchar_t caption[1];
  1192. WORD fontsiz;
  1193. wchar_t fontface[7];
  1194. } dialog_header = {{WS_CAPTION | WS_POPUP | WS_SYSMENU | WS_VISIBLE |
  1195. DS_SETFONT | WS_DLGFRAME,
  1196. WS_EX_TOOLWINDOW, 0, 200, 200, WIDTH, 0},
  1197. 0,
  1198. 0,
  1199. L"",
  1200. 8,
  1201. L"Tahoma"};
  1202. if (guard == 0) {
  1203. guard++;
  1204. } else {
  1205. return;
  1206. }
  1207. memset(&of, 0, sizeof(of));
  1208. of.lStructSize = sizeof(of);
  1209. of.hwndOwner = (HWND)hDlg;
  1210. of.lpstrFile = path;
  1211. of.nMaxFile = sizeof(path);
  1212. of.lpstrInitialDir = mg_get_option(g_ctx, "document_root");
  1213. of.Flags = OFN_CREATEPROMPT | OFN_NOCHANGEDIR | OFN_HIDEREADONLY;
  1214. if (IDOK != GetSaveFileName(&of)) {
  1215. guard--;
  1216. return;
  1217. }
  1218. f = fopen(path, "a+");
  1219. if (f) {
  1220. fclose(f);
  1221. } else {
  1222. MessageBox(NULL, path, "Can not open file", MB_ICONERROR);
  1223. guard--;
  1224. return;
  1225. }
  1226. do {
  1227. (void)memset(mem, 0, sizeof(mem));
  1228. (void)memcpy(mem, &dialog_header, sizeof(dialog_header));
  1229. p = mem + sizeof(dialog_header);
  1230. f = fopen(path, "r+");
  1231. if (!f) {
  1232. MessageBox(NULL, path, "Can not open file", MB_ICONERROR);
  1233. guard--;
  1234. return;
  1235. }
  1236. nelems = 0;
  1237. while (fgets(strbuf, sizeof(strbuf), f)) {
  1238. if (sscanf(strbuf, "%255[^:]:%255[^:]:%*s", u, d) != 2) {
  1239. continue;
  1240. }
  1241. u[255] = 0;
  1242. d[255] = 0;
  1243. y = (nelems + 1) * HEIGHT + 5;
  1244. add_control(&p, dia, 0x80,
  1245. ID_CONTROLS + nelems + ID_FILE_BUTTONS_DELTA * 3,
  1246. WS_CHILD | WS_VISIBLE | BS_PUSHBUTTON | WS_TABSTOP, 10,
  1247. y, 65, 12, "Modify password");
  1248. add_control(&p, dia, 0x80,
  1249. ID_CONTROLS + nelems + ID_FILE_BUTTONS_DELTA * 2,
  1250. WS_CHILD | WS_VISIBLE | BS_PUSHBUTTON | WS_TABSTOP, 80,
  1251. y, 55, 12, "Remove user");
  1252. add_control(&p, dia, 0x81,
  1253. ID_CONTROLS + nelems + ID_FILE_BUTTONS_DELTA,
  1254. WS_CHILD | WS_VISIBLE | WS_BORDER | ES_AUTOHSCROLL |
  1255. WS_DISABLED,
  1256. 245, y, 60, 12, d);
  1257. add_control(&p, dia, 0x81, ID_CONTROLS + nelems,
  1258. WS_CHILD | WS_VISIBLE | WS_BORDER | ES_AUTOHSCROLL |
  1259. WS_DISABLED,
  1260. 140, y, 100, 12, u);
  1261. nelems++;
  1262. assert(((int)p - (int)mem) < (int)sizeof(mem));
  1263. }
  1264. fclose(f);
  1265. y = (WORD)((nelems + 1) * HEIGHT + 10);
  1266. add_control(&p, dia, 0x80, ID_ADD_USER,
  1267. WS_CHILD | WS_VISIBLE | BS_PUSHBUTTON | WS_TABSTOP, 80, y,
  1268. 55, 12, "Add user");
  1269. add_control(&p, dia, 0x81, ID_ADD_USER_NAME,
  1270. WS_CHILD | WS_VISIBLE | WS_BORDER | ES_AUTOHSCROLL |
  1271. WS_TABSTOP,
  1272. 140, y, 100, 12, "");
  1273. add_control(&p, dia, 0x81, ID_ADD_USER_REALM,
  1274. WS_CHILD | WS_VISIBLE | WS_BORDER | ES_AUTOHSCROLL |
  1275. WS_TABSTOP,
  1276. 245, y, 60, 12, domain);
  1277. y = (WORD)((nelems + 2) * HEIGHT + 10);
  1278. add_control(&p, dia, 0x80, ID_GROUP,
  1279. WS_CHILD | WS_VISIBLE | BS_GROUPBOX, 5, 5, WIDTH - 10, y,
  1280. " Users ");
  1281. y += HEIGHT;
  1282. add_control(&p, dia, 0x82, ID_STATIC,
  1283. WS_CHILD | WS_VISIBLE | WS_DISABLED, 5, y, 100, 12,
  1284. g_server_base_name);
  1285. assert(((int)p - (int)mem) < (int)sizeof(mem));
  1286. dia->cy = y + 20;
  1287. } while ((IDOK == DialogBoxIndirectParam(NULL, dia, NULL, PasswordDlgProc,
  1288. (LPARAM)path)) &&
  1289. (!g_exit_flag));
  1290. guard--;
  1291. #undef HEIGHT
  1292. #undef WIDTH
  1293. #undef LABEL_WIDTH
  1294. }
  1295. static int manage_service(int action) {
  1296. static const char *service_name =
  1297. "Civetweb"; /* TODO: check using server_name instead of service_name */
  1298. SC_HANDLE hSCM = NULL, hService = NULL;
  1299. SERVICE_DESCRIPTION descr = {g_server_name};
  1300. char path[PATH_MAX + 20] = ""; /* Path to executable plus magic argument */
  1301. int success = 1;
  1302. if ((hSCM = OpenSCManager(NULL, NULL, action == ID_INSTALL_SERVICE
  1303. ? GENERIC_WRITE
  1304. : GENERIC_READ)) == NULL) {
  1305. success = 0;
  1306. show_error();
  1307. } else if (action == ID_INSTALL_SERVICE) {
  1308. path[sizeof(path) - 1] = 0;
  1309. GetModuleFileName(NULL, path, sizeof(path) - 1);
  1310. strncat(path, " ", sizeof(path) - 1);
  1311. strncat(path, service_magic_argument, sizeof(path) - 1);
  1312. hService = CreateService(hSCM, service_name, service_name,
  1313. SERVICE_ALL_ACCESS, SERVICE_WIN32_OWN_PROCESS,
  1314. SERVICE_AUTO_START, SERVICE_ERROR_NORMAL, path,
  1315. NULL, NULL, NULL, NULL, NULL);
  1316. if (hService) {
  1317. ChangeServiceConfig2(hService, SERVICE_CONFIG_DESCRIPTION, &descr);
  1318. } else {
  1319. show_error();
  1320. }
  1321. } else if (action == ID_REMOVE_SERVICE) {
  1322. if ((hService = OpenService(hSCM, service_name, DELETE)) == NULL ||
  1323. !DeleteService(hService)) {
  1324. show_error();
  1325. }
  1326. } else if ((hService = OpenService(hSCM, service_name,
  1327. SERVICE_QUERY_STATUS)) == NULL) {
  1328. success = 0;
  1329. }
  1330. if (hService)
  1331. CloseServiceHandle(hService);
  1332. if (hSCM)
  1333. CloseServiceHandle(hSCM);
  1334. return success;
  1335. }
  1336. static LRESULT CALLBACK
  1337. WindowProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam) {
  1338. static SERVICE_TABLE_ENTRY service_table[2];
  1339. int service_installed;
  1340. char buf[200], *service_argv[] = {__argv[0], NULL};
  1341. POINT pt;
  1342. HMENU hMenu;
  1343. static UINT s_uTaskbarRestart; /* for taskbar creation */
  1344. memset(service_table, 0, sizeof(service_table));
  1345. service_table[0].lpServiceName = g_server_name;
  1346. service_table[0].lpServiceProc = (LPSERVICE_MAIN_FUNCTION)ServiceMain;
  1347. switch (msg) {
  1348. case WM_CREATE:
  1349. if (__argv[1] != NULL && !strcmp(__argv[1], service_magic_argument)) {
  1350. start_civetweb(1, service_argv);
  1351. StartServiceCtrlDispatcher(service_table);
  1352. exit(EXIT_SUCCESS);
  1353. } else {
  1354. start_civetweb(__argc, __argv);
  1355. s_uTaskbarRestart = RegisterWindowMessage(TEXT("TaskbarCreated"));
  1356. }
  1357. break;
  1358. case WM_COMMAND:
  1359. switch (LOWORD(wParam)) {
  1360. case ID_QUIT:
  1361. stop_civetweb();
  1362. Shell_NotifyIcon(NIM_DELETE, &TrayIcon);
  1363. g_exit_flag = 1;
  1364. PostQuitMessage(0);
  1365. return 0;
  1366. case ID_SETTINGS:
  1367. show_settings_dialog();
  1368. break;
  1369. case ID_PASSWORD:
  1370. change_password_file();
  1371. break;
  1372. case ID_INSTALL_SERVICE:
  1373. case ID_REMOVE_SERVICE:
  1374. manage_service(LOWORD(wParam));
  1375. break;
  1376. case ID_CONNECT:
  1377. printf("[%s]\n", get_url_to_first_open_port(g_ctx));
  1378. ShellExecute(NULL, "open", get_url_to_first_open_port(g_ctx), NULL,
  1379. NULL, SW_SHOW);
  1380. break;
  1381. }
  1382. break;
  1383. case WM_USER:
  1384. switch (lParam) {
  1385. case WM_RBUTTONUP:
  1386. case WM_LBUTTONUP:
  1387. case WM_LBUTTONDBLCLK:
  1388. hMenu = CreatePopupMenu();
  1389. AppendMenu(hMenu, MF_STRING | MF_GRAYED, ID_SEPARATOR,
  1390. g_server_name);
  1391. AppendMenu(hMenu, MF_SEPARATOR, ID_SEPARATOR, "");
  1392. service_installed = manage_service(0);
  1393. snprintf(buf, sizeof(buf) - 1, "NT service: %s installed",
  1394. service_installed ? "" : "not");
  1395. buf[sizeof(buf) - 1] = 0;
  1396. AppendMenu(hMenu, MF_STRING | MF_GRAYED, ID_SEPARATOR, buf);
  1397. AppendMenu(hMenu, MF_STRING | (service_installed ? MF_GRAYED : 0),
  1398. ID_INSTALL_SERVICE, "Install service");
  1399. AppendMenu(hMenu, MF_STRING | (!service_installed ? MF_GRAYED : 0),
  1400. ID_REMOVE_SERVICE, "Deinstall service");
  1401. AppendMenu(hMenu, MF_SEPARATOR, ID_SEPARATOR, "");
  1402. AppendMenu(hMenu, MF_STRING, ID_CONNECT, "Start browser");
  1403. AppendMenu(hMenu, MF_STRING, ID_SETTINGS, "Edit settings");
  1404. AppendMenu(hMenu, MF_STRING, ID_PASSWORD, "Modify password file");
  1405. AppendMenu(hMenu, MF_SEPARATOR, ID_SEPARATOR, "");
  1406. AppendMenu(hMenu, MF_STRING, ID_QUIT, "Exit");
  1407. GetCursorPos(&pt);
  1408. SetForegroundWindow(hWnd);
  1409. TrackPopupMenu(hMenu, 0, pt.x, pt.y, 0, hWnd, NULL);
  1410. PostMessage(hWnd, WM_NULL, 0, 0);
  1411. DestroyMenu(hMenu);
  1412. break;
  1413. }
  1414. break;
  1415. case WM_CLOSE:
  1416. stop_civetweb();
  1417. Shell_NotifyIcon(NIM_DELETE, &TrayIcon);
  1418. g_exit_flag = 1;
  1419. PostQuitMessage(0);
  1420. return 0; /* We've just sent our own quit message, with proper hwnd. */
  1421. default:
  1422. if (msg == s_uTaskbarRestart)
  1423. Shell_NotifyIcon(NIM_ADD, &TrayIcon);
  1424. }
  1425. return DefWindowProc(hWnd, msg, wParam, lParam);
  1426. }
  1427. static int MakeConsole() {
  1428. DWORD err;
  1429. int ok = (GetConsoleWindow() != NULL);
  1430. if (!ok) {
  1431. if (!AttachConsole(ATTACH_PARENT_PROCESS)) {
  1432. FreeConsole();
  1433. if (!AllocConsole()) {
  1434. err = GetLastError();
  1435. if (err == ERROR_ACCESS_DENIED) {
  1436. MessageBox(NULL,
  1437. "Insufficient rights to create a console window",
  1438. "Error", MB_ICONERROR);
  1439. }
  1440. }
  1441. AttachConsole(GetCurrentProcessId());
  1442. }
  1443. ok = (GetConsoleWindow() != NULL);
  1444. if (ok) {
  1445. freopen("CONIN$", "r", stdin);
  1446. freopen("CONOUT$", "w", stdout);
  1447. freopen("CONOUT$", "w", stderr);
  1448. }
  1449. }
  1450. if (ok) {
  1451. SetConsoleTitle(g_server_name);
  1452. }
  1453. return ok;
  1454. }
  1455. int WINAPI WinMain(HINSTANCE hInst, HINSTANCE hPrev, LPSTR cmdline, int show) {
  1456. WNDCLASS cls;
  1457. HWND hWnd;
  1458. MSG msg;
  1459. (void)hInst;
  1460. (void)hPrev;
  1461. (void)cmdline;
  1462. (void)show;
  1463. init_server_name((int)__argc, (const char **)__argv);
  1464. memset(&cls, 0, sizeof(cls));
  1465. cls.lpfnWndProc = (WNDPROC)WindowProc;
  1466. cls.hIcon = LoadIcon(NULL, IDI_APPLICATION);
  1467. cls.lpszClassName = g_server_base_name;
  1468. RegisterClass(&cls);
  1469. hWnd = CreateWindow(cls.lpszClassName, g_server_name, WS_OVERLAPPEDWINDOW,
  1470. 0, 0, 0, 0, NULL, NULL, NULL, NULL);
  1471. ShowWindow(hWnd, SW_HIDE);
  1472. if (g_icon_name) {
  1473. hIcon =
  1474. LoadImage(NULL, g_icon_name, IMAGE_ICON, 16, 16, LR_LOADFROMFILE);
  1475. } else {
  1476. hIcon = LoadImage(GetModuleHandle(NULL), MAKEINTRESOURCE(ID_ICON),
  1477. IMAGE_ICON, 16, 16, 0);
  1478. }
  1479. TrayIcon.cbSize = sizeof(TrayIcon);
  1480. TrayIcon.uID = ID_ICON;
  1481. TrayIcon.uFlags = NIF_ICON | NIF_MESSAGE | NIF_TIP;
  1482. TrayIcon.hIcon = hIcon;
  1483. TrayIcon.hWnd = hWnd;
  1484. snprintf(TrayIcon.szTip, sizeof(TrayIcon.szTip), "%s", g_server_name);
  1485. TrayIcon.uCallbackMessage = WM_USER;
  1486. Shell_NotifyIcon(NIM_ADD, &TrayIcon);
  1487. while (GetMessage(&msg, hWnd, 0, 0) > 0) {
  1488. TranslateMessage(&msg);
  1489. DispatchMessage(&msg);
  1490. }
  1491. /* Return the WM_QUIT value. */
  1492. return (int)msg.wParam;
  1493. }
  1494. #if defined(CONSOLE)
  1495. void main(void) { WinMain(0, 0, 0, 0); }
  1496. #endif
  1497. #elif defined(USE_COCOA)
  1498. #import <Cocoa/Cocoa.h>
  1499. @interface Civetweb : NSObject <NSApplicationDelegate>
  1500. - (void)openBrowser;
  1501. - (void)shutDown;
  1502. @end
  1503. @implementation Civetweb
  1504. - (void)openBrowser {
  1505. [[NSWorkspace sharedWorkspace]
  1506. openURL:[NSURL URLWithString:[NSString stringWithUTF8String:
  1507. get_url_to_first_open_port(
  1508. g_ctx)]]];
  1509. }
  1510. - (void)editConfig {
  1511. create_config_file(g_ctx, g_config_file);
  1512. [[NSWorkspace sharedWorkspace]
  1513. openFile:[NSString stringWithUTF8String:g_config_file]
  1514. withApplication:@"TextEdit"];
  1515. }
  1516. - (void)shutDown {
  1517. [NSApp terminate:nil];
  1518. }
  1519. @end
  1520. int main(int argc, char *argv[]) {
  1521. init_server_name(argc, (const char **)argv);
  1522. start_civetweb(argc, argv);
  1523. [NSAutoreleasePool new];
  1524. [NSApplication sharedApplication];
  1525. /* Add delegate to process menu item actions */
  1526. Civetweb *myDelegate = [[Civetweb alloc] autorelease];
  1527. [NSApp setDelegate:myDelegate];
  1528. /* Run this app as agent */
  1529. ProcessSerialNumber psn = {0, kCurrentProcess};
  1530. TransformProcessType(&psn, kProcessTransformToBackgroundApplication);
  1531. SetFrontProcess(&psn);
  1532. /* Add status bar menu */
  1533. id menu = [[NSMenu new] autorelease];
  1534. /* Add version menu item */
  1535. [menu
  1536. addItem:
  1537. [[[NSMenuItem alloc]
  1538. /*initWithTitle:[NSString stringWithFormat:@"%s", server_name]*/
  1539. initWithTitle:[NSString stringWithUTF8String:g_server_name]
  1540. action:@selector(noexist)
  1541. keyEquivalent:@""] autorelease]];
  1542. /* Add configuration menu item */
  1543. [menu addItem:[[[NSMenuItem alloc] initWithTitle:@"Edit configuration"
  1544. action:@selector(editConfig)
  1545. keyEquivalent:@""] autorelease]];
  1546. /* Add connect menu item */
  1547. [menu
  1548. addItem:[[[NSMenuItem alloc] initWithTitle:@"Open web root in a browser"
  1549. action:@selector(openBrowser)
  1550. keyEquivalent:@""] autorelease]];
  1551. /* Separator */
  1552. [menu addItem:[NSMenuItem separatorItem]];
  1553. /* Add quit menu item */
  1554. [menu addItem:[[[NSMenuItem alloc] initWithTitle:@"Quit"
  1555. action:@selector(shutDown)
  1556. keyEquivalent:@"q"] autorelease]];
  1557. /* Attach menu to the status bar */
  1558. id item = [[[NSStatusBar systemStatusBar]
  1559. statusItemWithLength:NSVariableStatusItemLength] retain];
  1560. [item setHighlightMode:YES];
  1561. [item setImage:[NSImage imageNamed:@"civetweb_22x22.png"]];
  1562. [item setMenu:menu];
  1563. /* Run the app */
  1564. [NSApp activateIgnoringOtherApps:YES];
  1565. [NSApp run];
  1566. stop_civetweb(g_ctx);
  1567. return EXIT_SUCCESS;
  1568. }
  1569. #else
  1570. int main(int argc, char *argv[]) {
  1571. init_server_name(argc, (const char **)argv);
  1572. start_civetweb(argc, argv);
  1573. printf("%s started on port(s) %s with web root [%s]\n", g_server_name,
  1574. mg_get_option(g_ctx, "listening_ports"),
  1575. mg_get_option(g_ctx, "document_root"));
  1576. while (g_exit_flag == 0) {
  1577. sleep(1);
  1578. }
  1579. printf("Exiting on signal %d, waiting for all threads to finish...",
  1580. g_exit_flag);
  1581. fflush(stdout);
  1582. stop_civetweb();
  1583. printf("%s", " done.\n");
  1584. return EXIT_SUCCESS;
  1585. }
  1586. #endif /* _WIN32 */