httpd.c 77 KB

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