httpd.c 66 KB

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