main.c 62 KB

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