httpd.c 78 KB

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