httpd.c 53 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004
  1. /* vi: set sw=4 ts=4: */
  2. /*
  3. * httpd implementation for busybox
  4. *
  5. * Copyright (C) 2002,2003 Glenn Engel <glenne@engel.org>
  6. * Copyright (C) 2003-2006 Vladimir Oleynik <dzo@simtreas.ru>
  7. *
  8. * simplify patch stolen from libbb without using strdup
  9. *
  10. * Licensed under GPLv2 or later, see file LICENSE in this tarball for details.
  11. *
  12. *****************************************************************************
  13. *
  14. * Typical usage:
  15. * for non root user
  16. * httpd -p 8080 -h $HOME/public_html
  17. * or for daemon start from rc script with uid=0:
  18. * httpd -u www
  19. * This is equivalent if www user have uid=80 to
  20. * httpd -p 80 -u 80 -h /www -c /etc/httpd.conf -r "Web Server Authentication"
  21. *
  22. *
  23. * When a url contains "cgi-bin" it is assumed to be a cgi script. The
  24. * server changes directory to the location of the script and executes it
  25. * after setting QUERY_STRING and other environment variables.
  26. *
  27. * Doc:
  28. * "CGI Environment Variables": http://hoohoo.ncsa.uiuc.edu/cgi/env.html
  29. *
  30. * The server can also be invoked as a url arg decoder and html text encoder
  31. * as follows:
  32. * foo=`httpd -d $foo` # decode "Hello%20World" as "Hello World"
  33. * bar=`httpd -e "<Hello World>"` # encode as "&#60Hello&#32World&#62"
  34. * Note that url encoding for arguments is not the same as html encoding for
  35. * presentation. -d decodes a url-encoded argument while -e encodes in html
  36. * for page display.
  37. *
  38. * httpd.conf has the following format:
  39. *
  40. * A:172.20. # Allow address from 172.20.0.0/16
  41. * A:10.0.0.0/25 # Allow any address from 10.0.0.0-10.0.0.127
  42. * A:10.0.0.0/255.255.255.128 # Allow any address that previous set
  43. * A:127.0.0.1 # Allow local loopback connections
  44. * D:* # Deny from other IP connections
  45. * /cgi-bin:foo:bar # Require user foo, pwd bar on urls starting with /cgi-bin/
  46. * /adm:admin:setup # Require user admin, pwd setup on urls starting with /adm/
  47. * /adm:toor:PaSsWd # or user toor, pwd PaSsWd on urls starting with /adm/
  48. * .au:audio/basic # additional mime type for audio.au files
  49. * *.php:/path/php # running cgi.php scripts through an interpreter
  50. *
  51. * A/D may be as a/d or allow/deny - first char case insensitive
  52. * Deny IP rules take precedence over allow rules.
  53. *
  54. *
  55. * The Deny/Allow IP logic:
  56. *
  57. * - Default is to allow all. No addresses are denied unless
  58. * denied with a D: rule.
  59. * - Order of Deny/Allow rules is significant
  60. * - Deny rules take precedence over allow rules.
  61. * - If a deny all rule (D:*) is used it acts as a catch-all for unmatched
  62. * addresses.
  63. * - Specification of Allow all (A:*) is a no-op
  64. *
  65. * Example:
  66. * 1. Allow only specified addresses
  67. * A:172.20 # Allow any address that begins with 172.20.
  68. * A:10.10. # Allow any address that begins with 10.10.
  69. * A:127.0.0.1 # Allow local loopback connections
  70. * D:* # Deny from other IP connections
  71. *
  72. * 2. Only deny specified addresses
  73. * D:1.2.3. # deny from 1.2.3.0 - 1.2.3.255
  74. * D:2.3.4. # deny from 2.3.4.0 - 2.3.4.255
  75. * A:* # (optional line added for clarity)
  76. *
  77. * If a sub directory contains a config file it is parsed and merged with
  78. * any existing settings as if it was appended to the original configuration.
  79. *
  80. * subdir paths are relative to the containing subdir and thus cannot
  81. * affect the parent rules.
  82. *
  83. * Note that since the sub dir is parsed in the forked thread servicing the
  84. * subdir http request, any merge is discarded when the process exits. As a
  85. * result, the subdir settings only have a lifetime of a single request.
  86. *
  87. *
  88. * If -c is not set, an attempt will be made to open the default
  89. * root configuration file. If -c is set and the file is not found, the
  90. * server exits with an error.
  91. *
  92. */
  93. #include "busybox.h"
  94. /* amount of buffering in a pipe */
  95. #ifndef PIPE_BUF
  96. # define PIPE_BUF 4096
  97. #endif
  98. static const char httpdVersion[] = "busybox httpd/1.35 6-Oct-2004";
  99. static const char default_path_httpd_conf[] = "/etc";
  100. static const char httpd_conf[] = "httpd.conf";
  101. static const char home[] = "./";
  102. #define TIMEOUT 60
  103. // Note: busybox xfuncs are not used because we want the server to keep running
  104. // if something bad happens due to a malformed user request.
  105. // As a result, all memory allocation after daemonize
  106. // is checked rigorously
  107. //#define DEBUG 1
  108. #define DEBUG 0
  109. #define MAX_MEMORY_BUFF 8192 /* IO buffer */
  110. typedef struct HT_ACCESS {
  111. char *after_colon;
  112. struct HT_ACCESS *next;
  113. char before_colon[1]; /* really bigger, must last */
  114. } Htaccess;
  115. typedef struct HT_ACCESS_IP {
  116. unsigned int ip;
  117. unsigned int mask;
  118. int allow_deny;
  119. struct HT_ACCESS_IP *next;
  120. } Htaccess_IP;
  121. typedef struct {
  122. char buf[MAX_MEMORY_BUFF];
  123. USE_FEATURE_HTTPD_BASIC_AUTH(const char *realm;)
  124. USE_FEATURE_HTTPD_BASIC_AUTH(char *remoteuser;)
  125. const char *query;
  126. USE_FEATURE_HTTPD_CGI(char *referer;)
  127. const char *configFile;
  128. unsigned int rmt_ip;
  129. #if ENABLE_FEATURE_HTTPD_CGI || DEBUG
  130. char *rmt_ip_str; /* for set env REMOTE_ADDR */
  131. #endif
  132. unsigned port; /* server initial port and for
  133. set env REMOTE_PORT */
  134. const char *found_mime_type;
  135. const char *found_moved_temporarily;
  136. off_t ContentLength; /* -1 - unknown */
  137. time_t last_mod;
  138. Htaccess_IP *ip_a_d; /* config allow/deny lines */
  139. int flg_deny_all;
  140. #if ENABLE_FEATURE_HTTPD_BASIC_AUTH
  141. Htaccess *auth; /* config user:password lines */
  142. #endif
  143. #if ENABLE_FEATURE_HTTPD_CONFIG_WITH_MIME_TYPES
  144. Htaccess *mime_a; /* config mime types */
  145. #endif
  146. int server_socket;
  147. int accepted_socket;
  148. volatile int alarm_signaled;
  149. #if ENABLE_FEATURE_HTTPD_CONFIG_WITH_SCRIPT_INTERPR
  150. Htaccess *script_i; /* config script interpreters */
  151. #endif
  152. } HttpdConfig;
  153. static HttpdConfig *config;
  154. static const char request_GET[] = "GET"; /* size algorithmic optimize */
  155. static const char* const suffixTable [] = {
  156. /* Warning: shorted equivalent suffix in one line must be first */
  157. ".htm.html", "text/html",
  158. ".jpg.jpeg", "image/jpeg",
  159. ".gif", "image/gif",
  160. ".png", "image/png",
  161. ".txt.h.c.cc.cpp", "text/plain",
  162. ".css", "text/css",
  163. ".wav", "audio/wav",
  164. ".avi", "video/x-msvideo",
  165. ".qt.mov", "video/quicktime",
  166. ".mpe.mpeg", "video/mpeg",
  167. ".mid.midi", "audio/midi",
  168. ".mp3", "audio/mpeg",
  169. #if 0 /* unpopular */
  170. ".au", "audio/basic",
  171. ".pac", "application/x-ns-proxy-autoconfig",
  172. ".vrml.wrl", "model/vrml",
  173. #endif
  174. 0, "application/octet-stream" /* default */
  175. };
  176. typedef enum {
  177. HTTP_OK = 200,
  178. HTTP_MOVED_TEMPORARILY = 302,
  179. HTTP_BAD_REQUEST = 400, /* malformed syntax */
  180. HTTP_UNAUTHORIZED = 401, /* authentication needed, respond with auth hdr */
  181. HTTP_NOT_FOUND = 404,
  182. HTTP_FORBIDDEN = 403,
  183. HTTP_REQUEST_TIMEOUT = 408,
  184. HTTP_NOT_IMPLEMENTED = 501, /* used for unrecognized requests */
  185. HTTP_INTERNAL_SERVER_ERROR = 500,
  186. #if 0 /* future use */
  187. HTTP_CONTINUE = 100,
  188. HTTP_SWITCHING_PROTOCOLS = 101,
  189. HTTP_CREATED = 201,
  190. HTTP_ACCEPTED = 202,
  191. HTTP_NON_AUTHORITATIVE_INFO = 203,
  192. HTTP_NO_CONTENT = 204,
  193. HTTP_MULTIPLE_CHOICES = 300,
  194. HTTP_MOVED_PERMANENTLY = 301,
  195. HTTP_NOT_MODIFIED = 304,
  196. HTTP_PAYMENT_REQUIRED = 402,
  197. HTTP_BAD_GATEWAY = 502,
  198. HTTP_SERVICE_UNAVAILABLE = 503, /* overload, maintenance */
  199. HTTP_RESPONSE_SETSIZE = 0xffffffff
  200. #endif
  201. } HttpResponseNum;
  202. typedef struct {
  203. HttpResponseNum type;
  204. const char *name;
  205. const char *info;
  206. } HttpEnumString;
  207. static const HttpEnumString httpResponseNames[] = {
  208. { HTTP_OK, "OK", NULL },
  209. { HTTP_MOVED_TEMPORARILY, "Found", "Directories must end with a slash." },
  210. { HTTP_REQUEST_TIMEOUT, "Request Timeout",
  211. "No request appeared within a reasonable time period." },
  212. { HTTP_NOT_IMPLEMENTED, "Not Implemented",
  213. "The requested method is not recognized by this server." },
  214. #if ENABLE_FEATURE_HTTPD_BASIC_AUTH
  215. { HTTP_UNAUTHORIZED, "Unauthorized", "" },
  216. #endif
  217. { HTTP_NOT_FOUND, "Not Found",
  218. "The requested URL was not found on this server." },
  219. { HTTP_BAD_REQUEST, "Bad Request", "Unsupported method." },
  220. { HTTP_FORBIDDEN, "Forbidden", "" },
  221. { HTTP_INTERNAL_SERVER_ERROR, "Internal Server Error",
  222. "Internal Server Error" },
  223. #if 0 /* not implemented */
  224. { HTTP_CREATED, "Created" },
  225. { HTTP_ACCEPTED, "Accepted" },
  226. { HTTP_NO_CONTENT, "No Content" },
  227. { HTTP_MULTIPLE_CHOICES, "Multiple Choices" },
  228. { HTTP_MOVED_PERMANENTLY, "Moved Permanently" },
  229. { HTTP_NOT_MODIFIED, "Not Modified" },
  230. { HTTP_BAD_GATEWAY, "Bad Gateway", "" },
  231. { HTTP_SERVICE_UNAVAILABLE, "Service Unavailable", "" },
  232. #endif
  233. };
  234. static const char RFC1123FMT[] = "%a, %d %b %Y %H:%M:%S GMT";
  235. #define STRNCASECMP(a, str) strncasecmp((a), (str), sizeof(str)-1)
  236. static int scan_ip(const char **ep, unsigned int *ip, unsigned char endc)
  237. {
  238. const char *p = *ep;
  239. int auto_mask = 8;
  240. int j;
  241. *ip = 0;
  242. for (j = 0; j < 4; j++) {
  243. unsigned int octet;
  244. if ((*p < '0' || *p > '9') && (*p != '/' || j == 0) && *p != 0)
  245. return -auto_mask;
  246. octet = 0;
  247. while (*p >= '0' && *p <= '9') {
  248. octet *= 10;
  249. octet += *p - '0';
  250. if (octet > 255)
  251. return -auto_mask;
  252. p++;
  253. }
  254. if (*p == '.')
  255. p++;
  256. if (*p != '/' && *p != 0)
  257. auto_mask += 8;
  258. *ip = ((*ip) << 8) | octet;
  259. }
  260. if (*p != 0) {
  261. if (*p != endc)
  262. return -auto_mask;
  263. p++;
  264. if (*p == 0)
  265. return -auto_mask;
  266. }
  267. *ep = p;
  268. return auto_mask;
  269. }
  270. static int scan_ip_mask(const char *ipm, unsigned int *ip, unsigned int *mask)
  271. {
  272. int i;
  273. unsigned int msk;
  274. i = scan_ip(&ipm, ip, '/');
  275. if (i < 0)
  276. return i;
  277. if (*ipm) {
  278. const char *p = ipm;
  279. i = 0;
  280. while (*p) {
  281. if (*p < '0' || *p > '9') {
  282. if (*p == '.') {
  283. i = scan_ip(&ipm, mask, 0);
  284. return i != 32;
  285. }
  286. return -1;
  287. }
  288. i *= 10;
  289. i += *p - '0';
  290. p++;
  291. }
  292. }
  293. if (i > 32 || i < 0)
  294. return -1;
  295. msk = 0x80000000;
  296. *mask = 0;
  297. while (i > 0) {
  298. *mask |= msk;
  299. msk >>= 1;
  300. i--;
  301. }
  302. return 0;
  303. }
  304. #if ENABLE_FEATURE_HTTPD_BASIC_AUTH \
  305. || ENABLE_FEATURE_HTTPD_CONFIG_WITH_MIME_TYPES \
  306. || ENABLE_FEATURE_HTTPD_CONFIG_WITH_SCRIPT_INTERPR
  307. static void free_config_lines(Htaccess **pprev)
  308. {
  309. Htaccess *prev = *pprev;
  310. while (prev) {
  311. Htaccess *cur = prev;
  312. prev = cur->next;
  313. free(cur);
  314. }
  315. *pprev = NULL;
  316. }
  317. #endif
  318. /* flag */
  319. #define FIRST_PARSE 0
  320. #define SUBDIR_PARSE 1
  321. #define SIGNALED_PARSE 2
  322. #define FIND_FROM_HTTPD_ROOT 3
  323. /****************************************************************************
  324. *
  325. > $Function: parse_conf()
  326. *
  327. * $Description: parse configuration file into in-memory linked list.
  328. *
  329. * The first non-white character is examined to determine if the config line
  330. * is one of the following:
  331. * .ext:mime/type # new mime type not compiled into httpd
  332. * [adAD]:from # ip address allow/deny, * for wildcard
  333. * /path:user:pass # username/password
  334. *
  335. * Any previous IP rules are discarded.
  336. * If the flag argument is not SUBDIR_PARSE then all /path and mime rules
  337. * are also discarded. That is, previous settings are retained if flag is
  338. * SUBDIR_PARSE.
  339. *
  340. * $Parameters:
  341. * (const char *) path . . null for ip address checks, path for password
  342. * checks.
  343. * (int) flag . . . . . . the source of the parse request.
  344. *
  345. * $Return: (None)
  346. *
  347. ****************************************************************************/
  348. static void parse_conf(const char *path, int flag)
  349. {
  350. FILE *f;
  351. #if ENABLE_FEATURE_HTTPD_BASIC_AUTH
  352. Htaccess *prev;
  353. #endif
  354. #if ENABLE_FEATURE_HTTPD_BASIC_AUTH \
  355. || ENABLE_FEATURE_HTTPD_CONFIG_WITH_MIME_TYPES \
  356. || ENABLE_FEATURE_HTTPD_CONFIG_WITH_SCRIPT_INTERPR
  357. Htaccess *cur;
  358. #endif
  359. const char *cf = config->configFile;
  360. char buf[160];
  361. char *p0 = NULL;
  362. char *c, *p;
  363. /* free previous ip setup if present */
  364. Htaccess_IP *pip = config->ip_a_d;
  365. while (pip) {
  366. Htaccess_IP *cur_ipl = pip;
  367. pip = cur_ipl->next;
  368. free(cur_ipl);
  369. }
  370. config->ip_a_d = NULL;
  371. config->flg_deny_all = 0;
  372. #if ENABLE_FEATURE_HTTPD_BASIC_AUTH \
  373. || ENABLE_FEATURE_HTTPD_CONFIG_WITH_MIME_TYPES \
  374. || ENABLE_FEATURE_HTTPD_CONFIG_WITH_SCRIPT_INTERPR
  375. /* retain previous auth and mime config only for subdir parse */
  376. if (flag != SUBDIR_PARSE) {
  377. #if ENABLE_FEATURE_HTTPD_BASIC_AUTH
  378. free_config_lines(&config->auth);
  379. #endif
  380. #if ENABLE_FEATURE_HTTPD_CONFIG_WITH_MIME_TYPES
  381. free_config_lines(&config->mime_a);
  382. #endif
  383. #if ENABLE_FEATURE_HTTPD_CONFIG_WITH_SCRIPT_INTERPR
  384. free_config_lines(&config->script_i);
  385. #endif
  386. }
  387. #endif
  388. if (flag == SUBDIR_PARSE || cf == NULL) {
  389. cf = alloca(strlen(path) + sizeof(httpd_conf) + 2);
  390. if (cf == NULL) {
  391. if (flag == FIRST_PARSE)
  392. bb_error_msg_and_die(bb_msg_memory_exhausted);
  393. return;
  394. }
  395. sprintf((char *)cf, "%s/%s", path, httpd_conf);
  396. }
  397. while ((f = fopen(cf, "r")) == NULL) {
  398. if (flag == SUBDIR_PARSE || flag == FIND_FROM_HTTPD_ROOT) {
  399. /* config file not found, no changes to config */
  400. return;
  401. }
  402. if (config->configFile && flag == FIRST_PARSE) /* if -c option given */
  403. bb_perror_msg_and_die("%s", cf);
  404. flag = FIND_FROM_HTTPD_ROOT;
  405. cf = httpd_conf;
  406. }
  407. #if ENABLE_FEATURE_HTTPD_BASIC_AUTH
  408. prev = config->auth;
  409. #endif
  410. /* This could stand some work */
  411. while ((p0 = fgets(buf, sizeof(buf), f)) != NULL) {
  412. c = NULL;
  413. for (p = p0; *p0 != 0 && *p0 != '#'; p0++) {
  414. if (!isspace(*p0)) {
  415. *p++ = *p0;
  416. if (*p0 == ':' && c == NULL)
  417. c = p;
  418. }
  419. }
  420. *p = 0;
  421. /* test for empty or strange line */
  422. if (c == NULL || *c == 0)
  423. continue;
  424. p0 = buf;
  425. if (*p0 == 'd')
  426. *p0 = 'D';
  427. if (*c == '*') {
  428. if (*p0 == 'D') {
  429. /* memorize deny all */
  430. config->flg_deny_all++;
  431. }
  432. /* skip default other "word:*" config lines */
  433. continue;
  434. }
  435. if (*p0 == 'a')
  436. *p0 = 'A';
  437. else if (*p0 != 'D' && *p0 != 'A'
  438. #if ENABLE_FEATURE_HTTPD_BASIC_AUTH
  439. && *p0 != '/'
  440. #endif
  441. #if ENABLE_FEATURE_HTTPD_CONFIG_WITH_MIME_TYPES
  442. && *p0 != '.'
  443. #endif
  444. #if ENABLE_FEATURE_HTTPD_CONFIG_WITH_SCRIPT_INTERPR
  445. && *p0 != '*'
  446. #endif
  447. )
  448. continue;
  449. if (*p0 == 'A' || *p0 == 'D') {
  450. /* storing current config IP line */
  451. pip = xzalloc(sizeof(Htaccess_IP));
  452. if (pip) {
  453. if (scan_ip_mask(c, &(pip->ip), &(pip->mask))) {
  454. /* syntax IP{/mask} error detected, protect all */
  455. *p0 = 'D';
  456. pip->mask = 0;
  457. }
  458. pip->allow_deny = *p0;
  459. if (*p0 == 'D') {
  460. /* Deny:form_IP move top */
  461. pip->next = config->ip_a_d;
  462. config->ip_a_d = pip;
  463. } else {
  464. /* add to bottom A:form_IP config line */
  465. Htaccess_IP *prev_IP = config->ip_a_d;
  466. if (prev_IP == NULL) {
  467. config->ip_a_d = pip;
  468. } else {
  469. while (prev_IP->next)
  470. prev_IP = prev_IP->next;
  471. prev_IP->next = pip;
  472. }
  473. }
  474. }
  475. continue;
  476. }
  477. #if ENABLE_FEATURE_HTTPD_BASIC_AUTH
  478. if (*p0 == '/') {
  479. /* make full path from httpd root / curent_path / config_line_path */
  480. cf = flag == SUBDIR_PARSE ? path : "";
  481. p0 = malloc(strlen(cf) + (c - buf) + 2 + strlen(c));
  482. if (p0 == NULL)
  483. continue;
  484. c[-1] = 0;
  485. sprintf(p0, "/%s%s", cf, buf);
  486. /* another call bb_simplify_path */
  487. cf = p = p0;
  488. do {
  489. if (*p == '/') {
  490. if (*cf == '/') { /* skip duplicate (or initial) slash */
  491. continue;
  492. } else if (*cf == '.') {
  493. if (cf[1] == '/' || cf[1] == 0) { /* remove extra '.' */
  494. continue;
  495. } else if ((cf[1] == '.') && (cf[2] == '/' || cf[2] == 0)) {
  496. ++cf;
  497. if (p > p0) {
  498. while (*--p != '/') /* omit previous dir */;
  499. }
  500. continue;
  501. }
  502. }
  503. }
  504. *++p = *cf;
  505. } while (*++cf);
  506. if ((p == p0) || (*p != '/')) { /* not a trailing slash */
  507. ++p; /* so keep last character */
  508. }
  509. *p = 0;
  510. sprintf(p0, "%s:%s", p0, c);
  511. }
  512. #endif
  513. #if ENABLE_FEATURE_HTTPD_BASIC_AUTH \
  514. || ENABLE_FEATURE_HTTPD_CONFIG_WITH_MIME_TYPES \
  515. || ENABLE_FEATURE_HTTPD_CONFIG_WITH_SCRIPT_INTERPR
  516. /* storing current config line */
  517. cur = xzalloc(sizeof(Htaccess) + strlen(p0));
  518. if (cur) {
  519. cf = strcpy(cur->before_colon, p0);
  520. c = strchr(cf, ':');
  521. *c++ = 0;
  522. cur->after_colon = c;
  523. #if ENABLE_FEATURE_HTTPD_CONFIG_WITH_MIME_TYPES
  524. if (*cf == '.') {
  525. /* config .mime line move top for overwrite previous */
  526. cur->next = config->mime_a;
  527. config->mime_a = cur;
  528. continue;
  529. }
  530. #endif
  531. #if ENABLE_FEATURE_HTTPD_CONFIG_WITH_SCRIPT_INTERPR
  532. if (*cf == '*' && cf[1] == '.') {
  533. /* config script interpreter line move top for overwrite previous */
  534. cur->next = config->script_i;
  535. config->script_i = cur;
  536. continue;
  537. }
  538. #endif
  539. #if ENABLE_FEATURE_HTTPD_BASIC_AUTH
  540. free(p0);
  541. if (prev == NULL) {
  542. /* first line */
  543. config->auth = prev = cur;
  544. } else {
  545. /* sort path, if current lenght eq or bigger then move up */
  546. Htaccess *prev_hti = config->auth;
  547. size_t l = strlen(cf);
  548. Htaccess *hti;
  549. for (hti = prev_hti; hti; hti = hti->next) {
  550. if (l >= strlen(hti->before_colon)) {
  551. /* insert before hti */
  552. cur->next = hti;
  553. if (prev_hti != hti) {
  554. prev_hti->next = cur;
  555. } else {
  556. /* insert as top */
  557. config->auth = cur;
  558. }
  559. break;
  560. }
  561. if (prev_hti != hti)
  562. prev_hti = prev_hti->next;
  563. }
  564. if (!hti) { /* not inserted, add to bottom */
  565. prev->next = cur;
  566. prev = cur;
  567. }
  568. }
  569. #endif
  570. }
  571. #endif
  572. }
  573. fclose(f);
  574. }
  575. #if ENABLE_FEATURE_HTTPD_ENCODE_URL_STR
  576. /****************************************************************************
  577. *
  578. > $Function: encodeString()
  579. *
  580. * $Description: Given a string, html encode special characters.
  581. * This is used for the -e command line option to provide an easy way
  582. * for scripts to encode result data without confusing browsers. The
  583. * returned string pointer is memory allocated by malloc().
  584. *
  585. * $Parameters:
  586. * (const char *) string . . The first string to encode.
  587. *
  588. * $Return: (char *) . . . .. . . A pointer to the encoded string.
  589. *
  590. * $Errors: Returns a null string ("") if memory is not available.
  591. *
  592. ****************************************************************************/
  593. static char *encodeString(const char *string)
  594. {
  595. /* take the simple route and encode everything */
  596. /* could possibly scan once to get length. */
  597. int len = strlen(string);
  598. char *out = xmalloc(len * 6 + 1);
  599. char *p = out;
  600. char ch;
  601. while ((ch = *string++)) {
  602. // very simple check for what to encode
  603. if (isalnum(ch)) *p++ = ch;
  604. else p += sprintf(p, "&#%d;", (unsigned char) ch);
  605. }
  606. *p = '\0';
  607. return out;
  608. }
  609. #endif /* FEATURE_HTTPD_ENCODE_URL_STR */
  610. /****************************************************************************
  611. *
  612. > $Function: decodeString()
  613. *
  614. * $Description: Given a URL encoded string, convert it to plain ascii.
  615. * Since decoding always makes strings smaller, the decode is done in-place.
  616. * Thus, callers should strdup() the argument if they do not want the
  617. * argument modified. The return is the original pointer, allowing this
  618. * function to be easily used as arguments to other functions.
  619. *
  620. * $Parameters:
  621. * (char *) string . . . The first string to decode.
  622. * (int) option_d . . 1 if called for httpd -d
  623. *
  624. * $Return: (char *) . . . . A pointer to the decoded string (same as input).
  625. *
  626. * $Errors: None
  627. *
  628. ****************************************************************************/
  629. static char *decodeString(char *orig, int option_d)
  630. {
  631. /* note that decoded string is always shorter than original */
  632. char *string = orig;
  633. char *ptr = string;
  634. char c;
  635. while ((c = *ptr++) != '\0') {
  636. unsigned value1, value2;
  637. if (option_d && c == '+') {
  638. *string++ = ' ';
  639. continue;
  640. }
  641. if (c != '%') {
  642. *string++ = c;
  643. continue;
  644. }
  645. if (sscanf(ptr, "%1X", &value1) != 1
  646. || sscanf(ptr+1, "%1X", &value2) != 1
  647. ) {
  648. if (!option_d)
  649. return NULL;
  650. *string++ = '%';
  651. continue;
  652. }
  653. value1 = value1 * 16 + value2;
  654. if (!option_d && (value1 == '/' || value1 == '\0')) {
  655. /* caller takes it as indication of invalid
  656. * (dangerous wrt exploits) chars */
  657. return orig + 1;
  658. }
  659. *string++ = value1;
  660. ptr += 2;
  661. }
  662. *string = '\0';
  663. return orig;
  664. }
  665. #if ENABLE_FEATURE_HTTPD_CGI
  666. /****************************************************************************
  667. * setenv helpers
  668. ****************************************************************************/
  669. static void setenv1(const char *name, const char *value)
  670. {
  671. if (!value)
  672. value = "";
  673. setenv(name, value, 1);
  674. }
  675. static void setenv_long(const char *name, long value)
  676. {
  677. char buf[sizeof(value)*3 + 1];
  678. sprintf(buf, "%ld", value);
  679. setenv(name, buf, 1);
  680. }
  681. #endif
  682. #if ENABLE_FEATURE_HTTPD_BASIC_AUTH
  683. /****************************************************************************
  684. *
  685. > $Function: decodeBase64()
  686. *
  687. > $Description: Decode a base 64 data stream as per rfc1521.
  688. * Note that the rfc states that none base64 chars are to be ignored.
  689. * Since the decode always results in a shorter size than the input, it is
  690. * OK to pass the input arg as an output arg.
  691. *
  692. * $Parameter:
  693. * (char *) Data . . . . A pointer to a base64 encoded string.
  694. * Where to place the decoded data.
  695. *
  696. * $Return: void
  697. *
  698. * $Errors: None
  699. *
  700. ****************************************************************************/
  701. static void decodeBase64(char *Data)
  702. {
  703. const unsigned char *in = (const unsigned char *)Data;
  704. // The decoded size will be at most 3/4 the size of the encoded
  705. unsigned long ch = 0;
  706. int i = 0;
  707. while (*in) {
  708. int t = *in++;
  709. if (t >= '0' && t <= '9')
  710. t = t - '0' + 52;
  711. else if (t >= 'A' && t <= 'Z')
  712. t = t - 'A';
  713. else if (t >= 'a' && t <= 'z')
  714. t = t - 'a' + 26;
  715. else if (t == '+')
  716. t = 62;
  717. else if (t == '/')
  718. t = 63;
  719. else if (t == '=')
  720. t = 0;
  721. else
  722. continue;
  723. ch = (ch << 6) | t;
  724. i++;
  725. if (i == 4) {
  726. *Data++ = (char) (ch >> 16);
  727. *Data++ = (char) (ch >> 8);
  728. *Data++ = (char) ch;
  729. i = 0;
  730. }
  731. }
  732. *Data = 0;
  733. }
  734. #endif
  735. /****************************************************************************
  736. *
  737. > $Function: openServer()
  738. *
  739. * $Description: create a listen server socket on the designated port.
  740. *
  741. * $Return: (int) . . . A connection socket. -1 for errors.
  742. *
  743. * $Errors: None
  744. *
  745. ****************************************************************************/
  746. static int openServer(void)
  747. {
  748. int fd;
  749. /* create the socket right now */
  750. fd = create_and_bind_stream_or_die(NULL, config->port);
  751. xlisten(fd, 9);
  752. return fd;
  753. }
  754. /****************************************************************************
  755. *
  756. > $Function: sendHeaders()
  757. *
  758. * $Description: Create and send HTTP response headers.
  759. * The arguments are combined and sent as one write operation. Note that
  760. * IE will puke big-time if the headers are not sent in one packet and the
  761. * second packet is delayed for any reason.
  762. *
  763. * $Parameter:
  764. * (HttpResponseNum) responseNum . . . The result code to send.
  765. *
  766. * $Return: (int) . . . . writing errors
  767. *
  768. ****************************************************************************/
  769. static int sendHeaders(HttpResponseNum responseNum)
  770. {
  771. char *buf = config->buf;
  772. const char *responseString = "";
  773. const char *infoString = 0;
  774. const char *mime_type;
  775. unsigned i;
  776. time_t timer = time(0);
  777. char timeStr[80];
  778. int len;
  779. enum {
  780. numNames = sizeof(httpResponseNames) / sizeof(httpResponseNames[0])
  781. };
  782. for (i = 0; i < numNames; i++) {
  783. if (httpResponseNames[i].type == responseNum) {
  784. responseString = httpResponseNames[i].name;
  785. infoString = httpResponseNames[i].info;
  786. break;
  787. }
  788. }
  789. /* error message is HTML */
  790. mime_type = responseNum == HTTP_OK ?
  791. config->found_mime_type : "text/html";
  792. /* emit the current date */
  793. strftime(timeStr, sizeof(timeStr), RFC1123FMT, gmtime(&timer));
  794. len = sprintf(buf,
  795. "HTTP/1.0 %d %s\r\nContent-type: %s\r\n"
  796. "Date: %s\r\nConnection: close\r\n",
  797. responseNum, responseString, mime_type, timeStr);
  798. #if ENABLE_FEATURE_HTTPD_BASIC_AUTH
  799. if (responseNum == HTTP_UNAUTHORIZED) {
  800. len += sprintf(buf+len, "WWW-Authenticate: Basic realm=\"%s\"\r\n",
  801. config->realm);
  802. }
  803. #endif
  804. if (responseNum == HTTP_MOVED_TEMPORARILY) {
  805. len += sprintf(buf+len, "Location: %s/%s%s\r\n",
  806. config->found_moved_temporarily,
  807. (config->query ? "?" : ""),
  808. (config->query ? config->query : ""));
  809. }
  810. if (config->ContentLength != -1) { /* file */
  811. strftime(timeStr, sizeof(timeStr), RFC1123FMT, gmtime(&config->last_mod));
  812. len += sprintf(buf+len, "Last-Modified: %s\r\n%s %"OFF_FMT"d\r\n",
  813. timeStr, "Content-length:", config->ContentLength);
  814. }
  815. strcat(buf, "\r\n");
  816. len += 2;
  817. if (infoString) {
  818. len += sprintf(buf+len,
  819. "<HEAD><TITLE>%d %s</TITLE></HEAD>\n"
  820. "<BODY><H1>%d %s</H1>\n%s\n</BODY>\n",
  821. responseNum, responseString,
  822. responseNum, responseString, infoString);
  823. }
  824. if (DEBUG)
  825. fprintf(stderr, "headers: '%s'\n", buf);
  826. i = config->accepted_socket;
  827. if (i == 0) i++; /* write to fd# 1 in inetd mode */
  828. return full_write(i, buf, len);
  829. }
  830. /****************************************************************************
  831. *
  832. > $Function: getLine()
  833. *
  834. * $Description: Read from the socket until an end of line char found.
  835. *
  836. * Characters are read one at a time until an eol sequence is found.
  837. *
  838. * $Return: (int) . . . . number of characters read. -1 if error.
  839. *
  840. ****************************************************************************/
  841. static int getLine(void)
  842. {
  843. int count = 0;
  844. char *buf = config->buf;
  845. while (read(config->accepted_socket, buf + count, 1) == 1) {
  846. if (buf[count] == '\r') continue;
  847. if (buf[count] == '\n') {
  848. buf[count] = 0;
  849. return count;
  850. }
  851. if (count < (MAX_MEMORY_BUFF-1)) /* check overflow */
  852. count++;
  853. }
  854. if (count) return count;
  855. else return -1;
  856. }
  857. #if ENABLE_FEATURE_HTTPD_CGI
  858. /****************************************************************************
  859. *
  860. > $Function: sendCgi()
  861. *
  862. * $Description: Execute a CGI script and send it's stdout back
  863. *
  864. * Environment variables are set up and the script is invoked with pipes
  865. * for stdin/stdout. If a post is being done the script is fed the POST
  866. * data in addition to setting the QUERY_STRING variable (for GETs or POSTs).
  867. *
  868. * $Parameters:
  869. * (const char *) url . . . . . . The requested URL (with leading /).
  870. * (int bodyLen) . . . . . . . . Length of the post body.
  871. * (const char *cookie) . . . . . For set HTTP_COOKIE.
  872. * (const char *content_type) . . For set CONTENT_TYPE.
  873. *
  874. * $Return: (char *) . . . . A pointer to the decoded string (same as input).
  875. *
  876. * $Errors: None
  877. *
  878. ****************************************************************************/
  879. static int sendCgi(const char *url,
  880. const char *request, int bodyLen, const char *cookie,
  881. const char *content_type)
  882. {
  883. int fromCgi[2]; /* pipe for reading data from CGI */
  884. int toCgi[2]; /* pipe for sending data to CGI */
  885. static char * argp[] = { 0, 0 };
  886. int pid = 0;
  887. int inFd;
  888. int outFd;
  889. int firstLine = 1;
  890. int status;
  891. size_t post_read_size, post_read_idx;
  892. if (pipe(fromCgi) != 0)
  893. return 0;
  894. if (pipe(toCgi) != 0)
  895. return 0;
  896. pid = fork();
  897. if (pid < 0)
  898. return 0;
  899. if (!pid) {
  900. /* child process */
  901. char *script;
  902. char *purl = xstrdup(url);
  903. char realpath_buff[MAXPATHLEN];
  904. if (purl == NULL)
  905. _exit(242);
  906. inFd = toCgi[0];
  907. outFd = fromCgi[1];
  908. dup2(inFd, 0); // replace stdin with the pipe
  909. dup2(outFd, 1); // replace stdout with the pipe
  910. if (!DEBUG)
  911. dup2(outFd, 2); // replace stderr with the pipe
  912. close(toCgi[0]);
  913. close(toCgi[1]);
  914. close(fromCgi[0]);
  915. close(fromCgi[1]);
  916. close(config->accepted_socket);
  917. close(config->server_socket);
  918. /*
  919. * Find PATH_INFO.
  920. */
  921. script = purl;
  922. while ((script = strchr(script + 1, '/')) != NULL) {
  923. /* have script.cgi/PATH_INFO or dirs/script.cgi[/PATH_INFO] */
  924. struct stat sb;
  925. *script = '\0';
  926. if (is_directory(purl + 1, 1, &sb) == 0) {
  927. /* not directory, found script.cgi/PATH_INFO */
  928. *script = '/';
  929. break;
  930. }
  931. *script = '/'; /* is directory, find next '/' */
  932. }
  933. setenv1("PATH_INFO", script); /* set /PATH_INFO or "" */
  934. /* setenv1("PATH", getenv("PATH")); redundant */
  935. setenv1("REQUEST_METHOD", request);
  936. if (config->query) {
  937. char *uri = alloca(strlen(purl) + 2 + strlen(config->query));
  938. if (uri)
  939. sprintf(uri, "%s?%s", purl, config->query);
  940. setenv1("REQUEST_URI", uri);
  941. } else {
  942. setenv1("REQUEST_URI", purl);
  943. }
  944. if (script != NULL)
  945. *script = '\0'; /* cut off /PATH_INFO */
  946. /* SCRIPT_FILENAME required by PHP in CGI mode */
  947. if (!realpath(purl + 1, realpath_buff))
  948. goto error_execing_cgi;
  949. setenv1("SCRIPT_FILENAME", realpath_buff);
  950. /* set SCRIPT_NAME as full path: /cgi-bin/dirs/script.cgi */
  951. setenv1("SCRIPT_NAME", purl);
  952. /* http://hoohoo.ncsa.uiuc.edu/cgi/env.html:
  953. * QUERY_STRING: The information which follows the ? in the URL
  954. * which referenced this script. This is the query information.
  955. * It should not be decoded in any fashion. This variable
  956. * should always be set when there is query information,
  957. * regardless of command line decoding. */
  958. /* (Older versions of bbox seem to do some decoding) */
  959. setenv1("QUERY_STRING", config->query);
  960. setenv1("SERVER_SOFTWARE", httpdVersion);
  961. putenv((char*)"SERVER_PROTOCOL=HTTP/1.0");
  962. putenv((char*)"GATEWAY_INTERFACE=CGI/1.1");
  963. /* Having _separate_ variables for IP and port defeats
  964. * the purpose of having socket abstraction. Which "port"
  965. * are you using on Unix domain socket?
  966. * IOW - REMOTE_PEER="1.2.3.4:56" makes much more sense.
  967. * Oh well... */
  968. {
  969. char *p = config->rmt_ip_str ? : (char*)"";
  970. char *cp = strrchr(p, ':');
  971. if (ENABLE_FEATURE_IPV6 && cp && strchr(cp, ']'))
  972. cp = NULL;
  973. if (cp) *cp = '\0'; /* delete :PORT */
  974. setenv1("REMOTE_ADDR", p);
  975. }
  976. #if ENABLE_FEATURE_HTTPD_SET_REMOTE_PORT_TO_ENV
  977. setenv_long("REMOTE_PORT", config->port);
  978. #endif
  979. if (bodyLen)
  980. setenv_long("CONTENT_LENGTH", bodyLen);
  981. if (cookie)
  982. setenv1("HTTP_COOKIE", cookie);
  983. if (content_type)
  984. setenv1("CONTENT_TYPE", content_type);
  985. #if ENABLE_FEATURE_HTTPD_BASIC_AUTH
  986. if (config->remoteuser) {
  987. setenv1("REMOTE_USER", config->remoteuser);
  988. putenv((char*)"AUTH_TYPE=Basic");
  989. }
  990. #endif
  991. if (config->referer)
  992. setenv1("HTTP_REFERER", config->referer);
  993. /* set execve argp[0] without path */
  994. argp[0] = strrchr(purl, '/') + 1;
  995. /* but script argp[0] must have absolute path and chdiring to this */
  996. script = strrchr(realpath_buff, '/');
  997. if (!script)
  998. goto error_execing_cgi;
  999. *script = '\0';
  1000. if (chdir(realpath_buff) == 0) {
  1001. // Now run the program. If it fails,
  1002. // use _exit() so no destructors
  1003. // get called and make a mess.
  1004. #if ENABLE_FEATURE_HTTPD_CONFIG_WITH_SCRIPT_INTERPR
  1005. char *interpr = NULL;
  1006. char *suffix = strrchr(purl, '.');
  1007. if (suffix) {
  1008. Htaccess *cur;
  1009. for (cur = config->script_i; cur; cur = cur->next) {
  1010. if (strcmp(cur->before_colon + 1, suffix) == 0) {
  1011. interpr = cur->after_colon;
  1012. break;
  1013. }
  1014. }
  1015. }
  1016. #endif
  1017. *script = '/';
  1018. #if ENABLE_FEATURE_HTTPD_CONFIG_WITH_SCRIPT_INTERPR
  1019. if (interpr)
  1020. execv(interpr, argp);
  1021. else
  1022. #endif
  1023. execv(realpath_buff, argp);
  1024. }
  1025. error_execing_cgi:
  1026. /* send to stdout (even if we are not from inetd) */
  1027. config->accepted_socket = 1;
  1028. sendHeaders(HTTP_NOT_FOUND);
  1029. _exit(242);
  1030. } /* end child */
  1031. /* parent process */
  1032. post_read_size = 0;
  1033. post_read_idx = 0; /* for gcc */
  1034. inFd = fromCgi[0];
  1035. outFd = toCgi[1];
  1036. close(fromCgi[1]);
  1037. close(toCgi[0]);
  1038. signal(SIGPIPE, SIG_IGN);
  1039. while (1) {
  1040. fd_set readSet;
  1041. fd_set writeSet;
  1042. char wbuf[128];
  1043. int nfound;
  1044. int count;
  1045. FD_ZERO(&readSet);
  1046. FD_ZERO(&writeSet);
  1047. FD_SET(inFd, &readSet);
  1048. if (bodyLen > 0 || post_read_size > 0) {
  1049. FD_SET(outFd, &writeSet);
  1050. nfound = outFd > inFd ? outFd : inFd;
  1051. if (post_read_size == 0) {
  1052. FD_SET(config->accepted_socket, &readSet);
  1053. if (nfound < config->accepted_socket)
  1054. nfound = config->accepted_socket;
  1055. }
  1056. /* Now wait on the set of sockets! */
  1057. nfound = select(nfound + 1, &readSet, &writeSet, NULL, NULL);
  1058. } else {
  1059. if (!bodyLen) {
  1060. close(outFd); /* no more POST data to CGI */
  1061. bodyLen = -1;
  1062. }
  1063. nfound = select(inFd + 1, &readSet, NULL, NULL, NULL);
  1064. }
  1065. if (nfound <= 0) {
  1066. if (waitpid(pid, &status, WNOHANG) <= 0)
  1067. /* Weird. CGI didn't exit and no fd's
  1068. * are ready, yet select returned?! */
  1069. continue;
  1070. close(inFd);
  1071. if (DEBUG && WIFEXITED(status))
  1072. bb_error_msg("piped has exited with status=%d", WEXITSTATUS(status));
  1073. if (DEBUG && WIFSIGNALED(status))
  1074. bb_error_msg("piped has exited with signal=%d", WTERMSIG(status));
  1075. break;
  1076. }
  1077. if (post_read_size > 0 && FD_ISSET(outFd, &writeSet)) {
  1078. /* Have data from peer and can write to CGI */
  1079. // huh? why full_write? what if we will block?
  1080. // (imagine that CGI does not read its stdin...)
  1081. count = full_write(outFd, wbuf + post_read_idx, post_read_size);
  1082. if (count > 0) {
  1083. post_read_idx += count;
  1084. post_read_size -= count;
  1085. } else {
  1086. post_read_size = bodyLen = 0; /* broken pipe to CGI */
  1087. }
  1088. } else if (bodyLen > 0 && post_read_size == 0
  1089. && FD_ISSET(config->accepted_socket, &readSet)
  1090. ) {
  1091. /* We expect data, prev data portion is eaten by CGI
  1092. * and there *is* data to read from the peer
  1093. * (POST data?) */
  1094. count = bodyLen > (int)sizeof(wbuf) ? (int)sizeof(wbuf) : bodyLen;
  1095. count = safe_read(config->accepted_socket, wbuf, count);
  1096. if (count > 0) {
  1097. post_read_size = count;
  1098. post_read_idx = 0;
  1099. bodyLen -= count;
  1100. } else {
  1101. bodyLen = 0; /* closed */
  1102. }
  1103. }
  1104. if (FD_ISSET(inFd, &readSet)) {
  1105. /* There is something to read from CGI */
  1106. int s = config->accepted_socket;
  1107. char *rbuf = config->buf;
  1108. #define PIPESIZE PIPE_BUF
  1109. #if PIPESIZE >= MAX_MEMORY_BUFF
  1110. # error "PIPESIZE >= MAX_MEMORY_BUFF"
  1111. #endif
  1112. /* NB: was safe_read. If it *has to be* safe_read, */
  1113. /* please explain why in this comment... */
  1114. count = full_read(inFd, rbuf, PIPESIZE);
  1115. if (count == 0)
  1116. break; /* closed */
  1117. if (count < 0)
  1118. continue; /* huh, error, why continue?? */
  1119. if (firstLine) {
  1120. /* full_read (above) avoids
  1121. * "chopped up into small chunks" syndrome here */
  1122. rbuf[count] = '\0';
  1123. /* check to see if the user script added headers */
  1124. #define HTTP_200 "HTTP/1.0 200 OK\r\n\r\n"
  1125. if (memcmp(rbuf, HTTP_200, 4) != 0) {
  1126. /* there is no "HTTP", do it ourself */
  1127. full_write(s, HTTP_200, sizeof(HTTP_200)-1);
  1128. }
  1129. #undef HTTP_200
  1130. /* Example of valid GCI without "Content-type:"
  1131. * echo -en "HTTP/1.0 302 Found\r\n"
  1132. * echo -en "Location: http://www.busybox.net\r\n"
  1133. * echo -en "\r\n"
  1134. */
  1135. //if (!strstr(rbuf, "ontent-")) {
  1136. // full_write(s, "Content-type: text/plain\r\n\r\n", 28);
  1137. //}
  1138. firstLine = 0;
  1139. }
  1140. if (full_write(s, rbuf, count) != count)
  1141. break;
  1142. if (DEBUG)
  1143. fprintf(stderr, "cgi read %d bytes: '%.*s'\n", count, count, rbuf);
  1144. } /* if (FD_ISSET(inFd)) */
  1145. } /* while (1) */
  1146. return 0;
  1147. }
  1148. #endif /* FEATURE_HTTPD_CGI */
  1149. /****************************************************************************
  1150. *
  1151. > $Function: sendFile()
  1152. *
  1153. * $Description: Send a file response to a HTTP request
  1154. *
  1155. * $Parameter:
  1156. * (const char *) url . . The URL requested.
  1157. *
  1158. * $Return: (int) . . . . . . Always 0.
  1159. *
  1160. ****************************************************************************/
  1161. static int sendFile(const char *url)
  1162. {
  1163. char * suffix;
  1164. int f;
  1165. const char * const * table;
  1166. const char * try_suffix;
  1167. suffix = strrchr(url, '.');
  1168. for (table = suffixTable; *table; table += 2)
  1169. if (suffix != NULL && (try_suffix = strstr(*table, suffix)) != 0) {
  1170. try_suffix += strlen(suffix);
  1171. if (*try_suffix == 0 || *try_suffix == '.')
  1172. break;
  1173. }
  1174. /* also, if not found, set default as "application/octet-stream"; */
  1175. config->found_mime_type = table[1];
  1176. #if ENABLE_FEATURE_HTTPD_CONFIG_WITH_MIME_TYPES
  1177. if (suffix) {
  1178. Htaccess * cur;
  1179. for (cur = config->mime_a; cur; cur = cur->next) {
  1180. if (strcmp(cur->before_colon, suffix) == 0) {
  1181. config->found_mime_type = cur->after_colon;
  1182. break;
  1183. }
  1184. }
  1185. }
  1186. #endif /* FEATURE_HTTPD_CONFIG_WITH_MIME_TYPES */
  1187. if (DEBUG)
  1188. fprintf(stderr, "sending file '%s' content-type: %s\n",
  1189. url, config->found_mime_type);
  1190. f = open(url, O_RDONLY);
  1191. if (f >= 0) {
  1192. int count;
  1193. char *buf = config->buf;
  1194. sendHeaders(HTTP_OK);
  1195. /* TODO: sendfile() */
  1196. while ((count = full_read(f, buf, MAX_MEMORY_BUFF)) > 0) {
  1197. int fd = config->accepted_socket;
  1198. if (fd == 0) fd++; /* write to fd# 1 in inetd mode */
  1199. if (full_write(fd, buf, count) != count)
  1200. break;
  1201. }
  1202. close(f);
  1203. } else {
  1204. if (DEBUG)
  1205. bb_perror_msg("cannot open '%s'", url);
  1206. sendHeaders(HTTP_NOT_FOUND);
  1207. }
  1208. return 0;
  1209. }
  1210. static int checkPermIP(void)
  1211. {
  1212. Htaccess_IP * cur;
  1213. /* This could stand some work */
  1214. for (cur = config->ip_a_d; cur; cur = cur->next) {
  1215. #if ENABLE_FEATURE_HTTPD_CGI && DEBUG
  1216. fprintf(stderr, "checkPermIP: '%s' ? ", config->rmt_ip_str);
  1217. #endif
  1218. #if DEBUG
  1219. fprintf(stderr, "'%u.%u.%u.%u/%u.%u.%u.%u'\n",
  1220. (unsigned char)(cur->ip >> 24),
  1221. (unsigned char)(cur->ip >> 16),
  1222. (unsigned char)(cur->ip >> 8),
  1223. (unsigned char)(cur->ip),
  1224. (unsigned char)(cur->mask >> 24),
  1225. (unsigned char)(cur->mask >> 16),
  1226. (unsigned char)(cur->mask >> 8),
  1227. (unsigned char)(cur->mask)
  1228. );
  1229. #endif
  1230. if ((config->rmt_ip & cur->mask) == cur->ip)
  1231. return cur->allow_deny == 'A'; /* Allow/Deny */
  1232. }
  1233. /* if unconfigured, return 1 - access from all */
  1234. return !config->flg_deny_all;
  1235. }
  1236. /****************************************************************************
  1237. *
  1238. > $Function: checkPerm()
  1239. *
  1240. * $Description: Check the permission file for access password protected.
  1241. *
  1242. * If config file isn't present, everything is allowed.
  1243. * Entries are of the form you can see example from header source
  1244. *
  1245. * $Parameters:
  1246. * (const char *) path . . . . The file path.
  1247. * (const char *) request . . . User information to validate.
  1248. *
  1249. * $Return: (int) . . . . . . . . . 1 if request OK, 0 otherwise.
  1250. *
  1251. ****************************************************************************/
  1252. #if ENABLE_FEATURE_HTTPD_BASIC_AUTH
  1253. static int checkPerm(const char *path, const char *request)
  1254. {
  1255. Htaccess * cur;
  1256. const char *p;
  1257. const char *p0;
  1258. const char *prev = NULL;
  1259. /* This could stand some work */
  1260. for (cur = config->auth; cur; cur = cur->next) {
  1261. size_t l;
  1262. p0 = cur->before_colon;
  1263. if (prev != NULL && strcmp(prev, p0) != 0)
  1264. continue; /* find next identical */
  1265. p = cur->after_colon;
  1266. if (DEBUG)
  1267. fprintf(stderr, "checkPerm: '%s' ? '%s'\n", p0, request);
  1268. l = strlen(p0);
  1269. if (strncmp(p0, path, l) == 0
  1270. && (l == 1 || path[l] == '/' || path[l] == '\0')
  1271. ) {
  1272. char *u;
  1273. /* path match found. Check request */
  1274. /* for check next /path:user:password */
  1275. prev = p0;
  1276. u = strchr(request, ':');
  1277. if (u == NULL) {
  1278. /* bad request, ':' required */
  1279. break;
  1280. }
  1281. if (ENABLE_FEATURE_HTTPD_AUTH_MD5) {
  1282. char *cipher;
  1283. char *pp;
  1284. if (strncmp(p, request, u-request) != 0) {
  1285. /* user uncompared */
  1286. continue;
  1287. }
  1288. pp = strchr(p, ':');
  1289. if (pp && pp[1] == '$' && pp[2] == '1' &&
  1290. pp[3] == '$' && pp[4]) {
  1291. pp++;
  1292. cipher = pw_encrypt(u+1, pp);
  1293. if (strcmp(cipher, pp) == 0)
  1294. goto set_remoteuser_var; /* Ok */
  1295. /* unauthorized */
  1296. continue;
  1297. }
  1298. }
  1299. if (strcmp(p, request) == 0) {
  1300. set_remoteuser_var:
  1301. config->remoteuser = strdup(request);
  1302. if (config->remoteuser)
  1303. config->remoteuser[(u - request)] = 0;
  1304. return 1; /* Ok */
  1305. }
  1306. /* unauthorized */
  1307. }
  1308. } /* for */
  1309. return prev == NULL;
  1310. }
  1311. #endif /* FEATURE_HTTPD_BASIC_AUTH */
  1312. /****************************************************************************
  1313. *
  1314. > $Function: handle_sigalrm()
  1315. *
  1316. * $Description: Handle timeouts
  1317. *
  1318. ****************************************************************************/
  1319. static void handle_sigalrm(int sig)
  1320. {
  1321. sendHeaders(HTTP_REQUEST_TIMEOUT);
  1322. config->alarm_signaled = sig;
  1323. }
  1324. /****************************************************************************
  1325. *
  1326. > $Function: handleIncoming()
  1327. *
  1328. * $Description: Handle an incoming http request.
  1329. *
  1330. ****************************************************************************/
  1331. static void handleIncoming(void)
  1332. {
  1333. char *buf = config->buf;
  1334. char *url;
  1335. char *purl;
  1336. int blank = -1;
  1337. char *test;
  1338. struct stat sb;
  1339. int ip_allowed;
  1340. #if ENABLE_FEATURE_HTTPD_CGI
  1341. const char *prequest = request_GET;
  1342. unsigned long length = 0;
  1343. char *cookie = 0;
  1344. char *content_type = 0;
  1345. #endif
  1346. fd_set s_fd;
  1347. struct timeval tv;
  1348. int retval;
  1349. struct sigaction sa;
  1350. #if ENABLE_FEATURE_HTTPD_BASIC_AUTH
  1351. int credentials = -1; /* if not required this is Ok */
  1352. #endif
  1353. sa.sa_handler = handle_sigalrm;
  1354. sigemptyset(&sa.sa_mask);
  1355. sa.sa_flags = 0; /* no SA_RESTART */
  1356. sigaction(SIGALRM, &sa, NULL);
  1357. do {
  1358. int count;
  1359. (void) alarm(TIMEOUT);
  1360. if (getLine() <= 0)
  1361. break; /* closed */
  1362. purl = strpbrk(buf, " \t");
  1363. if (purl == NULL) {
  1364. BAD_REQUEST:
  1365. sendHeaders(HTTP_BAD_REQUEST);
  1366. break;
  1367. }
  1368. *purl = '\0';
  1369. #if ENABLE_FEATURE_HTTPD_CGI
  1370. if (strcasecmp(buf, prequest) != 0) {
  1371. prequest = "POST";
  1372. if (strcasecmp(buf, prequest) != 0) {
  1373. sendHeaders(HTTP_NOT_IMPLEMENTED);
  1374. break;
  1375. }
  1376. }
  1377. #else
  1378. if (strcasecmp(buf, request_GET) != 0) {
  1379. sendHeaders(HTTP_NOT_IMPLEMENTED);
  1380. break;
  1381. }
  1382. #endif
  1383. *purl = ' ';
  1384. count = sscanf(purl, " %[^ ] HTTP/%d.%*d", buf, &blank);
  1385. if (count < 1 || buf[0] != '/') {
  1386. /* Garbled request/URL */
  1387. goto BAD_REQUEST;
  1388. }
  1389. url = alloca(strlen(buf) + sizeof("/index.html"));
  1390. if (url == NULL) {
  1391. sendHeaders(HTTP_INTERNAL_SERVER_ERROR);
  1392. break;
  1393. }
  1394. strcpy(url, buf);
  1395. /* extract url args if present */
  1396. test = strchr(url, '?');
  1397. config->query = NULL;
  1398. if (test) {
  1399. *test++ = '\0';
  1400. config->query = test;
  1401. }
  1402. test = decodeString(url, 0);
  1403. if (test == NULL)
  1404. goto BAD_REQUEST;
  1405. if (test == url+1) {
  1406. /* '/' or NUL is encoded */
  1407. sendHeaders(HTTP_NOT_FOUND);
  1408. break;
  1409. }
  1410. /* algorithm stolen from libbb bb_simplify_path(),
  1411. but don't strdup and reducing trailing slash and protect out root */
  1412. purl = test = url;
  1413. do {
  1414. if (*purl == '/') {
  1415. /* skip duplicate (or initial) slash */
  1416. if (*test == '/') {
  1417. continue;
  1418. }
  1419. if (*test == '.') {
  1420. /* skip extra '.' */
  1421. if (test[1] == '/' || test[1] == 0) {
  1422. continue;
  1423. } else
  1424. /* '..': be careful */
  1425. if (test[1] == '.' && (test[2] == '/' || test[2] == 0)) {
  1426. ++test;
  1427. if (purl == url) {
  1428. /* protect out root */
  1429. goto BAD_REQUEST;
  1430. }
  1431. while (*--purl != '/') /* omit previous dir */;
  1432. continue;
  1433. }
  1434. }
  1435. }
  1436. *++purl = *test;
  1437. } while (*++test);
  1438. *++purl = '\0'; /* so keep last character */
  1439. test = purl; /* end ptr */
  1440. /* If URL is directory, adding '/' */
  1441. if (test[-1] != '/') {
  1442. if (is_directory(url + 1, 1, &sb)) {
  1443. config->found_moved_temporarily = url;
  1444. }
  1445. }
  1446. if (DEBUG)
  1447. fprintf(stderr, "url='%s', args=%s\n", url, config->query);
  1448. test = url;
  1449. ip_allowed = checkPermIP();
  1450. while (ip_allowed && (test = strchr(test + 1, '/')) != NULL) {
  1451. /* have path1/path2 */
  1452. *test = '\0';
  1453. if (is_directory(url + 1, 1, &sb)) {
  1454. /* may be having subdir config */
  1455. parse_conf(url + 1, SUBDIR_PARSE);
  1456. ip_allowed = checkPermIP();
  1457. }
  1458. *test = '/';
  1459. }
  1460. if (blank >= 0) {
  1461. /* read until blank line for HTTP version specified, else parse immediate */
  1462. while (1) {
  1463. alarm(TIMEOUT);
  1464. count = getLine();
  1465. if (count <= 0)
  1466. break;
  1467. if (DEBUG)
  1468. fprintf(stderr, "header: '%s'\n", buf);
  1469. #if ENABLE_FEATURE_HTTPD_CGI
  1470. /* try and do our best to parse more lines */
  1471. if ((STRNCASECMP(buf, "Content-length:") == 0)) {
  1472. /* extra read only for POST */
  1473. if (prequest != request_GET) {
  1474. test = buf + sizeof("Content-length:")-1;
  1475. if (!test[0])
  1476. goto bail_out;
  1477. errno = 0;
  1478. /* not using strtoul: it ignores leading munis! */
  1479. length = strtol(test, &test, 10);
  1480. /* length is "ulong", but we need to pass it to int later */
  1481. /* so we check for negative or too large values in one go: */
  1482. /* (long -> ulong conv caused negatives to be seen as > INT_MAX) */
  1483. if (test[0] || errno || length > INT_MAX)
  1484. goto bail_out;
  1485. }
  1486. } else if ((STRNCASECMP(buf, "Cookie:") == 0)) {
  1487. cookie = strdup(skip_whitespace(buf + sizeof("Cookie:")-1));
  1488. } else if ((STRNCASECMP(buf, "Content-Type:") == 0)) {
  1489. content_type = strdup(skip_whitespace(buf + sizeof("Content-Type:")-1));
  1490. } else if ((STRNCASECMP(buf, "Referer:") == 0)) {
  1491. config->referer = strdup(skip_whitespace(buf + sizeof("Referer:")-1));
  1492. }
  1493. #endif
  1494. #if ENABLE_FEATURE_HTTPD_BASIC_AUTH
  1495. if (STRNCASECMP(buf, "Authorization:") == 0) {
  1496. /* We only allow Basic credentials.
  1497. * It shows up as "Authorization: Basic <userid:password>" where
  1498. * the userid:password is base64 encoded.
  1499. */
  1500. test = skip_whitespace(buf + sizeof("Authorization:")-1);
  1501. if (STRNCASECMP(test, "Basic") != 0)
  1502. continue;
  1503. test += sizeof("Basic")-1;
  1504. /* decodeBase64() skips whitespace itself */
  1505. decodeBase64(test);
  1506. credentials = checkPerm(url, test);
  1507. }
  1508. #endif /* FEATURE_HTTPD_BASIC_AUTH */
  1509. } /* while extra header reading */
  1510. }
  1511. alarm(0);
  1512. if (config->alarm_signaled)
  1513. break;
  1514. if (strcmp(strrchr(url, '/') + 1, httpd_conf) == 0 || ip_allowed == 0) {
  1515. /* protect listing [/path]/httpd_conf or IP deny */
  1516. #if ENABLE_FEATURE_HTTPD_CGI
  1517. FORBIDDEN: /* protect listing /cgi-bin */
  1518. #endif
  1519. sendHeaders(HTTP_FORBIDDEN);
  1520. break;
  1521. }
  1522. #if ENABLE_FEATURE_HTTPD_BASIC_AUTH
  1523. if (credentials <= 0 && checkPerm(url, ":") == 0) {
  1524. sendHeaders(HTTP_UNAUTHORIZED);
  1525. break;
  1526. }
  1527. #endif
  1528. if (config->found_moved_temporarily) {
  1529. sendHeaders(HTTP_MOVED_TEMPORARILY);
  1530. /* clear unforked memory flag */
  1531. config->found_moved_temporarily = NULL;
  1532. break;
  1533. }
  1534. test = url + 1; /* skip first '/' */
  1535. #if ENABLE_FEATURE_HTTPD_CGI
  1536. if (strncmp(test, "cgi-bin", 7) == 0) {
  1537. if (test[7] == '/' && test[8] == 0)
  1538. goto FORBIDDEN; /* protect listing cgi-bin/ */
  1539. sendCgi(url, prequest, length, cookie, content_type);
  1540. break;
  1541. }
  1542. if (prequest != request_GET) {
  1543. sendHeaders(HTTP_NOT_IMPLEMENTED);
  1544. break;
  1545. }
  1546. #endif /* FEATURE_HTTPD_CGI */
  1547. if (purl[-1] == '/')
  1548. strcpy(purl, "index.html");
  1549. if (stat(test, &sb) == 0) {
  1550. /* It's a dir URL and there is index.html */
  1551. config->ContentLength = sb.st_size;
  1552. config->last_mod = sb.st_mtime;
  1553. }
  1554. #if ENABLE_FEATURE_HTTPD_CGI
  1555. else if (purl[-1] == '/') {
  1556. /* It's a dir URL and there is no index.html
  1557. * Try cgi-bin/index.cgi */
  1558. if (access("/cgi-bin/index.cgi"+1, X_OK) == 0) {
  1559. purl[0] = '\0';
  1560. config->query = url;
  1561. sendCgi("/cgi-bin/index.cgi", prequest, length, cookie, content_type);
  1562. break;
  1563. }
  1564. }
  1565. #endif /* FEATURE_HTTPD_CGI */
  1566. sendFile(test);
  1567. config->ContentLength = -1;
  1568. } while (0);
  1569. #if ENABLE_FEATURE_HTTPD_CGI
  1570. bail_out:
  1571. #endif
  1572. if (DEBUG)
  1573. fprintf(stderr, "closing socket\n\n");
  1574. #if ENABLE_FEATURE_HTTPD_CGI
  1575. free(cookie);
  1576. free(content_type);
  1577. free(config->referer);
  1578. config->referer = NULL;
  1579. # if ENABLE_FEATURE_HTTPD_BASIC_AUTH
  1580. free(config->remoteuser);
  1581. config->remoteuser = NULL;
  1582. # endif
  1583. #endif
  1584. shutdown(config->accepted_socket, SHUT_WR);
  1585. /* Properly wait for remote to closed */
  1586. FD_ZERO(&s_fd);
  1587. FD_SET(config->accepted_socket, &s_fd);
  1588. do {
  1589. tv.tv_sec = 2;
  1590. tv.tv_usec = 0;
  1591. retval = select(config->accepted_socket + 1, &s_fd, NULL, NULL, &tv);
  1592. } while (retval > 0 && read(config->accepted_socket, buf, sizeof(config->buf) > 0));
  1593. shutdown(config->accepted_socket, SHUT_RD);
  1594. /* In inetd case, we close fd 1 (stdout) here. We will exit soon anyway */
  1595. close(config->accepted_socket);
  1596. }
  1597. /****************************************************************************
  1598. *
  1599. > $Function: miniHttpd()
  1600. *
  1601. * $Description: The main http server function.
  1602. *
  1603. * Given an open socket fildes, listen for new connections and farm out
  1604. * the processing as a forked process.
  1605. *
  1606. * $Parameters:
  1607. * (int) server. . . The server socket fildes.
  1608. *
  1609. * $Return: (int) . . . . Always 0.
  1610. *
  1611. ****************************************************************************/
  1612. static int miniHttpd(int server)
  1613. {
  1614. fd_set readfd, portfd;
  1615. FD_ZERO(&portfd);
  1616. FD_SET(server, &portfd);
  1617. /* copy the ports we are watching to the readfd set */
  1618. while (1) {
  1619. int s;
  1620. union {
  1621. struct sockaddr sa;
  1622. struct sockaddr_in sin;
  1623. USE_FEATURE_IPV6(struct sockaddr_in6 sin6;)
  1624. } fromAddr;
  1625. socklen_t fromAddrLen = sizeof(fromAddr);
  1626. /* Now wait INDEFINITELY on the set of sockets! */
  1627. readfd = portfd;
  1628. if (select(server + 1, &readfd, 0, 0, 0) <= 0)
  1629. continue;
  1630. if (!FD_ISSET(server, &readfd))
  1631. continue;
  1632. s = accept(server, &fromAddr.sa, &fromAddrLen);
  1633. if (s < 0)
  1634. continue;
  1635. config->accepted_socket = s;
  1636. config->rmt_ip = 0;
  1637. config->port = 0;
  1638. #if ENABLE_FEATURE_HTTPD_CGI || DEBUG
  1639. free(config->rmt_ip_str);
  1640. config->rmt_ip_str = xmalloc_sockaddr2dotted(&fromAddr.sa, fromAddrLen);
  1641. #if DEBUG
  1642. bb_error_msg("connection from '%s'", config->rmt_ip_str);
  1643. #endif
  1644. #endif /* FEATURE_HTTPD_CGI */
  1645. if (fromAddr.sa.sa_family == AF_INET) {
  1646. config->rmt_ip = ntohl(fromAddr.sin.sin_addr.s_addr);
  1647. config->port = ntohs(fromAddr.sin.sin_port);
  1648. }
  1649. #if ENABLE_FEATURE_IPV6
  1650. if (fromAddr.sa.sa_family == AF_INET6) {
  1651. //config->rmt_ip = ntohl(fromAddr.sin.sin_addr.s_addr);
  1652. config->port = ntohs(fromAddr.sin6.sin6_port);
  1653. }
  1654. #endif
  1655. /* set the KEEPALIVE option to cull dead connections */
  1656. setsockopt(s, SOL_SOCKET, SO_KEEPALIVE, &const_int_1, sizeof(const_int_1));
  1657. if (DEBUG || fork() == 0) {
  1658. /* child */
  1659. #if ENABLE_FEATURE_HTTPD_RELOAD_CONFIG_SIGHUP
  1660. /* protect reload config, may be confuse checking */
  1661. signal(SIGHUP, SIG_IGN);
  1662. #endif
  1663. handleIncoming();
  1664. if (!DEBUG)
  1665. exit(0);
  1666. }
  1667. close(s);
  1668. } /* while (1) */
  1669. return 0;
  1670. }
  1671. /* from inetd */
  1672. static int miniHttpd_inetd(void)
  1673. {
  1674. union {
  1675. struct sockaddr sa;
  1676. struct sockaddr_in sin;
  1677. USE_FEATURE_IPV6(struct sockaddr_in6 sin6;)
  1678. } fromAddr;
  1679. socklen_t fromAddrLen = sizeof(fromAddr);
  1680. getpeername(0, &fromAddr.sa, &fromAddrLen);
  1681. config->rmt_ip = 0;
  1682. config->port = 0;
  1683. #if ENABLE_FEATURE_HTTPD_CGI || DEBUG
  1684. free(config->rmt_ip_str);
  1685. config->rmt_ip_str = xmalloc_sockaddr2dotted(&fromAddr.sa, fromAddrLen);
  1686. #endif
  1687. if (fromAddr.sa.sa_family == AF_INET) {
  1688. config->rmt_ip = ntohl(fromAddr.sin.sin_addr.s_addr);
  1689. config->port = ntohs(fromAddr.sin.sin_port);
  1690. }
  1691. #if ENABLE_FEATURE_IPV6
  1692. if (fromAddr.sa.sa_family == AF_INET6) {
  1693. //config->rmt_ip = ntohl(fromAddr.sin.sin_addr.s_addr);
  1694. config->port = ntohs(fromAddr.sin6.sin6_port);
  1695. }
  1696. #endif
  1697. handleIncoming();
  1698. return 0;
  1699. }
  1700. #if ENABLE_FEATURE_HTTPD_RELOAD_CONFIG_SIGHUP
  1701. static void sighup_handler(int sig)
  1702. {
  1703. /* set and reset */
  1704. struct sigaction sa;
  1705. parse_conf(default_path_httpd_conf, sig == SIGHUP ? SIGNALED_PARSE : FIRST_PARSE);
  1706. sa.sa_handler = sighup_handler;
  1707. sigemptyset(&sa.sa_mask);
  1708. sa.sa_flags = SA_RESTART;
  1709. sigaction(SIGHUP, &sa, NULL);
  1710. }
  1711. #endif
  1712. enum {
  1713. c_opt_config_file = 0,
  1714. d_opt_decode_url,
  1715. h_opt_home_httpd,
  1716. USE_FEATURE_HTTPD_ENCODE_URL_STR(e_opt_encode_url,)
  1717. USE_FEATURE_HTTPD_BASIC_AUTH( r_opt_realm ,)
  1718. USE_FEATURE_HTTPD_AUTH_MD5( m_opt_md5 ,)
  1719. USE_FEATURE_HTTPD_SETUID( u_opt_setuid ,)
  1720. p_opt_port ,
  1721. p_opt_inetd ,
  1722. p_opt_foreground,
  1723. OPT_CONFIG_FILE = 1 << c_opt_config_file,
  1724. OPT_DECODE_URL = 1 << d_opt_decode_url,
  1725. OPT_HOME_HTTPD = 1 << h_opt_home_httpd,
  1726. OPT_ENCODE_URL = USE_FEATURE_HTTPD_ENCODE_URL_STR((1 << e_opt_encode_url)) + 0,
  1727. OPT_REALM = USE_FEATURE_HTTPD_BASIC_AUTH( (1 << r_opt_realm )) + 0,
  1728. OPT_MD5 = USE_FEATURE_HTTPD_AUTH_MD5( (1 << m_opt_md5 )) + 0,
  1729. OPT_SETUID = USE_FEATURE_HTTPD_SETUID( (1 << u_opt_setuid )) + 0,
  1730. OPT_PORT = 1 << p_opt_port,
  1731. OPT_INETD = 1 << p_opt_inetd,
  1732. OPT_FOREGROUND = 1 << p_opt_foreground,
  1733. };
  1734. static const char httpd_opts[] = "c:d:h:"
  1735. USE_FEATURE_HTTPD_ENCODE_URL_STR("e:")
  1736. USE_FEATURE_HTTPD_BASIC_AUTH("r:")
  1737. USE_FEATURE_HTTPD_AUTH_MD5("m:")
  1738. USE_FEATURE_HTTPD_SETUID("u:")
  1739. "p:if";
  1740. int httpd_main(int argc, char *argv[])
  1741. {
  1742. unsigned opt;
  1743. const char *home_httpd = home;
  1744. char *url_for_decode;
  1745. USE_FEATURE_HTTPD_ENCODE_URL_STR(const char *url_for_encode;)
  1746. const char *s_port;
  1747. USE_FEATURE_HTTPD_SETUID(const char *s_ugid = NULL;)
  1748. USE_FEATURE_HTTPD_SETUID(struct bb_uidgid_t ugid;)
  1749. USE_FEATURE_HTTPD_AUTH_MD5(const char *pass;)
  1750. #if ENABLE_LOCALE_SUPPORT
  1751. /* Undo busybox.c: we want to speak English in http (dates etc) */
  1752. setlocale(LC_TIME, "C");
  1753. #endif
  1754. config = xzalloc(sizeof(*config));
  1755. #if ENABLE_FEATURE_HTTPD_BASIC_AUTH
  1756. config->realm = "Web Server Authentication";
  1757. #endif
  1758. config->port = 80;
  1759. config->ContentLength = -1;
  1760. opt = getopt32(argc, argv, httpd_opts,
  1761. &(config->configFile), &url_for_decode, &home_httpd
  1762. USE_FEATURE_HTTPD_ENCODE_URL_STR(, &url_for_encode)
  1763. USE_FEATURE_HTTPD_BASIC_AUTH(, &(config->realm))
  1764. USE_FEATURE_HTTPD_AUTH_MD5(, &pass)
  1765. USE_FEATURE_HTTPD_SETUID(, &s_ugid)
  1766. , &s_port
  1767. );
  1768. if (opt & OPT_DECODE_URL) {
  1769. printf("%s", decodeString(url_for_decode, 1));
  1770. return 0;
  1771. }
  1772. #if ENABLE_FEATURE_HTTPD_ENCODE_URL_STR
  1773. if (opt & OPT_ENCODE_URL) {
  1774. printf("%s", encodeString(url_for_encode));
  1775. return 0;
  1776. }
  1777. #endif
  1778. #if ENABLE_FEATURE_HTTPD_AUTH_MD5
  1779. if (opt & OPT_MD5) {
  1780. puts(pw_encrypt(pass, "$1$"));
  1781. return 0;
  1782. }
  1783. #endif
  1784. if (opt & OPT_PORT)
  1785. config->port = xatou16(s_port);
  1786. #if ENABLE_FEATURE_HTTPD_SETUID
  1787. if (opt & OPT_SETUID) {
  1788. if (!get_uidgid(&ugid, s_ugid, 1))
  1789. bb_error_msg_and_die("unrecognized user[:group] "
  1790. "name '%s'", s_ugid);
  1791. }
  1792. #endif
  1793. xchdir(home_httpd);
  1794. if (!(opt & OPT_INETD)) {
  1795. signal(SIGCHLD, SIG_IGN);
  1796. config->server_socket = openServer();
  1797. #if ENABLE_FEATURE_HTTPD_SETUID
  1798. /* drop privileges */
  1799. if (opt & OPT_SETUID) {
  1800. if (ugid.gid != (gid_t)-1) {
  1801. if (setgroups(1, &ugid.gid) == -1)
  1802. bb_perror_msg_and_die("setgroups");
  1803. xsetgid(ugid.gid);
  1804. }
  1805. xsetuid(ugid.uid);
  1806. }
  1807. #endif
  1808. }
  1809. #if ENABLE_FEATURE_HTTPD_CGI
  1810. {
  1811. char *p = getenv("PATH");
  1812. p = xstrdup(p); /* if gets NULL, returns NULL */
  1813. clearenv();
  1814. if (p)
  1815. setenv1("PATH", p);
  1816. if (!(opt & OPT_INETD))
  1817. setenv_long("SERVER_PORT", config->port);
  1818. }
  1819. #endif
  1820. #if ENABLE_FEATURE_HTTPD_RELOAD_CONFIG_SIGHUP
  1821. sighup_handler(0);
  1822. #else
  1823. parse_conf(default_path_httpd_conf, FIRST_PARSE);
  1824. #endif
  1825. if (opt & OPT_INETD)
  1826. return miniHttpd_inetd();
  1827. if (!(opt & OPT_FOREGROUND))
  1828. xdaemon(1, 0); /* don't change current directory */
  1829. return miniHttpd(config->server_socket);
  1830. }