httpd.c 69 KB

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