httpd.c 55 KB

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