parsers.c 152 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933
  1. /*********************************************************************
  2. *
  3. * File : $Source: /cvsroot/ijbswa/current/parsers.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. #ifndef _WIN32
  35. #include <stdio.h>
  36. #include <sys/types.h>
  37. #endif
  38. #include <stdlib.h>
  39. #include <ctype.h>
  40. #include <assert.h>
  41. #include <string.h>
  42. #ifdef __GLIBC__
  43. /*
  44. * Convince GNU's libc to provide a strptime prototype.
  45. */
  46. #define __USE_XOPEN
  47. #endif /*__GLIBC__ */
  48. #include <time.h>
  49. #ifdef FEATURE_ZLIB
  50. #include <zlib.h>
  51. #define GZIP_IDENTIFIER_1 0x1f
  52. #define GZIP_IDENTIFIER_2 0x8b
  53. #define GZIP_FLAG_CHECKSUM 0x02
  54. #define GZIP_FLAG_EXTRA_FIELDS 0x04
  55. #define GZIP_FLAG_FILE_NAME 0x08
  56. #define GZIP_FLAG_COMMENT 0x10
  57. #define GZIP_FLAG_RESERVED_BITS 0xe0
  58. #endif
  59. #ifdef FEATURE_BROTLI
  60. #include <brotli/decode.h>
  61. #endif
  62. #if !defined(_WIN32)
  63. #include <unistd.h>
  64. #endif
  65. #include "project.h"
  66. #ifdef FEATURE_PTHREAD
  67. #include "jcc.h"
  68. /* jcc.h is for mutex semapores only */
  69. #endif /* def FEATURE_PTHREAD */
  70. #include "list.h"
  71. #include "parsers.h"
  72. #include "ssplit.h"
  73. #include "errlog.h"
  74. #include "jbsockets.h"
  75. #include "miscutil.h"
  76. #include "list.h"
  77. #include "actions.h"
  78. #include "filters.h"
  79. #ifdef FEATURE_HTTPS_INSPECTION
  80. #include "ssl.h"
  81. #endif
  82. #ifndef HAVE_STRPTIME
  83. #include "strptime.h"
  84. #endif
  85. static char *get_header_line(struct iob *iob);
  86. static jb_err scan_headers(struct client_state *csp);
  87. static jb_err header_tagger(struct client_state *csp, char *header);
  88. static jb_err parse_header_time(const char *header_time, time_t *result);
  89. static jb_err parse_time_header(const char *header, time_t *result);
  90. static jb_err crumble (struct client_state *csp, char **header);
  91. static jb_err filter_header (struct client_state *csp, char **header);
  92. static jb_err client_connection (struct client_state *csp, char **header);
  93. static jb_err client_referrer (struct client_state *csp, char **header);
  94. static jb_err client_uagent (struct client_state *csp, char **header);
  95. static jb_err client_ua (struct client_state *csp, char **header);
  96. static jb_err client_from (struct client_state *csp, char **header);
  97. static jb_err client_send_cookie (struct client_state *csp, char **header);
  98. static jb_err client_x_forwarded (struct client_state *csp, char **header);
  99. static jb_err client_accept_encoding (struct client_state *csp, char **header);
  100. static jb_err client_te (struct client_state *csp, char **header);
  101. static jb_err client_max_forwards (struct client_state *csp, char **header);
  102. static jb_err client_host (struct client_state *csp, char **header);
  103. static jb_err client_if_modified_since (struct client_state *csp, char **header);
  104. static jb_err client_accept_language (struct client_state *csp, char **header);
  105. static jb_err client_if_none_match (struct client_state *csp, char **header);
  106. static jb_err crunch_client_header (struct client_state *csp, char **header);
  107. static jb_err client_x_filter (struct client_state *csp, char **header);
  108. static jb_err client_range (struct client_state *csp, char **header);
  109. static jb_err client_expect (struct client_state *csp, char **header);
  110. static jb_err server_set_cookie (struct client_state *csp, char **header);
  111. static jb_err server_connection (struct client_state *csp, char **header);
  112. static jb_err server_content_type (struct client_state *csp, char **header);
  113. static jb_err server_adjust_content_length(struct client_state *csp, char **header);
  114. static jb_err server_content_md5 (struct client_state *csp, char **header);
  115. static jb_err server_content_encoding (struct client_state *csp, char **header);
  116. static jb_err server_transfer_coding (struct client_state *csp, char **header);
  117. static jb_err server_http (struct client_state *csp, char **header);
  118. static jb_err crunch_server_header (struct client_state *csp, char **header);
  119. static jb_err server_last_modified (struct client_state *csp, char **header);
  120. static jb_err server_content_disposition(struct client_state *csp, char **header);
  121. #ifdef FEATURE_ZLIB
  122. static jb_err server_adjust_content_encoding(struct client_state *csp, char **header);
  123. #endif
  124. #ifdef FEATURE_CONNECTION_KEEP_ALIVE
  125. static jb_err server_save_content_length(struct client_state *csp, char **header);
  126. static jb_err server_keep_alive(struct client_state *csp, char **header);
  127. static jb_err server_proxy_connection(struct client_state *csp, char **header);
  128. static jb_err client_keep_alive(struct client_state *csp, char **header);
  129. static jb_err client_proxy_connection(struct client_state *csp, char **header);
  130. #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
  131. static jb_err client_save_content_length(struct client_state *csp, char **header);
  132. static jb_err client_host_adder (struct client_state *csp);
  133. static jb_err client_xtra_adder (struct client_state *csp);
  134. static jb_err client_x_forwarded_for_adder(struct client_state *csp);
  135. static jb_err client_connection_header_adder(struct client_state *csp);
  136. static jb_err server_connection_adder(struct client_state *csp);
  137. #ifdef FEATURE_CONNECTION_KEEP_ALIVE
  138. static jb_err server_proxy_connection_adder(struct client_state *csp);
  139. #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
  140. static jb_err proxy_authentication(struct client_state *csp, char **header);
  141. static jb_err create_forged_referrer(char **header, const char *hostport);
  142. static jb_err create_fake_referrer(char **header, const char *fake_referrer);
  143. static jb_err handle_conditional_hide_referrer_parameter(char **header,
  144. const char *host, const int parameter_conditional_block);
  145. static void create_content_length_header(unsigned long long content_length,
  146. char *header, size_t buffer_length);
  147. /*
  148. * List of functions to run on a list of headers.
  149. */
  150. struct parsers
  151. {
  152. /** The header prefix to match */
  153. const char *str;
  154. /** The length of the prefix to match */
  155. const size_t len;
  156. /** The function to apply to this line */
  157. const parser_func_ptr parser;
  158. };
  159. static const struct parsers client_patterns[] = {
  160. { "referer:", 8, client_referrer },
  161. { "user-agent:", 11, client_uagent },
  162. { "ua-", 3, client_ua },
  163. { "from:", 5, client_from },
  164. { "cookie:", 7, client_send_cookie },
  165. { "x-forwarded-for:", 16, client_x_forwarded },
  166. { "Accept-Encoding:", 16, client_accept_encoding },
  167. { "TE:", 3, client_te },
  168. { "Host:", 5, client_host },
  169. { "if-modified-since:", 18, client_if_modified_since },
  170. { "Content-Length:", 15, client_save_content_length },
  171. #ifdef FEATURE_CONNECTION_KEEP_ALIVE
  172. { "Keep-Alive:", 11, client_keep_alive },
  173. { "Proxy-Connection:", 17, client_proxy_connection },
  174. #else
  175. { "Keep-Alive:", 11, crumble },
  176. { "Proxy-Connection:", 17, crumble },
  177. #endif
  178. { "connection:", 11, client_connection },
  179. { "max-forwards:", 13, client_max_forwards },
  180. { "Accept-Language:", 16, client_accept_language },
  181. { "if-none-match:", 14, client_if_none_match },
  182. { "Range:", 6, client_range },
  183. { "Request-Range:", 14, client_range },
  184. { "If-Range:", 9, client_range },
  185. { "X-Filter:", 9, client_x_filter },
  186. { "Proxy-Authorization:", 20, proxy_authentication },
  187. #if 0
  188. { "Transfer-Encoding:", 18, client_transfer_encoding },
  189. #endif
  190. { "Expect:", 7, client_expect },
  191. { "*", 0, crunch_client_header },
  192. { "*", 0, filter_header },
  193. { NULL, 0, NULL }
  194. };
  195. static const struct parsers server_patterns[] = {
  196. { "HTTP/", 5, server_http },
  197. { "set-cookie:", 11, server_set_cookie },
  198. { "connection:", 11, server_connection },
  199. { "Content-Type:", 13, server_content_type },
  200. { "Content-MD5:", 12, server_content_md5 },
  201. { "Content-Encoding:", 17, server_content_encoding },
  202. #ifdef FEATURE_CONNECTION_KEEP_ALIVE
  203. { "Content-Length:", 15, server_save_content_length },
  204. { "Keep-Alive:", 11, server_keep_alive },
  205. { "Proxy-Connection:", 17, server_proxy_connection },
  206. #else
  207. { "Keep-Alive:", 11, crumble },
  208. #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
  209. { "Transfer-Encoding:", 18, server_transfer_coding },
  210. { "content-disposition:", 20, server_content_disposition },
  211. { "Last-Modified:", 14, server_last_modified },
  212. { "Proxy-Authenticate:", 19, proxy_authentication },
  213. { "*", 0, crunch_server_header },
  214. { "*", 0, filter_header },
  215. { NULL, 0, NULL }
  216. };
  217. static const add_header_func_ptr add_client_headers[] = {
  218. client_host_adder,
  219. client_x_forwarded_for_adder,
  220. client_xtra_adder,
  221. client_connection_header_adder,
  222. NULL
  223. };
  224. static const add_header_func_ptr add_server_headers[] = {
  225. server_connection_adder,
  226. #ifdef FEATURE_CONNECTION_KEEP_ALIVE
  227. server_proxy_connection_adder,
  228. #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
  229. NULL
  230. };
  231. /*********************************************************************
  232. *
  233. * Function : flush_iob
  234. *
  235. * Description : Write any pending "buffered" content.
  236. *
  237. * Parameters :
  238. * 1 : fd = file descriptor of the socket to read
  239. * 2 : iob = The I/O buffer to flush, usually csp->iob.
  240. * 3 : delay = Number of milliseconds to delay the writes
  241. *
  242. * Returns : On success, the number of bytes written are returned (zero
  243. * indicates nothing was written). On error, -1 is returned,
  244. * and errno is set appropriately. If count is zero and the
  245. * file descriptor refers to a regular file, 0 will be
  246. * returned without causing any other effect. For a special
  247. * file, the results are not portable.
  248. *
  249. *********************************************************************/
  250. long flush_iob(jb_socket fd, struct iob *iob, unsigned int delay)
  251. {
  252. long len = iob->eod - iob->cur;
  253. if (len <= 0)
  254. {
  255. return(0);
  256. }
  257. if (write_socket_delayed(fd, iob->cur, (size_t)len, delay))
  258. {
  259. return(-1);
  260. }
  261. iob->eod = iob->cur = iob->buf;
  262. return(len);
  263. }
  264. /*********************************************************************
  265. *
  266. * Function : add_to_iob
  267. *
  268. * Description : Add content to the buffer, expanding the
  269. * buffer if necessary.
  270. *
  271. * Parameters :
  272. * 1 : iob = Destination buffer.
  273. * 2 : buffer_limit = Limit to which the destination may grow
  274. * 3 : src = holds the content to be added
  275. * 4 : n = number of bytes to be added
  276. *
  277. * Returns : JB_ERR_OK on success, JB_ERR_MEMORY if out-of-memory
  278. * or buffer limit reached.
  279. *
  280. *********************************************************************/
  281. jb_err add_to_iob(struct iob *iob, const size_t buffer_limit, char *src, long n)
  282. {
  283. size_t used, offset, need;
  284. char *p;
  285. if (n <= 0) return JB_ERR_OK;
  286. used = (size_t)(iob->eod - iob->buf);
  287. offset = (size_t)(iob->cur - iob->buf);
  288. need = used + (size_t)n + 1;
  289. /*
  290. * If the buffer can't hold the new data, extend it first.
  291. * Use the next power of two if possible, else use the actual need.
  292. */
  293. if (need > buffer_limit)
  294. {
  295. log_error(LOG_LEVEL_INFO,
  296. "Buffer limit reached while extending the buffer (iob). Needed: %lu. Limit: %lu",
  297. need, buffer_limit);
  298. return JB_ERR_MEMORY;
  299. }
  300. if (need > iob->size)
  301. {
  302. size_t want = iob->size ? iob->size : 512;
  303. while (want <= need)
  304. {
  305. want *= 2;
  306. }
  307. if (want <= buffer_limit && NULL != (p = (char *)realloc(iob->buf, want)))
  308. {
  309. iob->size = want;
  310. }
  311. else if (NULL != (p = (char *)realloc(iob->buf, need)))
  312. {
  313. iob->size = need;
  314. }
  315. else
  316. {
  317. log_error(LOG_LEVEL_ERROR, "Extending the buffer (iob) failed: %E");
  318. return JB_ERR_MEMORY;
  319. }
  320. /* Update the iob pointers */
  321. iob->cur = p + offset;
  322. iob->eod = p + used;
  323. iob->buf = p;
  324. }
  325. /* copy the new data into the iob buffer */
  326. memcpy(iob->eod, src, (size_t)n);
  327. /* point to the end of the data */
  328. iob->eod += n;
  329. /* null terminate == cheap insurance */
  330. *iob->eod = '\0';
  331. return JB_ERR_OK;
  332. }
  333. /*********************************************************************
  334. *
  335. * Function : clear_iob
  336. *
  337. * Description : Frees the memory allocated for an I/O buffer and
  338. * resets the structure.
  339. *
  340. * Parameters :
  341. * 1 : iob = I/O buffer to clear.
  342. *
  343. * Returns : N/A
  344. *
  345. *********************************************************************/
  346. void clear_iob(struct iob *iob)
  347. {
  348. free(iob->buf);
  349. memset(iob, '\0', sizeof(*iob));
  350. }
  351. #ifdef FEATURE_ZLIB
  352. #ifdef FEATURE_BROTLI
  353. /*********************************************************************
  354. *
  355. * Function : decompress_iob_with_brotli
  356. *
  357. * Description : Decompress buffered page using Brotli.
  358. *
  359. * Parameters :
  360. * 1 : csp = Current client state (buffers, headers, etc...)
  361. *
  362. * Returns : JB_ERR_OK on success,
  363. * JB_ERR_MEMORY if out-of-memory limit reached, and
  364. * JB_ERR_COMPRESS if error decompressing buffer.
  365. *
  366. *********************************************************************/
  367. static jb_err decompress_iob_with_brotli(struct client_state *csp)
  368. {
  369. BrotliDecoderResult result;
  370. char *decoded_buffer;
  371. size_t decoded_size;
  372. size_t decoded_buffer_size;
  373. size_t encoded_size;
  374. enum { MAX_COMPRESSION_FACTOR = 15 };
  375. encoded_size = (size_t)(csp->iob->eod - csp->iob->cur);
  376. /*
  377. * The BrotliDecoderDecompress() api is a bit unfortunate
  378. * and requires the caller to reserve enough memory for
  379. * the decompressed content. Hopefully reserving
  380. * MAX_COMPRESSION_FACTOR times the original size is
  381. * sufficient. If not, BrotliDecoderDecompress() will fail.
  382. */
  383. decoded_buffer_size = encoded_size * MAX_COMPRESSION_FACTOR;
  384. if (decoded_buffer_size > csp->config->buffer_limit)
  385. {
  386. log_error(LOG_LEVEL_ERROR,
  387. "Buffer limit reached before decompressing iob with Brotli");
  388. return JB_ERR_MEMORY;
  389. }
  390. decoded_buffer = malloc(decoded_buffer_size);
  391. if (decoded_buffer == NULL)
  392. {
  393. log_error(LOG_LEVEL_ERROR,
  394. "Failed to allocate %lu bytes for Brotli decompression",
  395. decoded_buffer_size);
  396. return JB_ERR_MEMORY;
  397. }
  398. decoded_size = decoded_buffer_size;
  399. result = BrotliDecoderDecompress(encoded_size,
  400. (const uint8_t *)csp->iob->cur, &decoded_size,
  401. (uint8_t *)decoded_buffer);
  402. if (result == BROTLI_DECODER_RESULT_SUCCESS)
  403. {
  404. /*
  405. * Update the iob, since the decompression was successful.
  406. */
  407. freez(csp->iob->buf);
  408. csp->iob->buf = decoded_buffer;
  409. csp->iob->cur = csp->iob->buf;
  410. csp->iob->eod = csp->iob->cur + decoded_size;
  411. csp->iob->size = decoded_buffer_size;
  412. log_error(LOG_LEVEL_RE_FILTER,
  413. "Decompression successful. Old size: %lu, new size: %lu.",
  414. encoded_size, decoded_size);
  415. return JB_ERR_OK;
  416. }
  417. else
  418. {
  419. log_error(LOG_LEVEL_ERROR, "Failed to decompress buffer with Brotli");
  420. freez(decoded_buffer);
  421. return JB_ERR_COMPRESS;
  422. }
  423. }
  424. #endif
  425. /*********************************************************************
  426. *
  427. * Function : decompress_iob
  428. *
  429. * Description : Decompress buffered page, expanding the
  430. * buffer as necessary. csp->iob->cur
  431. * should point to the the beginning of the
  432. * compressed data block.
  433. *
  434. * Parameters :
  435. * 1 : csp = Current client state (buffers, headers, etc...)
  436. *
  437. * Returns : JB_ERR_OK on success,
  438. * JB_ERR_MEMORY if out-of-memory limit reached, and
  439. * JB_ERR_COMPRESS if error decompressing buffer.
  440. *
  441. *********************************************************************/
  442. jb_err decompress_iob(struct client_state *csp)
  443. {
  444. char *buf; /* new, uncompressed buffer */
  445. char *cur; /* Current iob position (to keep the original
  446. * iob->cur unmodified if we return early) */
  447. size_t bufsize; /* allocated size of the new buffer */
  448. size_t old_size; /* Content size before decompression */
  449. size_t skip_size; /* Number of bytes at the beginning of the iob
  450. that we should NOT decompress. */
  451. int status; /* return status of the inflate() call */
  452. z_stream zstr; /* used by calls to zlib */
  453. #ifdef FUZZ
  454. assert(csp->iob->cur - csp->iob->buf >= 0);
  455. assert(csp->iob->eod - csp->iob->cur >= 0);
  456. #else
  457. assert(csp->iob->cur - csp->iob->buf > 0);
  458. assert(csp->iob->eod - csp->iob->cur > 0);
  459. #endif
  460. bufsize = csp->iob->size;
  461. skip_size = (size_t)(csp->iob->cur - csp->iob->buf);
  462. old_size = (size_t)(csp->iob->eod - csp->iob->cur);
  463. cur = csp->iob->cur;
  464. if (bufsize < (size_t)10)
  465. {
  466. /*
  467. * This is to protect the parsing of gzipped data,
  468. * but it should(?) be valid for deflated data also.
  469. */
  470. log_error(LOG_LEVEL_ERROR,
  471. "Insufficient data to start decompression. Bytes in buffer: %ld",
  472. csp->iob->eod - csp->iob->cur);
  473. return JB_ERR_COMPRESS;
  474. }
  475. #ifdef FEATURE_BROTLI
  476. if (csp->content_type & CT_BROTLI)
  477. {
  478. return decompress_iob_with_brotli(csp);
  479. }
  480. #endif
  481. if (csp->content_type & CT_GZIP)
  482. {
  483. /*
  484. * Our task is slightly complicated by the facts that data
  485. * compressed by gzip does not include a zlib header, and
  486. * that there is no easily accessible interface in zlib to
  487. * handle a gzip header. We strip off the gzip header by
  488. * hand, and later inform zlib not to expect a header.
  489. */
  490. /*
  491. * Strip off the gzip header. Please see RFC 1952 for more
  492. * explanation of the appropriate fields.
  493. */
  494. if (((*cur++ & 0xff) != GZIP_IDENTIFIER_1)
  495. || ((*cur++ & 0xff) != GZIP_IDENTIFIER_2)
  496. || (*cur++ != Z_DEFLATED))
  497. {
  498. log_error(LOG_LEVEL_ERROR, "Invalid gzip header when decompressing");
  499. return JB_ERR_COMPRESS;
  500. }
  501. else
  502. {
  503. int flags = *cur++;
  504. if (flags & GZIP_FLAG_RESERVED_BITS)
  505. {
  506. /* The gzip header has reserved bits set; bail out. */
  507. log_error(LOG_LEVEL_ERROR, "Invalid gzip header flags when decompressing");
  508. return JB_ERR_COMPRESS;
  509. }
  510. /*
  511. * Skip mtime (4 bytes), extra flags (1 byte)
  512. * and OS type (1 byte).
  513. */
  514. cur += 6;
  515. /* Skip extra fields if necessary. */
  516. if (flags & GZIP_FLAG_EXTRA_FIELDS)
  517. {
  518. /*
  519. * Skip a given number of bytes, specified
  520. * as a 16-bit little-endian value.
  521. *
  522. * XXX: this code is untested and should probably be removed.
  523. */
  524. int skip_bytes;
  525. skip_bytes = *cur++;
  526. skip_bytes += *cur++ << 8;
  527. /*
  528. * The number of bytes to skip should be positive
  529. * and we'd like to stay in the buffer.
  530. */
  531. if ((skip_bytes < 0) || (skip_bytes >= (csp->iob->eod - cur)))
  532. {
  533. log_error(LOG_LEVEL_ERROR,
  534. "Unreasonable amount of bytes to skip (%d). Stopping decompression",
  535. skip_bytes);
  536. return JB_ERR_COMPRESS;
  537. }
  538. log_error(LOG_LEVEL_INFO,
  539. "Skipping %d bytes for gzip compression. Does this sound right?",
  540. skip_bytes);
  541. cur += skip_bytes;
  542. }
  543. /* Skip the filename if necessary. */
  544. if (flags & GZIP_FLAG_FILE_NAME)
  545. {
  546. /* A null-terminated string is supposed to follow. */
  547. while (*cur++ && (cur < csp->iob->eod));
  548. }
  549. /* Skip the comment if necessary. */
  550. if (flags & GZIP_FLAG_COMMENT)
  551. {
  552. /* A null-terminated string is supposed to follow. */
  553. while (*cur++ && (cur < csp->iob->eod));
  554. }
  555. /* Skip the CRC if necessary. */
  556. if (flags & GZIP_FLAG_CHECKSUM)
  557. {
  558. cur += 2;
  559. }
  560. if (cur >= csp->iob->eod)
  561. {
  562. /*
  563. * If the current position pointer reached or passed
  564. * the buffer end, we were obviously tricked to skip
  565. * too much.
  566. */
  567. log_error(LOG_LEVEL_ERROR,
  568. "Malformed gzip header detected. Aborting decompression.");
  569. return JB_ERR_COMPRESS;
  570. }
  571. }
  572. }
  573. else if (csp->content_type & CT_DEFLATE)
  574. {
  575. /*
  576. * In theory (that is, according to RFC 1950), deflate-compressed
  577. * data should begin with a two-byte zlib header and have an
  578. * adler32 checksum at the end. It seems that in practice only
  579. * the raw compressed data is sent. Note that this means that
  580. * we are not RFC 1950-compliant here, but the advantage is that
  581. * this actually works. :)
  582. *
  583. * We add a dummy null byte to tell zlib where the data ends,
  584. * and later inform it not to expect a header.
  585. *
  586. * Fortunately, add_to_iob() has thoughtfully null-terminated
  587. * the buffer; we can just increment the end pointer to include
  588. * the dummy byte.
  589. */
  590. csp->iob->eod++;
  591. }
  592. else
  593. {
  594. log_error(LOG_LEVEL_ERROR,
  595. "Unable to determine compression format for decompression");
  596. return JB_ERR_COMPRESS;
  597. }
  598. /* Set up the fields required by zlib. */
  599. zstr.next_in = (Bytef *)cur;
  600. zstr.avail_in = (unsigned int)(csp->iob->eod - cur);
  601. zstr.zalloc = Z_NULL;
  602. zstr.zfree = Z_NULL;
  603. zstr.opaque = Z_NULL;
  604. /*
  605. * Passing -MAX_WBITS to inflateInit2 tells the library
  606. * that there is no zlib header.
  607. */
  608. if (inflateInit2(&zstr, -MAX_WBITS) != Z_OK)
  609. {
  610. log_error(LOG_LEVEL_ERROR, "Error initializing decompression");
  611. return JB_ERR_COMPRESS;
  612. }
  613. /*
  614. * Next, we allocate new storage for the inflated data.
  615. * We don't modify the existing iob yet, so in case there
  616. * is error in decompression we can recover gracefully.
  617. */
  618. buf = zalloc(bufsize);
  619. if (NULL == buf)
  620. {
  621. log_error(LOG_LEVEL_ERROR, "Out of memory decompressing iob");
  622. return JB_ERR_MEMORY;
  623. }
  624. assert(bufsize >= skip_size);
  625. memcpy(buf, csp->iob->buf, skip_size);
  626. zstr.avail_out = (uInt)(bufsize - skip_size);
  627. zstr.next_out = (Bytef *)buf + skip_size;
  628. /* Try to decompress the whole stream in one shot. */
  629. while (Z_BUF_ERROR == (status = inflate(&zstr, Z_FINISH)))
  630. {
  631. /* We need to allocate more memory for the output buffer. */
  632. char *tmpbuf; /* used for realloc'ing the buffer */
  633. size_t oldbufsize = bufsize; /* keep track of the old bufsize */
  634. if (0 == zstr.avail_in)
  635. {
  636. /*
  637. * If zlib wants more data then there's a problem, because
  638. * the complete compressed file should have been buffered.
  639. */
  640. log_error(LOG_LEVEL_ERROR,
  641. "Unexpected end of compressed iob. Using what we got so far.");
  642. break;
  643. }
  644. /*
  645. * If we reached the buffer limit and still didn't have enough
  646. * memory, just give up. Due to the ceiling enforced by the next
  647. * if block we could actually check for equality here, but as it
  648. * can be easily mistaken for a bug we don't.
  649. */
  650. if (bufsize >= csp->config->buffer_limit)
  651. {
  652. log_error(LOG_LEVEL_ERROR, "Buffer limit reached while decompressing iob");
  653. freez(buf);
  654. inflateEnd(&zstr);
  655. return JB_ERR_MEMORY;
  656. }
  657. /* Try doubling the buffer size each time. */
  658. bufsize *= 2;
  659. /* Don't exceed the buffer limit. */
  660. if (bufsize > csp->config->buffer_limit)
  661. {
  662. bufsize = csp->config->buffer_limit;
  663. }
  664. /* Try to allocate the new buffer. */
  665. tmpbuf = realloc(buf, bufsize);
  666. if (NULL == tmpbuf)
  667. {
  668. log_error(LOG_LEVEL_ERROR, "Out of memory decompressing iob");
  669. freez(buf);
  670. inflateEnd(&zstr);
  671. return JB_ERR_MEMORY;
  672. }
  673. else
  674. {
  675. char *oldnext_out = (char *)zstr.next_out;
  676. /*
  677. * Update the fields for inflate() to use the new
  678. * buffer, which may be in a location different from
  679. * the old one.
  680. */
  681. zstr.avail_out += (uInt)(bufsize - oldbufsize);
  682. zstr.next_out = (Bytef *)tmpbuf + bufsize - zstr.avail_out;
  683. /*
  684. * Compare with an uglier method of calculating these values
  685. * that doesn't require the extra oldbufsize variable.
  686. */
  687. assert(zstr.avail_out == tmpbuf + bufsize - (char *)zstr.next_out);
  688. assert((char *)zstr.next_out == tmpbuf + ((char *)oldnext_out - buf));
  689. buf = tmpbuf;
  690. }
  691. }
  692. if (Z_STREAM_ERROR == inflateEnd(&zstr))
  693. {
  694. log_error(LOG_LEVEL_ERROR,
  695. "Inconsistent stream state after decompression: %s", zstr.msg);
  696. /*
  697. * XXX: Intentionally no return.
  698. *
  699. * According to zlib.h, Z_STREAM_ERROR is returned
  700. * "if the stream state was inconsistent".
  701. *
  702. * I assume in this case inflate()'s status
  703. * would also be something different than Z_STREAM_END
  704. * so this check should be redundant, but lets see.
  705. */
  706. }
  707. if ((status != Z_STREAM_END) && (0 != zstr.avail_in))
  708. {
  709. /*
  710. * We failed to decompress the stream and it's
  711. * not simply because of missing data.
  712. */
  713. log_error(LOG_LEVEL_ERROR,
  714. "Unexpected error while decompressing to the buffer (iob): %s",
  715. zstr.msg);
  716. return JB_ERR_COMPRESS;
  717. }
  718. /*
  719. * Finally, we can actually update the iob, since the
  720. * decompression was successful. First, free the old
  721. * buffer.
  722. */
  723. freez(csp->iob->buf);
  724. /* Now, update the iob to use the new buffer. */
  725. csp->iob->buf = buf;
  726. csp->iob->cur = csp->iob->buf + skip_size;
  727. csp->iob->eod = (char *)zstr.next_out;
  728. csp->iob->size = bufsize;
  729. /*
  730. * Make sure the new uncompressed iob obeys some minimal
  731. * consistency conditions.
  732. */
  733. if ((csp->iob->buf <= csp->iob->cur)
  734. && (csp->iob->cur <= csp->iob->eod)
  735. && (csp->iob->eod <= csp->iob->buf + csp->iob->size))
  736. {
  737. const size_t new_size = (size_t)(csp->iob->eod - csp->iob->cur);
  738. if (new_size > (size_t)0)
  739. {
  740. log_error(LOG_LEVEL_RE_FILTER,
  741. "Decompression successful. Old size: %lu, new size: %lu.",
  742. old_size, new_size);
  743. }
  744. else
  745. {
  746. /* zlib thinks this is OK, so let's do the same. */
  747. log_error(LOG_LEVEL_RE_FILTER,
  748. "Decompression didn't result in any content.");
  749. }
  750. }
  751. else
  752. {
  753. /* It seems that zlib did something weird. */
  754. log_error(LOG_LEVEL_ERROR, "Inconsistent buffer after decompression");
  755. return JB_ERR_COMPRESS;
  756. }
  757. return JB_ERR_OK;
  758. }
  759. #endif /* defined(FEATURE_ZLIB) */
  760. /*********************************************************************
  761. *
  762. * Function : normalize_lws
  763. *
  764. * Description : Reduces unquoted linear whitespace in headers to
  765. * a single space in accordance with RFC 7230 3.2.4.
  766. * This simplifies parsing and filtering later on.
  767. *
  768. * Parameters :
  769. * 1 : header = A header with linear whitespace to reduce.
  770. *
  771. * Returns : N/A
  772. *
  773. *********************************************************************/
  774. static void normalize_lws(char *header)
  775. {
  776. char *p = header;
  777. while (*p != '\0')
  778. {
  779. if (privoxy_isspace(*p) && privoxy_isspace(*(p+1)))
  780. {
  781. char *q = p+1;
  782. while (privoxy_isspace(*q))
  783. {
  784. q++;
  785. }
  786. log_error(LOG_LEVEL_HEADER, "Reducing whitespace in '%s'", header);
  787. string_move(p+1, q);
  788. }
  789. if (*p == '\t')
  790. {
  791. log_error(LOG_LEVEL_HEADER,
  792. "Converting tab to space in '%s'", header);
  793. *p = ' ';
  794. }
  795. else if (*p == '"')
  796. {
  797. char *end_of_token = strstr(p+1, "\"");
  798. if (NULL != end_of_token)
  799. {
  800. /* Don't mess with quoted text. */
  801. p = end_of_token;
  802. }
  803. else
  804. {
  805. log_error(LOG_LEVEL_HEADER,
  806. "Ignoring single quote in '%s'", header);
  807. }
  808. }
  809. p++;
  810. }
  811. p = strchr(header, ':');
  812. if ((p != NULL) && (p != header) && privoxy_isspace(*(p-1)))
  813. {
  814. /*
  815. * There's still space before the colon.
  816. * We don't want it.
  817. */
  818. string_move(p-1, p);
  819. }
  820. }
  821. /*********************************************************************
  822. *
  823. * Function : get_header
  824. *
  825. * Description : This (odd) routine will parse the csp->iob
  826. * to get the next complete header.
  827. *
  828. * Parameters :
  829. * 1 : iob = The I/O buffer to parse, usually csp->iob.
  830. *
  831. * Returns : Any one of the following:
  832. *
  833. * 1) a pointer to a dynamically allocated string that contains a header line
  834. * 2) NULL indicating that the end of the header was reached
  835. * 3) "" indicating that the end of the iob was reached before finding
  836. * a complete header line.
  837. *
  838. *********************************************************************/
  839. char *get_header(struct iob *iob)
  840. {
  841. char *header;
  842. header = get_header_line(iob);
  843. if ((header == NULL) || (*header == '\0'))
  844. {
  845. /*
  846. * No complete header read yet, tell the client.
  847. */
  848. return header;
  849. }
  850. while ((iob->cur[0] == ' ') || (iob->cur[0] == '\t'))
  851. {
  852. /*
  853. * Header spans multiple lines, append the next one.
  854. */
  855. char *continued_header;
  856. continued_header = get_header_line(iob);
  857. if ((continued_header == NULL) || (*continued_header == '\0'))
  858. {
  859. /*
  860. * No complete header read yet, return what we got.
  861. * XXX: Should "unread" header instead.
  862. */
  863. log_error(LOG_LEVEL_INFO,
  864. "Failed to read a multi-line header properly: '%s'",
  865. header);
  866. break;
  867. }
  868. if (JB_ERR_OK != string_join(&header, continued_header))
  869. {
  870. log_error(LOG_LEVEL_FATAL,
  871. "Out of memory while appending multiple headers.");
  872. }
  873. else
  874. {
  875. /* XXX: remove before next stable release. */
  876. log_error(LOG_LEVEL_HEADER,
  877. "Merged multiple header lines to: '%s'",
  878. header);
  879. }
  880. }
  881. normalize_lws(header);
  882. return header;
  883. }
  884. /*********************************************************************
  885. *
  886. * Function : get_header_line
  887. *
  888. * Description : This (odd) routine will parse the csp->iob
  889. * to get the next header line.
  890. *
  891. * Parameters :
  892. * 1 : iob = The I/O buffer to parse, usually csp->iob.
  893. *
  894. * Returns : Any one of the following:
  895. *
  896. * 1) a pointer to a dynamically allocated string that contains a header line
  897. * 2) NULL indicating that the end of the header was reached
  898. * 3) "" indicating that the end of the iob was reached before finding
  899. * a complete header line.
  900. *
  901. *********************************************************************/
  902. static char *get_header_line(struct iob *iob)
  903. {
  904. char *p, *q, *ret;
  905. if ((iob->cur == NULL)
  906. || ((p = strchr(iob->cur, '\n')) == NULL))
  907. {
  908. return(""); /* couldn't find a complete header */
  909. }
  910. *p = '\0';
  911. ret = strdup(iob->cur);
  912. if (ret == NULL)
  913. {
  914. /* FIXME No way to handle error properly */
  915. log_error(LOG_LEVEL_FATAL, "Out of memory in get_header_line()");
  916. }
  917. assert(ret != NULL);
  918. iob->cur = p+1;
  919. if ((q = strchr(ret, '\r')) != NULL) *q = '\0';
  920. /* is this a blank line (i.e. the end of the header) ? */
  921. if (*ret == '\0')
  922. {
  923. freez(ret);
  924. return NULL;
  925. }
  926. return ret;
  927. }
  928. /*********************************************************************
  929. *
  930. * Function : get_header_value
  931. *
  932. * Description : Get the value of a given header from a chained list
  933. * of header lines or return NULL if no such header is
  934. * present in the list.
  935. *
  936. * Parameters :
  937. * 1 : header_list = pointer to list
  938. * 2 : header_name = string with name of header to look for.
  939. * Trailing colon required, capitalization
  940. * doesn't matter.
  941. *
  942. * Returns : NULL if not found, else value of header
  943. *
  944. *********************************************************************/
  945. char *get_header_value(const struct list *header_list, const char *header_name)
  946. {
  947. struct list_entry *cur_entry;
  948. char *ret = NULL;
  949. size_t length = 0;
  950. assert(header_list);
  951. assert(header_name);
  952. length = strlen(header_name);
  953. for (cur_entry = header_list->first; cur_entry ; cur_entry = cur_entry->next)
  954. {
  955. if (cur_entry->str)
  956. {
  957. if (!strncmpic(cur_entry->str, header_name, length))
  958. {
  959. /*
  960. * Found: return pointer to start of value
  961. */
  962. ret = cur_entry->str + length;
  963. while (*ret && privoxy_isspace(*ret)) ret++;
  964. return ret;
  965. }
  966. }
  967. }
  968. /*
  969. * Not found
  970. */
  971. return NULL;
  972. }
  973. /*********************************************************************
  974. *
  975. * Function : scan_headers
  976. *
  977. * Description : Scans headers, applies tags and updates action bits.
  978. *
  979. * Parameters :
  980. * 1 : csp = Current client state (buffers, headers, etc...)
  981. *
  982. * Returns : JB_ERR_OK
  983. *
  984. *********************************************************************/
  985. static jb_err scan_headers(struct client_state *csp)
  986. {
  987. struct list_entry *h; /* Header */
  988. jb_err err = JB_ERR_OK;
  989. for (h = csp->headers->first; (err == JB_ERR_OK) && (h != NULL) ; h = h->next)
  990. {
  991. /* Header crunch()ed in previous run? -> ignore */
  992. if (h->str == NULL) continue;
  993. log_error(LOG_LEVEL_HEADER, "scan: %s", h->str);
  994. err = header_tagger(csp, h->str);
  995. }
  996. return err;
  997. }
  998. /*********************************************************************
  999. *
  1000. * Function : enforce_header_order
  1001. *
  1002. * Description : Enforces a given header order.
  1003. *
  1004. * Parameters :
  1005. * 1 : headers = List of headers to order.
  1006. * 2 : ordered_headers = List of ordered header names.
  1007. *
  1008. * Returns : N/A
  1009. *
  1010. *********************************************************************/
  1011. static void enforce_header_order(struct list *headers, const struct list *ordered_headers)
  1012. {
  1013. struct list_entry *sorted_header;
  1014. struct list new_headers[1];
  1015. struct list_entry *header;
  1016. init_list(new_headers);
  1017. /* The request line is always the first "header" */
  1018. assert(NULL != headers->first->str);
  1019. enlist(new_headers, headers->first->str);
  1020. freez(headers->first->str)
  1021. /* Enlist the specified headers in the given order */
  1022. for (sorted_header = ordered_headers->first; sorted_header != NULL;
  1023. sorted_header = sorted_header->next)
  1024. {
  1025. const size_t sorted_header_length = strlen(sorted_header->str);
  1026. for (header = headers->first; header != NULL; header = header->next)
  1027. {
  1028. /* Header enlisted in previous run? -> ignore */
  1029. if (header->str == NULL) continue;
  1030. if (0 == strncmpic(sorted_header->str, header->str, sorted_header_length)
  1031. && (header->str[sorted_header_length] == ':'))
  1032. {
  1033. log_error(LOG_LEVEL_HEADER, "Enlisting sorted header %s", header->str);
  1034. if (JB_ERR_OK != enlist(new_headers, header->str))
  1035. {
  1036. log_error(LOG_LEVEL_HEADER, "Failed to enlist %s", header->str);
  1037. }
  1038. freez(header->str);
  1039. }
  1040. }
  1041. }
  1042. /* Enlist the rest of the headers behind the ordered ones */
  1043. for (header = headers->first; header != NULL; header = header->next)
  1044. {
  1045. /* Header enlisted in previous run? -> ignore */
  1046. if (header->str == NULL) continue;
  1047. log_error(LOG_LEVEL_HEADER,
  1048. "Enlisting left-over header %s", header->str);
  1049. if (JB_ERR_OK != enlist(new_headers, header->str))
  1050. {
  1051. log_error(LOG_LEVEL_HEADER, "Failed to enlist %s", header->str);
  1052. }
  1053. freez(header->str);
  1054. }
  1055. list_remove_all(headers);
  1056. list_duplicate(headers, new_headers);
  1057. list_remove_all(new_headers);
  1058. return;
  1059. }
  1060. /*********************************************************************
  1061. *
  1062. * Function : sed
  1063. *
  1064. * Description : add, delete or modify lines in the HTTP header streams.
  1065. * On entry, it receives a linked list of headers space
  1066. * that was allocated dynamically (both the list nodes
  1067. * and the header contents).
  1068. *
  1069. * As a side effect it frees the space used by the original
  1070. * header lines.
  1071. *
  1072. * Parameters :
  1073. * 1 : csp = Current client state (buffers, headers, etc...)
  1074. * 2 : filter_server_headers = Boolean to switch between
  1075. * server and header filtering.
  1076. *
  1077. * Returns : JB_ERR_OK in case off success, or
  1078. * JB_ERR_MEMORY on some out-of-memory errors, or
  1079. * JB_ERR_PARSE in case of fatal parse errors.
  1080. *
  1081. *********************************************************************/
  1082. jb_err sed(struct client_state *csp, int filter_server_headers)
  1083. {
  1084. /* XXX: use more descriptive names. */
  1085. struct list_entry *p;
  1086. const struct parsers *v;
  1087. const add_header_func_ptr *f;
  1088. jb_err err = JB_ERR_OK;
  1089. scan_headers(csp);
  1090. if (filter_server_headers)
  1091. {
  1092. v = server_patterns;
  1093. f = add_server_headers;
  1094. check_negative_tag_patterns(csp, PATTERN_SPEC_NO_RESPONSE_TAG_PATTERN);
  1095. }
  1096. else
  1097. {
  1098. v = client_patterns;
  1099. f = add_client_headers;
  1100. check_negative_tag_patterns(csp, PATTERN_SPEC_NO_REQUEST_TAG_PATTERN);
  1101. }
  1102. while (v->str != NULL)
  1103. {
  1104. for (p = csp->headers->first; p != NULL; p = p->next)
  1105. {
  1106. /* Header crunch()ed in previous run? -> ignore */
  1107. if (p->str == NULL) continue;
  1108. /* Does the current parser handle this header? */
  1109. if ((strncmpic(p->str, v->str, v->len) == 0) ||
  1110. (v->len == CHECK_EVERY_HEADER_REMAINING))
  1111. {
  1112. err = v->parser(csp, &(p->str));
  1113. if (err != JB_ERR_OK)
  1114. {
  1115. return err;
  1116. }
  1117. }
  1118. }
  1119. v++;
  1120. }
  1121. /* place additional headers on the csp->headers list */
  1122. while ((err == JB_ERR_OK) && (*f))
  1123. {
  1124. err = (*f)(csp);
  1125. f++;
  1126. }
  1127. if (!filter_server_headers && !list_is_empty(csp->config->ordered_client_headers))
  1128. {
  1129. enforce_header_order(csp->headers, csp->config->ordered_client_headers);
  1130. }
  1131. return err;
  1132. }
  1133. #ifdef FEATURE_HTTPS_INSPECTION
  1134. /*********************************************************************
  1135. *
  1136. * Function : sed_https
  1137. *
  1138. * Description : add, delete or modify lines in the HTTPS client
  1139. * header streams. Wrapper around sed().
  1140. *
  1141. * Parameters :
  1142. * 1 : csp = Current client state (buffers, headers, etc...)
  1143. *
  1144. * Returns : JB_ERR_OK in case off success, or
  1145. * JB_ERR_MEMORY on some out-of-memory errors, or
  1146. * JB_ERR_PARSE in case of fatal parse errors.
  1147. *
  1148. *********************************************************************/
  1149. jb_err sed_https(struct client_state *csp)
  1150. {
  1151. jb_err err;
  1152. struct list headers;
  1153. /*
  1154. * Temporarily replace csp->headers with csp->https_headers
  1155. * to trick sed() into filtering the https headers.
  1156. */
  1157. headers.first = csp->headers->first;
  1158. headers.last = csp->headers->last;
  1159. csp->headers->first = csp->https_headers->first;
  1160. csp->headers->last = csp->https_headers->last;
  1161. /*
  1162. * Start with fresh tags. Already existing tags may
  1163. * be set again. This is necessary to overrule
  1164. * URL-based patterns.
  1165. */
  1166. destroy_list(csp->tags);
  1167. /*
  1168. * We want client header filters and taggers
  1169. * so temporarily remove the flag.
  1170. */
  1171. csp->flags &= ~CSP_FLAG_CLIENT_HEADER_PARSING_DONE;
  1172. err = sed(csp, FILTER_CLIENT_HEADERS);
  1173. csp->flags |= CSP_FLAG_CLIENT_HEADER_PARSING_DONE;
  1174. /*
  1175. * Update the last header which may have changed
  1176. * due to header additions,
  1177. */
  1178. csp->https_headers->last = csp->headers->last;
  1179. csp->headers->first = headers.first;
  1180. csp->headers->last = headers.last;
  1181. return err;
  1182. }
  1183. #endif /* def FEATURE_HTTPS_INSPECTION */
  1184. /*********************************************************************
  1185. *
  1186. * Function : update_server_headers
  1187. *
  1188. * Description : Updates server headers after the body has been modified.
  1189. *
  1190. * Parameters :
  1191. * 1 : csp = Current client state (buffers, headers, etc...)
  1192. *
  1193. * Returns : JB_ERR_OK in case off success, or
  1194. * JB_ERR_MEMORY on out-of-memory error.
  1195. *
  1196. *********************************************************************/
  1197. jb_err update_server_headers(struct client_state *csp)
  1198. {
  1199. jb_err err = JB_ERR_OK;
  1200. static const struct parsers server_patterns_light[] = {
  1201. { "Content-Length:", 15, server_adjust_content_length },
  1202. { "Transfer-Encoding:", 18, server_transfer_coding },
  1203. #ifdef FEATURE_ZLIB
  1204. { "Content-Encoding:", 17, server_adjust_content_encoding },
  1205. #endif /* def FEATURE_ZLIB */
  1206. { NULL, 0, NULL }
  1207. };
  1208. if (strncmpic(csp->http->cmd, "HEAD", 4))
  1209. {
  1210. const struct parsers *v;
  1211. struct list_entry *p;
  1212. for (v = server_patterns_light; (err == JB_ERR_OK) && (v->str != NULL); v++)
  1213. {
  1214. for (p = csp->headers->first; (err == JB_ERR_OK) && (p != NULL); p = p->next)
  1215. {
  1216. /* Header crunch()ed in previous run? -> ignore */
  1217. if (p->str == NULL) continue;
  1218. /* Does the current parser handle this header? */
  1219. if (strncmpic(p->str, v->str, v->len) == 0)
  1220. {
  1221. err = v->parser(csp, (char **)&(p->str));
  1222. }
  1223. }
  1224. }
  1225. }
  1226. #ifdef FEATURE_CONNECTION_KEEP_ALIVE
  1227. if ((JB_ERR_OK == err)
  1228. && (csp->flags & CSP_FLAG_MODIFIED)
  1229. && (csp->flags & CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE)
  1230. && !(csp->flags & CSP_FLAG_SERVER_CONTENT_LENGTH_SET))
  1231. {
  1232. char header[50];
  1233. create_content_length_header(csp->content_length, header, sizeof(header));
  1234. err = enlist(csp->headers, header);
  1235. if (JB_ERR_OK == err)
  1236. {
  1237. log_error(LOG_LEVEL_HEADER,
  1238. "Content modified with no Content-Length header set. "
  1239. "Created: %s.", header);
  1240. csp->flags |= CSP_FLAG_SERVER_CONTENT_LENGTH_SET;
  1241. }
  1242. }
  1243. #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
  1244. #ifdef FEATURE_COMPRESSION
  1245. if ((JB_ERR_OK == err)
  1246. && (csp->flags & CSP_FLAG_BUFFERED_CONTENT_DEFLATED))
  1247. {
  1248. err = enlist_unique_header(csp->headers, "Content-Encoding", "deflate");
  1249. if (JB_ERR_OK == err)
  1250. {
  1251. log_error(LOG_LEVEL_HEADER, "Added header: Content-Encoding: deflate");
  1252. }
  1253. }
  1254. #endif
  1255. return err;
  1256. }
  1257. /*********************************************************************
  1258. *
  1259. * Function : header_tagger
  1260. *
  1261. * Description : Executes all text substitutions from applying
  1262. * tag actions and saves the result as tag.
  1263. *
  1264. * XXX: Shares enough code with filter_header() and
  1265. * pcrs_filter_response() to warrant some helper functions.
  1266. *
  1267. * Parameters :
  1268. * 1 : csp = Current client state (buffers, headers, etc...)
  1269. * 2 : header = Header that is used as tagger input
  1270. *
  1271. * Returns : JB_ERR_OK on success and always succeeds
  1272. *
  1273. *********************************************************************/
  1274. static jb_err header_tagger(struct client_state *csp, char *header)
  1275. {
  1276. enum filter_type wanted_filter_type;
  1277. int multi_action_index;
  1278. pcrs_job *job;
  1279. struct re_filterfile_spec *b;
  1280. struct list_entry *tag_name;
  1281. const size_t header_length = strlen(header);
  1282. if (csp->flags & CSP_FLAG_CLIENT_HEADER_PARSING_DONE)
  1283. {
  1284. wanted_filter_type = FT_SERVER_HEADER_TAGGER;
  1285. multi_action_index = ACTION_MULTI_SERVER_HEADER_TAGGER;
  1286. }
  1287. else
  1288. {
  1289. wanted_filter_type = FT_CLIENT_HEADER_TAGGER;
  1290. multi_action_index = ACTION_MULTI_CLIENT_HEADER_TAGGER;
  1291. }
  1292. if (list_is_empty(csp->action->multi[multi_action_index])
  1293. || filters_available(csp) == FALSE)
  1294. {
  1295. /* Return early if no taggers apply or if none are available. */
  1296. return JB_ERR_OK;
  1297. }
  1298. /* Execute all applying taggers */
  1299. for (tag_name = csp->action->multi[multi_action_index]->first;
  1300. NULL != tag_name; tag_name = tag_name->next)
  1301. {
  1302. char *modified_tag = NULL;
  1303. char *tag = header;
  1304. size_t size = header_length;
  1305. pcrs_job *joblist;
  1306. b = get_filter(csp, tag_name->str, wanted_filter_type);
  1307. if (b == NULL)
  1308. {
  1309. continue;
  1310. }
  1311. joblist = b->joblist;
  1312. if (b->dynamic) joblist = compile_dynamic_pcrs_job_list(csp, b);
  1313. if (NULL == joblist)
  1314. {
  1315. log_error(LOG_LEVEL_RE_FILTER,
  1316. "Tagger %s has empty joblist. Nothing to do.", b->name);
  1317. continue;
  1318. }
  1319. /* execute their pcrs_joblist on the header. */
  1320. for (job = joblist; NULL != job; job = job->next)
  1321. {
  1322. const int hits = pcrs_execute(job, tag, size, &modified_tag, &size);
  1323. if (0 < hits)
  1324. {
  1325. /* Success, continue with the modified version. */
  1326. if (tag != header)
  1327. {
  1328. freez(tag);
  1329. }
  1330. tag = modified_tag;
  1331. }
  1332. else
  1333. {
  1334. /* Tagger doesn't match */
  1335. if (0 > hits)
  1336. {
  1337. /* Regex failure, log it but continue anyway. */
  1338. assert(NULL != header);
  1339. log_error(LOG_LEVEL_ERROR,
  1340. "Problems with tagger \'%s\' and header \'%s\': %s",
  1341. b->name, header, pcrs_strerror(hits));
  1342. }
  1343. freez(modified_tag);
  1344. }
  1345. }
  1346. if (b->dynamic) pcrs_free_joblist(joblist);
  1347. /* If this tagger matched */
  1348. if (tag != header)
  1349. {
  1350. if (0 == size)
  1351. {
  1352. /*
  1353. * There is no technical limitation which makes
  1354. * it impossible to use empty tags, but I assume
  1355. * no one would do it intentionally.
  1356. */
  1357. freez(tag);
  1358. log_error(LOG_LEVEL_INFO,
  1359. "Tagger \'%s\' created an empty tag. Ignored.", b->name);
  1360. continue;
  1361. }
  1362. if (!list_contains_item(csp->tags, tag))
  1363. {
  1364. if (JB_ERR_OK != enlist(csp->tags, tag))
  1365. {
  1366. log_error(LOG_LEVEL_ERROR,
  1367. "Insufficient memory to add tag \'%s\', "
  1368. "based on tagger \'%s\' and header \'%s\'",
  1369. tag, b->name, header);
  1370. }
  1371. else
  1372. {
  1373. char *action_message;
  1374. /*
  1375. * update the action bits right away, to make
  1376. * tagging based on tags set by earlier taggers
  1377. * of the same kind possible.
  1378. */
  1379. if (update_action_bits_for_tag(csp, tag))
  1380. {
  1381. action_message = "Action bits updated accordingly.";
  1382. }
  1383. else
  1384. {
  1385. action_message = "No action bits update necessary.";
  1386. }
  1387. log_error(LOG_LEVEL_HEADER,
  1388. "Tagger \'%s\' added tag \'%s\'. %s",
  1389. b->name, tag, action_message);
  1390. }
  1391. }
  1392. else
  1393. {
  1394. /* XXX: Is this log-worthy? */
  1395. log_error(LOG_LEVEL_HEADER,
  1396. "Tagger \'%s\' didn't add tag \'%s\'. Tag already present",
  1397. b->name, tag);
  1398. }
  1399. freez(tag);
  1400. }
  1401. }
  1402. return JB_ERR_OK;
  1403. }
  1404. /* here begins the family of parser functions that reformat header lines */
  1405. /*********************************************************************
  1406. *
  1407. * Function : filter_header
  1408. *
  1409. * Description : Executes all text substitutions from all applying
  1410. * +(server|client)-header-filter actions on the header.
  1411. * Most of the code was copied from pcrs_filter_response,
  1412. * including the rather short variable names
  1413. *
  1414. * Parameters :
  1415. * 1 : csp = Current client state (buffers, headers, etc...)
  1416. * 2 : header = On input, pointer to header to modify.
  1417. * On output, pointer to the modified header, or NULL
  1418. * to remove the header. This function frees the
  1419. * original string if necessary.
  1420. *
  1421. * Returns : JB_ERR_OK on success and always succeeds
  1422. *
  1423. *********************************************************************/
  1424. static jb_err filter_header(struct client_state *csp, char **header)
  1425. {
  1426. int hits=0;
  1427. int matches;
  1428. size_t size = strlen(*header);
  1429. char *newheader = NULL;
  1430. pcrs_job *job;
  1431. struct re_filterfile_spec *b;
  1432. struct list_entry *filtername;
  1433. enum filter_type wanted_filter_type;
  1434. int multi_action_index;
  1435. if (csp->flags & CSP_FLAG_NO_FILTERING)
  1436. {
  1437. return JB_ERR_OK;
  1438. }
  1439. if (csp->flags & CSP_FLAG_CLIENT_HEADER_PARSING_DONE)
  1440. {
  1441. wanted_filter_type = FT_SERVER_HEADER_FILTER;
  1442. multi_action_index = ACTION_MULTI_SERVER_HEADER_FILTER;
  1443. }
  1444. else
  1445. {
  1446. wanted_filter_type = FT_CLIENT_HEADER_FILTER;
  1447. multi_action_index = ACTION_MULTI_CLIENT_HEADER_FILTER;
  1448. }
  1449. if (list_is_empty(csp->action->multi[multi_action_index])
  1450. || filters_available(csp) == FALSE)
  1451. {
  1452. /* Return early if no filters apply or if none are available. */
  1453. return JB_ERR_OK;
  1454. }
  1455. /* Execute all applying header filters */
  1456. for (filtername = csp->action->multi[multi_action_index]->first;
  1457. filtername != NULL; filtername = filtername->next)
  1458. {
  1459. int current_hits = 0;
  1460. pcrs_job *joblist;
  1461. b = get_filter(csp, filtername->str, wanted_filter_type);
  1462. if (b == NULL)
  1463. {
  1464. continue;
  1465. }
  1466. joblist = b->joblist;
  1467. if (b->dynamic) joblist = compile_dynamic_pcrs_job_list(csp, b);
  1468. if (NULL == joblist)
  1469. {
  1470. log_error(LOG_LEVEL_RE_FILTER, "Filter %s has empty joblist. Nothing to do.", b->name);
  1471. continue;
  1472. }
  1473. log_error(LOG_LEVEL_RE_FILTER, "filtering \'%s\' (size %lu) with \'%s\' ...",
  1474. *header, size, b->name);
  1475. /* Apply all jobs from the joblist */
  1476. for (job = joblist; NULL != job; job = job->next)
  1477. {
  1478. matches = pcrs_execute(job, *header, size, &newheader, &size);
  1479. if (0 < matches)
  1480. {
  1481. current_hits += matches;
  1482. log_error(LOG_LEVEL_HEADER, "Transforming \"%s\" to \"%s\"", *header, newheader);
  1483. freez(*header);
  1484. *header = newheader;
  1485. }
  1486. else if (0 == matches)
  1487. {
  1488. /* Filter doesn't change header */
  1489. freez(newheader);
  1490. }
  1491. else
  1492. {
  1493. /* RegEx failure */
  1494. log_error(LOG_LEVEL_ERROR, "Filtering \'%s\' with \'%s\' didn't work out: %s",
  1495. *header, b->name, pcrs_strerror(matches));
  1496. if (newheader != NULL)
  1497. {
  1498. log_error(LOG_LEVEL_ERROR, "Freeing what's left: %s", newheader);
  1499. freez(newheader);
  1500. }
  1501. }
  1502. }
  1503. if (b->dynamic) pcrs_free_joblist(joblist);
  1504. log_error(LOG_LEVEL_RE_FILTER,
  1505. "... produced %d hits (new size %lu).", current_hits, size);
  1506. hits += current_hits;
  1507. }
  1508. /*
  1509. * Additionally checking for hits is important because if
  1510. * the continue hack is triggered, server headers can
  1511. * arrive empty to separate multiple heads from each other.
  1512. */
  1513. if ((0 == size) && hits)
  1514. {
  1515. log_error(LOG_LEVEL_HEADER, "Removing empty header %s", *header);
  1516. freez(*header);
  1517. }
  1518. return JB_ERR_OK;
  1519. }
  1520. /*********************************************************************
  1521. *
  1522. * Function : server_connection
  1523. *
  1524. * Description : Makes sure a proper "Connection:" header is
  1525. * set and signals connection_header_adder to
  1526. * do nothing.
  1527. *
  1528. * Parameters :
  1529. * 1 : csp = Current client state (buffers, headers, etc...)
  1530. * 2 : header = On input, pointer to header to modify.
  1531. * On output, pointer to the modified header, or NULL
  1532. * to remove the header. This function frees the
  1533. * original string if necessary.
  1534. *
  1535. * Returns : JB_ERR_OK on success.
  1536. *
  1537. *********************************************************************/
  1538. static jb_err server_connection(struct client_state *csp, char **header)
  1539. {
  1540. if (!strcmpic(*header, "Connection: keep-alive")
  1541. #ifdef FEATURE_CONNECTION_KEEP_ALIVE
  1542. && !(csp->flags & CSP_FLAG_SERVER_SOCKET_TAINTED)
  1543. #endif
  1544. )
  1545. {
  1546. #ifdef FEATURE_CONNECTION_KEEP_ALIVE
  1547. if ((csp->config->feature_flags & RUNTIME_FEATURE_CONNECTION_KEEP_ALIVE))
  1548. {
  1549. csp->flags |= CSP_FLAG_SERVER_CONNECTION_KEEP_ALIVE;
  1550. }
  1551. if ((csp->flags & CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE))
  1552. {
  1553. log_error(LOG_LEVEL_HEADER,
  1554. "Keeping the server header '%s' around.", *header);
  1555. }
  1556. else
  1557. #endif /* FEATURE_CONNECTION_KEEP_ALIVE */
  1558. {
  1559. char *old_header = *header;
  1560. *header = strdup_or_die("Connection: close");
  1561. log_error(LOG_LEVEL_HEADER, "Replaced: \'%s\' with \'%s\'", old_header, *header);
  1562. freez(old_header);
  1563. }
  1564. }
  1565. /* Signal server_connection_adder() to return early. */
  1566. csp->flags |= CSP_FLAG_SERVER_CONNECTION_HEADER_SET;
  1567. return JB_ERR_OK;
  1568. }
  1569. #ifdef FEATURE_CONNECTION_KEEP_ALIVE
  1570. /*********************************************************************
  1571. *
  1572. * Function : server_keep_alive
  1573. *
  1574. * Description : Stores the server's keep alive timeout.
  1575. *
  1576. * Parameters :
  1577. * 1 : csp = Current client state (buffers, headers, etc...)
  1578. * 2 : header = On input, pointer to header to modify.
  1579. * On output, pointer to the modified header, or NULL
  1580. * to remove the header. This function frees the
  1581. * original string if necessary.
  1582. *
  1583. * Returns : JB_ERR_OK.
  1584. *
  1585. *********************************************************************/
  1586. static jb_err server_keep_alive(struct client_state *csp, char **header)
  1587. {
  1588. unsigned int keep_alive_timeout;
  1589. const char *timeout_position = strstr(*header, "timeout=");
  1590. if ((NULL == timeout_position)
  1591. || (1 != sscanf(timeout_position, "timeout=%u", &keep_alive_timeout)))
  1592. {
  1593. log_error(LOG_LEVEL_ERROR, "Couldn't parse: %s", *header);
  1594. }
  1595. else
  1596. {
  1597. if (keep_alive_timeout < csp->server_connection.keep_alive_timeout)
  1598. {
  1599. log_error(LOG_LEVEL_HEADER,
  1600. "Reducing keep-alive timeout from %u to %u.",
  1601. csp->server_connection.keep_alive_timeout, keep_alive_timeout);
  1602. csp->server_connection.keep_alive_timeout = keep_alive_timeout;
  1603. }
  1604. else
  1605. {
  1606. /* XXX: Is this log worthy? */
  1607. log_error(LOG_LEVEL_HEADER,
  1608. "Server keep-alive timeout is %u. Sticking with %u.",
  1609. keep_alive_timeout, csp->server_connection.keep_alive_timeout);
  1610. }
  1611. csp->flags |= CSP_FLAG_SERVER_KEEP_ALIVE_TIMEOUT_SET;
  1612. }
  1613. freez(*header);
  1614. return JB_ERR_OK;
  1615. }
  1616. /*********************************************************************
  1617. *
  1618. * Function : server_proxy_connection
  1619. *
  1620. * Description : Figures out whether or not we should add a
  1621. * Proxy-Connection header.
  1622. *
  1623. * Parameters :
  1624. * 1 : csp = Current client state (buffers, headers, etc...)
  1625. * 2 : header = On input, pointer to header to modify.
  1626. * On output, pointer to the modified header, or NULL
  1627. * to remove the header. This function frees the
  1628. * original string if necessary.
  1629. *
  1630. * Returns : JB_ERR_OK.
  1631. *
  1632. *********************************************************************/
  1633. static jb_err server_proxy_connection(struct client_state *csp, char **header)
  1634. {
  1635. csp->flags |= CSP_FLAG_SERVER_PROXY_CONNECTION_HEADER_SET;
  1636. return JB_ERR_OK;
  1637. }
  1638. #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
  1639. /*********************************************************************
  1640. *
  1641. * Function : proxy_authentication
  1642. *
  1643. * Description : Removes headers that are relevant for proxy
  1644. * authentication unless forwarding them has
  1645. * been explicitly requested.
  1646. *
  1647. * Parameters :
  1648. * 1 : csp = Current client state (buffers, headers, etc...)
  1649. * 2 : header = On input, pointer to header to modify.
  1650. * On output, pointer to the modified header, or NULL
  1651. * to remove the header. This function frees the
  1652. * original string if necessary.
  1653. *
  1654. * Returns : JB_ERR_OK.
  1655. *
  1656. *********************************************************************/
  1657. static jb_err proxy_authentication(struct client_state *csp, char **header)
  1658. {
  1659. if ((csp->config->feature_flags &
  1660. RUNTIME_FEATURE_FORWARD_PROXY_AUTHENTICATION_HEADERS) == 0) {
  1661. log_error(LOG_LEVEL_HEADER,
  1662. "Forwarding proxy authentication headers is disabled. Crunching: %s", *header);
  1663. freez(*header);
  1664. }
  1665. return JB_ERR_OK;
  1666. }
  1667. #ifdef FEATURE_CONNECTION_KEEP_ALIVE
  1668. /*********************************************************************
  1669. *
  1670. * Function : client_keep_alive
  1671. *
  1672. * Description : Stores the client's keep alive timeout.
  1673. *
  1674. * Parameters :
  1675. * 1 : csp = Current client state (buffers, headers, etc...)
  1676. * 2 : header = On input, pointer to header to modify.
  1677. * On output, pointer to the modified header, or NULL
  1678. * to remove the header. This function frees the
  1679. * original string if necessary.
  1680. *
  1681. * Returns : JB_ERR_OK.
  1682. *
  1683. *********************************************************************/
  1684. static jb_err client_keep_alive(struct client_state *csp, char **header)
  1685. {
  1686. unsigned int keep_alive_timeout;
  1687. char *timeout_position;
  1688. if (!(csp->config->feature_flags & RUNTIME_FEATURE_CONNECTION_KEEP_ALIVE))
  1689. {
  1690. log_error(LOG_LEVEL_HEADER,
  1691. "keep-alive support is disabled. Crunching: %s.", *header);
  1692. freez(*header);
  1693. return JB_ERR_OK;
  1694. }
  1695. /* Check for parameter-less format "Keep-Alive: 100" */
  1696. timeout_position = strstr(*header, ": ");
  1697. if ((NULL == timeout_position)
  1698. || (1 != sscanf(timeout_position, ": %u", &keep_alive_timeout)))
  1699. {
  1700. /* Assume parameter format "Keep-Alive: timeout=100" */
  1701. timeout_position = strstr(*header, "timeout=");
  1702. if ((NULL == timeout_position)
  1703. || (1 != sscanf(timeout_position, "timeout=%u", &keep_alive_timeout)))
  1704. {
  1705. log_error(LOG_LEVEL_HEADER,
  1706. "Couldn't parse: '%s'. Using default timeout %u",
  1707. *header, csp->config->keep_alive_timeout);
  1708. freez(*header);
  1709. return JB_ERR_OK;
  1710. }
  1711. }
  1712. if (keep_alive_timeout < csp->config->keep_alive_timeout)
  1713. {
  1714. log_error(LOG_LEVEL_HEADER,
  1715. "Reducing keep-alive timeout from %u to %u.",
  1716. csp->config->keep_alive_timeout, keep_alive_timeout);
  1717. csp->server_connection.keep_alive_timeout = keep_alive_timeout;
  1718. }
  1719. else
  1720. {
  1721. /* XXX: Is this log worthy? */
  1722. log_error(LOG_LEVEL_HEADER,
  1723. "Client keep-alive timeout is %u. Sticking with %u.",
  1724. keep_alive_timeout, csp->config->keep_alive_timeout);
  1725. freez(*header);
  1726. }
  1727. return JB_ERR_OK;
  1728. }
  1729. #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
  1730. /*********************************************************************
  1731. *
  1732. * Function : get_content_length
  1733. *
  1734. * Description : Gets the content length specified in a
  1735. * Content-Length header.
  1736. *
  1737. * Parameters :
  1738. * 1 : header_value = The Content-Length header value.
  1739. * 2 : length = Storage to return the value.
  1740. *
  1741. * Returns : JB_ERR_OK on success, or
  1742. * JB_ERR_PARSE if no value is recognized.
  1743. *
  1744. *********************************************************************/
  1745. static jb_err get_content_length(const char *header_value, unsigned long long *length)
  1746. {
  1747. #ifdef _WIN32
  1748. #if SIZEOF_LONG_LONG < 8
  1749. #error sizeof(unsigned long long) too small
  1750. #endif
  1751. if (1 != sscanf(header_value, "%I64u", length))
  1752. #else
  1753. if (1 != sscanf(header_value, "%llu", length))
  1754. #endif
  1755. {
  1756. return JB_ERR_PARSE;
  1757. }
  1758. return JB_ERR_OK;
  1759. }
  1760. /*********************************************************************
  1761. *
  1762. * Function : client_save_content_length
  1763. *
  1764. * Description : Save the Content-Length sent by the client.
  1765. *
  1766. * Parameters :
  1767. * 1 : csp = Current client state (buffers, headers, etc...)
  1768. * 2 : header = On input, pointer to header to modify.
  1769. * On output, pointer to the modified header, or NULL
  1770. * to remove the header. This function frees the
  1771. * original string if necessary.
  1772. *
  1773. * Returns : JB_ERR_OK on success, or
  1774. * JB_ERR_MEMORY on out-of-memory error.
  1775. *
  1776. *********************************************************************/
  1777. static jb_err client_save_content_length(struct client_state *csp, char **header)
  1778. {
  1779. unsigned long long content_length = 0;
  1780. const char *header_value;
  1781. assert(*(*header+14) == ':');
  1782. header_value = *header + 15;
  1783. if (JB_ERR_OK != get_content_length(header_value, &content_length))
  1784. {
  1785. log_error(LOG_LEVEL_ERROR, "Crunching invalid header: %s", *header);
  1786. freez(*header);
  1787. }
  1788. else
  1789. {
  1790. csp->expected_client_content_length = content_length;
  1791. }
  1792. return JB_ERR_OK;
  1793. }
  1794. /*********************************************************************
  1795. *
  1796. * Function : client_connection
  1797. *
  1798. * Description : Makes sure a proper "Connection:" header is
  1799. * set and signals connection_header_adder
  1800. * to do nothing.
  1801. *
  1802. * Parameters :
  1803. * 1 : csp = Current client state (buffers, headers, etc...)
  1804. * 2 : header = On input, pointer to header to modify.
  1805. * On output, pointer to the modified header, or NULL
  1806. * to remove the header. This function frees the
  1807. * original string if necessary.
  1808. *
  1809. * Returns : JB_ERR_OK on success.
  1810. *
  1811. *********************************************************************/
  1812. static jb_err client_connection(struct client_state *csp, char **header)
  1813. {
  1814. static const char connection_close[] = "Connection: close";
  1815. if (!strcmpic(*header, connection_close))
  1816. {
  1817. #ifdef FEATURE_CONNECTION_KEEP_ALIVE
  1818. if ((csp->config->feature_flags & RUNTIME_FEATURE_CONNECTION_SHARING)
  1819. && !(csp->flags & CSP_FLAG_SERVER_SOCKET_TAINTED)
  1820. #ifdef FEATURE_HTTPS_INSPECTION
  1821. && !client_use_ssl(csp)
  1822. #endif
  1823. )
  1824. {
  1825. if (!strcmpic(csp->http->version, "HTTP/1.1"))
  1826. {
  1827. log_error(LOG_LEVEL_HEADER,
  1828. "Removing \'%s\' to imply keep-alive.", *header);
  1829. freez(*header);
  1830. /*
  1831. * While we imply keep-alive to the server,
  1832. * we have to remember that the client didn't.
  1833. */
  1834. csp->flags &= ~CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE;
  1835. }
  1836. else
  1837. {
  1838. char *old_header = *header;
  1839. *header = strdup_or_die("Connection: keep-alive");
  1840. log_error(LOG_LEVEL_HEADER,
  1841. "Replaced: \'%s\' with \'%s\'", old_header, *header);
  1842. freez(old_header);
  1843. }
  1844. }
  1845. else
  1846. {
  1847. log_error(LOG_LEVEL_HEADER,
  1848. "Keeping the client header '%s' around. "
  1849. "The connection will not be kept alive.",
  1850. *header);
  1851. csp->flags &= ~CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE;
  1852. }
  1853. }
  1854. else if ((csp->config->feature_flags & RUNTIME_FEATURE_CONNECTION_KEEP_ALIVE)
  1855. && !(csp->flags & CSP_FLAG_SERVER_SOCKET_TAINTED))
  1856. {
  1857. log_error(LOG_LEVEL_HEADER,
  1858. "Keeping the client header '%s' around. "
  1859. "The server connection will be kept alive if possible.",
  1860. *header);
  1861. csp->flags |= CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE;
  1862. #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
  1863. }
  1864. else
  1865. {
  1866. char *old_header = *header;
  1867. *header = strdup_or_die(connection_close);
  1868. log_error(LOG_LEVEL_HEADER,
  1869. "Replaced: \'%s\' with \'%s\'", old_header, *header);
  1870. freez(old_header);
  1871. }
  1872. /* Signal client_connection_header_adder() to return early. */
  1873. csp->flags |= CSP_FLAG_CLIENT_CONNECTION_HEADER_SET;
  1874. return JB_ERR_OK;
  1875. }
  1876. #ifdef FEATURE_CONNECTION_KEEP_ALIVE
  1877. /*********************************************************************
  1878. *
  1879. * Function : client_proxy_connection
  1880. *
  1881. * Description : Sets the CLIENT_CONNECTION_KEEP_ALIVE flag when
  1882. * appropriate and removes the Proxy-Connection
  1883. * header.
  1884. *
  1885. * Parameters :
  1886. * 1 : csp = Current client state (buffers, headers, etc...)
  1887. * 2 : header = On input, pointer to header to modify.
  1888. * On output, pointer to the modified header, or NULL
  1889. * to remove the header. This function frees the
  1890. * original string if necessary.
  1891. *
  1892. * Returns : JB_ERR_OK
  1893. *
  1894. *********************************************************************/
  1895. static jb_err client_proxy_connection(struct client_state *csp, char **header)
  1896. {
  1897. if (0 == (csp->flags & CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE)
  1898. && (csp->http->ssl == 0)
  1899. && (NULL == strstr(*header, "close")))
  1900. {
  1901. log_error(LOG_LEVEL_HEADER,
  1902. "The client connection can be kept alive due to: %s", *header);
  1903. csp->flags |= CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE;
  1904. }
  1905. crumble(csp, header);
  1906. return JB_ERR_OK;
  1907. }
  1908. #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
  1909. /*********************************************************************
  1910. *
  1911. * Function : client_transfer_encoding
  1912. *
  1913. * Description : Raise the CSP_FLAG_CHUNKED_CLIENT_BODY flag if
  1914. * the request body is "chunked"
  1915. *
  1916. * XXX: Currently not called through sed() as we
  1917. * need the flag earlier on. Should be fixed.
  1918. *
  1919. * Parameters :
  1920. * 1 : csp = Current client state (buffers, headers, etc...)
  1921. * 2 : header = On input, pointer to header to modify.
  1922. * On output, pointer to the modified header, or NULL
  1923. * to remove the header. This function frees the
  1924. * original string if necessary.
  1925. *
  1926. * Returns : JB_ERR_OK on success, or
  1927. *
  1928. *********************************************************************/
  1929. jb_err client_transfer_encoding(struct client_state *csp, char **header)
  1930. {
  1931. if (strstr(*header, "chunked"))
  1932. {
  1933. csp->flags |= CSP_FLAG_CHUNKED_CLIENT_BODY;
  1934. log_error(LOG_LEVEL_HEADER, "Expecting chunked client body");
  1935. }
  1936. return JB_ERR_OK;
  1937. }
  1938. /*********************************************************************
  1939. *
  1940. * Function : client_expect
  1941. *
  1942. * Description : Raise the CSP_FLAG_UNSUPPORTED_CLIENT_EXPECTATION
  1943. * if the Expect header value is unsupported.
  1944. *
  1945. * Rejecting unsupported expectations is a RFC 7231 5.1.1
  1946. * MAY and a RFC 2616 (obsolete) MUST.
  1947. *
  1948. * Parameters :
  1949. * 1 : csp = Current client state (buffers, headers, etc...)
  1950. * 2 : header = On input, pointer to header to modify.
  1951. * On output, pointer to the modified header, or NULL
  1952. * to remove the header. This function frees the
  1953. * original string if necessary.
  1954. *
  1955. * Returns : JB_ERR_OK on success, or
  1956. *
  1957. *********************************************************************/
  1958. jb_err client_expect(struct client_state *csp, char **header)
  1959. {
  1960. if (0 != strcmpic(*header, "Expect: 100-continue"))
  1961. {
  1962. csp->flags |= CSP_FLAG_UNSUPPORTED_CLIENT_EXPECTATION;
  1963. log_error(LOG_LEVEL_HEADER,
  1964. "Unsupported client expectaction: %s", *header);
  1965. }
  1966. return JB_ERR_OK;
  1967. }
  1968. /*********************************************************************
  1969. *
  1970. * Function : crumble
  1971. *
  1972. * Description : This is called if a header matches a pattern to "crunch"
  1973. *
  1974. * Parameters :
  1975. * 1 : csp = Current client state (buffers, headers, etc...)
  1976. * 2 : header = On input, pointer to header to modify.
  1977. * On output, pointer to the modified header, or NULL
  1978. * to remove the header. This function frees the
  1979. * original string if necessary.
  1980. *
  1981. * Returns : JB_ERR_OK on success, or
  1982. * JB_ERR_MEMORY on out-of-memory error.
  1983. *
  1984. *********************************************************************/
  1985. static jb_err crumble(struct client_state *csp, char **header)
  1986. {
  1987. (void)csp;
  1988. log_error(LOG_LEVEL_HEADER, "crumble crunched: %s!", *header);
  1989. freez(*header);
  1990. return JB_ERR_OK;
  1991. }
  1992. /*********************************************************************
  1993. *
  1994. * Function : crunch_server_header
  1995. *
  1996. * Description : Crunch server header if it matches a string supplied by the
  1997. * user. Called from `sed'.
  1998. *
  1999. * Parameters :
  2000. * 1 : csp = Current client state (buffers, headers, etc...)
  2001. * 2 : header = On input, pointer to header to modify.
  2002. * On output, pointer to the modified header, or NULL
  2003. * to remove the header. This function frees the
  2004. * original string if necessary.
  2005. *
  2006. * Returns : JB_ERR_OK on success and always succeeds
  2007. *
  2008. *********************************************************************/
  2009. static jb_err crunch_server_header(struct client_state *csp, char **header)
  2010. {
  2011. const char *crunch_pattern;
  2012. /* Do we feel like crunching? */
  2013. if ((csp->action->flags & ACTION_CRUNCH_SERVER_HEADER))
  2014. {
  2015. crunch_pattern = csp->action->string[ACTION_STRING_SERVER_HEADER];
  2016. /* Is the current header the lucky one? */
  2017. if (strstr(*header, crunch_pattern))
  2018. {
  2019. log_error(LOG_LEVEL_HEADER, "Crunching server header: %s (contains: %s)", *header, crunch_pattern);
  2020. freez(*header);
  2021. }
  2022. }
  2023. return JB_ERR_OK;
  2024. }
  2025. /*********************************************************************
  2026. *
  2027. * Function : server_content_type
  2028. *
  2029. * Description : Set the content-type for filterable types (text/.*,
  2030. * .*xml.*, .*script.* and image/gif) unless filtering has been
  2031. * forbidden (CT_TABOO) while parsing earlier headers.
  2032. * NOTE: Since text/plain is commonly used by web servers
  2033. * for files whose correct type is unknown, we don't
  2034. * set CT_TEXT for it.
  2035. *
  2036. * Parameters :
  2037. * 1 : csp = Current client state (buffers, headers, etc...)
  2038. * 2 : header = On input, pointer to header to modify.
  2039. * On output, pointer to the modified header, or NULL
  2040. * to remove the header. This function frees the
  2041. * original string if necessary.
  2042. *
  2043. * Returns : JB_ERR_OK on success, or
  2044. * JB_ERR_MEMORY on out-of-memory error.
  2045. *
  2046. *********************************************************************/
  2047. static jb_err server_content_type(struct client_state *csp, char **header)
  2048. {
  2049. /* Remove header if it isn't the first Content-Type header */
  2050. if ((csp->content_type & CT_DECLARED))
  2051. {
  2052. if (content_filters_enabled(csp->action))
  2053. {
  2054. /*
  2055. * Making sure the client interprets the content the same way
  2056. * Privoxy did is only relevant if Privoxy modified it.
  2057. *
  2058. * Checking for this is "hard" as it's not yet known when
  2059. * this function is called, thus go shopping and and just
  2060. * check if Privoxy could filter it.
  2061. *
  2062. * The main thing is that we don't mess with the headers
  2063. * unless the user signalled that it's acceptable.
  2064. */
  2065. log_error(LOG_LEVEL_HEADER,
  2066. "Multiple Content-Type headers detected. "
  2067. "Removing and ignoring: %s",
  2068. *header);
  2069. freez(*header);
  2070. }
  2071. return JB_ERR_OK;
  2072. }
  2073. /*
  2074. * Signal that the Content-Type has been set.
  2075. */
  2076. csp->content_type |= CT_DECLARED;
  2077. if (!(csp->content_type & CT_TABOO))
  2078. {
  2079. /*
  2080. * XXX: The assumption that text/plain is a sign of
  2081. * binary data seems to be somewhat unreasonable nowadays
  2082. * and should be dropped after 3.0.8 is out.
  2083. */
  2084. if ((strstr(*header, "text/") && !strstr(*header, "plain"))
  2085. || strstr(*header, "xml")
  2086. || strstr(*header, "script"))
  2087. {
  2088. csp->content_type |= CT_TEXT;
  2089. }
  2090. else if (strstr(*header, "image/gif"))
  2091. {
  2092. csp->content_type |= CT_GIF;
  2093. }
  2094. }
  2095. /*
  2096. * Are we messing with the content type?
  2097. */
  2098. if (csp->action->flags & ACTION_CONTENT_TYPE_OVERWRITE)
  2099. {
  2100. /*
  2101. * Make sure the user doesn't accidentally
  2102. * change the content type of binary documents.
  2103. */
  2104. if ((csp->content_type & CT_TEXT) || (csp->action->flags & ACTION_FORCE_TEXT_MODE))
  2105. {
  2106. jb_err err;
  2107. freez(*header);
  2108. *header = strdup_or_die("Content-Type: ");
  2109. err = string_append(header, csp->action->string[ACTION_STRING_CONTENT_TYPE]);
  2110. if (JB_ERR_OK != err)
  2111. {
  2112. log_error(LOG_LEVEL_HEADER, "Insufficient memory to replace Content-Type!");
  2113. return JB_ERR_MEMORY;
  2114. }
  2115. log_error(LOG_LEVEL_HEADER, "Modified: %s!", *header);
  2116. }
  2117. else
  2118. {
  2119. log_error(LOG_LEVEL_HEADER, "%s not replaced. "
  2120. "It doesn't look like a content type that should be filtered. "
  2121. "Enable force-text-mode if you know what you're doing.", *header);
  2122. }
  2123. }
  2124. return JB_ERR_OK;
  2125. }
  2126. /*********************************************************************
  2127. *
  2128. * Function : server_transfer_coding
  2129. *
  2130. * Description : - Prohibit filtering (CT_TABOO) if transfer coding compresses
  2131. * - Raise the CSP_FLAG_CHUNKED flag if coding is "chunked"
  2132. * - Remove header if body was chunked but has been
  2133. * de-chunked for filtering.
  2134. *
  2135. * Parameters :
  2136. * 1 : csp = Current client state (buffers, headers, etc...)
  2137. * 2 : header = On input, pointer to header to modify.
  2138. * On output, pointer to the modified header, or NULL
  2139. * to remove the header. This function frees the
  2140. * original string if necessary.
  2141. *
  2142. * Returns : JB_ERR_OK on success, or
  2143. * JB_ERR_MEMORY on out-of-memory error.
  2144. *
  2145. *********************************************************************/
  2146. static jb_err server_transfer_coding(struct client_state *csp, char **header)
  2147. {
  2148. /*
  2149. * Turn off pcrs and gif filtering if body compressed
  2150. */
  2151. if (strstr(*header, "gzip") || strstr(*header, "compress") || strstr(*header, "deflate"))
  2152. {
  2153. #ifdef FEATURE_ZLIB
  2154. /*
  2155. * XXX: Added to test if we could use CT_GZIP and CT_DEFLATE here.
  2156. */
  2157. log_error(LOG_LEVEL_INFO, "Marking content type for %s as CT_TABOO because of %s.",
  2158. csp->http->cmd, *header);
  2159. #endif /* def FEATURE_ZLIB */
  2160. csp->content_type = CT_TABOO;
  2161. }
  2162. /*
  2163. * Raise flag if body chunked
  2164. */
  2165. if (strstr(*header, "chunked"))
  2166. {
  2167. csp->flags |= CSP_FLAG_CHUNKED;
  2168. /*
  2169. * If the body was modified, it has been de-chunked first
  2170. * and the header must be removed.
  2171. *
  2172. * FIXME: If there is more than one transfer encoding,
  2173. * only the "chunked" part should be removed here.
  2174. */
  2175. if (csp->flags & CSP_FLAG_MODIFIED)
  2176. {
  2177. log_error(LOG_LEVEL_HEADER, "Removing: %s", *header);
  2178. freez(*header);
  2179. }
  2180. }
  2181. return JB_ERR_OK;
  2182. }
  2183. /*********************************************************************
  2184. *
  2185. * Function : server_content_encoding
  2186. *
  2187. * Description : Used to check if the content is compressed, and if
  2188. * FEATURE_ZLIB is disabled, filtering is disabled as
  2189. * well.
  2190. *
  2191. * If FEATURE_ZLIB is enabled and the compression type
  2192. * supported, the content is marked for decompression.
  2193. *
  2194. * XXX: Doesn't properly deal with multiple or with
  2195. * unsupported but unknown encodings.
  2196. * Is case-sensitive but shouldn't be.
  2197. *
  2198. * Parameters :
  2199. * 1 : csp = Current client state (buffers, headers, etc...)
  2200. * 2 : header = On input, pointer to header to modify.
  2201. * On output, pointer to the modified header, or NULL
  2202. * to remove the header. This function frees the
  2203. * original string if necessary.
  2204. *
  2205. * Returns : JB_ERR_OK on success, or
  2206. * JB_ERR_MEMORY on out-of-memory error.
  2207. *
  2208. *********************************************************************/
  2209. static jb_err server_content_encoding(struct client_state *csp, char **header)
  2210. {
  2211. #ifdef FEATURE_ZLIB
  2212. if (strstr(*header, "sdch"))
  2213. {
  2214. /*
  2215. * Shared Dictionary Compression over HTTP isn't supported,
  2216. * filtering it anyway is pretty much guaranteed to mess up
  2217. * the encoding.
  2218. */
  2219. csp->content_type |= CT_TABOO;
  2220. /*
  2221. * Log a warning if the user expects the content to be filtered.
  2222. */
  2223. if (content_filters_enabled(csp->action))
  2224. {
  2225. log_error(LOG_LEVEL_INFO,
  2226. "SDCH-compressed content detected, content filtering disabled. "
  2227. "Consider suppressing SDCH offers made by the client.");
  2228. }
  2229. }
  2230. else if (strstr(*header, "gzip"))
  2231. {
  2232. /* Mark for gzip decompression */
  2233. csp->content_type |= CT_GZIP;
  2234. }
  2235. else if (strstr(*header, "deflate"))
  2236. {
  2237. /* Mark for zlib decompression */
  2238. csp->content_type |= CT_DEFLATE;
  2239. }
  2240. else if (strstr(*header, "br"))
  2241. {
  2242. #ifdef FEATURE_BROTLI
  2243. /* Mark for Brotli decompression */
  2244. csp->content_type |= CT_BROTLI;
  2245. #else
  2246. csp->content_type |= CT_TABOO;
  2247. #endif
  2248. }
  2249. else if (strstr(*header, "compress"))
  2250. {
  2251. /*
  2252. * We can't decompress this; therefore we can't filter
  2253. * it either.
  2254. */
  2255. csp->content_type |= CT_TABOO;
  2256. }
  2257. #else /* !defined(FEATURE_ZLIB) */
  2258. /*
  2259. * XXX: Using a black list here isn't the right approach.
  2260. *
  2261. * In case of SDCH, building with zlib support isn't
  2262. * going to help.
  2263. */
  2264. if (strstr(*header, "gzip") ||
  2265. strstr(*header, "compress") ||
  2266. strstr(*header, "deflate") ||
  2267. strstr(*header, "sdch"))
  2268. {
  2269. /*
  2270. * Body is compressed, turn off pcrs and gif filtering.
  2271. */
  2272. csp->content_type |= CT_TABOO;
  2273. /*
  2274. * Log a warning if the user expects the content to be filtered.
  2275. */
  2276. if (content_filters_enabled(csp->action))
  2277. {
  2278. log_error(LOG_LEVEL_INFO,
  2279. "Compressed content detected, content filtering disabled. "
  2280. "Consider recompiling Privoxy with zlib support or "
  2281. "enable the prevent-compression action.");
  2282. }
  2283. }
  2284. #endif /* defined(FEATURE_ZLIB) */
  2285. return JB_ERR_OK;
  2286. }
  2287. #ifdef FEATURE_ZLIB
  2288. /*********************************************************************
  2289. *
  2290. * Function : server_adjust_content_encoding
  2291. *
  2292. * Description : Remove the Content-Encoding header if the
  2293. * decompression was successful and the content
  2294. * has been modified.
  2295. *
  2296. * Parameters :
  2297. * 1 : csp = Current client state (buffers, headers, etc...)
  2298. * 2 : header = On input, pointer to header to modify.
  2299. * On output, pointer to the modified header, or NULL
  2300. * to remove the header. This function frees the
  2301. * original string if necessary.
  2302. *
  2303. * Returns : JB_ERR_OK on success, or
  2304. * JB_ERR_MEMORY on out-of-memory error.
  2305. *
  2306. *********************************************************************/
  2307. static jb_err server_adjust_content_encoding(struct client_state *csp, char **header)
  2308. {
  2309. if ((csp->flags & CSP_FLAG_MODIFIED)
  2310. && ((csp->content_type & (CT_GZIP | CT_DEFLATE))
  2311. #ifdef FEATURE_BROTLI
  2312. || (csp->content_type & CT_BROTLI)
  2313. #endif
  2314. )
  2315. )
  2316. {
  2317. /*
  2318. * We successfully decompressed the content,
  2319. * and have to clean the header now, so the
  2320. * client no longer expects compressed data.
  2321. *
  2322. * XXX: There is a difference between cleaning
  2323. * and removing it completely.
  2324. */
  2325. log_error(LOG_LEVEL_HEADER, "Crunching: %s", *header);
  2326. freez(*header);
  2327. }
  2328. return JB_ERR_OK;
  2329. }
  2330. #endif /* defined(FEATURE_ZLIB) */
  2331. /*********************************************************************
  2332. *
  2333. * Function : server_adjust_content_length
  2334. *
  2335. * Description : Adjust Content-Length header if we modified
  2336. * the body.
  2337. *
  2338. * Parameters :
  2339. * 1 : csp = Current client state (buffers, headers, etc...)
  2340. * 2 : header = On input, pointer to header to modify.
  2341. * On output, pointer to the modified header, or NULL
  2342. * to remove the header. This function frees the
  2343. * original string if necessary.
  2344. *
  2345. * Returns : JB_ERR_OK on success, or
  2346. * JB_ERR_MEMORY on out-of-memory error.
  2347. *
  2348. *********************************************************************/
  2349. static jb_err server_adjust_content_length(struct client_state *csp, char **header)
  2350. {
  2351. /* Regenerate header if the content was modified. */
  2352. if (csp->flags & CSP_FLAG_MODIFIED)
  2353. {
  2354. const size_t header_length = 50;
  2355. freez(*header);
  2356. *header = malloc(header_length);
  2357. if (*header == NULL)
  2358. {
  2359. return JB_ERR_MEMORY;
  2360. }
  2361. create_content_length_header(csp->content_length, *header, header_length);
  2362. log_error(LOG_LEVEL_HEADER,
  2363. "Adjusted Content-Length to %llu", csp->content_length);
  2364. }
  2365. return JB_ERR_OK;
  2366. }
  2367. #ifdef FEATURE_CONNECTION_KEEP_ALIVE
  2368. /*********************************************************************
  2369. *
  2370. * Function : server_save_content_length
  2371. *
  2372. * Description : Save the Content-Length sent by the server.
  2373. *
  2374. * Parameters :
  2375. * 1 : csp = Current client state (buffers, headers, etc...)
  2376. * 2 : header = On input, pointer to header to modify.
  2377. * On output, pointer to the modified header, or NULL
  2378. * to remove the header. This function frees the
  2379. * original string if necessary.
  2380. *
  2381. * Returns : JB_ERR_OK on success, or
  2382. * JB_ERR_MEMORY on out-of-memory error.
  2383. *
  2384. *********************************************************************/
  2385. static jb_err server_save_content_length(struct client_state *csp, char **header)
  2386. {
  2387. unsigned long long content_length = 0;
  2388. const char *header_value;
  2389. assert(*(*header+14) == ':');
  2390. header_value = *header + 15;
  2391. if (JB_ERR_OK != get_content_length(header_value, &content_length))
  2392. {
  2393. log_error(LOG_LEVEL_ERROR, "Crunching invalid header: %s", *header);
  2394. freez(*header);
  2395. }
  2396. else
  2397. {
  2398. csp->expected_content_length = content_length;
  2399. csp->flags |= CSP_FLAG_SERVER_CONTENT_LENGTH_SET;
  2400. csp->flags |= CSP_FLAG_CONTENT_LENGTH_SET;
  2401. }
  2402. return JB_ERR_OK;
  2403. }
  2404. #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
  2405. /*********************************************************************
  2406. *
  2407. * Function : server_content_md5
  2408. *
  2409. * Description : Crumble any Content-MD5 headers if the document was
  2410. * modified. FIXME: Should we re-compute instead?
  2411. *
  2412. * Parameters :
  2413. * 1 : csp = Current client state (buffers, headers, etc...)
  2414. * 2 : header = On input, pointer to header to modify.
  2415. * On output, pointer to the modified header, or NULL
  2416. * to remove the header. This function frees the
  2417. * original string if necessary.
  2418. *
  2419. * Returns : JB_ERR_OK on success, or
  2420. * JB_ERR_MEMORY on out-of-memory error.
  2421. *
  2422. *********************************************************************/
  2423. static jb_err server_content_md5(struct client_state *csp, char **header)
  2424. {
  2425. if (csp->flags & CSP_FLAG_MODIFIED)
  2426. {
  2427. log_error(LOG_LEVEL_HEADER, "Crunching Content-MD5");
  2428. freez(*header);
  2429. }
  2430. return JB_ERR_OK;
  2431. }
  2432. /*********************************************************************
  2433. *
  2434. * Function : server_content_disposition
  2435. *
  2436. * Description : If enabled, blocks or modifies the "Content-Disposition" header.
  2437. * Called from `sed'.
  2438. *
  2439. * Parameters :
  2440. * 1 : csp = Current client state (buffers, headers, etc...)
  2441. * 2 : header = On input, pointer to header to modify.
  2442. * On output, pointer to the modified header, or NULL
  2443. * to remove the header. This function frees the
  2444. * original string if necessary.
  2445. *
  2446. * Returns : JB_ERR_OK on success, or
  2447. * JB_ERR_MEMORY on out-of-memory error.
  2448. *
  2449. *********************************************************************/
  2450. static jb_err server_content_disposition(struct client_state *csp, char **header)
  2451. {
  2452. const char *newval;
  2453. /*
  2454. * Are we messing with the Content-Disposition header?
  2455. */
  2456. if ((csp->action->flags & ACTION_HIDE_CONTENT_DISPOSITION) == 0)
  2457. {
  2458. /* Me tinks not */
  2459. return JB_ERR_OK;
  2460. }
  2461. newval = csp->action->string[ACTION_STRING_CONTENT_DISPOSITION];
  2462. if ((newval == NULL) || (0 == strcmpic(newval, "block")))
  2463. {
  2464. /*
  2465. * Blocking content-disposition header
  2466. */
  2467. log_error(LOG_LEVEL_HEADER, "Crunching %s!", *header);
  2468. freez(*header);
  2469. return JB_ERR_OK;
  2470. }
  2471. else
  2472. {
  2473. /*
  2474. * Replacing Content-Disposition header
  2475. */
  2476. freez(*header);
  2477. *header = strdup("Content-Disposition: ");
  2478. string_append(header, newval);
  2479. if (*header != NULL)
  2480. {
  2481. log_error(LOG_LEVEL_HEADER,
  2482. "Content-Disposition header crunched and replaced with: %s", *header);
  2483. }
  2484. }
  2485. return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
  2486. }
  2487. /*********************************************************************
  2488. *
  2489. * Function : server_last_modified
  2490. *
  2491. * Description : Changes Last-Modified header to the actual date
  2492. * to help hide-if-modified-since.
  2493. * Called from `sed'.
  2494. *
  2495. * Parameters :
  2496. * 1 : csp = Current client state (buffers, headers, etc...)
  2497. * 2 : header = On input, pointer to header to modify.
  2498. * On output, pointer to the modified header, or NULL
  2499. * to remove the header. This function frees the
  2500. * original string if necessary.
  2501. *
  2502. * Returns : JB_ERR_OK on success, or
  2503. * JB_ERR_MEMORY on out-of-memory error.
  2504. *
  2505. *********************************************************************/
  2506. static jb_err server_last_modified(struct client_state *csp, char **header)
  2507. {
  2508. const char *newval;
  2509. time_t last_modified;
  2510. char newheader[50];
  2511. /*
  2512. * Are we messing with the Last-Modified header?
  2513. */
  2514. if ((csp->action->flags & ACTION_OVERWRITE_LAST_MODIFIED) == 0)
  2515. {
  2516. /*Nope*/
  2517. return JB_ERR_OK;
  2518. }
  2519. newval = csp->action->string[ACTION_STRING_LAST_MODIFIED];
  2520. if (0 == strcmpic(newval, "block"))
  2521. {
  2522. /*
  2523. * Blocking Last-Modified header. Useless but why not.
  2524. */
  2525. log_error(LOG_LEVEL_HEADER, "Crunching %s!", *header);
  2526. freez(*header);
  2527. return JB_ERR_OK;
  2528. }
  2529. else if (0 == strcmpic(newval, "reset-to-request-time"))
  2530. {
  2531. /*
  2532. * Setting Last-Modified Header to now.
  2533. */
  2534. char buf[30];
  2535. get_http_time(0, buf, sizeof(buf));
  2536. freez(*header);
  2537. *header = strdup("Last-Modified: ");
  2538. string_append(header, buf);
  2539. if (*header == NULL)
  2540. {
  2541. log_error(LOG_LEVEL_HEADER, "Insufficient memory. Last-Modified header got lost, boohoo.");
  2542. }
  2543. else
  2544. {
  2545. log_error(LOG_LEVEL_HEADER, "Reset to present time: %s", *header);
  2546. }
  2547. }
  2548. else if (0 == strcmpic(newval, "randomize"))
  2549. {
  2550. log_error(LOG_LEVEL_HEADER, "Randomizing: %s", *header);
  2551. if (JB_ERR_OK != parse_time_header(*header, &last_modified))
  2552. {
  2553. log_error(LOG_LEVEL_HEADER,
  2554. "Couldn't parse time in %s (crunching!)", *header);
  2555. freez(*header);
  2556. }
  2557. else
  2558. {
  2559. time_t now;
  2560. struct tm *timeptr = NULL;
  2561. long int rtime;
  2562. struct tm gmt;
  2563. now = time(NULL);
  2564. rtime = (long int)difftime(now, last_modified);
  2565. if (rtime)
  2566. {
  2567. long int days, hours, minutes, seconds;
  2568. const int negative_delta = (rtime < 0);
  2569. if (negative_delta)
  2570. {
  2571. rtime *= -1;
  2572. log_error(LOG_LEVEL_HEADER, "Server time in the future.");
  2573. }
  2574. rtime = pick_from_range(rtime);
  2575. if (negative_delta)
  2576. {
  2577. rtime *= -1;
  2578. }
  2579. last_modified += rtime;
  2580. timeptr = privoxy_gmtime_r(&last_modified, &gmt);
  2581. if ((NULL == timeptr) || !strftime(newheader,
  2582. sizeof(newheader), "%a, %d %b %Y %H:%M:%S GMT", timeptr))
  2583. {
  2584. log_error(LOG_LEVEL_ERROR,
  2585. "Randomizing '%s' failed. Crunching the header without replacement.",
  2586. *header);
  2587. freez(*header);
  2588. return JB_ERR_OK;
  2589. }
  2590. freez(*header);
  2591. *header = strdup("Last-Modified: ");
  2592. string_append(header, newheader);
  2593. if (*header == NULL)
  2594. {
  2595. log_error(LOG_LEVEL_ERROR, "Insufficient memory, header crunched without replacement.");
  2596. return JB_ERR_MEMORY;
  2597. }
  2598. days = rtime / (3600 * 24);
  2599. hours = rtime / 3600 % 24;
  2600. minutes = rtime / 60 % 60;
  2601. seconds = rtime % 60;
  2602. log_error(LOG_LEVEL_HEADER,
  2603. "Randomized: %s (added %ld da%s %ld hou%s %ld minut%s %ld second%s",
  2604. *header, days, (days == 1) ? "y" : "ys", hours, (hours == 1) ? "r" : "rs",
  2605. minutes, (minutes == 1) ? "e" : "es", seconds, (seconds == 1) ? ")" : "s)");
  2606. }
  2607. else
  2608. {
  2609. log_error(LOG_LEVEL_HEADER, "Randomized ... or not. No time difference to work with.");
  2610. }
  2611. }
  2612. }
  2613. return JB_ERR_OK;
  2614. }
  2615. /*********************************************************************
  2616. *
  2617. * Function : client_accept_encoding
  2618. *
  2619. * Description : Rewrite the client's Accept-Encoding header so that
  2620. * if doesn't allow compression, if the action applies.
  2621. * Note: For HTTP/1.0 the absence of the header is enough.
  2622. *
  2623. * Parameters :
  2624. * 1 : csp = Current client state (buffers, headers, etc...)
  2625. * 2 : header = On input, pointer to header to modify.
  2626. * On output, pointer to the modified header, or NULL
  2627. * to remove the header. This function frees the
  2628. * original string if necessary.
  2629. *
  2630. * Returns : JB_ERR_OK on success, or
  2631. * JB_ERR_MEMORY on out-of-memory error.
  2632. *
  2633. *********************************************************************/
  2634. static jb_err client_accept_encoding(struct client_state *csp, char **header)
  2635. {
  2636. #ifdef FEATURE_COMPRESSION
  2637. if ((csp->config->feature_flags & RUNTIME_FEATURE_COMPRESSION)
  2638. && strstr(*header, "deflate"))
  2639. {
  2640. csp->flags |= CSP_FLAG_CLIENT_SUPPORTS_DEFLATE;
  2641. }
  2642. #endif
  2643. if ((csp->action->flags & ACTION_NO_COMPRESSION) != 0)
  2644. {
  2645. log_error(LOG_LEVEL_HEADER, "Suppressed offer to compress content");
  2646. freez(*header);
  2647. }
  2648. return JB_ERR_OK;
  2649. }
  2650. /*********************************************************************
  2651. *
  2652. * Function : client_te
  2653. *
  2654. * Description : Rewrite the client's TE header so that
  2655. * if doesn't allow compression, if the action applies.
  2656. *
  2657. * Parameters :
  2658. * 1 : csp = Current client state (buffers, headers, etc...)
  2659. * 2 : header = On input, pointer to header to modify.
  2660. * On output, pointer to the modified header, or NULL
  2661. * to remove the header. This function frees the
  2662. * original string if necessary.
  2663. *
  2664. * Returns : JB_ERR_OK on success, or
  2665. * JB_ERR_MEMORY on out-of-memory error.
  2666. *
  2667. *********************************************************************/
  2668. static jb_err client_te(struct client_state *csp, char **header)
  2669. {
  2670. if ((csp->action->flags & ACTION_NO_COMPRESSION) != 0)
  2671. {
  2672. freez(*header);
  2673. log_error(LOG_LEVEL_HEADER, "Suppressed offer to compress transfer");
  2674. }
  2675. return JB_ERR_OK;
  2676. }
  2677. /*********************************************************************
  2678. *
  2679. * Function : client_referrer
  2680. *
  2681. * Description : Handle the "referer" config setting properly.
  2682. * Called from `sed'.
  2683. *
  2684. * Parameters :
  2685. * 1 : csp = Current client state (buffers, headers, etc...)
  2686. * 2 : header = On input, pointer to header to modify.
  2687. * On output, pointer to the modified header, or NULL
  2688. * to remove the header. This function frees the
  2689. * original string if necessary.
  2690. *
  2691. * Returns : JB_ERR_OK on success, or
  2692. * JB_ERR_MEMORY on out-of-memory error.
  2693. *
  2694. *********************************************************************/
  2695. static jb_err client_referrer(struct client_state *csp, char **header)
  2696. {
  2697. const char *parameter;
  2698. /* booleans for parameters we have to check multiple times */
  2699. int parameter_conditional_block;
  2700. int parameter_conditional_forge;
  2701. #ifdef FEATURE_FORCE_LOAD
  2702. /*
  2703. * Since the referrer can include the prefix even
  2704. * if the request itself is non-forced, we must
  2705. * clean it unconditionally.
  2706. *
  2707. * XXX: strclean is too broad
  2708. */
  2709. strclean(*header, FORCE_PREFIX);
  2710. #endif /* def FEATURE_FORCE_LOAD */
  2711. if ((csp->action->flags & ACTION_HIDE_REFERER) == 0)
  2712. {
  2713. /* Nothing left to do */
  2714. return JB_ERR_OK;
  2715. }
  2716. parameter = csp->action->string[ACTION_STRING_REFERER];
  2717. assert(parameter != NULL);
  2718. parameter_conditional_block = (0 == strcmpic(parameter, "conditional-block"));
  2719. parameter_conditional_forge = (0 == strcmpic(parameter, "conditional-forge"));
  2720. if (!parameter_conditional_block && !parameter_conditional_forge)
  2721. {
  2722. /*
  2723. * As conditional-block and conditional-forge are the only
  2724. * parameters that rely on the original referrer, we can
  2725. * remove it now for all the others.
  2726. */
  2727. freez(*header);
  2728. }
  2729. if (0 == strcmpic(parameter, "block"))
  2730. {
  2731. log_error(LOG_LEVEL_HEADER, "Referer crunched!");
  2732. return JB_ERR_OK;
  2733. }
  2734. else if (parameter_conditional_block || parameter_conditional_forge)
  2735. {
  2736. return handle_conditional_hide_referrer_parameter(header,
  2737. csp->http->hostport, parameter_conditional_block);
  2738. }
  2739. else if (0 == strcmpic(parameter, "forge"))
  2740. {
  2741. return create_forged_referrer(header, csp->http->hostport);
  2742. }
  2743. else
  2744. {
  2745. /* interpret parameter as user-supplied referer to fake */
  2746. return create_fake_referrer(header, parameter);
  2747. }
  2748. }
  2749. /*********************************************************************
  2750. *
  2751. * Function : client_accept_language
  2752. *
  2753. * Description : Handle the "Accept-Language" config setting properly.
  2754. * Called from `sed'.
  2755. *
  2756. * Parameters :
  2757. * 1 : csp = Current client state (buffers, headers, etc...)
  2758. * 2 : header = On input, pointer to header to modify.
  2759. * On output, pointer to the modified header, or NULL
  2760. * to remove the header. This function frees the
  2761. * original string if necessary.
  2762. *
  2763. * Returns : JB_ERR_OK on success, or
  2764. * JB_ERR_MEMORY on out-of-memory error.
  2765. *
  2766. *********************************************************************/
  2767. static jb_err client_accept_language(struct client_state *csp, char **header)
  2768. {
  2769. const char *newval;
  2770. /*
  2771. * Are we messing with the Accept-Language?
  2772. */
  2773. if ((csp->action->flags & ACTION_HIDE_ACCEPT_LANGUAGE) == 0)
  2774. {
  2775. /*I don't think so*/
  2776. return JB_ERR_OK;
  2777. }
  2778. newval = csp->action->string[ACTION_STRING_LANGUAGE];
  2779. if ((newval == NULL) || (0 == strcmpic(newval, "block")))
  2780. {
  2781. /*
  2782. * Blocking Accept-Language header
  2783. */
  2784. log_error(LOG_LEVEL_HEADER, "Crunching Accept-Language!");
  2785. freez(*header);
  2786. return JB_ERR_OK;
  2787. }
  2788. else
  2789. {
  2790. /*
  2791. * Replacing Accept-Language header
  2792. */
  2793. freez(*header);
  2794. *header = strdup("Accept-Language: ");
  2795. string_append(header, newval);
  2796. if (*header == NULL)
  2797. {
  2798. log_error(LOG_LEVEL_ERROR,
  2799. "Insufficient memory. Accept-Language header crunched without replacement.");
  2800. }
  2801. else
  2802. {
  2803. log_error(LOG_LEVEL_HEADER,
  2804. "Accept-Language header crunched and replaced with: %s", *header);
  2805. }
  2806. }
  2807. return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
  2808. }
  2809. /*********************************************************************
  2810. *
  2811. * Function : crunch_client_header
  2812. *
  2813. * Description : Crunch client header if it matches a string supplied by the
  2814. * user. Called from `sed'.
  2815. *
  2816. * Parameters :
  2817. * 1 : csp = Current client state (buffers, headers, etc...)
  2818. * 2 : header = On input, pointer to header to modify.
  2819. * On output, pointer to the modified header, or NULL
  2820. * to remove the header. This function frees the
  2821. * original string if necessary.
  2822. *
  2823. * Returns : JB_ERR_OK on success and always succeeds
  2824. *
  2825. *********************************************************************/
  2826. static jb_err crunch_client_header(struct client_state *csp, char **header)
  2827. {
  2828. const char *crunch_pattern;
  2829. /* Do we feel like crunching? */
  2830. if ((csp->action->flags & ACTION_CRUNCH_CLIENT_HEADER))
  2831. {
  2832. crunch_pattern = csp->action->string[ACTION_STRING_CLIENT_HEADER];
  2833. /* Is the current header the lucky one? */
  2834. if (strstr(*header, crunch_pattern))
  2835. {
  2836. log_error(LOG_LEVEL_HEADER, "Crunching client header: %s (contains: %s)", *header, crunch_pattern);
  2837. freez(*header);
  2838. }
  2839. }
  2840. return JB_ERR_OK;
  2841. }
  2842. /*********************************************************************
  2843. *
  2844. * Function : client_uagent
  2845. *
  2846. * Description : Handle the "user-agent" config setting properly
  2847. * and remember its original value to enable browser
  2848. * bug workarounds. Called from `sed'.
  2849. *
  2850. * Parameters :
  2851. * 1 : csp = Current client state (buffers, headers, etc...)
  2852. * 2 : header = On input, pointer to header to modify.
  2853. * On output, pointer to the modified header, or NULL
  2854. * to remove the header. This function frees the
  2855. * original string if necessary.
  2856. *
  2857. * Returns : JB_ERR_OK on success, or
  2858. * JB_ERR_MEMORY on out-of-memory error.
  2859. *
  2860. *********************************************************************/
  2861. static jb_err client_uagent(struct client_state *csp, char **header)
  2862. {
  2863. const char *newval;
  2864. if ((csp->action->flags & ACTION_HIDE_USER_AGENT) == 0)
  2865. {
  2866. return JB_ERR_OK;
  2867. }
  2868. newval = csp->action->string[ACTION_STRING_USER_AGENT];
  2869. if (newval == NULL)
  2870. {
  2871. return JB_ERR_OK;
  2872. }
  2873. freez(*header);
  2874. *header = strdup("User-Agent: ");
  2875. string_append(header, newval);
  2876. log_error(LOG_LEVEL_HEADER, "Modified: %s", *header);
  2877. return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
  2878. }
  2879. /*********************************************************************
  2880. *
  2881. * Function : client_ua
  2882. *
  2883. * Description : Handle "ua-" headers properly. Called from `sed'.
  2884. *
  2885. * Parameters :
  2886. * 1 : csp = Current client state (buffers, headers, etc...)
  2887. * 2 : header = On input, pointer to header to modify.
  2888. * On output, pointer to the modified header, or NULL
  2889. * to remove the header. This function frees the
  2890. * original string if necessary.
  2891. *
  2892. * Returns : JB_ERR_OK on success, or
  2893. * JB_ERR_MEMORY on out-of-memory error.
  2894. *
  2895. *********************************************************************/
  2896. static jb_err client_ua(struct client_state *csp, char **header)
  2897. {
  2898. if ((csp->action->flags & ACTION_HIDE_USER_AGENT) != 0)
  2899. {
  2900. log_error(LOG_LEVEL_HEADER, "crunched User-Agent!");
  2901. freez(*header);
  2902. }
  2903. return JB_ERR_OK;
  2904. }
  2905. /*********************************************************************
  2906. *
  2907. * Function : client_from
  2908. *
  2909. * Description : Handle the "from" config setting properly.
  2910. * Called from `sed'.
  2911. *
  2912. * Parameters :
  2913. * 1 : csp = Current client state (buffers, headers, etc...)
  2914. * 2 : header = On input, pointer to header to modify.
  2915. * On output, pointer to the modified header, or NULL
  2916. * to remove the header. This function frees the
  2917. * original string if necessary.
  2918. *
  2919. * Returns : JB_ERR_OK on success, or
  2920. * JB_ERR_MEMORY on out-of-memory error.
  2921. *
  2922. *********************************************************************/
  2923. static jb_err client_from(struct client_state *csp, char **header)
  2924. {
  2925. const char *newval;
  2926. if ((csp->action->flags & ACTION_HIDE_FROM) == 0)
  2927. {
  2928. return JB_ERR_OK;
  2929. }
  2930. freez(*header);
  2931. newval = csp->action->string[ACTION_STRING_FROM];
  2932. /*
  2933. * Are we blocking the e-mail address?
  2934. */
  2935. if ((newval == NULL) || (0 == strcmpic(newval, "block")))
  2936. {
  2937. log_error(LOG_LEVEL_HEADER, "crunched From!");
  2938. return JB_ERR_OK;
  2939. }
  2940. log_error(LOG_LEVEL_HEADER, " modified");
  2941. *header = strdup("From: ");
  2942. string_append(header, newval);
  2943. return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
  2944. }
  2945. /*********************************************************************
  2946. *
  2947. * Function : client_send_cookie
  2948. *
  2949. * Description : Crunches the "cookie" header if necessary.
  2950. * Called from `sed'.
  2951. *
  2952. * XXX: Stupid name, doesn't send squat.
  2953. *
  2954. * Parameters :
  2955. * 1 : csp = Current client state (buffers, headers, etc...)
  2956. * 2 : header = On input, pointer to header to modify.
  2957. * On output, pointer to the modified header, or NULL
  2958. * to remove the header. This function frees the
  2959. * original string if necessary.
  2960. *
  2961. * Returns : JB_ERR_OK on success, or
  2962. * JB_ERR_MEMORY on out-of-memory error.
  2963. *
  2964. *********************************************************************/
  2965. static jb_err client_send_cookie(struct client_state *csp, char **header)
  2966. {
  2967. if (csp->action->flags & ACTION_CRUNCH_OUTGOING_COOKIES)
  2968. {
  2969. log_error(LOG_LEVEL_HEADER, "Crunched outgoing cookie: %s", *header);
  2970. freez(*header);
  2971. }
  2972. return JB_ERR_OK;
  2973. }
  2974. /*********************************************************************
  2975. *
  2976. * Function : client_x_forwarded
  2977. *
  2978. * Description : Handle the "x-forwarded-for" config setting properly,
  2979. * also used in the add_client_headers list. Called from `sed'.
  2980. *
  2981. * Parameters :
  2982. * 1 : csp = Current client state (buffers, headers, etc...)
  2983. * 2 : header = On input, pointer to header to modify.
  2984. * On output, pointer to the modified header, or NULL
  2985. * to remove the header. This function frees the
  2986. * original string if necessary.
  2987. *
  2988. * Returns : JB_ERR_OK on success, or
  2989. * JB_ERR_MEMORY on out-of-memory error.
  2990. *
  2991. *********************************************************************/
  2992. jb_err client_x_forwarded(struct client_state *csp, char **header)
  2993. {
  2994. if (0 != (csp->action->flags & ACTION_CHANGE_X_FORWARDED_FOR))
  2995. {
  2996. const char *parameter = csp->action->string[ACTION_STRING_CHANGE_X_FORWARDED_FOR];
  2997. if (0 == strcmpic(parameter, "block"))
  2998. {
  2999. freez(*header);
  3000. log_error(LOG_LEVEL_HEADER, "crunched x-forwarded-for!");
  3001. }
  3002. else if (0 == strcmpic(parameter, "add"))
  3003. {
  3004. string_append(header, ", ");
  3005. string_append(header, csp->ip_addr_str);
  3006. if (*header == NULL)
  3007. {
  3008. return JB_ERR_MEMORY;
  3009. }
  3010. log_error(LOG_LEVEL_HEADER,
  3011. "Appended client IP address to %s", *header);
  3012. csp->flags |= CSP_FLAG_X_FORWARDED_FOR_APPENDED;
  3013. }
  3014. else
  3015. {
  3016. log_error(LOG_LEVEL_FATAL,
  3017. "Invalid change-x-forwarded-for parameter: '%s'", parameter);
  3018. }
  3019. }
  3020. return JB_ERR_OK;
  3021. }
  3022. /*********************************************************************
  3023. *
  3024. * Function : client_max_forwards
  3025. *
  3026. * Description : If the HTTP method is OPTIONS or TRACE, subtract one
  3027. * from the value of the Max-Forwards header field.
  3028. *
  3029. * Parameters :
  3030. * 1 : csp = Current client state (buffers, headers, etc...)
  3031. * 2 : header = On input, pointer to header to modify.
  3032. * On output, pointer to the modified header, or NULL
  3033. * to remove the header. This function frees the
  3034. * original string if necessary.
  3035. *
  3036. * Returns : JB_ERR_OK on success, or
  3037. * JB_ERR_MEMORY on out-of-memory error.
  3038. *
  3039. *********************************************************************/
  3040. static jb_err client_max_forwards(struct client_state *csp, char **header)
  3041. {
  3042. int max_forwards;
  3043. if ((0 == strcmpic(csp->http->gpc, "trace")) ||
  3044. (0 == strcmpic(csp->http->gpc, "options")))
  3045. {
  3046. assert(*(*header+12) == ':');
  3047. if (1 == sscanf(*header+12, ": %d", &max_forwards))
  3048. {
  3049. if (max_forwards > 0)
  3050. {
  3051. snprintf(*header, strlen(*header)+1, "Max-Forwards: %d", --max_forwards);
  3052. log_error(LOG_LEVEL_HEADER,
  3053. "Max-Forwards value for %s request reduced to %d.",
  3054. csp->http->gpc, max_forwards);
  3055. }
  3056. else if (max_forwards < 0)
  3057. {
  3058. log_error(LOG_LEVEL_ERROR, "Crunching invalid header: %s", *header);
  3059. freez(*header);
  3060. }
  3061. }
  3062. else
  3063. {
  3064. log_error(LOG_LEVEL_ERROR, "Crunching invalid header: %s", *header);
  3065. freez(*header);
  3066. }
  3067. }
  3068. return JB_ERR_OK;
  3069. }
  3070. /*********************************************************************
  3071. *
  3072. * Function : client_host
  3073. *
  3074. * Description : If the request URI did not contain host and
  3075. * port information, parse and evaluate the Host
  3076. * header field.
  3077. *
  3078. * Parameters :
  3079. * 1 : csp = Current client state (buffers, headers, etc...)
  3080. * 2 : header = On input, pointer to header to modify.
  3081. * On output, pointer to the modified header, or NULL
  3082. * to remove the header. This function frees the
  3083. * original string if necessary.
  3084. *
  3085. * Returns : JB_ERR_OK on success, or
  3086. * JB_ERR_MEMORY on out-of-memory error.
  3087. *
  3088. *********************************************************************/
  3089. static jb_err client_host(struct client_state *csp, char **header)
  3090. {
  3091. char *p, *q;
  3092. if (strlen(*header) < 7)
  3093. {
  3094. log_error(LOG_LEVEL_HEADER, "Removing empty Host header");
  3095. freez(*header);
  3096. return JB_ERR_OK;
  3097. }
  3098. if (!csp->http->hostport || (*csp->http->hostport == '*') ||
  3099. *csp->http->hostport == ' ' || *csp->http->hostport == '\0')
  3100. {
  3101. p = strdup_or_die((*header)+6);
  3102. chomp(p);
  3103. q = strdup_or_die(p);
  3104. freez(csp->http->hostport);
  3105. csp->http->hostport = p;
  3106. freez(csp->http->host);
  3107. csp->http->host = q;
  3108. q = strchr(csp->http->host, ':');
  3109. if (q != NULL)
  3110. {
  3111. /* Terminate hostname and evaluate port string */
  3112. *q++ = '\0';
  3113. csp->http->port = atoi(q);
  3114. }
  3115. else
  3116. {
  3117. csp->http->port = csp->http->ssl ? 443 : 80;
  3118. }
  3119. log_error(LOG_LEVEL_HEADER, "New host and port from Host field: %s = %s:%d",
  3120. csp->http->hostport, csp->http->host, csp->http->port);
  3121. }
  3122. /* Signal client_host_adder() to return right away */
  3123. csp->flags |= CSP_FLAG_HOST_HEADER_IS_SET;
  3124. return JB_ERR_OK;
  3125. }
  3126. /*********************************************************************
  3127. *
  3128. * Function : client_if_modified_since
  3129. *
  3130. * Description : Remove or modify the If-Modified-Since header.
  3131. *
  3132. * Parameters :
  3133. * 1 : csp = Current client state (buffers, headers, etc...)
  3134. * 2 : header = On input, pointer to header to modify.
  3135. * On output, pointer to the modified header, or NULL
  3136. * to remove the header. This function frees the
  3137. * original string if necessary.
  3138. *
  3139. * Returns : JB_ERR_OK on success, or
  3140. * JB_ERR_MEMORY on out-of-memory error.
  3141. *
  3142. *********************************************************************/
  3143. static jb_err client_if_modified_since(struct client_state *csp, char **header)
  3144. {
  3145. char newheader[50];
  3146. struct tm gmt;
  3147. struct tm *timeptr = NULL;
  3148. time_t tm = 0;
  3149. const char *newval;
  3150. char * endptr;
  3151. if (0 == strcmpic(*header, "If-Modified-Since: Wed, 08 Jun 1955 12:00:00 GMT"))
  3152. {
  3153. /*
  3154. * The client got an error message because of a temporary problem,
  3155. * the problem is gone and the client now tries to revalidate our
  3156. * error message on the real server. The revalidation would always
  3157. * end with the transmission of the whole document and there is
  3158. * no need to expose the bogus If-Modified-Since header.
  3159. */
  3160. log_error(LOG_LEVEL_HEADER, "Crunching useless If-Modified-Since header.");
  3161. freez(*header);
  3162. }
  3163. else if (csp->action->flags & ACTION_HIDE_IF_MODIFIED_SINCE)
  3164. {
  3165. newval = csp->action->string[ACTION_STRING_IF_MODIFIED_SINCE];
  3166. if ((0 == strcmpic(newval, "block")))
  3167. {
  3168. log_error(LOG_LEVEL_HEADER, "Crunching %s", *header);
  3169. freez(*header);
  3170. }
  3171. else /* add random value */
  3172. {
  3173. if (JB_ERR_OK != parse_time_header(*header, &tm))
  3174. {
  3175. log_error(LOG_LEVEL_HEADER,
  3176. "Couldn't parse time in %s (crunching!)", *header);
  3177. freez(*header);
  3178. }
  3179. else
  3180. {
  3181. long int hours, minutes, seconds;
  3182. long int rtime = strtol(newval, &endptr, 0);
  3183. const int negative_range = (rtime < 0);
  3184. if (rtime)
  3185. {
  3186. log_error(LOG_LEVEL_HEADER, "Randomizing: %s (random range: %ld minut%s)",
  3187. *header, rtime, (rtime == 1 || rtime == -1) ? "e": "es");
  3188. if (negative_range)
  3189. {
  3190. rtime *= -1;
  3191. }
  3192. rtime *= 60;
  3193. rtime = pick_from_range(rtime);
  3194. }
  3195. else
  3196. {
  3197. log_error(LOG_LEVEL_ERROR,
  3198. "Random range is 0. Assuming time transformation test.");
  3199. }
  3200. tm += rtime * (negative_range ? -1 : 1);
  3201. timeptr = privoxy_gmtime_r(&tm, &gmt);
  3202. if ((NULL == timeptr) || !strftime(newheader,
  3203. sizeof(newheader), "%a, %d %b %Y %H:%M:%S GMT", timeptr))
  3204. {
  3205. log_error(LOG_LEVEL_ERROR,
  3206. "Randomizing '%s' failed. Crunching the header without replacement.",
  3207. *header);
  3208. freez(*header);
  3209. return JB_ERR_OK;
  3210. }
  3211. freez(*header);
  3212. *header = strdup("If-Modified-Since: ");
  3213. string_append(header, newheader);
  3214. if (*header == NULL)
  3215. {
  3216. log_error(LOG_LEVEL_HEADER, "Insufficient memory, header crunched without replacement.");
  3217. return JB_ERR_MEMORY;
  3218. }
  3219. hours = rtime / 3600;
  3220. minutes = rtime / 60 % 60;
  3221. seconds = rtime % 60;
  3222. log_error(LOG_LEVEL_HEADER,
  3223. "Randomized: %s (%s %ld hou%s %ld minut%s %ld second%s",
  3224. *header, (negative_range) ? "subtracted" : "added", hours,
  3225. (hours == 1) ? "r" : "rs", minutes, (minutes == 1) ? "e" : "es",
  3226. seconds, (seconds == 1) ? ")" : "s)");
  3227. }
  3228. }
  3229. }
  3230. return JB_ERR_OK;
  3231. }
  3232. /*********************************************************************
  3233. *
  3234. * Function : client_if_none_match
  3235. *
  3236. * Description : Remove the If-None-Match header.
  3237. *
  3238. * Parameters :
  3239. * 1 : csp = Current client state (buffers, headers, etc...)
  3240. * 2 : header = On input, pointer to header to modify.
  3241. * On output, pointer to the modified header, or NULL
  3242. * to remove the header. This function frees the
  3243. * original string if necessary.
  3244. *
  3245. * Returns : JB_ERR_OK on success, or
  3246. * JB_ERR_MEMORY on out-of-memory error.
  3247. *
  3248. *********************************************************************/
  3249. static jb_err client_if_none_match(struct client_state *csp, char **header)
  3250. {
  3251. if (csp->action->flags & ACTION_CRUNCH_IF_NONE_MATCH)
  3252. {
  3253. log_error(LOG_LEVEL_HEADER, "Crunching %s", *header);
  3254. freez(*header);
  3255. }
  3256. return JB_ERR_OK;
  3257. }
  3258. /*********************************************************************
  3259. *
  3260. * Function : client_x_filter
  3261. *
  3262. * Description : Disables filtering if the client set "X-Filter: No".
  3263. * Called from `sed'.
  3264. *
  3265. * Parameters :
  3266. * 1 : csp = Current client state (buffers, headers, etc...)
  3267. * 2 : header = On input, pointer to header to modify.
  3268. * On output, pointer to the modified header, or NULL
  3269. * to remove the header. This function frees the
  3270. * original string if necessary.
  3271. *
  3272. * Returns : JB_ERR_OK on success
  3273. *
  3274. *********************************************************************/
  3275. jb_err client_x_filter(struct client_state *csp, char **header)
  3276. {
  3277. if (0 == strcmpic(*header, "X-Filter: No"))
  3278. {
  3279. if (!(csp->config->feature_flags & RUNTIME_FEATURE_HTTP_TOGGLE))
  3280. {
  3281. log_error(LOG_LEVEL_INFO, "Ignored the client's request to fetch without filtering.");
  3282. }
  3283. else
  3284. {
  3285. if (csp->action->flags & ACTION_FORCE_TEXT_MODE)
  3286. {
  3287. log_error(LOG_LEVEL_HEADER,
  3288. "force-text-mode overruled the client's request to fetch without filtering!");
  3289. }
  3290. else
  3291. {
  3292. csp->content_type = CT_TABOO; /* XXX: This hack shouldn't be necessary */
  3293. csp->flags |= CSP_FLAG_NO_FILTERING;
  3294. log_error(LOG_LEVEL_HEADER, "Accepted the client's request to fetch without filtering.");
  3295. }
  3296. log_error(LOG_LEVEL_HEADER, "Crunching %s", *header);
  3297. freez(*header);
  3298. }
  3299. }
  3300. return JB_ERR_OK;
  3301. }
  3302. /*********************************************************************
  3303. *
  3304. * Function : client_range
  3305. *
  3306. * Description : Removes Range, Request-Range and If-Range headers if
  3307. * content filtering is enabled and the range doesn't
  3308. * start at byte 0.
  3309. *
  3310. * If the client's version of the document has been
  3311. * altered by Privoxy, the server could interpret the
  3312. * range differently than the client intended in which
  3313. * case the user could end up with corrupted content.
  3314. *
  3315. * If the range starts at byte 0 this isn't an issue
  3316. * so the header can pass. Partial requests like this
  3317. * are used to render preview images for videos without
  3318. * downloading the whole video.
  3319. *
  3320. * While HTTP doesn't require that range requests are
  3321. * honoured and the client could simply abort the download
  3322. * after receiving a sufficient amount of data, various
  3323. * clients don't handle complete responses to range
  3324. * requests gracefully and emit misleading error messages
  3325. * instead.
  3326. *
  3327. * Parameters :
  3328. * 1 : csp = Current client state (buffers, headers, etc...)
  3329. * 2 : header = On input, pointer to header to modify.
  3330. * On output, pointer to the modified header, or NULL
  3331. * to remove the header. This function frees the
  3332. * original string if necessary.
  3333. *
  3334. * Returns : JB_ERR_OK
  3335. *
  3336. *********************************************************************/
  3337. static jb_err client_range(struct client_state *csp, char **header)
  3338. {
  3339. if (content_filters_enabled(csp->action)
  3340. && (0 != strncmpic(strstr(*header, ":"), ": bytes=0-", 10)))
  3341. {
  3342. log_error(LOG_LEVEL_HEADER, "Content filtering is enabled."
  3343. " Crunching: \'%s\' to prevent range-mismatch problems.", *header);
  3344. freez(*header);
  3345. }
  3346. return JB_ERR_OK;
  3347. }
  3348. /* the following functions add headers directly to the header list */
  3349. /*********************************************************************
  3350. *
  3351. * Function : client_host_adder
  3352. *
  3353. * Description : Adds the Host: header field if it is missing.
  3354. * Called from `sed'.
  3355. *
  3356. * Parameters :
  3357. * 1 : csp = Current client state (buffers, headers, etc...)
  3358. *
  3359. * Returns : JB_ERR_OK on success, or
  3360. * JB_ERR_MEMORY on out-of-memory error.
  3361. *
  3362. *********************************************************************/
  3363. static jb_err client_host_adder(struct client_state *csp)
  3364. {
  3365. char *p;
  3366. jb_err err;
  3367. if (csp->flags & CSP_FLAG_HOST_HEADER_IS_SET)
  3368. {
  3369. /* Header already set by the client, nothing to do. */
  3370. return JB_ERR_OK;
  3371. }
  3372. if (!csp->http->hostport || !*(csp->http->hostport))
  3373. {
  3374. log_error(LOG_LEVEL_ERROR, "Destination host unknown.");
  3375. return JB_ERR_PARSE;
  3376. }
  3377. /*
  3378. * remove 'user:pass@' from 'proto://user:pass@host'
  3379. */
  3380. if ((p = strchr( csp->http->hostport, '@')) != NULL)
  3381. {
  3382. p++;
  3383. }
  3384. else
  3385. {
  3386. p = csp->http->hostport;
  3387. }
  3388. /* XXX: Just add it, we already made sure that it will be unique */
  3389. log_error(LOG_LEVEL_HEADER, "addh-unique: Host: %s", p);
  3390. err = enlist_unique_header(csp->headers, "Host", p);
  3391. return err;
  3392. }
  3393. /*********************************************************************
  3394. *
  3395. * Function : client_xtra_adder
  3396. *
  3397. * Description : Used in the add_client_headers list. Called from `sed'.
  3398. *
  3399. * Parameters :
  3400. * 1 : csp = Current client state (buffers, headers, etc...)
  3401. *
  3402. * Returns : JB_ERR_OK on success, or
  3403. * JB_ERR_MEMORY on out-of-memory error.
  3404. *
  3405. *********************************************************************/
  3406. static jb_err client_xtra_adder(struct client_state *csp)
  3407. {
  3408. struct list_entry *lst;
  3409. jb_err err;
  3410. for (lst = csp->action->multi[ACTION_MULTI_ADD_HEADER]->first;
  3411. lst ; lst = lst->next)
  3412. {
  3413. log_error(LOG_LEVEL_HEADER, "addh: %s", lst->str);
  3414. err = enlist(csp->headers, lst->str);
  3415. if (err)
  3416. {
  3417. return err;
  3418. }
  3419. }
  3420. return JB_ERR_OK;
  3421. }
  3422. /*********************************************************************
  3423. *
  3424. * Function : client_x_forwarded_for_adder
  3425. *
  3426. * Description : Used in the add_client_headers list. Called from `sed'.
  3427. *
  3428. * Parameters :
  3429. * 1 : csp = Current client state (buffers, headers, etc...)
  3430. *
  3431. * Returns : JB_ERR_OK on success, or
  3432. * JB_ERR_MEMORY on out-of-memory error.
  3433. *
  3434. *********************************************************************/
  3435. static jb_err client_x_forwarded_for_adder(struct client_state *csp)
  3436. {
  3437. char *header = NULL;
  3438. jb_err err;
  3439. if (!((csp->action->flags & ACTION_CHANGE_X_FORWARDED_FOR)
  3440. && (0 == strcmpic(csp->action->string[ACTION_STRING_CHANGE_X_FORWARDED_FOR], "add")))
  3441. || (csp->flags & CSP_FLAG_X_FORWARDED_FOR_APPENDED))
  3442. {
  3443. /*
  3444. * If we aren't adding X-Forwarded-For headers,
  3445. * or we already appended an existing X-Forwarded-For
  3446. * header, there's nothing left to do here.
  3447. */
  3448. return JB_ERR_OK;
  3449. }
  3450. header = strdup("X-Forwarded-For: ");
  3451. string_append(&header, csp->ip_addr_str);
  3452. if (header == NULL)
  3453. {
  3454. return JB_ERR_MEMORY;
  3455. }
  3456. log_error(LOG_LEVEL_HEADER, "addh: %s", header);
  3457. err = enlist(csp->headers, header);
  3458. freez(header);
  3459. return err;
  3460. }
  3461. /*********************************************************************
  3462. *
  3463. * Function : server_connection_adder
  3464. *
  3465. * Description : Adds an appropriate "Connection:" header to csp->headers
  3466. * unless the header was already present. Called from `sed'.
  3467. *
  3468. * Parameters :
  3469. * 1 : csp = Current client state (buffers, headers, etc...)
  3470. *
  3471. * Returns : JB_ERR_OK on success, or
  3472. * JB_ERR_MEMORY on out-of-memory error.
  3473. *
  3474. *********************************************************************/
  3475. static jb_err server_connection_adder(struct client_state *csp)
  3476. {
  3477. const unsigned int flags = csp->flags;
  3478. const char *response_status_line = csp->headers->first->str;
  3479. static const char connection_close[] = "Connection: close";
  3480. if ((flags & CSP_FLAG_CLIENT_HEADER_PARSING_DONE)
  3481. && (flags & CSP_FLAG_SERVER_CONNECTION_HEADER_SET))
  3482. {
  3483. return JB_ERR_OK;
  3484. }
  3485. /*
  3486. * XXX: if we downgraded the response, this check will fail.
  3487. */
  3488. if ((csp->config->feature_flags &
  3489. RUNTIME_FEATURE_CONNECTION_KEEP_ALIVE)
  3490. && (NULL != response_status_line)
  3491. && !strncmpic(response_status_line, "HTTP/1.1", 8)
  3492. #ifdef FEATURE_CONNECTION_KEEP_ALIVE
  3493. && !(csp->flags & CSP_FLAG_SERVER_SOCKET_TAINTED)
  3494. #endif
  3495. )
  3496. {
  3497. log_error(LOG_LEVEL_HEADER, "A HTTP/1.1 response "
  3498. "without Connection header implies keep-alive.");
  3499. csp->flags |= CSP_FLAG_SERVER_CONNECTION_KEEP_ALIVE;
  3500. return JB_ERR_OK;
  3501. }
  3502. log_error(LOG_LEVEL_HEADER, "Adding: %s", connection_close);
  3503. return enlist(csp->headers, connection_close);
  3504. }
  3505. #ifdef FEATURE_CONNECTION_KEEP_ALIVE
  3506. /*********************************************************************
  3507. *
  3508. * Function : server_proxy_connection_adder
  3509. *
  3510. * Description : Adds a "Proxy-Connection: keep-alive" header to
  3511. * csp->headers when appropriate.
  3512. *
  3513. * Parameters :
  3514. * 1 : csp = Current client state (buffers, headers, etc...)
  3515. *
  3516. * Returns : JB_ERR_OK on success, or
  3517. * JB_ERR_MEMORY on out-of-memory error.
  3518. *
  3519. *********************************************************************/
  3520. static jb_err server_proxy_connection_adder(struct client_state *csp)
  3521. {
  3522. static const char proxy_connection_header[] = "Proxy-Connection: keep-alive";
  3523. jb_err err = JB_ERR_OK;
  3524. if ((csp->flags & CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE)
  3525. && !(csp->flags & CSP_FLAG_SERVER_SOCKET_TAINTED)
  3526. && !(csp->flags & CSP_FLAG_SERVER_PROXY_CONNECTION_HEADER_SET)
  3527. && ((csp->flags & CSP_FLAG_SERVER_CONTENT_LENGTH_SET)
  3528. || (csp->flags & CSP_FLAG_CHUNKED))
  3529. #ifdef FEATURE_HTTPS_INSPECTION
  3530. && !client_use_ssl(csp)
  3531. && !csp->http->ssl
  3532. #endif
  3533. )
  3534. {
  3535. log_error(LOG_LEVEL_HEADER, "Adding: %s", proxy_connection_header);
  3536. err = enlist(csp->headers, proxy_connection_header);
  3537. }
  3538. return err;
  3539. }
  3540. #endif /* FEATURE_CONNECTION_KEEP_ALIVE */
  3541. /*********************************************************************
  3542. *
  3543. * Function : client_connection_header_adder
  3544. *
  3545. * Description : Adds a proper "Connection:" header to csp->headers
  3546. * unless the header was already present or it's a
  3547. * CONNECT request. Called from `sed'.
  3548. *
  3549. * Parameters :
  3550. * 1 : csp = Current client state (buffers, headers, etc...)
  3551. *
  3552. * Returns : JB_ERR_OK on success, or
  3553. * JB_ERR_MEMORY on out-of-memory error.
  3554. *
  3555. *********************************************************************/
  3556. static jb_err client_connection_header_adder(struct client_state *csp)
  3557. {
  3558. static const char connection_close[] = "Connection: close";
  3559. if (!(csp->flags & CSP_FLAG_CLIENT_HEADER_PARSING_DONE)
  3560. && (csp->flags & CSP_FLAG_CLIENT_CONNECTION_HEADER_SET))
  3561. {
  3562. return JB_ERR_OK;
  3563. }
  3564. /*
  3565. * In case of CONNECT requests "Connection: close" is implied,
  3566. * but actually setting the header has been reported to cause
  3567. * problems with some forwarding proxies that close the
  3568. * connection prematurely.
  3569. */
  3570. if (csp->http->ssl != 0)
  3571. {
  3572. return JB_ERR_OK;
  3573. }
  3574. #ifdef FEATURE_CONNECTION_KEEP_ALIVE
  3575. if ((csp->config->feature_flags & RUNTIME_FEATURE_CONNECTION_KEEP_ALIVE)
  3576. && !(csp->flags & CSP_FLAG_SERVER_SOCKET_TAINTED)
  3577. && !strcmpic(csp->http->version, "HTTP/1.1"))
  3578. {
  3579. csp->flags |= CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE;
  3580. return JB_ERR_OK;
  3581. }
  3582. #endif /* FEATURE_CONNECTION_KEEP_ALIVE */
  3583. log_error(LOG_LEVEL_HEADER, "Adding: %s", connection_close);
  3584. return enlist(csp->headers, connection_close);
  3585. }
  3586. /*********************************************************************
  3587. *
  3588. * Function : server_http
  3589. *
  3590. * Description : - Save the HTTP Status into csp->http->status
  3591. * - Set CT_TABOO to prevent filtering if the answer
  3592. * is a partial range (HTTP status 206)
  3593. * - Rewrite HTTP/1.1 answers to HTTP/1.0 if +downgrade
  3594. * action applies.
  3595. * - Normalize the HTTP-version.
  3596. *
  3597. * Parameters :
  3598. * 1 : csp = Current client state (buffers, headers, etc...)
  3599. * 2 : header = On input, pointer to header to modify.
  3600. * On output, pointer to the modified header, or NULL
  3601. * to remove the header. This function frees the
  3602. * original string if necessary.
  3603. *
  3604. * Returns : JB_ERR_OK on success, or
  3605. * JB_ERR_PARSE on fatal parse errors.
  3606. *
  3607. *********************************************************************/
  3608. static jb_err server_http(struct client_state *csp, char **header)
  3609. {
  3610. char *reason_phrase = NULL;
  3611. char *new_response_line;
  3612. char *p;
  3613. size_t length;
  3614. unsigned int major_version;
  3615. unsigned int minor_version;
  3616. /* Get the reason phrase which start after the second whitespace */
  3617. p = strchr(*header, ' ');
  3618. if (NULL != p)
  3619. {
  3620. p++;
  3621. reason_phrase = strchr(p, ' ');
  3622. }
  3623. if (reason_phrase != NULL)
  3624. {
  3625. reason_phrase++;
  3626. }
  3627. else
  3628. {
  3629. log_error(LOG_LEVEL_ERROR,
  3630. "Response line lacks reason phrase: %s", *header);
  3631. reason_phrase="";
  3632. }
  3633. if (3 != sscanf(*header, "HTTP/%u.%u %d", &major_version,
  3634. &minor_version, &(csp->http->status)))
  3635. {
  3636. log_error(LOG_LEVEL_ERROR,
  3637. "Failed to parse the response line: %s", *header);
  3638. return JB_ERR_PARSE;
  3639. }
  3640. if (csp->http->status == 101 ||
  3641. csp->http->status == 206)
  3642. {
  3643. csp->content_type = CT_TABOO;
  3644. }
  3645. if (major_version != 1 || (minor_version != 0 && minor_version != 1))
  3646. {
  3647. /*
  3648. * According to RFC 7230 2.6 intermediaries MUST send
  3649. * their own HTTP-version in forwarded messages.
  3650. */
  3651. log_error(LOG_LEVEL_ERROR,
  3652. "Unsupported HTTP version. Downgrading to 1.1.");
  3653. major_version = 1;
  3654. minor_version = 1;
  3655. }
  3656. if (((csp->action->flags & ACTION_DOWNGRADE) != 0) && (minor_version == 1))
  3657. {
  3658. log_error(LOG_LEVEL_HEADER, "Downgrading answer to HTTP/1.0");
  3659. minor_version = 0;
  3660. }
  3661. /* Rebuild response line. */
  3662. length = sizeof("HTTP/1.1 200 ") + strlen(reason_phrase) + 1;
  3663. new_response_line = malloc_or_die(length);
  3664. snprintf(new_response_line, length, "HTTP/%u.%u %d %s",
  3665. major_version, minor_version, csp->http->status, reason_phrase);
  3666. if (0 != strcmp(*header, new_response_line))
  3667. {
  3668. log_error(LOG_LEVEL_HEADER, "Response line '%s' changed to '%s'",
  3669. *header, new_response_line);
  3670. }
  3671. freez(*header);
  3672. *header = new_response_line;
  3673. return JB_ERR_OK;
  3674. }
  3675. /*********************************************************************
  3676. *
  3677. * Function : add_cooky_expiry_date
  3678. *
  3679. * Description : Adds a cookie expiry date to a string.
  3680. *
  3681. * Parameters :
  3682. * 1 : cookie = On input, pointer to cookie to modify.
  3683. * On output, pointer to the modified header.
  3684. * The original string is freed.
  3685. * 2 : lifetime = Seconds the cookie should be valid
  3686. *
  3687. * Returns : N/A
  3688. *
  3689. *********************************************************************/
  3690. static void add_cookie_expiry_date(char **cookie, time_t lifetime)
  3691. {
  3692. char tmp[50];
  3693. struct tm *timeptr = NULL;
  3694. time_t expiry_date = time(NULL) + lifetime;
  3695. struct tm gmt;
  3696. timeptr = privoxy_gmtime_r(&expiry_date, &gmt);
  3697. if (NULL == timeptr)
  3698. {
  3699. log_error(LOG_LEVEL_FATAL,
  3700. "Failed to get the time in add_cooky_expiry_date()");
  3701. }
  3702. strftime(tmp, sizeof(tmp), "; expires=%a, %d-%b-%Y %H:%M:%S GMT", timeptr);
  3703. if (JB_ERR_OK != string_append(cookie, tmp))
  3704. {
  3705. log_error(LOG_LEVEL_FATAL, "Out of memory in add_cooky_expiry()");
  3706. }
  3707. }
  3708. /*********************************************************************
  3709. *
  3710. * Function : server_set_cookie
  3711. *
  3712. * Description : Handle the server "cookie" header properly.
  3713. * Crunch, accept or rewrite it to a session cookie.
  3714. * Called from `sed'.
  3715. *
  3716. * Parameters :
  3717. * 1 : csp = Current client state (buffers, headers, etc...)
  3718. * 2 : header = On input, pointer to header to modify.
  3719. * On output, pointer to the modified header, or NULL
  3720. * to remove the header. This function frees the
  3721. * original string if necessary.
  3722. *
  3723. * Returns : JB_ERR_OK on success, or
  3724. * JB_ERR_MEMORY on out-of-memory error.
  3725. *
  3726. *********************************************************************/
  3727. static jb_err server_set_cookie(struct client_state *csp, char **header)
  3728. {
  3729. if ((csp->action->flags & ACTION_CRUNCH_INCOMING_COOKIES) != 0)
  3730. {
  3731. log_error(LOG_LEVEL_HEADER, "Crunching incoming cookie: %s", *header);
  3732. freez(*header);
  3733. }
  3734. else if ((0 != (csp->action->flags & ACTION_SESSION_COOKIES_ONLY))
  3735. || (0 != (csp->action->flags & ACTION_LIMIT_COOKIE_LIFETIME)))
  3736. {
  3737. time_t now;
  3738. time_t cookie_time;
  3739. long cookie_lifetime = 0;
  3740. enum
  3741. {
  3742. NO_EXPIRY_DATE_SPECIFIED,
  3743. EXPIRY_DATE_ACCEPTABLE,
  3744. EXPIRY_DATE_UNACCEPTABLE
  3745. } expiry_date_status = NO_EXPIRY_DATE_SPECIFIED;
  3746. /* A variable to store the tag we're working on */
  3747. char *cur_tag;
  3748. /* Skip "Set-Cookie:" (11 characters) in header */
  3749. cur_tag = *header + 11;
  3750. /* skip whitespace between "Set-Cookie:" and value */
  3751. while (*cur_tag && privoxy_isspace(*cur_tag))
  3752. {
  3753. cur_tag++;
  3754. }
  3755. time(&now);
  3756. if ((csp->action->flags & ACTION_LIMIT_COOKIE_LIFETIME) != 0)
  3757. {
  3758. const char *param = csp->action->string[ACTION_STRING_LIMIT_COOKIE_LIFETIME];
  3759. cookie_lifetime = strtol(param, NULL, 0);
  3760. if (cookie_lifetime < 0)
  3761. {
  3762. log_error(LOG_LEVEL_FATAL, "Invalid cookie lifetime limit: %s", param);
  3763. }
  3764. cookie_lifetime *= 60;
  3765. }
  3766. /* Loop through each tag in the cookie */
  3767. while (*cur_tag)
  3768. {
  3769. /* Find next tag */
  3770. char *next_tag = strchr(cur_tag, ';');
  3771. if (next_tag != NULL)
  3772. {
  3773. /* Skip the ';' character itself */
  3774. next_tag++;
  3775. /* skip whitespace ";" and start of tag */
  3776. while (*next_tag && privoxy_isspace(*next_tag))
  3777. {
  3778. next_tag++;
  3779. }
  3780. }
  3781. else
  3782. {
  3783. /* "Next tag" is the end of the string */
  3784. next_tag = cur_tag + strlen(cur_tag);
  3785. }
  3786. /*
  3787. * Check the expiration date to see
  3788. * if the cookie is still valid, if yes,
  3789. * rewrite it to a session cookie.
  3790. */
  3791. if ((strncmpic(cur_tag, "expires=", 8) == 0) && *(cur_tag + 8))
  3792. {
  3793. char *expiration_date = cur_tag + 8; /* Skip "[Ee]xpires=" */
  3794. if ((expiration_date[0] == '"')
  3795. && (expiration_date[1] != '\0'))
  3796. {
  3797. /*
  3798. * Skip quotation mark. RFC 2109 10.1.2 seems to hint
  3799. * that the expiration date isn't supposed to be quoted,
  3800. * but some servers do it anyway.
  3801. */
  3802. expiration_date++;
  3803. }
  3804. /* Did we detect the date properly? */
  3805. if (JB_ERR_OK != parse_header_time(expiration_date, &cookie_time))
  3806. {
  3807. /*
  3808. * Nope, treat it as if it was still valid.
  3809. *
  3810. * XXX: Should we remove the whole cookie instead?
  3811. */
  3812. log_error(LOG_LEVEL_ERROR,
  3813. "Can't parse \'%s\', send by %s. Unsupported time format?", cur_tag, csp->http->url);
  3814. string_move(cur_tag, next_tag);
  3815. expiry_date_status = EXPIRY_DATE_UNACCEPTABLE;
  3816. }
  3817. else
  3818. {
  3819. /*
  3820. * Yes. Check if the cookie is still valid.
  3821. *
  3822. * If the cookie is already expired it's probably
  3823. * a delete cookie and even if it isn't, the browser
  3824. * will discard it anyway.
  3825. */
  3826. /*
  3827. * XXX: timegm() isn't available on some AmigaOS
  3828. * versions and our replacement doesn't work.
  3829. *
  3830. * Our options are to either:
  3831. *
  3832. * - disable session-cookies-only completely if timegm
  3833. * is missing,
  3834. *
  3835. * - to simply remove all expired tags, like it has
  3836. * been done until Privoxy 3.0.6 and to live with
  3837. * the consequence that it can cause login/logout
  3838. * problems on servers that don't validate their
  3839. * input properly, or
  3840. *
  3841. * - to replace it with mktime in which
  3842. * case there is a slight chance of valid cookies
  3843. * passing as already expired.
  3844. *
  3845. * This is the way it's currently done and it's not
  3846. * as bad as it sounds. If the missing GMT offset is
  3847. * enough to change the result of the expiration check
  3848. * the cookie will be only valid for a few hours
  3849. * anyway, which in many cases will be shorter
  3850. * than a browser session.
  3851. */
  3852. if (cookie_time < now)
  3853. {
  3854. log_error(LOG_LEVEL_HEADER,
  3855. "Cookie \'%s\' is already expired and can pass unmodified.", *header);
  3856. /* Just in case some clown sets more then one expiration date */
  3857. cur_tag = next_tag;
  3858. expiry_date_status = EXPIRY_DATE_ACCEPTABLE;
  3859. }
  3860. else if ((cookie_lifetime != 0) && (cookie_time < (now + cookie_lifetime)))
  3861. {
  3862. log_error(LOG_LEVEL_HEADER, "Cookie \'%s\' can pass unmodified. "
  3863. "Its lifetime is below the limit.", *header);
  3864. /* Just in case some clown sets more then one expiration date */
  3865. cur_tag = next_tag;
  3866. expiry_date_status = EXPIRY_DATE_ACCEPTABLE;
  3867. }
  3868. else
  3869. {
  3870. /*
  3871. * Still valid, delete expiration date by copying
  3872. * the rest of the string over it.
  3873. */
  3874. string_move(cur_tag, next_tag);
  3875. /* That changed the header, need to issue a log message */
  3876. expiry_date_status = EXPIRY_DATE_UNACCEPTABLE;
  3877. /*
  3878. * Note that the next tag has now been moved to *cur_tag,
  3879. * so we do not need to update the cur_tag pointer.
  3880. */
  3881. }
  3882. }
  3883. }
  3884. else
  3885. {
  3886. /* Move on to next cookie tag */
  3887. cur_tag = next_tag;
  3888. }
  3889. }
  3890. if (expiry_date_status != EXPIRY_DATE_ACCEPTABLE)
  3891. {
  3892. assert(NULL != *header);
  3893. if (cookie_lifetime != 0)
  3894. {
  3895. add_cookie_expiry_date(header, cookie_lifetime);
  3896. log_error(LOG_LEVEL_HEADER, "Cookie rewritten to: %s", *header);
  3897. }
  3898. else if (expiry_date_status != NO_EXPIRY_DATE_SPECIFIED)
  3899. {
  3900. log_error(LOG_LEVEL_HEADER,
  3901. "Cookie rewritten to a temporary one: %s", *header);
  3902. }
  3903. }
  3904. }
  3905. return JB_ERR_OK;
  3906. }
  3907. #ifdef FEATURE_FORCE_LOAD
  3908. /*********************************************************************
  3909. *
  3910. * Function : strclean
  3911. *
  3912. * Description : In-Situ-Eliminate all occurrences of substring in
  3913. * string
  3914. *
  3915. * Parameters :
  3916. * 1 : string = string to clean
  3917. * 2 : substring = substring to eliminate
  3918. *
  3919. * Returns : Number of eliminations
  3920. *
  3921. *********************************************************************/
  3922. int strclean(char *string, const char *substring)
  3923. {
  3924. int hits = 0;
  3925. size_t len;
  3926. char *pos, *p;
  3927. len = strlen(substring);
  3928. while((pos = strstr(string, substring)) != NULL)
  3929. {
  3930. p = pos + len;
  3931. do
  3932. {
  3933. *(p - len) = *p;
  3934. }
  3935. while (*p++ != '\0');
  3936. hits++;
  3937. }
  3938. return(hits);
  3939. }
  3940. #endif /* def FEATURE_FORCE_LOAD */
  3941. /*********************************************************************
  3942. *
  3943. * Function : parse_header_time
  3944. *
  3945. * Description : Parses time formats used in HTTP header strings
  3946. * to get the numerical respresentation.
  3947. *
  3948. * Parameters :
  3949. * 1 : header_time = HTTP header time as string.
  3950. * 2 : result = storage for header_time in seconds
  3951. *
  3952. * Returns : JB_ERR_OK if the time format was recognized, or
  3953. * JB_ERR_PARSE otherwise.
  3954. *
  3955. *********************************************************************/
  3956. static jb_err parse_header_time(const char *header_time, time_t *result)
  3957. {
  3958. struct tm gmt;
  3959. /*
  3960. * Checking for two-digit years first in an
  3961. * attempt to work around GNU libc's strptime()
  3962. * reporting negative year values when using %Y.
  3963. */
  3964. static const char time_formats[][22] = {
  3965. /* Tue, 02-Jun-37 20:00:00 */
  3966. "%a, %d-%b-%y %H:%M:%S",
  3967. /* Tue, 02 Jun 2037 20:00:00 */
  3968. "%a, %d %b %Y %H:%M:%S",
  3969. /* Tue, 02-Jun-2037 20:00:00 */
  3970. "%a, %d-%b-%Y %H:%M:%S",
  3971. /* Tuesday, 02-Jun-2037 20:00:00 */
  3972. "%A, %d-%b-%Y %H:%M:%S",
  3973. /* Tuesday Jun 02 20:00:00 2037 */
  3974. "%A %b %d %H:%M:%S %Y"
  3975. };
  3976. unsigned int i;
  3977. for (i = 0; i < SZ(time_formats); i++)
  3978. {
  3979. /*
  3980. * Zero out gmt to prevent time zone offsets.
  3981. * Documented to be required for GNU libc.
  3982. */
  3983. memset(&gmt, 0, sizeof(gmt));
  3984. if (NULL != strptime(header_time, time_formats[i], &gmt))
  3985. {
  3986. /* Sanity check for GNU libc. */
  3987. if (gmt.tm_year < 0)
  3988. {
  3989. log_error(LOG_LEVEL_HEADER,
  3990. "Failed to parse '%s' using '%s'. Moving on.",
  3991. header_time, time_formats[i]);
  3992. continue;
  3993. }
  3994. *result = timegm(&gmt);
  3995. #ifdef FEATURE_STRPTIME_SANITY_CHECKS
  3996. /*
  3997. * Verify that parsing the date recreated from the first
  3998. * parse operation gets the previous result. If it doesn't,
  3999. * either strptime() or strftime() are malfunctioning.
  4000. *
  4001. * We could string-compare the recreated date with the original
  4002. * header date, but this leads to false positives as strptime()
  4003. * may let %a accept all day formats while strftime() will only
  4004. * create one.
  4005. */
  4006. {
  4007. char recreated_date[100];
  4008. struct tm *tm;
  4009. struct tm storage;
  4010. time_t result2;
  4011. tm = privoxy_gmtime_r(result, &storage);
  4012. if (!strftime(recreated_date, sizeof(recreated_date),
  4013. time_formats[i], tm))
  4014. {
  4015. log_error(LOG_LEVEL_ERROR, "Failed to recreate date '%s' with '%s'.",
  4016. header_time, time_formats[i]);
  4017. continue;
  4018. }
  4019. memset(&gmt, 0, sizeof(gmt));
  4020. if (NULL == strptime(recreated_date, time_formats[i], &gmt))
  4021. {
  4022. log_error(LOG_LEVEL_ERROR,
  4023. "Failed to parse '%s' generated with '%s' to recreate '%s'.",
  4024. recreated_date, time_formats[i], header_time);
  4025. continue;
  4026. }
  4027. result2 = timegm(&gmt);
  4028. if (*result != result2)
  4029. {
  4030. log_error(LOG_LEVEL_ERROR, "strftime() and strptime() disagree. "
  4031. "Format: '%s'. In: '%s', out: '%s'. %ld != %ld. Rejecting.",
  4032. time_formats[i], header_time, recreated_date, *result, result2);
  4033. continue;
  4034. }
  4035. }
  4036. #endif
  4037. return JB_ERR_OK;
  4038. }
  4039. }
  4040. return JB_ERR_PARSE;
  4041. }
  4042. /*********************************************************************
  4043. *
  4044. * Function : parse_time_header
  4045. *
  4046. * Description : Parses the time in an HTTP time header to get
  4047. * the numerical respresentation.
  4048. *
  4049. * Parameters :
  4050. * 1 : header = HTTP header with a time value
  4051. * 2 : result = storage for header_time in seconds
  4052. *
  4053. * Returns : JB_ERR_OK if the time format was recognized, or
  4054. * JB_ERR_PARSE otherwise.
  4055. *
  4056. *********************************************************************/
  4057. static jb_err parse_time_header(const char *header, time_t *result)
  4058. {
  4059. const char *header_time;
  4060. header_time = strchr(header, ':');
  4061. /*
  4062. * Currently this can't happen as all callers are called
  4063. * through sed() which requires a header name followed by
  4064. * a colon.
  4065. */
  4066. assert(header_time != NULL);
  4067. header_time++;
  4068. if (*header_time == ' ')
  4069. {
  4070. header_time++;
  4071. }
  4072. return parse_header_time(header_time, result);
  4073. }
  4074. /*********************************************************************
  4075. *
  4076. * Function : get_destination_from_headers
  4077. *
  4078. * Description : Parse the "Host:" header to get the request's destination.
  4079. * Only needed if the client's request was forcefully
  4080. * redirected into Privoxy.
  4081. *
  4082. * Code mainly copied from client_host() which is currently
  4083. * run too late for this purpose.
  4084. *
  4085. * Parameters :
  4086. * 1 : headers = List of headers (one of them hopefully being
  4087. * the "Host:" header)
  4088. * 2 : http = storage for the result (host, port and hostport).
  4089. *
  4090. * Returns : JB_ERR_MEMORY (or terminates) in case of memory problems,
  4091. * JB_ERR_PARSE if the host header couldn't be found,
  4092. * JB_ERR_OK otherwise.
  4093. *
  4094. *********************************************************************/
  4095. jb_err get_destination_from_headers(const struct list *headers, struct http_request *http)
  4096. {
  4097. char *q;
  4098. char *p;
  4099. char *host;
  4100. host = get_header_value(headers, "Host:");
  4101. if (NULL == host)
  4102. {
  4103. log_error(LOG_LEVEL_ERROR, "No \"Host:\" header found.");
  4104. return JB_ERR_PARSE;
  4105. }
  4106. p = string_tolower(host);
  4107. if (p == NULL)
  4108. {
  4109. return JB_ERR_MEMORY;
  4110. }
  4111. chomp(p);
  4112. q = strdup_or_die(p);
  4113. freez(http->hostport);
  4114. http->hostport = p;
  4115. freez(http->host);
  4116. http->host = q;
  4117. q = strchr(http->host, ':');
  4118. if (q != NULL)
  4119. {
  4120. /* Terminate hostname and evaluate port string */
  4121. *q++ = '\0';
  4122. http->port = atoi(q);
  4123. }
  4124. else
  4125. {
  4126. http->port = 80;
  4127. }
  4128. /* Rebuild request URL */
  4129. freez(http->url);
  4130. http->url = strdup("http://");
  4131. string_append(&http->url, http->hostport);
  4132. string_append(&http->url, http->path);
  4133. if (http->url == NULL)
  4134. {
  4135. return JB_ERR_MEMORY;
  4136. }
  4137. log_error(LOG_LEVEL_HEADER,
  4138. "Destination extracted from \"Host\" header. New request URL: %s",
  4139. http->url);
  4140. /*
  4141. * Regenerate request line in "proxy format"
  4142. * to make rewrites more convenient.
  4143. */
  4144. assert(http->cmd != NULL);
  4145. freez(http->cmd);
  4146. http->cmd = strdup_or_die(http->gpc);
  4147. string_append(&http->cmd, " ");
  4148. string_append(&http->cmd, http->url);
  4149. string_append(&http->cmd, " ");
  4150. string_append(&http->cmd, http->version);
  4151. if (http->cmd == NULL)
  4152. {
  4153. return JB_ERR_MEMORY;
  4154. }
  4155. return JB_ERR_OK;
  4156. }
  4157. #ifdef FEATURE_HTTPS_INSPECTION
  4158. /*********************************************************************
  4159. *
  4160. * Function : get_destination_from_https_headers
  4161. *
  4162. * Description : Parse the previously encrypted "Host:" header to
  4163. * get the request's destination.
  4164. *
  4165. * Parameters :
  4166. * 1 : headers = List of headers (one of them hopefully being
  4167. * the "Host:" header)
  4168. * 2 : http = storage for the result (host, port and hostport).
  4169. *
  4170. * Returns : JB_ERR_MEMORY (or terminates) in case of memory problems,
  4171. * JB_ERR_PARSE if the host header couldn't be found,
  4172. * JB_ERR_OK otherwise.
  4173. *
  4174. *********************************************************************/
  4175. jb_err get_destination_from_https_headers(const struct list *headers, struct http_request *http)
  4176. {
  4177. char *q;
  4178. char *p;
  4179. char *host;
  4180. host = get_header_value(headers, "Host:");
  4181. if (NULL == host)
  4182. {
  4183. log_error(LOG_LEVEL_ERROR, "No \"Host:\" header found.");
  4184. return JB_ERR_PARSE;
  4185. }
  4186. p = string_tolower(host);
  4187. if (p == NULL)
  4188. {
  4189. return JB_ERR_MEMORY;
  4190. }
  4191. chomp(p);
  4192. q = strdup_or_die(p);
  4193. freez(http->hostport);
  4194. http->hostport = p;
  4195. freez(http->host);
  4196. http->host = q;
  4197. q = strchr(http->host, ':');
  4198. if (q != NULL)
  4199. {
  4200. /* Terminate hostname and evaluate port string */
  4201. *q++ = '\0';
  4202. http->port = atoi(q);
  4203. }
  4204. else
  4205. {
  4206. http->port = 443;
  4207. }
  4208. /* Rebuild request URL */
  4209. freez(http->url);
  4210. http->url = strdup_or_die(http->path);
  4211. log_error(LOG_LEVEL_HEADER,
  4212. "Destination extracted from \"Host\" header. New request URL: %s",
  4213. http->url);
  4214. /*
  4215. * Regenerate request line in "proxy format"
  4216. * to make rewrites more convenient.
  4217. */
  4218. assert(http->cmd != NULL);
  4219. freez(http->cmd);
  4220. http->cmd = strdup_or_die(http->gpc);
  4221. string_append(&http->cmd, " ");
  4222. string_append(&http->cmd, http->url);
  4223. string_append(&http->cmd, " ");
  4224. string_append(&http->cmd, http->version);
  4225. if (http->cmd == NULL)
  4226. {
  4227. return JB_ERR_MEMORY;
  4228. }
  4229. return JB_ERR_OK;
  4230. }
  4231. #endif /* def FEATURE_HTTPS_INSPECTION */
  4232. /*********************************************************************
  4233. *
  4234. * Function : create_forged_referrer
  4235. *
  4236. * Description : Helper for client_referrer to forge a referer as
  4237. * 'http://hostname[:port]/' to fool stupid
  4238. * checks for in-site links
  4239. *
  4240. * Parameters :
  4241. * 1 : header = Pointer to header pointer
  4242. * 2 : hostport = Host and optionally port as string
  4243. *
  4244. * Returns : JB_ERR_OK in case of success, or
  4245. * JB_ERR_MEMORY in case of memory problems.
  4246. *
  4247. *********************************************************************/
  4248. static jb_err create_forged_referrer(char **header, const char *hostport)
  4249. {
  4250. assert(NULL == *header);
  4251. *header = strdup("Referer: http://");
  4252. string_append(header, hostport);
  4253. string_append(header, "/");
  4254. if (NULL == *header)
  4255. {
  4256. return JB_ERR_MEMORY;
  4257. }
  4258. log_error(LOG_LEVEL_HEADER, "Referer forged to: %s", *header);
  4259. return JB_ERR_OK;
  4260. }
  4261. /*********************************************************************
  4262. *
  4263. * Function : create_fake_referrer
  4264. *
  4265. * Description : Helper for client_referrer to create a fake referrer
  4266. * based on a string supplied by the user.
  4267. *
  4268. * Parameters :
  4269. * 1 : header = Pointer to header pointer
  4270. * 2 : hosthost = Referrer to fake
  4271. *
  4272. * Returns : JB_ERR_OK in case of success, or
  4273. * JB_ERR_MEMORY in case of memory problems.
  4274. *
  4275. *********************************************************************/
  4276. static jb_err create_fake_referrer(char **header, const char *fake_referrer)
  4277. {
  4278. assert(NULL == *header);
  4279. if ((0 != strncmpic(fake_referrer, "http://", 7)) && (0 != strncmpic(fake_referrer, "https://", 8)))
  4280. {
  4281. log_error(LOG_LEVEL_HEADER,
  4282. "Parameter: +hide-referrer{%s} is a bad idea, but I don't care.", fake_referrer);
  4283. }
  4284. *header = strdup("Referer: ");
  4285. string_append(header, fake_referrer);
  4286. if (NULL == *header)
  4287. {
  4288. return JB_ERR_MEMORY;
  4289. }
  4290. log_error(LOG_LEVEL_HEADER, "Referer replaced with: %s", *header);
  4291. return JB_ERR_OK;
  4292. }
  4293. /*********************************************************************
  4294. *
  4295. * Function : handle_conditional_hide_referrer_parameter
  4296. *
  4297. * Description : Helper for client_referrer to crunch or forge
  4298. * the referrer header if the host has changed.
  4299. *
  4300. * Parameters :
  4301. * 1 : header = Pointer to header pointer
  4302. * 2 : host = The target host (may include the port)
  4303. * 3 : parameter_conditional_block = Boolean to signal
  4304. * if we're in conditional-block mode. If not set,
  4305. * we're in conditional-forge mode.
  4306. *
  4307. * Returns : JB_ERR_OK in case of success, or
  4308. * JB_ERR_MEMORY in case of memory problems.
  4309. *
  4310. *********************************************************************/
  4311. static jb_err handle_conditional_hide_referrer_parameter(char **header,
  4312. const char *host, const int parameter_conditional_block)
  4313. {
  4314. char *referer = strdup_or_die(*header);
  4315. const size_t hostlength = strlen(host);
  4316. const char *referer_url = NULL;
  4317. /* referer begins with 'Referer: http[s]://' */
  4318. if ((hostlength+17) < strlen(referer))
  4319. {
  4320. /*
  4321. * Shorten referer to make sure the referer is blocked
  4322. * if www.example.org/www.example.com-shall-see-the-referer/
  4323. * links to www.example.com/
  4324. */
  4325. referer[hostlength+17] = '\0';
  4326. }
  4327. referer_url = strstr(referer, "http://");
  4328. if ((NULL == referer_url) || (NULL == strstr(referer_url, host)))
  4329. {
  4330. /* Host has changed, Referer is invalid or a https URL. */
  4331. if (parameter_conditional_block)
  4332. {
  4333. log_error(LOG_LEVEL_HEADER, "New host is: %s. Crunching %s!", host, *header);
  4334. freez(*header);
  4335. }
  4336. else
  4337. {
  4338. freez(*header);
  4339. freez(referer);
  4340. return create_forged_referrer(header, host);
  4341. }
  4342. }
  4343. freez(referer);
  4344. return JB_ERR_OK;
  4345. }
  4346. /*********************************************************************
  4347. *
  4348. * Function : create_content_length_header
  4349. *
  4350. * Description : Creates a Content-Length header.
  4351. *
  4352. * Parameters :
  4353. * 1 : content_length = The content length to be used in the header.
  4354. * 2 : header = Allocated space to safe the header.
  4355. * 3 : buffer_length = The length of the allocated space.
  4356. *
  4357. * Returns : void
  4358. *
  4359. *********************************************************************/
  4360. static void create_content_length_header(unsigned long long content_length,
  4361. char *header, size_t buffer_length)
  4362. {
  4363. #ifdef _WIN32
  4364. #if SIZEOF_LONG_LONG < 8
  4365. #error sizeof(unsigned long long) too small
  4366. #endif
  4367. snprintf(header, buffer_length, "Content-Length: %I64u", content_length);
  4368. #else
  4369. snprintf(header, buffer_length, "Content-Length: %llu", content_length);
  4370. #endif
  4371. }
  4372. /*********************************************************************
  4373. *
  4374. * Function : get_expected_content_length
  4375. *
  4376. * Description : Figures out the content length from a list of headers.
  4377. *
  4378. * Parameters :
  4379. * 1 : headers = List of headers
  4380. *
  4381. * Returns : Number of bytes to expect
  4382. *
  4383. *********************************************************************/
  4384. unsigned long long get_expected_content_length(struct list *headers)
  4385. {
  4386. const char *content_length_header;
  4387. unsigned long long content_length = 0;
  4388. content_length_header = get_header_value(headers, "Content-Length:");
  4389. if (content_length_header != NULL)
  4390. {
  4391. if (JB_ERR_OK != get_content_length(content_length_header, &content_length))
  4392. {
  4393. log_error(LOG_LEVEL_ERROR,
  4394. "Failed to get the Content-Length in %s", content_length_header);
  4395. /* XXX: The header will be removed later on */
  4396. return 0;
  4397. }
  4398. }
  4399. return content_length;
  4400. }
  4401. /*
  4402. Local Variables:
  4403. tab-width: 3
  4404. end:
  4405. */