3
0

httpd.c 67 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463
  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. * Licensed under GPLv2 or later, see file LICENSE in this source tree.
  9. *
  10. *****************************************************************************
  11. *
  12. * Typical usage:
  13. * For non root user:
  14. * httpd -p 8080 -h $HOME/public_html
  15. * For daemon start from rc script with uid=0:
  16. * httpd -u www
  17. * which is equivalent to (assuming user www has uid 80):
  18. * httpd -p 80 -u 80 -h $PWD -c /etc/httpd.conf -r "Web Server Authentication"
  19. *
  20. * When an url starts with "/cgi-bin/" it is assumed to be a cgi script.
  21. * The server changes directory to the location of the script and executes it
  22. * after setting QUERY_STRING and other environment variables.
  23. *
  24. * Doc:
  25. * "CGI Environment Variables": http://hoohoo.ncsa.uiuc.edu/cgi/env.html
  26. *
  27. * The applet can also be invoked as an url arg decoder and html text encoder
  28. * as follows:
  29. * foo=`httpd -d $foo` # decode "Hello%20World" as "Hello World"
  30. * bar=`httpd -e "<Hello World>"` # encode as "&#60Hello&#32World&#62"
  31. * Note that url encoding for arguments is not the same as html encoding for
  32. * presentation. -d decodes an url-encoded argument while -e encodes in html
  33. * for page display.
  34. *
  35. * httpd.conf has the following format:
  36. *
  37. * H:/serverroot # define the server root. It will override -h
  38. * A:172.20. # Allow address from 172.20.0.0/16
  39. * A:10.0.0.0/25 # Allow any address from 10.0.0.0-10.0.0.127
  40. * A:10.0.0.0/255.255.255.128 # Allow any address that previous set
  41. * A:127.0.0.1 # Allow local loopback connections
  42. * D:* # Deny from other IP connections
  43. * E404:/path/e404.html # /path/e404.html is the 404 (not found) error page
  44. * I:index.html # Show index.html when a directory is requested
  45. *
  46. * P:/url:[http://]hostname[:port]/new/path
  47. * # When /urlXXXXXX is requested, reverse proxy
  48. * # it to http://hostname[:port]/new/pathXXXXXX
  49. *
  50. * /cgi-bin:foo:bar # Require user foo, pwd bar on urls starting with /cgi-bin/
  51. * /adm:admin:setup # Require user admin, pwd setup on urls starting with /adm/
  52. * /adm:toor:PaSsWd # or user toor, pwd PaSsWd on urls starting with /adm/
  53. * .au:audio/basic # additional mime type for audio.au files
  54. * *.php:/path/php # run xxx.php through an interpreter
  55. *
  56. * A/D may be as a/d or allow/deny - only first char matters.
  57. * Deny/Allow IP logic:
  58. * - Default is to allow all (Allow all (A:*) is a no-op).
  59. * - Deny rules take precedence over allow rules.
  60. * - "Deny all" rule (D:*) is applied last.
  61. *
  62. * Example:
  63. * 1. Allow only specified addresses
  64. * A:172.20 # Allow any address that begins with 172.20.
  65. * A:10.10. # Allow any address that begins with 10.10.
  66. * A:127.0.0.1 # Allow local loopback connections
  67. * D:* # Deny from other IP connections
  68. *
  69. * 2. Only deny specified addresses
  70. * D:1.2.3. # deny from 1.2.3.0 - 1.2.3.255
  71. * D:2.3.4. # deny from 2.3.4.0 - 2.3.4.255
  72. * A:* # (optional line added for clarity)
  73. *
  74. * If a sub directory contains a config file it is parsed and merged with
  75. * any existing settings as if it was appended to the original configuration.
  76. *
  77. * subdir paths are relative to the containing subdir and thus cannot
  78. * affect the parent rules.
  79. *
  80. * Note that since the sub dir is parsed in the forked thread servicing the
  81. * subdir http request, any merge is discarded when the process exits. As a
  82. * result, the subdir settings only have a lifetime of a single request.
  83. *
  84. * Custom error pages can contain an absolute path or be relative to
  85. * 'home_httpd'. Error pages are to be static files (no CGI or script). Error
  86. * page can only be defined in the root configuration file and are not taken
  87. * into account in local (directories) config files.
  88. *
  89. * If -c is not set, an attempt will be made to open the default
  90. * root configuration file. If -c is set and the file is not found, the
  91. * server exits with an error.
  92. *
  93. */
  94. /* TODO: use TCP_CORK, parse_config() */
  95. #include "libbb.h"
  96. #if ENABLE_FEATURE_HTTPD_USE_SENDFILE
  97. # include <sys/sendfile.h>
  98. #endif
  99. /* amount of buffering in a pipe */
  100. #ifndef PIPE_BUF
  101. # define PIPE_BUF 4096
  102. #endif
  103. #define DEBUG 0
  104. #define IOBUF_SIZE 8192
  105. #if PIPE_BUF >= IOBUF_SIZE
  106. # error "PIPE_BUF >= IOBUF_SIZE"
  107. #endif
  108. #define HEADER_READ_TIMEOUT 60
  109. static const char DEFAULT_PATH_HTTPD_CONF[] ALIGN1 = "/etc";
  110. static const char HTTPD_CONF[] ALIGN1 = "httpd.conf";
  111. static const char HTTP_200[] ALIGN1 = "HTTP/1.0 200 OK\r\n";
  112. static const char index_html[] ALIGN1 = "index.html";
  113. typedef struct has_next_ptr {
  114. struct has_next_ptr *next;
  115. } has_next_ptr;
  116. /* Must have "next" as a first member */
  117. typedef struct Htaccess {
  118. struct Htaccess *next;
  119. char *after_colon;
  120. char before_colon[1]; /* really bigger, must be last */
  121. } Htaccess;
  122. /* Must have "next" as a first member */
  123. typedef struct Htaccess_IP {
  124. struct Htaccess_IP *next;
  125. unsigned ip;
  126. unsigned mask;
  127. int allow_deny;
  128. } Htaccess_IP;
  129. /* Must have "next" as a first member */
  130. typedef struct Htaccess_Proxy {
  131. struct Htaccess_Proxy *next;
  132. char *url_from;
  133. char *host_port;
  134. char *url_to;
  135. } Htaccess_Proxy;
  136. enum {
  137. HTTP_OK = 200,
  138. HTTP_PARTIAL_CONTENT = 206,
  139. HTTP_MOVED_TEMPORARILY = 302,
  140. HTTP_BAD_REQUEST = 400, /* malformed syntax */
  141. HTTP_UNAUTHORIZED = 401, /* authentication needed, respond with auth hdr */
  142. HTTP_NOT_FOUND = 404,
  143. HTTP_FORBIDDEN = 403,
  144. HTTP_REQUEST_TIMEOUT = 408,
  145. HTTP_NOT_IMPLEMENTED = 501, /* used for unrecognized requests */
  146. HTTP_INTERNAL_SERVER_ERROR = 500,
  147. HTTP_CONTINUE = 100,
  148. #if 0 /* future use */
  149. HTTP_SWITCHING_PROTOCOLS = 101,
  150. HTTP_CREATED = 201,
  151. HTTP_ACCEPTED = 202,
  152. HTTP_NON_AUTHORITATIVE_INFO = 203,
  153. HTTP_NO_CONTENT = 204,
  154. HTTP_MULTIPLE_CHOICES = 300,
  155. HTTP_MOVED_PERMANENTLY = 301,
  156. HTTP_NOT_MODIFIED = 304,
  157. HTTP_PAYMENT_REQUIRED = 402,
  158. HTTP_BAD_GATEWAY = 502,
  159. HTTP_SERVICE_UNAVAILABLE = 503, /* overload, maintenance */
  160. #endif
  161. };
  162. static const uint16_t http_response_type[] ALIGN2 = {
  163. HTTP_OK,
  164. #if ENABLE_FEATURE_HTTPD_RANGES
  165. HTTP_PARTIAL_CONTENT,
  166. #endif
  167. HTTP_MOVED_TEMPORARILY,
  168. HTTP_REQUEST_TIMEOUT,
  169. HTTP_NOT_IMPLEMENTED,
  170. #if ENABLE_FEATURE_HTTPD_BASIC_AUTH
  171. HTTP_UNAUTHORIZED,
  172. #endif
  173. HTTP_NOT_FOUND,
  174. HTTP_BAD_REQUEST,
  175. HTTP_FORBIDDEN,
  176. HTTP_INTERNAL_SERVER_ERROR,
  177. #if 0 /* not implemented */
  178. HTTP_CREATED,
  179. HTTP_ACCEPTED,
  180. HTTP_NO_CONTENT,
  181. HTTP_MULTIPLE_CHOICES,
  182. HTTP_MOVED_PERMANENTLY,
  183. HTTP_NOT_MODIFIED,
  184. HTTP_BAD_GATEWAY,
  185. HTTP_SERVICE_UNAVAILABLE,
  186. #endif
  187. };
  188. static const struct {
  189. const char *name;
  190. const char *info;
  191. } http_response[ARRAY_SIZE(http_response_type)] = {
  192. { "OK", NULL },
  193. #if ENABLE_FEATURE_HTTPD_RANGES
  194. { "Partial Content", NULL },
  195. #endif
  196. { "Found", NULL },
  197. { "Request Timeout", "No request appeared within 60 seconds" },
  198. { "Not Implemented", "The requested method is not recognized" },
  199. #if ENABLE_FEATURE_HTTPD_BASIC_AUTH
  200. { "Unauthorized", "" },
  201. #endif
  202. { "Not Found", "The requested URL was not found" },
  203. { "Bad Request", "Unsupported method" },
  204. { "Forbidden", "" },
  205. { "Internal Server Error", "Internal Server Error" },
  206. #if 0 /* not implemented */
  207. { "Created" },
  208. { "Accepted" },
  209. { "No Content" },
  210. { "Multiple Choices" },
  211. { "Moved Permanently" },
  212. { "Not Modified" },
  213. { "Bad Gateway", "" },
  214. { "Service Unavailable", "" },
  215. #endif
  216. };
  217. struct globals {
  218. int verbose; /* must be int (used by getopt32) */
  219. smallint flg_deny_all;
  220. unsigned rmt_ip; /* used for IP-based allow/deny rules */
  221. time_t last_mod;
  222. char *rmt_ip_str; /* for $REMOTE_ADDR and $REMOTE_PORT */
  223. const char *bind_addr_or_port;
  224. const char *g_query;
  225. const char *opt_c_configFile;
  226. const char *home_httpd;
  227. const char *index_page;
  228. const char *found_mime_type;
  229. const char *found_moved_temporarily;
  230. Htaccess_IP *ip_a_d; /* config allow/deny lines */
  231. IF_FEATURE_HTTPD_BASIC_AUTH(const char *g_realm;)
  232. IF_FEATURE_HTTPD_BASIC_AUTH(char *remoteuser;)
  233. IF_FEATURE_HTTPD_CGI(char *referer;)
  234. IF_FEATURE_HTTPD_CGI(char *user_agent;)
  235. IF_FEATURE_HTTPD_CGI(char *host;)
  236. IF_FEATURE_HTTPD_CGI(char *http_accept;)
  237. IF_FEATURE_HTTPD_CGI(char *http_accept_language;)
  238. off_t file_size; /* -1 - unknown */
  239. #if ENABLE_FEATURE_HTTPD_RANGES
  240. off_t range_start;
  241. off_t range_end;
  242. off_t range_len;
  243. #endif
  244. #if ENABLE_FEATURE_HTTPD_BASIC_AUTH
  245. Htaccess *g_auth; /* config user:password lines */
  246. #endif
  247. Htaccess *mime_a; /* config mime types */
  248. #if ENABLE_FEATURE_HTTPD_CONFIG_WITH_SCRIPT_INTERPR
  249. Htaccess *script_i; /* config script interpreters */
  250. #endif
  251. char *iobuf; /* [IOBUF_SIZE] */
  252. #define hdr_buf bb_common_bufsiz1
  253. char *hdr_ptr;
  254. int hdr_cnt;
  255. #if ENABLE_FEATURE_HTTPD_ERROR_PAGES
  256. const char *http_error_page[ARRAY_SIZE(http_response_type)];
  257. #endif
  258. #if ENABLE_FEATURE_HTTPD_PROXY
  259. Htaccess_Proxy *proxy;
  260. #endif
  261. #if ENABLE_FEATURE_HTTPD_GZIP
  262. /* client can handle gzip / we are going to send gzip */
  263. smallint content_gzip;
  264. #endif
  265. };
  266. #define G (*ptr_to_globals)
  267. #define verbose (G.verbose )
  268. #define flg_deny_all (G.flg_deny_all )
  269. #define rmt_ip (G.rmt_ip )
  270. #define bind_addr_or_port (G.bind_addr_or_port)
  271. #define g_query (G.g_query )
  272. #define opt_c_configFile (G.opt_c_configFile )
  273. #define home_httpd (G.home_httpd )
  274. #define index_page (G.index_page )
  275. #define found_mime_type (G.found_mime_type )
  276. #define found_moved_temporarily (G.found_moved_temporarily)
  277. #define last_mod (G.last_mod )
  278. #define ip_a_d (G.ip_a_d )
  279. #define g_realm (G.g_realm )
  280. #define remoteuser (G.remoteuser )
  281. #define referer (G.referer )
  282. #define user_agent (G.user_agent )
  283. #define host (G.host )
  284. #define http_accept (G.http_accept )
  285. #define http_accept_language (G.http_accept_language)
  286. #define file_size (G.file_size )
  287. #if ENABLE_FEATURE_HTTPD_RANGES
  288. #define range_start (G.range_start )
  289. #define range_end (G.range_end )
  290. #define range_len (G.range_len )
  291. #else
  292. enum {
  293. range_start = 0,
  294. range_end = MAXINT(off_t) - 1,
  295. range_len = MAXINT(off_t),
  296. };
  297. #endif
  298. #define rmt_ip_str (G.rmt_ip_str )
  299. #define g_auth (G.g_auth )
  300. #define mime_a (G.mime_a )
  301. #define script_i (G.script_i )
  302. #define iobuf (G.iobuf )
  303. #define hdr_ptr (G.hdr_ptr )
  304. #define hdr_cnt (G.hdr_cnt )
  305. #define http_error_page (G.http_error_page )
  306. #define proxy (G.proxy )
  307. #if ENABLE_FEATURE_HTTPD_GZIP
  308. # define content_gzip (G.content_gzip )
  309. #else
  310. # define content_gzip 0
  311. #endif
  312. #define INIT_G() do { \
  313. SET_PTR_TO_GLOBALS(xzalloc(sizeof(G))); \
  314. IF_FEATURE_HTTPD_BASIC_AUTH(g_realm = "Web Server Authentication";) \
  315. bind_addr_or_port = "80"; \
  316. index_page = index_html; \
  317. file_size = -1; \
  318. } while (0)
  319. #define STRNCASECMP(a, str) strncasecmp((a), (str), sizeof(str)-1)
  320. /* Prototypes */
  321. enum {
  322. SEND_HEADERS = (1 << 0),
  323. SEND_BODY = (1 << 1),
  324. SEND_HEADERS_AND_BODY = SEND_HEADERS + SEND_BODY,
  325. };
  326. static void send_file_and_exit(const char *url, int what) NORETURN;
  327. static void free_llist(has_next_ptr **pptr)
  328. {
  329. has_next_ptr *cur = *pptr;
  330. while (cur) {
  331. has_next_ptr *t = cur;
  332. cur = cur->next;
  333. free(t);
  334. }
  335. *pptr = NULL;
  336. }
  337. static ALWAYS_INLINE void free_Htaccess_list(Htaccess **pptr)
  338. {
  339. free_llist((has_next_ptr**)pptr);
  340. }
  341. static ALWAYS_INLINE void free_Htaccess_IP_list(Htaccess_IP **pptr)
  342. {
  343. free_llist((has_next_ptr**)pptr);
  344. }
  345. /* Returns presumed mask width in bits or < 0 on error.
  346. * Updates strp, stores IP at provided pointer */
  347. static int scan_ip(const char **strp, unsigned *ipp, unsigned char endc)
  348. {
  349. const char *p = *strp;
  350. int auto_mask = 8;
  351. unsigned ip = 0;
  352. int j;
  353. if (*p == '/')
  354. return -auto_mask;
  355. for (j = 0; j < 4; j++) {
  356. unsigned octet;
  357. if ((*p < '0' || *p > '9') && *p != '/' && *p)
  358. return -auto_mask;
  359. octet = 0;
  360. while (*p >= '0' && *p <= '9') {
  361. octet *= 10;
  362. octet += *p - '0';
  363. if (octet > 255)
  364. return -auto_mask;
  365. p++;
  366. }
  367. if (*p == '.')
  368. p++;
  369. if (*p != '/' && *p)
  370. auto_mask += 8;
  371. ip = (ip << 8) | octet;
  372. }
  373. if (*p) {
  374. if (*p != endc)
  375. return -auto_mask;
  376. p++;
  377. if (*p == '\0')
  378. return -auto_mask;
  379. }
  380. *ipp = ip;
  381. *strp = p;
  382. return auto_mask;
  383. }
  384. /* Returns 0 on success. Stores IP and mask at provided pointers */
  385. static int scan_ip_mask(const char *str, unsigned *ipp, unsigned *maskp)
  386. {
  387. int i;
  388. unsigned mask;
  389. char *p;
  390. i = scan_ip(&str, ipp, '/');
  391. if (i < 0)
  392. return i;
  393. if (*str) {
  394. /* there is /xxx after dotted-IP address */
  395. i = bb_strtou(str, &p, 10);
  396. if (*p == '.') {
  397. /* 'xxx' itself is dotted-IP mask, parse it */
  398. /* (return 0 (success) only if it has N.N.N.N form) */
  399. return scan_ip(&str, maskp, '\0') - 32;
  400. }
  401. if (*p)
  402. return -1;
  403. }
  404. if (i > 32)
  405. return -1;
  406. if (sizeof(unsigned) == 4 && i == 32) {
  407. /* mask >>= 32 below may not work */
  408. mask = 0;
  409. } else {
  410. mask = 0xffffffff;
  411. mask >>= i;
  412. }
  413. /* i == 0 -> *maskp = 0x00000000
  414. * i == 1 -> *maskp = 0x80000000
  415. * i == 4 -> *maskp = 0xf0000000
  416. * i == 31 -> *maskp = 0xfffffffe
  417. * i == 32 -> *maskp = 0xffffffff */
  418. *maskp = (uint32_t)(~mask);
  419. return 0;
  420. }
  421. /*
  422. * Parse configuration file into in-memory linked list.
  423. *
  424. * Any previous IP rules are discarded.
  425. * If the flag argument is not SUBDIR_PARSE then all /path and mime rules
  426. * are also discarded. That is, previous settings are retained if flag is
  427. * SUBDIR_PARSE.
  428. * Error pages are only parsed on the main config file.
  429. *
  430. * path Path where to look for httpd.conf (without filename).
  431. * flag Type of the parse request.
  432. */
  433. /* flag param: */
  434. enum {
  435. FIRST_PARSE = 0, /* path will be "/etc" */
  436. SIGNALED_PARSE = 1, /* path will be "/etc" */
  437. SUBDIR_PARSE = 2, /* path will be derived from URL */
  438. };
  439. static void parse_conf(const char *path, int flag)
  440. {
  441. /* internally used extra flag state */
  442. enum { TRY_CURDIR_PARSE = 3 };
  443. FILE *f;
  444. const char *filename;
  445. char buf[160];
  446. /* discard old rules */
  447. free_Htaccess_IP_list(&ip_a_d);
  448. flg_deny_all = 0;
  449. /* retain previous auth and mime config only for subdir parse */
  450. if (flag != SUBDIR_PARSE) {
  451. free_Htaccess_list(&mime_a);
  452. #if ENABLE_FEATURE_HTTPD_BASIC_AUTH
  453. free_Htaccess_list(&g_auth);
  454. #endif
  455. #if ENABLE_FEATURE_HTTPD_CONFIG_WITH_SCRIPT_INTERPR
  456. free_Htaccess_list(&script_i);
  457. #endif
  458. }
  459. filename = opt_c_configFile;
  460. if (flag == SUBDIR_PARSE || filename == NULL) {
  461. filename = alloca(strlen(path) + sizeof(HTTPD_CONF) + 2);
  462. sprintf((char *)filename, "%s/%s", path, HTTPD_CONF);
  463. }
  464. while ((f = fopen_for_read(filename)) == NULL) {
  465. if (flag >= SUBDIR_PARSE) { /* SUBDIR or TRY_CURDIR */
  466. /* config file not found, no changes to config */
  467. return;
  468. }
  469. if (flag == FIRST_PARSE) {
  470. /* -c CONFFILE given, but CONFFILE doesn't exist? */
  471. if (opt_c_configFile)
  472. bb_simple_perror_msg_and_die(opt_c_configFile);
  473. /* else: no -c, thus we looked at /etc/httpd.conf,
  474. * and it's not there. try ./httpd.conf: */
  475. }
  476. flag = TRY_CURDIR_PARSE;
  477. filename = HTTPD_CONF;
  478. }
  479. #if ENABLE_FEATURE_HTTPD_BASIC_AUTH
  480. /* in "/file:user:pass" lines, we prepend path in subdirs */
  481. if (flag != SUBDIR_PARSE)
  482. path = "";
  483. #endif
  484. /* The lines can be:
  485. *
  486. * I:default_index_file
  487. * H:http_home
  488. * [AD]:IP[/mask] # allow/deny, * for wildcard
  489. * Ennn:error.html # error page for status nnn
  490. * P:/url:[http://]hostname[:port]/new/path # reverse proxy
  491. * .ext:mime/type # mime type
  492. * *.php:/path/php # run xxx.php through an interpreter
  493. * /file:user:pass # username and password
  494. */
  495. while (fgets(buf, sizeof(buf), f) != NULL) {
  496. unsigned strlen_buf;
  497. unsigned char ch;
  498. char *after_colon;
  499. { /* remove all whitespace, and # comments */
  500. char *p, *p0;
  501. p0 = buf;
  502. /* skip non-whitespace beginning. Often the whole line
  503. * is non-whitespace. We want this case to work fast,
  504. * without needless copying, therefore we don't merge
  505. * this operation into next while loop. */
  506. while ((ch = *p0) != '\0' && ch != '\n' && ch != '#'
  507. && ch != ' ' && ch != '\t'
  508. ) {
  509. p0++;
  510. }
  511. p = p0;
  512. /* if we enter this loop, we have some whitespace.
  513. * discard it */
  514. while (ch != '\0' && ch != '\n' && ch != '#') {
  515. if (ch != ' ' && ch != '\t') {
  516. *p++ = ch;
  517. }
  518. ch = *++p0;
  519. }
  520. *p = '\0';
  521. strlen_buf = p - buf;
  522. if (strlen_buf == 0)
  523. continue; /* empty line */
  524. }
  525. after_colon = strchr(buf, ':');
  526. /* strange line? */
  527. if (after_colon == NULL || *++after_colon == '\0')
  528. goto config_error;
  529. ch = (buf[0] & ~0x20); /* toupper if it's a letter */
  530. if (ch == 'I') {
  531. if (index_page != index_html)
  532. free((char*)index_page);
  533. index_page = xstrdup(after_colon);
  534. continue;
  535. }
  536. /* do not allow jumping around using H in subdir's configs */
  537. if (flag == FIRST_PARSE && ch == 'H') {
  538. home_httpd = xstrdup(after_colon);
  539. xchdir(home_httpd);
  540. continue;
  541. }
  542. if (ch == 'A' || ch == 'D') {
  543. Htaccess_IP *pip;
  544. if (*after_colon == '*') {
  545. if (ch == 'D') {
  546. /* memorize "deny all" */
  547. flg_deny_all = 1;
  548. }
  549. /* skip assumed "A:*", it is a default anyway */
  550. continue;
  551. }
  552. /* store "allow/deny IP/mask" line */
  553. pip = xzalloc(sizeof(*pip));
  554. if (scan_ip_mask(after_colon, &pip->ip, &pip->mask)) {
  555. /* IP{/mask} syntax error detected, protect all */
  556. ch = 'D';
  557. pip->mask = 0;
  558. }
  559. pip->allow_deny = ch;
  560. if (ch == 'D') {
  561. /* Deny:from_IP - prepend */
  562. pip->next = ip_a_d;
  563. ip_a_d = pip;
  564. } else {
  565. /* A:from_IP - append (thus all D's precedes A's) */
  566. Htaccess_IP *prev_IP = ip_a_d;
  567. if (prev_IP == NULL) {
  568. ip_a_d = pip;
  569. } else {
  570. while (prev_IP->next)
  571. prev_IP = prev_IP->next;
  572. prev_IP->next = pip;
  573. }
  574. }
  575. continue;
  576. }
  577. #if ENABLE_FEATURE_HTTPD_ERROR_PAGES
  578. if (flag == FIRST_PARSE && ch == 'E') {
  579. unsigned i;
  580. int status = atoi(buf + 1); /* error status code */
  581. if (status < HTTP_CONTINUE) {
  582. goto config_error;
  583. }
  584. /* then error page; find matching status */
  585. for (i = 0; i < ARRAY_SIZE(http_response_type); i++) {
  586. if (http_response_type[i] == status) {
  587. /* We chdir to home_httpd, thus no need to
  588. * concat_path_file(home_httpd, after_colon)
  589. * here */
  590. http_error_page[i] = xstrdup(after_colon);
  591. break;
  592. }
  593. }
  594. continue;
  595. }
  596. #endif
  597. #if ENABLE_FEATURE_HTTPD_PROXY
  598. if (flag == FIRST_PARSE && ch == 'P') {
  599. /* P:/url:[http://]hostname[:port]/new/path */
  600. char *url_from, *host_port, *url_to;
  601. Htaccess_Proxy *proxy_entry;
  602. url_from = after_colon;
  603. host_port = strchr(after_colon, ':');
  604. if (host_port == NULL) {
  605. goto config_error;
  606. }
  607. *host_port++ = '\0';
  608. if (strncmp(host_port, "http://", 7) == 0)
  609. host_port += 7;
  610. if (*host_port == '\0') {
  611. goto config_error;
  612. }
  613. url_to = strchr(host_port, '/');
  614. if (url_to == NULL) {
  615. goto config_error;
  616. }
  617. *url_to = '\0';
  618. proxy_entry = xzalloc(sizeof(*proxy_entry));
  619. proxy_entry->url_from = xstrdup(url_from);
  620. proxy_entry->host_port = xstrdup(host_port);
  621. *url_to = '/';
  622. proxy_entry->url_to = xstrdup(url_to);
  623. proxy_entry->next = proxy;
  624. proxy = proxy_entry;
  625. continue;
  626. }
  627. #endif
  628. /* the rest of directives are non-alphabetic,
  629. * must avoid using "toupper'ed" ch */
  630. ch = buf[0];
  631. if (ch == '.' /* ".ext:mime/type" */
  632. #if ENABLE_FEATURE_HTTPD_CONFIG_WITH_SCRIPT_INTERPR
  633. || (ch == '*' && buf[1] == '.') /* "*.php:/path/php" */
  634. #endif
  635. ) {
  636. char *p;
  637. Htaccess *cur;
  638. cur = xzalloc(sizeof(*cur) /* includes space for NUL */ + strlen_buf);
  639. strcpy(cur->before_colon, buf);
  640. p = cur->before_colon + (after_colon - buf);
  641. p[-1] = '\0';
  642. cur->after_colon = p;
  643. if (ch == '.') {
  644. /* .mime line: prepend to mime_a list */
  645. cur->next = mime_a;
  646. mime_a = cur;
  647. }
  648. #if ENABLE_FEATURE_HTTPD_CONFIG_WITH_SCRIPT_INTERPR
  649. else {
  650. /* script interpreter line: prepend to script_i list */
  651. cur->next = script_i;
  652. script_i = cur;
  653. }
  654. #endif
  655. continue;
  656. }
  657. #if ENABLE_FEATURE_HTTPD_BASIC_AUTH
  658. if (ch == '/') { /* "/file:user:pass" */
  659. char *p;
  660. Htaccess *cur;
  661. unsigned file_len;
  662. /* note: path is "" unless we are in SUBDIR parse,
  663. * otherwise it does NOT start with "/" */
  664. cur = xzalloc(sizeof(*cur) /* includes space for NUL */
  665. + 1 + strlen(path)
  666. + strlen_buf
  667. );
  668. /* form "/path/file" */
  669. sprintf(cur->before_colon, "/%s%.*s",
  670. path,
  671. (int) (after_colon - buf - 1), /* includes "/", but not ":" */
  672. buf);
  673. /* canonicalize it */
  674. p = bb_simplify_abs_path_inplace(cur->before_colon);
  675. file_len = p - cur->before_colon;
  676. /* add "user:pass" after NUL */
  677. strcpy(++p, after_colon);
  678. cur->after_colon = p;
  679. /* insert cur into g_auth */
  680. /* g_auth is sorted by decreased filename length */
  681. {
  682. Htaccess *auth, **authp;
  683. authp = &g_auth;
  684. while ((auth = *authp) != NULL) {
  685. if (file_len >= strlen(auth->before_colon)) {
  686. /* insert cur before auth */
  687. cur->next = auth;
  688. break;
  689. }
  690. authp = &auth->next;
  691. }
  692. *authp = cur;
  693. }
  694. continue;
  695. }
  696. #endif /* BASIC_AUTH */
  697. /* the line is not recognized */
  698. config_error:
  699. bb_error_msg("config error '%s' in '%s'", buf, filename);
  700. } /* while (fgets) */
  701. fclose(f);
  702. }
  703. #if ENABLE_FEATURE_HTTPD_ENCODE_URL_STR
  704. /*
  705. * Given a string, html-encode special characters.
  706. * This is used for the -e command line option to provide an easy way
  707. * for scripts to encode result data without confusing browsers. The
  708. * returned string pointer is memory allocated by malloc().
  709. *
  710. * Returns a pointer to the encoded string (malloced).
  711. */
  712. static char *encodeString(const char *string)
  713. {
  714. /* take the simple route and encode everything */
  715. /* could possibly scan once to get length. */
  716. int len = strlen(string);
  717. char *out = xmalloc(len * 6 + 1);
  718. char *p = out;
  719. char ch;
  720. while ((ch = *string++) != '\0') {
  721. /* very simple check for what to encode */
  722. if (isalnum(ch))
  723. *p++ = ch;
  724. else
  725. p += sprintf(p, "&#%d;", (unsigned char) ch);
  726. }
  727. *p = '\0';
  728. return out;
  729. }
  730. #endif
  731. /*
  732. * Given a URL encoded string, convert it to plain ascii.
  733. * Since decoding always makes strings smaller, the decode is done in-place.
  734. * Thus, callers should xstrdup() the argument if they do not want the
  735. * argument modified. The return is the original pointer, allowing this
  736. * function to be easily used as arguments to other functions.
  737. *
  738. * string The first string to decode.
  739. * option_d 1 if called for httpd -d
  740. *
  741. * Returns a pointer to the decoded string (same as input).
  742. */
  743. static unsigned hex_to_bin(unsigned char c)
  744. {
  745. unsigned v;
  746. v = c - '0';
  747. if (v <= 9)
  748. return v;
  749. /* c | 0x20: letters to lower case, non-letters
  750. * to (potentially different) non-letters */
  751. v = (unsigned)(c | 0x20) - 'a';
  752. if (v <= 5)
  753. return v + 10;
  754. return ~0;
  755. /* For testing:
  756. void t(char c) { printf("'%c'(%u) %u\n", c, c, hex_to_bin(c)); }
  757. int main() { t(0x10); t(0x20); t('0'); t('9'); t('A'); t('F'); t('a'); t('f');
  758. t('0'-1); t('9'+1); t('A'-1); t('F'+1); t('a'-1); t('f'+1); return 0; }
  759. */
  760. }
  761. static char *decodeString(char *orig, int option_d)
  762. {
  763. /* note that decoded string is always shorter than original */
  764. char *string = orig;
  765. char *ptr = string;
  766. char c;
  767. while ((c = *ptr++) != '\0') {
  768. unsigned v;
  769. if (option_d && c == '+') {
  770. *string++ = ' ';
  771. continue;
  772. }
  773. if (c != '%') {
  774. *string++ = c;
  775. continue;
  776. }
  777. v = hex_to_bin(ptr[0]);
  778. if (v > 15) {
  779. bad_hex:
  780. if (!option_d)
  781. return NULL;
  782. *string++ = '%';
  783. continue;
  784. }
  785. v = (v * 16) | hex_to_bin(ptr[1]);
  786. if (v > 255)
  787. goto bad_hex;
  788. if (!option_d && (v == '/' || v == '\0')) {
  789. /* caller takes it as indication of invalid
  790. * (dangerous wrt exploits) chars */
  791. return orig + 1;
  792. }
  793. *string++ = v;
  794. ptr += 2;
  795. }
  796. *string = '\0';
  797. return orig;
  798. }
  799. #if ENABLE_FEATURE_HTTPD_BASIC_AUTH
  800. /*
  801. * Decode a base64 data stream as per rfc1521.
  802. * Note that the rfc states that non base64 chars are to be ignored.
  803. * Since the decode always results in a shorter size than the input,
  804. * it is OK to pass the input arg as an output arg.
  805. * Parameter: a pointer to a base64 encoded string.
  806. * Decoded data is stored in-place.
  807. */
  808. static void decodeBase64(char *Data)
  809. {
  810. const unsigned char *in = (const unsigned char *)Data;
  811. /* The decoded size will be at most 3/4 the size of the encoded */
  812. unsigned ch = 0;
  813. int i = 0;
  814. while (*in) {
  815. int t = *in++;
  816. if (t >= '0' && t <= '9')
  817. t = t - '0' + 52;
  818. else if (t >= 'A' && t <= 'Z')
  819. t = t - 'A';
  820. else if (t >= 'a' && t <= 'z')
  821. t = t - 'a' + 26;
  822. else if (t == '+')
  823. t = 62;
  824. else if (t == '/')
  825. t = 63;
  826. else if (t == '=')
  827. t = 0;
  828. else
  829. continue;
  830. ch = (ch << 6) | t;
  831. i++;
  832. if (i == 4) {
  833. *Data++ = (char) (ch >> 16);
  834. *Data++ = (char) (ch >> 8);
  835. *Data++ = (char) ch;
  836. i = 0;
  837. }
  838. }
  839. *Data = '\0';
  840. }
  841. #endif
  842. /*
  843. * Create a listen server socket on the designated port.
  844. */
  845. static int openServer(void)
  846. {
  847. unsigned n = bb_strtou(bind_addr_or_port, NULL, 10);
  848. if (!errno && n && n <= 0xffff)
  849. n = create_and_bind_stream_or_die(NULL, n);
  850. else
  851. n = create_and_bind_stream_or_die(bind_addr_or_port, 80);
  852. xlisten(n, 9);
  853. return n;
  854. }
  855. /*
  856. * Log the connection closure and exit.
  857. */
  858. static void log_and_exit(void) NORETURN;
  859. static void log_and_exit(void)
  860. {
  861. /* Paranoia. IE said to be buggy. It may send some extra data
  862. * or be confused by us just exiting without SHUT_WR. Oh well. */
  863. shutdown(1, SHUT_WR);
  864. /* Why??
  865. (this also messes up stdin when user runs httpd -i from terminal)
  866. ndelay_on(0);
  867. while (read(STDIN_FILENO, iobuf, IOBUF_SIZE) > 0)
  868. continue;
  869. */
  870. if (verbose > 2)
  871. bb_error_msg("closed");
  872. _exit(xfunc_error_retval);
  873. }
  874. /*
  875. * Create and send HTTP response headers.
  876. * The arguments are combined and sent as one write operation. Note that
  877. * IE will puke big-time if the headers are not sent in one packet and the
  878. * second packet is delayed for any reason.
  879. * responseNum - the result code to send.
  880. */
  881. static void send_headers(int responseNum)
  882. {
  883. static const char RFC1123FMT[] ALIGN1 = "%a, %d %b %Y %H:%M:%S GMT";
  884. const char *responseString = "";
  885. const char *infoString = NULL;
  886. const char *mime_type;
  887. #if ENABLE_FEATURE_HTTPD_ERROR_PAGES
  888. const char *error_page = NULL;
  889. #endif
  890. unsigned i;
  891. time_t timer = time(NULL);
  892. char tmp_str[80];
  893. int len;
  894. for (i = 0; i < ARRAY_SIZE(http_response_type); i++) {
  895. if (http_response_type[i] == responseNum) {
  896. responseString = http_response[i].name;
  897. infoString = http_response[i].info;
  898. #if ENABLE_FEATURE_HTTPD_ERROR_PAGES
  899. error_page = http_error_page[i];
  900. #endif
  901. break;
  902. }
  903. }
  904. /* error message is HTML */
  905. mime_type = responseNum == HTTP_OK ?
  906. found_mime_type : "text/html";
  907. if (verbose)
  908. bb_error_msg("response:%u", responseNum);
  909. /* emit the current date */
  910. strftime(tmp_str, sizeof(tmp_str), RFC1123FMT, gmtime(&timer));
  911. len = sprintf(iobuf,
  912. "HTTP/1.0 %d %s\r\nContent-type: %s\r\n"
  913. "Date: %s\r\nConnection: close\r\n",
  914. responseNum, responseString, mime_type, tmp_str);
  915. #if ENABLE_FEATURE_HTTPD_BASIC_AUTH
  916. if (responseNum == HTTP_UNAUTHORIZED) {
  917. len += sprintf(iobuf + len,
  918. "WWW-Authenticate: Basic realm=\"%s\"\r\n",
  919. g_realm);
  920. }
  921. #endif
  922. if (responseNum == HTTP_MOVED_TEMPORARILY) {
  923. len += sprintf(iobuf + len, "Location: %s/%s%s\r\n",
  924. found_moved_temporarily,
  925. (g_query ? "?" : ""),
  926. (g_query ? g_query : ""));
  927. }
  928. #if ENABLE_FEATURE_HTTPD_ERROR_PAGES
  929. if (error_page && access(error_page, R_OK) == 0) {
  930. strcat(iobuf, "\r\n");
  931. len += 2;
  932. if (DEBUG)
  933. fprintf(stderr, "headers: '%s'\n", iobuf);
  934. full_write(STDOUT_FILENO, iobuf, len);
  935. if (DEBUG)
  936. fprintf(stderr, "writing error page: '%s'\n", error_page);
  937. return send_file_and_exit(error_page, SEND_BODY);
  938. }
  939. #endif
  940. if (file_size != -1) { /* file */
  941. strftime(tmp_str, sizeof(tmp_str), RFC1123FMT, gmtime(&last_mod));
  942. #if ENABLE_FEATURE_HTTPD_RANGES
  943. if (responseNum == HTTP_PARTIAL_CONTENT) {
  944. len += sprintf(iobuf + len, "Content-Range: bytes %"OFF_FMT"u-%"OFF_FMT"u/%"OFF_FMT"u\r\n",
  945. range_start,
  946. range_end,
  947. file_size);
  948. file_size = range_end - range_start + 1;
  949. }
  950. #endif
  951. len += sprintf(iobuf + len,
  952. #if ENABLE_FEATURE_HTTPD_RANGES
  953. "Accept-Ranges: bytes\r\n"
  954. #endif
  955. "Last-Modified: %s\r\n%s %"OFF_FMT"u\r\n",
  956. tmp_str,
  957. content_gzip ? "Transfer-length:" : "Content-length:",
  958. file_size
  959. );
  960. }
  961. if (content_gzip)
  962. len += sprintf(iobuf + len, "Content-Encoding: gzip\r\n");
  963. iobuf[len++] = '\r';
  964. iobuf[len++] = '\n';
  965. if (infoString) {
  966. len += sprintf(iobuf + len,
  967. "<HTML><HEAD><TITLE>%d %s</TITLE></HEAD>\n"
  968. "<BODY><H1>%d %s</H1>\n%s\n</BODY></HTML>\n",
  969. responseNum, responseString,
  970. responseNum, responseString, infoString);
  971. }
  972. if (DEBUG)
  973. fprintf(stderr, "headers: '%s'\n", iobuf);
  974. if (full_write(STDOUT_FILENO, iobuf, len) != len) {
  975. if (verbose > 1)
  976. bb_perror_msg("error");
  977. log_and_exit();
  978. }
  979. }
  980. static void send_headers_and_exit(int responseNum) NORETURN;
  981. static void send_headers_and_exit(int responseNum)
  982. {
  983. send_headers(responseNum);
  984. log_and_exit();
  985. }
  986. /*
  987. * Read from the socket until '\n' or EOF. '\r' chars are removed.
  988. * '\n' is replaced with NUL.
  989. * Return number of characters read or 0 if nothing is read
  990. * ('\r' and '\n' are not counted).
  991. * Data is returned in iobuf.
  992. */
  993. static int get_line(void)
  994. {
  995. int count = 0;
  996. char c;
  997. alarm(HEADER_READ_TIMEOUT);
  998. while (1) {
  999. if (hdr_cnt <= 0) {
  1000. hdr_cnt = safe_read(STDIN_FILENO, hdr_buf, sizeof(hdr_buf));
  1001. if (hdr_cnt <= 0)
  1002. break;
  1003. hdr_ptr = hdr_buf;
  1004. }
  1005. iobuf[count] = c = *hdr_ptr++;
  1006. hdr_cnt--;
  1007. if (c == '\r')
  1008. continue;
  1009. if (c == '\n') {
  1010. iobuf[count] = '\0';
  1011. break;
  1012. }
  1013. if (count < (IOBUF_SIZE - 1)) /* check overflow */
  1014. count++;
  1015. }
  1016. return count;
  1017. }
  1018. #if ENABLE_FEATURE_HTTPD_CGI || ENABLE_FEATURE_HTTPD_PROXY
  1019. /* gcc 4.2.1 fares better with NOINLINE */
  1020. static NOINLINE void cgi_io_loop_and_exit(int fromCgi_rd, int toCgi_wr, int post_len) NORETURN;
  1021. static NOINLINE void cgi_io_loop_and_exit(int fromCgi_rd, int toCgi_wr, int post_len)
  1022. {
  1023. enum { FROM_CGI = 1, TO_CGI = 2 }; /* indexes in pfd[] */
  1024. struct pollfd pfd[3];
  1025. int out_cnt; /* we buffer a bit of initial CGI output */
  1026. int count;
  1027. /* iobuf is used for CGI -> network data,
  1028. * hdr_buf is for network -> CGI data (POSTDATA) */
  1029. /* If CGI dies, we still want to correctly finish reading its output
  1030. * and send it to the peer. So please no SIGPIPEs! */
  1031. signal(SIGPIPE, SIG_IGN);
  1032. // We inconsistently handle a case when more POSTDATA from network
  1033. // is coming than we expected. We may give *some part* of that
  1034. // extra data to CGI.
  1035. //if (hdr_cnt > post_len) {
  1036. // /* We got more POSTDATA from network than we expected */
  1037. // hdr_cnt = post_len;
  1038. //}
  1039. post_len -= hdr_cnt;
  1040. /* post_len - number of POST bytes not yet read from network */
  1041. /* NB: breaking out of this loop jumps to log_and_exit() */
  1042. out_cnt = 0;
  1043. while (1) {
  1044. memset(pfd, 0, sizeof(pfd));
  1045. pfd[FROM_CGI].fd = fromCgi_rd;
  1046. pfd[FROM_CGI].events = POLLIN;
  1047. if (toCgi_wr) {
  1048. pfd[TO_CGI].fd = toCgi_wr;
  1049. if (hdr_cnt > 0) {
  1050. pfd[TO_CGI].events = POLLOUT;
  1051. } else if (post_len > 0) {
  1052. pfd[0].events = POLLIN;
  1053. } else {
  1054. /* post_len <= 0 && hdr_cnt <= 0:
  1055. * no more POST data to CGI,
  1056. * let CGI see EOF on CGI's stdin */
  1057. if (toCgi_wr != fromCgi_rd)
  1058. close(toCgi_wr);
  1059. toCgi_wr = 0;
  1060. }
  1061. }
  1062. /* Now wait on the set of sockets */
  1063. count = safe_poll(pfd, toCgi_wr ? TO_CGI+1 : FROM_CGI+1, -1);
  1064. if (count <= 0) {
  1065. #if 0
  1066. if (safe_waitpid(pid, &status, WNOHANG) <= 0) {
  1067. /* Weird. CGI didn't exit and no fd's
  1068. * are ready, yet poll returned?! */
  1069. continue;
  1070. }
  1071. if (DEBUG && WIFEXITED(status))
  1072. bb_error_msg("CGI exited, status=%d", WEXITSTATUS(status));
  1073. if (DEBUG && WIFSIGNALED(status))
  1074. bb_error_msg("CGI killed, signal=%d", WTERMSIG(status));
  1075. #endif
  1076. break;
  1077. }
  1078. if (pfd[TO_CGI].revents) {
  1079. /* hdr_cnt > 0 here due to the way pfd[TO_CGI].events set */
  1080. /* Have data from peer and can write to CGI */
  1081. count = safe_write(toCgi_wr, hdr_ptr, hdr_cnt);
  1082. /* Doesn't happen, we dont use nonblocking IO here
  1083. *if (count < 0 && errno == EAGAIN) {
  1084. * ...
  1085. *} else */
  1086. if (count > 0) {
  1087. hdr_ptr += count;
  1088. hdr_cnt -= count;
  1089. } else {
  1090. /* EOF/broken pipe to CGI, stop piping POST data */
  1091. hdr_cnt = post_len = 0;
  1092. }
  1093. }
  1094. if (pfd[0].revents) {
  1095. /* post_len > 0 && hdr_cnt == 0 here */
  1096. /* We expect data, prev data portion is eaten by CGI
  1097. * and there *is* data to read from the peer
  1098. * (POSTDATA) */
  1099. //count = post_len > (int)sizeof(hdr_buf) ? (int)sizeof(hdr_buf) : post_len;
  1100. //count = safe_read(STDIN_FILENO, hdr_buf, count);
  1101. count = safe_read(STDIN_FILENO, hdr_buf, sizeof(hdr_buf));
  1102. if (count > 0) {
  1103. hdr_cnt = count;
  1104. hdr_ptr = hdr_buf;
  1105. post_len -= count;
  1106. } else {
  1107. /* no more POST data can be read */
  1108. post_len = 0;
  1109. }
  1110. }
  1111. if (pfd[FROM_CGI].revents) {
  1112. /* There is something to read from CGI */
  1113. char *rbuf = iobuf;
  1114. /* Are we still buffering CGI output? */
  1115. if (out_cnt >= 0) {
  1116. /* HTTP_200[] has single "\r\n" at the end.
  1117. * According to http://hoohoo.ncsa.uiuc.edu/cgi/out.html,
  1118. * CGI scripts MUST send their own header terminated by
  1119. * empty line, then data. That's why we have only one
  1120. * <cr><lf> pair here. We will output "200 OK" line
  1121. * if needed, but CGI still has to provide blank line
  1122. * between header and body */
  1123. /* Must use safe_read, not full_read, because
  1124. * CGI may output a few first bytes and then wait
  1125. * for POSTDATA without closing stdout.
  1126. * With full_read we may wait here forever. */
  1127. count = safe_read(fromCgi_rd, rbuf + out_cnt, PIPE_BUF - 8);
  1128. if (count <= 0) {
  1129. /* eof (or error) and there was no "HTTP",
  1130. * so write it, then write received data */
  1131. if (out_cnt) {
  1132. full_write(STDOUT_FILENO, HTTP_200, sizeof(HTTP_200)-1);
  1133. full_write(STDOUT_FILENO, rbuf, out_cnt);
  1134. }
  1135. break; /* CGI stdout is closed, exiting */
  1136. }
  1137. out_cnt += count;
  1138. count = 0;
  1139. /* "Status" header format is: "Status: 302 Redirected\r\n" */
  1140. if (out_cnt >= 8 && memcmp(rbuf, "Status: ", 8) == 0) {
  1141. /* send "HTTP/1.0 " */
  1142. if (full_write(STDOUT_FILENO, HTTP_200, 9) != 9)
  1143. break;
  1144. rbuf += 8; /* skip "Status: " */
  1145. count = out_cnt - 8;
  1146. out_cnt = -1; /* buffering off */
  1147. } else if (out_cnt >= 4) {
  1148. /* Did CGI add "HTTP"? */
  1149. if (memcmp(rbuf, HTTP_200, 4) != 0) {
  1150. /* there is no "HTTP", do it ourself */
  1151. if (full_write(STDOUT_FILENO, HTTP_200, sizeof(HTTP_200)-1) != sizeof(HTTP_200)-1)
  1152. break;
  1153. }
  1154. /* Commented out:
  1155. if (!strstr(rbuf, "ontent-")) {
  1156. full_write(s, "Content-type: text/plain\r\n\r\n", 28);
  1157. }
  1158. * Counter-example of valid CGI without Content-type:
  1159. * echo -en "HTTP/1.0 302 Found\r\n"
  1160. * echo -en "Location: http://www.busybox.net\r\n"
  1161. * echo -en "\r\n"
  1162. */
  1163. count = out_cnt;
  1164. out_cnt = -1; /* buffering off */
  1165. }
  1166. } else {
  1167. count = safe_read(fromCgi_rd, rbuf, PIPE_BUF);
  1168. if (count <= 0)
  1169. break; /* eof (or error) */
  1170. }
  1171. if (full_write(STDOUT_FILENO, rbuf, count) != count)
  1172. break;
  1173. if (DEBUG)
  1174. fprintf(stderr, "cgi read %d bytes: '%.*s'\n", count, count, rbuf);
  1175. } /* if (pfd[FROM_CGI].revents) */
  1176. } /* while (1) */
  1177. log_and_exit();
  1178. }
  1179. #endif
  1180. #if ENABLE_FEATURE_HTTPD_CGI
  1181. static void setenv1(const char *name, const char *value)
  1182. {
  1183. setenv(name, value ? value : "", 1);
  1184. }
  1185. /*
  1186. * Spawn CGI script, forward CGI's stdin/out <=> network
  1187. *
  1188. * Environment variables are set up and the script is invoked with pipes
  1189. * for stdin/stdout. If a POST is being done the script is fed the POST
  1190. * data in addition to setting the QUERY_STRING variable (for GETs or POSTs).
  1191. *
  1192. * Parameters:
  1193. * const char *url The requested URL (with leading /).
  1194. * int post_len Length of the POST body.
  1195. * const char *cookie For set HTTP_COOKIE.
  1196. * const char *content_type For set CONTENT_TYPE.
  1197. */
  1198. static void send_cgi_and_exit(
  1199. const char *url,
  1200. const char *request,
  1201. int post_len,
  1202. const char *cookie,
  1203. const char *content_type) NORETURN;
  1204. static void send_cgi_and_exit(
  1205. const char *url,
  1206. const char *request,
  1207. int post_len,
  1208. const char *cookie,
  1209. const char *content_type)
  1210. {
  1211. struct fd_pair fromCgi; /* CGI -> httpd pipe */
  1212. struct fd_pair toCgi; /* httpd -> CGI pipe */
  1213. char *script;
  1214. int pid;
  1215. /* Make a copy. NB: caller guarantees:
  1216. * url[0] == '/', url[1] != '/' */
  1217. url = xstrdup(url);
  1218. /*
  1219. * We are mucking with environment _first_ and then vfork/exec,
  1220. * this allows us to use vfork safely. Parent doesn't care about
  1221. * these environment changes anyway.
  1222. */
  1223. /* Check for [dirs/]script.cgi/PATH_INFO */
  1224. script = (char*)url;
  1225. while ((script = strchr(script + 1, '/')) != NULL) {
  1226. *script = '\0';
  1227. if (!is_directory(url + 1, 1, NULL)) {
  1228. /* not directory, found script.cgi/PATH_INFO */
  1229. *script = '/';
  1230. break;
  1231. }
  1232. *script = '/'; /* is directory, find next '/' */
  1233. }
  1234. setenv1("PATH_INFO", script); /* set to /PATH_INFO or "" */
  1235. setenv1("REQUEST_METHOD", request);
  1236. if (g_query) {
  1237. putenv(xasprintf("%s=%s?%s", "REQUEST_URI", url, g_query));
  1238. } else {
  1239. setenv1("REQUEST_URI", url);
  1240. }
  1241. if (script != NULL)
  1242. *script = '\0'; /* cut off /PATH_INFO */
  1243. /* SCRIPT_FILENAME is required by PHP in CGI mode */
  1244. if (home_httpd[0] == '/') {
  1245. char *fullpath = concat_path_file(home_httpd, url);
  1246. setenv1("SCRIPT_FILENAME", fullpath);
  1247. }
  1248. /* set SCRIPT_NAME as full path: /cgi-bin/dirs/script.cgi */
  1249. setenv1("SCRIPT_NAME", url);
  1250. /* http://hoohoo.ncsa.uiuc.edu/cgi/env.html:
  1251. * QUERY_STRING: The information which follows the ? in the URL
  1252. * which referenced this script. This is the query information.
  1253. * It should not be decoded in any fashion. This variable
  1254. * should always be set when there is query information,
  1255. * regardless of command line decoding. */
  1256. /* (Older versions of bbox seem to do some decoding) */
  1257. setenv1("QUERY_STRING", g_query);
  1258. putenv((char*)"SERVER_SOFTWARE=busybox httpd/"BB_VER);
  1259. putenv((char*)"SERVER_PROTOCOL=HTTP/1.0");
  1260. putenv((char*)"GATEWAY_INTERFACE=CGI/1.1");
  1261. /* Having _separate_ variables for IP and port defeats
  1262. * the purpose of having socket abstraction. Which "port"
  1263. * are you using on Unix domain socket?
  1264. * IOW - REMOTE_PEER="1.2.3.4:56" makes much more sense.
  1265. * Oh well... */
  1266. {
  1267. char *p = rmt_ip_str ? rmt_ip_str : (char*)"";
  1268. char *cp = strrchr(p, ':');
  1269. if (ENABLE_FEATURE_IPV6 && cp && strchr(cp, ']'))
  1270. cp = NULL;
  1271. if (cp) *cp = '\0'; /* delete :PORT */
  1272. setenv1("REMOTE_ADDR", p);
  1273. if (cp) {
  1274. *cp = ':';
  1275. #if ENABLE_FEATURE_HTTPD_SET_REMOTE_PORT_TO_ENV
  1276. setenv1("REMOTE_PORT", cp + 1);
  1277. #endif
  1278. }
  1279. }
  1280. setenv1("HTTP_USER_AGENT", user_agent);
  1281. if (http_accept)
  1282. setenv1("HTTP_ACCEPT", http_accept);
  1283. if (http_accept_language)
  1284. setenv1("HTTP_ACCEPT_LANGUAGE", http_accept_language);
  1285. if (post_len)
  1286. putenv(xasprintf("CONTENT_LENGTH=%d", post_len));
  1287. if (cookie)
  1288. setenv1("HTTP_COOKIE", cookie);
  1289. if (content_type)
  1290. setenv1("CONTENT_TYPE", content_type);
  1291. #if ENABLE_FEATURE_HTTPD_BASIC_AUTH
  1292. if (remoteuser) {
  1293. setenv1("REMOTE_USER", remoteuser);
  1294. putenv((char*)"AUTH_TYPE=Basic");
  1295. }
  1296. #endif
  1297. if (referer)
  1298. setenv1("HTTP_REFERER", referer);
  1299. setenv1("HTTP_HOST", host); /* set to "" if NULL */
  1300. /* setenv1("SERVER_NAME", safe_gethostname()); - don't do this,
  1301. * just run "env SERVER_NAME=xyz httpd ..." instead */
  1302. xpiped_pair(fromCgi);
  1303. xpiped_pair(toCgi);
  1304. pid = vfork();
  1305. if (pid < 0) {
  1306. /* TODO: log perror? */
  1307. log_and_exit();
  1308. }
  1309. if (!pid) {
  1310. /* Child process */
  1311. char *argv[3];
  1312. xfunc_error_retval = 242;
  1313. /* NB: close _first_, then move fds! */
  1314. close(toCgi.wr);
  1315. close(fromCgi.rd);
  1316. xmove_fd(toCgi.rd, 0); /* replace stdin with the pipe */
  1317. xmove_fd(fromCgi.wr, 1); /* replace stdout with the pipe */
  1318. /* User seeing stderr output can be a security problem.
  1319. * If CGI really wants that, it can always do dup itself. */
  1320. /* dup2(1, 2); */
  1321. /* Chdiring to script's dir */
  1322. script = strrchr(url, '/');
  1323. if (script != url) { /* paranoia */
  1324. *script = '\0';
  1325. if (chdir(url + 1) != 0) {
  1326. bb_perror_msg("chdir(%s)", url + 1);
  1327. goto error_execing_cgi;
  1328. }
  1329. // not needed: *script = '/';
  1330. }
  1331. script++;
  1332. /* set argv[0] to name without path */
  1333. argv[0] = script;
  1334. argv[1] = NULL;
  1335. #if ENABLE_FEATURE_HTTPD_CONFIG_WITH_SCRIPT_INTERPR
  1336. {
  1337. char *suffix = strrchr(script, '.');
  1338. if (suffix) {
  1339. Htaccess *cur;
  1340. for (cur = script_i; cur; cur = cur->next) {
  1341. if (strcmp(cur->before_colon + 1, suffix) == 0) {
  1342. /* found interpreter name */
  1343. argv[0] = cur->after_colon;
  1344. argv[1] = script;
  1345. argv[2] = NULL;
  1346. break;
  1347. }
  1348. }
  1349. }
  1350. }
  1351. #endif
  1352. /* restore default signal dispositions for CGI process */
  1353. bb_signals(0
  1354. | (1 << SIGCHLD)
  1355. | (1 << SIGPIPE)
  1356. | (1 << SIGHUP)
  1357. , SIG_DFL);
  1358. /* _NOT_ execvp. We do not search PATH. argv[0] is a filename
  1359. * without any dir components and will only match a file
  1360. * in the current directory */
  1361. execv(argv[0], argv);
  1362. if (verbose)
  1363. bb_perror_msg("can't execute '%s'", argv[0]);
  1364. error_execing_cgi:
  1365. /* send to stdout
  1366. * (we are CGI here, our stdout is pumped to the net) */
  1367. send_headers_and_exit(HTTP_NOT_FOUND);
  1368. } /* end child */
  1369. /* Parent process */
  1370. /* Restore variables possibly changed by child */
  1371. xfunc_error_retval = 0;
  1372. /* Pump data */
  1373. close(fromCgi.wr);
  1374. close(toCgi.rd);
  1375. cgi_io_loop_and_exit(fromCgi.rd, toCgi.wr, post_len);
  1376. }
  1377. #endif /* FEATURE_HTTPD_CGI */
  1378. /*
  1379. * Send a file response to a HTTP request, and exit
  1380. *
  1381. * Parameters:
  1382. * const char *url The requested URL (with leading /).
  1383. * what What to send (headers/body/both).
  1384. */
  1385. static NOINLINE void send_file_and_exit(const char *url, int what)
  1386. {
  1387. char *suffix;
  1388. int fd;
  1389. ssize_t count;
  1390. if (content_gzip) {
  1391. /* does <url>.gz exist? Then use it instead */
  1392. char *gzurl = xasprintf("%s.gz", url);
  1393. fd = open(gzurl, O_RDONLY);
  1394. free(gzurl);
  1395. if (fd != -1) {
  1396. struct stat sb;
  1397. fstat(fd, &sb);
  1398. file_size = sb.st_size;
  1399. last_mod = sb.st_mtime;
  1400. } else {
  1401. IF_FEATURE_HTTPD_GZIP(content_gzip = 0;)
  1402. fd = open(url, O_RDONLY);
  1403. }
  1404. } else {
  1405. fd = open(url, O_RDONLY);
  1406. }
  1407. if (fd < 0) {
  1408. if (DEBUG)
  1409. bb_perror_msg("can't open '%s'", url);
  1410. /* Error pages are sent by using send_file_and_exit(SEND_BODY).
  1411. * IOW: it is unsafe to call send_headers_and_exit
  1412. * if what is SEND_BODY! Can recurse! */
  1413. if (what != SEND_BODY)
  1414. send_headers_and_exit(HTTP_NOT_FOUND);
  1415. log_and_exit();
  1416. }
  1417. /* If you want to know about EPIPE below
  1418. * (happens if you abort downloads from local httpd): */
  1419. signal(SIGPIPE, SIG_IGN);
  1420. /* If not found, default is "application/octet-stream" */
  1421. found_mime_type = "application/octet-stream";
  1422. suffix = strrchr(url, '.');
  1423. if (suffix) {
  1424. static const char suffixTable[] ALIGN1 =
  1425. /* Shorter suffix must be first:
  1426. * ".html.htm" will fail for ".htm"
  1427. */
  1428. ".txt.h.c.cc.cpp\0" "text/plain\0"
  1429. /* .htm line must be after .h line */
  1430. ".htm.html\0" "text/html\0"
  1431. ".jpg.jpeg\0" "image/jpeg\0"
  1432. ".gif\0" "image/gif\0"
  1433. ".png\0" "image/png\0"
  1434. /* .css line must be after .c line */
  1435. ".css\0" "text/css\0"
  1436. ".wav\0" "audio/wav\0"
  1437. ".avi\0" "video/x-msvideo\0"
  1438. ".qt.mov\0" "video/quicktime\0"
  1439. ".mpe.mpeg\0" "video/mpeg\0"
  1440. ".mid.midi\0" "audio/midi\0"
  1441. ".mp3\0" "audio/mpeg\0"
  1442. #if 0 /* unpopular */
  1443. ".au\0" "audio/basic\0"
  1444. ".pac\0" "application/x-ns-proxy-autoconfig\0"
  1445. ".vrml.wrl\0" "model/vrml\0"
  1446. #endif
  1447. /* compiler adds another "\0" here */
  1448. ;
  1449. Htaccess *cur;
  1450. /* Examine built-in table */
  1451. const char *table = suffixTable;
  1452. const char *table_next;
  1453. for (; *table; table = table_next) {
  1454. const char *try_suffix;
  1455. const char *mime_type;
  1456. mime_type = table + strlen(table) + 1;
  1457. table_next = mime_type + strlen(mime_type) + 1;
  1458. try_suffix = strstr(table, suffix);
  1459. if (!try_suffix)
  1460. continue;
  1461. try_suffix += strlen(suffix);
  1462. if (*try_suffix == '\0' || *try_suffix == '.') {
  1463. found_mime_type = mime_type;
  1464. break;
  1465. }
  1466. /* Example: strstr(table, ".av") != NULL, but it
  1467. * does not match ".avi" after all and we end up here.
  1468. * The table is arranged so that in this case we know
  1469. * that it can't match anything in the following lines,
  1470. * and we stop the search: */
  1471. break;
  1472. }
  1473. /* ...then user's table */
  1474. for (cur = mime_a; cur; cur = cur->next) {
  1475. if (strcmp(cur->before_colon, suffix) == 0) {
  1476. found_mime_type = cur->after_colon;
  1477. break;
  1478. }
  1479. }
  1480. }
  1481. if (DEBUG)
  1482. bb_error_msg("sending file '%s' content-type: %s",
  1483. url, found_mime_type);
  1484. #if ENABLE_FEATURE_HTTPD_RANGES
  1485. if (what == SEND_BODY /* err pages and ranges don't mix */
  1486. || content_gzip /* we are sending compressed page: can't do ranges */ ///why?
  1487. ) {
  1488. range_start = 0;
  1489. }
  1490. range_len = MAXINT(off_t);
  1491. if (range_start) {
  1492. if (!range_end) {
  1493. range_end = file_size - 1;
  1494. }
  1495. if (range_end < range_start
  1496. || lseek(fd, range_start, SEEK_SET) != range_start
  1497. ) {
  1498. lseek(fd, 0, SEEK_SET);
  1499. range_start = 0;
  1500. } else {
  1501. range_len = range_end - range_start + 1;
  1502. send_headers(HTTP_PARTIAL_CONTENT);
  1503. what = SEND_BODY;
  1504. }
  1505. }
  1506. #endif
  1507. if (what & SEND_HEADERS)
  1508. send_headers(HTTP_OK);
  1509. #if ENABLE_FEATURE_HTTPD_USE_SENDFILE
  1510. {
  1511. off_t offset = range_start;
  1512. while (1) {
  1513. /* sz is rounded down to 64k */
  1514. ssize_t sz = MAXINT(ssize_t) - 0xffff;
  1515. IF_FEATURE_HTTPD_RANGES(if (sz > range_len) sz = range_len;)
  1516. count = sendfile(STDOUT_FILENO, fd, &offset, sz);
  1517. if (count < 0) {
  1518. if (offset == range_start)
  1519. break; /* fall back to read/write loop */
  1520. goto fin;
  1521. }
  1522. IF_FEATURE_HTTPD_RANGES(range_len -= sz;)
  1523. if (count == 0 || range_len == 0)
  1524. log_and_exit();
  1525. }
  1526. }
  1527. #endif
  1528. while ((count = safe_read(fd, iobuf, IOBUF_SIZE)) > 0) {
  1529. ssize_t n;
  1530. IF_FEATURE_HTTPD_RANGES(if (count > range_len) count = range_len;)
  1531. n = full_write(STDOUT_FILENO, iobuf, count);
  1532. if (count != n)
  1533. break;
  1534. IF_FEATURE_HTTPD_RANGES(range_len -= count;)
  1535. if (range_len == 0)
  1536. break;
  1537. }
  1538. if (count < 0) {
  1539. IF_FEATURE_HTTPD_USE_SENDFILE(fin:)
  1540. if (verbose > 1)
  1541. bb_perror_msg("error");
  1542. }
  1543. log_and_exit();
  1544. }
  1545. static int checkPermIP(void)
  1546. {
  1547. Htaccess_IP *cur;
  1548. for (cur = ip_a_d; cur; cur = cur->next) {
  1549. #if DEBUG
  1550. fprintf(stderr,
  1551. "checkPermIP: '%s' ? '%u.%u.%u.%u/%u.%u.%u.%u'\n",
  1552. rmt_ip_str,
  1553. (unsigned char)(cur->ip >> 24),
  1554. (unsigned char)(cur->ip >> 16),
  1555. (unsigned char)(cur->ip >> 8),
  1556. (unsigned char)(cur->ip),
  1557. (unsigned char)(cur->mask >> 24),
  1558. (unsigned char)(cur->mask >> 16),
  1559. (unsigned char)(cur->mask >> 8),
  1560. (unsigned char)(cur->mask)
  1561. );
  1562. #endif
  1563. if ((rmt_ip & cur->mask) == cur->ip)
  1564. return (cur->allow_deny == 'A'); /* A -> 1 */
  1565. }
  1566. return !flg_deny_all; /* depends on whether we saw "D:*" */
  1567. }
  1568. #if ENABLE_FEATURE_HTTPD_BASIC_AUTH
  1569. /*
  1570. * Config file entries are of the form "/<path>:<user>:<passwd>".
  1571. * If config file has no prefix match for path, access is allowed.
  1572. *
  1573. * path The file path
  1574. * user_and_passwd "user:passwd" to validate
  1575. *
  1576. * Returns 1 if user_and_passwd is OK.
  1577. */
  1578. static int check_user_passwd(const char *path, const char *user_and_passwd)
  1579. {
  1580. Htaccess *cur;
  1581. const char *prev = NULL;
  1582. for (cur = g_auth; cur; cur = cur->next) {
  1583. const char *dir_prefix;
  1584. size_t len;
  1585. dir_prefix = cur->before_colon;
  1586. /* WHY? */
  1587. /* If already saw a match, don't accept other different matches */
  1588. if (prev && strcmp(prev, dir_prefix) != 0)
  1589. continue;
  1590. if (DEBUG)
  1591. fprintf(stderr, "checkPerm: '%s' ? '%s'\n", dir_prefix, user_and_passwd);
  1592. /* If it's not a prefix match, continue searching */
  1593. len = strlen(dir_prefix);
  1594. if (len != 1 /* dir_prefix "/" matches all, don't need to check */
  1595. && (strncmp(dir_prefix, path, len) != 0
  1596. || (path[len] != '/' && path[len] != '\0'))
  1597. ) {
  1598. continue;
  1599. }
  1600. /* Path match found */
  1601. prev = dir_prefix;
  1602. if (ENABLE_FEATURE_HTTPD_AUTH_MD5) {
  1603. char *md5_passwd;
  1604. md5_passwd = strchr(cur->after_colon, ':');
  1605. if (md5_passwd && md5_passwd[1] == '$' && md5_passwd[2] == '1'
  1606. && md5_passwd[3] == '$' && md5_passwd[4]
  1607. ) {
  1608. char *encrypted;
  1609. int r, user_len_p1;
  1610. md5_passwd++;
  1611. user_len_p1 = md5_passwd - cur->after_colon;
  1612. /* comparing "user:" */
  1613. if (strncmp(cur->after_colon, user_and_passwd, user_len_p1) != 0) {
  1614. continue;
  1615. }
  1616. encrypted = pw_encrypt(
  1617. user_and_passwd + user_len_p1 /* cleartext pwd from user */,
  1618. md5_passwd /*salt */, 1 /* cleanup */);
  1619. r = strcmp(encrypted, md5_passwd);
  1620. free(encrypted);
  1621. if (r == 0)
  1622. goto set_remoteuser_var; /* Ok */
  1623. continue;
  1624. }
  1625. }
  1626. /* Comparing plaintext "user:pass" in one go */
  1627. if (strcmp(cur->after_colon, user_and_passwd) == 0) {
  1628. set_remoteuser_var:
  1629. remoteuser = xstrndup(user_and_passwd,
  1630. strchrnul(user_and_passwd, ':') - user_and_passwd);
  1631. return 1; /* Ok */
  1632. }
  1633. } /* for */
  1634. /* 0(bad) if prev is set: matches were found but passwd was wrong */
  1635. return (prev == NULL);
  1636. }
  1637. #endif /* FEATURE_HTTPD_BASIC_AUTH */
  1638. #if ENABLE_FEATURE_HTTPD_PROXY
  1639. static Htaccess_Proxy *find_proxy_entry(const char *url)
  1640. {
  1641. Htaccess_Proxy *p;
  1642. for (p = proxy; p; p = p->next) {
  1643. if (strncmp(url, p->url_from, strlen(p->url_from)) == 0)
  1644. return p;
  1645. }
  1646. return NULL;
  1647. }
  1648. #endif
  1649. /*
  1650. * Handle timeouts
  1651. */
  1652. static void send_REQUEST_TIMEOUT_and_exit(int sig) NORETURN;
  1653. static void send_REQUEST_TIMEOUT_and_exit(int sig UNUSED_PARAM)
  1654. {
  1655. send_headers_and_exit(HTTP_REQUEST_TIMEOUT);
  1656. }
  1657. /*
  1658. * Handle an incoming http request and exit.
  1659. */
  1660. static void handle_incoming_and_exit(const len_and_sockaddr *fromAddr) NORETURN;
  1661. static void handle_incoming_and_exit(const len_and_sockaddr *fromAddr)
  1662. {
  1663. static const char request_GET[] ALIGN1 = "GET";
  1664. struct stat sb;
  1665. char *urlcopy;
  1666. char *urlp;
  1667. char *tptr;
  1668. #if ENABLE_FEATURE_HTTPD_CGI
  1669. static const char request_HEAD[] ALIGN1 = "HEAD";
  1670. const char *prequest;
  1671. char *cookie = NULL;
  1672. char *content_type = NULL;
  1673. unsigned long length = 0;
  1674. #elif ENABLE_FEATURE_HTTPD_PROXY
  1675. #define prequest request_GET
  1676. unsigned long length = 0;
  1677. #endif
  1678. #if ENABLE_FEATURE_HTTPD_BASIC_AUTH
  1679. smallint authorized = -1;
  1680. #endif
  1681. smallint ip_allowed;
  1682. char http_major_version;
  1683. #if ENABLE_FEATURE_HTTPD_PROXY
  1684. char http_minor_version;
  1685. char *header_buf = header_buf; /* for gcc */
  1686. char *header_ptr = header_ptr;
  1687. Htaccess_Proxy *proxy_entry;
  1688. #endif
  1689. /* Allocation of iobuf is postponed until now
  1690. * (IOW, server process doesn't need to waste 8k) */
  1691. iobuf = xmalloc(IOBUF_SIZE);
  1692. rmt_ip = 0;
  1693. if (fromAddr->u.sa.sa_family == AF_INET) {
  1694. rmt_ip = ntohl(fromAddr->u.sin.sin_addr.s_addr);
  1695. }
  1696. #if ENABLE_FEATURE_IPV6
  1697. if (fromAddr->u.sa.sa_family == AF_INET6
  1698. && fromAddr->u.sin6.sin6_addr.s6_addr32[0] == 0
  1699. && fromAddr->u.sin6.sin6_addr.s6_addr32[1] == 0
  1700. && ntohl(fromAddr->u.sin6.sin6_addr.s6_addr32[2]) == 0xffff)
  1701. rmt_ip = ntohl(fromAddr->u.sin6.sin6_addr.s6_addr32[3]);
  1702. #endif
  1703. if (ENABLE_FEATURE_HTTPD_CGI || DEBUG || verbose) {
  1704. /* NB: can be NULL (user runs httpd -i by hand?) */
  1705. rmt_ip_str = xmalloc_sockaddr2dotted(&fromAddr->u.sa);
  1706. }
  1707. if (verbose) {
  1708. /* this trick makes -v logging much simpler */
  1709. if (rmt_ip_str)
  1710. applet_name = rmt_ip_str;
  1711. if (verbose > 2)
  1712. bb_error_msg("connected");
  1713. }
  1714. /* Install timeout handler. get_line() needs it. */
  1715. signal(SIGALRM, send_REQUEST_TIMEOUT_and_exit);
  1716. if (!get_line()) /* EOF or error or empty line */
  1717. send_headers_and_exit(HTTP_BAD_REQUEST);
  1718. /* Determine type of request (GET/POST) */
  1719. urlp = strpbrk(iobuf, " \t");
  1720. if (urlp == NULL)
  1721. send_headers_and_exit(HTTP_BAD_REQUEST);
  1722. *urlp++ = '\0';
  1723. #if ENABLE_FEATURE_HTTPD_CGI
  1724. prequest = request_GET;
  1725. if (strcasecmp(iobuf, prequest) != 0) {
  1726. prequest = request_HEAD;
  1727. if (strcasecmp(iobuf, prequest) != 0) {
  1728. prequest = "POST";
  1729. if (strcasecmp(iobuf, prequest) != 0)
  1730. send_headers_and_exit(HTTP_NOT_IMPLEMENTED);
  1731. }
  1732. }
  1733. #else
  1734. if (strcasecmp(iobuf, request_GET) != 0)
  1735. send_headers_and_exit(HTTP_NOT_IMPLEMENTED);
  1736. #endif
  1737. urlp = skip_whitespace(urlp);
  1738. if (urlp[0] != '/')
  1739. send_headers_and_exit(HTTP_BAD_REQUEST);
  1740. /* Find end of URL and parse HTTP version, if any */
  1741. http_major_version = '0';
  1742. IF_FEATURE_HTTPD_PROXY(http_minor_version = '0';)
  1743. tptr = strchrnul(urlp, ' ');
  1744. /* Is it " HTTP/"? */
  1745. if (tptr[0] && strncmp(tptr + 1, HTTP_200, 5) == 0) {
  1746. http_major_version = tptr[6];
  1747. IF_FEATURE_HTTPD_PROXY(http_minor_version = tptr[8];)
  1748. }
  1749. *tptr = '\0';
  1750. /* Copy URL from after "GET "/"POST " to stack-allocated char[] */
  1751. urlcopy = alloca((tptr - urlp) + 2 + strlen(index_page));
  1752. /*if (urlcopy == NULL)
  1753. * send_headers_and_exit(HTTP_INTERNAL_SERVER_ERROR);*/
  1754. strcpy(urlcopy, urlp);
  1755. /* NB: urlcopy ptr is never changed after this */
  1756. /* Extract url args if present */
  1757. g_query = NULL;
  1758. tptr = strchr(urlcopy, '?');
  1759. if (tptr) {
  1760. *tptr++ = '\0';
  1761. g_query = tptr;
  1762. }
  1763. /* Decode URL escape sequences */
  1764. tptr = decodeString(urlcopy, 0);
  1765. if (tptr == NULL)
  1766. send_headers_and_exit(HTTP_BAD_REQUEST);
  1767. if (tptr == urlcopy + 1) {
  1768. /* '/' or NUL is encoded */
  1769. send_headers_and_exit(HTTP_NOT_FOUND);
  1770. }
  1771. /* Canonicalize path */
  1772. /* Algorithm stolen from libbb bb_simplify_path(),
  1773. * but don't strdup, retain trailing slash, protect root */
  1774. urlp = tptr = urlcopy;
  1775. do {
  1776. if (*urlp == '/') {
  1777. /* skip duplicate (or initial) slash */
  1778. if (*tptr == '/') {
  1779. continue;
  1780. }
  1781. if (*tptr == '.') {
  1782. /* skip extra "/./" */
  1783. if (tptr[1] == '/' || !tptr[1]) {
  1784. continue;
  1785. }
  1786. /* "..": be careful */
  1787. if (tptr[1] == '.' && (tptr[2] == '/' || !tptr[2])) {
  1788. ++tptr;
  1789. if (urlp == urlcopy) /* protect root */
  1790. send_headers_and_exit(HTTP_BAD_REQUEST);
  1791. while (*--urlp != '/') /* omit previous dir */;
  1792. continue;
  1793. }
  1794. }
  1795. }
  1796. *++urlp = *tptr;
  1797. } while (*++tptr);
  1798. *++urlp = '\0'; /* terminate after last character */
  1799. /* If URL is a directory, add '/' */
  1800. if (urlp[-1] != '/') {
  1801. if (is_directory(urlcopy + 1, 1, NULL)) {
  1802. found_moved_temporarily = urlcopy;
  1803. }
  1804. }
  1805. /* Log it */
  1806. if (verbose > 1)
  1807. bb_error_msg("url:%s", urlcopy);
  1808. tptr = urlcopy;
  1809. ip_allowed = checkPermIP();
  1810. while (ip_allowed && (tptr = strchr(tptr + 1, '/')) != NULL) {
  1811. /* have path1/path2 */
  1812. *tptr = '\0';
  1813. if (is_directory(urlcopy + 1, 1, NULL)) {
  1814. /* may have subdir config */
  1815. parse_conf(urlcopy + 1, SUBDIR_PARSE);
  1816. ip_allowed = checkPermIP();
  1817. }
  1818. *tptr = '/';
  1819. }
  1820. #if ENABLE_FEATURE_HTTPD_PROXY
  1821. proxy_entry = find_proxy_entry(urlcopy);
  1822. if (proxy_entry)
  1823. header_buf = header_ptr = xmalloc(IOBUF_SIZE);
  1824. #endif
  1825. if (http_major_version >= '0') {
  1826. /* Request was with "... HTTP/nXXX", and n >= 0 */
  1827. /* Read until blank line */
  1828. while (1) {
  1829. if (!get_line())
  1830. break; /* EOF or error or empty line */
  1831. if (DEBUG)
  1832. bb_error_msg("header: '%s'", iobuf);
  1833. #if ENABLE_FEATURE_HTTPD_PROXY
  1834. /* We need 2 more bytes for yet another "\r\n" -
  1835. * see near fdprintf(proxy_fd...) further below */
  1836. if (proxy_entry && (header_ptr - header_buf) < IOBUF_SIZE - 2) {
  1837. int len = strlen(iobuf);
  1838. if (len > IOBUF_SIZE - (header_ptr - header_buf) - 4)
  1839. len = IOBUF_SIZE - (header_ptr - header_buf) - 4;
  1840. memcpy(header_ptr, iobuf, len);
  1841. header_ptr += len;
  1842. header_ptr[0] = '\r';
  1843. header_ptr[1] = '\n';
  1844. header_ptr += 2;
  1845. }
  1846. #endif
  1847. #if ENABLE_FEATURE_HTTPD_CGI || ENABLE_FEATURE_HTTPD_PROXY
  1848. /* Try and do our best to parse more lines */
  1849. if ((STRNCASECMP(iobuf, "Content-length:") == 0)) {
  1850. /* extra read only for POST */
  1851. if (prequest != request_GET
  1852. # if ENABLE_FEATURE_HTTPD_CGI
  1853. && prequest != request_HEAD
  1854. # endif
  1855. ) {
  1856. tptr = skip_whitespace(iobuf + sizeof("Content-length:") - 1);
  1857. if (!tptr[0])
  1858. send_headers_and_exit(HTTP_BAD_REQUEST);
  1859. /* not using strtoul: it ignores leading minus! */
  1860. length = bb_strtou(tptr, NULL, 10);
  1861. /* length is "ulong", but we need to pass it to int later */
  1862. if (errno || length > INT_MAX)
  1863. send_headers_and_exit(HTTP_BAD_REQUEST);
  1864. }
  1865. }
  1866. #endif
  1867. #if ENABLE_FEATURE_HTTPD_CGI
  1868. else if (STRNCASECMP(iobuf, "Cookie:") == 0) {
  1869. cookie = xstrdup(skip_whitespace(iobuf + sizeof("Cookie:")-1));
  1870. } else if (STRNCASECMP(iobuf, "Content-Type:") == 0) {
  1871. content_type = xstrdup(skip_whitespace(iobuf + sizeof("Content-Type:")-1));
  1872. } else if (STRNCASECMP(iobuf, "Referer:") == 0) {
  1873. referer = xstrdup(skip_whitespace(iobuf + sizeof("Referer:")-1));
  1874. } else if (STRNCASECMP(iobuf, "User-Agent:") == 0) {
  1875. user_agent = xstrdup(skip_whitespace(iobuf + sizeof("User-Agent:")-1));
  1876. } else if (STRNCASECMP(iobuf, "Host:") == 0) {
  1877. host = xstrdup(skip_whitespace(iobuf + sizeof("Host:")-1));
  1878. } else if (STRNCASECMP(iobuf, "Accept:") == 0) {
  1879. http_accept = xstrdup(skip_whitespace(iobuf + sizeof("Accept:")-1));
  1880. } else if (STRNCASECMP(iobuf, "Accept-Language:") == 0) {
  1881. http_accept_language = xstrdup(skip_whitespace(iobuf + sizeof("Accept-Language:")-1));
  1882. }
  1883. #endif
  1884. #if ENABLE_FEATURE_HTTPD_BASIC_AUTH
  1885. if (STRNCASECMP(iobuf, "Authorization:") == 0) {
  1886. /* We only allow Basic credentials.
  1887. * It shows up as "Authorization: Basic <user>:<passwd>" where
  1888. * "<user>:<passwd>" is base64 encoded.
  1889. */
  1890. tptr = skip_whitespace(iobuf + sizeof("Authorization:")-1);
  1891. if (STRNCASECMP(tptr, "Basic") != 0)
  1892. continue;
  1893. tptr += sizeof("Basic")-1;
  1894. /* decodeBase64() skips whitespace itself */
  1895. decodeBase64(tptr);
  1896. authorized = check_user_passwd(urlcopy, tptr);
  1897. }
  1898. #endif
  1899. #if ENABLE_FEATURE_HTTPD_RANGES
  1900. if (STRNCASECMP(iobuf, "Range:") == 0) {
  1901. /* We know only bytes=NNN-[MMM] */
  1902. char *s = skip_whitespace(iobuf + sizeof("Range:")-1);
  1903. if (strncmp(s, "bytes=", 6) == 0) {
  1904. s += sizeof("bytes=")-1;
  1905. range_start = BB_STRTOOFF(s, &s, 10);
  1906. if (s[0] != '-' || range_start < 0) {
  1907. range_start = 0;
  1908. } else if (s[1]) {
  1909. range_end = BB_STRTOOFF(s+1, NULL, 10);
  1910. if (errno || range_end < range_start)
  1911. range_start = 0;
  1912. }
  1913. }
  1914. }
  1915. #endif
  1916. #if ENABLE_FEATURE_HTTPD_GZIP
  1917. if (STRNCASECMP(iobuf, "Accept-Encoding:") == 0) {
  1918. /* Note: we do not support "gzip;q=0"
  1919. * method of _disabling_ gzip
  1920. * delivery. No one uses that, though */
  1921. const char *s = strstr(iobuf, "gzip");
  1922. if (s) {
  1923. // want more thorough checks?
  1924. //if (s[-1] == ' '
  1925. // || s[-1] == ','
  1926. // || s[-1] == ':'
  1927. //) {
  1928. content_gzip = 1;
  1929. //}
  1930. }
  1931. }
  1932. #endif
  1933. } /* while extra header reading */
  1934. }
  1935. /* We are done reading headers, disable peer timeout */
  1936. alarm(0);
  1937. if (strcmp(bb_basename(urlcopy), HTTPD_CONF) == 0 || !ip_allowed) {
  1938. /* protect listing [/path]/httpd.conf or IP deny */
  1939. send_headers_and_exit(HTTP_FORBIDDEN);
  1940. }
  1941. #if ENABLE_FEATURE_HTTPD_BASIC_AUTH
  1942. /* Case: no "Authorization:" was seen, but page does require passwd.
  1943. * Check that with dummy user:pass */
  1944. if (authorized < 0)
  1945. authorized = check_user_passwd(urlcopy, ":");
  1946. if (!authorized)
  1947. send_headers_and_exit(HTTP_UNAUTHORIZED);
  1948. #endif
  1949. if (found_moved_temporarily) {
  1950. send_headers_and_exit(HTTP_MOVED_TEMPORARILY);
  1951. }
  1952. #if ENABLE_FEATURE_HTTPD_PROXY
  1953. if (proxy_entry != NULL) {
  1954. int proxy_fd;
  1955. len_and_sockaddr *lsa;
  1956. proxy_fd = socket(AF_INET, SOCK_STREAM, 0);
  1957. if (proxy_fd < 0)
  1958. send_headers_and_exit(HTTP_INTERNAL_SERVER_ERROR);
  1959. lsa = host2sockaddr(proxy_entry->host_port, 80);
  1960. if (lsa == NULL)
  1961. send_headers_and_exit(HTTP_INTERNAL_SERVER_ERROR);
  1962. if (connect(proxy_fd, &lsa->u.sa, lsa->len) < 0)
  1963. send_headers_and_exit(HTTP_INTERNAL_SERVER_ERROR);
  1964. fdprintf(proxy_fd, "%s %s%s%s%s HTTP/%c.%c\r\n",
  1965. prequest, /* GET or POST */
  1966. proxy_entry->url_to, /* url part 1 */
  1967. urlcopy + strlen(proxy_entry->url_from), /* url part 2 */
  1968. (g_query ? "?" : ""), /* "?" (maybe) */
  1969. (g_query ? g_query : ""), /* query string (maybe) */
  1970. http_major_version, http_minor_version);
  1971. header_ptr[0] = '\r';
  1972. header_ptr[1] = '\n';
  1973. header_ptr += 2;
  1974. write(proxy_fd, header_buf, header_ptr - header_buf);
  1975. free(header_buf); /* on the order of 8k, free it */
  1976. cgi_io_loop_and_exit(proxy_fd, proxy_fd, length);
  1977. }
  1978. #endif
  1979. tptr = urlcopy + 1; /* skip first '/' */
  1980. #if ENABLE_FEATURE_HTTPD_CGI
  1981. if (strncmp(tptr, "cgi-bin/", 8) == 0) {
  1982. if (tptr[8] == '\0') {
  1983. /* protect listing "cgi-bin/" */
  1984. send_headers_and_exit(HTTP_FORBIDDEN);
  1985. }
  1986. send_cgi_and_exit(urlcopy, prequest, length, cookie, content_type);
  1987. }
  1988. #endif
  1989. if (urlp[-1] == '/')
  1990. strcpy(urlp, index_page);
  1991. if (stat(tptr, &sb) == 0) {
  1992. #if ENABLE_FEATURE_HTTPD_CONFIG_WITH_SCRIPT_INTERPR
  1993. char *suffix = strrchr(tptr, '.');
  1994. if (suffix) {
  1995. Htaccess *cur;
  1996. for (cur = script_i; cur; cur = cur->next) {
  1997. if (strcmp(cur->before_colon + 1, suffix) == 0) {
  1998. send_cgi_and_exit(urlcopy, prequest, length, cookie, content_type);
  1999. }
  2000. }
  2001. }
  2002. #endif
  2003. file_size = sb.st_size;
  2004. last_mod = sb.st_mtime;
  2005. }
  2006. #if ENABLE_FEATURE_HTTPD_CGI
  2007. else if (urlp[-1] == '/') {
  2008. /* It's a dir URL and there is no index.html
  2009. * Try cgi-bin/index.cgi */
  2010. if (access("/cgi-bin/index.cgi"+1, X_OK) == 0) {
  2011. urlp[0] = '\0';
  2012. g_query = urlcopy;
  2013. send_cgi_and_exit("/cgi-bin/index.cgi", prequest, length, cookie, content_type);
  2014. }
  2015. }
  2016. /* else fall through to send_file, it errors out if open fails: */
  2017. if (prequest != request_GET && prequest != request_HEAD) {
  2018. /* POST for files does not make sense */
  2019. send_headers_and_exit(HTTP_NOT_IMPLEMENTED);
  2020. }
  2021. send_file_and_exit(tptr,
  2022. (prequest != request_HEAD ? SEND_HEADERS_AND_BODY : SEND_HEADERS)
  2023. );
  2024. #else
  2025. send_file_and_exit(tptr, SEND_HEADERS_AND_BODY);
  2026. #endif
  2027. }
  2028. /*
  2029. * The main http server function.
  2030. * Given a socket, listen for new connections and farm out
  2031. * the processing as a [v]forked process.
  2032. * Never returns.
  2033. */
  2034. #if BB_MMU
  2035. static void mini_httpd(int server_socket) NORETURN;
  2036. static void mini_httpd(int server_socket)
  2037. {
  2038. /* NB: it's best to not use xfuncs in this loop before fork().
  2039. * Otherwise server may die on transient errors (temporary
  2040. * out-of-memory condition, etc), which is Bad(tm).
  2041. * Try to do any dangerous calls after fork.
  2042. */
  2043. while (1) {
  2044. int n;
  2045. len_and_sockaddr fromAddr;
  2046. /* Wait for connections... */
  2047. fromAddr.len = LSA_SIZEOF_SA;
  2048. n = accept(server_socket, &fromAddr.u.sa, &fromAddr.len);
  2049. if (n < 0)
  2050. continue;
  2051. /* set the KEEPALIVE option to cull dead connections */
  2052. setsockopt(n, SOL_SOCKET, SO_KEEPALIVE, &const_int_1, sizeof(const_int_1));
  2053. if (fork() == 0) {
  2054. /* child */
  2055. /* Do not reload config on HUP */
  2056. signal(SIGHUP, SIG_IGN);
  2057. close(server_socket);
  2058. xmove_fd(n, 0);
  2059. xdup2(0, 1);
  2060. handle_incoming_and_exit(&fromAddr);
  2061. }
  2062. /* parent, or fork failed */
  2063. close(n);
  2064. } /* while (1) */
  2065. /* never reached */
  2066. }
  2067. #else
  2068. static void mini_httpd_nommu(int server_socket, int argc, char **argv) NORETURN;
  2069. static void mini_httpd_nommu(int server_socket, int argc, char **argv)
  2070. {
  2071. char *argv_copy[argc + 2];
  2072. argv_copy[0] = argv[0];
  2073. argv_copy[1] = (char*)"-i";
  2074. memcpy(&argv_copy[2], &argv[1], argc * sizeof(argv[0]));
  2075. /* NB: it's best to not use xfuncs in this loop before vfork().
  2076. * Otherwise server may die on transient errors (temporary
  2077. * out-of-memory condition, etc), which is Bad(tm).
  2078. * Try to do any dangerous calls after fork.
  2079. */
  2080. while (1) {
  2081. int n;
  2082. len_and_sockaddr fromAddr;
  2083. /* Wait for connections... */
  2084. fromAddr.len = LSA_SIZEOF_SA;
  2085. n = accept(server_socket, &fromAddr.u.sa, &fromAddr.len);
  2086. if (n < 0)
  2087. continue;
  2088. /* set the KEEPALIVE option to cull dead connections */
  2089. setsockopt(n, SOL_SOCKET, SO_KEEPALIVE, &const_int_1, sizeof(const_int_1));
  2090. if (vfork() == 0) {
  2091. /* child */
  2092. /* Do not reload config on HUP */
  2093. signal(SIGHUP, SIG_IGN);
  2094. close(server_socket);
  2095. xmove_fd(n, 0);
  2096. xdup2(0, 1);
  2097. /* Run a copy of ourself in inetd mode */
  2098. re_exec(argv_copy);
  2099. }
  2100. /* parent, or vfork failed */
  2101. close(n);
  2102. } /* while (1) */
  2103. /* never reached */
  2104. }
  2105. #endif
  2106. /*
  2107. * Process a HTTP connection on stdin/out.
  2108. * Never returns.
  2109. */
  2110. static void mini_httpd_inetd(void) NORETURN;
  2111. static void mini_httpd_inetd(void)
  2112. {
  2113. len_and_sockaddr fromAddr;
  2114. memset(&fromAddr, 0, sizeof(fromAddr));
  2115. fromAddr.len = LSA_SIZEOF_SA;
  2116. /* NB: can fail if user runs it by hand and types in http cmds */
  2117. getpeername(0, &fromAddr.u.sa, &fromAddr.len);
  2118. handle_incoming_and_exit(&fromAddr);
  2119. }
  2120. static void sighup_handler(int sig UNUSED_PARAM)
  2121. {
  2122. parse_conf(DEFAULT_PATH_HTTPD_CONF, SIGNALED_PARSE);
  2123. }
  2124. enum {
  2125. c_opt_config_file = 0,
  2126. d_opt_decode_url,
  2127. h_opt_home_httpd,
  2128. IF_FEATURE_HTTPD_ENCODE_URL_STR(e_opt_encode_url,)
  2129. IF_FEATURE_HTTPD_BASIC_AUTH( r_opt_realm ,)
  2130. IF_FEATURE_HTTPD_AUTH_MD5( m_opt_md5 ,)
  2131. IF_FEATURE_HTTPD_SETUID( u_opt_setuid ,)
  2132. p_opt_port ,
  2133. p_opt_inetd ,
  2134. p_opt_foreground,
  2135. p_opt_verbose ,
  2136. OPT_CONFIG_FILE = 1 << c_opt_config_file,
  2137. OPT_DECODE_URL = 1 << d_opt_decode_url,
  2138. OPT_HOME_HTTPD = 1 << h_opt_home_httpd,
  2139. OPT_ENCODE_URL = IF_FEATURE_HTTPD_ENCODE_URL_STR((1 << e_opt_encode_url)) + 0,
  2140. OPT_REALM = IF_FEATURE_HTTPD_BASIC_AUTH( (1 << r_opt_realm )) + 0,
  2141. OPT_MD5 = IF_FEATURE_HTTPD_AUTH_MD5( (1 << m_opt_md5 )) + 0,
  2142. OPT_SETUID = IF_FEATURE_HTTPD_SETUID( (1 << u_opt_setuid )) + 0,
  2143. OPT_PORT = 1 << p_opt_port,
  2144. OPT_INETD = 1 << p_opt_inetd,
  2145. OPT_FOREGROUND = 1 << p_opt_foreground,
  2146. OPT_VERBOSE = 1 << p_opt_verbose,
  2147. };
  2148. int httpd_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
  2149. int httpd_main(int argc UNUSED_PARAM, char **argv)
  2150. {
  2151. int server_socket = server_socket; /* for gcc */
  2152. unsigned opt;
  2153. char *url_for_decode;
  2154. IF_FEATURE_HTTPD_ENCODE_URL_STR(const char *url_for_encode;)
  2155. IF_FEATURE_HTTPD_SETUID(const char *s_ugid = NULL;)
  2156. IF_FEATURE_HTTPD_SETUID(struct bb_uidgid_t ugid;)
  2157. IF_FEATURE_HTTPD_AUTH_MD5(const char *pass;)
  2158. INIT_G();
  2159. #if ENABLE_LOCALE_SUPPORT
  2160. /* Undo busybox.c: we want to speak English in http (dates etc) */
  2161. setlocale(LC_TIME, "C");
  2162. #endif
  2163. home_httpd = xrealloc_getcwd_or_warn(NULL);
  2164. /* -v counts, -i implies -f */
  2165. opt_complementary = "vv:if";
  2166. /* We do not "absolutize" path given by -h (home) opt.
  2167. * If user gives relative path in -h,
  2168. * $SCRIPT_FILENAME will not be set. */
  2169. opt = getopt32(argv, "c:d:h:"
  2170. IF_FEATURE_HTTPD_ENCODE_URL_STR("e:")
  2171. IF_FEATURE_HTTPD_BASIC_AUTH("r:")
  2172. IF_FEATURE_HTTPD_AUTH_MD5("m:")
  2173. IF_FEATURE_HTTPD_SETUID("u:")
  2174. "p:ifv",
  2175. &opt_c_configFile, &url_for_decode, &home_httpd
  2176. IF_FEATURE_HTTPD_ENCODE_URL_STR(, &url_for_encode)
  2177. IF_FEATURE_HTTPD_BASIC_AUTH(, &g_realm)
  2178. IF_FEATURE_HTTPD_AUTH_MD5(, &pass)
  2179. IF_FEATURE_HTTPD_SETUID(, &s_ugid)
  2180. , &bind_addr_or_port
  2181. , &verbose
  2182. );
  2183. if (opt & OPT_DECODE_URL) {
  2184. fputs(decodeString(url_for_decode, 1), stdout);
  2185. return 0;
  2186. }
  2187. #if ENABLE_FEATURE_HTTPD_ENCODE_URL_STR
  2188. if (opt & OPT_ENCODE_URL) {
  2189. fputs(encodeString(url_for_encode), stdout);
  2190. return 0;
  2191. }
  2192. #endif
  2193. #if ENABLE_FEATURE_HTTPD_AUTH_MD5
  2194. if (opt & OPT_MD5) {
  2195. char salt[sizeof("$1$XXXXXXXX")];
  2196. salt[0] = '$';
  2197. salt[1] = '1';
  2198. salt[2] = '$';
  2199. crypt_make_salt(salt + 3, 4, 0);
  2200. puts(pw_encrypt(pass, salt, 1));
  2201. return 0;
  2202. }
  2203. #endif
  2204. #if ENABLE_FEATURE_HTTPD_SETUID
  2205. if (opt & OPT_SETUID) {
  2206. xget_uidgid(&ugid, s_ugid);
  2207. }
  2208. #endif
  2209. #if !BB_MMU
  2210. if (!(opt & OPT_FOREGROUND)) {
  2211. bb_daemonize_or_rexec(0, argv); /* don't change current directory */
  2212. }
  2213. #endif
  2214. xchdir(home_httpd);
  2215. if (!(opt & OPT_INETD)) {
  2216. signal(SIGCHLD, SIG_IGN);
  2217. server_socket = openServer();
  2218. #if ENABLE_FEATURE_HTTPD_SETUID
  2219. /* drop privileges */
  2220. if (opt & OPT_SETUID) {
  2221. if (ugid.gid != (gid_t)-1) {
  2222. if (setgroups(1, &ugid.gid) == -1)
  2223. bb_perror_msg_and_die("setgroups");
  2224. xsetgid(ugid.gid);
  2225. }
  2226. xsetuid(ugid.uid);
  2227. }
  2228. #endif
  2229. }
  2230. #if 0
  2231. /* User can do it himself: 'env - PATH="$PATH" httpd'
  2232. * We don't do it because we don't want to screw users
  2233. * which want to do
  2234. * 'env - VAR1=val1 VAR2=val2 httpd'
  2235. * and have VAR1 and VAR2 values visible in their CGIs.
  2236. * Besides, it is also smaller. */
  2237. {
  2238. char *p = getenv("PATH");
  2239. /* env strings themself are not freed, no need to xstrdup(p): */
  2240. clearenv();
  2241. if (p)
  2242. putenv(p - 5);
  2243. // if (!(opt & OPT_INETD))
  2244. // setenv_long("SERVER_PORT", ???);
  2245. }
  2246. #endif
  2247. parse_conf(DEFAULT_PATH_HTTPD_CONF, FIRST_PARSE);
  2248. if (!(opt & OPT_INETD))
  2249. signal(SIGHUP, sighup_handler);
  2250. xfunc_error_retval = 0;
  2251. if (opt & OPT_INETD)
  2252. mini_httpd_inetd();
  2253. #if BB_MMU
  2254. if (!(opt & OPT_FOREGROUND))
  2255. bb_daemonize(0); /* don't change current directory */
  2256. mini_httpd(server_socket); /* never returns */
  2257. #else
  2258. mini_httpd_nommu(server_socket, argc, argv); /* never returns */
  2259. #endif
  2260. /* return 0; */
  2261. }