httpd.c 72 KB

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