httpd.c 71 KB

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