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