httpd.c 72 KB

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