httpd.c 81 KB

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