main.c 56 KB

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