filters.c 83 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035
  1. /*********************************************************************
  2. *
  3. * File : $Source: /cvsroot/ijbswa/current/filters.c,v $
  4. *
  5. * Purpose : Declares functions to parse/crunch headers and pages.
  6. *
  7. * Copyright : Written by and Copyright (C) 2001-2020 the
  8. * Privoxy team. https://www.privoxy.org/
  9. *
  10. * Based on the Internet Junkbuster originally written
  11. * by and Copyright (C) 1997 Anonymous Coders and
  12. * Junkbusters Corporation. http://www.junkbusters.com
  13. *
  14. * This program is free software; you can redistribute it
  15. * and/or modify it under the terms of the GNU General
  16. * Public License as published by the Free Software
  17. * Foundation; either version 2 of the License, or (at
  18. * your option) any later version.
  19. *
  20. * This program is distributed in the hope that it will
  21. * be useful, but WITHOUT ANY WARRANTY; without even the
  22. * implied warranty of MERCHANTABILITY or FITNESS FOR A
  23. * PARTICULAR PURPOSE. See the GNU General Public
  24. * License for more details.
  25. *
  26. * The GNU General Public License should be included with
  27. * this file. If not, you can view it at
  28. * http://www.gnu.org/copyleft/gpl.html
  29. * or write to the Free Software Foundation, Inc., 59
  30. * Temple Place - Suite 330, Boston, MA 02111-1307, USA.
  31. *
  32. *********************************************************************/
  33. #include "config.h"
  34. #include <stdio.h>
  35. #include <sys/types.h>
  36. #include <stdlib.h>
  37. #include <ctype.h>
  38. #include <string.h>
  39. #include <assert.h>
  40. #ifndef _WIN32
  41. #include <unistd.h>
  42. #include <netinet/in.h>
  43. #else
  44. #include <winsock2.h>
  45. #endif /* ndef _WIN32 */
  46. #include "project.h"
  47. #include "filters.h"
  48. #include "encode.h"
  49. #include "parsers.h"
  50. #include "ssplit.h"
  51. #include "errlog.h"
  52. #include "jbsockets.h"
  53. #include "miscutil.h"
  54. #include "actions.h"
  55. #include "cgi.h"
  56. #include "jcc.h"
  57. #include "list.h"
  58. #include "deanimate.h"
  59. #include "urlmatch.h"
  60. #include "loaders.h"
  61. #ifdef FEATURE_CLIENT_TAGS
  62. #include "client-tags.h"
  63. #endif
  64. #ifdef _WIN32
  65. #include "win32.h"
  66. #endif
  67. typedef char *(*filter_function_ptr)();
  68. static filter_function_ptr get_filter_function(const struct client_state *csp);
  69. static jb_err prepare_for_filtering(struct client_state *csp);
  70. static void apply_url_actions(struct current_action_spec *action,
  71. struct http_request *http,
  72. #ifdef FEATURE_CLIENT_TAGS
  73. const struct list *client_tags,
  74. #endif
  75. struct url_actions *b);
  76. #ifdef FEATURE_EXTENDED_STATISTICS
  77. static void increment_block_reason_counter(const char *block_reason);
  78. #endif
  79. #ifdef FEATURE_ACL
  80. #ifdef HAVE_RFC2553
  81. /*********************************************************************
  82. *
  83. * Function : sockaddr_storage_to_ip
  84. *
  85. * Description : Access internal structure of sockaddr_storage
  86. *
  87. * Parameters :
  88. * 1 : addr = socket address
  89. * 2 : ip = IP address as array of octets in network order
  90. * (it points into addr)
  91. * 3 : len = length of IP address in octets
  92. * 4 : port = port number in network order;
  93. *
  94. * Returns : void
  95. *
  96. *********************************************************************/
  97. static void sockaddr_storage_to_ip(const struct sockaddr_storage *addr,
  98. uint8_t **ip, unsigned int *len,
  99. in_port_t **port)
  100. {
  101. assert(NULL != addr);
  102. assert(addr->ss_family == AF_INET || addr->ss_family == AF_INET6);
  103. switch (addr->ss_family)
  104. {
  105. case AF_INET:
  106. if (NULL != len)
  107. {
  108. *len = 4;
  109. }
  110. if (NULL != ip)
  111. {
  112. *ip = (uint8_t *)
  113. &(((struct sockaddr_in *)addr)->sin_addr.s_addr);
  114. }
  115. if (NULL != port)
  116. {
  117. *port = &((struct sockaddr_in *)addr)->sin_port;
  118. }
  119. break;
  120. case AF_INET6:
  121. if (NULL != len)
  122. {
  123. *len = 16;
  124. }
  125. if (NULL != ip)
  126. {
  127. *ip = ((struct sockaddr_in6 *)addr)->sin6_addr.s6_addr;
  128. }
  129. if (NULL != port)
  130. {
  131. *port = &((struct sockaddr_in6 *)addr)->sin6_port;
  132. }
  133. break;
  134. }
  135. }
  136. /*********************************************************************
  137. *
  138. * Function : match_sockaddr
  139. *
  140. * Description : Check whether address matches network (IP address and port)
  141. *
  142. * Parameters :
  143. * 1 : network = socket address of subnework
  144. * 2 : netmask = network mask as socket address
  145. * 3 : address = checked socket address against given network
  146. *
  147. * Returns : 0 = doesn't match; 1 = does match
  148. *
  149. *********************************************************************/
  150. static int match_sockaddr(const struct sockaddr_storage *network,
  151. const struct sockaddr_storage *netmask,
  152. const struct sockaddr_storage *address)
  153. {
  154. uint8_t *network_addr, *netmask_addr, *address_addr;
  155. unsigned int addr_len;
  156. in_port_t *network_port, *netmask_port, *address_port;
  157. int i;
  158. if (network->ss_family != netmask->ss_family)
  159. {
  160. /* This should never happen */
  161. assert(network->ss_family == netmask->ss_family);
  162. log_error(LOG_LEVEL_FATAL, "Network and netmask differ in family.");
  163. }
  164. sockaddr_storage_to_ip(network, &network_addr, &addr_len, &network_port);
  165. sockaddr_storage_to_ip(netmask, &netmask_addr, NULL, &netmask_port);
  166. sockaddr_storage_to_ip(address, &address_addr, NULL, &address_port);
  167. /* Check for family */
  168. if ((network->ss_family == AF_INET) && (address->ss_family == AF_INET6)
  169. && IN6_IS_ADDR_V4MAPPED((struct in6_addr *)address_addr))
  170. {
  171. /* Map AF_INET6 V4MAPPED address into AF_INET */
  172. address_addr += 12;
  173. addr_len = 4;
  174. }
  175. else if ((network->ss_family == AF_INET6) && (address->ss_family == AF_INET)
  176. && IN6_IS_ADDR_V4MAPPED((struct in6_addr *)network_addr))
  177. {
  178. /* Map AF_INET6 V4MAPPED network into AF_INET */
  179. network_addr += 12;
  180. netmask_addr += 12;
  181. addr_len = 4;
  182. }
  183. /* XXX: Port check is signaled in netmask */
  184. if (*netmask_port && *network_port != *address_port)
  185. {
  186. return 0;
  187. }
  188. /* TODO: Optimize by checking by words instead of octets */
  189. for (i = 0; (i < addr_len) && netmask_addr[i]; i++)
  190. {
  191. if ((network_addr[i] & netmask_addr[i]) !=
  192. (address_addr[i] & netmask_addr[i]))
  193. {
  194. return 0;
  195. }
  196. }
  197. return 1;
  198. }
  199. #endif /* def HAVE_RFC2553 */
  200. /*********************************************************************
  201. *
  202. * Function : block_acl
  203. *
  204. * Description : Block this request?
  205. * Decide yes or no based on ACL file.
  206. *
  207. * Parameters :
  208. * 1 : dst = The proxy or gateway address this is going to.
  209. * Or NULL to check all possible targets.
  210. * 2 : csp = Current client state (buffers, headers, etc...)
  211. * Also includes the client IP address.
  212. *
  213. * Returns : 0 = FALSE (don't block) and 1 = TRUE (do block)
  214. *
  215. *********************************************************************/
  216. int block_acl(const struct access_control_addr *dst, const struct client_state *csp)
  217. {
  218. struct access_control_list *acl = csp->config->acl;
  219. /* if not using an access control list, then permit the connection */
  220. if (acl == NULL)
  221. {
  222. return(0);
  223. }
  224. /* search the list */
  225. while (acl != NULL)
  226. {
  227. if (
  228. #ifdef HAVE_RFC2553
  229. match_sockaddr(&acl->src->addr, &acl->src->mask, &csp->tcp_addr)
  230. #else
  231. (csp->ip_addr_long & acl->src->mask) == acl->src->addr
  232. #endif
  233. )
  234. {
  235. if (dst == NULL)
  236. {
  237. /* Just want to check if they have any access */
  238. if (acl->action == ACL_PERMIT)
  239. {
  240. return(0);
  241. }
  242. else
  243. {
  244. return(1);
  245. }
  246. }
  247. else if (
  248. #ifdef HAVE_RFC2553
  249. /*
  250. * XXX: An undefined acl->dst is full of zeros and should be
  251. * considered a wildcard address. sockaddr_storage_to_ip()
  252. * fails on such destinations because of unknown sa_familly
  253. * (glibc only?). However this test is not portable.
  254. *
  255. * So, we signal the acl->dst is wildcard in wildcard_dst.
  256. */
  257. acl->wildcard_dst ||
  258. match_sockaddr(&acl->dst->addr, &acl->dst->mask, &dst->addr)
  259. #else
  260. ((dst->addr & acl->dst->mask) == acl->dst->addr)
  261. && ((dst->port == acl->dst->port) || (acl->dst->port == 0))
  262. #endif
  263. )
  264. {
  265. if (acl->action == ACL_PERMIT)
  266. {
  267. return(0);
  268. }
  269. else
  270. {
  271. return(1);
  272. }
  273. }
  274. }
  275. acl = acl->next;
  276. }
  277. return(1);
  278. }
  279. /*********************************************************************
  280. *
  281. * Function : acl_addr
  282. *
  283. * Description : Called from `load_config' to parse an ACL address.
  284. *
  285. * Parameters :
  286. * 1 : aspec = String specifying ACL address.
  287. * 2 : aca = struct access_control_addr to fill in.
  288. *
  289. * Returns : 0 => Ok, everything else is an error.
  290. *
  291. *********************************************************************/
  292. int acl_addr(const char *aspec, struct access_control_addr *aca)
  293. {
  294. int i, masklength;
  295. #ifdef HAVE_RFC2553
  296. struct addrinfo hints, *result;
  297. uint8_t *mask_data;
  298. in_port_t *mask_port;
  299. unsigned int addr_len;
  300. #else
  301. long port;
  302. #endif /* def HAVE_RFC2553 */
  303. char *p;
  304. char *acl_spec = NULL;
  305. #ifdef HAVE_RFC2553
  306. /* XXX: Depend on ai_family */
  307. masklength = 128;
  308. #else
  309. masklength = 32;
  310. port = 0;
  311. #endif
  312. /*
  313. * Use a temporary acl spec copy so we can log
  314. * the unmodified original in case of parse errors.
  315. */
  316. acl_spec = strdup_or_die(aspec);
  317. if ((p = strchr(acl_spec, '/')) != NULL)
  318. {
  319. *p++ = '\0';
  320. if (privoxy_isdigit(*p) == 0)
  321. {
  322. freez(acl_spec);
  323. return(-1);
  324. }
  325. masklength = atoi(p);
  326. }
  327. if ((masklength < 0) ||
  328. #ifdef HAVE_RFC2553
  329. (masklength > 128)
  330. #else
  331. (masklength > 32)
  332. #endif
  333. )
  334. {
  335. freez(acl_spec);
  336. return(-1);
  337. }
  338. if ((*acl_spec == '[') && (NULL != (p = strchr(acl_spec, ']'))))
  339. {
  340. *p = '\0';
  341. memmove(acl_spec, acl_spec + 1, (size_t)(p - acl_spec));
  342. if (*++p != ':')
  343. {
  344. p = NULL;
  345. }
  346. }
  347. else
  348. {
  349. p = strchr(acl_spec, ':');
  350. }
  351. if (p != NULL)
  352. {
  353. assert(*p == ':');
  354. *p = '\0';
  355. p++;
  356. }
  357. #ifdef HAVE_RFC2553
  358. memset(&hints, 0, sizeof(struct addrinfo));
  359. hints.ai_family = AF_UNSPEC;
  360. hints.ai_socktype = SOCK_STREAM;
  361. i = getaddrinfo(acl_spec, p, &hints, &result);
  362. if (i != 0)
  363. {
  364. log_error(LOG_LEVEL_ERROR, "Can not resolve [%s]:%s: %s",
  365. acl_spec, p, gai_strerror(i));
  366. freez(acl_spec);
  367. return(-1);
  368. }
  369. freez(acl_spec);
  370. /* TODO: Allow multihomed hostnames */
  371. memcpy(&(aca->addr), result->ai_addr, result->ai_addrlen);
  372. freeaddrinfo(result);
  373. #else
  374. if (p != NULL)
  375. {
  376. char *endptr;
  377. port = strtol(p, &endptr, 10);
  378. if (port <= 0 || port > 65535 || *endptr != '\0')
  379. {
  380. freez(acl_spec);
  381. return(-1);
  382. }
  383. }
  384. aca->port = (unsigned long)port;
  385. aca->addr = ntohl(resolve_hostname_to_ip(acl_spec));
  386. freez(acl_spec);
  387. if (aca->addr == INADDR_NONE)
  388. {
  389. /* XXX: This will be logged as parse error. */
  390. return(-1);
  391. }
  392. #endif /* def HAVE_RFC2553 */
  393. /* build the netmask */
  394. #ifdef HAVE_RFC2553
  395. /* Clip masklength according to current family. */
  396. if ((aca->addr.ss_family == AF_INET) && (masklength > 32))
  397. {
  398. masklength = 32;
  399. }
  400. aca->mask.ss_family = aca->addr.ss_family;
  401. sockaddr_storage_to_ip(&aca->mask, &mask_data, &addr_len, &mask_port);
  402. if (p)
  403. {
  404. /* ACL contains a port number, check ports in the future. */
  405. *mask_port = 1;
  406. }
  407. /*
  408. * XXX: This could be optimized to operate on whole words instead
  409. * of octets (128-bit CPU could do it in one iteration).
  410. */
  411. /*
  412. * Octets after prefix can be omitted because of
  413. * previous initialization to zeros.
  414. */
  415. for (i = 0; (i < addr_len) && masklength; i++)
  416. {
  417. if (masklength >= 8)
  418. {
  419. mask_data[i] = 0xFF;
  420. masklength -= 8;
  421. }
  422. else
  423. {
  424. /*
  425. * XXX: This assumes MSB of octet is on the left side.
  426. * This should be true for all architectures or solved
  427. * by the link layer.
  428. */
  429. mask_data[i] = (uint8_t)~((1 << (8 - masklength)) - 1);
  430. masklength = 0;
  431. }
  432. }
  433. #else
  434. aca->mask = 0;
  435. for (i=1; i <= masklength ; i++)
  436. {
  437. aca->mask |= (1U << (32 - i));
  438. }
  439. /* now mask off the host portion of the ip address
  440. * (i.e. save on the network portion of the address).
  441. */
  442. aca->addr = aca->addr & aca->mask;
  443. #endif /* def HAVE_RFC2553 */
  444. return(0);
  445. }
  446. #endif /* def FEATURE_ACL */
  447. /*********************************************************************
  448. *
  449. * Function : connect_port_is_forbidden
  450. *
  451. * Description : Check to see if CONNECT requests to the destination
  452. * port of this request are forbidden. The check is
  453. * independent of the actual request method.
  454. *
  455. * Parameters :
  456. * 1 : csp = Current client state (buffers, headers, etc...)
  457. *
  458. * Returns : True if yes, false otherwise.
  459. *
  460. *********************************************************************/
  461. int connect_port_is_forbidden(const struct client_state *csp)
  462. {
  463. return ((csp->action->flags & ACTION_LIMIT_CONNECT) &&
  464. !match_portlist(csp->action->string[ACTION_STRING_LIMIT_CONNECT],
  465. csp->http->port));
  466. }
  467. /*********************************************************************
  468. *
  469. * Function : block_url
  470. *
  471. * Description : Called from `chat'. Check to see if we need to block this.
  472. *
  473. * Parameters :
  474. * 1 : csp = Current client state (buffers, headers, etc...)
  475. *
  476. * Returns : NULL => unblocked, else HTTP block response
  477. *
  478. *********************************************************************/
  479. struct http_response *block_url(struct client_state *csp)
  480. {
  481. struct http_response *rsp;
  482. const char *new_content_type = NULL;
  483. /*
  484. * If it's not blocked, don't block it ;-)
  485. */
  486. if ((csp->action->flags & ACTION_BLOCK) == 0)
  487. {
  488. return NULL;
  489. }
  490. if (csp->action->flags & ACTION_REDIRECT)
  491. {
  492. log_error(LOG_LEVEL_ERROR, "redirect{} overruled by block.");
  493. }
  494. /*
  495. * Else, prepare a response
  496. */
  497. if (NULL == (rsp = alloc_http_response()))
  498. {
  499. return cgi_error_memory();
  500. }
  501. #ifdef FEATURE_EXTENDED_STATISTICS
  502. if (csp->action->string[ACTION_STRING_BLOCK] != NULL)
  503. {
  504. increment_block_reason_counter(csp->action->string[ACTION_STRING_BLOCK]);
  505. }
  506. #endif
  507. /*
  508. * If it's an image-url, send back an image or redirect
  509. * as specified by the relevant +image action
  510. */
  511. #ifdef FEATURE_IMAGE_BLOCKING
  512. if (((csp->action->flags & ACTION_IMAGE_BLOCKER) != 0)
  513. && is_imageurl(csp))
  514. {
  515. char *p;
  516. /* determine HOW images should be blocked */
  517. p = csp->action->string[ACTION_STRING_IMAGE_BLOCKER];
  518. if (csp->action->flags & ACTION_HANDLE_AS_EMPTY_DOCUMENT)
  519. {
  520. log_error(LOG_LEVEL_ERROR, "handle-as-empty-document overruled by handle-as-image.");
  521. }
  522. /* and handle accordingly: */
  523. if ((p == NULL) || (0 == strcmpic(p, "pattern")))
  524. {
  525. rsp->status = strdup_or_die("403 Request blocked by Privoxy");
  526. rsp->body = bindup(image_pattern_data, image_pattern_length);
  527. if (rsp->body == NULL)
  528. {
  529. free_http_response(rsp);
  530. return cgi_error_memory();
  531. }
  532. rsp->content_length = image_pattern_length;
  533. if (enlist_unique_header(rsp->headers, "Content-Type", BUILTIN_IMAGE_MIMETYPE))
  534. {
  535. free_http_response(rsp);
  536. return cgi_error_memory();
  537. }
  538. }
  539. else if (0 == strcmpic(p, "blank"))
  540. {
  541. rsp->status = strdup_or_die("403 Request blocked by Privoxy");
  542. rsp->body = bindup(image_blank_data, image_blank_length);
  543. if (rsp->body == NULL)
  544. {
  545. free_http_response(rsp);
  546. return cgi_error_memory();
  547. }
  548. rsp->content_length = image_blank_length;
  549. if (enlist_unique_header(rsp->headers, "Content-Type", BUILTIN_IMAGE_MIMETYPE))
  550. {
  551. free_http_response(rsp);
  552. return cgi_error_memory();
  553. }
  554. }
  555. else
  556. {
  557. rsp->status = strdup_or_die("302 Local Redirect from Privoxy");
  558. if (enlist_unique_header(rsp->headers, "Location", p))
  559. {
  560. free_http_response(rsp);
  561. return cgi_error_memory();
  562. }
  563. }
  564. }
  565. else
  566. #endif /* def FEATURE_IMAGE_BLOCKING */
  567. if (csp->action->flags & ACTION_HANDLE_AS_EMPTY_DOCUMENT)
  568. {
  569. /*
  570. * Send empty document.
  571. */
  572. new_content_type = csp->action->string[ACTION_STRING_CONTENT_TYPE];
  573. freez(rsp->body);
  574. rsp->body = strdup_or_die(" ");
  575. rsp->content_length = 1;
  576. if (csp->config->feature_flags & RUNTIME_FEATURE_EMPTY_DOC_RETURNS_OK)
  577. {
  578. /*
  579. * Workaround for firefox bug 492459
  580. * https://bugzilla.mozilla.org/show_bug.cgi?id=492459
  581. * Return a 200 OK status for pages blocked with +handle-as-empty-document
  582. * if the "handle-as-empty-doc-returns-ok" runtime config option is set.
  583. */
  584. rsp->status = strdup_or_die("200 Request blocked by Privoxy");
  585. }
  586. else
  587. {
  588. rsp->status = strdup_or_die("403 Request blocked by Privoxy");
  589. }
  590. if (new_content_type != 0)
  591. {
  592. log_error(LOG_LEVEL_HEADER, "Overwriting Content-Type with %s", new_content_type);
  593. if (enlist_unique_header(rsp->headers, "Content-Type", new_content_type))
  594. {
  595. free_http_response(rsp);
  596. return cgi_error_memory();
  597. }
  598. }
  599. }
  600. else
  601. /*
  602. * Else, generate an HTML "blocked" message:
  603. */
  604. {
  605. jb_err err;
  606. struct map * exports;
  607. rsp->status = strdup_or_die("403 Request blocked by Privoxy");
  608. exports = default_exports(csp, NULL);
  609. if (exports == NULL)
  610. {
  611. free_http_response(rsp);
  612. return cgi_error_memory();
  613. }
  614. #ifdef FEATURE_FORCE_LOAD
  615. err = map(exports, "force-prefix", 1, FORCE_PREFIX, 1);
  616. /*
  617. * Export the force conditional block killer if
  618. *
  619. * - Privoxy was compiled without FEATURE_FORCE_LOAD, or
  620. * - Privoxy is configured to enforce blocks, or
  621. * - it's a CONNECT request and enforcing wouldn't work anyway.
  622. */
  623. if ((csp->config->feature_flags & RUNTIME_FEATURE_ENFORCE_BLOCKS)
  624. || (0 == strcmpic(csp->http->gpc, "connect")))
  625. #endif /* ndef FEATURE_FORCE_LOAD */
  626. {
  627. err = map_block_killer(exports, "force-support");
  628. }
  629. if (!err) err = map(exports, "protocol", 1, csp->http->ssl ? "https://" : "http://", 1);
  630. if (!err) err = map(exports, "hostport", 1, html_encode(csp->http->hostport), 0);
  631. if (!err) err = map(exports, "path", 1, html_encode(csp->http->path), 0);
  632. if (!err) err = map(exports, "path-ue", 1, url_encode(csp->http->path), 0);
  633. if (!err)
  634. {
  635. const char *block_reason;
  636. if (csp->action->string[ACTION_STRING_BLOCK] != NULL)
  637. {
  638. block_reason = csp->action->string[ACTION_STRING_BLOCK];
  639. }
  640. else
  641. {
  642. assert(connect_port_is_forbidden(csp));
  643. block_reason = "Forbidden CONNECT port.";
  644. }
  645. err = map(exports, "block-reason", 1, html_encode(block_reason), 0);
  646. }
  647. if (err)
  648. {
  649. free_map(exports);
  650. free_http_response(rsp);
  651. return cgi_error_memory();
  652. }
  653. err = template_fill_for_cgi(csp, "blocked", exports, rsp);
  654. if (err)
  655. {
  656. free_http_response(rsp);
  657. return cgi_error_memory();
  658. }
  659. }
  660. rsp->crunch_reason = BLOCKED;
  661. return finish_http_response(csp, rsp);
  662. }
  663. #ifdef FEATURE_TRUST
  664. /*********************************************************************
  665. *
  666. * Function : trust_url FIXME: I should be called distrust_url
  667. *
  668. * Description : Calls is_untrusted_url to determine if the URL is trusted
  669. * and if not, returns a HTTP 403 response with a reject message.
  670. *
  671. * Parameters :
  672. * 1 : csp = Current client state (buffers, headers, etc...)
  673. *
  674. * Returns : NULL => trusted, else http_response.
  675. *
  676. *********************************************************************/
  677. struct http_response *trust_url(struct client_state *csp)
  678. {
  679. struct http_response *rsp;
  680. struct map * exports;
  681. char buf[BUFFER_SIZE];
  682. char *p;
  683. struct pattern_spec **tl;
  684. struct pattern_spec *t;
  685. jb_err err;
  686. /*
  687. * Don't bother to work on trusted URLs
  688. */
  689. if (!is_untrusted_url(csp))
  690. {
  691. return NULL;
  692. }
  693. /*
  694. * Else, prepare a response:
  695. */
  696. if (NULL == (rsp = alloc_http_response()))
  697. {
  698. return cgi_error_memory();
  699. }
  700. rsp->status = strdup_or_die("403 Request blocked by Privoxy");
  701. exports = default_exports(csp, NULL);
  702. if (exports == NULL)
  703. {
  704. free_http_response(rsp);
  705. return cgi_error_memory();
  706. }
  707. /*
  708. * Export the protocol, host, port, and referrer information
  709. */
  710. err = map(exports, "hostport", 1, csp->http->hostport, 1);
  711. if (!err) err = map(exports, "protocol", 1, csp->http->ssl ? "https://" : "http://", 1);
  712. if (!err) err = map(exports, "path", 1, csp->http->path, 1);
  713. if (NULL != (p = get_header_value(csp->headers, "Referer:")))
  714. {
  715. if (!err) err = map(exports, "referrer", 1, html_encode(p), 0);
  716. }
  717. else
  718. {
  719. if (!err) err = map(exports, "referrer", 1, "none set", 1);
  720. }
  721. if (err)
  722. {
  723. free_map(exports);
  724. free_http_response(rsp);
  725. return cgi_error_memory();
  726. }
  727. /*
  728. * Export the trust list
  729. */
  730. p = strdup_or_die("");
  731. for (tl = csp->config->trust_list; (t = *tl) != NULL ; tl++)
  732. {
  733. snprintf(buf, sizeof(buf), "<li>%s</li>\n", t->spec);
  734. string_append(&p, buf);
  735. }
  736. err = map(exports, "trusted-referrers", 1, p, 0);
  737. if (err)
  738. {
  739. free_map(exports);
  740. free_http_response(rsp);
  741. return cgi_error_memory();
  742. }
  743. /*
  744. * Export the trust info, if available
  745. */
  746. if (csp->config->trust_info->first)
  747. {
  748. struct list_entry *l;
  749. p = strdup_or_die("");
  750. for (l = csp->config->trust_info->first; l ; l = l->next)
  751. {
  752. snprintf(buf, sizeof(buf), "<li> <a href=\"%s\">%s</a><br>\n", l->str, l->str);
  753. string_append(&p, buf);
  754. }
  755. err = map(exports, "trust-info", 1, p, 0);
  756. }
  757. else
  758. {
  759. err = map_block_killer(exports, "have-trust-info");
  760. }
  761. if (err)
  762. {
  763. free_map(exports);
  764. free_http_response(rsp);
  765. return cgi_error_memory();
  766. }
  767. /*
  768. * Export the force conditional block killer if
  769. *
  770. * - Privoxy was compiled without FEATURE_FORCE_LOAD, or
  771. * - Privoxy is configured to enforce blocks, or
  772. * - it's a CONNECT request and enforcing wouldn't work anyway.
  773. */
  774. #ifdef FEATURE_FORCE_LOAD
  775. if ((csp->config->feature_flags & RUNTIME_FEATURE_ENFORCE_BLOCKS)
  776. || (0 == strcmpic(csp->http->gpc, "connect")))
  777. {
  778. err = map_block_killer(exports, "force-support");
  779. }
  780. else
  781. {
  782. err = map(exports, "force-prefix", 1, FORCE_PREFIX, 1);
  783. }
  784. #else /* ifndef FEATURE_FORCE_LOAD */
  785. err = map_block_killer(exports, "force-support");
  786. #endif /* ndef FEATURE_FORCE_LOAD */
  787. if (err)
  788. {
  789. free_map(exports);
  790. free_http_response(rsp);
  791. return cgi_error_memory();
  792. }
  793. /*
  794. * Build the response
  795. */
  796. err = template_fill_for_cgi(csp, "untrusted", exports, rsp);
  797. if (err)
  798. {
  799. free_http_response(rsp);
  800. return cgi_error_memory();
  801. }
  802. rsp->crunch_reason = UNTRUSTED;
  803. return finish_http_response(csp, rsp);
  804. }
  805. #endif /* def FEATURE_TRUST */
  806. /*********************************************************************
  807. *
  808. * Function : compile_dynamic_pcrs_job_list
  809. *
  810. * Description : Compiles a dynamic pcrs job list (one with variables
  811. * resolved at request time)
  812. *
  813. * Parameters :
  814. * 1 : csp = Current client state (buffers, headers, etc...)
  815. * 2 : b = The filter list to compile
  816. *
  817. * Returns : NULL in case of errors, otherwise the
  818. * pcrs job list.
  819. *
  820. *********************************************************************/
  821. pcrs_job *compile_dynamic_pcrs_job_list(const struct client_state *csp, const struct re_filterfile_spec *b)
  822. {
  823. struct list_entry *pattern;
  824. pcrs_job *job_list = NULL;
  825. pcrs_job *dummy = NULL;
  826. pcrs_job *lastjob = NULL;
  827. int error = 0;
  828. const struct pcrs_variable variables[] =
  829. {
  830. {"url", csp->http->url, 1},
  831. {"path", csp->http->path, 1},
  832. {"host", csp->http->host, 1},
  833. {"origin", csp->ip_addr_str, 1},
  834. {"listen-address", csp->listen_addr_str, 1},
  835. {NULL, NULL, 1}
  836. };
  837. for (pattern = b->patterns->first; pattern != NULL; pattern = pattern->next)
  838. {
  839. assert(pattern->str != NULL);
  840. dummy = pcrs_compile_dynamic_command(pattern->str, variables, &error);
  841. if (NULL == dummy)
  842. {
  843. log_error(LOG_LEVEL_ERROR,
  844. "Compiling dynamic pcrs job '%s' for '%s' failed with error code %d: %s",
  845. pattern->str, b->name, error, pcrs_strerror(error));
  846. continue;
  847. }
  848. else
  849. {
  850. if (error == PCRS_WARN_TRUNCATION)
  851. {
  852. log_error(LOG_LEVEL_ERROR,
  853. "At least one of the variables in \'%s\' had to "
  854. "be truncated before compilation", pattern->str);
  855. }
  856. if (job_list == NULL)
  857. {
  858. job_list = dummy;
  859. }
  860. else
  861. {
  862. lastjob->next = dummy;
  863. }
  864. lastjob = dummy;
  865. }
  866. }
  867. return job_list;
  868. }
  869. /*********************************************************************
  870. *
  871. * Function : rewrite_url
  872. *
  873. * Description : Rewrites a URL with a single pcrs command
  874. * and returns the result if it differs from the
  875. * original and isn't obviously invalid.
  876. *
  877. * Parameters :
  878. * 1 : old_url = URL to rewrite.
  879. * 2 : pcrs_command = pcrs command formatted as string (s@foo@bar@)
  880. *
  881. *
  882. * Returns : NULL if the pcrs_command didn't change the url, or
  883. * the result of the modification.
  884. *
  885. *********************************************************************/
  886. char *rewrite_url(char *old_url, const char *pcrs_command)
  887. {
  888. char *new_url = NULL;
  889. int hits;
  890. assert(old_url);
  891. assert(pcrs_command);
  892. new_url = pcrs_execute_single_command(old_url, pcrs_command, &hits);
  893. if (hits == 0)
  894. {
  895. log_error(LOG_LEVEL_REDIRECTS,
  896. "pcrs command \"%s\" didn't change \"%s\".",
  897. pcrs_command, old_url);
  898. freez(new_url);
  899. }
  900. else if (hits < 0)
  901. {
  902. log_error(LOG_LEVEL_REDIRECTS,
  903. "executing pcrs command \"%s\" to rewrite %s failed: %s",
  904. pcrs_command, old_url, pcrs_strerror(hits));
  905. freez(new_url);
  906. }
  907. else if (strncmpic(new_url, "http://", 7) && strncmpic(new_url, "https://", 8))
  908. {
  909. log_error(LOG_LEVEL_ERROR,
  910. "pcrs command \"%s\" changed \"%s\" to \"%s\" (%u hi%s), "
  911. "but the result doesn't look like a valid URL and will be ignored.",
  912. pcrs_command, old_url, new_url, hits, (hits == 1) ? "t" : "ts");
  913. freez(new_url);
  914. }
  915. else
  916. {
  917. log_error(LOG_LEVEL_REDIRECTS,
  918. "pcrs command \"%s\" changed \"%s\" to \"%s\" (%u hi%s).",
  919. pcrs_command, old_url, new_url, hits, (hits == 1) ? "t" : "ts");
  920. }
  921. return new_url;
  922. }
  923. #ifdef FEATURE_FAST_REDIRECTS
  924. /*********************************************************************
  925. *
  926. * Function : get_last_url
  927. *
  928. * Description : Search for the last URL inside a string.
  929. * If the string already is a URL, it will
  930. * be the first URL found.
  931. *
  932. * Parameters :
  933. * 1 : subject = the string to check
  934. * 2 : redirect_mode = +fast-redirect{} mode
  935. *
  936. * Returns : NULL if no URL was found, or
  937. * the last URL found.
  938. *
  939. *********************************************************************/
  940. static char *get_last_url(char *subject, const char *redirect_mode)
  941. {
  942. char *new_url = NULL;
  943. char *tmp;
  944. assert(subject);
  945. assert(redirect_mode);
  946. subject = strdup(subject);
  947. if (subject == NULL)
  948. {
  949. log_error(LOG_LEVEL_ERROR, "Out of memory while searching for redirects.");
  950. return NULL;
  951. }
  952. if (0 == strcmpic(redirect_mode, "check-decoded-url") && strchr(subject, '%'))
  953. {
  954. char *url_segment = NULL;
  955. char **url_segments;
  956. size_t max_segments;
  957. int segments;
  958. log_error(LOG_LEVEL_REDIRECTS,
  959. "Checking \"%s\" for encoded redirects.", subject);
  960. /*
  961. * Check each parameter in the URL separately.
  962. * Sectionize the URL at "?" and "&",
  963. * go backwards through the segments, URL-decode them
  964. * and look for a URL in the decoded result.
  965. * Stop the search after the first match.
  966. *
  967. * XXX: This estimate is guaranteed to be high enough as we
  968. * let ssplit() ignore empty fields, but also a bit wasteful.
  969. */
  970. max_segments = strlen(subject) / 2;
  971. url_segments = malloc(max_segments * sizeof(char *));
  972. if (NULL == url_segments)
  973. {
  974. log_error(LOG_LEVEL_ERROR,
  975. "Out of memory while decoding URL: %s", subject);
  976. freez(subject);
  977. return NULL;
  978. }
  979. segments = ssplit(subject, "?&", url_segments, max_segments);
  980. while (segments-- > 0)
  981. {
  982. char *dtoken = url_decode(url_segments[segments]);
  983. if (NULL == dtoken)
  984. {
  985. log_error(LOG_LEVEL_ERROR, "Unable to decode \"%s\".", url_segments[segments]);
  986. continue;
  987. }
  988. url_segment = strstr(dtoken, "http://");
  989. if (NULL == url_segment)
  990. {
  991. url_segment = strstr(dtoken, "https://");
  992. }
  993. if (NULL != url_segment)
  994. {
  995. url_segment = strdup_or_die(url_segment);
  996. freez(dtoken);
  997. break;
  998. }
  999. freez(dtoken);
  1000. }
  1001. freez(subject);
  1002. freez(url_segments);
  1003. if (url_segment == NULL)
  1004. {
  1005. return NULL;
  1006. }
  1007. subject = url_segment;
  1008. }
  1009. else
  1010. {
  1011. /* Look for a URL inside this one, without decoding anything. */
  1012. log_error(LOG_LEVEL_REDIRECTS,
  1013. "Checking \"%s\" for unencoded redirects.", subject);
  1014. }
  1015. /*
  1016. * Find the last URL encoded in the request
  1017. */
  1018. tmp = subject;
  1019. while ((tmp = strstr(tmp, "http://")) != NULL)
  1020. {
  1021. new_url = tmp++;
  1022. }
  1023. tmp = (new_url != NULL) ? new_url : subject;
  1024. while ((tmp = strstr(tmp, "https://")) != NULL)
  1025. {
  1026. new_url = tmp++;
  1027. }
  1028. if ((new_url != NULL)
  1029. && ( (new_url != subject)
  1030. || (0 == strncmpic(subject, "http://", 7))
  1031. || (0 == strncmpic(subject, "https://", 8))
  1032. ))
  1033. {
  1034. /*
  1035. * Return new URL if we found a redirect
  1036. * or if the subject already was a URL.
  1037. *
  1038. * The second case makes sure that we can
  1039. * chain get_last_url after another redirection check
  1040. * (like rewrite_url) without losing earlier redirects.
  1041. */
  1042. new_url = strdup(new_url);
  1043. freez(subject);
  1044. return new_url;
  1045. }
  1046. freez(subject);
  1047. return NULL;
  1048. }
  1049. #endif /* def FEATURE_FAST_REDIRECTS */
  1050. /*********************************************************************
  1051. *
  1052. * Function : redirect_url
  1053. *
  1054. * Description : Checks if Privoxy should answer the request with
  1055. * a HTTP redirect and generates the redirect if
  1056. * necessary.
  1057. *
  1058. * Parameters :
  1059. * 1 : csp = Current client state (buffers, headers, etc...)
  1060. *
  1061. * Returns : NULL if the request can pass, HTTP redirect otherwise.
  1062. *
  1063. *********************************************************************/
  1064. struct http_response *redirect_url(struct client_state *csp)
  1065. {
  1066. struct http_response *rsp;
  1067. #ifdef FEATURE_FAST_REDIRECTS
  1068. /*
  1069. * XXX: Do we still need FEATURE_FAST_REDIRECTS
  1070. * as compile-time option? The user can easily disable
  1071. * it in his action file.
  1072. */
  1073. char * redirect_mode;
  1074. #endif /* def FEATURE_FAST_REDIRECTS */
  1075. char *old_url = NULL;
  1076. char *new_url = NULL;
  1077. char *redirection_string;
  1078. if ((csp->action->flags & ACTION_REDIRECT))
  1079. {
  1080. redirection_string = csp->action->string[ACTION_STRING_REDIRECT];
  1081. /*
  1082. * If the redirection string begins with 's',
  1083. * assume it's a pcrs command, otherwise treat it as
  1084. * properly formatted URL and use it for the redirection
  1085. * directly.
  1086. *
  1087. * According to (the now obsolete) RFC 2616 section 14.30
  1088. * the URL has to be absolute and if the user tries:
  1089. * +redirect{sadly/this/will/be/parsed/as/pcrs_command.html}
  1090. * she would get undefined results anyway.
  1091. *
  1092. * RFC 7231 7.1.2 actually allows relative references,
  1093. * but those start with a leading slash (RFC 3986 4.2) and
  1094. * thus can't be mistaken for pcrs commands either.
  1095. */
  1096. if (*redirection_string == 's')
  1097. {
  1098. old_url = csp->http->url;
  1099. new_url = rewrite_url(old_url, redirection_string);
  1100. }
  1101. else
  1102. {
  1103. log_error(LOG_LEVEL_REDIRECTS,
  1104. "No pcrs command recognized, assuming that \"%s\" is already properly formatted.",
  1105. redirection_string);
  1106. new_url = strdup(redirection_string);
  1107. }
  1108. }
  1109. #ifdef FEATURE_FAST_REDIRECTS
  1110. if ((csp->action->flags & ACTION_FAST_REDIRECTS))
  1111. {
  1112. redirect_mode = csp->action->string[ACTION_STRING_FAST_REDIRECTS];
  1113. /*
  1114. * If it exists, use the previously rewritten URL as input
  1115. * otherwise just use the old path.
  1116. */
  1117. old_url = (new_url != NULL) ? new_url : strdup(csp->http->path);
  1118. new_url = get_last_url(old_url, redirect_mode);
  1119. freez(old_url);
  1120. }
  1121. /*
  1122. * Disable redirect checkers, so that they
  1123. * will be only run more than once if the user
  1124. * also enables them through tags.
  1125. *
  1126. * From a performance point of view
  1127. * it doesn't matter, but the duplicated
  1128. * log messages are annoying.
  1129. */
  1130. csp->action->flags &= ~ACTION_FAST_REDIRECTS;
  1131. #endif /* def FEATURE_FAST_REDIRECTS */
  1132. csp->action->flags &= ~ACTION_REDIRECT;
  1133. /* Did any redirect action trigger? */
  1134. if (new_url)
  1135. {
  1136. if (url_requires_percent_encoding(new_url))
  1137. {
  1138. char *encoded_url;
  1139. log_error(LOG_LEVEL_REDIRECTS, "Percent-encoding redirect URL: %N",
  1140. strlen(new_url), new_url);
  1141. encoded_url = percent_encode_url(new_url);
  1142. freez(new_url);
  1143. if (encoded_url == NULL)
  1144. {
  1145. return cgi_error_memory();
  1146. }
  1147. new_url = encoded_url;
  1148. assert(FALSE == url_requires_percent_encoding(new_url));
  1149. }
  1150. if (0 == strcmpic(new_url, csp->http->url))
  1151. {
  1152. log_error(LOG_LEVEL_ERROR,
  1153. "New URL \"%s\" and old URL \"%s\" are the same. Redirection loop prevented.",
  1154. csp->http->url, new_url);
  1155. freez(new_url);
  1156. }
  1157. else
  1158. {
  1159. log_error(LOG_LEVEL_REDIRECTS, "New URL is: %s", new_url);
  1160. if (NULL == (rsp = alloc_http_response()))
  1161. {
  1162. freez(new_url);
  1163. return cgi_error_memory();
  1164. }
  1165. rsp->status = strdup_or_die("302 Local Redirect from Privoxy");
  1166. if (enlist_unique_header(rsp->headers, "Location", new_url))
  1167. {
  1168. freez(new_url);
  1169. free_http_response(rsp);
  1170. return cgi_error_memory();
  1171. }
  1172. rsp->crunch_reason = REDIRECTED;
  1173. freez(new_url);
  1174. return finish_http_response(csp, rsp);
  1175. }
  1176. }
  1177. /* Only reached if no redirect is required */
  1178. return NULL;
  1179. }
  1180. #ifdef FEATURE_IMAGE_BLOCKING
  1181. /*********************************************************************
  1182. *
  1183. * Function : is_imageurl
  1184. *
  1185. * Description : Given a URL, decide whether it should be treated
  1186. * as image URL or not.
  1187. *
  1188. * Parameters :
  1189. * 1 : csp = Current client state (buffers, headers, etc...)
  1190. *
  1191. * Returns : True (nonzero) if URL is an image URL, false (0)
  1192. * otherwise
  1193. *
  1194. *********************************************************************/
  1195. int is_imageurl(const struct client_state *csp)
  1196. {
  1197. return ((csp->action->flags & ACTION_IMAGE) != 0);
  1198. }
  1199. #endif /* def FEATURE_IMAGE_BLOCKING */
  1200. #ifdef FEATURE_TRUST
  1201. /*********************************************************************
  1202. *
  1203. * Function : is_untrusted_url
  1204. *
  1205. * Description : Should we "distrust" this URL (and block it)?
  1206. *
  1207. * Yes if it matches a line in the trustfile, or if the
  1208. * referrer matches a line starting with "+" in the
  1209. * trustfile.
  1210. * No otherwise.
  1211. *
  1212. * Parameters :
  1213. * 1 : csp = Current client state (buffers, headers, etc...)
  1214. *
  1215. * Returns : 0 => trusted, 1 => untrusted
  1216. *
  1217. *********************************************************************/
  1218. int is_untrusted_url(const struct client_state *csp)
  1219. {
  1220. struct file_list *fl;
  1221. struct block_spec *b;
  1222. struct pattern_spec **trusted_url;
  1223. struct http_request rhttp[1];
  1224. const char * referer;
  1225. jb_err err;
  1226. /*
  1227. * If we don't have a trustlist, we trust everybody
  1228. */
  1229. if (((fl = csp->tlist) == NULL) || ((b = fl->f) == NULL))
  1230. {
  1231. return 0;
  1232. }
  1233. memset(rhttp, '\0', sizeof(*rhttp));
  1234. /*
  1235. * Do we trust the request URL itself?
  1236. */
  1237. for (b = b->next; b ; b = b->next)
  1238. {
  1239. if (url_match(b->url, csp->http))
  1240. {
  1241. return b->reject;
  1242. }
  1243. }
  1244. if (NULL == (referer = get_header_value(csp->headers, "Referer:")))
  1245. {
  1246. /* no referrer was supplied */
  1247. return 1;
  1248. }
  1249. /*
  1250. * If not, do we maybe trust its referrer?
  1251. */
  1252. err = parse_http_url(referer, rhttp, REQUIRE_PROTOCOL);
  1253. if (err)
  1254. {
  1255. return 1;
  1256. }
  1257. for (trusted_url = csp->config->trust_list; *trusted_url != NULL; trusted_url++)
  1258. {
  1259. if (url_match(*trusted_url, rhttp))
  1260. {
  1261. /* if the URL's referrer is from a trusted referrer, then
  1262. * add the target spec to the trustfile as an unblocked
  1263. * domain and return 0 (which means it's OK).
  1264. */
  1265. FILE *fp;
  1266. if (NULL != (fp = fopen(csp->config->trustfile, "a")))
  1267. {
  1268. char * path;
  1269. char * path_end;
  1270. char * new_entry = strdup_or_die("~");
  1271. string_append(&new_entry, csp->http->hostport);
  1272. path = csp->http->path;
  1273. if ( (path[0] == '/')
  1274. && (path[1] == '~')
  1275. && ((path_end = strchr(path + 2, '/')) != NULL))
  1276. {
  1277. /* since this path points into a user's home space
  1278. * be sure to include this spec in the trustfile.
  1279. */
  1280. long path_len = path_end - path; /* save offset */
  1281. path = strdup(path); /* Copy string */
  1282. if (path != NULL)
  1283. {
  1284. path_end = path + path_len; /* regenerate ptr to new buffer */
  1285. *(path_end + 1) = '\0'; /* Truncate path after '/' */
  1286. }
  1287. string_join(&new_entry, path);
  1288. }
  1289. /*
  1290. * Give a reason for generating this entry.
  1291. */
  1292. string_append(&new_entry, " # Trusted referrer was: ");
  1293. string_append(&new_entry, referer);
  1294. if (new_entry != NULL)
  1295. {
  1296. if (-1 == fprintf(fp, "%s\n", new_entry))
  1297. {
  1298. log_error(LOG_LEVEL_ERROR, "Failed to append \'%s\' to trustfile \'%s\': %E",
  1299. new_entry, csp->config->trustfile);
  1300. }
  1301. freez(new_entry);
  1302. }
  1303. else
  1304. {
  1305. /* FIXME: No way to handle out-of memory, so mostly ignoring it */
  1306. log_error(LOG_LEVEL_ERROR, "Out of memory adding pattern to trust file");
  1307. }
  1308. fclose(fp);
  1309. }
  1310. else
  1311. {
  1312. log_error(LOG_LEVEL_ERROR, "Failed to append new entry for \'%s\' to trustfile \'%s\': %E",
  1313. csp->http->hostport, csp->config->trustfile);
  1314. }
  1315. return 0;
  1316. }
  1317. }
  1318. return 1;
  1319. }
  1320. #endif /* def FEATURE_TRUST */
  1321. /*********************************************************************
  1322. *
  1323. * Function : get_filter
  1324. *
  1325. * Description : Get a filter with a given name and type.
  1326. * Note that taggers are filters, too.
  1327. *
  1328. * Parameters :
  1329. * 1 : csp = Current client state (buffers, headers, etc...)
  1330. * 2 : requested_name = Name of the content filter to get
  1331. * 3 : requested_type = Type of the filter to tagger to lookup
  1332. *
  1333. * Returns : A pointer to the requested filter
  1334. * or NULL if the filter wasn't found
  1335. *
  1336. *********************************************************************/
  1337. struct re_filterfile_spec *get_filter(const struct client_state *csp,
  1338. const char *requested_name,
  1339. enum filter_type requested_type)
  1340. {
  1341. int i;
  1342. struct re_filterfile_spec *b;
  1343. struct file_list *fl;
  1344. for (i = 0; i < MAX_AF_FILES; i++)
  1345. {
  1346. fl = csp->rlist[i];
  1347. if ((NULL == fl) || (NULL == fl->f))
  1348. {
  1349. /*
  1350. * Either there are no filter files left or this
  1351. * filter file just contains no valid filters.
  1352. *
  1353. * Continue to be sure we don't miss valid filter
  1354. * files that are chained after empty or invalid ones.
  1355. */
  1356. continue;
  1357. }
  1358. for (b = fl->f; b != NULL; b = b->next)
  1359. {
  1360. if (b->type != requested_type)
  1361. {
  1362. /* The callers isn't interested in this filter type. */
  1363. continue;
  1364. }
  1365. if (strcmp(b->name, requested_name) == 0)
  1366. {
  1367. /* The requested filter has been found. Abort search. */
  1368. return b;
  1369. }
  1370. }
  1371. }
  1372. /* No filter with the given name and type exists. */
  1373. return NULL;
  1374. }
  1375. /*********************************************************************
  1376. *
  1377. * Function : pcrs_filter_response
  1378. *
  1379. * Description : Execute all text substitutions from all applying
  1380. * +filter actions on the text buffer that's been
  1381. * accumulated in csp->iob->buf.
  1382. *
  1383. * Parameters :
  1384. * 1 : csp = Current client state (buffers, headers, etc...)
  1385. *
  1386. * Returns : a pointer to the (newly allocated) modified buffer.
  1387. * or NULL if there were no hits or something went wrong
  1388. *
  1389. *********************************************************************/
  1390. static char *pcrs_filter_response(struct client_state *csp)
  1391. {
  1392. int hits = 0;
  1393. size_t size, prev_size;
  1394. char *old = NULL;
  1395. char *new = NULL;
  1396. pcrs_job *job;
  1397. struct re_filterfile_spec *b;
  1398. struct list_entry *filtername;
  1399. /*
  1400. * Sanity first
  1401. */
  1402. if (csp->iob->cur >= csp->iob->eod)
  1403. {
  1404. return(NULL);
  1405. }
  1406. if (filters_available(csp) == FALSE)
  1407. {
  1408. log_error(LOG_LEVEL_ERROR, "Inconsistent configuration: "
  1409. "content filtering enabled, but no content filters available.");
  1410. return(NULL);
  1411. }
  1412. size = (size_t)(csp->iob->eod - csp->iob->cur);
  1413. old = csp->iob->cur;
  1414. /*
  1415. * For all applying +filter actions, look if a filter by that
  1416. * name exists and if yes, execute it's pcrs_joblist on the
  1417. * buffer.
  1418. */
  1419. for (filtername = csp->action->multi[ACTION_MULTI_FILTER]->first;
  1420. filtername != NULL; filtername = filtername->next)
  1421. {
  1422. int current_hits = 0; /* Number of hits caused by this filter */
  1423. int job_number = 0; /* Which job we're currently executing */
  1424. int job_hits = 0; /* How many hits the current job caused */
  1425. pcrs_job *joblist;
  1426. b = get_filter(csp, filtername->str, FT_CONTENT_FILTER);
  1427. if (b == NULL)
  1428. {
  1429. continue;
  1430. }
  1431. joblist = b->joblist;
  1432. if (b->dynamic) joblist = compile_dynamic_pcrs_job_list(csp, b);
  1433. if (NULL == joblist)
  1434. {
  1435. log_error(LOG_LEVEL_RE_FILTER, "Filter %s has empty joblist. Nothing to do.", b->name);
  1436. continue;
  1437. }
  1438. prev_size = size;
  1439. /* Apply all jobs from the joblist */
  1440. for (job = joblist; NULL != job; job = job->next)
  1441. {
  1442. job_number++;
  1443. job_hits = pcrs_execute(job, old, size, &new, &size);
  1444. if (job_hits >= 0)
  1445. {
  1446. /*
  1447. * That went well. Continue filtering
  1448. * and use the result of this job as
  1449. * input for the next one.
  1450. */
  1451. current_hits += job_hits;
  1452. if (old != csp->iob->cur)
  1453. {
  1454. freez(old);
  1455. }
  1456. old = new;
  1457. }
  1458. else
  1459. {
  1460. /*
  1461. * This job caused an unexpected error. Inform the user
  1462. * and skip the rest of the jobs in this filter. We could
  1463. * continue with the next job, but usually the jobs
  1464. * depend on each other or are similar enough to
  1465. * fail for the same reason.
  1466. *
  1467. * At the moment our pcrs expects the error codes of pcre 3.4,
  1468. * but newer pcre versions can return additional error codes.
  1469. * As a result pcrs_strerror()'s error message might be
  1470. * "Unknown error ...", therefore we print the numerical value
  1471. * as well.
  1472. *
  1473. * XXX: Is this important enough for LOG_LEVEL_ERROR or
  1474. * should we use LOG_LEVEL_RE_FILTER instead?
  1475. */
  1476. log_error(LOG_LEVEL_ERROR, "Skipped filter \'%s\' after job number %u: %s (%d)",
  1477. b->name, job_number, pcrs_strerror(job_hits), job_hits);
  1478. break;
  1479. }
  1480. }
  1481. if (b->dynamic) pcrs_free_joblist(joblist);
  1482. log_error(LOG_LEVEL_RE_FILTER,
  1483. "filtering %s%s (size %lu) with \'%s\' produced %d hits (new size %lu).",
  1484. csp->http->hostport, csp->http->path, prev_size, b->name, current_hits, size);
  1485. #ifdef FEATURE_EXTENDED_STATISTICS
  1486. update_filter_statistics(b->name, current_hits);
  1487. #endif
  1488. hits += current_hits;
  1489. }
  1490. /*
  1491. * If there were no hits, destroy our copy and let
  1492. * chat() use the original in csp->iob
  1493. */
  1494. if (!hits)
  1495. {
  1496. if (old != csp->iob->cur && old != new)
  1497. {
  1498. freez(old);
  1499. }
  1500. freez(new);
  1501. return(NULL);
  1502. }
  1503. csp->flags |= CSP_FLAG_MODIFIED;
  1504. csp->content_length = size;
  1505. clear_iob(csp->iob);
  1506. return(new);
  1507. }
  1508. #ifdef FEATURE_EXTERNAL_FILTERS
  1509. /*********************************************************************
  1510. *
  1511. * Function : get_external_filter
  1512. *
  1513. * Description : Lookup the code to execute for an external filter.
  1514. * Masks the misuse of the re_filterfile_spec.
  1515. *
  1516. * Parameters :
  1517. * 1 : csp = Current client state (buffers, headers, etc...)
  1518. * 2 : name = Name of the content filter to get
  1519. *
  1520. * Returns : A pointer to the requested code
  1521. * or NULL if the filter wasn't found
  1522. *
  1523. *********************************************************************/
  1524. static const char *get_external_filter(const struct client_state *csp,
  1525. const char *name)
  1526. {
  1527. struct re_filterfile_spec *external_filter;
  1528. external_filter = get_filter(csp, name, FT_EXTERNAL_CONTENT_FILTER);
  1529. if (external_filter == NULL)
  1530. {
  1531. log_error(LOG_LEVEL_FATAL,
  1532. "Didn't find stuff to execute for external filter: %s",
  1533. name);
  1534. }
  1535. return external_filter->patterns->first->str;
  1536. }
  1537. /*********************************************************************
  1538. *
  1539. * Function : set_privoxy_variables
  1540. *
  1541. * Description : Sets a couple of privoxy-specific environment variables
  1542. *
  1543. * Parameters :
  1544. * 1 : csp = Current client state (buffers, headers, etc...)
  1545. *
  1546. * Returns : N/A
  1547. *
  1548. *********************************************************************/
  1549. static void set_privoxy_variables(const struct client_state *csp)
  1550. {
  1551. int i;
  1552. struct {
  1553. const char *name;
  1554. const char *value;
  1555. } env[] = {
  1556. { "PRIVOXY_URL", csp->http->url },
  1557. { "PRIVOXY_PATH", csp->http->path },
  1558. { "PRIVOXY_HOST", csp->http->host },
  1559. { "PRIVOXY_ORIGIN", csp->ip_addr_str },
  1560. { "PRIVOXY_LISTEN_ADDRESS", csp->listen_addr_str },
  1561. };
  1562. for (i = 0; i < SZ(env); i++)
  1563. {
  1564. if (setenv(env[i].name, env[i].value, 1))
  1565. {
  1566. log_error(LOG_LEVEL_ERROR, "Failed to set %s=%s: %E",
  1567. env[i].name, env[i].value);
  1568. }
  1569. }
  1570. }
  1571. /*********************************************************************
  1572. *
  1573. * Function : execute_external_filter
  1574. *
  1575. * Description : Pipe content into external filter and return the output
  1576. *
  1577. * Parameters :
  1578. * 1 : csp = Current client state (buffers, headers, etc...)
  1579. * 2 : name = Name of the external filter to execute
  1580. * 3 : content = The original content to filter
  1581. * 4 : size = The size of the content buffer
  1582. *
  1583. * Returns : a pointer to the (newly allocated) modified buffer.
  1584. * or NULL if there were no hits or something went wrong
  1585. *
  1586. *********************************************************************/
  1587. static char *execute_external_filter(const struct client_state *csp,
  1588. const char *name, char *content, size_t *size)
  1589. {
  1590. char cmd[200];
  1591. char file_name[FILENAME_MAX];
  1592. FILE *fp;
  1593. char *filter_output;
  1594. int fd;
  1595. int ret;
  1596. size_t new_size;
  1597. const char *external_filter;
  1598. if (csp->config->temporary_directory == NULL)
  1599. {
  1600. log_error(LOG_LEVEL_ERROR,
  1601. "No temporary-directory configured. Can't execute filter: %s",
  1602. name);
  1603. return NULL;
  1604. }
  1605. external_filter = get_external_filter(csp, name);
  1606. if (sizeof(file_name) < snprintf(file_name, sizeof(file_name),
  1607. "%s/privoxy-XXXXXXXX", csp->config->temporary_directory))
  1608. {
  1609. log_error(LOG_LEVEL_ERROR, "temporary-directory path too long");
  1610. return NULL;
  1611. }
  1612. fd = mkstemp(file_name);
  1613. if (fd == -1)
  1614. {
  1615. log_error(LOG_LEVEL_ERROR, "mkstemp() failed to create %s: %E", file_name);
  1616. return NULL;
  1617. }
  1618. fp = fdopen(fd, "w");
  1619. if (fp == NULL)
  1620. {
  1621. log_error(LOG_LEVEL_ERROR, "fdopen() failed: %E");
  1622. unlink(file_name);
  1623. return NULL;
  1624. }
  1625. /*
  1626. * The size may be zero if a previous filter discarded everything.
  1627. *
  1628. * This isn't necessary unintentional, so we just don't try
  1629. * to fwrite() nothing and let the user deal with the rest.
  1630. */
  1631. if ((*size != 0) && fwrite(content, *size, 1, fp) != 1)
  1632. {
  1633. log_error(LOG_LEVEL_ERROR, "fwrite(..., %lu, 1, ..) failed: %E", *size);
  1634. unlink(file_name);
  1635. fclose(fp);
  1636. return NULL;
  1637. }
  1638. fclose(fp);
  1639. if (sizeof(cmd) < snprintf(cmd, sizeof(cmd), "%s < %s", external_filter, file_name))
  1640. {
  1641. log_error(LOG_LEVEL_ERROR,
  1642. "temporary-directory or external filter path too long");
  1643. unlink(file_name);
  1644. return NULL;
  1645. }
  1646. log_error(LOG_LEVEL_RE_FILTER, "Executing '%s': %s", name, cmd);
  1647. /*
  1648. * The locking is necessary to prevent other threads
  1649. * from overwriting the environment variables before
  1650. * the popen fork. Afterwards this no longer matters.
  1651. */
  1652. privoxy_mutex_lock(&external_filter_mutex);
  1653. set_privoxy_variables(csp);
  1654. fp = popen(cmd, "r");
  1655. privoxy_mutex_unlock(&external_filter_mutex);
  1656. if (fp == NULL)
  1657. {
  1658. log_error(LOG_LEVEL_ERROR, "popen(\"%s\", \"r\") failed: %E", cmd);
  1659. unlink(file_name);
  1660. return NULL;
  1661. }
  1662. /* Allocate at least one byte */
  1663. filter_output = malloc_or_die(*size + 1);
  1664. new_size = 0;
  1665. while (!feof(fp) && !ferror(fp))
  1666. {
  1667. size_t len;
  1668. /* Could be bigger ... */
  1669. enum { READ_LENGTH = 2048 };
  1670. if (new_size + READ_LENGTH >= *size)
  1671. {
  1672. char *p;
  1673. /* Could be considered wasteful if the content is 'large'. */
  1674. *size += (*size >= READ_LENGTH) ? *size : READ_LENGTH;
  1675. p = realloc(filter_output, *size);
  1676. if (p == NULL)
  1677. {
  1678. log_error(LOG_LEVEL_ERROR, "Out of memory while reading "
  1679. "external filter output. Using what we got so far.");
  1680. break;
  1681. }
  1682. filter_output = p;
  1683. }
  1684. assert(new_size + READ_LENGTH < *size);
  1685. len = fread(&filter_output[new_size], 1, READ_LENGTH, fp);
  1686. if (len > 0)
  1687. {
  1688. new_size += len;
  1689. }
  1690. }
  1691. ret = pclose(fp);
  1692. if (ret == -1)
  1693. {
  1694. log_error(LOG_LEVEL_ERROR, "Executing %s failed: %E", cmd);
  1695. }
  1696. else
  1697. {
  1698. log_error(LOG_LEVEL_RE_FILTER,
  1699. "Executing '%s' resulted in return value %d. "
  1700. "Read %lu of up to %lu bytes.", name, (ret >> 8), new_size, *size);
  1701. }
  1702. unlink(file_name);
  1703. *size = new_size;
  1704. return filter_output;
  1705. }
  1706. #endif /* def FEATURE_EXTERNAL_FILTERS */
  1707. /*********************************************************************
  1708. *
  1709. * Function : gif_deanimate_response
  1710. *
  1711. * Description : Deanimate the GIF image that has been accumulated in
  1712. * csp->iob->buf, set csp->content_length to the modified
  1713. * size and raise the CSP_FLAG_MODIFIED flag.
  1714. *
  1715. * Parameters :
  1716. * 1 : csp = Current client state (buffers, headers, etc...)
  1717. *
  1718. * Returns : a pointer to the (newly allocated) modified buffer.
  1719. * or NULL in case something went wrong.
  1720. *
  1721. *********************************************************************/
  1722. #ifdef FUZZ
  1723. char *gif_deanimate_response(struct client_state *csp)
  1724. #else
  1725. static char *gif_deanimate_response(struct client_state *csp)
  1726. #endif
  1727. {
  1728. struct binbuffer *in, *out;
  1729. char *p;
  1730. size_t size;
  1731. size = (size_t)(csp->iob->eod - csp->iob->cur);
  1732. in = zalloc_or_die(sizeof(*in));
  1733. out = zalloc_or_die(sizeof(*out));
  1734. in->buffer = csp->iob->cur;
  1735. in->size = size;
  1736. if (gif_deanimate(in, out, strncmp("last", csp->action->string[ACTION_STRING_DEANIMATE], 4)))
  1737. {
  1738. log_error(LOG_LEVEL_DEANIMATE, "failed! (gif parsing)");
  1739. freez(in);
  1740. buf_free(out);
  1741. return(NULL);
  1742. }
  1743. else
  1744. {
  1745. if ((int)size == out->offset)
  1746. {
  1747. log_error(LOG_LEVEL_DEANIMATE, "GIF not changed.");
  1748. }
  1749. else
  1750. {
  1751. log_error(LOG_LEVEL_DEANIMATE,
  1752. "Success! GIF shrunk from %lu bytes to %lu.", size, out->offset);
  1753. }
  1754. csp->content_length = out->offset;
  1755. csp->flags |= CSP_FLAG_MODIFIED;
  1756. p = out->buffer;
  1757. freez(in);
  1758. freez(out);
  1759. return(p);
  1760. }
  1761. }
  1762. /*********************************************************************
  1763. *
  1764. * Function : get_filter_function
  1765. *
  1766. * Description : Decides which content filter function has
  1767. * to be applied (if any). Only considers functions
  1768. * for internal filters which are mutually-exclusive.
  1769. *
  1770. * Parameters :
  1771. * 1 : csp = Current client state (buffers, headers, etc...)
  1772. *
  1773. * Returns : The content filter function to run, or
  1774. * NULL if no content filter is active
  1775. *
  1776. *********************************************************************/
  1777. static filter_function_ptr get_filter_function(const struct client_state *csp)
  1778. {
  1779. filter_function_ptr filter_function = NULL;
  1780. /*
  1781. * Choose the applying filter function based on
  1782. * the content type and action settings.
  1783. */
  1784. if ((csp->content_type & CT_TEXT) &&
  1785. (!list_is_empty(csp->action->multi[ACTION_MULTI_FILTER])))
  1786. {
  1787. filter_function = pcrs_filter_response;
  1788. }
  1789. else if ((csp->content_type & CT_GIF) &&
  1790. (csp->action->flags & ACTION_DEANIMATE))
  1791. {
  1792. filter_function = gif_deanimate_response;
  1793. }
  1794. return filter_function;
  1795. }
  1796. /*********************************************************************
  1797. *
  1798. * Function : remove_chunked_transfer_coding
  1799. *
  1800. * Description : In-situ remove the "chunked" transfer coding as defined
  1801. * in RFC 7230 4.1 from a buffer. XXX: The implementation
  1802. * is neither complete nor compliant (TODO #129).
  1803. *
  1804. * Parameters :
  1805. * 1 : buffer = Pointer to the text buffer
  1806. * 2 : size = In: Number of bytes to be processed,
  1807. * Out: Number of bytes after de-chunking.
  1808. * (undefined in case of errors)
  1809. *
  1810. * Returns : JB_ERR_OK for success,
  1811. * JB_ERR_PARSE otherwise
  1812. *
  1813. *********************************************************************/
  1814. #ifdef FUZZ
  1815. extern jb_err remove_chunked_transfer_coding(char *buffer, size_t *size)
  1816. #else
  1817. static jb_err remove_chunked_transfer_coding(char *buffer, size_t *size)
  1818. #endif
  1819. {
  1820. size_t newsize = 0;
  1821. unsigned int chunksize = 0;
  1822. char *from_p, *to_p;
  1823. const char *end_of_buffer = buffer + *size;
  1824. if (*size == 0)
  1825. {
  1826. log_error(LOG_LEVEL_FATAL, "Invalid chunked input. Buffer is empty.");
  1827. return JB_ERR_PARSE;
  1828. }
  1829. assert(buffer);
  1830. from_p = to_p = buffer;
  1831. if (sscanf(buffer, "%x", &chunksize) != 1)
  1832. {
  1833. log_error(LOG_LEVEL_ERROR, "Invalid first chunksize while stripping \"chunked\" transfer coding");
  1834. return JB_ERR_PARSE;
  1835. }
  1836. while (chunksize > 0U)
  1837. {
  1838. /*
  1839. * If the chunk-size is valid, we should have at least
  1840. * chunk-size bytes of chunk-data and five bytes of
  1841. * meta data (chunk-size, CRLF, CRLF) left in the buffer.
  1842. */
  1843. if (chunksize + 5 >= *size - newsize)
  1844. {
  1845. log_error(LOG_LEVEL_ERROR,
  1846. "Chunk size %u exceeds buffered data left. "
  1847. "Already digested %lu of %lu buffered bytes.",
  1848. chunksize, newsize, *size);
  1849. return JB_ERR_PARSE;
  1850. }
  1851. /*
  1852. * Skip the chunk-size, the optional chunk-ext and the CRLF
  1853. * that is supposed to be located directly before the start
  1854. * of chunk-data.
  1855. */
  1856. if (NULL == (from_p = strstr(from_p, "\r\n")))
  1857. {
  1858. log_error(LOG_LEVEL_ERROR, "Parse error while stripping \"chunked\" transfer coding");
  1859. return JB_ERR_PARSE;
  1860. }
  1861. from_p += 2;
  1862. /*
  1863. * The previous strstr() does not enforce chunk-validity
  1864. * and is sattisfied as long a CRLF is left in the buffer.
  1865. *
  1866. * Make sure the bytes we consider chunk-data are within
  1867. * the valid range.
  1868. */
  1869. if (from_p + chunksize >= end_of_buffer)
  1870. {
  1871. log_error(LOG_LEVEL_ERROR,
  1872. "End of chunk is beyond the end of the buffer.");
  1873. return JB_ERR_PARSE;
  1874. }
  1875. memmove(to_p, from_p, (size_t) chunksize);
  1876. newsize += chunksize;
  1877. to_p = buffer + newsize;
  1878. from_p += chunksize;
  1879. /*
  1880. * Not merging this check with the previous one allows us
  1881. * to keep chunks without trailing CRLF. It's not clear
  1882. * if we actually have to care about those, though.
  1883. */
  1884. if (from_p + 2 >= end_of_buffer)
  1885. {
  1886. log_error(LOG_LEVEL_ERROR, "Not enough room for trailing CRLF.");
  1887. return JB_ERR_PARSE;
  1888. }
  1889. from_p += 2;
  1890. if (sscanf(from_p, "%x", &chunksize) != 1)
  1891. {
  1892. log_error(LOG_LEVEL_INFO, "Invalid \"chunked\" transfer encoding detected and ignored.");
  1893. break;
  1894. }
  1895. }
  1896. /* XXX: Should get its own loglevel. */
  1897. log_error(LOG_LEVEL_RE_FILTER,
  1898. "De-chunking successful. Shrunk from %lu to %lu", *size, newsize);
  1899. *size = newsize;
  1900. return JB_ERR_OK;
  1901. }
  1902. /*********************************************************************
  1903. *
  1904. * Function : prepare_for_filtering
  1905. *
  1906. * Description : If necessary, de-chunks and decompresses
  1907. * the content so it can get filterd.
  1908. *
  1909. * Parameters :
  1910. * 1 : csp = Current client state (buffers, headers, etc...)
  1911. *
  1912. * Returns : JB_ERR_OK for success,
  1913. * JB_ERR_PARSE otherwise
  1914. *
  1915. *********************************************************************/
  1916. static jb_err prepare_for_filtering(struct client_state *csp)
  1917. {
  1918. jb_err err = JB_ERR_OK;
  1919. /*
  1920. * If the body has a "chunked" transfer-encoding,
  1921. * get rid of it, adjusting size and iob->eod
  1922. */
  1923. if (csp->flags & CSP_FLAG_CHUNKED)
  1924. {
  1925. size_t size = (size_t)(csp->iob->eod - csp->iob->cur);
  1926. log_error(LOG_LEVEL_RE_FILTER, "Need to de-chunk first");
  1927. err = remove_chunked_transfer_coding(csp->iob->cur, &size);
  1928. if (JB_ERR_OK == err)
  1929. {
  1930. csp->iob->eod = csp->iob->cur + size;
  1931. csp->flags |= CSP_FLAG_MODIFIED;
  1932. }
  1933. else
  1934. {
  1935. return JB_ERR_PARSE;
  1936. }
  1937. }
  1938. #ifdef FEATURE_ZLIB
  1939. /*
  1940. * If the body has a supported transfer-encoding,
  1941. * decompress it, adjusting size and iob->eod.
  1942. */
  1943. if ((csp->content_type & (CT_GZIP|CT_DEFLATE))
  1944. #ifdef FEATURE_BROTLI
  1945. || (csp->content_type & CT_BROTLI)
  1946. #endif
  1947. )
  1948. {
  1949. if (0 == csp->iob->eod - csp->iob->cur)
  1950. {
  1951. /* Nothing left after de-chunking. */
  1952. return JB_ERR_OK;
  1953. }
  1954. err = decompress_iob(csp);
  1955. if (JB_ERR_OK == err)
  1956. {
  1957. csp->flags |= CSP_FLAG_MODIFIED;
  1958. csp->content_type &= ~CT_TABOO;
  1959. }
  1960. else
  1961. {
  1962. /*
  1963. * Unset content types to remember not to
  1964. * modify the Content-Encoding header later.
  1965. */
  1966. csp->content_type &= ~CT_GZIP;
  1967. csp->content_type &= ~CT_DEFLATE;
  1968. #ifdef FEATURE_BROTLI
  1969. csp->content_type &= ~CT_BROTLI;
  1970. #endif
  1971. }
  1972. }
  1973. #endif
  1974. return err;
  1975. }
  1976. /*********************************************************************
  1977. *
  1978. * Function : execute_content_filters
  1979. *
  1980. * Description : Executes a given content filter.
  1981. *
  1982. * Parameters :
  1983. * 1 : csp = Current client state (buffers, headers, etc...)
  1984. *
  1985. * Returns : Pointer to the modified buffer, or
  1986. * NULL if filtering failed or wasn't necessary.
  1987. *
  1988. *********************************************************************/
  1989. char *execute_content_filters(struct client_state *csp)
  1990. {
  1991. char *content;
  1992. filter_function_ptr content_filter;
  1993. assert(content_filters_enabled(csp->action));
  1994. if (0 == csp->iob->eod - csp->iob->cur)
  1995. {
  1996. /*
  1997. * No content (probably status code 301, 302 ...),
  1998. * no filtering necessary.
  1999. */
  2000. return NULL;
  2001. }
  2002. if (JB_ERR_OK != prepare_for_filtering(csp))
  2003. {
  2004. /*
  2005. * failed to de-chunk or decompress.
  2006. */
  2007. return NULL;
  2008. }
  2009. if (0 == csp->iob->eod - csp->iob->cur)
  2010. {
  2011. /*
  2012. * Clown alarm: chunked and/or compressed nothing delivered.
  2013. */
  2014. return NULL;
  2015. }
  2016. content_filter = get_filter_function(csp);
  2017. content = (content_filter != NULL) ? (*content_filter)(csp) : NULL;
  2018. #ifdef FEATURE_EXTERNAL_FILTERS
  2019. if ((csp->content_type & CT_TEXT) &&
  2020. !list_is_empty(csp->action->multi[ACTION_MULTI_EXTERNAL_FILTER]))
  2021. {
  2022. struct list_entry *filtername;
  2023. size_t size = (size_t)csp->content_length;
  2024. if (content == NULL)
  2025. {
  2026. content = csp->iob->cur;
  2027. size = (size_t)(csp->iob->eod - csp->iob->cur);
  2028. }
  2029. for (filtername = csp->action->multi[ACTION_MULTI_EXTERNAL_FILTER]->first;
  2030. filtername ; filtername = filtername->next)
  2031. {
  2032. char *result = execute_external_filter(csp, filtername->str, content, &size);
  2033. if (result != NULL)
  2034. {
  2035. if (content != csp->iob->cur)
  2036. {
  2037. free(content);
  2038. }
  2039. content = result;
  2040. }
  2041. }
  2042. csp->flags |= CSP_FLAG_MODIFIED;
  2043. csp->content_length = size;
  2044. }
  2045. #endif /* def FEATURE_EXTERNAL_FILTERS */
  2046. return content;
  2047. }
  2048. /*********************************************************************
  2049. *
  2050. * Function : get_url_actions
  2051. *
  2052. * Description : Gets the actions for this URL.
  2053. *
  2054. * Parameters :
  2055. * 1 : csp = Current client state (buffers, headers, etc...)
  2056. * 2 : http = http_request request for blocked URLs
  2057. *
  2058. * Returns : N/A
  2059. *
  2060. *********************************************************************/
  2061. void get_url_actions(struct client_state *csp, struct http_request *http)
  2062. {
  2063. struct file_list *fl;
  2064. struct url_actions *b;
  2065. int i;
  2066. init_current_action(csp->action);
  2067. for (i = 0; i < MAX_AF_FILES; i++)
  2068. {
  2069. if (((fl = csp->actions_list[i]) == NULL) || ((b = fl->f) == NULL))
  2070. {
  2071. return;
  2072. }
  2073. #ifdef FEATURE_CLIENT_TAGS
  2074. apply_url_actions(csp->action, http, csp->client_tags, b);
  2075. #else
  2076. apply_url_actions(csp->action, http, b);
  2077. #endif
  2078. }
  2079. return;
  2080. }
  2081. /*********************************************************************
  2082. *
  2083. * Function : apply_url_actions
  2084. *
  2085. * Description : Applies a list of URL actions.
  2086. *
  2087. * Parameters :
  2088. * 1 : action = Destination.
  2089. * 2 : http = Current URL
  2090. * 3 : client_tags = list of client tags
  2091. * 4 : b = list of URL actions to apply
  2092. *
  2093. * Returns : N/A
  2094. *
  2095. *********************************************************************/
  2096. static void apply_url_actions(struct current_action_spec *action,
  2097. struct http_request *http,
  2098. #ifdef FEATURE_CLIENT_TAGS
  2099. const struct list *client_tags,
  2100. #endif
  2101. struct url_actions *b)
  2102. {
  2103. if (b == NULL)
  2104. {
  2105. /* Should never happen */
  2106. return;
  2107. }
  2108. for (b = b->next; NULL != b; b = b->next)
  2109. {
  2110. if (url_match(b->url, http))
  2111. {
  2112. merge_current_action(action, b->action);
  2113. }
  2114. #ifdef FEATURE_CLIENT_TAGS
  2115. if (client_tag_match(b->url, client_tags))
  2116. {
  2117. merge_current_action(action, b->action);
  2118. }
  2119. #endif
  2120. }
  2121. }
  2122. /*********************************************************************
  2123. *
  2124. * Function : get_forward_override_settings
  2125. *
  2126. * Description : Returns forward settings as specified with the
  2127. * forward-override{} action. forward-override accepts
  2128. * forward lines similar to the one used in the
  2129. * configuration file, but without the URL pattern.
  2130. *
  2131. * For example:
  2132. *
  2133. * forward / .
  2134. *
  2135. * in the configuration file can be replaced with
  2136. * the action section:
  2137. *
  2138. * {+forward-override{forward .}}
  2139. * /
  2140. *
  2141. * Parameters :
  2142. * 1 : csp = Current client state (buffers, headers, etc...)
  2143. *
  2144. * Returns : Pointer to forwarding structure in case of success.
  2145. * Invalid syntax is fatal.
  2146. *
  2147. *********************************************************************/
  2148. static const struct forward_spec *get_forward_override_settings(struct client_state *csp)
  2149. {
  2150. const char *forward_override_line = csp->action->string[ACTION_STRING_FORWARD_OVERRIDE];
  2151. char forward_settings[BUFFER_SIZE];
  2152. char *http_parent = NULL;
  2153. /* variable names were chosen for consistency reasons. */
  2154. struct forward_spec *fwd = NULL;
  2155. int vec_count;
  2156. char *vec[3];
  2157. assert(csp->action->flags & ACTION_FORWARD_OVERRIDE);
  2158. /* Should be enforced by load_one_actions_file() */
  2159. assert(strlen(forward_override_line) < sizeof(forward_settings) - 1);
  2160. /* Create a copy ssplit can modify */
  2161. strlcpy(forward_settings, forward_override_line, sizeof(forward_settings));
  2162. if (NULL != csp->fwd)
  2163. {
  2164. /*
  2165. * XXX: Currently necessary to prevent memory
  2166. * leaks when the show-url-info cgi page is visited.
  2167. */
  2168. unload_forward_spec(csp->fwd);
  2169. }
  2170. /*
  2171. * allocate a new forward node, valid only for
  2172. * the lifetime of this request. Save its location
  2173. * in csp as well, so sweep() can free it later on.
  2174. */
  2175. fwd = csp->fwd = zalloc_or_die(sizeof(*fwd));
  2176. vec_count = ssplit(forward_settings, " \t", vec, SZ(vec));
  2177. if ((vec_count == 2) && !strcasecmp(vec[0], "forward"))
  2178. {
  2179. fwd->type = SOCKS_NONE;
  2180. /* Parse the parent HTTP proxy host:port */
  2181. http_parent = vec[1];
  2182. }
  2183. else if ((vec_count == 2) && !strcasecmp(vec[0], "forward-webserver"))
  2184. {
  2185. fwd->type = FORWARD_WEBSERVER;
  2186. /* Parse the parent HTTP server host:port */
  2187. http_parent = vec[1];
  2188. }
  2189. else if (vec_count == 3)
  2190. {
  2191. char *socks_proxy = NULL;
  2192. if (!strcasecmp(vec[0], "forward-socks4"))
  2193. {
  2194. fwd->type = SOCKS_4;
  2195. socks_proxy = vec[1];
  2196. }
  2197. else if (!strcasecmp(vec[0], "forward-socks4a"))
  2198. {
  2199. fwd->type = SOCKS_4A;
  2200. socks_proxy = vec[1];
  2201. }
  2202. else if (!strcasecmp(vec[0], "forward-socks5"))
  2203. {
  2204. fwd->type = SOCKS_5;
  2205. socks_proxy = vec[1];
  2206. }
  2207. else if (!strcasecmp(vec[0], "forward-socks5t"))
  2208. {
  2209. fwd->type = SOCKS_5T;
  2210. socks_proxy = vec[1];
  2211. }
  2212. if (NULL != socks_proxy)
  2213. {
  2214. /* Parse the SOCKS proxy [user:pass@]host[:port] */
  2215. fwd->gateway_port = 1080;
  2216. parse_forwarder_address(socks_proxy,
  2217. &fwd->gateway_host, &fwd->gateway_port,
  2218. &fwd->auth_username, &fwd->auth_password);
  2219. http_parent = vec[2];
  2220. }
  2221. }
  2222. if (NULL == http_parent)
  2223. {
  2224. log_error(LOG_LEVEL_FATAL,
  2225. "Invalid forward-override syntax in: %s", forward_override_line);
  2226. /* Never get here - LOG_LEVEL_FATAL causes program exit */
  2227. }
  2228. /* Parse http forwarding settings */
  2229. if (strcmp(http_parent, ".") != 0)
  2230. {
  2231. fwd->forward_port = 8000;
  2232. parse_forwarder_address(http_parent,
  2233. &fwd->forward_host, &fwd->forward_port,
  2234. NULL, NULL);
  2235. }
  2236. assert (NULL != fwd);
  2237. log_error(LOG_LEVEL_CONNECT,
  2238. "Overriding forwarding settings based on \'%s\'", forward_override_line);
  2239. return fwd;
  2240. }
  2241. /*********************************************************************
  2242. *
  2243. * Function : forward_url
  2244. *
  2245. * Description : Should we forward this to another proxy?
  2246. *
  2247. * Parameters :
  2248. * 1 : csp = Current client state (buffers, headers, etc...)
  2249. * 2 : http = http_request request for current URL
  2250. *
  2251. * Returns : Pointer to forwarding information.
  2252. *
  2253. *********************************************************************/
  2254. const struct forward_spec *forward_url(struct client_state *csp,
  2255. const struct http_request *http)
  2256. {
  2257. static const struct forward_spec fwd_default[1]; /* Zero'ed due to being static. */
  2258. struct forward_spec *fwd = csp->config->forward;
  2259. if (csp->action->flags & ACTION_FORWARD_OVERRIDE)
  2260. {
  2261. return get_forward_override_settings(csp);
  2262. }
  2263. if (fwd == NULL)
  2264. {
  2265. return fwd_default;
  2266. }
  2267. while (fwd != NULL)
  2268. {
  2269. if (url_match(fwd->url, http))
  2270. {
  2271. return fwd;
  2272. }
  2273. fwd = fwd->next;
  2274. }
  2275. return fwd_default;
  2276. }
  2277. /*********************************************************************
  2278. *
  2279. * Function : direct_response
  2280. *
  2281. * Description : Check if Max-Forwards == 0 for an OPTIONS or TRACE
  2282. * request and if so, return a HTTP 501 to the client.
  2283. *
  2284. * FIXME: I have a stupid name and I should handle the
  2285. * requests properly. Still, what we do here is rfc-
  2286. * compliant, whereas ignoring or forwarding are not.
  2287. *
  2288. * Parameters :
  2289. * 1 : csp = Current client state (buffers, headers, etc...)
  2290. *
  2291. * Returns : http_response if , NULL if nonmatch or handler fail
  2292. *
  2293. *********************************************************************/
  2294. struct http_response *direct_response(struct client_state *csp)
  2295. {
  2296. struct http_response *rsp;
  2297. struct list_entry *p;
  2298. if ((0 == strcmpic(csp->http->gpc, "trace"))
  2299. || (0 == strcmpic(csp->http->gpc, "options")))
  2300. {
  2301. for (p = csp->headers->first; (p != NULL) ; p = p->next)
  2302. {
  2303. if (!strncmpic(p->str, "Max-Forwards:", 13))
  2304. {
  2305. unsigned int max_forwards;
  2306. /*
  2307. * If it's a Max-Forwards value of zero,
  2308. * we have to intercept the request.
  2309. */
  2310. if (1 == sscanf(p->str+12, ": %u", &max_forwards) && max_forwards == 0)
  2311. {
  2312. /*
  2313. * FIXME: We could handle at least TRACE here,
  2314. * but that would require a verbatim copy of
  2315. * the request which we don't have anymore
  2316. */
  2317. log_error(LOG_LEVEL_HEADER,
  2318. "Detected header \'%s\' in OPTIONS or TRACE request. Returning 501.",
  2319. p->str);
  2320. /* Get mem for response or fail*/
  2321. if (NULL == (rsp = alloc_http_response()))
  2322. {
  2323. return cgi_error_memory();
  2324. }
  2325. rsp->status = strdup_or_die("501 Not Implemented");
  2326. rsp->is_static = 1;
  2327. rsp->crunch_reason = UNSUPPORTED;
  2328. return(finish_http_response(csp, rsp));
  2329. }
  2330. }
  2331. }
  2332. }
  2333. return NULL;
  2334. }
  2335. /*********************************************************************
  2336. *
  2337. * Function : content_requires_filtering
  2338. *
  2339. * Description : Checks whether there are any content filters
  2340. * enabled for the current request and if they
  2341. * can actually be applied..
  2342. *
  2343. * Parameters :
  2344. * 1 : csp = Current client state (buffers, headers, etc...)
  2345. *
  2346. * Returns : TRUE for yes, FALSE otherwise
  2347. *
  2348. *********************************************************************/
  2349. int content_requires_filtering(struct client_state *csp)
  2350. {
  2351. if ((csp->content_type & CT_TABOO)
  2352. && !(csp->action->flags & ACTION_FORCE_TEXT_MODE))
  2353. {
  2354. return FALSE;
  2355. }
  2356. /*
  2357. * Are we enabling text mode by force?
  2358. */
  2359. if (csp->action->flags & ACTION_FORCE_TEXT_MODE)
  2360. {
  2361. /*
  2362. * Do we really have to?
  2363. */
  2364. if (csp->content_type & CT_TEXT)
  2365. {
  2366. log_error(LOG_LEVEL_HEADER, "Text mode is already enabled.");
  2367. }
  2368. else
  2369. {
  2370. csp->content_type |= CT_TEXT;
  2371. log_error(LOG_LEVEL_HEADER, "Text mode enabled by force. Take cover!");
  2372. }
  2373. }
  2374. if (!(csp->content_type & CT_DECLARED))
  2375. {
  2376. /*
  2377. * The server didn't bother to declare a MIME-Type.
  2378. * Assume it's text that can be filtered.
  2379. *
  2380. * This also regularly happens with 304 responses,
  2381. * therefore logging anything here would cause
  2382. * too much noise.
  2383. */
  2384. csp->content_type |= CT_TEXT;
  2385. }
  2386. /*
  2387. * Choose the applying filter function based on
  2388. * the content type and action settings.
  2389. */
  2390. if ((csp->content_type & CT_TEXT) &&
  2391. (!list_is_empty(csp->action->multi[ACTION_MULTI_FILTER]) ||
  2392. !list_is_empty(csp->action->multi[ACTION_MULTI_EXTERNAL_FILTER])))
  2393. {
  2394. return TRUE;
  2395. }
  2396. else if ((csp->content_type & CT_GIF) &&
  2397. (csp->action->flags & ACTION_DEANIMATE))
  2398. {
  2399. return TRUE;
  2400. }
  2401. return FALSE;
  2402. }
  2403. /*********************************************************************
  2404. *
  2405. * Function : content_filters_enabled
  2406. *
  2407. * Description : Checks whether there are any content filters
  2408. * enabled for the current request.
  2409. *
  2410. * Parameters :
  2411. * 1 : action = Action spec to check.
  2412. *
  2413. * Returns : TRUE for yes, FALSE otherwise
  2414. *
  2415. *********************************************************************/
  2416. int content_filters_enabled(const struct current_action_spec *action)
  2417. {
  2418. return ((action->flags & ACTION_DEANIMATE) ||
  2419. !list_is_empty(action->multi[ACTION_MULTI_FILTER]) ||
  2420. !list_is_empty(action->multi[ACTION_MULTI_EXTERNAL_FILTER]));
  2421. }
  2422. /*********************************************************************
  2423. *
  2424. * Function : filters_available
  2425. *
  2426. * Description : Checks whether there are any filters available.
  2427. *
  2428. * Parameters :
  2429. * 1 : csp = Current client state (buffers, headers, etc...)
  2430. *
  2431. * Returns : TRUE for yes, FALSE otherwise.
  2432. *
  2433. *********************************************************************/
  2434. int filters_available(const struct client_state *csp)
  2435. {
  2436. int i;
  2437. for (i = 0; i < MAX_AF_FILES; i++)
  2438. {
  2439. const struct file_list *fl = csp->rlist[i];
  2440. if ((NULL != fl) && (NULL != fl->f))
  2441. {
  2442. return TRUE;
  2443. }
  2444. }
  2445. return FALSE;
  2446. }
  2447. #ifdef FEATURE_EXTENDED_STATISTICS
  2448. struct filter_statistics_entry
  2449. {
  2450. char *filter;
  2451. unsigned long long executions;
  2452. unsigned long long response_bodies_modified;
  2453. unsigned long long hits;
  2454. struct filter_statistics_entry *next;
  2455. };
  2456. static struct filter_statistics_entry *filter_statistics = NULL;
  2457. /*********************************************************************
  2458. *
  2459. * Function : register_filter_for_statistics
  2460. *
  2461. * Description : Registers a filter so we can gather statistics for
  2462. * it unless the filter has already been registered
  2463. * before.
  2464. *
  2465. * Parameters :
  2466. * 1 : filter = Name of the filter to register
  2467. *
  2468. * Returns : void
  2469. *
  2470. *********************************************************************/
  2471. void register_filter_for_statistics(const char *filter)
  2472. {
  2473. struct filter_statistics_entry *entry;
  2474. privoxy_mutex_lock(&filter_statistics_mutex);
  2475. if (filter_statistics == NULL)
  2476. {
  2477. filter_statistics = zalloc_or_die(sizeof(struct filter_statistics_entry));
  2478. entry = filter_statistics;
  2479. entry->filter = strdup_or_die(filter);
  2480. privoxy_mutex_unlock(&filter_statistics_mutex);
  2481. return;
  2482. }
  2483. entry = filter_statistics;
  2484. while (entry != NULL)
  2485. {
  2486. if (!strcmp(entry->filter, filter))
  2487. {
  2488. /* Already registered, nothing to do. */
  2489. break;
  2490. }
  2491. if (entry->next == NULL)
  2492. {
  2493. entry->next = zalloc_or_die(sizeof(struct filter_statistics_entry));
  2494. entry->next->filter = strdup_or_die(filter);
  2495. break;
  2496. }
  2497. entry = entry->next;
  2498. }
  2499. privoxy_mutex_unlock(&filter_statistics_mutex);
  2500. }
  2501. /*********************************************************************
  2502. *
  2503. * Function : update_filter_statistics
  2504. *
  2505. * Description : Updates the statistics for a filter.
  2506. *
  2507. * Parameters :
  2508. * 1 : filter = Name of the filter to update
  2509. * 2 : hits = Hit count.
  2510. *
  2511. * Returns : void
  2512. *
  2513. *********************************************************************/
  2514. void update_filter_statistics(const char *filter, int hits)
  2515. {
  2516. struct filter_statistics_entry *entry;
  2517. privoxy_mutex_lock(&filter_statistics_mutex);
  2518. entry = filter_statistics;
  2519. while (entry != NULL)
  2520. {
  2521. if (!strcmp(entry->filter, filter))
  2522. {
  2523. entry->executions++;
  2524. if (hits != 0)
  2525. {
  2526. entry->response_bodies_modified++;
  2527. entry->hits += (unsigned)hits;
  2528. }
  2529. break;
  2530. }
  2531. entry = entry->next;
  2532. }
  2533. privoxy_mutex_unlock(&filter_statistics_mutex);
  2534. }
  2535. /*********************************************************************
  2536. *
  2537. * Function : get_filter_statistics
  2538. *
  2539. * Description : Gets the statistics for a filter.
  2540. *
  2541. * Parameters :
  2542. * 1 : filter = Name of the filter to get statistics for.
  2543. * 2 : executions = Storage for the execution count.
  2544. * 3 : response_bodies_modified = Storage for the number
  2545. * of modified response bodies.
  2546. * 4 : hits = Storage for the number of hits.
  2547. *
  2548. * Returns : void
  2549. *
  2550. *********************************************************************/
  2551. void get_filter_statistics(const char *filter, unsigned long long *executions,
  2552. unsigned long long *response_bodies_modified,
  2553. unsigned long long *hits)
  2554. {
  2555. struct filter_statistics_entry *entry;
  2556. privoxy_mutex_lock(&filter_statistics_mutex);
  2557. entry = filter_statistics;
  2558. while (entry != NULL)
  2559. {
  2560. if (!strcmp(entry->filter, filter))
  2561. {
  2562. *executions = entry->executions;
  2563. *response_bodies_modified = entry->response_bodies_modified;
  2564. *hits = entry->hits;
  2565. break;
  2566. }
  2567. entry = entry->next;
  2568. }
  2569. privoxy_mutex_unlock(&filter_statistics_mutex);
  2570. }
  2571. struct block_statistics_entry
  2572. {
  2573. char *block_reason;
  2574. unsigned long long count;
  2575. struct block_statistics_entry *next;
  2576. };
  2577. static struct block_statistics_entry *block_statistics = NULL;
  2578. /*********************************************************************
  2579. *
  2580. * Function : register_block_reason_for_statistics
  2581. *
  2582. * Description : Registers a block reason so we can gather statistics
  2583. * for it unless the block reason has already been
  2584. * registered before.
  2585. *
  2586. * Parameters :
  2587. * 1 : block_reason = Block reason to register
  2588. *
  2589. * Returns : void
  2590. *
  2591. *********************************************************************/
  2592. void register_block_reason_for_statistics(const char *block_reason)
  2593. {
  2594. struct block_statistics_entry *entry;
  2595. privoxy_mutex_lock(&block_statistics_mutex);
  2596. if (block_statistics == NULL)
  2597. {
  2598. block_statistics = zalloc_or_die(sizeof(struct block_statistics_entry));
  2599. entry = block_statistics;
  2600. entry->block_reason = strdup_or_die(block_reason);
  2601. privoxy_mutex_unlock(&block_statistics_mutex);
  2602. return;
  2603. }
  2604. entry = block_statistics;
  2605. while (entry != NULL)
  2606. {
  2607. if (!strcmp(entry->block_reason, block_reason))
  2608. {
  2609. /* Already registered, nothing to do. */
  2610. break;
  2611. }
  2612. if (entry->next == NULL)
  2613. {
  2614. entry->next = zalloc_or_die(sizeof(struct block_statistics_entry));
  2615. entry->next->block_reason = strdup_or_die(block_reason);
  2616. break;
  2617. }
  2618. entry = entry->next;
  2619. }
  2620. privoxy_mutex_unlock(&block_statistics_mutex);
  2621. }
  2622. /*********************************************************************
  2623. *
  2624. * Function : increment_block_reason_counter
  2625. *
  2626. * Description : Updates the counter for a block reason.
  2627. *
  2628. * Parameters :
  2629. * 1 : block_reason = Block reason to count
  2630. *
  2631. * Returns : void
  2632. *
  2633. *********************************************************************/
  2634. static void increment_block_reason_counter(const char *block_reason)
  2635. {
  2636. struct block_statistics_entry *entry;
  2637. privoxy_mutex_lock(&block_statistics_mutex);
  2638. entry = block_statistics;
  2639. while (entry != NULL)
  2640. {
  2641. if (!strcmp(entry->block_reason, block_reason))
  2642. {
  2643. entry->count++;
  2644. break;
  2645. }
  2646. entry = entry->next;
  2647. }
  2648. privoxy_mutex_unlock(&block_statistics_mutex);
  2649. }
  2650. /*********************************************************************
  2651. *
  2652. * Function : get_block_reason_count
  2653. *
  2654. * Description : Gets number of times a block reason was used.
  2655. *
  2656. * Parameters :
  2657. * 1 : block_reason = Block reason to get statistics for.
  2658. * 2 : count = Storage for the number of times the block
  2659. * reason was used.
  2660. *
  2661. * Returns : void
  2662. *
  2663. *********************************************************************/
  2664. void get_block_reason_count(const char *block_reason, unsigned long long *count)
  2665. {
  2666. struct block_statistics_entry *entry;
  2667. privoxy_mutex_lock(&block_statistics_mutex);
  2668. entry = block_statistics;
  2669. while (entry != NULL)
  2670. {
  2671. if (!strcmp(entry->block_reason, block_reason))
  2672. {
  2673. *count = entry->count;
  2674. break;
  2675. }
  2676. entry = entry->next;
  2677. }
  2678. privoxy_mutex_unlock(&block_statistics_mutex);
  2679. }
  2680. #endif /* def FEATURE_EXTENDED_STATISTICS */
  2681. /*
  2682. Local Variables:
  2683. tab-width: 3
  2684. end:
  2685. */