main.c 51 KB

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