httpd.c 78 KB

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