httpd.c 65 KB

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