httpd.c 77 KB

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