main.c 61 KB

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