main.c 77 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107
  1. /* Copyright (c) 2013-2017 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. #elif defined(__GNUC__)
  50. #define NO_RETURN __attribute((noreturn))
  51. #else
  52. #define NO_RETURN
  53. #endif
  54. /* Use same defines as in civetweb.c before including system headers. */
  55. #ifndef _LARGEFILE_SOURCE
  56. #define _LARGEFILE_SOURCE /* For fseeko(), ftello() */
  57. #endif
  58. #ifndef _FILE_OFFSET_BITS
  59. #define _FILE_OFFSET_BITS 64 /* Use 64-bit file offsets by default */
  60. #endif
  61. #ifndef __STDC_FORMAT_MACROS
  62. #define __STDC_FORMAT_MACROS /* <inttypes.h> wants this for C++ */
  63. #endif
  64. #ifndef __STDC_LIMIT_MACROS
  65. #define __STDC_LIMIT_MACROS /* C++ wants that for INT64_MAX */
  66. #endif
  67. #include <string.h>
  68. #include <errno.h>
  69. #include <sys/stat.h>
  70. #include <stdio.h>
  71. #include <stdint.h>
  72. #include <limits.h>
  73. #include <stdlib.h>
  74. #include <signal.h>
  75. #include <stddef.h>
  76. #include <stdarg.h>
  77. #include <ctype.h>
  78. #include "civetweb.h"
  79. #define printf \
  80. DO_NOT_USE_THIS_FUNCTION__USE_fprintf /* Required for unit testing */
  81. #if defined(_WIN32) \
  82. && !defined(__SYMBIAN32__) /* WINDOWS / UNIX include block */
  83. #ifndef _WIN32_WINNT
  84. #define _WIN32_WINNT 0x0501 /* for tdm-gcc so we can use getconsolewindow */
  85. #endif
  86. #undef UNICODE
  87. #include <windows.h>
  88. #include <winsvc.h>
  89. #include <shlobj.h>
  90. #include <io.h>
  91. #define getcwd(a, b) (_getcwd(a, b))
  92. #if !defined(__MINGW32__)
  93. extern char *_getcwd(char *buf, size_t size);
  94. #endif
  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. #if !defined(DEBUG_ASSERT)
  118. #if defined(DEBUG)
  119. #if defined(_MSC_VER)
  120. /* DEBUG_ASSERT has some const conditions */
  121. #pragma warning(disable : 4127)
  122. #endif
  123. #define DEBUG_ASSERT(cond) \
  124. do { \
  125. if (!(cond)) { \
  126. fprintf(stderr, "ASSERTION FAILED: %s", #cond); \
  127. exit(2); /* Exit with error */ \
  128. } \
  129. } while (0)
  130. #else
  131. #define DEBUG_ASSERT(cond)
  132. #endif /* DEBUG */
  133. #endif
  134. #ifndef PATH_MAX
  135. #define PATH_MAX (1024)
  136. #endif
  137. #define MAX_OPTIONS (50)
  138. #define MAX_CONF_FILE_LINE_SIZE (8 * 1024)
  139. struct tuser_data {
  140. char *first_message;
  141. };
  142. static int g_exit_flag = 0; /* Main loop should exit */
  143. static char g_server_base_name[40]; /* Set by init_server_name() */
  144. static const char *g_server_name; /* Default from init_server_name,
  145. * updated later from the server config */
  146. static const char *g_icon_name; /* Default from init_server_name,
  147. * updated later from the server config */
  148. static const char *g_website; /* Default from init_server_name,
  149. * updated later from the server config */
  150. static int g_num_add_domains; /* Default from init_server_name,
  151. * updated later from the server config */
  152. static const char **g_add_domain; /* Default from init_server_name,
  153. * updated later from the server config */
  154. static char *g_system_info; /* Set by init_system_info() */
  155. static char g_config_file_name[PATH_MAX] = ""; /* Set by
  156. * process_command_line_arguments() */
  157. static struct mg_context *g_ctx; /* Set by start_civetweb() */
  158. static struct tuser_data
  159. g_user_data; /* Passed to mg_start() by start_civetweb() */
  160. #if !defined(CONFIG_FILE)
  161. #define CONFIG_FILE "civetweb.conf"
  162. #endif /* !CONFIG_FILE */
  163. #if !defined(PASSWORDS_FILE_NAME)
  164. #define PASSWORDS_FILE_NAME ".htpasswd"
  165. #endif
  166. /* backup config file */
  167. #if !defined(CONFIG_FILE2) && defined(__linux__)
  168. #define CONFIG_FILE2 "/usr/local/etc/civetweb.conf"
  169. #endif
  170. enum {
  171. OPTION_TITLE,
  172. OPTION_ICON,
  173. OPTION_WEBPAGE,
  174. OPTION_ADD_DOMAIN,
  175. NUM_MAIN_OPTIONS
  176. };
  177. static struct mg_option main_config_options[] = {
  178. {"title", MG_CONFIG_TYPE_STRING, NULL},
  179. {"icon", MG_CONFIG_TYPE_STRING, NULL},
  180. {"website", MG_CONFIG_TYPE_STRING, NULL},
  181. {"add_domain", MG_CONFIG_TYPE_STRING_LIST, NULL},
  182. {NULL, MG_CONFIG_TYPE_UNKNOWN, NULL}};
  183. static void WINCDECL
  184. signal_handler(int sig_num)
  185. {
  186. g_exit_flag = sig_num;
  187. }
  188. static NO_RETURN void
  189. die(const char *fmt, ...)
  190. {
  191. va_list ap;
  192. char msg[512] = "";
  193. va_start(ap, fmt);
  194. (void)vsnprintf(msg, sizeof(msg) - 1, fmt, ap);
  195. msg[sizeof(msg) - 1] = 0;
  196. va_end(ap);
  197. #if defined(_WIN32)
  198. MessageBox(NULL, msg, "Error", MB_OK);
  199. #else
  200. fprintf(stderr, "%s\n", msg);
  201. #endif
  202. exit(EXIT_FAILURE);
  203. }
  204. #ifdef WIN32
  205. static int MakeConsole(void);
  206. #endif
  207. static void
  208. show_server_name(void)
  209. {
  210. #ifdef WIN32
  211. (void)MakeConsole();
  212. #endif
  213. fprintf(stderr, "CivetWeb v%s, built on %s\n", mg_version(), __DATE__);
  214. }
  215. static NO_RETURN void
  216. show_usage_and_exit(const char *exeName)
  217. {
  218. const struct mg_option *options;
  219. int i;
  220. if (exeName == 0 || *exeName == 0) {
  221. exeName = "civetweb";
  222. }
  223. show_server_name();
  224. fprintf(stderr, "\nUsage:\n");
  225. fprintf(stderr, " Start server with a set of options:\n");
  226. fprintf(stderr, " %s [config_file]\n", exeName);
  227. fprintf(stderr, " %s [-option value ...]\n", exeName);
  228. fprintf(stderr, " Run as client:\n");
  229. fprintf(stderr, " %s -C\n", exeName);
  230. fprintf(stderr, " Show system information:\n");
  231. fprintf(stderr, " %s -I\n", exeName);
  232. fprintf(stderr, " Add user/change password:\n");
  233. fprintf(stderr,
  234. " %s -A <htpasswd_file> <realm> <user> <passwd>\n",
  235. exeName);
  236. fprintf(stderr, " Remove user:\n");
  237. fprintf(stderr, " %s -R <htpasswd_file> <realm> <user>\n", exeName);
  238. fprintf(stderr, "\nOPTIONS:\n");
  239. options = mg_get_valid_options();
  240. for (i = 0; options[i].name != NULL; i++) {
  241. fprintf(stderr,
  242. " -%s %s\n",
  243. options[i].name,
  244. ((options[i].default_value == NULL)
  245. ? "<empty>"
  246. : options[i].default_value));
  247. }
  248. options = main_config_options;
  249. for (i = 0; options[i].name != NULL; i++) {
  250. fprintf(stderr,
  251. " -%s %s\n",
  252. options[i].name,
  253. ((options[i].default_value == NULL)
  254. ? "<empty>"
  255. : options[i].default_value));
  256. }
  257. exit(EXIT_FAILURE);
  258. }
  259. #if defined(_WIN32) || defined(USE_COCOA)
  260. static const char *config_file_top_comment =
  261. "# CivetWeb web server configuration file.\n"
  262. "# For detailed description of every option, visit\n"
  263. "# https://github.com/civetweb/civetweb/blob/master/docs/UserManual.md\n"
  264. "# Lines starting with '#' and empty lines are ignored.\n"
  265. "# To make a change, remove leading '#', modify option's value,\n"
  266. "# save this file and then restart Civetweb.\n\n";
  267. static const char *
  268. get_url_to_first_open_port(const struct mg_context *ctx)
  269. {
  270. static char url[100];
  271. const char *open_ports = mg_get_option(ctx, "listening_ports");
  272. int a, b, c, d, port, n;
  273. if (sscanf(open_ports, "%d.%d.%d.%d:%d%n", &a, &b, &c, &d, &port, &n)
  274. == 5) {
  275. snprintf(url,
  276. sizeof(url),
  277. "%s://%d.%d.%d.%d:%d",
  278. open_ports[n] == 's' ? "https" : "http",
  279. a,
  280. b,
  281. c,
  282. d,
  283. port);
  284. } else if (sscanf(open_ports, "%d%n", &port, &n) == 1) {
  285. snprintf(url,
  286. sizeof(url),
  287. "%s://localhost:%d",
  288. open_ports[n] == 's' ? "https" : "http",
  289. port);
  290. } else {
  291. snprintf(url, sizeof(url), "%s", "http://localhost:8080");
  292. }
  293. return url;
  294. }
  295. #ifdef ENABLE_CREATE_CONFIG_FILE
  296. static void
  297. create_config_file(const struct mg_context *ctx, const char *path)
  298. {
  299. const struct mg_option *options;
  300. const char *value;
  301. FILE *fp;
  302. int i;
  303. /* Create config file if it is not present yet */
  304. if ((fp = fopen(path, "r")) != NULL) {
  305. fclose(fp);
  306. } else if ((fp = fopen(path, "a+")) != NULL) {
  307. fprintf(fp, "%s", config_file_top_comment);
  308. options = mg_get_valid_options();
  309. for (i = 0; options[i].name != NULL; i++) {
  310. value = mg_get_option(ctx, options[i].name);
  311. fprintf(fp,
  312. "# %s %s\n",
  313. options[i].name,
  314. value ? value : "<value>");
  315. }
  316. fclose(fp);
  317. }
  318. }
  319. #endif
  320. #endif
  321. static char *
  322. sdup(const char *str)
  323. {
  324. size_t len;
  325. char *p;
  326. len = strlen(str) + 1;
  327. p = (char *)malloc(len);
  328. if (p == NULL) {
  329. die("Cannot allocate %u bytes", (unsigned)len);
  330. }
  331. memcpy(p, str, len);
  332. return p;
  333. }
  334. #if 0 /* Unused code from "string duplicate with escape" */
  335. static unsigned
  336. hex2dec(char x)
  337. {
  338. if ((x >= '0') && (x <= '9')) {
  339. return (unsigned)x - (unsigned)'0';
  340. }
  341. if ((x >= 'A') && (x <= 'F')) {
  342. return (unsigned)x - (unsigned)'A' + 10u;
  343. }
  344. if ((x >= 'a') && (x <= 'f')) {
  345. return (unsigned)x - (unsigned)'a' + 10u;
  346. }
  347. return 0;
  348. }
  349. static char *
  350. sdupesc(const char *str)
  351. {
  352. char *p = sdup(str);
  353. if (p) {
  354. char *d = p;
  355. while ((d = strchr(d, '\\')) != NULL) {
  356. switch (d[1]) {
  357. case 'a':
  358. d[0] = '\a';
  359. memmove(d + 1, d + 2, strlen(d + 1));
  360. break;
  361. case 'b':
  362. d[0] = '\b';
  363. memmove(d + 1, d + 2, strlen(d + 1));
  364. break;
  365. case 'e':
  366. d[0] = 27;
  367. memmove(d + 1, d + 2, strlen(d + 1));
  368. break;
  369. case 'f':
  370. d[0] = '\f';
  371. memmove(d + 1, d + 2, strlen(d + 1));
  372. break;
  373. case 'n':
  374. d[0] = '\n';
  375. memmove(d + 1, d + 2, strlen(d + 1));
  376. break;
  377. case 'r':
  378. d[0] = '\r';
  379. memmove(d + 1, d + 2, strlen(d + 1));
  380. break;
  381. case 't':
  382. d[0] = '\t';
  383. memmove(d + 1, d + 2, strlen(d + 1));
  384. break;
  385. case 'u':
  386. if (isxdigit(d[2]) && isxdigit(d[3]) && isxdigit(d[4])
  387. && isxdigit(d[5])) {
  388. unsigned short u = (unsigned short)(hex2dec(d[2]) * 4096
  389. + hex2dec(d[3]) * 256
  390. + hex2dec(d[4]) * 16
  391. + hex2dec(d[5]));
  392. char mbc[16];
  393. int mbl = wctomb(mbc, (wchar_t)u);
  394. if ((mbl > 0) && (mbl < 6)) {
  395. memcpy(d, mbc, (unsigned)mbl);
  396. memmove(d + mbl, d + 6, strlen(d + 5));
  397. /* Advance mbl characters (+1 is below) */
  398. d += (mbl - 1);
  399. } else {
  400. /* Invalid multi byte character */
  401. /* TODO: define what to do */
  402. }
  403. } else {
  404. /* Invalid esc sequence */
  405. /* TODO: define what to do */
  406. }
  407. break;
  408. case 'v':
  409. d[0] = '\v';
  410. memmove(d + 1, d + 2, strlen(d + 1));
  411. break;
  412. case 'x':
  413. if (isxdigit(d[2]) && isxdigit(d[3])) {
  414. d[0] = (char)((unsigned char)(hex2dec(d[2]) * 16
  415. + hex2dec(d[3])));
  416. memmove(d + 1, d + 4, strlen(d + 3));
  417. } else {
  418. /* Invalid esc sequence */
  419. /* TODO: define what to do */
  420. }
  421. break;
  422. case 'z':
  423. d[0] = 0;
  424. memmove(d + 1, d + 2, strlen(d + 1));
  425. break;
  426. case '\\':
  427. d[0] = '\\';
  428. memmove(d + 1, d + 2, strlen(d + 1));
  429. break;
  430. case '\'':
  431. d[0] = '\'';
  432. memmove(d + 1, d + 2, strlen(d + 1));
  433. break;
  434. case '\"':
  435. d[0] = '\"';
  436. memmove(d + 1, d + 2, strlen(d + 1));
  437. break;
  438. case 0:
  439. if (d == p) {
  440. /* Line is only \ */
  441. free(p);
  442. return NULL;
  443. }
  444. /* no break */
  445. default:
  446. /* invalid ESC sequence */
  447. /* TODO: define what to do */
  448. break;
  449. }
  450. /* Advance to next character */
  451. d++;
  452. }
  453. }
  454. return p;
  455. }
  456. #endif
  457. static const char *
  458. get_option(char **options, const char *option_name)
  459. {
  460. int i = 0;
  461. const char *opt_value = NULL;
  462. /* TODO (low, api makeover): options should be an array of key-value-pairs,
  463. * like
  464. * struct {const char * key, const char * value} options[]
  465. * but it currently is an array with
  466. * options[2*i] = key, options[2*i + 1] = value
  467. * (probably with a MG_LEGACY_INTERFACE definition)
  468. */
  469. while (options[2 * i] != NULL) {
  470. if (strcmp(options[2 * i], option_name) == 0) {
  471. opt_value = options[2 * i + 1];
  472. break;
  473. }
  474. i++;
  475. }
  476. return opt_value;
  477. }
  478. static int
  479. set_option(char **options, const char *name, const char *value)
  480. {
  481. int i, type;
  482. const struct mg_option *default_options = mg_get_valid_options();
  483. const char *multi_sep = NULL;
  484. for (i = 0; main_config_options[i].name != NULL; i++) {
  485. /* These options are evaluated by main.c, not civetweb.c.
  486. * Do not add it to options, and return OK */
  487. if (!strcmp(name, main_config_options[OPTION_TITLE].name)) {
  488. g_server_name = sdup(value);
  489. return 1;
  490. }
  491. if (!strcmp(name, main_config_options[OPTION_ICON].name)) {
  492. g_icon_name = sdup(value);
  493. return 1;
  494. }
  495. if (!strcmp(name, main_config_options[OPTION_WEBPAGE].name)) {
  496. g_website = sdup(value);
  497. return 1;
  498. }
  499. if (!strcmp(name, main_config_options[OPTION_ADD_DOMAIN].name)) {
  500. if (g_num_add_domains > 0) {
  501. g_add_domain = (const char **)realloc(
  502. (void *)g_add_domain,
  503. sizeof(char *) * ((unsigned)g_num_add_domains + 1u));
  504. if (!g_add_domain) {
  505. die("Out of memory");
  506. }
  507. g_add_domain[g_num_add_domains] = sdup(value);
  508. g_num_add_domains++;
  509. } else {
  510. g_add_domain = (const char **)malloc(sizeof(char *));
  511. if (!g_add_domain) {
  512. die("Out of memory");
  513. }
  514. g_add_domain[0] = sdup(value);
  515. g_num_add_domains = 1;
  516. }
  517. return 1;
  518. }
  519. }
  520. /* Not an option of main.c, so check if it is a CivetWeb server option */
  521. type = MG_CONFIG_TYPE_UNKNOWN;
  522. for (i = 0; default_options[i].name != NULL; i++) {
  523. if (!strcmp(default_options[i].name, name)) {
  524. type = default_options[i].type;
  525. }
  526. }
  527. switch (type) {
  528. case MG_CONFIG_TYPE_UNKNOWN:
  529. /* unknown option */
  530. return 0;
  531. case MG_CONFIG_TYPE_NUMBER:
  532. /* integer number >= 0, e.g. number of threads */
  533. if (atol(value) < 0) {
  534. /* invalid number */
  535. return 0;
  536. }
  537. break;
  538. case MG_CONFIG_TYPE_STRING:
  539. /* any text */
  540. break;
  541. case MG_CONFIG_TYPE_STRING_LIST:
  542. /* list of text items, separated by , */
  543. multi_sep = ",";
  544. break;
  545. case MG_CONFIG_TYPE_STRING_MULTILINE:
  546. /* lines of text, separated by carriage return line feed */
  547. multi_sep = "\r\n";
  548. break;
  549. case MG_CONFIG_TYPE_BOOLEAN:
  550. /* boolean value, yes or no */
  551. if ((0 != strcmp(value, "yes")) && (0 != strcmp(value, "no"))) {
  552. /* invalid boolean */
  553. return 0;
  554. }
  555. break;
  556. case MG_CONFIG_TYPE_YES_NO_OPTIONAL:
  557. /* boolean value, yes or no */
  558. if ((0 != strcmp(value, "yes")) && (0 != strcmp(value, "no"))
  559. && (0 != strcmp(value, "optional"))) {
  560. /* invalid boolean */
  561. return 0;
  562. }
  563. break;
  564. case MG_CONFIG_TYPE_FILE:
  565. case MG_CONFIG_TYPE_DIRECTORY:
  566. /* TODO (low): check this option when it is set, instead of calling
  567. * verify_existence later */
  568. break;
  569. case MG_CONFIG_TYPE_EXT_PATTERN:
  570. /* list of patterns, separated by | */
  571. multi_sep = "|";
  572. break;
  573. default:
  574. die("Unknown option type - option %s", name);
  575. }
  576. for (i = 0; i < MAX_OPTIONS; i++) {
  577. if (options[2 * i] == NULL) {
  578. /* Option not set yet. Add new option */
  579. options[2 * i] = sdup(name);
  580. options[2 * i + 1] = sdup(value);
  581. options[2 * i + 2] = NULL;
  582. break;
  583. } else if (!strcmp(options[2 * i], name)) {
  584. if (multi_sep) {
  585. /* Option already set. Overwrite */
  586. char *s = malloc(strlen(options[2 * i + 1]) + strlen(multi_sep)
  587. + strlen(value) + 1);
  588. if (!s) {
  589. die("Out of memory");
  590. }
  591. sprintf(s, "%s%s%s", options[2 * i + 1], multi_sep, value);
  592. free(options[2 * i + 1]);
  593. options[2 * i + 1] = s;
  594. } else {
  595. /* Option already set. Overwrite */
  596. free(options[2 * i + 1]);
  597. options[2 * i + 1] = sdup(value);
  598. }
  599. break;
  600. }
  601. }
  602. if (i == MAX_OPTIONS) {
  603. die("Too many options specified");
  604. }
  605. if (options[2 * i] == NULL) {
  606. die("Out of memory");
  607. }
  608. if (options[2 * i + 1] == NULL) {
  609. die("Illegal escape sequence, or out of memory");
  610. }
  611. /* option set correctly */
  612. return 1;
  613. }
  614. static int
  615. read_config_file(const char *config_file, char **options)
  616. {
  617. char line[MAX_CONF_FILE_LINE_SIZE], *p;
  618. FILE *fp = NULL;
  619. size_t i, j, line_no = 0;
  620. /* Open the config file */
  621. fp = fopen(config_file, "r");
  622. if (fp == NULL) {
  623. /* Failed to open the file. Keep errno for the caller. */
  624. return 0;
  625. }
  626. /* Load config file settings first */
  627. if (fp != NULL) {
  628. fprintf(stdout, "Loading config file %s\n", config_file);
  629. /* Loop over the lines in config file */
  630. while (fgets(line, sizeof(line), fp) != NULL) {
  631. if (!line_no && !memcmp(line, "\xEF\xBB\xBF", 3)) {
  632. /* strip UTF-8 BOM */
  633. p = line + 3;
  634. } else {
  635. p = line;
  636. }
  637. line_no++;
  638. /* Ignore empty lines and comments */
  639. for (i = 0; isspace(*(unsigned char *)&line[i]);)
  640. i++;
  641. if (p[i] == '#' || p[i] == '\0') {
  642. continue;
  643. }
  644. /* Skip spaces, \r and \n at the end of the line */
  645. for (j = strlen(line) - 1;
  646. isspace(*(unsigned char *)&line[j])
  647. || iscntrl(*(unsigned char *)&line[j]);)
  648. line[j--] = 0;
  649. /* Find the space character between option name and value */
  650. for (j = i; !isspace(*(unsigned char *)&line[j]) && (line[j] != 0);)
  651. j++;
  652. /* Terminate the string - then the string at (line+i) contains the
  653. * option name */
  654. line[j] = 0;
  655. j++;
  656. /* Trim additional spaces between option name and value - then
  657. * (line+j) contains the option value */
  658. while (isspace(line[j])) {
  659. j++;
  660. }
  661. /* Set option */
  662. if (!set_option(options, line + i, line + j)) {
  663. fprintf(stderr,
  664. "%s: line %d is invalid, ignoring it:\n %s",
  665. config_file,
  666. (int)line_no,
  667. p);
  668. }
  669. }
  670. (void)fclose(fp);
  671. }
  672. return 1;
  673. }
  674. static void
  675. process_command_line_arguments(int argc, char *argv[], char **options)
  676. {
  677. char *p;
  678. size_t i, cmd_line_opts_start = 1;
  679. #ifdef CONFIG_FILE2
  680. FILE *fp = NULL;
  681. #endif
  682. /* Should we use a config file ? */
  683. if ((argc > 1) && (argv[1] != NULL) && (argv[1][0] != '-')
  684. && (argv[1][0] != 0)) {
  685. /* The first command line parameter is a config file name. */
  686. snprintf(g_config_file_name,
  687. sizeof(g_config_file_name) - 1,
  688. "%s",
  689. argv[1]);
  690. cmd_line_opts_start = 2;
  691. } else if ((p = strrchr(argv[0], DIRSEP)) == NULL) {
  692. /* No config file set. No path in arg[0] found.
  693. * Use default file name in the current path. */
  694. snprintf(g_config_file_name,
  695. sizeof(g_config_file_name) - 1,
  696. "%s",
  697. CONFIG_FILE);
  698. } else {
  699. /* No config file set. Path to exe found in arg[0].
  700. * Use default file name next to the executable. */
  701. snprintf(g_config_file_name,
  702. sizeof(g_config_file_name) - 1,
  703. "%.*s%c%s",
  704. (int)(p - argv[0]),
  705. argv[0],
  706. DIRSEP,
  707. CONFIG_FILE);
  708. }
  709. g_config_file_name[sizeof(g_config_file_name) - 1] = 0;
  710. #ifdef CONFIG_FILE2
  711. fp = fopen(g_config_file_name, "r");
  712. /* try alternate config file */
  713. if (fp == NULL) {
  714. fp = fopen(CONFIG_FILE2, "r");
  715. if (fp != NULL) {
  716. strcpy(g_config_file_name, CONFIG_FILE2);
  717. }
  718. }
  719. if (fp != NULL) {
  720. fclose(fp);
  721. }
  722. #endif
  723. /* read all configurations from a config file */
  724. if (0 == read_config_file(g_config_file_name, options)) {
  725. if (cmd_line_opts_start == 2) {
  726. /* If config file was set in command line and open failed, die. */
  727. /* Errno will still hold the error from fopen. */
  728. die("Cannot open config file %s: %s",
  729. g_config_file_name,
  730. strerror(errno));
  731. }
  732. /* Otherwise: CivetWeb can work without a config file */
  733. }
  734. /* If we're under MacOS and started by launchd, then the second
  735. argument is process serial number, -psn_.....
  736. In this case, don't process arguments at all. */
  737. if (argv[1] == NULL || memcmp(argv[1], "-psn_", 5) != 0) {
  738. /* Handle command line flags.
  739. They override config file and default settings. */
  740. for (i = cmd_line_opts_start; argv[i] != NULL; i += 2) {
  741. if (argv[i][0] != '-' || argv[i + 1] == NULL) {
  742. show_usage_and_exit(argv[0]);
  743. }
  744. if (!set_option(options, &argv[i][1], argv[i + 1])) {
  745. fprintf(
  746. stderr,
  747. "command line option is invalid, ignoring it:\n %s %s\n",
  748. argv[i],
  749. argv[i + 1]);
  750. }
  751. }
  752. }
  753. }
  754. static void
  755. init_system_info(void)
  756. {
  757. int len = mg_get_system_info(NULL, 0);
  758. if (len > 0) {
  759. g_system_info = (char *)malloc((unsigned)len + 1);
  760. (void)mg_get_system_info(g_system_info, len + 1);
  761. } else {
  762. g_system_info = sdup("Not available");
  763. }
  764. }
  765. static void
  766. init_server_name(void)
  767. {
  768. DEBUG_ASSERT(sizeof(main_config_options) / sizeof(main_config_options[0])
  769. == NUM_MAIN_OPTIONS + 1);
  770. DEBUG_ASSERT((strlen(mg_version()) + 12) < sizeof(g_server_base_name));
  771. snprintf(g_server_base_name,
  772. sizeof(g_server_base_name),
  773. "CivetWeb V%s",
  774. mg_version());
  775. g_server_name = g_server_base_name;
  776. g_icon_name = NULL;
  777. g_website = "http://civetweb.github.io/civetweb/";
  778. g_num_add_domains = 0;
  779. g_add_domain = NULL;
  780. }
  781. static void
  782. free_system_info(void)
  783. {
  784. free(g_system_info);
  785. }
  786. static int
  787. log_message(const struct mg_connection *conn, const char *message)
  788. {
  789. const struct mg_context *ctx = mg_get_context(conn);
  790. struct tuser_data *ud = (struct tuser_data *)mg_get_user_data(ctx);
  791. fprintf(stderr, "%s\n", message);
  792. if (ud->first_message == NULL) {
  793. ud->first_message = sdup(message);
  794. }
  795. return 0;
  796. }
  797. static int
  798. is_path_absolute(const char *path)
  799. {
  800. #ifdef _WIN32
  801. return path != NULL
  802. && ((path[0] == '\\' && path[1] == '\\') || /* UNC path, e.g.
  803. \\server\dir */
  804. (isalpha(path[0]) && path[1] == ':'
  805. && path[2] == '\\')); /* E.g. X:\dir */
  806. #else
  807. return path != NULL && path[0] == '/';
  808. #endif
  809. }
  810. static void
  811. verify_existence(char **options, const char *option_name, int must_be_dir)
  812. {
  813. struct stat st;
  814. const char *path = get_option(options, option_name);
  815. #ifdef _WIN32
  816. wchar_t wbuf[1024];
  817. char mbbuf[1024];
  818. int len;
  819. if (path) {
  820. memset(wbuf, 0, sizeof(wbuf));
  821. memset(mbbuf, 0, sizeof(mbbuf));
  822. len = MultiByteToWideChar(CP_UTF8,
  823. 0,
  824. path,
  825. -1,
  826. wbuf,
  827. (int)sizeof(wbuf) / sizeof(wbuf[0]) - 1);
  828. wcstombs(mbbuf, wbuf, sizeof(mbbuf) - 1);
  829. path = mbbuf;
  830. (void)len;
  831. }
  832. #endif
  833. if (path != NULL && (stat(path, &st) != 0
  834. || ((S_ISDIR(st.st_mode) ? 1 : 0) != must_be_dir))) {
  835. die("Invalid path for %s: [%s]: (%s). Make sure that path is either "
  836. "absolute, or it is relative to civetweb executable.",
  837. option_name,
  838. path,
  839. strerror(errno));
  840. }
  841. }
  842. static void
  843. set_absolute_path(char *options[],
  844. const char *option_name,
  845. const char *path_to_civetweb_exe)
  846. {
  847. char path[PATH_MAX] = "", absolute[PATH_MAX] = "";
  848. const char *option_value;
  849. const char *p;
  850. /* Check whether option is already set */
  851. option_value = get_option(options, option_name);
  852. /* If option is already set and it is an absolute path,
  853. leave it as it is -- it's already absolute. */
  854. if (option_value != NULL && !is_path_absolute(option_value)) {
  855. /* Not absolute. Use the directory where civetweb executable lives
  856. be the relative directory for everything.
  857. Extract civetweb executable directory into path. */
  858. if ((p = strrchr(path_to_civetweb_exe, DIRSEP)) == NULL) {
  859. IGNORE_UNUSED_RESULT(getcwd(path, sizeof(path)));
  860. } else {
  861. snprintf(path,
  862. sizeof(path) - 1,
  863. "%.*s",
  864. (int)(p - path_to_civetweb_exe),
  865. path_to_civetweb_exe);
  866. path[sizeof(path) - 1] = 0;
  867. }
  868. strncat(path, "/", sizeof(path) - strlen(path) - 1);
  869. strncat(path, option_value, sizeof(path) - strlen(path) - 1);
  870. /* Absolutize the path, and set the option */
  871. IGNORE_UNUSED_RESULT(abs_path(path, absolute, sizeof(absolute)));
  872. set_option(options, option_name, absolute);
  873. }
  874. }
  875. #ifdef USE_LUA
  876. #include "civetweb_private_lua.h"
  877. #endif
  878. #ifdef USE_DUKTAPE
  879. #include "duktape.h"
  880. static int
  881. run_duktape(const char *file_name)
  882. {
  883. duk_context *ctx = NULL;
  884. ctx = duk_create_heap_default();
  885. if (!ctx) {
  886. fprintf(stderr, "Failed to create a Duktape heap.\n");
  887. goto finished;
  888. }
  889. if (duk_peval_file(ctx, file_name) != 0) {
  890. fprintf(stderr, "%s\n", duk_safe_to_string(ctx, -1));
  891. goto finished;
  892. }
  893. duk_pop(ctx); /* ignore result */
  894. finished:
  895. duk_destroy_heap(ctx);
  896. return 0;
  897. }
  898. #endif
  899. #if defined(__MINGW32__) || defined(__MINGW64__)
  900. /* For __MINGW32/64_MAJOR/MINOR_VERSION define */
  901. #include <_mingw.h>
  902. #endif
  903. static int
  904. run_client(const char *url_arg)
  905. {
  906. /* connection data */
  907. char *url = sdup(url_arg);
  908. char *host;
  909. char *resource;
  910. int is_ssl = 0;
  911. unsigned long port = 0;
  912. size_t sep;
  913. char *endp = 0;
  914. char empty[] = "";
  915. /* connection object */
  916. struct mg_connection *conn;
  917. char ebuf[1024] = {0};
  918. /* Check parameter */
  919. if (!url) {
  920. fprintf(stderr, "Out of memory\n");
  921. return 0;
  922. }
  923. if (!strncmp(url, "http://", 7)) {
  924. host = url + 7;
  925. port = 80;
  926. } else if (!strncmp(url, "https://", 8)) {
  927. host = url + 8;
  928. is_ssl = 1;
  929. port = 443;
  930. } else {
  931. fprintf(stderr, "URL must start with http:// or https://\n");
  932. free(url);
  933. return 0;
  934. }
  935. if ((host[0] <= 32) || (host[0] > 126) || (host[0] == '/')
  936. || (host[0] == ':')) {
  937. fprintf(stderr, "Invalid host\n");
  938. free(url);
  939. return 0;
  940. }
  941. sep = strcspn(host, "/:");
  942. switch (host[sep]) {
  943. case 0:
  944. resource = empty;
  945. break;
  946. case '/':
  947. host[sep] = 0;
  948. resource = host + sep + 1;
  949. break;
  950. case ':':
  951. host[sep] = 0;
  952. port = strtoul(host + sep + 1, &endp, 10);
  953. if (!endp || (*endp != '/' && *endp != 0) || (port < 1)
  954. || (port > 0xFFFF)) {
  955. fprintf(stderr, "Invalid port\n");
  956. free(url);
  957. return 0;
  958. }
  959. if (*endp) {
  960. *endp = 0;
  961. resource = endp + 1;
  962. } else {
  963. resource = empty;
  964. }
  965. break;
  966. default:
  967. fprintf(stderr, "Syntax error\n");
  968. free(url);
  969. return 0;
  970. }
  971. fprintf(stdout, "Protocol: %s\n", is_ssl ? "https" : "http");
  972. fprintf(stdout, "Host: %s\n", host);
  973. fprintf(stdout, "Port: %lu\n", port);
  974. fprintf(stdout, "Resource: %s\n", resource);
  975. /* Initialize library */
  976. if (is_ssl) {
  977. mg_init_library(MG_FEATURES_TLS);
  978. } else {
  979. mg_init_library(MG_FEATURES_DEFAULT);
  980. }
  981. /* Connect to host */
  982. conn = mg_connect_client(host, (int)port, is_ssl, ebuf, sizeof(ebuf));
  983. if (conn) {
  984. /* Connecting to server worked */
  985. char buf[1024] = {0};
  986. int ret;
  987. fprintf(stdout, "Connected to %s\n", host);
  988. /* Send GET request */
  989. mg_printf(conn,
  990. "GET /%s HTTP/1.1\r\n"
  991. "Host: %s\r\n"
  992. "Connection: close\r\n"
  993. "\r\n",
  994. resource,
  995. host);
  996. /* Wait for server to respond with a HTTP header */
  997. ret = mg_get_response(conn, ebuf, sizeof(ebuf), 10000);
  998. if (ret >= 0) {
  999. const struct mg_response_info *ri = mg_get_response_info(conn);
  1000. fprintf(stdout,
  1001. "Response info: %i %s\n",
  1002. ri->status_code,
  1003. ri->status_text);
  1004. /* Respond reader read. Read body (if any) */
  1005. ret = mg_read(conn, buf, sizeof(buf));
  1006. while (ret > 0) {
  1007. fwrite(buf, 1, (unsigned)ret, stdout);
  1008. ret = mg_read(conn, buf, sizeof(buf));
  1009. }
  1010. fprintf(stdout, "Closing connection to %s\n", host);
  1011. } else {
  1012. /* Server did not reply to HTTP request */
  1013. fprintf(stderr, "Got no response from %s:\n%s\n", host, ebuf);
  1014. }
  1015. mg_close_connection(conn);
  1016. } else {
  1017. /* Connecting to server failed */
  1018. fprintf(stderr, "Error connecting to %s:\n%s\n", host, ebuf);
  1019. }
  1020. /* Free memory and exit library */
  1021. free(url);
  1022. mg_exit_library();
  1023. return 1;
  1024. }
  1025. static void
  1026. sanitize_options(char *options[] /* server options */,
  1027. const char *arg0 /* argv[0] */)
  1028. {
  1029. /* Make sure we have absolute paths for files and directories */
  1030. set_absolute_path(options, "document_root", arg0);
  1031. set_absolute_path(options, "put_delete_auth_file", arg0);
  1032. set_absolute_path(options, "cgi_interpreter", arg0);
  1033. set_absolute_path(options, "access_log_file", arg0);
  1034. set_absolute_path(options, "error_log_file", arg0);
  1035. set_absolute_path(options, "global_auth_file", arg0);
  1036. #ifdef USE_LUA
  1037. set_absolute_path(options, "lua_preload_file", arg0);
  1038. #endif
  1039. set_absolute_path(options, "ssl_certificate", arg0);
  1040. /* Make extra verification for certain options */
  1041. verify_existence(options, "document_root", 1);
  1042. verify_existence(options, "cgi_interpreter", 0);
  1043. verify_existence(options, "ssl_certificate", 0);
  1044. verify_existence(options, "ssl_ca_path", 1);
  1045. verify_existence(options, "ssl_ca_file", 0);
  1046. #ifdef USE_LUA
  1047. verify_existence(options, "lua_preload_file", 0);
  1048. #endif
  1049. }
  1050. static void
  1051. start_civetweb(int argc, char *argv[])
  1052. {
  1053. struct mg_callbacks callbacks;
  1054. char *options[2 * MAX_OPTIONS + 1];
  1055. int i;
  1056. /* Start option -I:
  1057. * Show system information and exit
  1058. * This is very useful for diagnosis. */
  1059. if (argc > 1 && !strcmp(argv[1], "-I")) {
  1060. #ifdef WIN32
  1061. (void)MakeConsole();
  1062. #endif
  1063. fprintf(stdout,
  1064. "\n%s (%s)\n%s\n",
  1065. g_server_base_name,
  1066. g_server_name,
  1067. g_system_info);
  1068. exit(EXIT_SUCCESS);
  1069. }
  1070. /* Edit passwords file: Add user or change password, if -A option is
  1071. * specified */
  1072. if (argc > 1 && !strcmp(argv[1], "-A")) {
  1073. if (argc != 6) {
  1074. show_usage_and_exit(argv[0]);
  1075. }
  1076. exit(mg_modify_passwords_file(argv[2], argv[3], argv[4], argv[5])
  1077. ? EXIT_SUCCESS
  1078. : EXIT_FAILURE);
  1079. }
  1080. /* Edit passwords file: Remove user, if -R option is specified */
  1081. if (argc > 1 && !strcmp(argv[1], "-R")) {
  1082. if (argc != 5) {
  1083. show_usage_and_exit(argv[0]);
  1084. }
  1085. exit(mg_modify_passwords_file(argv[2], argv[3], argv[4], NULL)
  1086. ? EXIT_SUCCESS
  1087. : EXIT_FAILURE);
  1088. }
  1089. /* Client mode */
  1090. if (argc > 1 && !strcmp(argv[1], "-C")) {
  1091. if (argc != 3) {
  1092. show_usage_and_exit(argv[0]);
  1093. }
  1094. exit(run_client(argv[2]) ? EXIT_SUCCESS : EXIT_FAILURE);
  1095. }
  1096. /* Call Lua with additional CivetWeb specific Lua functions, if -L option
  1097. * is specified */
  1098. if (argc > 1 && !strcmp(argv[1], "-L")) {
  1099. #ifdef USE_LUA
  1100. if (argc != 3) {
  1101. show_usage_and_exit(argv[0]);
  1102. }
  1103. #ifdef WIN32
  1104. (void)MakeConsole();
  1105. #endif
  1106. exit(run_lua(argv[2]));
  1107. #else
  1108. show_server_name();
  1109. fprintf(stderr, "\nError: Lua support not enabled\n");
  1110. exit(EXIT_FAILURE);
  1111. #endif
  1112. }
  1113. /* Call Duktape, if -E option is specified */
  1114. if (argc > 1 && !strcmp(argv[1], "-E")) {
  1115. #ifdef USE_DUKTAPE
  1116. if (argc != 3) {
  1117. show_usage_and_exit(argv[0]);
  1118. }
  1119. #ifdef WIN32
  1120. (void)MakeConsole();
  1121. #endif
  1122. exit(run_duktape(argv[2]));
  1123. #else
  1124. show_server_name();
  1125. fprintf(stderr, "\nError: Ecmascript support not enabled\n");
  1126. exit(EXIT_FAILURE);
  1127. #endif
  1128. }
  1129. /* Show usage if -h or --help options are specified */
  1130. if (argc == 2 && (!strcmp(argv[1], "-h") || !strcmp(argv[1], "-H")
  1131. || !strcmp(argv[1], "--help"))) {
  1132. show_usage_and_exit(argv[0]);
  1133. }
  1134. /* Initialize options structure */
  1135. memset(options, 0, sizeof(options));
  1136. set_option(options, "document_root", ".");
  1137. /* Update config based on command line arguments */
  1138. process_command_line_arguments(argc, argv, options);
  1139. sanitize_options(options, argv[0]);
  1140. /* Setup signal handler: quit on Ctrl-C */
  1141. signal(SIGTERM, signal_handler);
  1142. signal(SIGINT, signal_handler);
  1143. /* Initialize user data */
  1144. memset(&g_user_data, 0, sizeof(g_user_data));
  1145. /* Start Civetweb */
  1146. memset(&callbacks, 0, sizeof(callbacks));
  1147. callbacks.log_message = &log_message;
  1148. g_ctx = mg_start(&callbacks, &g_user_data, (const char **)options);
  1149. /* mg_start copies all options to an internal buffer.
  1150. * The options data field here is not required anymore. */
  1151. for (i = 0; options[i] != NULL; i++) {
  1152. free(options[i]);
  1153. }
  1154. /* If mg_start fails, it returns NULL */
  1155. if (g_ctx == NULL) {
  1156. die("Failed to start %s:\n%s",
  1157. g_server_name,
  1158. ((g_user_data.first_message == NULL) ? "unknown reason"
  1159. : g_user_data.first_message));
  1160. }
  1161. #if defined(MG_EXPERIMENTAL_INTERFACES)
  1162. for (i = 0; i < g_num_add_domains; i++) {
  1163. int j;
  1164. memset(options, 0, sizeof(options));
  1165. set_option(options, "document_root", ".");
  1166. if (0 == read_config_file(g_add_domain[i], options)) {
  1167. die("Cannot open config file %s: %s",
  1168. g_add_domain[i],
  1169. strerror(errno));
  1170. }
  1171. sanitize_options(options, argv[0]);
  1172. j = mg_start_domain(g_ctx, (const char **)options);
  1173. if (j < 0) {
  1174. die("Error loading domain file %s: %i", g_add_domain[i], j);
  1175. } else {
  1176. fprintf(stdout, "Domain file %s loaded\n", g_add_domain[i]);
  1177. }
  1178. for (j = 0; options[j] != NULL; j++) {
  1179. free(options[j]);
  1180. }
  1181. }
  1182. #endif
  1183. }
  1184. static void
  1185. stop_civetweb(void)
  1186. {
  1187. mg_stop(g_ctx);
  1188. free(g_user_data.first_message);
  1189. g_user_data.first_message = NULL;
  1190. }
  1191. #ifdef _WIN32
  1192. /* Win32 has a small GUI.
  1193. * Define some GUI elements and Windows message handlers. */
  1194. enum {
  1195. ID_ICON = 100,
  1196. ID_QUIT,
  1197. ID_SETTINGS,
  1198. ID_SEPARATOR,
  1199. ID_INSTALL_SERVICE,
  1200. ID_REMOVE_SERVICE,
  1201. ID_STATIC,
  1202. ID_GROUP,
  1203. ID_PASSWORD,
  1204. ID_SAVE,
  1205. ID_RESET_DEFAULTS,
  1206. ID_RESET_FILE,
  1207. ID_RESET_ACTIVE,
  1208. ID_STATUS,
  1209. ID_CONNECT,
  1210. ID_ADD_USER,
  1211. ID_ADD_USER_NAME,
  1212. ID_ADD_USER_REALM,
  1213. ID_INPUT_LINE,
  1214. ID_SYSINFO,
  1215. ID_WEBSITE,
  1216. /* All dynamically created text boxes for options have IDs starting from
  1217. ID_CONTROLS, incremented by one. */
  1218. ID_CONTROLS = 200,
  1219. /* Text boxes for files have "..." buttons to open file browser. These
  1220. buttons have IDs that are ID_FILE_BUTTONS_DELTA higher than associated
  1221. text box ID. */
  1222. ID_FILE_BUTTONS_DELTA = 1000
  1223. };
  1224. static HICON hIcon;
  1225. static SERVICE_STATUS ss;
  1226. static SERVICE_STATUS_HANDLE hStatus;
  1227. static const char *service_magic_argument = "--";
  1228. static NOTIFYICONDATA TrayIcon;
  1229. static void WINAPI
  1230. ControlHandler(DWORD code)
  1231. {
  1232. if (code == SERVICE_CONTROL_STOP || code == SERVICE_CONTROL_SHUTDOWN) {
  1233. ss.dwWin32ExitCode = 0;
  1234. ss.dwCurrentState = SERVICE_STOPPED;
  1235. }
  1236. SetServiceStatus(hStatus, &ss);
  1237. }
  1238. static void WINAPI
  1239. ServiceMain(void)
  1240. {
  1241. ss.dwServiceType = SERVICE_WIN32;
  1242. ss.dwCurrentState = SERVICE_RUNNING;
  1243. ss.dwControlsAccepted = SERVICE_ACCEPT_STOP | SERVICE_ACCEPT_SHUTDOWN;
  1244. hStatus = RegisterServiceCtrlHandler(g_server_name, ControlHandler);
  1245. SetServiceStatus(hStatus, &ss);
  1246. while (ss.dwCurrentState == SERVICE_RUNNING) {
  1247. Sleep(1000);
  1248. }
  1249. stop_civetweb();
  1250. ss.dwCurrentState = SERVICE_STOPPED;
  1251. ss.dwWin32ExitCode = (DWORD)-1;
  1252. SetServiceStatus(hStatus, &ss);
  1253. }
  1254. static void
  1255. show_error(void)
  1256. {
  1257. char buf[256];
  1258. FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
  1259. NULL,
  1260. GetLastError(),
  1261. MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
  1262. buf,
  1263. sizeof(buf),
  1264. NULL);
  1265. MessageBox(NULL, buf, "Error", MB_OK);
  1266. }
  1267. static void *
  1268. align(void *ptr, uintptr_t alig)
  1269. {
  1270. uintptr_t ul = (uintptr_t)ptr;
  1271. ul += alig;
  1272. ul &= ~alig;
  1273. return ((void *)ul);
  1274. }
  1275. static void
  1276. save_config(HWND hDlg, FILE *fp)
  1277. {
  1278. char value[2000] = "";
  1279. const char *default_value;
  1280. const struct mg_option *options;
  1281. int i, id;
  1282. fprintf(fp, "%s", config_file_top_comment);
  1283. options = mg_get_valid_options();
  1284. for (i = 0; options[i].name != NULL; i++) {
  1285. id = ID_CONTROLS + i;
  1286. if (options[i].type == MG_CONFIG_TYPE_BOOLEAN) {
  1287. snprintf(value,
  1288. sizeof(value) - 1,
  1289. "%s",
  1290. IsDlgButtonChecked(hDlg, id) ? "yes" : "no");
  1291. value[sizeof(value) - 1] = 0;
  1292. } else {
  1293. GetDlgItemText(hDlg, id, value, sizeof(value));
  1294. }
  1295. default_value =
  1296. options[i].default_value == NULL ? "" : options[i].default_value;
  1297. /* If value is the same as default, skip it */
  1298. if (strcmp(value, default_value) != 0) {
  1299. fprintf(fp, "%s %s\n", options[i].name, value);
  1300. }
  1301. }
  1302. }
  1303. /* LPARAM pointer passed to WM_INITDIALOG */
  1304. struct dlg_proc_param {
  1305. int guard;
  1306. HWND hWnd;
  1307. const char *name;
  1308. char *buffer;
  1309. unsigned buflen;
  1310. int idRetry;
  1311. BOOL (*fRetry)(struct dlg_proc_param *data);
  1312. };
  1313. /* Dialog proc for settings dialog */
  1314. static INT_PTR CALLBACK
  1315. SettingsDlgProc(HWND hDlg, UINT msg, WPARAM wParam, LPARAM lParam)
  1316. {
  1317. FILE *fp;
  1318. int i, j;
  1319. const char *name, *value;
  1320. const struct mg_option *default_options = mg_get_valid_options();
  1321. char *file_options[MAX_OPTIONS * 2 + 1] = {0};
  1322. char *title;
  1323. struct dlg_proc_param *pdlg_proc_param;
  1324. switch (msg) {
  1325. case WM_CLOSE:
  1326. DestroyWindow(hDlg);
  1327. break;
  1328. case WM_COMMAND:
  1329. switch (LOWORD(wParam)) {
  1330. case ID_SAVE:
  1331. EnableWindow(GetDlgItem(hDlg, ID_SAVE), FALSE);
  1332. if ((fp = fopen(g_config_file_name, "w+")) != NULL) {
  1333. save_config(hDlg, fp);
  1334. fclose(fp);
  1335. stop_civetweb();
  1336. start_civetweb(__argc, __argv);
  1337. }
  1338. EnableWindow(GetDlgItem(hDlg, ID_SAVE), TRUE);
  1339. break;
  1340. case ID_RESET_DEFAULTS:
  1341. for (i = 0; default_options[i].name != NULL; i++) {
  1342. name = default_options[i].name;
  1343. value = default_options[i].default_value == NULL
  1344. ? ""
  1345. : default_options[i].default_value;
  1346. if (default_options[i].type == MG_CONFIG_TYPE_BOOLEAN) {
  1347. CheckDlgButton(hDlg,
  1348. ID_CONTROLS + i,
  1349. !strcmp(value, "yes") ? BST_CHECKED
  1350. : BST_UNCHECKED);
  1351. } else {
  1352. SetWindowText(GetDlgItem(hDlg, ID_CONTROLS + i), value);
  1353. }
  1354. }
  1355. break;
  1356. case ID_RESET_FILE:
  1357. read_config_file(g_config_file_name, file_options);
  1358. for (i = 0; default_options[i].name != NULL; i++) {
  1359. name = default_options[i].name;
  1360. value = default_options[i].default_value;
  1361. for (j = 0; file_options[j * 2] != NULL; j++) {
  1362. if (!strcmp(name, file_options[j * 2])) {
  1363. value = file_options[j * 2 + 1];
  1364. }
  1365. }
  1366. if (value == NULL) {
  1367. value = "";
  1368. }
  1369. if (default_options[i].type == MG_CONFIG_TYPE_BOOLEAN) {
  1370. CheckDlgButton(hDlg,
  1371. ID_CONTROLS + i,
  1372. !strcmp(value, "yes") ? BST_CHECKED
  1373. : BST_UNCHECKED);
  1374. } else {
  1375. SetWindowText(GetDlgItem(hDlg, ID_CONTROLS + i), value);
  1376. }
  1377. }
  1378. for (i = 0; i < MAX_OPTIONS; i++) {
  1379. free(file_options[2 * i]);
  1380. free(file_options[2 * i + 1]);
  1381. }
  1382. break;
  1383. case ID_RESET_ACTIVE:
  1384. for (i = 0; default_options[i].name != NULL; i++) {
  1385. name = default_options[i].name;
  1386. value = mg_get_option(g_ctx, name);
  1387. if (default_options[i].type == MG_CONFIG_TYPE_BOOLEAN) {
  1388. CheckDlgButton(hDlg,
  1389. ID_CONTROLS + i,
  1390. !strcmp(value, "yes") ? BST_CHECKED
  1391. : BST_UNCHECKED);
  1392. } else {
  1393. SetDlgItemText(hDlg,
  1394. ID_CONTROLS + i,
  1395. value == NULL ? "" : value);
  1396. }
  1397. }
  1398. break;
  1399. }
  1400. for (i = 0; default_options[i].name != NULL; i++) {
  1401. name = default_options[i].name;
  1402. if (((default_options[i].type == MG_CONFIG_TYPE_FILE)
  1403. || (default_options[i].type == MG_CONFIG_TYPE_DIRECTORY))
  1404. && LOWORD(wParam) == ID_CONTROLS + i + ID_FILE_BUTTONS_DELTA) {
  1405. OPENFILENAME of;
  1406. BROWSEINFO bi;
  1407. char path[PATH_MAX] = "";
  1408. memset(&of, 0, sizeof(of));
  1409. of.lStructSize = sizeof(of);
  1410. of.hwndOwner = (HWND)hDlg;
  1411. of.lpstrFile = path;
  1412. of.nMaxFile = sizeof(path);
  1413. of.lpstrInitialDir = mg_get_option(g_ctx, "document_root");
  1414. of.Flags =
  1415. OFN_CREATEPROMPT | OFN_NOCHANGEDIR | OFN_HIDEREADONLY;
  1416. memset(&bi, 0, sizeof(bi));
  1417. bi.hwndOwner = (HWND)hDlg;
  1418. bi.lpszTitle = "Choose WWW root directory:";
  1419. bi.ulFlags = BIF_RETURNONLYFSDIRS;
  1420. if (default_options[i].type == MG_CONFIG_TYPE_DIRECTORY) {
  1421. SHGetPathFromIDList(SHBrowseForFolder(&bi), path);
  1422. } else {
  1423. GetOpenFileName(&of);
  1424. }
  1425. if (path[0] != '\0') {
  1426. SetWindowText(GetDlgItem(hDlg, ID_CONTROLS + i), path);
  1427. }
  1428. }
  1429. }
  1430. break;
  1431. case WM_INITDIALOG:
  1432. /* Store hWnd in a parameter accessible by the parent, so we can
  1433. * bring this window to front if required. */
  1434. pdlg_proc_param = (struct dlg_proc_param *)lParam;
  1435. pdlg_proc_param->hWnd = hDlg;
  1436. /* Initialize the dialog elements */
  1437. SendMessage(hDlg, WM_SETICON, (WPARAM)ICON_SMALL, (LPARAM)hIcon);
  1438. SendMessage(hDlg, WM_SETICON, (WPARAM)ICON_BIG, (LPARAM)hIcon);
  1439. title = (char *)malloc(strlen(g_server_name) + 16);
  1440. if (title) {
  1441. strcpy(title, g_server_name);
  1442. strcat(title, " settings");
  1443. SetWindowText(hDlg, title);
  1444. free(title);
  1445. }
  1446. SetFocus(GetDlgItem(hDlg, ID_SAVE));
  1447. /* Init dialog with active settings */
  1448. SendMessage(hDlg, WM_COMMAND, ID_RESET_ACTIVE, 0);
  1449. /* alternative: SendMessage(hDlg, WM_COMMAND, ID_RESET_FILE, 0); */
  1450. break;
  1451. default:
  1452. break;
  1453. }
  1454. return FALSE;
  1455. }
  1456. /* Dialog proc for input dialog */
  1457. static INT_PTR CALLBACK
  1458. InputDlgProc(HWND hDlg, UINT msg, WPARAM wParam, LPARAM lParam)
  1459. {
  1460. static struct dlg_proc_param *inBuf = 0;
  1461. WORD ctrlId;
  1462. HWND hIn;
  1463. switch (msg) {
  1464. case WM_CLOSE:
  1465. inBuf = 0;
  1466. DestroyWindow(hDlg);
  1467. break;
  1468. case WM_COMMAND:
  1469. ctrlId = LOWORD(wParam);
  1470. if (ctrlId == IDOK) {
  1471. /* Get handle of input line */
  1472. hIn = GetDlgItem(hDlg, ID_INPUT_LINE);
  1473. if (hIn) {
  1474. /* Get content of input line */
  1475. GetWindowText(hIn, inBuf->buffer, (int)inBuf->buflen);
  1476. if (strlen(inBuf->buffer) > 0) {
  1477. /* Input dialog is not empty. */
  1478. EndDialog(hDlg, IDOK);
  1479. }
  1480. } else {
  1481. /* There is no input line in this dialog. */
  1482. EndDialog(hDlg, IDOK);
  1483. }
  1484. } else if (ctrlId == IDRETRY) {
  1485. /* Get handle of input line */
  1486. hIn = GetDlgItem(hDlg, inBuf->idRetry);
  1487. if (hIn) {
  1488. /* Load current string */
  1489. GetWindowText(hIn, inBuf->buffer, (int)inBuf->buflen);
  1490. if (inBuf->fRetry) {
  1491. if (inBuf->fRetry(inBuf)) {
  1492. SetWindowText(hIn, inBuf->buffer);
  1493. }
  1494. }
  1495. }
  1496. } else if (ctrlId == IDCANCEL) {
  1497. EndDialog(hDlg, IDCANCEL);
  1498. }
  1499. break;
  1500. case WM_INITDIALOG:
  1501. /* Get handle of input line */
  1502. hIn = GetDlgItem(hDlg, ID_INPUT_LINE);
  1503. /* Get dialog parameters */
  1504. inBuf = (struct dlg_proc_param *)lParam;
  1505. /* Set dialog handle for the caller */
  1506. inBuf->hWnd = hDlg;
  1507. /* Set dialog name */
  1508. SetWindowText(hDlg, inBuf->name);
  1509. if (hIn) {
  1510. /* This is an input dialog */
  1511. DEBUG_ASSERT(inBuf != NULL);
  1512. DEBUG_ASSERT((inBuf->buffer != NULL) && (inBuf->buflen != 0));
  1513. DEBUG_ASSERT(strlen(inBuf->buffer) < inBuf->buflen);
  1514. SendMessage(hDlg, WM_SETICON, (WPARAM)ICON_SMALL, (LPARAM)hIcon);
  1515. SendMessage(hDlg, WM_SETICON, (WPARAM)ICON_BIG, (LPARAM)hIcon);
  1516. SendMessage(hIn, EM_LIMITTEXT, inBuf->buflen - 1, 0);
  1517. SetWindowText(hIn, inBuf->buffer);
  1518. SetFocus(hIn);
  1519. }
  1520. break;
  1521. default:
  1522. break;
  1523. }
  1524. return FALSE;
  1525. }
  1526. static void
  1527. suggest_passwd(char *passwd)
  1528. {
  1529. unsigned u;
  1530. char *p;
  1531. union {
  1532. FILETIME ft;
  1533. LARGE_INTEGER li;
  1534. } num;
  1535. /* valid characters are 32 to 126 */
  1536. GetSystemTimeAsFileTime(&num.ft);
  1537. num.li.HighPart |= (LONG)GetCurrentProcessId();
  1538. p = passwd;
  1539. while (num.li.QuadPart) {
  1540. u = (unsigned)(num.li.QuadPart % 95);
  1541. num.li.QuadPart -= u;
  1542. num.li.QuadPart /= 95;
  1543. *p = (char)(u + 32);
  1544. p++;
  1545. }
  1546. }
  1547. static void add_control(unsigned char **mem,
  1548. DLGTEMPLATE *dia,
  1549. WORD type,
  1550. WORD id,
  1551. DWORD style,
  1552. short x,
  1553. short y,
  1554. short cx,
  1555. short cy,
  1556. const char *caption);
  1557. static int
  1558. get_password(const char *user,
  1559. const char *realm,
  1560. char *passwd,
  1561. unsigned passwd_len)
  1562. {
  1563. #define HEIGHT (15)
  1564. #define WIDTH (280)
  1565. #define LABEL_WIDTH (90)
  1566. unsigned char mem[4096], *p;
  1567. DLGTEMPLATE *dia = (DLGTEMPLATE *)mem;
  1568. int ok;
  1569. short y;
  1570. static struct dlg_proc_param s_dlg_proc_param;
  1571. static struct {
  1572. DLGTEMPLATE dlg_template; /* 18 bytes */
  1573. WORD menu, dlg_class;
  1574. wchar_t caption[1];
  1575. WORD fontsiz;
  1576. wchar_t fontface[7];
  1577. } dialog_header = {{WS_CAPTION | WS_POPUP | WS_SYSMENU | WS_VISIBLE
  1578. | DS_SETFONT | WS_DLGFRAME,
  1579. WS_EX_TOOLWINDOW,
  1580. 0,
  1581. 200,
  1582. 200,
  1583. WIDTH,
  1584. 0},
  1585. 0,
  1586. 0,
  1587. L"",
  1588. 8,
  1589. L"Tahoma"};
  1590. DEBUG_ASSERT((user != NULL) && (realm != NULL) && (passwd != NULL));
  1591. /* Only allow one instance of this dialog to be open. */
  1592. if (s_dlg_proc_param.guard == 0) {
  1593. memset(&s_dlg_proc_param, 0, sizeof(s_dlg_proc_param));
  1594. s_dlg_proc_param.guard = 1;
  1595. } else {
  1596. SetForegroundWindow(s_dlg_proc_param.hWnd);
  1597. return 0;
  1598. }
  1599. /* Do not open a password dialog, if the username is empty */
  1600. if (user[0] == 0) {
  1601. s_dlg_proc_param.guard = 0;
  1602. return 0;
  1603. }
  1604. /* Create a password suggestion */
  1605. memset(passwd, 0, passwd_len);
  1606. suggest_passwd(passwd);
  1607. /* Make buffer available for input dialog */
  1608. s_dlg_proc_param.buffer = passwd;
  1609. s_dlg_proc_param.buflen = passwd_len;
  1610. /* Create the dialog */
  1611. (void)memset(mem, 0, sizeof(mem));
  1612. (void)memcpy(mem, &dialog_header, sizeof(dialog_header));
  1613. p = mem + sizeof(dialog_header);
  1614. y = HEIGHT;
  1615. add_control(&p,
  1616. dia,
  1617. 0x82,
  1618. ID_STATIC,
  1619. WS_VISIBLE | WS_CHILD,
  1620. 10,
  1621. y,
  1622. LABEL_WIDTH,
  1623. HEIGHT,
  1624. "User:");
  1625. add_control(&p,
  1626. dia,
  1627. 0x81,
  1628. ID_CONTROLS + 1,
  1629. WS_CHILD | WS_VISIBLE | WS_BORDER | ES_AUTOHSCROLL
  1630. | ES_READONLY,
  1631. 15 + LABEL_WIDTH,
  1632. y,
  1633. WIDTH - LABEL_WIDTH - 25,
  1634. HEIGHT,
  1635. user);
  1636. y += HEIGHT;
  1637. add_control(&p,
  1638. dia,
  1639. 0x82,
  1640. ID_STATIC,
  1641. WS_VISIBLE | WS_CHILD,
  1642. 10,
  1643. y,
  1644. LABEL_WIDTH,
  1645. HEIGHT,
  1646. "Realm:");
  1647. add_control(&p,
  1648. dia,
  1649. 0x81,
  1650. ID_CONTROLS + 2,
  1651. WS_CHILD | WS_VISIBLE | WS_BORDER | ES_AUTOHSCROLL
  1652. | ES_READONLY,
  1653. 15 + LABEL_WIDTH,
  1654. y,
  1655. WIDTH - LABEL_WIDTH - 25,
  1656. HEIGHT,
  1657. realm);
  1658. y += HEIGHT;
  1659. add_control(&p,
  1660. dia,
  1661. 0x82,
  1662. ID_STATIC,
  1663. WS_VISIBLE | WS_CHILD,
  1664. 10,
  1665. y,
  1666. LABEL_WIDTH,
  1667. HEIGHT,
  1668. "Password:");
  1669. add_control(&p,
  1670. dia,
  1671. 0x81,
  1672. ID_INPUT_LINE,
  1673. WS_CHILD | WS_VISIBLE | WS_BORDER | ES_AUTOHSCROLL | WS_TABSTOP,
  1674. 15 + LABEL_WIDTH,
  1675. y,
  1676. WIDTH - LABEL_WIDTH - 25,
  1677. HEIGHT,
  1678. "");
  1679. y += (WORD)(HEIGHT * 2);
  1680. add_control(&p,
  1681. dia,
  1682. 0x80,
  1683. IDOK,
  1684. WS_CHILD | WS_VISIBLE | BS_PUSHBUTTON | WS_TABSTOP,
  1685. 80,
  1686. y,
  1687. 55,
  1688. 12,
  1689. "Ok");
  1690. add_control(&p,
  1691. dia,
  1692. 0x80,
  1693. IDCANCEL,
  1694. WS_CHILD | WS_VISIBLE | BS_PUSHBUTTON | WS_TABSTOP,
  1695. 140,
  1696. y,
  1697. 55,
  1698. 12,
  1699. "Cancel");
  1700. DEBUG_ASSERT((intptr_t)p - (intptr_t)mem < (intptr_t)sizeof(mem));
  1701. dia->cy = y + (WORD)(HEIGHT * 1.5);
  1702. s_dlg_proc_param.name = "Modify password";
  1703. s_dlg_proc_param.fRetry = NULL;
  1704. ok =
  1705. (IDOK == DialogBoxIndirectParam(
  1706. NULL, dia, NULL, InputDlgProc, (LPARAM)&s_dlg_proc_param));
  1707. s_dlg_proc_param.hWnd = NULL;
  1708. s_dlg_proc_param.guard = 0;
  1709. return ok;
  1710. #undef HEIGHT
  1711. #undef WIDTH
  1712. #undef LABEL_WIDTH
  1713. }
  1714. /* Dialog proc for password dialog */
  1715. static INT_PTR CALLBACK
  1716. PasswordDlgProc(HWND hDlg, UINT msg, WPARAM wParam, LPARAM lParam)
  1717. {
  1718. static const char *passfile = 0;
  1719. char domain[256], user[256], password[256];
  1720. WORD ctrlId;
  1721. struct dlg_proc_param *pdlg_proc_param;
  1722. switch (msg) {
  1723. case WM_CLOSE:
  1724. passfile = 0;
  1725. DestroyWindow(hDlg);
  1726. break;
  1727. case WM_COMMAND:
  1728. ctrlId = LOWORD(wParam);
  1729. if (ctrlId == ID_ADD_USER) {
  1730. /* Add user */
  1731. GetWindowText(GetDlgItem(hDlg, ID_ADD_USER_NAME),
  1732. user,
  1733. sizeof(user));
  1734. GetWindowText(GetDlgItem(hDlg, ID_ADD_USER_REALM),
  1735. domain,
  1736. sizeof(domain));
  1737. if (get_password(user, domain, password, sizeof(password))) {
  1738. mg_modify_passwords_file(passfile, domain, user, password);
  1739. EndDialog(hDlg, IDOK);
  1740. }
  1741. } else if ((ctrlId >= (ID_CONTROLS + ID_FILE_BUTTONS_DELTA * 3))
  1742. && (ctrlId < (ID_CONTROLS + ID_FILE_BUTTONS_DELTA * 4))) {
  1743. /* Modify password */
  1744. GetWindowText(GetDlgItem(hDlg, ctrlId - ID_FILE_BUTTONS_DELTA * 3),
  1745. user,
  1746. sizeof(user));
  1747. GetWindowText(GetDlgItem(hDlg, ctrlId - ID_FILE_BUTTONS_DELTA * 2),
  1748. domain,
  1749. sizeof(domain));
  1750. if (get_password(user, domain, password, sizeof(password))) {
  1751. mg_modify_passwords_file(passfile, domain, user, password);
  1752. EndDialog(hDlg, IDOK);
  1753. }
  1754. } else if ((ctrlId >= (ID_CONTROLS + ID_FILE_BUTTONS_DELTA * 2))
  1755. && (ctrlId < (ID_CONTROLS + ID_FILE_BUTTONS_DELTA * 3))) {
  1756. /* Remove user */
  1757. GetWindowText(GetDlgItem(hDlg, ctrlId - ID_FILE_BUTTONS_DELTA * 2),
  1758. user,
  1759. sizeof(user));
  1760. GetWindowText(GetDlgItem(hDlg, ctrlId - ID_FILE_BUTTONS_DELTA),
  1761. domain,
  1762. sizeof(domain));
  1763. mg_modify_passwords_file(passfile, domain, user, NULL);
  1764. EndDialog(hDlg, IDOK);
  1765. }
  1766. break;
  1767. case WM_INITDIALOG:
  1768. pdlg_proc_param = (struct dlg_proc_param *)lParam;
  1769. pdlg_proc_param->hWnd = hDlg;
  1770. passfile = pdlg_proc_param->name;
  1771. SendMessage(hDlg, WM_SETICON, (WPARAM)ICON_SMALL, (LPARAM)hIcon);
  1772. SendMessage(hDlg, WM_SETICON, (WPARAM)ICON_BIG, (LPARAM)hIcon);
  1773. SetWindowText(hDlg, passfile);
  1774. SetFocus(GetDlgItem(hDlg, ID_ADD_USER_NAME));
  1775. break;
  1776. default:
  1777. break;
  1778. }
  1779. return FALSE;
  1780. }
  1781. static void
  1782. add_control(unsigned char **mem,
  1783. DLGTEMPLATE *dia,
  1784. WORD type,
  1785. WORD id,
  1786. DWORD style,
  1787. short x,
  1788. short y,
  1789. short cx,
  1790. short cy,
  1791. const char *caption)
  1792. {
  1793. DLGITEMTEMPLATE *tp;
  1794. LPWORD p;
  1795. dia->cdit++;
  1796. *mem = (unsigned char *)align(*mem, 3);
  1797. tp = (DLGITEMTEMPLATE *)*mem;
  1798. tp->id = id;
  1799. tp->style = style;
  1800. tp->dwExtendedStyle = 0;
  1801. tp->x = x;
  1802. tp->y = y;
  1803. tp->cx = cx;
  1804. tp->cy = cy;
  1805. p = (LPWORD)align(*mem + sizeof(*tp), 1);
  1806. *p++ = 0xffff;
  1807. *p++ = type;
  1808. while (*caption != '\0') {
  1809. *p++ = (WCHAR)*caption++;
  1810. }
  1811. *p++ = 0;
  1812. p = (LPWORD)align(p, 1);
  1813. *p++ = 0;
  1814. *mem = (unsigned char *)p;
  1815. }
  1816. static void
  1817. show_settings_dialog()
  1818. {
  1819. #define HEIGHT (15)
  1820. #define WIDTH (460)
  1821. #define LABEL_WIDTH (90)
  1822. unsigned char mem[16 * 1024], *p;
  1823. const struct mg_option *options;
  1824. DWORD style;
  1825. DLGTEMPLATE *dia = (DLGTEMPLATE *)mem;
  1826. WORD i, cl, nelems = 0;
  1827. short width, x, y;
  1828. static struct dlg_proc_param s_dlg_proc_param;
  1829. static struct {
  1830. DLGTEMPLATE dlg_template; /* 18 bytes */
  1831. WORD menu, dlg_class;
  1832. wchar_t caption[1];
  1833. WORD fontsiz;
  1834. wchar_t fontface[7];
  1835. } dialog_header = {{WS_CAPTION | WS_POPUP | WS_SYSMENU | WS_VISIBLE
  1836. | DS_SETFONT | WS_DLGFRAME,
  1837. WS_EX_TOOLWINDOW,
  1838. 0,
  1839. 200,
  1840. 200,
  1841. WIDTH,
  1842. 0},
  1843. 0,
  1844. 0,
  1845. L"",
  1846. 8,
  1847. L"Tahoma"};
  1848. if (s_dlg_proc_param.guard == 0) {
  1849. memset(&s_dlg_proc_param, 0, sizeof(s_dlg_proc_param));
  1850. s_dlg_proc_param.guard = 1;
  1851. } else {
  1852. SetForegroundWindow(s_dlg_proc_param.hWnd);
  1853. return;
  1854. }
  1855. (void)memset(mem, 0, sizeof(mem));
  1856. (void)memcpy(mem, &dialog_header, sizeof(dialog_header));
  1857. p = mem + sizeof(dialog_header);
  1858. options = mg_get_valid_options();
  1859. for (i = 0; options[i].name != NULL; i++) {
  1860. style = WS_CHILD | WS_VISIBLE | WS_TABSTOP;
  1861. x = 10 + (WIDTH / 2) * (nelems % 2);
  1862. y = (nelems / 2 + 1) * HEIGHT + 5;
  1863. width = WIDTH / 2 - 20 - LABEL_WIDTH;
  1864. if (options[i].type == MG_CONFIG_TYPE_NUMBER) {
  1865. style |= ES_NUMBER;
  1866. cl = 0x81;
  1867. style |= WS_BORDER | ES_AUTOHSCROLL;
  1868. } else if (options[i].type == MG_CONFIG_TYPE_BOOLEAN) {
  1869. cl = 0x80;
  1870. style |= BS_AUTOCHECKBOX;
  1871. } else if ((options[i].type == MG_CONFIG_TYPE_FILE)
  1872. || (options[i].type == MG_CONFIG_TYPE_DIRECTORY)) {
  1873. style |= WS_BORDER | ES_AUTOHSCROLL;
  1874. width -= 20;
  1875. cl = 0x81;
  1876. add_control(&p,
  1877. dia,
  1878. 0x80,
  1879. ID_CONTROLS + i + ID_FILE_BUTTONS_DELTA,
  1880. WS_VISIBLE | WS_CHILD | BS_PUSHBUTTON,
  1881. x + width + LABEL_WIDTH + 5,
  1882. y,
  1883. 15,
  1884. 12,
  1885. "...");
  1886. } else if (options[i].type == MG_CONFIG_TYPE_STRING_MULTILINE) {
  1887. /* TODO: This is not really uer friendly */
  1888. cl = 0x81;
  1889. style |= WS_BORDER | ES_AUTOHSCROLL | ES_MULTILINE | ES_WANTRETURN
  1890. | ES_AUTOVSCROLL;
  1891. } else {
  1892. cl = 0x81;
  1893. style |= WS_BORDER | ES_AUTOHSCROLL;
  1894. }
  1895. add_control(&p,
  1896. dia,
  1897. 0x82,
  1898. ID_STATIC,
  1899. WS_VISIBLE | WS_CHILD,
  1900. x,
  1901. y,
  1902. LABEL_WIDTH,
  1903. HEIGHT,
  1904. options[i].name);
  1905. add_control(&p,
  1906. dia,
  1907. cl,
  1908. ID_CONTROLS + i,
  1909. style,
  1910. x + LABEL_WIDTH,
  1911. y,
  1912. width,
  1913. 12,
  1914. "");
  1915. nelems++;
  1916. DEBUG_ASSERT(((intptr_t)p - (intptr_t)mem) < (intptr_t)sizeof(mem));
  1917. }
  1918. y = (((nelems + 1) / 2 + 1) * HEIGHT + 5);
  1919. add_control(&p,
  1920. dia,
  1921. 0x80,
  1922. ID_GROUP,
  1923. WS_CHILD | WS_VISIBLE | BS_GROUPBOX,
  1924. 5,
  1925. 5,
  1926. WIDTH - 10,
  1927. y,
  1928. " Settings ");
  1929. y += 10;
  1930. add_control(&p,
  1931. dia,
  1932. 0x80,
  1933. ID_SAVE,
  1934. WS_CHILD | WS_VISIBLE | BS_PUSHBUTTON | WS_TABSTOP,
  1935. WIDTH - 70,
  1936. y,
  1937. 65,
  1938. 12,
  1939. "Save Settings");
  1940. add_control(&p,
  1941. dia,
  1942. 0x80,
  1943. ID_RESET_DEFAULTS,
  1944. WS_CHILD | WS_VISIBLE | BS_PUSHBUTTON | WS_TABSTOP,
  1945. WIDTH - 140,
  1946. y,
  1947. 65,
  1948. 12,
  1949. "Reset to defaults");
  1950. add_control(&p,
  1951. dia,
  1952. 0x80,
  1953. ID_RESET_FILE,
  1954. WS_CHILD | WS_VISIBLE | BS_PUSHBUTTON | WS_TABSTOP,
  1955. WIDTH - 210,
  1956. y,
  1957. 65,
  1958. 12,
  1959. "Reload from file");
  1960. add_control(&p,
  1961. dia,
  1962. 0x80,
  1963. ID_RESET_ACTIVE,
  1964. WS_CHILD | WS_VISIBLE | BS_PUSHBUTTON | WS_TABSTOP,
  1965. WIDTH - 280,
  1966. y,
  1967. 65,
  1968. 12,
  1969. "Reload active");
  1970. add_control(&p,
  1971. dia,
  1972. 0x82,
  1973. ID_STATIC,
  1974. WS_CHILD | WS_VISIBLE | WS_DISABLED,
  1975. 5,
  1976. y,
  1977. 100,
  1978. 12,
  1979. g_server_base_name);
  1980. DEBUG_ASSERT(((intptr_t)p - (intptr_t)mem) < (intptr_t)sizeof(mem));
  1981. dia->cy = ((nelems + 1) / 2 + 1) * HEIGHT + 30;
  1982. s_dlg_proc_param.fRetry = NULL;
  1983. DialogBoxIndirectParam(
  1984. NULL, dia, NULL, SettingsDlgProc, (LPARAM)&s_dlg_proc_param);
  1985. s_dlg_proc_param.hWnd = NULL;
  1986. s_dlg_proc_param.guard = 0;
  1987. #undef HEIGHT
  1988. #undef WIDTH
  1989. #undef LABEL_WIDTH
  1990. }
  1991. static void
  1992. change_password_file()
  1993. {
  1994. #define HEIGHT (15)
  1995. #define WIDTH (320)
  1996. #define LABEL_WIDTH (90)
  1997. OPENFILENAME of;
  1998. char path[PATH_MAX] = PASSWORDS_FILE_NAME;
  1999. char strbuf[256], u[256], d[256];
  2000. HWND hDlg = NULL;
  2001. FILE *f;
  2002. short y, nelems;
  2003. unsigned char mem[4096], *p;
  2004. DLGTEMPLATE *dia = (DLGTEMPLATE *)mem;
  2005. const char *domain = mg_get_option(g_ctx, "authentication_domain");
  2006. static struct dlg_proc_param s_dlg_proc_param;
  2007. static struct {
  2008. DLGTEMPLATE dlg_template; /* 18 bytes */
  2009. WORD menu, dlg_class;
  2010. wchar_t caption[1];
  2011. WORD fontsiz;
  2012. wchar_t fontface[7];
  2013. } dialog_header = {{WS_CAPTION | WS_POPUP | WS_SYSMENU | WS_VISIBLE
  2014. | DS_SETFONT | WS_DLGFRAME,
  2015. WS_EX_TOOLWINDOW,
  2016. 0,
  2017. 200,
  2018. 200,
  2019. WIDTH,
  2020. 0},
  2021. 0,
  2022. 0,
  2023. L"",
  2024. 8,
  2025. L"Tahoma"};
  2026. if (s_dlg_proc_param.guard == 0) {
  2027. memset(&s_dlg_proc_param, 0, sizeof(s_dlg_proc_param));
  2028. s_dlg_proc_param.guard = 1;
  2029. } else {
  2030. SetForegroundWindow(s_dlg_proc_param.hWnd);
  2031. return;
  2032. }
  2033. memset(&of, 0, sizeof(of));
  2034. of.lStructSize = sizeof(of);
  2035. of.hwndOwner = (HWND)hDlg;
  2036. of.lpstrFile = path;
  2037. of.nMaxFile = sizeof(path);
  2038. of.lpstrInitialDir = mg_get_option(g_ctx, "document_root");
  2039. of.Flags = OFN_CREATEPROMPT | OFN_NOCHANGEDIR | OFN_HIDEREADONLY;
  2040. if (IDOK != GetSaveFileName(&of)) {
  2041. s_dlg_proc_param.guard = 0;
  2042. return;
  2043. }
  2044. f = fopen(path, "a+");
  2045. if (f) {
  2046. fclose(f);
  2047. } else {
  2048. MessageBox(NULL, path, "Can not open file", MB_ICONERROR);
  2049. s_dlg_proc_param.guard = 0;
  2050. return;
  2051. }
  2052. do {
  2053. s_dlg_proc_param.hWnd = NULL;
  2054. (void)memset(mem, 0, sizeof(mem));
  2055. (void)memcpy(mem, &dialog_header, sizeof(dialog_header));
  2056. p = mem + sizeof(dialog_header);
  2057. f = fopen(path, "r+");
  2058. if (!f) {
  2059. MessageBox(NULL, path, "Can not open file", MB_ICONERROR);
  2060. s_dlg_proc_param.guard = 0;
  2061. return;
  2062. }
  2063. nelems = 0;
  2064. while (fgets(strbuf, sizeof(strbuf), f)) {
  2065. if (sscanf(strbuf, "%255[^:]:%255[^:]:%*s", u, d) != 2) {
  2066. continue;
  2067. }
  2068. u[255] = 0;
  2069. d[255] = 0;
  2070. y = (nelems + 1) * HEIGHT + 5;
  2071. add_control(&p,
  2072. dia,
  2073. 0x80,
  2074. ID_CONTROLS + nelems + ID_FILE_BUTTONS_DELTA * 3,
  2075. WS_CHILD | WS_VISIBLE | BS_PUSHBUTTON | WS_TABSTOP,
  2076. 10,
  2077. y,
  2078. 65,
  2079. 12,
  2080. "Modify password");
  2081. add_control(&p,
  2082. dia,
  2083. 0x80,
  2084. ID_CONTROLS + nelems + ID_FILE_BUTTONS_DELTA * 2,
  2085. WS_CHILD | WS_VISIBLE | BS_PUSHBUTTON | WS_TABSTOP,
  2086. 80,
  2087. y,
  2088. 55,
  2089. 12,
  2090. "Remove user");
  2091. add_control(&p,
  2092. dia,
  2093. 0x81,
  2094. ID_CONTROLS + nelems + ID_FILE_BUTTONS_DELTA,
  2095. WS_CHILD | WS_VISIBLE | WS_BORDER | ES_AUTOHSCROLL
  2096. | ES_READONLY,
  2097. 245,
  2098. y,
  2099. 60,
  2100. 12,
  2101. d);
  2102. add_control(&p,
  2103. dia,
  2104. 0x81,
  2105. ID_CONTROLS + nelems,
  2106. WS_CHILD | WS_VISIBLE | WS_BORDER | ES_AUTOHSCROLL
  2107. | ES_READONLY,
  2108. 140,
  2109. y,
  2110. 100,
  2111. 12,
  2112. u);
  2113. nelems++;
  2114. DEBUG_ASSERT(((intptr_t)p - (intptr_t)mem) < (intptr_t)sizeof(mem));
  2115. }
  2116. fclose(f);
  2117. y = (nelems + 1) * HEIGHT + 10;
  2118. add_control(&p,
  2119. dia,
  2120. 0x80,
  2121. ID_ADD_USER,
  2122. WS_CHILD | WS_VISIBLE | BS_PUSHBUTTON | WS_TABSTOP,
  2123. 80,
  2124. y,
  2125. 55,
  2126. 12,
  2127. "Add user");
  2128. add_control(&p,
  2129. dia,
  2130. 0x81,
  2131. ID_ADD_USER_NAME,
  2132. WS_CHILD | WS_VISIBLE | WS_BORDER | ES_AUTOHSCROLL
  2133. | WS_TABSTOP,
  2134. 140,
  2135. y,
  2136. 100,
  2137. 12,
  2138. "");
  2139. add_control(&p,
  2140. dia,
  2141. 0x81,
  2142. ID_ADD_USER_REALM,
  2143. WS_CHILD | WS_VISIBLE | WS_BORDER | ES_AUTOHSCROLL
  2144. | WS_TABSTOP,
  2145. 245,
  2146. y,
  2147. 60,
  2148. 12,
  2149. domain);
  2150. y = (nelems + 2) * HEIGHT + 10;
  2151. add_control(&p,
  2152. dia,
  2153. 0x80,
  2154. ID_GROUP,
  2155. WS_CHILD | WS_VISIBLE | BS_GROUPBOX,
  2156. 5,
  2157. 5,
  2158. WIDTH - 10,
  2159. y,
  2160. " Users ");
  2161. y += HEIGHT;
  2162. add_control(&p,
  2163. dia,
  2164. 0x82,
  2165. ID_STATIC,
  2166. WS_CHILD | WS_VISIBLE | WS_DISABLED,
  2167. 5,
  2168. y,
  2169. 100,
  2170. 12,
  2171. g_server_base_name);
  2172. DEBUG_ASSERT(((intptr_t)p - (intptr_t)mem) < (intptr_t)sizeof(mem));
  2173. dia->cy = y + 20;
  2174. s_dlg_proc_param.name = path;
  2175. s_dlg_proc_param.fRetry = NULL;
  2176. } while ((IDOK == DialogBoxIndirectParam(NULL,
  2177. dia,
  2178. NULL,
  2179. PasswordDlgProc,
  2180. (LPARAM)&s_dlg_proc_param))
  2181. && (!g_exit_flag));
  2182. s_dlg_proc_param.hWnd = NULL;
  2183. s_dlg_proc_param.guard = 0;
  2184. #undef HEIGHT
  2185. #undef WIDTH
  2186. #undef LABEL_WIDTH
  2187. }
  2188. static BOOL
  2189. sysinfo_reload(struct dlg_proc_param *prm)
  2190. {
  2191. static char *buf = 0;
  2192. int cl, rl;
  2193. cl = mg_get_context_info(g_ctx, NULL, 0);
  2194. free(buf);
  2195. cl += 510;
  2196. buf = (char *)malloc(cl + 1);
  2197. rl = mg_get_context_info(g_ctx, buf, cl);
  2198. if ((rl > cl) || (rl <= 0)) {
  2199. if (g_ctx == NULL) {
  2200. prm->buffer = "Server not running";
  2201. } else if (rl <= 0) {
  2202. prm->buffer = "No server statistics available";
  2203. } else {
  2204. prm->buffer = "Please retry";
  2205. }
  2206. } else {
  2207. prm->buffer = buf;
  2208. }
  2209. return TRUE;
  2210. }
  2211. int
  2212. show_system_info()
  2213. {
  2214. #define HEIGHT (15)
  2215. #define WIDTH (320)
  2216. #define LABEL_WIDTH (50)
  2217. unsigned char mem[4096], *p;
  2218. DLGTEMPLATE *dia = (DLGTEMPLATE *)mem;
  2219. int ok;
  2220. short y;
  2221. static struct dlg_proc_param s_dlg_proc_param;
  2222. static struct {
  2223. DLGTEMPLATE dlg_template; /* 18 bytes */
  2224. WORD menu, dlg_class;
  2225. wchar_t caption[1];
  2226. WORD fontsiz;
  2227. wchar_t fontface[7];
  2228. } dialog_header = {{WS_CAPTION | WS_POPUP | WS_SYSMENU | WS_VISIBLE
  2229. | DS_SETFONT | WS_DLGFRAME,
  2230. WS_EX_TOOLWINDOW,
  2231. 0,
  2232. 200,
  2233. 200,
  2234. WIDTH,
  2235. 0},
  2236. 0,
  2237. 0,
  2238. L"",
  2239. 8,
  2240. L"Tahoma"};
  2241. /* Only allow one instance of this dialog to be open. */
  2242. if (s_dlg_proc_param.guard == 0) {
  2243. memset(&s_dlg_proc_param, 0, sizeof(s_dlg_proc_param));
  2244. s_dlg_proc_param.guard = 1;
  2245. } else {
  2246. SetForegroundWindow(s_dlg_proc_param.hWnd);
  2247. return 0;
  2248. }
  2249. /* Create the dialog */
  2250. (void)memset(mem, 0, sizeof(mem));
  2251. (void)memcpy(mem, &dialog_header, sizeof(dialog_header));
  2252. p = mem + sizeof(dialog_header);
  2253. y = HEIGHT;
  2254. add_control(&p,
  2255. dia,
  2256. 0x82,
  2257. ID_STATIC,
  2258. WS_VISIBLE | WS_CHILD,
  2259. 10,
  2260. y,
  2261. LABEL_WIDTH,
  2262. HEIGHT,
  2263. "System Information:");
  2264. add_control(&p,
  2265. dia,
  2266. 0x81,
  2267. ID_CONTROLS + 1,
  2268. WS_CHILD | WS_VISIBLE | WS_BORDER | ES_AUTOHSCROLL
  2269. | ES_AUTOVSCROLL | ES_MULTILINE | ES_READONLY,
  2270. 15 + LABEL_WIDTH,
  2271. y,
  2272. WIDTH - LABEL_WIDTH - 25,
  2273. HEIGHT * 7,
  2274. g_system_info);
  2275. y += (WORD)(HEIGHT * 8);
  2276. add_control(&p,
  2277. dia,
  2278. 0x80,
  2279. IDRETRY,
  2280. WS_CHILD | WS_VISIBLE | BS_PUSHBUTTON | WS_TABSTOP,
  2281. WIDTH - 10 - 55 - 10 - 55,
  2282. y,
  2283. 55,
  2284. 12,
  2285. "Reload");
  2286. add_control(&p,
  2287. dia,
  2288. 0x80,
  2289. IDOK,
  2290. WS_CHILD | WS_VISIBLE | BS_PUSHBUTTON | WS_TABSTOP,
  2291. WIDTH - 10 - 55,
  2292. y,
  2293. 55,
  2294. 12,
  2295. "Close");
  2296. DEBUG_ASSERT((intptr_t)p - (intptr_t)mem < (intptr_t)sizeof(mem));
  2297. dia->cy = y + (WORD)(HEIGHT * 1.5);
  2298. s_dlg_proc_param.name = "System information";
  2299. s_dlg_proc_param.fRetry = sysinfo_reload;
  2300. s_dlg_proc_param.idRetry = ID_CONTROLS + 1; /* Reload field with this ID */
  2301. ok =
  2302. (IDOK == DialogBoxIndirectParam(
  2303. NULL, dia, NULL, InputDlgProc, (LPARAM)&s_dlg_proc_param));
  2304. s_dlg_proc_param.hWnd = NULL;
  2305. s_dlg_proc_param.guard = 0;
  2306. return ok;
  2307. #undef HEIGHT
  2308. #undef WIDTH
  2309. #undef LABEL_WIDTH
  2310. }
  2311. static int
  2312. manage_service(int action)
  2313. {
  2314. const char *service_name = g_server_name;
  2315. SC_HANDLE hSCM = NULL, hService = NULL;
  2316. SERVICE_DESCRIPTION descr;
  2317. char path[PATH_MAX + 20] = ""; /* Path to executable plus magic argument */
  2318. int success = 1;
  2319. descr.lpDescription = (LPSTR)g_server_name;
  2320. if ((hSCM = OpenSCManager(NULL,
  2321. NULL,
  2322. action == ID_INSTALL_SERVICE ? GENERIC_WRITE
  2323. : GENERIC_READ))
  2324. == NULL) {
  2325. success = 0;
  2326. show_error();
  2327. } else if (action == ID_INSTALL_SERVICE) {
  2328. path[sizeof(path) - 1] = 0;
  2329. GetModuleFileName(NULL, path, sizeof(path) - 1);
  2330. strncat(path, " ", sizeof(path) - 1);
  2331. strncat(path, service_magic_argument, sizeof(path) - 1);
  2332. hService = CreateService(hSCM,
  2333. service_name,
  2334. service_name,
  2335. SERVICE_ALL_ACCESS,
  2336. SERVICE_WIN32_OWN_PROCESS,
  2337. SERVICE_AUTO_START,
  2338. SERVICE_ERROR_NORMAL,
  2339. path,
  2340. NULL,
  2341. NULL,
  2342. NULL,
  2343. NULL,
  2344. NULL);
  2345. if (hService) {
  2346. ChangeServiceConfig2(hService, SERVICE_CONFIG_DESCRIPTION, &descr);
  2347. } else {
  2348. show_error();
  2349. }
  2350. } else if (action == ID_REMOVE_SERVICE) {
  2351. if ((hService = OpenService(hSCM, service_name, DELETE)) == NULL
  2352. || !DeleteService(hService)) {
  2353. show_error();
  2354. }
  2355. } else if ((hService =
  2356. OpenService(hSCM, service_name, SERVICE_QUERY_STATUS))
  2357. == NULL) {
  2358. success = 0;
  2359. }
  2360. if (hService)
  2361. CloseServiceHandle(hService);
  2362. if (hSCM)
  2363. CloseServiceHandle(hSCM);
  2364. return success;
  2365. }
  2366. /* Window proc for taskbar icon */
  2367. static LRESULT CALLBACK
  2368. WindowProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam)
  2369. {
  2370. int service_installed;
  2371. char buf[200];
  2372. POINT pt;
  2373. HMENU hMenu;
  2374. static UINT s_uTaskbarRestart; /* for taskbar creation */
  2375. switch (msg) {
  2376. case WM_CREATE:
  2377. if ((__argv[1] != NULL) && !strcmp(__argv[1], service_magic_argument)) {
  2378. static SERVICE_TABLE_ENTRY service_table[2];
  2379. char *service_argv[2];
  2380. service_argv[0] = __argv[0];
  2381. service_argv[1] = NULL;
  2382. start_civetweb(1, service_argv);
  2383. memset(service_table, 0, sizeof(service_table));
  2384. service_table[0].lpServiceName = (LPSTR)g_server_name;
  2385. service_table[0].lpServiceProc =
  2386. (LPSERVICE_MAIN_FUNCTION)ServiceMain;
  2387. StartServiceCtrlDispatcher(service_table);
  2388. exit(EXIT_SUCCESS);
  2389. } else {
  2390. start_civetweb(__argc, __argv);
  2391. s_uTaskbarRestart = RegisterWindowMessage(TEXT("TaskbarCreated"));
  2392. }
  2393. break;
  2394. case WM_COMMAND:
  2395. switch (LOWORD(wParam)) {
  2396. case ID_QUIT:
  2397. stop_civetweb();
  2398. Shell_NotifyIcon(NIM_DELETE, &TrayIcon);
  2399. g_exit_flag = 1;
  2400. PostQuitMessage(0);
  2401. return 0;
  2402. case ID_SETTINGS:
  2403. show_settings_dialog();
  2404. break;
  2405. case ID_PASSWORD:
  2406. change_password_file();
  2407. break;
  2408. case ID_SYSINFO:
  2409. show_system_info();
  2410. break;
  2411. case ID_INSTALL_SERVICE:
  2412. case ID_REMOVE_SERVICE:
  2413. manage_service(LOWORD(wParam));
  2414. break;
  2415. case ID_CONNECT:
  2416. fprintf(stdout, "[%s]\n", get_url_to_first_open_port(g_ctx));
  2417. ShellExecute(NULL,
  2418. "open",
  2419. get_url_to_first_open_port(g_ctx),
  2420. NULL,
  2421. NULL,
  2422. SW_SHOW);
  2423. break;
  2424. case ID_WEBSITE:
  2425. fprintf(stdout, "[%s]\n", g_website);
  2426. ShellExecute(NULL, "open", g_website, NULL, NULL, SW_SHOW);
  2427. break;
  2428. }
  2429. break;
  2430. case WM_USER:
  2431. switch (lParam) {
  2432. case WM_RBUTTONUP:
  2433. case WM_LBUTTONUP:
  2434. case WM_LBUTTONDBLCLK:
  2435. hMenu = CreatePopupMenu();
  2436. AppendMenu(hMenu,
  2437. MF_STRING | MF_GRAYED,
  2438. ID_SEPARATOR,
  2439. g_server_name);
  2440. AppendMenu(hMenu, MF_SEPARATOR, ID_SEPARATOR, "");
  2441. service_installed = manage_service(0);
  2442. snprintf(buf,
  2443. sizeof(buf) - 1,
  2444. "NT service: %s installed",
  2445. service_installed ? "" : "not");
  2446. buf[sizeof(buf) - 1] = 0;
  2447. AppendMenu(hMenu, MF_STRING | MF_GRAYED, ID_SEPARATOR, buf);
  2448. AppendMenu(hMenu,
  2449. MF_STRING | (service_installed ? MF_GRAYED : 0),
  2450. ID_INSTALL_SERVICE,
  2451. "Install service");
  2452. AppendMenu(hMenu,
  2453. MF_STRING | (!service_installed ? MF_GRAYED : 0),
  2454. ID_REMOVE_SERVICE,
  2455. "Deinstall service");
  2456. AppendMenu(hMenu, MF_SEPARATOR, ID_SEPARATOR, "");
  2457. AppendMenu(hMenu, MF_STRING, ID_CONNECT, "Start browser");
  2458. AppendMenu(hMenu, MF_STRING, ID_SETTINGS, "Edit settings");
  2459. AppendMenu(hMenu, MF_STRING, ID_PASSWORD, "Modify password file");
  2460. AppendMenu(hMenu, MF_STRING, ID_SYSINFO, "Show system info");
  2461. AppendMenu(hMenu, MF_STRING, ID_WEBSITE, "Visit website");
  2462. AppendMenu(hMenu, MF_SEPARATOR, ID_SEPARATOR, "");
  2463. AppendMenu(hMenu, MF_STRING, ID_QUIT, "Exit");
  2464. GetCursorPos(&pt);
  2465. SetForegroundWindow(hWnd);
  2466. TrackPopupMenu(hMenu, 0, pt.x, pt.y, 0, hWnd, NULL);
  2467. PostMessage(hWnd, WM_NULL, 0, 0);
  2468. DestroyMenu(hMenu);
  2469. break;
  2470. }
  2471. break;
  2472. case WM_CLOSE:
  2473. stop_civetweb();
  2474. Shell_NotifyIcon(NIM_DELETE, &TrayIcon);
  2475. g_exit_flag = 1;
  2476. PostQuitMessage(0);
  2477. return 0; /* We've just sent our own quit message, with proper hwnd. */
  2478. default:
  2479. if (msg == s_uTaskbarRestart)
  2480. Shell_NotifyIcon(NIM_ADD, &TrayIcon);
  2481. }
  2482. return DefWindowProc(hWnd, msg, wParam, lParam);
  2483. }
  2484. static int
  2485. MakeConsole(void)
  2486. {
  2487. DWORD err;
  2488. int ok = (GetConsoleWindow() != NULL);
  2489. if (!ok) {
  2490. if (!AttachConsole(ATTACH_PARENT_PROCESS)) {
  2491. FreeConsole();
  2492. if (!AllocConsole()) {
  2493. err = GetLastError();
  2494. if (err == ERROR_ACCESS_DENIED) {
  2495. MessageBox(NULL,
  2496. "Insufficient rights to create a console window",
  2497. "Error",
  2498. MB_ICONERROR);
  2499. }
  2500. }
  2501. AttachConsole(GetCurrentProcessId());
  2502. }
  2503. ok = (GetConsoleWindow() != NULL);
  2504. if (ok) {
  2505. freopen("CONIN$", "r", stdin);
  2506. freopen("CONOUT$", "w", stdout);
  2507. freopen("CONOUT$", "w", stderr);
  2508. }
  2509. }
  2510. if (ok) {
  2511. SetConsoleTitle(g_server_name);
  2512. }
  2513. return ok;
  2514. }
  2515. int WINAPI
  2516. WinMain(HINSTANCE hInst, HINSTANCE hPrev, LPSTR cmdline, int show)
  2517. {
  2518. WNDCLASS cls;
  2519. HWND hWnd;
  2520. MSG msg;
  2521. #if defined(DEBUG)
  2522. (void)MakeConsole();
  2523. #endif
  2524. (void)hInst;
  2525. (void)hPrev;
  2526. (void)cmdline;
  2527. (void)show;
  2528. init_server_name();
  2529. init_system_info();
  2530. memset(&cls, 0, sizeof(cls));
  2531. cls.lpfnWndProc = (WNDPROC)WindowProc;
  2532. cls.hIcon = LoadIcon(NULL, IDI_APPLICATION);
  2533. cls.lpszClassName = g_server_base_name;
  2534. RegisterClass(&cls);
  2535. hWnd = CreateWindow(cls.lpszClassName,
  2536. g_server_name,
  2537. WS_OVERLAPPEDWINDOW,
  2538. 0,
  2539. 0,
  2540. 0,
  2541. 0,
  2542. NULL,
  2543. NULL,
  2544. NULL,
  2545. NULL);
  2546. ShowWindow(hWnd, SW_HIDE);
  2547. if (g_icon_name) {
  2548. hIcon = (HICON)
  2549. LoadImage(NULL, g_icon_name, IMAGE_ICON, 16, 16, LR_LOADFROMFILE);
  2550. } else {
  2551. hIcon = (HICON)LoadImage(GetModuleHandle(NULL),
  2552. MAKEINTRESOURCE(ID_ICON),
  2553. IMAGE_ICON,
  2554. 16,
  2555. 16,
  2556. 0);
  2557. }
  2558. TrayIcon.cbSize = sizeof(TrayIcon);
  2559. TrayIcon.uID = ID_ICON;
  2560. TrayIcon.uFlags = NIF_ICON | NIF_MESSAGE | NIF_TIP;
  2561. TrayIcon.hIcon = hIcon;
  2562. TrayIcon.hWnd = hWnd;
  2563. snprintf(TrayIcon.szTip, sizeof(TrayIcon.szTip), "%s", g_server_name);
  2564. TrayIcon.uCallbackMessage = WM_USER;
  2565. Shell_NotifyIcon(NIM_ADD, &TrayIcon);
  2566. while (GetMessage(&msg, hWnd, 0, 0) > 0) {
  2567. TranslateMessage(&msg);
  2568. DispatchMessage(&msg);
  2569. }
  2570. free_system_info();
  2571. /* Return the WM_QUIT value. */
  2572. return (int)msg.wParam;
  2573. }
  2574. int
  2575. main(int argc, char *argv[])
  2576. {
  2577. (void)argc;
  2578. (void)argv;
  2579. return WinMain(0, 0, 0, 0);
  2580. }
  2581. #elif defined(USE_COCOA)
  2582. #import <Cocoa/Cocoa.h>
  2583. @interface Civetweb : NSObject <NSApplicationDelegate>
  2584. - (void)openBrowser;
  2585. - (void)shutDown;
  2586. @end
  2587. @implementation Civetweb
  2588. - (void)openBrowser
  2589. {
  2590. [[NSWorkspace sharedWorkspace]
  2591. openURL:[NSURL URLWithString:[NSString stringWithUTF8String:
  2592. get_url_to_first_open_port(
  2593. g_ctx)]]];
  2594. }
  2595. - (void)editConfig
  2596. {
  2597. create_config_file(g_ctx, g_config_file_name);
  2598. NSString *path = [NSString stringWithUTF8String:g_config_file_name];
  2599. if (![[NSWorkspace sharedWorkspace] openFile:path
  2600. withApplication:@"TextEdit"]) {
  2601. NSAlert *alert = [[[NSAlert alloc] init] autorelease];
  2602. [alert setAlertStyle:NSWarningAlertStyle];
  2603. [alert setMessageText:NSLocalizedString(@"Unable to open config file.",
  2604. "")];
  2605. [alert setInformativeText:path];
  2606. (void)[alert runModal];
  2607. }
  2608. }
  2609. - (void)shutDown
  2610. {
  2611. [NSApp terminate:nil];
  2612. }
  2613. @end
  2614. int
  2615. main(int argc, char *argv[])
  2616. {
  2617. init_server_name();
  2618. init_system_info();
  2619. start_civetweb(argc, argv);
  2620. [NSAutoreleasePool new];
  2621. [NSApplication sharedApplication];
  2622. /* Add delegate to process menu item actions */
  2623. Civetweb *myDelegate = [[Civetweb alloc] autorelease];
  2624. [NSApp setDelegate:myDelegate];
  2625. /* Run this app as agent */
  2626. ProcessSerialNumber psn = {0, kCurrentProcess};
  2627. TransformProcessType(&psn, kProcessTransformToBackgroundApplication);
  2628. SetFrontProcess(&psn);
  2629. /* Add status bar menu */
  2630. id menu = [[NSMenu new] autorelease];
  2631. /* Add version menu item */
  2632. [menu
  2633. addItem:
  2634. [[[NSMenuItem alloc]
  2635. /*initWithTitle:[NSString stringWithFormat:@"%s", server_name]*/
  2636. initWithTitle:[NSString stringWithUTF8String:g_server_name]
  2637. action:@selector(noexist)
  2638. keyEquivalent:@""] autorelease]];
  2639. /* Add configuration menu item */
  2640. [menu addItem:[[[NSMenuItem alloc] initWithTitle:@"Edit configuration"
  2641. action:@selector(editConfig)
  2642. keyEquivalent:@""] autorelease]];
  2643. /* Add connect menu item */
  2644. [menu
  2645. addItem:[[[NSMenuItem alloc] initWithTitle:@"Open web root in a browser"
  2646. action:@selector(openBrowser)
  2647. keyEquivalent:@""] autorelease]];
  2648. /* Separator */
  2649. [menu addItem:[NSMenuItem separatorItem]];
  2650. /* Add quit menu item */
  2651. [menu addItem:[[[NSMenuItem alloc] initWithTitle:@"Quit"
  2652. action:@selector(shutDown)
  2653. keyEquivalent:@"q"] autorelease]];
  2654. /* Attach menu to the status bar */
  2655. id item = [[[NSStatusBar systemStatusBar]
  2656. statusItemWithLength:NSVariableStatusItemLength] retain];
  2657. [item setHighlightMode:YES];
  2658. [item setImage:[NSImage imageNamed:@"civetweb_22x22.png"]];
  2659. [item setMenu:menu];
  2660. /* Run the app */
  2661. [NSApp activateIgnoringOtherApps:YES];
  2662. [NSApp run];
  2663. stop_civetweb();
  2664. free_system_info();
  2665. return EXIT_SUCCESS;
  2666. }
  2667. #else
  2668. int
  2669. main(int argc, char *argv[])
  2670. {
  2671. init_server_name();
  2672. init_system_info();
  2673. start_civetweb(argc, argv);
  2674. fprintf(stdout,
  2675. "%s started on port(s) %s with web root [%s]\n",
  2676. g_server_name,
  2677. mg_get_option(g_ctx, "listening_ports"),
  2678. mg_get_option(g_ctx, "document_root"));
  2679. while (g_exit_flag == 0) {
  2680. sleep(1);
  2681. }
  2682. fprintf(stdout,
  2683. "Exiting on signal %d, waiting for all threads to finish...",
  2684. g_exit_flag);
  2685. fflush(stdout);
  2686. stop_civetweb();
  2687. fprintf(stdout, "%s", " done.\n");
  2688. free_system_info();
  2689. return EXIT_SUCCESS;
  2690. }
  2691. #endif /* _WIN32 */