httpd.c 82 KB

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