main.c 56 KB

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