main.c 81 KB

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