httpd.c 72 KB

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