jcc.c 178 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833
  1. /*********************************************************************
  2. *
  3. * File : $Source: /cvsroot/ijbswa/current/jcc.c,v $
  4. *
  5. * Purpose : Main file. Contains main() method, main loop, and
  6. * the main connection-handling function.
  7. *
  8. * Copyright : Written by and Copyright (C) 2001-2020 the
  9. * Privoxy team. https://www.privoxy.org/
  10. *
  11. * Based on the Internet Junkbuster originally written
  12. * by and Copyright (C) 1997 Anonymous Coders and
  13. * Junkbusters Corporation. http://www.junkbusters.com
  14. *
  15. * This program is free software; you can redistribute it
  16. * and/or modify it under the terms of the GNU General
  17. * Public License as published by the Free Software
  18. * Foundation; either version 2 of the License, or (at
  19. * your option) any later version.
  20. *
  21. * This program is distributed in the hope that it will
  22. * be useful, but WITHOUT ANY WARRANTY; without even the
  23. * implied warranty of MERCHANTABILITY or FITNESS FOR A
  24. * PARTICULAR PURPOSE. See the GNU General Public
  25. * License for more details.
  26. *
  27. * The GNU General Public License should be included with
  28. * this file. If not, you can view it at
  29. * http://www.gnu.org/copyleft/gpl.html
  30. * or write to the Free Software Foundation, Inc., 59
  31. * Temple Place - Suite 330, Boston, MA 02111-1307, USA.
  32. *
  33. *********************************************************************/
  34. #include "config.h"
  35. #include <stdio.h>
  36. #include <sys/types.h>
  37. #include <stdlib.h>
  38. #include <string.h>
  39. #include <signal.h>
  40. #include <fcntl.h>
  41. #include <errno.h>
  42. #include <assert.h>
  43. #ifdef _WIN32
  44. # ifndef FEATURE_PTHREAD
  45. # ifndef STRICT
  46. # define STRICT
  47. # endif
  48. # include <winsock2.h>
  49. # include <windows.h>
  50. # include <process.h>
  51. # endif /* ndef FEATURE_PTHREAD */
  52. # include "win32.h"
  53. # ifndef _WIN_CONSOLE
  54. # include "w32log.h"
  55. # endif /* ndef _WIN_CONSOLE */
  56. # include "w32svrapi.h"
  57. #else /* ifndef _WIN32 */
  58. # include <unistd.h>
  59. # include <sys/wait.h>
  60. # include <sys/time.h>
  61. # include <sys/stat.h>
  62. # include <sys/ioctl.h>
  63. #ifdef sun
  64. #include <sys/termios.h>
  65. #endif /* sun */
  66. #ifdef unix
  67. #include <pwd.h>
  68. #include <grp.h>
  69. #endif
  70. # include <signal.h>
  71. # ifdef __BEOS__
  72. # include <socket.h> /* BeOS has select() for sockets only. */
  73. # include <OS.h> /* declarations for threads and stuff. */
  74. # endif
  75. #ifdef HAVE_POLL
  76. #ifdef __GLIBC__
  77. #include <sys/poll.h>
  78. #else
  79. #include <poll.h>
  80. #endif /* def __GLIBC__ */
  81. #else
  82. # ifndef FD_ZERO
  83. # include <select.h>
  84. # endif
  85. #warning poll() appears to be unavailable. Your platform will become unsupported in the future.
  86. #endif /* HAVE_POLL */
  87. #endif
  88. #include "project.h"
  89. #include "list.h"
  90. #include "jcc.h"
  91. #ifdef FEATURE_HTTPS_INSPECTION
  92. #include "ssl.h"
  93. #endif
  94. #include "filters.h"
  95. #include "loaders.h"
  96. #include "parsers.h"
  97. #include "miscutil.h"
  98. #include "errlog.h"
  99. #include "jbsockets.h"
  100. #include "gateway.h"
  101. #include "actions.h"
  102. #include "cgi.h"
  103. #include "loadcfg.h"
  104. #include "urlmatch.h"
  105. #ifdef FEATURE_CLIENT_TAGS
  106. #include "client-tags.h"
  107. #endif
  108. int daemon_mode = 1;
  109. struct client_states clients[1];
  110. struct file_list files[1];
  111. #ifdef FEATURE_STATISTICS
  112. int urls_read = 0; /* total nr of urls read inc rejected */
  113. int urls_rejected = 0; /* total nr of urls rejected */
  114. #endif /* def FEATURE_STATISTICS */
  115. #ifdef FEATURE_GRACEFUL_TERMINATION
  116. int g_terminate = 0;
  117. #endif
  118. #if !defined(_WIN32)
  119. static void sig_handler(int the_signal);
  120. #endif
  121. static int client_protocol_is_unsupported(struct client_state *csp, char *req);
  122. static jb_err get_request_destination_elsewhere(struct client_state *csp, struct list *headers);
  123. static jb_err get_server_headers(struct client_state *csp);
  124. static const char *crunch_reason(const struct http_response *rsp);
  125. static void send_crunch_response(struct client_state *csp, struct http_response *rsp);
  126. static char *get_request_line(struct client_state *csp);
  127. static jb_err receive_client_request(struct client_state *csp);
  128. static jb_err parse_client_request(struct client_state *csp);
  129. static void build_request_line(struct client_state *csp, const struct forward_spec *fwd, char **request_line);
  130. static jb_err change_request_destination(struct client_state *csp);
  131. static void handle_established_connection(struct client_state *csp);
  132. static void chat(struct client_state *csp);
  133. static void serve(struct client_state *csp);
  134. #if !defined(_WIN32) || defined(_WIN_CONSOLE)
  135. static void usage(const char *myname);
  136. #endif
  137. static void initialize_mutexes(void);
  138. static jb_socket bind_port_helper(const char *haddr, int hport, int backlog);
  139. static void bind_ports_helper(struct configuration_spec *config, jb_socket sockets[]);
  140. static void close_ports_helper(jb_socket sockets[]);
  141. static void listen_loop(void);
  142. static void serve(struct client_state *csp);
  143. #ifdef __BEOS__
  144. static int32 server_thread(void *data);
  145. #endif /* def __BEOS__ */
  146. #ifdef _WIN32
  147. #define sleep(N) Sleep(((N) * 1000))
  148. #endif
  149. #ifdef FUZZ
  150. int process_fuzzed_input(char *fuzz_input_type, char *fuzz_input_file);
  151. void show_fuzz_usage(const char *name);
  152. #endif
  153. #ifdef MUTEX_LOCKS_AVAILABLE
  154. /*
  155. * XXX: Does the locking stuff really belong in this file?
  156. */
  157. privoxy_mutex_t log_mutex;
  158. privoxy_mutex_t log_init_mutex;
  159. privoxy_mutex_t connection_reuse_mutex;
  160. #ifdef FEATURE_HTTPS_INSPECTION
  161. privoxy_mutex_t certificate_mutex;
  162. privoxy_mutex_t ssl_init_mutex;
  163. #endif
  164. #ifdef FEATURE_EXTERNAL_FILTERS
  165. privoxy_mutex_t external_filter_mutex;
  166. #endif
  167. #ifdef FEATURE_CLIENT_TAGS
  168. privoxy_mutex_t client_tags_mutex;
  169. #endif
  170. #ifdef FEATURE_EXTENDED_STATISTICS
  171. privoxy_mutex_t filter_statistics_mutex;
  172. privoxy_mutex_t block_statistics_mutex;
  173. #endif
  174. #if !defined(HAVE_GETHOSTBYADDR_R) || !defined(HAVE_GETHOSTBYNAME_R)
  175. privoxy_mutex_t resolver_mutex;
  176. #endif /* !defined(HAVE_GETHOSTBYADDR_R) || !defined(HAVE_GETHOSTBYNAME_R) */
  177. #ifndef HAVE_GMTIME_R
  178. privoxy_mutex_t gmtime_mutex;
  179. #endif /* ndef HAVE_GMTIME_R */
  180. #ifndef HAVE_LOCALTIME_R
  181. privoxy_mutex_t localtime_mutex;
  182. #endif /* ndef HAVE_GMTIME_R */
  183. #if !defined(HAVE_ARC4RANDOM) && !defined(HAVE_RANDOM)
  184. privoxy_mutex_t rand_mutex;
  185. #endif /* !defined(HAVE_ARC4RANDOM) && !defined(HAVE_RANDOM) */
  186. #endif /* def MUTEX_LOCKS_AVAILABLE */
  187. #if defined(unix)
  188. const char *basedir = NULL;
  189. const char *pidfile = NULL;
  190. static int received_hup_signal = 0;
  191. #endif /* defined unix */
  192. /* HTTP snipplets. */
  193. static const char CSUCCEED[] =
  194. "HTTP/1.1 200 Connection established\r\n\r\n";
  195. static const char CHEADER[] =
  196. "HTTP/1.1 400 Invalid header received from client\r\n"
  197. "Content-Type: text/plain\r\n"
  198. "Connection: close\r\n\r\n"
  199. "Invalid header received from client.\r\n";
  200. static const char FTP_RESPONSE[] =
  201. "HTTP/1.1 400 Invalid request received from client\r\n"
  202. "Content-Type: text/plain\r\n"
  203. "Connection: close\r\n\r\n"
  204. "Invalid request. Privoxy doesn't support FTP.\r\n";
  205. static const char GOPHER_RESPONSE[] =
  206. "HTTP/1.1 400 Invalid request received from client\r\n"
  207. "Content-Type: text/plain\r\n"
  208. "Connection: close\r\n\r\n"
  209. "Invalid request. Privoxy doesn't support gopher.\r\n";
  210. /* XXX: should be a template */
  211. static const char MISSING_DESTINATION_RESPONSE[] =
  212. "HTTP/1.1 400 Bad request received from client\r\n"
  213. "Content-Type: text/plain\r\n"
  214. "Connection: close\r\n\r\n"
  215. "Bad request. Privoxy was unable to extract the destination.\r\n";
  216. /* XXX: should be a template */
  217. static const char INVALID_SERVER_HEADERS_RESPONSE[] =
  218. "HTTP/1.1 502 Server or forwarder response invalid\r\n"
  219. "Content-Type: text/plain\r\n"
  220. "Connection: close\r\n\r\n"
  221. "Bad response. The server or forwarder response doesn't look like HTTP.\r\n";
  222. /* XXX: should be a template */
  223. static const char MESSED_UP_REQUEST_RESPONSE[] =
  224. "HTTP/1.1 400 Malformed request after rewriting\r\n"
  225. "Content-Type: text/plain\r\n"
  226. "Connection: close\r\n\r\n"
  227. "Bad request. Messed up with header filters.\r\n";
  228. static const char TOO_MANY_CONNECTIONS_RESPONSE[] =
  229. "HTTP/1.1 503 Too many open connections\r\n"
  230. "Content-Type: text/plain\r\n"
  231. "Connection: close\r\n\r\n"
  232. "Maximum number of open connections reached.\r\n";
  233. static const char CLIENT_CONNECTION_TIMEOUT_RESPONSE[] =
  234. "HTTP/1.1 504 Connection timeout\r\n"
  235. "Content-Type: text/plain\r\n"
  236. "Connection: close\r\n\r\n"
  237. "The connection timed out because the client request didn't arrive in time.\r\n";
  238. static const char CLIENT_BODY_PARSE_ERROR_RESPONSE[] =
  239. "HTTP/1.1 400 Failed reading client body\r\n"
  240. "Content-Type: text/plain\r\n"
  241. "Connection: close\r\n\r\n"
  242. "Failed parsing or buffering the chunk-encoded client body.\r\n";
  243. static const char UNSUPPORTED_CLIENT_EXPECTATION_ERROR_RESPONSE[] =
  244. "HTTP/1.1 417 Expecting too much\r\n"
  245. "Content-Type: text/plain\r\n"
  246. "Connection: close\r\n\r\n"
  247. "Privoxy detected an unsupported Expect header value.\r\n";
  248. /* A function to crunch a response */
  249. typedef struct http_response *(*crunch_func_ptr)(struct client_state *);
  250. /* Crunch function flags */
  251. #define CF_NO_FLAGS 0
  252. /* Cruncher applies to forced requests as well */
  253. #define CF_IGNORE_FORCE 1
  254. /* Crunched requests are counted for the block statistics */
  255. #define CF_COUNT_AS_REJECT 2
  256. /* A crunch function and its flags */
  257. struct cruncher
  258. {
  259. const crunch_func_ptr cruncher;
  260. const int flags;
  261. };
  262. static int crunch_response_triggered(struct client_state *csp, const struct cruncher crunchers[]);
  263. /* Complete list of cruncher functions */
  264. static const struct cruncher crunchers_all[] = {
  265. { direct_response, CF_COUNT_AS_REJECT|CF_IGNORE_FORCE},
  266. { block_url, CF_COUNT_AS_REJECT },
  267. #ifdef FEATURE_TRUST
  268. { trust_url, CF_COUNT_AS_REJECT },
  269. #endif /* def FEATURE_TRUST */
  270. { redirect_url, CF_NO_FLAGS },
  271. { dispatch_cgi, CF_IGNORE_FORCE},
  272. { NULL, 0 }
  273. };
  274. /* Light version, used after tags are applied */
  275. static const struct cruncher crunchers_light[] = {
  276. { block_url, CF_COUNT_AS_REJECT },
  277. { redirect_url, CF_NO_FLAGS },
  278. { NULL, 0 }
  279. };
  280. /*
  281. * XXX: Don't we really mean
  282. *
  283. * #if defined(unix)
  284. *
  285. * here?
  286. */
  287. #if !defined(_WIN32)
  288. /*********************************************************************
  289. *
  290. * Function : sig_handler
  291. *
  292. * Description : Signal handler for different signals.
  293. * Exit gracefully on TERM and INT
  294. * or set a flag that will cause the errlog
  295. * to be reopened by the main thread on HUP.
  296. *
  297. * Parameters :
  298. * 1 : the_signal = the signal cause this function to call
  299. *
  300. * Returns : -
  301. *
  302. *********************************************************************/
  303. static void sig_handler(int the_signal)
  304. {
  305. switch(the_signal)
  306. {
  307. case SIGTERM:
  308. case SIGINT:
  309. log_error(LOG_LEVEL_INFO, "exiting by signal %d .. bye", the_signal);
  310. #if defined(unix)
  311. if (pidfile)
  312. {
  313. unlink(pidfile);
  314. }
  315. #endif /* unix */
  316. exit(the_signal);
  317. break;
  318. case SIGHUP:
  319. #if defined(unix)
  320. received_hup_signal = 1;
  321. #endif
  322. break;
  323. default:
  324. /*
  325. * We shouldn't be here, unless we catch signals
  326. * in main() that we can't handle here!
  327. */
  328. log_error(LOG_LEVEL_FATAL, "sig_handler: exiting on unexpected signal %d", the_signal);
  329. }
  330. return;
  331. }
  332. #endif
  333. /*********************************************************************
  334. *
  335. * Function : get_write_delay
  336. *
  337. * Description : Parse the delay-response parameter.
  338. *
  339. * Parameters :
  340. * 1 : csp = Current client state (buffers, headers, etc...)
  341. *
  342. * Returns : Number of milliseconds to delay writes.
  343. *
  344. *********************************************************************/
  345. static unsigned int get_write_delay(const struct client_state *csp)
  346. {
  347. unsigned int delay;
  348. char *endptr;
  349. char *newval;
  350. if ((csp->action->flags & ACTION_DELAY_RESPONSE) == 0)
  351. {
  352. return 0;
  353. }
  354. newval = csp->action->string[ACTION_STRING_DELAY_RESPONSE];
  355. delay = (unsigned)strtol(newval, &endptr, 0);
  356. if (*endptr != '\0')
  357. {
  358. log_error(LOG_LEVEL_FATAL,
  359. "Invalid delay-response{} parameter: '%s'", newval);
  360. }
  361. return delay;
  362. }
  363. /*********************************************************************
  364. *
  365. * Function : client_protocol_is_unsupported
  366. *
  367. * Description : Checks if the client used a known unsupported
  368. * protocol and deals with it by sending an error
  369. * response.
  370. *
  371. * Parameters :
  372. * 1 : csp = Current client state (buffers, headers, etc...)
  373. * 2 : req = the first request line send by the client
  374. *
  375. * Returns : TRUE if an error response has been generated, or
  376. * FALSE if the request doesn't look invalid.
  377. *
  378. *********************************************************************/
  379. static int client_protocol_is_unsupported(struct client_state *csp, char *req)
  380. {
  381. /*
  382. * If it's a FTP or gopher request, we don't support it.
  383. *
  384. * These checks are better than nothing, but they might
  385. * not work in all configurations and some clients might
  386. * have problems digesting the answer.
  387. *
  388. * They should, however, never cause more problems than
  389. * Privoxy's old behaviour (returning the misleading HTML
  390. * error message:
  391. *
  392. * "Could not resolve http://(ftp|gopher)://example.org").
  393. */
  394. if (!strncmpic(req, "GET ftp://", 10) || !strncmpic(req, "GET gopher://", 13))
  395. {
  396. const char *response = NULL;
  397. const char *protocol = NULL;
  398. if (!strncmpic(req, "GET ftp://", 10))
  399. {
  400. response = FTP_RESPONSE;
  401. protocol = "FTP";
  402. }
  403. else
  404. {
  405. response = GOPHER_RESPONSE;
  406. protocol = "GOPHER";
  407. }
  408. log_error(LOG_LEVEL_ERROR,
  409. "%s tried to use Privoxy as %s proxy: %s",
  410. csp->ip_addr_str, protocol, req);
  411. log_error(LOG_LEVEL_CLF,
  412. "%s - - [%T] \"%s\" 400 0", csp->ip_addr_str, req);
  413. freez(req);
  414. #ifdef FEATURE_HTTPS_INSPECTION
  415. if (client_use_ssl(csp))
  416. {
  417. ssl_send_data_delayed(&(csp->ssl_client_attr),
  418. (const unsigned char *)response, strlen(response),
  419. get_write_delay(csp));
  420. }
  421. else
  422. #endif
  423. {
  424. write_socket_delayed(csp->cfd, response, strlen(response),
  425. get_write_delay(csp));
  426. }
  427. return TRUE;
  428. }
  429. return FALSE;
  430. }
  431. /*********************************************************************
  432. *
  433. * Function : client_has_unsupported_expectations
  434. *
  435. * Description : Checks if the client used an unsupported expectation
  436. * in which case an error message is delivered.
  437. *
  438. * Parameters :
  439. * 1 : csp = Current client state (buffers, headers, etc...)
  440. *
  441. * Returns : TRUE if an error response has been generated, or
  442. * FALSE if the request doesn't look invalid.
  443. *
  444. *********************************************************************/
  445. static int client_has_unsupported_expectations(const struct client_state *csp)
  446. {
  447. if ((csp->flags & CSP_FLAG_UNSUPPORTED_CLIENT_EXPECTATION))
  448. {
  449. log_error(LOG_LEVEL_ERROR,
  450. "Rejecting request from client %s with unsupported Expect header value",
  451. csp->ip_addr_str);
  452. log_error(LOG_LEVEL_CLF,
  453. "%s - - [%T] \"%s\" 417 0", csp->ip_addr_str, csp->http->cmd);
  454. write_socket_delayed(csp->cfd,
  455. UNSUPPORTED_CLIENT_EXPECTATION_ERROR_RESPONSE,
  456. strlen(UNSUPPORTED_CLIENT_EXPECTATION_ERROR_RESPONSE),
  457. get_write_delay(csp));
  458. return TRUE;
  459. }
  460. return FALSE;
  461. }
  462. /*********************************************************************
  463. *
  464. * Function : get_request_destination_elsewhere
  465. *
  466. * Description : If the client's request was redirected into
  467. * Privoxy without the client's knowledge,
  468. * the request line lacks the destination host.
  469. *
  470. * This function tries to get it elsewhere,
  471. * provided accept-intercepted-requests is enabled.
  472. *
  473. * "Elsewhere" currently only means "Host: header",
  474. * but in the future we may ask the redirecting
  475. * packet filter to look the destination up.
  476. *
  477. * If the destination stays unknown, an error
  478. * response is send to the client and headers
  479. * are freed so that chat() can return directly.
  480. *
  481. * Parameters :
  482. * 1 : csp = Current client state (buffers, headers, etc...)
  483. * 2 : headers = a header list
  484. *
  485. * Returns : JB_ERR_OK if the destination is now known, or
  486. * JB_ERR_PARSE if it isn't.
  487. *
  488. *********************************************************************/
  489. static jb_err get_request_destination_elsewhere(struct client_state *csp, struct list *headers)
  490. {
  491. if (!(csp->config->feature_flags & RUNTIME_FEATURE_ACCEPT_INTERCEPTED_REQUESTS))
  492. {
  493. log_error(LOG_LEVEL_ERROR, "%s's request: \'%s\' is invalid."
  494. " Privoxy isn't configured to accept intercepted requests.",
  495. csp->ip_addr_str, csp->http->cmd);
  496. /* XXX: Use correct size */
  497. log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 400 0",
  498. csp->ip_addr_str, csp->http->cmd);
  499. write_socket_delayed(csp->cfd, CHEADER, strlen(CHEADER),
  500. get_write_delay(csp));
  501. destroy_list(headers);
  502. return JB_ERR_PARSE;
  503. }
  504. else if (JB_ERR_OK == get_destination_from_headers(headers, csp->http))
  505. {
  506. /* Split the domain we just got for pattern matching */
  507. init_domain_components(csp->http);
  508. return JB_ERR_OK;
  509. }
  510. else
  511. {
  512. /* We can't work without destination. Go spread the news.*/
  513. /* XXX: Use correct size */
  514. log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 400 0",
  515. csp->ip_addr_str, csp->http->cmd);
  516. log_error(LOG_LEVEL_ERROR,
  517. "Privoxy was unable to get the destination for %s's request: %s",
  518. csp->ip_addr_str, csp->http->cmd);
  519. write_socket_delayed(csp->cfd, MISSING_DESTINATION_RESPONSE,
  520. strlen(MISSING_DESTINATION_RESPONSE), get_write_delay(csp));
  521. destroy_list(headers);
  522. return JB_ERR_PARSE;
  523. }
  524. /*
  525. * TODO: If available, use PF's ioctl DIOCNATLOOK as last resort
  526. * to get the destination IP address, use it as host directly
  527. * or do a reverse DNS lookup first.
  528. */
  529. }
  530. /*********************************************************************
  531. *
  532. * Function : get_server_headers
  533. *
  534. * Description : Parses server headers in iob and fills them
  535. * into csp->headers so that they can later be
  536. * handled by sed().
  537. *
  538. * Parameters :
  539. * 1 : csp = Current client state (buffers, headers, etc...)
  540. *
  541. * Returns : JB_ERR_OK if everything went fine, or
  542. * JB_ERR_PARSE if the headers were incomplete.
  543. *
  544. *********************************************************************/
  545. static jb_err get_server_headers(struct client_state *csp)
  546. {
  547. int continue_hack_in_da_house = 0;
  548. char * header;
  549. while (((header = get_header(csp->iob)) != NULL) || continue_hack_in_da_house)
  550. {
  551. if (header == NULL)
  552. {
  553. /*
  554. * continue hack in da house. Ignore the ending of
  555. * this head and continue enlisting header lines.
  556. * The reason is described below.
  557. */
  558. enlist(csp->headers, "");
  559. continue_hack_in_da_house = 0;
  560. continue;
  561. }
  562. else if (0 == strncmpic(header, "HTTP/1.1 100", 12))
  563. {
  564. /*
  565. * It's a bodyless continue response, don't
  566. * stop header parsing after reaching its end.
  567. *
  568. * As a result Privoxy will concatenate the
  569. * next response's head and parse and deliver
  570. * the headers as if they belonged to one request.
  571. *
  572. * The client will separate them because of the
  573. * empty line between them.
  574. *
  575. * XXX: What we're doing here is clearly against
  576. * the intended purpose of the continue header,
  577. * and under some conditions (HTTP/1.0 client request)
  578. * it's a standard violation.
  579. *
  580. * Anyway, "sort of against the spec" is preferable
  581. * to "always getting confused by Continue responses"
  582. * (Privoxy's behaviour before this hack was added)
  583. */
  584. log_error(LOG_LEVEL_HEADER, "Continue hack in da house.");
  585. continue_hack_in_da_house = 1;
  586. }
  587. else if (*header == '\0')
  588. {
  589. /*
  590. * If the header is empty, but the Continue hack
  591. * isn't active, we can assume that we reached the
  592. * end of the buffer before we hit the end of the
  593. * head.
  594. *
  595. * Inform the caller an let it decide how to handle it.
  596. */
  597. return JB_ERR_PARSE;
  598. }
  599. if (JB_ERR_MEMORY == enlist(csp->headers, header))
  600. {
  601. /*
  602. * XXX: Should we quit the request and return a
  603. * out of memory error page instead?
  604. */
  605. log_error(LOG_LEVEL_ERROR,
  606. "Out of memory while enlisting server headers. %s lost.",
  607. header);
  608. }
  609. freez(header);
  610. }
  611. return JB_ERR_OK;
  612. }
  613. /*********************************************************************
  614. *
  615. * Function : crunch_reason
  616. *
  617. * Description : Translates the crunch reason code into a string.
  618. *
  619. * Parameters :
  620. * 1 : rsp = a http_response
  621. *
  622. * Returns : A string with the crunch reason or an error description.
  623. *
  624. *********************************************************************/
  625. static const char *crunch_reason(const struct http_response *rsp)
  626. {
  627. char * reason = NULL;
  628. assert(rsp != NULL);
  629. if (rsp == NULL)
  630. {
  631. return "Internal error while searching for crunch reason";
  632. }
  633. switch (rsp->crunch_reason)
  634. {
  635. case UNSUPPORTED:
  636. reason = "Unsupported HTTP feature";
  637. break;
  638. case BLOCKED:
  639. reason = "Blocked";
  640. break;
  641. case UNTRUSTED:
  642. reason = "Untrusted";
  643. break;
  644. case REDIRECTED:
  645. reason = "Redirected";
  646. break;
  647. case CGI_CALL:
  648. reason = "CGI Call";
  649. break;
  650. case NO_SUCH_DOMAIN:
  651. reason = "DNS failure";
  652. break;
  653. case FORWARDING_FAILED:
  654. reason = "Forwarding failed";
  655. break;
  656. case CONNECT_FAILED:
  657. reason = "Connection failure";
  658. break;
  659. case OUT_OF_MEMORY:
  660. reason = "Out of memory (may mask other reasons)";
  661. break;
  662. case CONNECTION_TIMEOUT:
  663. reason = "Connection timeout";
  664. break;
  665. case NO_SERVER_DATA:
  666. reason = "No server data received";
  667. break;
  668. default:
  669. reason = "No reason recorded";
  670. break;
  671. }
  672. return reason;
  673. }
  674. /*********************************************************************
  675. *
  676. * Function : log_applied_actions
  677. *
  678. * Description : Logs the applied actions if LOG_LEVEL_ACTIONS is
  679. * enabled.
  680. *
  681. * Parameters :
  682. * 1 : actions = Current action spec to log
  683. *
  684. * Returns : Nothing.
  685. *
  686. *********************************************************************/
  687. static void log_applied_actions(const struct current_action_spec *actions)
  688. {
  689. /*
  690. * The conversion to text requires lots of memory allocations so
  691. * we only do the conversion if the user is actually interested.
  692. */
  693. if (debug_level_is_enabled(LOG_LEVEL_ACTIONS))
  694. {
  695. char *actions_as_text = actions_to_line_of_text(actions);
  696. log_error(LOG_LEVEL_ACTIONS, "%s", actions_as_text);
  697. freez(actions_as_text);
  698. }
  699. }
  700. /*********************************************************************
  701. *
  702. * Function : send_crunch_response
  703. *
  704. * Description : Delivers already prepared response for
  705. * intercepted requests, logs the interception
  706. * and frees the response.
  707. *
  708. * Parameters :
  709. * 1 : csp = Current client state (buffers, headers, etc...)
  710. * 2 : rsp = Fully prepared response. Will be freed on exit.
  711. *
  712. * Returns : Nothing.
  713. *
  714. *********************************************************************/
  715. static void send_crunch_response(struct client_state *csp, struct http_response *rsp)
  716. {
  717. const struct http_request *http = csp->http;
  718. char status_code[4];
  719. assert(rsp != NULL);
  720. assert(rsp->head != NULL);
  721. if (rsp == NULL)
  722. {
  723. log_error(LOG_LEVEL_FATAL, "NULL response in send_crunch_response.");
  724. }
  725. /*
  726. * Extract the status code from the actual head
  727. * that will be send to the client. It is the only
  728. * way to get it right for all requests, including
  729. * the fixed ones for out-of-memory problems.
  730. *
  731. * A head starts like this: 'HTTP/1.1 200...'
  732. * 0123456789|11
  733. * 10
  734. */
  735. status_code[0] = rsp->head[9];
  736. status_code[1] = rsp->head[10];
  737. status_code[2] = rsp->head[11];
  738. status_code[3] = '\0';
  739. /* Log that the request was crunched and why. */
  740. log_applied_actions(csp->action);
  741. #ifdef FEATURE_HTTPS_INSPECTION
  742. if (client_use_ssl(csp))
  743. {
  744. log_error(LOG_LEVEL_CRUNCH, "%s: https://%s%s", crunch_reason(rsp),
  745. http->hostport, http->path);
  746. log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s https://%s%s %s\" %s %lu",
  747. csp->ip_addr_str, http->gpc, http->hostport, http->path,
  748. http->version, status_code, rsp->content_length);
  749. }
  750. else
  751. #endif
  752. {
  753. log_error(LOG_LEVEL_CRUNCH, "%s: %s", crunch_reason(rsp), http->url);
  754. log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" %s %lu",
  755. csp->ip_addr_str, http->ocmd, status_code, rsp->content_length);
  756. }
  757. /* Write the answer to the client */
  758. #ifdef FEATURE_HTTPS_INSPECTION
  759. if (client_use_ssl(csp))
  760. {
  761. if ((ssl_send_data_delayed(&(csp->ssl_client_attr),
  762. (const unsigned char *)rsp->head, rsp->head_length,
  763. get_write_delay(csp)) < 0)
  764. || (ssl_send_data_delayed(&(csp->ssl_client_attr),
  765. (const unsigned char *)rsp->body, rsp->content_length,
  766. get_write_delay(csp)) < 0))
  767. {
  768. /* There is nothing we can do about it. */
  769. log_error(LOG_LEVEL_CONNECT, "Couldn't deliver the error message "
  770. "for https://%s%s through client socket %d using TLS/SSL",
  771. http->hostport, http->url, csp->cfd);
  772. }
  773. }
  774. else
  775. #endif
  776. {
  777. if (write_socket_delayed(csp->cfd, rsp->head, rsp->head_length,
  778. get_write_delay(csp))
  779. || write_socket_delayed(csp->cfd, rsp->body, rsp->content_length,
  780. get_write_delay(csp)))
  781. {
  782. /* There is nothing we can do about it. */
  783. log_error(LOG_LEVEL_CONNECT,
  784. "Couldn't deliver the error message for %s through client socket %d: %E",
  785. http->url, csp->cfd);
  786. }
  787. }
  788. /* Clean up and return */
  789. if (cgi_error_memory() != rsp)
  790. {
  791. free_http_response(rsp);
  792. }
  793. return;
  794. }
  795. /*********************************************************************
  796. *
  797. * Function : crunch_response_triggered
  798. *
  799. * Description : Checks if the request has to be crunched,
  800. * and delivers the crunch response if necessary.
  801. *
  802. * Parameters :
  803. * 1 : csp = Current client state (buffers, headers, etc...)
  804. * 2 : crunchers = list of cruncher functions to run
  805. *
  806. * Returns : TRUE if the request was answered with a crunch response
  807. * FALSE otherwise.
  808. *
  809. *********************************************************************/
  810. static int crunch_response_triggered(struct client_state *csp, const struct cruncher crunchers[])
  811. {
  812. struct http_response *rsp = NULL;
  813. const struct cruncher *c;
  814. /*
  815. * If CGI request crunching is disabled,
  816. * check the CGI dispatcher out of order to
  817. * prevent unintentional blocks or redirects.
  818. */
  819. if (!(csp->config->feature_flags & RUNTIME_FEATURE_CGI_CRUNCHING)
  820. && (NULL != (rsp = dispatch_cgi(csp))))
  821. {
  822. /* Deliver, log and free the interception response. */
  823. send_crunch_response(csp, rsp);
  824. csp->flags |= CSP_FLAG_CRUNCHED;
  825. return TRUE;
  826. }
  827. for (c = crunchers; c->cruncher != NULL; c++)
  828. {
  829. /*
  830. * Check the cruncher if either Privoxy is toggled
  831. * on and the request isn't forced, or if the cruncher
  832. * applies to forced requests as well.
  833. */
  834. if (((csp->flags & CSP_FLAG_TOGGLED_ON) &&
  835. !(csp->flags & CSP_FLAG_FORCED)) ||
  836. (c->flags & CF_IGNORE_FORCE))
  837. {
  838. rsp = c->cruncher(csp);
  839. if (NULL != rsp)
  840. {
  841. /* Deliver, log and free the interception response. */
  842. send_crunch_response(csp, rsp);
  843. csp->flags |= CSP_FLAG_CRUNCHED;
  844. #ifdef FEATURE_STATISTICS
  845. if (c->flags & CF_COUNT_AS_REJECT)
  846. {
  847. csp->flags |= CSP_FLAG_REJECTED;
  848. }
  849. #endif /* def FEATURE_STATISTICS */
  850. return TRUE;
  851. }
  852. }
  853. }
  854. return FALSE;
  855. }
  856. /*********************************************************************
  857. *
  858. * Function : build_request_line
  859. *
  860. * Description : Builds the HTTP request line.
  861. *
  862. * If a HTTP forwarder is used it expects the whole URL,
  863. * web servers only get the path.
  864. *
  865. * Parameters :
  866. * 1 : csp = Current client state (buffers, headers, etc...)
  867. * 2 : fwd = The forwarding spec used for the request
  868. * XXX: Should use http->fwd instead.
  869. * 3 : request_line = The old request line which will be replaced.
  870. *
  871. * Returns : Nothing. Terminates in case of memory problems.
  872. *
  873. *********************************************************************/
  874. static void build_request_line(struct client_state *csp, const struct forward_spec *fwd, char **request_line)
  875. {
  876. struct http_request *http = csp->http;
  877. /*
  878. * Downgrade http version from 1.1 to 1.0
  879. * if +downgrade action applies.
  880. */
  881. if ((csp->action->flags & ACTION_DOWNGRADE)
  882. && (!strcmpic(http->version, "HTTP/1.1")))
  883. {
  884. freez(http->version);
  885. http->version = strdup_or_die("HTTP/1.0");
  886. }
  887. /*
  888. * Rebuild the request line.
  889. */
  890. freez(*request_line);
  891. *request_line = strdup(http->gpc);
  892. string_append(request_line, " ");
  893. if (fwd->forward_host && fwd->type != FORWARD_WEBSERVER)
  894. {
  895. string_append(request_line, http->url);
  896. }
  897. else
  898. {
  899. string_append(request_line, http->path);
  900. }
  901. string_append(request_line, " ");
  902. string_append(request_line, http->version);
  903. if (*request_line == NULL)
  904. {
  905. log_error(LOG_LEVEL_FATAL, "Out of memory writing HTTP command");
  906. }
  907. log_error(LOG_LEVEL_HEADER, "New HTTP Request-Line: %s", *request_line);
  908. }
  909. /*********************************************************************
  910. *
  911. * Function : change_request_destination
  912. *
  913. * Description : Parse a (rewritten) request line and regenerate
  914. * the http request data.
  915. *
  916. * Parameters :
  917. * 1 : csp = Current client state (buffers, headers, etc...)
  918. *
  919. * Returns : Forwards the parse_http_request() return code.
  920. * Terminates in case of memory problems.
  921. *
  922. *********************************************************************/
  923. static jb_err change_request_destination(struct client_state *csp)
  924. {
  925. struct http_request *http = csp->http;
  926. jb_err err;
  927. log_error(LOG_LEVEL_REDIRECTS, "Rewrite detected: %s",
  928. csp->headers->first->str);
  929. free_http_request(http);
  930. err = parse_http_request(csp->headers->first->str, http);
  931. if (JB_ERR_OK != err)
  932. {
  933. log_error(LOG_LEVEL_ERROR, "Couldn't parse rewritten request: %s.",
  934. jb_err_to_string(err));
  935. }
  936. return err;
  937. }
  938. #ifdef FEATURE_CONNECTION_KEEP_ALIVE
  939. /*********************************************************************
  940. *
  941. * Function : server_response_is_complete
  942. *
  943. * Description : Determines whether we should stop reading
  944. * from the server socket.
  945. *
  946. * Parameters :
  947. * 1 : csp = Current client state (buffers, headers, etc...)
  948. * 2 : content_length = Length of content received so far.
  949. *
  950. * Returns : TRUE if the response is complete,
  951. * FALSE otherwise.
  952. *
  953. *********************************************************************/
  954. static int server_response_is_complete(struct client_state *csp,
  955. unsigned long long content_length)
  956. {
  957. int content_length_known = !!(csp->flags & CSP_FLAG_CONTENT_LENGTH_SET);
  958. if (!strcmpic(csp->http->gpc, "HEAD"))
  959. {
  960. /*
  961. * "HEAD" implies no body, we are thus expecting
  962. * no content. XXX: incomplete "list" of methods?
  963. */
  964. csp->expected_content_length = 0;
  965. content_length_known = TRUE;
  966. csp->flags |= CSP_FLAG_SERVER_CONTENT_LENGTH_SET;
  967. }
  968. if (csp->http->status == 204 || csp->http->status == 304)
  969. {
  970. /*
  971. * Expect no body. XXX: incomplete "list" of status codes?
  972. */
  973. csp->expected_content_length = 0;
  974. content_length_known = TRUE;
  975. csp->flags |= CSP_FLAG_SERVER_CONTENT_LENGTH_SET;
  976. }
  977. return (content_length_known && ((0 == csp->expected_content_length)
  978. || (csp->expected_content_length <= content_length)));
  979. }
  980. #ifdef FEATURE_CONNECTION_SHARING
  981. /*********************************************************************
  982. *
  983. * Function : wait_for_alive_connections
  984. *
  985. * Description : Waits for alive connections to timeout.
  986. *
  987. * Parameters : N/A
  988. *
  989. * Returns : N/A
  990. *
  991. *********************************************************************/
  992. static void wait_for_alive_connections(void)
  993. {
  994. int connections_alive = close_unusable_connections();
  995. while (0 < connections_alive)
  996. {
  997. log_error(LOG_LEVEL_CONNECT,
  998. "Waiting for %d connections to timeout.",
  999. connections_alive);
  1000. sleep(60);
  1001. connections_alive = close_unusable_connections();
  1002. }
  1003. log_error(LOG_LEVEL_CONNECT, "No connections to wait for left.");
  1004. }
  1005. #endif /* def FEATURE_CONNECTION_SHARING */
  1006. /*********************************************************************
  1007. *
  1008. * Function : save_connection_destination
  1009. *
  1010. * Description : Remembers a connection for reuse later on.
  1011. *
  1012. * Parameters :
  1013. * 1 : sfd = Open socket to remember.
  1014. * 2 : http = The destination for the connection.
  1015. * 3 : fwd = The forwarder settings used.
  1016. * 4 : server_connection = storage.
  1017. *
  1018. * Returns : void
  1019. *
  1020. *********************************************************************/
  1021. void save_connection_destination(jb_socket sfd,
  1022. const struct http_request *http,
  1023. const struct forward_spec *fwd,
  1024. struct reusable_connection *server_connection)
  1025. {
  1026. assert(sfd != JB_INVALID_SOCKET);
  1027. assert(NULL != http->host);
  1028. server_connection->sfd = sfd;
  1029. server_connection->host = strdup_or_die(http->host);
  1030. server_connection->port = http->port;
  1031. assert(NULL != fwd);
  1032. assert(server_connection->gateway_host == NULL);
  1033. assert(server_connection->gateway_port == 0);
  1034. assert(server_connection->forwarder_type == 0);
  1035. assert(server_connection->forward_host == NULL);
  1036. assert(server_connection->forward_port == 0);
  1037. server_connection->forwarder_type = fwd->type;
  1038. if (NULL != fwd->gateway_host)
  1039. {
  1040. server_connection->gateway_host = strdup_or_die(fwd->gateway_host);
  1041. }
  1042. else
  1043. {
  1044. server_connection->gateway_host = NULL;
  1045. }
  1046. server_connection->gateway_port = fwd->gateway_port;
  1047. if (NULL != fwd->auth_username)
  1048. {
  1049. server_connection->auth_username = strdup_or_die(fwd->auth_username);
  1050. }
  1051. else
  1052. {
  1053. server_connection->auth_username = NULL;
  1054. }
  1055. if (NULL != fwd->auth_password)
  1056. {
  1057. server_connection->auth_password = strdup_or_die(fwd->auth_password);
  1058. }
  1059. else
  1060. {
  1061. server_connection->auth_password = NULL;
  1062. }
  1063. if (NULL != fwd->forward_host)
  1064. {
  1065. server_connection->forward_host = strdup_or_die(fwd->forward_host);
  1066. }
  1067. else
  1068. {
  1069. server_connection->forward_host = NULL;
  1070. }
  1071. server_connection->forward_port = fwd->forward_port;
  1072. }
  1073. #endif /* FEATURE_CONNECTION_KEEP_ALIVE */
  1074. /*********************************************************************
  1075. *
  1076. * Function : verify_request_length
  1077. *
  1078. * Description : Checks if we already got the whole client requests
  1079. * and sets CSP_FLAG_CLIENT_REQUEST_COMPLETELY_READ if
  1080. * we do.
  1081. *
  1082. * Data that doesn't belong to the current request is
  1083. * either thrown away to let the client retry on a clean
  1084. * socket, or stashed to be dealt with after the current
  1085. * request is served.
  1086. *
  1087. * Parameters :
  1088. * 1 : csp = Current client state (buffers, headers, etc...)
  1089. *
  1090. * Returns : void
  1091. *
  1092. *********************************************************************/
  1093. static void verify_request_length(struct client_state *csp)
  1094. {
  1095. unsigned long long buffered_request_bytes =
  1096. (unsigned long long)(csp->client_iob->eod - csp->client_iob->cur);
  1097. if ((csp->expected_client_content_length != 0)
  1098. && (buffered_request_bytes != 0))
  1099. {
  1100. if (csp->expected_client_content_length >= buffered_request_bytes)
  1101. {
  1102. csp->expected_client_content_length -= buffered_request_bytes;
  1103. log_error(LOG_LEVEL_CONNECT, "Reduced expected bytes to %llu "
  1104. "to account for the %llu ones we already got.",
  1105. csp->expected_client_content_length, buffered_request_bytes);
  1106. }
  1107. else
  1108. {
  1109. assert(csp->client_iob->eod > csp->client_iob->cur + csp->expected_client_content_length);
  1110. csp->client_iob->eod = csp->client_iob->cur + csp->expected_client_content_length;
  1111. log_error(LOG_LEVEL_CONNECT, "Reducing expected bytes to 0. "
  1112. "Marking the server socket tainted after throwing %llu bytes away.",
  1113. buffered_request_bytes - csp->expected_client_content_length);
  1114. csp->expected_client_content_length = 0;
  1115. csp->flags |= CSP_FLAG_SERVER_SOCKET_TAINTED;
  1116. }
  1117. if (csp->expected_client_content_length == 0)
  1118. {
  1119. csp->flags |= CSP_FLAG_CLIENT_REQUEST_COMPLETELY_READ;
  1120. }
  1121. }
  1122. if (!(csp->flags & CSP_FLAG_CLIENT_REQUEST_COMPLETELY_READ)
  1123. && ((csp->client_iob->cur < csp->client_iob->eod)
  1124. || (csp->expected_client_content_length != 0)))
  1125. {
  1126. if (strcmpic(csp->http->gpc, "GET")
  1127. && strcmpic(csp->http->gpc, "HEAD")
  1128. && strcmpic(csp->http->gpc, "TRACE")
  1129. && strcmpic(csp->http->gpc, "OPTIONS")
  1130. && strcmpic(csp->http->gpc, "DELETE"))
  1131. {
  1132. /* XXX: this is an incomplete hack */
  1133. csp->flags &= ~CSP_FLAG_CLIENT_REQUEST_COMPLETELY_READ;
  1134. log_error(LOG_LEVEL_CONNECT, "There better be a request body.");
  1135. }
  1136. else
  1137. {
  1138. csp->flags |= CSP_FLAG_CLIENT_REQUEST_COMPLETELY_READ;
  1139. if ((csp->config->feature_flags & RUNTIME_FEATURE_TOLERATE_PIPELINING) == 0)
  1140. {
  1141. csp->flags |= CSP_FLAG_SERVER_SOCKET_TAINTED;
  1142. log_error(LOG_LEVEL_CONNECT,
  1143. "Possible pipeline attempt detected. The connection will not "
  1144. "be kept alive and we will only serve the first request.");
  1145. /* Nuke the pipelined requests from orbit, just to be sure. */
  1146. clear_iob(csp->client_iob);
  1147. }
  1148. else
  1149. {
  1150. /*
  1151. * Keep the pipelined data around for now, we'll deal with
  1152. * it once we're done serving the current request.
  1153. */
  1154. csp->flags |= CSP_FLAG_PIPELINED_REQUEST_WAITING;
  1155. assert(csp->client_iob->eod >= csp->client_iob->cur);
  1156. log_error(LOG_LEVEL_CONNECT, "Complete client request followed by "
  1157. "%d bytes of pipelined data received.",
  1158. (int)(csp->client_iob->eod - csp->client_iob->cur));
  1159. }
  1160. }
  1161. }
  1162. else
  1163. {
  1164. csp->flags |= CSP_FLAG_CLIENT_REQUEST_COMPLETELY_READ;
  1165. log_error(LOG_LEVEL_CONNECT, "Complete client request received.");
  1166. }
  1167. }
  1168. /*********************************************************************
  1169. *
  1170. * Function : mark_server_socket_tainted
  1171. *
  1172. * Description : Makes sure we don't reuse a server socket
  1173. * (if we didn't read everything the server sent
  1174. * us reusing the socket would lead to garbage).
  1175. *
  1176. * Parameters :
  1177. * 1 : csp = Current client state (buffers, headers, etc...)
  1178. *
  1179. * Returns : void.
  1180. *
  1181. *********************************************************************/
  1182. static void mark_server_socket_tainted(struct client_state *csp)
  1183. {
  1184. /*
  1185. * For consistency we always mark the server socket
  1186. * tainted, however, to reduce the log noise we only
  1187. * emit a log message if the server socket could have
  1188. * actually been reused.
  1189. */
  1190. if ((csp->flags & CSP_FLAG_SERVER_CONNECTION_KEEP_ALIVE)
  1191. && !(csp->flags & CSP_FLAG_SERVER_SOCKET_TAINTED))
  1192. {
  1193. log_error(LOG_LEVEL_CONNECT,
  1194. "Marking the server socket %d tainted.",
  1195. csp->server_connection.sfd);
  1196. }
  1197. csp->flags |= CSP_FLAG_SERVER_SOCKET_TAINTED;
  1198. }
  1199. /*********************************************************************
  1200. *
  1201. * Function : get_request_line
  1202. *
  1203. * Description : Read the client request line.
  1204. *
  1205. * Parameters :
  1206. * 1 : csp = Current client state (buffers, headers, etc...)
  1207. *
  1208. * Returns : Pointer to request line or NULL in case of errors.
  1209. *
  1210. *********************************************************************/
  1211. static char *get_request_line(struct client_state *csp)
  1212. {
  1213. char buf[BUFFER_SIZE];
  1214. char *request_line = NULL;
  1215. int len;
  1216. memset(buf, 0, sizeof(buf));
  1217. if ((csp->flags & CSP_FLAG_PIPELINED_REQUEST_WAITING) != 0)
  1218. {
  1219. /*
  1220. * If there are multiple pipelined requests waiting,
  1221. * the flag will be set again once the next request
  1222. * has been parsed.
  1223. */
  1224. csp->flags &= ~CSP_FLAG_PIPELINED_REQUEST_WAITING;
  1225. request_line = get_header(csp->client_iob);
  1226. if ((NULL != request_line) && ('\0' != *request_line))
  1227. {
  1228. return request_line;
  1229. }
  1230. else
  1231. {
  1232. log_error(LOG_LEVEL_CONNECT, "No complete request line "
  1233. "received yet. Continuing reading from %d.", csp->cfd);
  1234. }
  1235. }
  1236. do
  1237. {
  1238. if (
  1239. #ifdef FUZZ
  1240. 0 == (csp->flags & CSP_FLAG_FUZZED_INPUT) &&
  1241. #endif
  1242. !data_is_available(csp->cfd, csp->config->socket_timeout)
  1243. )
  1244. {
  1245. if (socket_is_still_alive(csp->cfd))
  1246. {
  1247. log_error(LOG_LEVEL_CONNECT,
  1248. "No request line on socket %d received in time. Timeout: %d.",
  1249. csp->cfd, csp->config->socket_timeout);
  1250. write_socket_delayed(csp->cfd, CLIENT_CONNECTION_TIMEOUT_RESPONSE,
  1251. strlen(CLIENT_CONNECTION_TIMEOUT_RESPONSE),
  1252. get_write_delay(csp));
  1253. }
  1254. else
  1255. {
  1256. log_error(LOG_LEVEL_CONNECT,
  1257. "The client side of the connection on socket %d got "
  1258. "closed without sending a complete request line.", csp->cfd);
  1259. }
  1260. return NULL;
  1261. }
  1262. len = read_socket(csp->cfd, buf, sizeof(buf) - 1);
  1263. if (len <= 0) return NULL;
  1264. /*
  1265. * If there is no memory left for buffering the
  1266. * request, there is nothing we can do but hang up
  1267. */
  1268. if (add_to_iob(csp->client_iob, csp->config->buffer_limit, buf, len))
  1269. {
  1270. return NULL;
  1271. }
  1272. request_line = get_header(csp->client_iob);
  1273. } while ((NULL != request_line) && ('\0' == *request_line));
  1274. return request_line;
  1275. }
  1276. enum chunk_status
  1277. {
  1278. CHUNK_STATUS_MISSING_DATA,
  1279. CHUNK_STATUS_BODY_COMPLETE,
  1280. CHUNK_STATUS_PARSE_ERROR
  1281. };
  1282. /*********************************************************************
  1283. *
  1284. * Function : chunked_body_is_complete
  1285. *
  1286. * Description : Figures out whether or not a chunked body is complete.
  1287. *
  1288. * Currently it always starts at the beginning of the
  1289. * buffer which is somewhat wasteful and prevents Privoxy
  1290. * from starting to forward the correctly parsed chunks
  1291. * as soon as theoretically possible.
  1292. *
  1293. * Should be modified to work with a common buffer,
  1294. * and allow the caller to skip already parsed chunks.
  1295. *
  1296. * This would allow the function to be used for unbuffered
  1297. * response bodies as well.
  1298. *
  1299. * Parameters :
  1300. * 1 : iob = Buffer with the body to check.
  1301. * 2 : length = Length of complete body
  1302. *
  1303. * Returns : Enum with the result of the check.
  1304. *
  1305. *********************************************************************/
  1306. static enum chunk_status chunked_body_is_complete(struct iob *iob, size_t *length)
  1307. {
  1308. unsigned int chunksize;
  1309. char *p = iob->cur;
  1310. do
  1311. {
  1312. /*
  1313. * We need at least a single digit, followed by "\r\n",
  1314. * followed by an unknown amount of data, followed by "\r\n".
  1315. */
  1316. if (p + 5 > iob->eod)
  1317. {
  1318. return CHUNK_STATUS_MISSING_DATA;
  1319. }
  1320. if (sscanf(p, "%x", &chunksize) != 1)
  1321. {
  1322. return CHUNK_STATUS_PARSE_ERROR;
  1323. }
  1324. /*
  1325. * We want at least a single digit, followed by "\r\n",
  1326. * followed by the specified amount of data, followed by "\r\n".
  1327. */
  1328. if (p + chunksize + 5 > iob->eod)
  1329. {
  1330. return CHUNK_STATUS_MISSING_DATA;
  1331. }
  1332. /* Skip chunk-size. */
  1333. p = strstr(p, "\r\n");
  1334. if (NULL == p)
  1335. {
  1336. return CHUNK_STATUS_PARSE_ERROR;
  1337. }
  1338. /* Move beyond the chunkdata. */
  1339. p += 2 + chunksize;
  1340. /* There should be another "\r\n" to skip */
  1341. if (memcmp(p, "\r\n", 2))
  1342. {
  1343. return CHUNK_STATUS_PARSE_ERROR;
  1344. }
  1345. p += 2;
  1346. } while (chunksize > 0U);
  1347. *length = (size_t)(p - iob->cur);
  1348. assert(*length <= (size_t)(iob->eod - iob->cur));
  1349. assert(p <= iob->eod);
  1350. return CHUNK_STATUS_BODY_COMPLETE;
  1351. }
  1352. /*********************************************************************
  1353. *
  1354. * Function : receive_chunked_client_request_body
  1355. *
  1356. * Description : Read the chunk-encoded client request body.
  1357. * Failures are dealt with.
  1358. *
  1359. * Parameters :
  1360. * 1 : csp = Current client state (buffers, headers, etc...)
  1361. *
  1362. * Returns : JB_ERR_OK or JB_ERR_PARSE
  1363. *
  1364. *********************************************************************/
  1365. static jb_err receive_chunked_client_request_body(struct client_state *csp)
  1366. {
  1367. size_t body_length;
  1368. enum chunk_status status;
  1369. while (CHUNK_STATUS_MISSING_DATA ==
  1370. (status = chunked_body_is_complete(csp->client_iob, &body_length)))
  1371. {
  1372. char buf[BUFFER_SIZE];
  1373. int len;
  1374. if (!data_is_available(csp->cfd, csp->config->socket_timeout))
  1375. {
  1376. log_error(LOG_LEVEL_ERROR,
  1377. "Timeout while waiting for the client body.");
  1378. break;
  1379. }
  1380. len = read_socket(csp->cfd, buf, sizeof(buf) - 1);
  1381. if (len <= 0)
  1382. {
  1383. log_error(LOG_LEVEL_ERROR, "Read the client body failed: %E");
  1384. break;
  1385. }
  1386. if (add_to_iob(csp->client_iob, csp->config->buffer_limit, buf, len))
  1387. {
  1388. break;
  1389. }
  1390. }
  1391. if (status != CHUNK_STATUS_BODY_COMPLETE)
  1392. {
  1393. write_socket_delayed(csp->cfd, CLIENT_BODY_PARSE_ERROR_RESPONSE,
  1394. strlen(CLIENT_BODY_PARSE_ERROR_RESPONSE), get_write_delay(csp));
  1395. log_error(LOG_LEVEL_CLF,
  1396. "%s - - [%T] \"Failed reading chunked client body\" 400 0", csp->ip_addr_str);
  1397. return JB_ERR_PARSE;
  1398. }
  1399. log_error(LOG_LEVEL_CONNECT,
  1400. "Chunked client body completely read. Length: %lu", body_length);
  1401. csp->expected_client_content_length = body_length;
  1402. return JB_ERR_OK;
  1403. }
  1404. #ifdef FUZZ
  1405. /*********************************************************************
  1406. *
  1407. * Function : fuzz_chunked_transfer_encoding
  1408. *
  1409. * Description : Treat the fuzzed input as chunked transfer encoding
  1410. * to check and dechunk.
  1411. *
  1412. * Parameters :
  1413. * 1 : csp = Used to store the data.
  1414. * 2 : fuzz_input_file = File to read the input from.
  1415. *
  1416. * Returns : Result of dechunking
  1417. *
  1418. *********************************************************************/
  1419. extern int fuzz_chunked_transfer_encoding(struct client_state *csp, char *fuzz_input_file)
  1420. {
  1421. size_t length;
  1422. size_t size = (size_t)(csp->iob->eod - csp->iob->cur);
  1423. enum chunk_status status;
  1424. status = chunked_body_is_complete(csp->iob, &length);
  1425. if (CHUNK_STATUS_BODY_COMPLETE != status)
  1426. {
  1427. log_error(LOG_LEVEL_INFO, "Chunked body is incomplete or invalid");
  1428. }
  1429. return (JB_ERR_OK == remove_chunked_transfer_coding(csp->iob->cur, &size));
  1430. }
  1431. /*********************************************************************
  1432. *
  1433. * Function : fuzz_client_request
  1434. *
  1435. * Description : Try to get a client request from the fuzzed input.
  1436. *
  1437. * Parameters :
  1438. * 1 : csp = Current client state (buffers, headers, etc...)
  1439. * 2 : fuzz_input_file = File to read the input from.
  1440. *
  1441. * Returns : Result of fuzzing.
  1442. *
  1443. *********************************************************************/
  1444. extern int fuzz_client_request(struct client_state *csp, char *fuzz_input_file)
  1445. {
  1446. jb_err err;
  1447. csp->cfd = 0;
  1448. csp->ip_addr_str = "fuzzer";
  1449. if (strcmp(fuzz_input_file, "-") != 0)
  1450. {
  1451. log_error(LOG_LEVEL_FATAL,
  1452. "Fuzzed client requests can currently only be read from stdin (-).");
  1453. }
  1454. err = receive_client_request(csp);
  1455. if (err != JB_ERR_OK)
  1456. {
  1457. return 1;
  1458. }
  1459. err = parse_client_request(csp);
  1460. if (err != JB_ERR_OK)
  1461. {
  1462. return 1;
  1463. }
  1464. return 0;
  1465. }
  1466. #endif /* def FUZZ */
  1467. #ifdef FEATURE_FORCE_LOAD
  1468. /*********************************************************************
  1469. *
  1470. * Function : force_required
  1471. *
  1472. * Description : Checks a request line to see if it contains
  1473. * the FORCE_PREFIX. If it does, it is removed
  1474. * unless enforcing requests has beend disabled.
  1475. *
  1476. * Parameters :
  1477. * 1 : request_line = HTTP request line
  1478. *
  1479. * Returns : TRUE if force is required, FALSE otherwise.
  1480. *
  1481. *********************************************************************/
  1482. static int force_required(const struct client_state *csp, char *request_line)
  1483. {
  1484. char *p;
  1485. p = strstr(request_line, "http://");
  1486. if (p != NULL)
  1487. {
  1488. /* Skip protocol */
  1489. p += strlen("http://");
  1490. }
  1491. else
  1492. {
  1493. /* Intercepted request usually don't specify the protocol. */
  1494. p = request_line;
  1495. }
  1496. /* Go to the beginning of the path */
  1497. p = strstr(p, "/");
  1498. if (p == NULL)
  1499. {
  1500. /*
  1501. * If the path is missing the request line is invalid and we
  1502. * are done here. The client-visible rejection happens later on.
  1503. */
  1504. return 0;
  1505. }
  1506. if (0 == strncmpic(p, FORCE_PREFIX, strlen(FORCE_PREFIX) - 1))
  1507. {
  1508. if (!(csp->config->feature_flags & RUNTIME_FEATURE_ENFORCE_BLOCKS))
  1509. {
  1510. /* XXX: Should clean more carefully */
  1511. strclean(request_line, FORCE_PREFIX);
  1512. log_error(LOG_LEVEL_FORCE,
  1513. "Enforcing request: \"%s\".", request_line);
  1514. return 1;
  1515. }
  1516. log_error(LOG_LEVEL_FORCE,
  1517. "Ignored force prefix in request: \"%s\".", request_line);
  1518. }
  1519. return 0;
  1520. }
  1521. #endif /* def FEATURE_FORCE_LOAD */
  1522. /*********************************************************************
  1523. *
  1524. * Function : receive_client_request
  1525. *
  1526. * Description : Read the client's request (more precisely the
  1527. * client headers) and answer it if necessary.
  1528. *
  1529. * Parameters :
  1530. * 1 : csp = Current client state (buffers, headers, etc...)
  1531. *
  1532. * Returns : JB_ERR_OK, JB_ERR_PARSE or JB_ERR_MEMORY
  1533. *
  1534. *********************************************************************/
  1535. static jb_err receive_client_request(struct client_state *csp)
  1536. {
  1537. char buf[BUFFER_SIZE];
  1538. char *p;
  1539. char *req = NULL;
  1540. struct http_request *http;
  1541. int len;
  1542. jb_err err;
  1543. /* Temporary copy of the client's headers before they get enlisted in csp->headers */
  1544. struct list header_list;
  1545. struct list *headers = &header_list;
  1546. /* We don't care if the arriving data is a valid HTTP request or not. */
  1547. csp->requests_received_total++;
  1548. http = csp->http;
  1549. memset(buf, 0, sizeof(buf));
  1550. req = get_request_line(csp);
  1551. if (req == NULL)
  1552. {
  1553. mark_server_socket_tainted(csp);
  1554. return JB_ERR_PARSE;
  1555. }
  1556. assert(*req != '\0');
  1557. if (client_protocol_is_unsupported(csp, req))
  1558. {
  1559. return JB_ERR_PARSE;
  1560. }
  1561. #ifdef FEATURE_FORCE_LOAD
  1562. if (force_required(csp, req))
  1563. {
  1564. csp->flags |= CSP_FLAG_FORCED;
  1565. }
  1566. #endif /* def FEATURE_FORCE_LOAD */
  1567. err = parse_http_request(req, http);
  1568. freez(req);
  1569. if (JB_ERR_OK != err)
  1570. {
  1571. write_socket_delayed(csp->cfd, CHEADER, strlen(CHEADER),
  1572. get_write_delay(csp));
  1573. /* XXX: Use correct size */
  1574. log_error(LOG_LEVEL_CLF, "%s - - [%T] \"Invalid request\" 400 0", csp->ip_addr_str);
  1575. log_error(LOG_LEVEL_ERROR,
  1576. "Couldn't parse request line received from %s: %s",
  1577. csp->ip_addr_str, jb_err_to_string(err));
  1578. free_http_request(http);
  1579. return JB_ERR_PARSE;
  1580. }
  1581. /* grab the rest of the client's headers */
  1582. init_list(headers);
  1583. for (;;)
  1584. {
  1585. p = get_header(csp->client_iob);
  1586. if (p == NULL)
  1587. {
  1588. /* There are no additional headers to read. */
  1589. break;
  1590. }
  1591. if (*p == '\0')
  1592. {
  1593. /*
  1594. * We didn't receive a complete header
  1595. * line yet, get the rest of it.
  1596. */
  1597. if (!data_is_available(csp->cfd, csp->config->socket_timeout))
  1598. {
  1599. log_error(LOG_LEVEL_ERROR,
  1600. "Stopped grabbing the client headers.");
  1601. destroy_list(headers);
  1602. return JB_ERR_PARSE;
  1603. }
  1604. len = read_socket(csp->cfd, buf, sizeof(buf) - 1);
  1605. if (len <= 0)
  1606. {
  1607. log_error(LOG_LEVEL_ERROR, "read from client failed: %E");
  1608. destroy_list(headers);
  1609. return JB_ERR_PARSE;
  1610. }
  1611. if (add_to_iob(csp->client_iob, csp->config->buffer_limit, buf, len))
  1612. {
  1613. /*
  1614. * If there is no memory left for buffering the
  1615. * request, there is nothing we can do but hang up
  1616. */
  1617. destroy_list(headers);
  1618. return JB_ERR_MEMORY;
  1619. }
  1620. }
  1621. else
  1622. {
  1623. if (!strncmpic(p, "Transfer-Encoding:", 18))
  1624. {
  1625. /*
  1626. * XXX: should be called through sed()
  1627. * but currently can't.
  1628. */
  1629. client_transfer_encoding(csp, &p);
  1630. }
  1631. /*
  1632. * We were able to read a complete
  1633. * header and can finally enlist it.
  1634. */
  1635. enlist(headers, p);
  1636. freez(p);
  1637. }
  1638. }
  1639. if (http->host == NULL)
  1640. {
  1641. /*
  1642. * If we still don't know the request destination,
  1643. * the request is invalid or the client uses
  1644. * Privoxy without its knowledge.
  1645. */
  1646. if (JB_ERR_OK != get_request_destination_elsewhere(csp, headers))
  1647. {
  1648. /*
  1649. * Our attempts to get the request destination
  1650. * elsewhere failed or Privoxy is configured
  1651. * to only accept proxy requests.
  1652. *
  1653. * An error response has already been send
  1654. * and we're done here.
  1655. */
  1656. return JB_ERR_PARSE;
  1657. }
  1658. }
  1659. #ifdef FEATURE_CLIENT_TAGS
  1660. /* XXX: If the headers were enlisted sooner, passing csp would do. */
  1661. set_client_address(csp, headers);
  1662. get_tag_list_for_client(csp->client_tags, csp->client_address);
  1663. #endif
  1664. /*
  1665. * Determine the actions for this URL
  1666. */
  1667. #ifdef FEATURE_TOGGLE
  1668. if (!(csp->flags & CSP_FLAG_TOGGLED_ON))
  1669. {
  1670. /* Most compatible set of actions (i.e. none) */
  1671. init_current_action(csp->action);
  1672. }
  1673. else
  1674. #endif /* ndef FEATURE_TOGGLE */
  1675. {
  1676. get_url_actions(csp, http);
  1677. }
  1678. enlist(csp->headers, http->cmd);
  1679. /* Append the previously read headers */
  1680. err = list_append_list_unique(csp->headers, headers);
  1681. destroy_list(headers);
  1682. return err;
  1683. }
  1684. /*********************************************************************
  1685. *
  1686. * Function : parse_client_request
  1687. *
  1688. * Description : Parses the client's request and decides what to do
  1689. * with it.
  1690. *
  1691. * Note that since we're not using select() we could get
  1692. * blocked here if a client connected, then didn't say
  1693. * anything!
  1694. *
  1695. * Parameters :
  1696. * 1 : csp = Current client state (buffers, headers, etc...)
  1697. *
  1698. * Returns : JB_ERR_OK or JB_ERR_PARSE
  1699. *
  1700. *********************************************************************/
  1701. static jb_err parse_client_request(struct client_state *csp)
  1702. {
  1703. struct http_request *http = csp->http;
  1704. jb_err err;
  1705. #ifdef FEATURE_CONNECTION_KEEP_ALIVE
  1706. if ((csp->config->feature_flags & RUNTIME_FEATURE_CONNECTION_KEEP_ALIVE)
  1707. && (!strcmpic(csp->http->version, "HTTP/1.1"))
  1708. && (csp->http->ssl == 0))
  1709. {
  1710. /* Assume persistence until further notice */
  1711. csp->flags |= CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE;
  1712. }
  1713. #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
  1714. if (csp->http->ssl == 0)
  1715. {
  1716. /*
  1717. * This whole block belongs to chat() but currently
  1718. * has to be executed before sed().
  1719. */
  1720. if (csp->flags & CSP_FLAG_CHUNKED_CLIENT_BODY)
  1721. {
  1722. if (receive_chunked_client_request_body(csp) != JB_ERR_OK)
  1723. {
  1724. return JB_ERR_PARSE;
  1725. }
  1726. }
  1727. else
  1728. {
  1729. csp->expected_client_content_length = get_expected_content_length(csp->headers);
  1730. }
  1731. verify_request_length(csp);
  1732. }
  1733. #ifndef FEATURE_HTTPS_INSPECTION
  1734. else
  1735. {
  1736. csp->flags |= CSP_FLAG_SERVER_SOCKET_TAINTED;
  1737. }
  1738. #endif
  1739. err = sed(csp, FILTER_CLIENT_HEADERS);
  1740. if (JB_ERR_OK != err)
  1741. {
  1742. log_error(LOG_LEVEL_ERROR, "Failed to parse client request from %s.",
  1743. csp->ip_addr_str);
  1744. log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 400 0",
  1745. csp->ip_addr_str, csp->http->cmd);
  1746. write_socket_delayed(csp->cfd, CHEADER, strlen(CHEADER), get_write_delay(csp));
  1747. return JB_ERR_PARSE;
  1748. }
  1749. csp->flags |= CSP_FLAG_CLIENT_HEADER_PARSING_DONE;
  1750. /* Check request line for rewrites. */
  1751. if ((NULL == csp->headers->first->str)
  1752. || (strcmp(http->cmd, csp->headers->first->str) &&
  1753. (JB_ERR_OK != change_request_destination(csp))))
  1754. {
  1755. /*
  1756. * A header filter broke the request line - bail out.
  1757. */
  1758. write_socket_delayed(csp->cfd, MESSED_UP_REQUEST_RESPONSE,
  1759. strlen(MESSED_UP_REQUEST_RESPONSE), get_write_delay(csp));
  1760. /* XXX: Use correct size */
  1761. log_error(LOG_LEVEL_CLF,
  1762. "%s - - [%T] \"Invalid request generated\" 500 0", csp->ip_addr_str);
  1763. log_error(LOG_LEVEL_ERROR,
  1764. "Invalid request line after applying header filters.");
  1765. free_http_request(http);
  1766. return JB_ERR_PARSE;
  1767. }
  1768. if (client_has_unsupported_expectations(csp))
  1769. {
  1770. return JB_ERR_PARSE;
  1771. }
  1772. return JB_ERR_OK;
  1773. }
  1774. /*********************************************************************
  1775. *
  1776. * Function : send_http_request
  1777. *
  1778. * Description : Sends the HTTP headers from the client request
  1779. * and all the body data that has already been received.
  1780. *
  1781. * Parameters :
  1782. * 1 : csp = Current client state (buffers, headers, etc...)
  1783. *
  1784. * Returns : 0 on success, anything else is an error.
  1785. *
  1786. *********************************************************************/
  1787. static int send_http_request(struct client_state *csp)
  1788. {
  1789. char *hdr;
  1790. int write_failure;
  1791. hdr = list_to_text(csp->headers);
  1792. if (hdr == NULL)
  1793. {
  1794. /* FIXME Should handle error properly */
  1795. log_error(LOG_LEVEL_FATAL, "Out of memory parsing client header");
  1796. }
  1797. list_remove_all(csp->headers);
  1798. /*
  1799. * Write the client's (modified) header to the server
  1800. * (along with anything else that may be in the buffer)
  1801. */
  1802. write_failure = 0 != write_socket(csp->server_connection.sfd, hdr, strlen(hdr));
  1803. freez(hdr);
  1804. if (write_failure)
  1805. {
  1806. log_error(LOG_LEVEL_CONNECT, "Failed sending request headers to: %s: %E",
  1807. csp->http->hostport);
  1808. }
  1809. else if (((csp->flags & CSP_FLAG_PIPELINED_REQUEST_WAITING) == 0)
  1810. && (flush_iob(csp->server_connection.sfd, csp->client_iob, 0) < 0))
  1811. {
  1812. write_failure = 1;
  1813. log_error(LOG_LEVEL_CONNECT, "Failed sending request body to: %s: %E",
  1814. csp->http->hostport);
  1815. }
  1816. return write_failure;
  1817. }
  1818. #ifdef FEATURE_HTTPS_INSPECTION
  1819. /*********************************************************************
  1820. *
  1821. * Function : receive_and_send_encrypted_post_data
  1822. *
  1823. * Description : Reads remaining POST data from the client and sends
  1824. * it to the server.
  1825. *
  1826. * Parameters :
  1827. * 1 : csp = Current client state (buffers, headers, etc...)
  1828. *
  1829. * Returns : 0 on success, anything else is an error.
  1830. *
  1831. *********************************************************************/
  1832. static int receive_and_send_encrypted_post_data(struct client_state *csp)
  1833. {
  1834. int content_length_known = csp->expected_client_content_length != 0;
  1835. while (is_ssl_pending(&(csp->ssl_client_attr))
  1836. || (content_length_known && csp->expected_client_content_length != 0))
  1837. {
  1838. unsigned char buf[BUFFER_SIZE];
  1839. int len;
  1840. int max_bytes_to_read = sizeof(buf);
  1841. if (content_length_known && csp->expected_client_content_length < sizeof(buf))
  1842. {
  1843. max_bytes_to_read = (int)csp->expected_client_content_length;
  1844. }
  1845. log_error(LOG_LEVEL_CONNECT,
  1846. "Waiting for up to %d bytes of POST data from the client.",
  1847. max_bytes_to_read);
  1848. len = ssl_recv_data(&(csp->ssl_client_attr), buf,
  1849. (unsigned)max_bytes_to_read);
  1850. if (len == -1)
  1851. {
  1852. return 1;
  1853. }
  1854. if (len == 0)
  1855. {
  1856. /* XXX: Does this actually happen? */
  1857. break;
  1858. }
  1859. log_error(LOG_LEVEL_CONNECT, "Forwarding %d bytes of encrypted POST data",
  1860. len);
  1861. len = ssl_send_data(&(csp->ssl_server_attr), buf, (size_t)len);
  1862. if (len == -1)
  1863. {
  1864. return 1;
  1865. }
  1866. if (csp->expected_client_content_length != 0)
  1867. {
  1868. if (csp->expected_client_content_length >= len)
  1869. {
  1870. csp->expected_client_content_length -= (unsigned)len;
  1871. }
  1872. if (csp->expected_client_content_length == 0)
  1873. {
  1874. log_error(LOG_LEVEL_CONNECT, "Forwarded the last %d bytes", len);
  1875. break;
  1876. }
  1877. }
  1878. }
  1879. log_error(LOG_LEVEL_CONNECT, "Done forwarding encrypted POST data");
  1880. return 0;
  1881. }
  1882. /*********************************************************************
  1883. *
  1884. * Function : send_https_request
  1885. *
  1886. * Description : Sends the HTTP headers from the client request
  1887. * and all the body data that has already been received.
  1888. *
  1889. * Parameters :
  1890. * 1 : csp = Current client state (buffers, headers, etc...)
  1891. *
  1892. * Returns : 0 on success, anything else is an error.
  1893. *
  1894. *********************************************************************/
  1895. static int send_https_request(struct client_state *csp)
  1896. {
  1897. char *hdr;
  1898. int ret;
  1899. long flushed = 0;
  1900. hdr = list_to_text(csp->https_headers);
  1901. if (hdr == NULL)
  1902. {
  1903. /* FIXME Should handle error properly */
  1904. log_error(LOG_LEVEL_FATAL, "Out of memory parsing client header");
  1905. }
  1906. list_remove_all(csp->https_headers);
  1907. /*
  1908. * Write the client's (modified) header to the server
  1909. * (along with anything else that may be in the buffer)
  1910. */
  1911. ret = ssl_send_data(&(csp->ssl_server_attr),
  1912. (const unsigned char *)hdr, strlen(hdr));
  1913. freez(hdr);
  1914. if (ret < 0)
  1915. {
  1916. log_error(LOG_LEVEL_CONNECT,
  1917. "Failed sending encrypted request headers to: %s: %E",
  1918. csp->http->hostport);
  1919. mark_server_socket_tainted(csp);
  1920. return 1;
  1921. }
  1922. if (((csp->flags & CSP_FLAG_PIPELINED_REQUEST_WAITING) == 0)
  1923. && ((flushed = ssl_flush_socket(&(csp->ssl_server_attr),
  1924. csp->client_iob)) < 0))
  1925. {
  1926. log_error(LOG_LEVEL_CONNECT, "Failed sending request body to: %s: %E",
  1927. csp->http->hostport);
  1928. return 1;
  1929. }
  1930. if (flushed != 0 || csp->expected_client_content_length != 0)
  1931. {
  1932. if (csp->expected_client_content_length != 0)
  1933. {
  1934. if (csp->expected_client_content_length < flushed)
  1935. {
  1936. log_error(LOG_LEVEL_ERROR,
  1937. "Flushed %ld bytes of request body while only expecting %llu",
  1938. flushed, csp->expected_client_content_length);
  1939. csp->expected_client_content_length = 0;
  1940. }
  1941. else
  1942. {
  1943. log_error(LOG_LEVEL_CONNECT,
  1944. "Flushed %ld bytes of request body while expecting %llu",
  1945. flushed, csp->expected_client_content_length);
  1946. csp->expected_client_content_length -= (unsigned)flushed;
  1947. if (receive_and_send_encrypted_post_data(csp))
  1948. {
  1949. return 1;
  1950. }
  1951. }
  1952. }
  1953. else
  1954. {
  1955. log_error(LOG_LEVEL_CONNECT,
  1956. "Flushed %ld bytes of request body", flushed);
  1957. }
  1958. }
  1959. log_error(LOG_LEVEL_CONNECT, "Encrypted request sent");
  1960. return 0;
  1961. }
  1962. /*********************************************************************
  1963. *
  1964. * Function : receive_encrypted_request
  1965. *
  1966. * Description : Receives an encrypted request.
  1967. *
  1968. * Parameters :
  1969. * 1 : csp = Current client state (buffers, headers, etc...)
  1970. *
  1971. * Returns : JB_ERR_OK on success,
  1972. * JB_ERR_PARSE or JB_ERR_MEMORY otherwise
  1973. *
  1974. *********************************************************************/
  1975. static jb_err receive_encrypted_request(struct client_state *csp)
  1976. {
  1977. char buf[BUFFER_SIZE];
  1978. int len;
  1979. char *p;
  1980. do
  1981. {
  1982. log_error(LOG_LEVEL_HEADER, "Reading encrypted headers");
  1983. if (!is_ssl_pending(&(csp->ssl_client_attr)) &&
  1984. !data_is_available(csp->cfd, csp->config->socket_timeout))
  1985. {
  1986. log_error(LOG_LEVEL_CONNECT,
  1987. "Socket %d timed out while waiting for client headers", csp->cfd);
  1988. return JB_ERR_PARSE;
  1989. }
  1990. len = ssl_recv_data(&(csp->ssl_client_attr),
  1991. (unsigned char *)buf, sizeof(buf));
  1992. if (len == 0)
  1993. {
  1994. log_error(LOG_LEVEL_CONNECT,
  1995. "Socket %d closed while waiting for client headers", csp->cfd);
  1996. return JB_ERR_PARSE;
  1997. }
  1998. if (len == -1)
  1999. {
  2000. return JB_ERR_PARSE;
  2001. }
  2002. if (add_to_iob(csp->client_iob, csp->config->buffer_limit, buf, len))
  2003. {
  2004. return JB_ERR_MEMORY;
  2005. }
  2006. p = strstr(csp->client_iob->cur, "\r\n\r\n");
  2007. } while (p == NULL);
  2008. log_error(LOG_LEVEL_HEADER, "Encrypted headers received completely");
  2009. return JB_ERR_OK;
  2010. }
  2011. /*********************************************************************
  2012. *
  2013. * Function : process_encrypted_request
  2014. *
  2015. * Description : Receives and parses an encrypted request.
  2016. *
  2017. * Parameters :
  2018. * 1 : csp = Current client state (buffers, headers, etc...)
  2019. *
  2020. * Returns : JB_ERR_OK on success,
  2021. * JB_ERR_PARSE or JB_ERR_MEMORY otherwise
  2022. *
  2023. *********************************************************************/
  2024. static jb_err process_encrypted_request(struct client_state *csp)
  2025. {
  2026. char *p;
  2027. char *request_line;
  2028. jb_err err;
  2029. /* Temporary copy of the client's headers before they get enlisted in csp->https_headers */
  2030. struct list header_list;
  2031. struct list *headers = &header_list;
  2032. assert(csp->ssl_with_client_is_opened);
  2033. #ifdef FEATURE_CONNECTION_KEEP_ALIVE
  2034. if (csp->config->feature_flags & RUNTIME_FEATURE_CONNECTION_KEEP_ALIVE)
  2035. {
  2036. csp->flags |= CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE;
  2037. }
  2038. #endif
  2039. err = receive_encrypted_request(csp);
  2040. if (err != JB_ERR_OK)
  2041. {
  2042. if (csp->client_iob->cur == NULL ||
  2043. csp->client_iob->cur == csp->client_iob->eod)
  2044. {
  2045. /*
  2046. * We did not receive any data, most likely because the
  2047. * client is done. Don't log this as a parse failure.
  2048. */
  2049. return JB_ERR_PARSE;
  2050. }
  2051. /* XXX: Also used for JB_ERR_MEMORY */
  2052. log_error(LOG_LEVEL_ERROR, "Failed to receive encrypted request: %s",
  2053. jb_err_to_string(err));
  2054. ssl_send_data_delayed(&(csp->ssl_client_attr),
  2055. (const unsigned char *)CHEADER, strlen(CHEADER), get_write_delay(csp));
  2056. return err;
  2057. }
  2058. /* We don't need get_request_line() because the whole HTTP head is buffered. */
  2059. request_line = get_header(csp->client_iob);
  2060. if (request_line == NULL)
  2061. {
  2062. log_error(LOG_LEVEL_ERROR, "Failed to get the encrypted request line");
  2063. ssl_send_data_delayed(&(csp->ssl_client_attr),
  2064. (const unsigned char *)CHEADER, strlen(CHEADER), get_write_delay(csp));
  2065. return JB_ERR_PARSE;
  2066. }
  2067. assert(*request_line != '\0');
  2068. if (client_protocol_is_unsupported(csp, request_line))
  2069. {
  2070. /*
  2071. * If the protocol is unsupported we're done here.
  2072. * client_protocol_is_unsupported() took care of sending
  2073. * the error response and logging the error message.
  2074. */
  2075. return JB_ERR_PARSE;
  2076. }
  2077. #ifdef FEATURE_FORCE_LOAD
  2078. if (force_required(csp, request_line))
  2079. {
  2080. csp->flags |= CSP_FLAG_FORCED;
  2081. }
  2082. #endif /* def FEATURE_FORCE_LOAD */
  2083. free_http_request(csp->http);
  2084. err = parse_http_request(request_line, csp->http);
  2085. /* XXX: Restore ssl setting. This is ugly */
  2086. csp->http->client_ssl = 1;
  2087. csp->http->server_ssl = 1;
  2088. freez(request_line);
  2089. if (JB_ERR_OK != err)
  2090. {
  2091. ssl_send_data_delayed(&(csp->ssl_client_attr),
  2092. (const unsigned char *)CHEADER, strlen(CHEADER), get_write_delay(csp));
  2093. /* XXX: Use correct size */
  2094. log_error(LOG_LEVEL_CLF, "%s - - [%T] \"Invalid request\" 400 0", csp->ip_addr_str);
  2095. log_error(LOG_LEVEL_ERROR,
  2096. "Couldn't parse request line received from %s: %s",
  2097. csp->ip_addr_str, jb_err_to_string(err));
  2098. free_http_request(csp->http);
  2099. return JB_ERR_PARSE;
  2100. }
  2101. /* Parse the rest of the client's headers. */
  2102. init_list(headers);
  2103. for (;;)
  2104. {
  2105. p = get_header(csp->client_iob);
  2106. if (p == NULL)
  2107. {
  2108. /* There are no additional headers to read. */
  2109. break;
  2110. }
  2111. enlist(headers, p);
  2112. freez(p);
  2113. }
  2114. if (JB_ERR_OK != get_destination_from_https_headers(headers, csp->http))
  2115. {
  2116. /*
  2117. * Our attempts to get the request destination
  2118. * elsewhere failed.
  2119. */
  2120. log_error(LOG_LEVEL_ERROR,
  2121. "Failed to get the encrypted request destination");
  2122. ssl_send_data_delayed(&(csp->ssl_client_attr),
  2123. (const unsigned char *)CHEADER, strlen(CHEADER), get_write_delay(csp));
  2124. return JB_ERR_PARSE;
  2125. }
  2126. /* Split the domain we just got for pattern matching */
  2127. init_domain_components(csp->http);
  2128. #ifdef FEATURE_CLIENT_TAGS
  2129. /* XXX: If the headers were enlisted sooner, passing csp would do. */
  2130. if (csp->client_address == NULL)
  2131. {
  2132. set_client_address(csp, headers);
  2133. get_tag_list_for_client(csp->client_tags, csp->client_address);
  2134. }
  2135. #endif
  2136. #ifdef FEATURE_TOGGLE
  2137. if ((csp->flags & CSP_FLAG_TOGGLED_ON) != 0)
  2138. #endif
  2139. {
  2140. /*
  2141. * Determine the actions for this request after
  2142. * clearing the ones from the previous one.
  2143. */
  2144. free_current_action(csp->action);
  2145. get_url_actions(csp, csp->http);
  2146. }
  2147. enlist(csp->https_headers, csp->http->cmd);
  2148. /* Append the previously read headers */
  2149. err = list_append_list_unique(csp->https_headers, headers);
  2150. destroy_list(headers);
  2151. if (JB_ERR_OK != err)
  2152. {
  2153. /* XXX: Send error message */
  2154. return err;
  2155. }
  2156. /* XXX: Work around crash */
  2157. csp->error_message = NULL;
  2158. /* XXX: Why do this here? */
  2159. csp->http->ssl = 1;
  2160. err = sed_https(csp);
  2161. if (JB_ERR_OK != err)
  2162. {
  2163. ssl_send_data_delayed(&(csp->ssl_client_attr),
  2164. (const unsigned char *)CHEADER, strlen(CHEADER), get_write_delay(csp));
  2165. log_error(LOG_LEVEL_ERROR, "Failed to parse client request from %s.",
  2166. csp->ip_addr_str);
  2167. log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 400 0",
  2168. csp->ip_addr_str, csp->http->cmd);
  2169. return JB_ERR_PARSE;
  2170. }
  2171. log_error(LOG_LEVEL_HEADER, "Encrypted request processed");
  2172. log_applied_actions(csp->action);
  2173. log_error(LOG_LEVEL_REQUEST, "https://%s%s", csp->http->hostport,
  2174. csp->http->path);
  2175. return err;
  2176. }
  2177. /*********************************************************************
  2178. *
  2179. * Function : cgi_page_requested
  2180. *
  2181. * Description : Checks if a request is for an internal CGI page.
  2182. *
  2183. * Parameters :
  2184. * 1 : host = The host requested by the client.
  2185. *
  2186. * Returns : 1 if a CGI page has been requested, 0 otherwise
  2187. *
  2188. *********************************************************************/
  2189. static int cgi_page_requested(const char *host)
  2190. {
  2191. if ((0 == strcmpic(host, CGI_SITE_1_HOST))
  2192. || (0 == strcmpic(host, CGI_SITE_1_HOST "."))
  2193. || (0 == strcmpic(host, CGI_SITE_2_HOST))
  2194. || (0 == strcmpic(host, CGI_SITE_2_HOST ".")))
  2195. {
  2196. return 1;
  2197. }
  2198. return 0;
  2199. }
  2200. #ifdef FEATURE_CONNECTION_KEEP_ALIVE
  2201. /*********************************************************************
  2202. *
  2203. * Function : continue_https_chat
  2204. *
  2205. * Description : Behaves similar to chat() but only deals with
  2206. * https-inspected requests that arrive on an already
  2207. * established connection. The first request is always
  2208. * served by chat() which is a lot more complex as it
  2209. * has to deal with forwarding settings and connection
  2210. * failures etc.
  2211. *
  2212. * If a connection to the server has already been
  2213. * opened it is reused unless the request is blocked
  2214. * or the forwarder changed.
  2215. *
  2216. * If a connection to the server has not yet been
  2217. * opened (because the previous request was crunched),
  2218. * or the forwarder changed, the connection is dropped
  2219. * so that the client retries on a fresh one.
  2220. *
  2221. * Parameters :
  2222. * 1 : csp = Current client state (buffers, headers, etc...)
  2223. *
  2224. * Returns : Nothing.
  2225. *
  2226. *********************************************************************/
  2227. static void continue_https_chat(struct client_state *csp)
  2228. {
  2229. const struct forward_spec *fwd;
  2230. if (JB_ERR_OK != process_encrypted_request(csp))
  2231. {
  2232. return;
  2233. }
  2234. csp->requests_received_total++;
  2235. /*
  2236. * We have an encrypted request. Check if one of the crunchers wants it.
  2237. */
  2238. if (crunch_response_triggered(csp, crunchers_all))
  2239. {
  2240. /*
  2241. * Yes. The client got the crunch response and we're done here.
  2242. */
  2243. return;
  2244. }
  2245. if (csp->ssl_with_server_is_opened == 0)
  2246. {
  2247. log_error(LOG_LEVEL_CONNECT,
  2248. "Dropping the client connection on socket %d. "
  2249. "The server connection has not been established yet.",
  2250. csp->cfd);
  2251. csp->flags &= ~CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE;
  2252. return;
  2253. }
  2254. assert(csp->server_connection.sfd != JB_INVALID_SOCKET);
  2255. fwd = forward_url(csp, csp->http);
  2256. if (!connection_destination_matches(&csp->server_connection, csp->http, fwd))
  2257. {
  2258. log_error(LOG_LEVEL_CONNECT,
  2259. "Dropping the client connection on socket %d with "
  2260. "server socket %d connected to %s. The forwarder has changed.",
  2261. csp->cfd, csp->server_connection.sfd, csp->server_connection.host);
  2262. csp->flags &= ~CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE;
  2263. return;
  2264. }
  2265. log_error(LOG_LEVEL_CONNECT,
  2266. "Reusing server socket %d connected to %s. Requests already sent: %u.",
  2267. csp->server_connection.sfd, csp->server_connection.host,
  2268. csp->server_connection.requests_sent_total);
  2269. if (send_https_request(csp))
  2270. {
  2271. /*
  2272. * Most likely the server connection timed out. We can't easily
  2273. * create a new one so simply drop the client connection without a
  2274. * error response to let the client retry.
  2275. */
  2276. log_error(LOG_LEVEL_CONNECT,
  2277. "Dropping client connection on socket %d. "
  2278. "Forwarding the encrypted client request failed.",
  2279. csp->cfd);
  2280. return;
  2281. }
  2282. csp->server_connection.requests_sent_total++;
  2283. handle_established_connection(csp);
  2284. freez(csp->receive_buffer);
  2285. }
  2286. #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
  2287. #endif
  2288. /*********************************************************************
  2289. *
  2290. * Function : handle_established_connection
  2291. *
  2292. * Description : Shuffle data between client and server once the
  2293. * connection has been established.
  2294. *
  2295. * Parameters :
  2296. * 1 : csp = Current client state (buffers, headers, etc...)
  2297. *
  2298. * Returns : Nothing.
  2299. *
  2300. *********************************************************************/
  2301. static void handle_established_connection(struct client_state *csp)
  2302. {
  2303. char *hdr;
  2304. char *p;
  2305. int n;
  2306. #ifdef HAVE_POLL
  2307. struct pollfd poll_fds[2];
  2308. #else
  2309. fd_set rfds;
  2310. jb_socket maxfd;
  2311. struct timeval timeout;
  2312. #endif
  2313. int server_body;
  2314. int ms_iis5_hack = 0;
  2315. unsigned long long byte_count = 0;
  2316. struct http_request *http;
  2317. long len = 0; /* for buffer sizes (and negative error codes) */
  2318. int buffer_and_filter_content = 0;
  2319. unsigned int write_delay;
  2320. #ifdef FEATURE_HTTPS_INSPECTION
  2321. int ret = 0;
  2322. int use_ssl_tunnel = 0;
  2323. csp->dont_verify_certificate = 0;
  2324. if (csp->http->ssl && !(csp->action->flags & ACTION_HTTPS_INSPECTION))
  2325. {
  2326. /* Pass encrypted content without filtering. */
  2327. use_ssl_tunnel = 1;
  2328. }
  2329. #endif
  2330. /* Skeleton for HTTP response, if we should intercept the request */
  2331. struct http_response *rsp;
  2332. #ifdef FEATURE_CONNECTION_KEEP_ALIVE
  2333. int watch_client_socket;
  2334. #endif
  2335. csp->receive_buffer_size = csp->config->receive_buffer_size;
  2336. csp->receive_buffer = zalloc(csp->receive_buffer_size + 1);
  2337. if (csp->receive_buffer == NULL)
  2338. {
  2339. log_error(LOG_LEVEL_ERROR,
  2340. "Out of memory. Failed to allocate the receive buffer.");
  2341. rsp = cgi_error_memory();
  2342. send_crunch_response(csp, rsp);
  2343. return;
  2344. }
  2345. http = csp->http;
  2346. #ifndef HAVE_POLL
  2347. maxfd = (csp->cfd > csp->server_connection.sfd) ?
  2348. csp->cfd : csp->server_connection.sfd;
  2349. #endif
  2350. /* pass data between the client and server
  2351. * until one or the other shuts down the connection.
  2352. */
  2353. server_body = 0;
  2354. #ifdef FEATURE_CONNECTION_KEEP_ALIVE
  2355. watch_client_socket = 0 == (csp->flags & CSP_FLAG_PIPELINED_REQUEST_WAITING);
  2356. #endif
  2357. write_delay = get_write_delay(csp);
  2358. for (;;)
  2359. {
  2360. #ifndef HAVE_POLL
  2361. FD_ZERO(&rfds);
  2362. #ifdef FEATURE_CONNECTION_KEEP_ALIVE
  2363. if (!watch_client_socket)
  2364. {
  2365. maxfd = csp->server_connection.sfd;
  2366. }
  2367. else
  2368. #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
  2369. {
  2370. FD_SET(csp->cfd, &rfds);
  2371. }
  2372. FD_SET(csp->server_connection.sfd, &rfds);
  2373. #endif /* ndef HAVE_POLL */
  2374. #ifdef FEATURE_CONNECTION_KEEP_ALIVE
  2375. if ((csp->flags & CSP_FLAG_CHUNKED)
  2376. && !(csp->flags & CSP_FLAG_CONTENT_LENGTH_SET)
  2377. && ((csp->iob->eod - csp->iob->cur) >= 5)
  2378. && !memcmp(csp->iob->eod-5, "0\r\n\r\n", 5))
  2379. {
  2380. /*
  2381. * XXX: This check should be obsolete now,
  2382. * but let's wait a while to be sure.
  2383. */
  2384. log_error(LOG_LEVEL_CONNECT,
  2385. "Looks like we got the last chunk together with "
  2386. "the server headers but didn't detect it earlier. "
  2387. "We better stop reading.");
  2388. byte_count = (unsigned long long)(csp->iob->eod - csp->iob->cur);
  2389. csp->expected_content_length = byte_count;
  2390. csp->flags |= CSP_FLAG_CONTENT_LENGTH_SET;
  2391. }
  2392. if (server_body && server_response_is_complete(csp, byte_count))
  2393. {
  2394. if (csp->expected_content_length == byte_count)
  2395. {
  2396. log_error(LOG_LEVEL_CONNECT,
  2397. "Done reading from server. Content length: %llu as expected. "
  2398. "Bytes most recently read: %ld.",
  2399. byte_count, len);
  2400. }
  2401. else
  2402. {
  2403. log_error(LOG_LEVEL_CONNECT,
  2404. "Done reading from server. Expected content length: %llu. "
  2405. "Actual content length: %llu. Bytes most recently read: %ld.",
  2406. csp->expected_content_length, byte_count, len);
  2407. }
  2408. len = 0;
  2409. /*
  2410. * XXX: Should not jump around, handle_established_connection()
  2411. * is complicated enough already.
  2412. */
  2413. goto reading_done;
  2414. }
  2415. #endif /* FEATURE_CONNECTION_KEEP_ALIVE */
  2416. #ifdef HAVE_POLL
  2417. poll_fds[0].fd = csp->cfd;
  2418. #ifdef FEATURE_CONNECTION_KEEP_ALIVE
  2419. if (!watch_client_socket)
  2420. {
  2421. /*
  2422. * Ignore incoming data, but still watch out
  2423. * for disconnects etc. These flags are always
  2424. * implied anyway but explicitly setting them
  2425. * doesn't hurt.
  2426. */
  2427. poll_fds[0].events = POLLERR|POLLHUP;
  2428. }
  2429. else
  2430. #endif
  2431. {
  2432. poll_fds[0].events = POLLIN;
  2433. }
  2434. poll_fds[1].fd = csp->server_connection.sfd;
  2435. poll_fds[1].events = POLLIN;
  2436. n = poll(poll_fds, 2, csp->config->socket_timeout * 1000);
  2437. #else
  2438. timeout.tv_sec = csp->config->socket_timeout;
  2439. timeout.tv_usec = 0;
  2440. n = select((int)maxfd + 1, &rfds, NULL, NULL, &timeout);
  2441. #endif /* def HAVE_POLL */
  2442. /*server or client not responding in timeout */
  2443. if (n == 0)
  2444. {
  2445. log_error(LOG_LEVEL_CONNECT, "Socket timeout %d reached: %s",
  2446. csp->config->socket_timeout, http->url);
  2447. if ((byte_count == 0) && (http->ssl == 0))
  2448. {
  2449. send_crunch_response(csp, error_response(csp, "connection-timeout"));
  2450. }
  2451. mark_server_socket_tainted(csp);
  2452. #ifdef FEATURE_HTTPS_INSPECTION
  2453. close_client_and_server_ssl_connections(csp);
  2454. #endif
  2455. return;
  2456. }
  2457. else if (n < 0)
  2458. {
  2459. #ifdef HAVE_POLL
  2460. log_error(LOG_LEVEL_ERROR, "poll() failed!: %E");
  2461. #else
  2462. log_error(LOG_LEVEL_ERROR, "select() failed!: %E");
  2463. #endif
  2464. mark_server_socket_tainted(csp);
  2465. #ifdef FEATURE_HTTPS_INSPECTION
  2466. close_client_and_server_ssl_connections(csp);
  2467. #endif
  2468. return;
  2469. }
  2470. /*
  2471. * This is the body of the browser's request,
  2472. * just read and write it.
  2473. *
  2474. * Receives data from browser and sends it to server
  2475. *
  2476. * XXX: Make sure the client doesn't use pipelining
  2477. * behind Privoxy's back.
  2478. */
  2479. #ifdef HAVE_POLL
  2480. if ((poll_fds[0].revents & (POLLERR|POLLHUP|POLLNVAL)) != 0)
  2481. {
  2482. log_error(LOG_LEVEL_CONNECT,
  2483. "The client socket %d has become unusable while "
  2484. "the server socket %d is still open.",
  2485. csp->cfd, csp->server_connection.sfd);
  2486. mark_server_socket_tainted(csp);
  2487. break;
  2488. }
  2489. if (poll_fds[0].revents != 0)
  2490. #else
  2491. if (FD_ISSET(csp->cfd, &rfds))
  2492. #endif /* def HAVE_POLL*/
  2493. {
  2494. int max_bytes_to_read = (int)csp->receive_buffer_size;
  2495. #ifdef FEATURE_CONNECTION_KEEP_ALIVE
  2496. if ((csp->flags & CSP_FLAG_CLIENT_REQUEST_COMPLETELY_READ))
  2497. {
  2498. if (data_is_available(csp->cfd, 0))
  2499. {
  2500. /*
  2501. * If the next request is already waiting, we have
  2502. * to stop select()ing the client socket. Otherwise
  2503. * we would always return right away and get nothing
  2504. * else done.
  2505. */
  2506. watch_client_socket = 0;
  2507. log_error(LOG_LEVEL_CONNECT,
  2508. "Stop watching client socket %d. "
  2509. "There's already another request waiting.",
  2510. csp->cfd);
  2511. continue;
  2512. }
  2513. /*
  2514. * If the client socket is set, but there's no data
  2515. * available on the socket, the client went fishing
  2516. * and continuing talking to the server makes no sense.
  2517. */
  2518. log_error(LOG_LEVEL_CONNECT,
  2519. "The client closed socket %d while "
  2520. "the server socket %d is still open.",
  2521. csp->cfd, csp->server_connection.sfd);
  2522. mark_server_socket_tainted(csp);
  2523. break;
  2524. }
  2525. if (csp->expected_client_content_length != 0)
  2526. {
  2527. if (csp->expected_client_content_length < csp->receive_buffer_size)
  2528. {
  2529. max_bytes_to_read = (int)csp->expected_client_content_length;
  2530. }
  2531. log_error(LOG_LEVEL_CONNECT,
  2532. "Waiting for up to %d bytes from the client.",
  2533. max_bytes_to_read);
  2534. }
  2535. assert(max_bytes_to_read <= csp->receive_buffer_size);
  2536. #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
  2537. #ifdef FEATURE_HTTPS_INSPECTION
  2538. if (client_use_ssl(csp))
  2539. {
  2540. if (csp->http->status == 101)
  2541. {
  2542. len = ssl_recv_data(&(csp->ssl_client_attr),
  2543. (unsigned char *)csp->receive_buffer,
  2544. (size_t)max_bytes_to_read);
  2545. if (len == -1)
  2546. {
  2547. log_error(LOG_LEVEL_ERROR, "Failed to receive data "
  2548. "on client socket %d for an upgraded connection",
  2549. csp->cfd);
  2550. break;
  2551. }
  2552. if (len == 0)
  2553. {
  2554. log_error(LOG_LEVEL_CONNECT, "Done receiving data "
  2555. "on client socket %d for an upgraded connection",
  2556. csp->cfd);
  2557. break;
  2558. }
  2559. byte_count += (unsigned long long)len;
  2560. len = ssl_send_data(&(csp->ssl_server_attr),
  2561. (unsigned char *)csp->receive_buffer, (size_t)len);
  2562. if (len == -1)
  2563. {
  2564. log_error(LOG_LEVEL_ERROR, "Failed to send data "
  2565. "on server socket %d for an upgraded connection",
  2566. csp->server_connection.sfd);
  2567. break;
  2568. }
  2569. continue;
  2570. }
  2571. log_error(LOG_LEVEL_CONNECT, "Breaking with TLS/SSL.");
  2572. break;
  2573. }
  2574. else
  2575. #endif /* def FEATURE_HTTPS_INSPECTION */
  2576. {
  2577. len = read_socket(csp->cfd, csp->receive_buffer, max_bytes_to_read);
  2578. if (len <= 0)
  2579. {
  2580. /* XXX: not sure if this is necessary. */
  2581. mark_server_socket_tainted(csp);
  2582. break; /* "game over, man" */
  2583. }
  2584. #ifdef FEATURE_CONNECTION_KEEP_ALIVE
  2585. if (csp->expected_client_content_length != 0)
  2586. {
  2587. assert(len <= max_bytes_to_read);
  2588. csp->expected_client_content_length -= (unsigned)len;
  2589. log_error(LOG_LEVEL_CONNECT,
  2590. "Expected client content length set to %llu "
  2591. "after reading %ld bytes.",
  2592. csp->expected_client_content_length, len);
  2593. if (csp->expected_client_content_length == 0)
  2594. {
  2595. log_error(LOG_LEVEL_CONNECT,
  2596. "Done reading from the client.");
  2597. csp->flags |= CSP_FLAG_CLIENT_REQUEST_COMPLETELY_READ;
  2598. }
  2599. }
  2600. #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
  2601. if (write_socket(csp->server_connection.sfd, csp->receive_buffer, (size_t)len))
  2602. {
  2603. log_error(LOG_LEVEL_ERROR, "write to: %s failed: %E", http->host);
  2604. mark_server_socket_tainted(csp);
  2605. return;
  2606. }
  2607. }
  2608. continue;
  2609. }
  2610. /*
  2611. * The server wants to talk. It could be the header or the body.
  2612. * If `hdr' is null, then it's the header otherwise it's the body.
  2613. * FIXME: Does `hdr' really mean `host'? No.
  2614. */
  2615. #ifdef HAVE_POLL
  2616. if (poll_fds[1].revents != 0)
  2617. #else
  2618. if (FD_ISSET(csp->server_connection.sfd, &rfds))
  2619. #endif /* HAVE_POLL */
  2620. {
  2621. #ifdef FEATURE_CONNECTION_KEEP_ALIVE
  2622. /*
  2623. * If we are buffering content, we don't want to eat up to
  2624. * buffer-limit bytes if the client no longer cares about them.
  2625. * If we aren't buffering, however, a dead client socket will be
  2626. * noticed pretty much right away anyway, so we can reduce the
  2627. * overhead by skipping the check.
  2628. */
  2629. if (buffer_and_filter_content && !socket_is_still_alive(csp->cfd))
  2630. {
  2631. #ifdef _WIN32
  2632. log_error(LOG_LEVEL_CONNECT,
  2633. "The server still wants to talk, but the client may already have hung up on us.");
  2634. #else
  2635. log_error(LOG_LEVEL_CONNECT,
  2636. "The server still wants to talk, but the client hung up on us.");
  2637. mark_server_socket_tainted(csp);
  2638. #ifdef FEATURE_HTTPS_INSPECTION
  2639. close_client_and_server_ssl_connections(csp);
  2640. #endif
  2641. return;
  2642. #endif /* def _WIN32 */
  2643. }
  2644. #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
  2645. #ifdef FEATURE_HTTPS_INSPECTION
  2646. /*
  2647. * Reading data from standard or secured connection (HTTP/HTTPS)
  2648. */
  2649. if (server_use_ssl(csp))
  2650. {
  2651. len = ssl_recv_data(&(csp->ssl_server_attr),
  2652. (unsigned char *)csp->receive_buffer, csp->receive_buffer_size);
  2653. }
  2654. else
  2655. #endif
  2656. {
  2657. len = read_socket(csp->server_connection.sfd, csp->receive_buffer,
  2658. (int)csp->receive_buffer_size);
  2659. }
  2660. if (len < 0)
  2661. {
  2662. log_error(LOG_LEVEL_ERROR, "read from: %s failed: %E", http->host);
  2663. if ((http->ssl && (csp->fwd == NULL))
  2664. #ifdef FEATURE_HTTPS_INSPECTION
  2665. && use_ssl_tunnel
  2666. #endif
  2667. )
  2668. {
  2669. /*
  2670. * Just hang up. We already confirmed the client's CONNECT
  2671. * request with status code 200 and unencrypted content is
  2672. * no longer welcome.
  2673. */
  2674. log_error(LOG_LEVEL_ERROR,
  2675. "CONNECT already confirmed. Unable to tell the client about the problem.");
  2676. return;
  2677. }
  2678. else if (byte_count)
  2679. {
  2680. /*
  2681. * Just hang up. We already transmitted the original headers
  2682. * and parts of the original content and therefore missed the
  2683. * chance to send an error message (without risking data corruption).
  2684. *
  2685. * XXX: we could retry with a fancy range request here.
  2686. */
  2687. log_error(LOG_LEVEL_ERROR, "Already forwarded the original headers. "
  2688. "Unable to tell the client about the problem.");
  2689. mark_server_socket_tainted(csp);
  2690. #ifdef FEATURE_HTTPS_INSPECTION
  2691. close_client_and_server_ssl_connections(csp);
  2692. #endif
  2693. return;
  2694. }
  2695. /*
  2696. * XXX: Consider handling the cases above the same.
  2697. */
  2698. mark_server_socket_tainted(csp);
  2699. len = 0;
  2700. }
  2701. #ifdef FEATURE_CONNECTION_KEEP_ALIVE
  2702. if (csp->flags & CSP_FLAG_CHUNKED)
  2703. {
  2704. if ((len >= 5) && !memcmp(csp->receive_buffer+len-5, "0\r\n\r\n", 5))
  2705. {
  2706. /* XXX: this is a temporary hack */
  2707. log_error(LOG_LEVEL_CONNECT,
  2708. "Looks like we reached the end of the last chunk. "
  2709. "We better stop reading.");
  2710. csp->expected_content_length = byte_count + (unsigned long long)len;
  2711. csp->flags |= CSP_FLAG_CONTENT_LENGTH_SET;
  2712. }
  2713. }
  2714. reading_done:
  2715. #endif /* FEATURE_CONNECTION_KEEP_ALIVE */
  2716. /*
  2717. * This is guaranteed by allocating with zalloc_or_die()
  2718. * and never (intentionally) writing to the last byte.
  2719. *
  2720. * csp->receive_buffer_size is the size of the part of the
  2721. * buffer we intentionally write to, but we actually
  2722. * allocated csp->receive_buffer_size+1 bytes so the assertion
  2723. * stays within the allocated range.
  2724. */
  2725. assert(csp->receive_buffer[csp->receive_buffer_size] == '\0');
  2726. /*
  2727. * Add a trailing zero to let be able to use string operations.
  2728. * XXX: do we still need this with filter_popups gone?
  2729. */
  2730. assert(len <= csp->receive_buffer_size);
  2731. csp->receive_buffer[len] = '\0';
  2732. /*
  2733. * Normally, this would indicate that we've read
  2734. * as much as the server has sent us and we can
  2735. * close the client connection. However, Microsoft
  2736. * in its wisdom has released IIS/5 with a bug that
  2737. * prevents it from sending the trailing \r\n in
  2738. * a 302 redirect header (and possibly other headers).
  2739. * To work around this if we've haven't parsed
  2740. * a full header we'll append a trailing \r\n
  2741. * and see if this now generates a valid one.
  2742. *
  2743. * This hack shouldn't have any impacts. If we've
  2744. * already transmitted the header or if this is a
  2745. * SSL connection, then we won't bother with this
  2746. * hack. So we only work on partially received
  2747. * headers. If we append a \r\n and this still
  2748. * doesn't generate a valid header, then we won't
  2749. * transmit anything to the client.
  2750. */
  2751. if (len == 0)
  2752. {
  2753. if (server_body || (http->ssl
  2754. #ifdef FEATURE_HTTPS_INSPECTION
  2755. && use_ssl_tunnel
  2756. #endif
  2757. ))
  2758. {
  2759. /*
  2760. * If we have been buffering up the document,
  2761. * now is the time to apply content modification
  2762. * and send the result to the client.
  2763. */
  2764. if (buffer_and_filter_content)
  2765. {
  2766. p = execute_content_filters(csp);
  2767. /*
  2768. * If content filtering fails, use the original
  2769. * buffer and length.
  2770. * (see p != NULL ? p : csp->iob->cur below)
  2771. */
  2772. if (NULL == p)
  2773. {
  2774. csp->content_length = (size_t)(csp->iob->eod - csp->iob->cur);
  2775. }
  2776. #ifdef FEATURE_COMPRESSION
  2777. else if ((csp->flags & CSP_FLAG_CLIENT_SUPPORTS_DEFLATE)
  2778. && (csp->content_length > LOWER_LENGTH_LIMIT_FOR_COMPRESSION))
  2779. {
  2780. char *compressed_content = compress_buffer(p,
  2781. (size_t *)&csp->content_length, csp->config->compression_level);
  2782. if (compressed_content != NULL)
  2783. {
  2784. freez(p);
  2785. p = compressed_content;
  2786. csp->flags |= CSP_FLAG_BUFFERED_CONTENT_DEFLATED;
  2787. }
  2788. }
  2789. #endif
  2790. if (JB_ERR_OK != update_server_headers(csp))
  2791. {
  2792. log_error(LOG_LEVEL_FATAL,
  2793. "Failed to update server headers. after filtering.");
  2794. }
  2795. hdr = list_to_text(csp->headers);
  2796. if (hdr == NULL)
  2797. {
  2798. /* FIXME Should handle error properly */
  2799. log_error(LOG_LEVEL_FATAL, "Out of memory parsing server header");
  2800. }
  2801. #ifdef FEATURE_HTTPS_INSPECTION
  2802. /*
  2803. * Sending data with standard or secured connection (HTTP/HTTPS)
  2804. */
  2805. if (client_use_ssl(csp))
  2806. {
  2807. if ((ssl_send_data_delayed(&(csp->ssl_client_attr),
  2808. (const unsigned char *)hdr, strlen(hdr),
  2809. get_write_delay(csp)) < 0)
  2810. || (ssl_send_data_delayed(&(csp->ssl_client_attr),
  2811. (const unsigned char *) ((p != NULL) ? p : csp->iob->cur),
  2812. csp->content_length, get_write_delay(csp)) < 0))
  2813. {
  2814. log_error(LOG_LEVEL_ERROR, "write modified content to "
  2815. "client over TLS/SSL failed");
  2816. freez(hdr);
  2817. freez(p);
  2818. mark_server_socket_tainted(csp);
  2819. close_client_and_server_ssl_connections(csp);
  2820. return;
  2821. }
  2822. }
  2823. else
  2824. #endif /* def FEATURE_HTTPS_INSPECTION */
  2825. {
  2826. if (write_socket_delayed(csp->cfd, hdr, strlen(hdr), write_delay)
  2827. || write_socket_delayed(csp->cfd, ((p != NULL) ? p : csp->iob->cur),
  2828. (size_t)csp->content_length, write_delay))
  2829. {
  2830. log_error(LOG_LEVEL_ERROR, "write modified content to client failed: %E");
  2831. freez(hdr);
  2832. freez(p);
  2833. mark_server_socket_tainted(csp);
  2834. return;
  2835. }
  2836. }
  2837. freez(hdr);
  2838. freez(p);
  2839. }
  2840. break; /* "game over, man" */
  2841. }
  2842. /*
  2843. * This is NOT the body, so
  2844. * Let's pretend the server just sent us a blank line.
  2845. */
  2846. snprintf(csp->receive_buffer, csp->receive_buffer_size, "\r\n");
  2847. len = (int)strlen(csp->receive_buffer);
  2848. /*
  2849. * Now, let the normal header parsing algorithm below do its
  2850. * job. If it fails, we'll exit instead of continuing.
  2851. */
  2852. ms_iis5_hack = 1;
  2853. }
  2854. /*
  2855. * If we're in the body of the server document, just write it to
  2856. * the client, unless we need to buffer the body for later
  2857. * content-filtering.
  2858. */
  2859. if (server_body || (http->ssl
  2860. #ifdef FEATURE_HTTPS_INSPECTION
  2861. && use_ssl_tunnel
  2862. #endif
  2863. ))
  2864. {
  2865. if (buffer_and_filter_content)
  2866. {
  2867. /*
  2868. * If there is no memory left for buffering the content, or the buffer limit
  2869. * has been reached, switch to non-filtering mode, i.e. make & write the
  2870. * header, flush the iob and buf, and get out of the way.
  2871. */
  2872. if (add_to_iob(csp->iob, csp->config->buffer_limit, csp->receive_buffer, len))
  2873. {
  2874. size_t hdrlen;
  2875. long flushed;
  2876. log_error(LOG_LEVEL_INFO,
  2877. "Flushing header and buffers. Stepping back from filtering.");
  2878. hdr = list_to_text(csp->headers);
  2879. if (hdr == NULL)
  2880. {
  2881. /*
  2882. * Memory is too tight to even generate the header.
  2883. * Send our static "Out-of-memory" page.
  2884. */
  2885. log_error(LOG_LEVEL_ERROR, "Out of memory while trying to flush.");
  2886. rsp = cgi_error_memory();
  2887. send_crunch_response(csp, rsp);
  2888. mark_server_socket_tainted(csp);
  2889. #ifdef FEATURE_HTTPS_INSPECTION
  2890. close_client_and_server_ssl_connections(csp);
  2891. #endif
  2892. return;
  2893. }
  2894. hdrlen = strlen(hdr);
  2895. #ifdef FEATURE_HTTPS_INSPECTION
  2896. /*
  2897. * Sending data with standard or secured connection (HTTP/HTTPS)
  2898. */
  2899. if (client_use_ssl(csp))
  2900. {
  2901. if ((ssl_send_data_delayed(&(csp->ssl_client_attr),
  2902. (const unsigned char *)hdr, hdrlen, get_write_delay(csp)) < 0)
  2903. || ((flushed = ssl_flush_socket(&(csp->ssl_client_attr),
  2904. csp->iob)) < 0)
  2905. || (ssl_send_data_delayed(&(csp->ssl_client_attr),
  2906. (const unsigned char *)csp->receive_buffer, (size_t)len,
  2907. get_write_delay(csp)) < 0))
  2908. {
  2909. log_error(LOG_LEVEL_CONNECT,
  2910. "Flush header and buffers to client failed");
  2911. freez(hdr);
  2912. mark_server_socket_tainted(csp);
  2913. close_client_and_server_ssl_connections(csp);
  2914. return;
  2915. }
  2916. }
  2917. else
  2918. #endif /* def FEATURE_HTTPS_INSPECTION */
  2919. {
  2920. if (write_socket_delayed(csp->cfd, hdr, hdrlen, write_delay)
  2921. || ((flushed = flush_iob(csp->cfd, csp->iob, write_delay)) < 0)
  2922. || write_socket_delayed(csp->cfd, csp->receive_buffer, (size_t)len,
  2923. write_delay))
  2924. {
  2925. log_error(LOG_LEVEL_CONNECT,
  2926. "Flush header and buffers to client failed: %E");
  2927. freez(hdr);
  2928. mark_server_socket_tainted(csp);
  2929. return;
  2930. }
  2931. }
  2932. /*
  2933. * Reset the byte_count to the amount of bytes
  2934. * we just flushed. len will be added a few lines below,
  2935. * hdrlen doesn't matter for LOG_LEVEL_CLF.
  2936. */
  2937. byte_count = (unsigned long long)flushed;
  2938. freez(hdr);
  2939. buffer_and_filter_content = 0;
  2940. server_body = 1;
  2941. }
  2942. }
  2943. else
  2944. {
  2945. #ifdef FEATURE_HTTPS_INSPECTION
  2946. /*
  2947. * Sending data with standard or secured connection (HTTP/HTTPS)
  2948. */
  2949. if (client_use_ssl(csp))
  2950. {
  2951. ret = ssl_send_data_delayed(&(csp->ssl_client_attr),
  2952. (const unsigned char *)csp->receive_buffer, (size_t)len,
  2953. get_write_delay(csp));
  2954. if (ret < 0)
  2955. {
  2956. log_error(LOG_LEVEL_ERROR,
  2957. "Sending data to client failed");
  2958. mark_server_socket_tainted(csp);
  2959. close_client_and_server_ssl_connections(csp);
  2960. return;
  2961. }
  2962. }
  2963. else
  2964. #endif /* def FEATURE_HTTPS_INSPECTION */
  2965. {
  2966. if (write_socket_delayed(csp->cfd, csp->receive_buffer,
  2967. (size_t)len, write_delay))
  2968. {
  2969. log_error(LOG_LEVEL_ERROR, "write to client failed: %E");
  2970. mark_server_socket_tainted(csp);
  2971. return;
  2972. }
  2973. }
  2974. }
  2975. byte_count += (unsigned long long)len;
  2976. continue;
  2977. }
  2978. else
  2979. {
  2980. /*
  2981. * We're still looking for the end of the server's header.
  2982. * Buffer up the data we just read. If that fails, there's
  2983. * little we can do but send our static out-of-memory page.
  2984. */
  2985. if (add_to_iob(csp->iob, csp->config->buffer_limit, csp->receive_buffer, len))
  2986. {
  2987. log_error(LOG_LEVEL_ERROR, "Out of memory while looking for end of server headers.");
  2988. rsp = cgi_error_memory();
  2989. send_crunch_response(csp, rsp);
  2990. mark_server_socket_tainted(csp);
  2991. #ifdef FEATURE_HTTPS_INSPECTION
  2992. close_client_and_server_ssl_connections(csp);
  2993. #endif
  2994. return;
  2995. }
  2996. /* Convert iob into something sed() can digest */
  2997. if (JB_ERR_PARSE == get_server_headers(csp))
  2998. {
  2999. if (ms_iis5_hack)
  3000. {
  3001. /*
  3002. * Well, we tried our MS IIS/5 hack and it didn't work.
  3003. * The header is incomplete and there isn't anything
  3004. * we can do about it.
  3005. */
  3006. log_error(LOG_LEVEL_ERROR, "Invalid server headers. "
  3007. "Applying the MS IIS5 hack didn't help.");
  3008. log_error(LOG_LEVEL_CLF,
  3009. "%s - - [%T] \"%s\" 502 0", csp->ip_addr_str, http->cmd);
  3010. #ifdef FEATURE_HTTPS_INSPECTION
  3011. /*
  3012. * Sending data with standard or secured connection (HTTP/HTTPS)
  3013. */
  3014. if (client_use_ssl(csp))
  3015. {
  3016. ssl_send_data_delayed(&(csp->ssl_client_attr),
  3017. (const unsigned char *)INVALID_SERVER_HEADERS_RESPONSE,
  3018. strlen(INVALID_SERVER_HEADERS_RESPONSE), get_write_delay(csp));
  3019. }
  3020. else
  3021. #endif /* def FEATURE_HTTPS_INSPECTION */
  3022. {
  3023. write_socket_delayed(csp->cfd,
  3024. INVALID_SERVER_HEADERS_RESPONSE,
  3025. strlen(INVALID_SERVER_HEADERS_RESPONSE), write_delay);
  3026. }
  3027. mark_server_socket_tainted(csp);
  3028. #ifdef FEATURE_HTTPS_INSPECTION
  3029. close_client_and_server_ssl_connections(csp);
  3030. #endif
  3031. return;
  3032. }
  3033. else
  3034. {
  3035. /*
  3036. * Since we have to wait for more from the server before
  3037. * we can parse the headers we just continue here.
  3038. */
  3039. log_error(LOG_LEVEL_CONNECT,
  3040. "Continuing buffering server headers from socket %d. "
  3041. "Bytes most recently read: %ld.", csp->cfd, len);
  3042. continue;
  3043. }
  3044. }
  3045. else
  3046. {
  3047. /*
  3048. * Account for the content bytes we
  3049. * might have gotten with the headers.
  3050. */
  3051. assert(csp->iob->eod >= csp->iob->cur);
  3052. byte_count = (unsigned long long)(csp->iob->eod - csp->iob->cur);
  3053. }
  3054. /* Did we actually get anything? */
  3055. if (NULL == csp->headers->first)
  3056. {
  3057. if ((csp->flags & CSP_FLAG_REUSED_CLIENT_CONNECTION))
  3058. {
  3059. log_error(LOG_LEVEL_ERROR,
  3060. "No server or forwarder response received on socket %d. "
  3061. "Closing client socket %d without sending data.",
  3062. csp->server_connection.sfd, csp->cfd);
  3063. log_error(LOG_LEVEL_CLF,
  3064. "%s - - [%T] \"%s\" 502 0", csp->ip_addr_str, http->cmd);
  3065. }
  3066. else
  3067. {
  3068. log_error(LOG_LEVEL_ERROR,
  3069. "No server or forwarder response received on socket %d.",
  3070. csp->server_connection.sfd);
  3071. send_crunch_response(csp, error_response(csp, "no-server-data"));
  3072. }
  3073. free_http_request(http);
  3074. mark_server_socket_tainted(csp);
  3075. #ifdef FEATURE_HTTPS_INSPECTION
  3076. close_client_and_server_ssl_connections(csp);
  3077. #endif
  3078. return;
  3079. }
  3080. if (!csp->headers->first->str)
  3081. {
  3082. log_error(LOG_LEVEL_ERROR, "header search: csp->headers->first->str == NULL, assert will be called");
  3083. }
  3084. assert(csp->headers->first->str);
  3085. if (strncmpic(csp->headers->first->str, "HTTP", 4) &&
  3086. strncmpic(csp->headers->first->str, "ICY", 3))
  3087. {
  3088. /*
  3089. * It doesn't look like a HTTP (or Shoutcast) response:
  3090. * tell the client and log the problem.
  3091. */
  3092. if (strlen(csp->headers->first->str) > 30)
  3093. {
  3094. csp->headers->first->str[30] = '\0';
  3095. }
  3096. log_error(LOG_LEVEL_ERROR,
  3097. "Invalid server or forwarder response. Starts with: %s",
  3098. csp->headers->first->str);
  3099. log_error(LOG_LEVEL_CLF,
  3100. "%s - - [%T] \"%s\" 502 0", csp->ip_addr_str, http->cmd);
  3101. #ifdef FEATURE_HTTPS_INSPECTION
  3102. /*
  3103. * Sending data with standard or secured connection (HTTP/HTTPS)
  3104. */
  3105. if (client_use_ssl(csp))
  3106. {
  3107. ssl_send_data_delayed(&(csp->ssl_client_attr),
  3108. (const unsigned char *)INVALID_SERVER_HEADERS_RESPONSE,
  3109. strlen(INVALID_SERVER_HEADERS_RESPONSE),
  3110. get_write_delay(csp));
  3111. }
  3112. else
  3113. #endif /* def FEATURE_HTTPS_INSPECTION */
  3114. {
  3115. write_socket_delayed(csp->cfd, INVALID_SERVER_HEADERS_RESPONSE,
  3116. strlen(INVALID_SERVER_HEADERS_RESPONSE), write_delay);
  3117. }
  3118. free_http_request(http);
  3119. mark_server_socket_tainted(csp);
  3120. #ifdef FEATURE_HTTPS_INSPECTION
  3121. close_client_and_server_ssl_connections(csp);
  3122. #endif
  3123. return;
  3124. }
  3125. /*
  3126. * We have now received the entire server header,
  3127. * filter it and send the result to the client
  3128. */
  3129. if (JB_ERR_OK != sed(csp, FILTER_SERVER_HEADERS))
  3130. {
  3131. log_error(LOG_LEVEL_CLF,
  3132. "%s - - [%T] \"%s\" 502 0", csp->ip_addr_str, http->cmd);
  3133. #ifdef FEATURE_HTTPS_INSPECTION
  3134. /*
  3135. * Sending data with standard or secured connection (HTTP/HTTPS)
  3136. */
  3137. if (client_use_ssl(csp))
  3138. {
  3139. ssl_send_data_delayed(&(csp->ssl_client_attr),
  3140. (const unsigned char *)INVALID_SERVER_HEADERS_RESPONSE,
  3141. strlen(INVALID_SERVER_HEADERS_RESPONSE),
  3142. get_write_delay(csp));
  3143. }
  3144. else
  3145. #endif
  3146. {
  3147. write_socket_delayed(csp->cfd, INVALID_SERVER_HEADERS_RESPONSE,
  3148. strlen(INVALID_SERVER_HEADERS_RESPONSE), write_delay);
  3149. }
  3150. free_http_request(http);
  3151. mark_server_socket_tainted(csp);
  3152. #ifdef FEATURE_HTTPS_INSPECTION
  3153. close_client_and_server_ssl_connections(csp);
  3154. #endif
  3155. return;
  3156. }
  3157. hdr = list_to_text(csp->headers);
  3158. if (hdr == NULL)
  3159. {
  3160. /* FIXME Should handle error properly */
  3161. log_error(LOG_LEVEL_FATAL, "Out of memory parsing server header");
  3162. }
  3163. if ((csp->flags & CSP_FLAG_CHUNKED)
  3164. && !(csp->flags & CSP_FLAG_CONTENT_LENGTH_SET)
  3165. && ((csp->iob->eod - csp->iob->cur) >= 5)
  3166. && !memcmp(csp->iob->eod-5, "0\r\n\r\n", 5))
  3167. {
  3168. log_error(LOG_LEVEL_CONNECT,
  3169. "Looks like we got the last chunk together with "
  3170. "the server headers. We better stop reading.");
  3171. byte_count = (unsigned long long)(csp->iob->eod - csp->iob->cur);
  3172. csp->expected_content_length = byte_count;
  3173. csp->flags |= CSP_FLAG_CONTENT_LENGTH_SET;
  3174. }
  3175. csp->server_connection.response_received = time(NULL);
  3176. if (crunch_response_triggered(csp, crunchers_light))
  3177. {
  3178. /*
  3179. * One of the tags created by a server-header
  3180. * tagger triggered a crunch. We already
  3181. * delivered the crunch response to the client
  3182. * and are done here after cleaning up.
  3183. */
  3184. freez(hdr);
  3185. mark_server_socket_tainted(csp);
  3186. #ifdef FEATURE_HTTPS_INSPECTION
  3187. close_client_and_server_ssl_connections(csp);
  3188. #endif
  3189. return;
  3190. }
  3191. /* Buffer and pcrs filter this if appropriate. */
  3192. buffer_and_filter_content = content_requires_filtering(csp);
  3193. if (!buffer_and_filter_content)
  3194. {
  3195. /*
  3196. * Write the server's (modified) header to
  3197. * the client (along with anything else that
  3198. * may be in the buffer). Use standard or secured
  3199. * connection.
  3200. */
  3201. #ifdef FEATURE_HTTPS_INSPECTION
  3202. if (client_use_ssl(csp))
  3203. {
  3204. if ((ssl_send_data_delayed(&(csp->ssl_client_attr),
  3205. (const unsigned char *)hdr, strlen(hdr),
  3206. get_write_delay(csp)) < 0)
  3207. || (len = ssl_flush_socket(&(csp->ssl_client_attr),
  3208. csp->iob) < 0))
  3209. {
  3210. log_error(LOG_LEVEL_CONNECT, "Write header to client failed");
  3211. /*
  3212. * The write failed, so don't bother mentioning it
  3213. * to the client... it probably can't hear us anyway.
  3214. */
  3215. freez(hdr);
  3216. mark_server_socket_tainted(csp);
  3217. #ifdef FEATURE_HTTPS_INSPECTION
  3218. close_client_and_server_ssl_connections(csp);
  3219. #endif
  3220. return;
  3221. }
  3222. }
  3223. else
  3224. #endif /* def FEATURE_HTTPS_INSPECTION */
  3225. {
  3226. if (write_socket_delayed(csp->cfd, hdr, strlen(hdr), write_delay)
  3227. || ((len = flush_iob(csp->cfd, csp->iob, write_delay)) < 0))
  3228. {
  3229. log_error(LOG_LEVEL_ERROR,
  3230. "write header to client failed");
  3231. /*
  3232. * The write failed, so don't bother mentioning it
  3233. * to the client... it probably can't hear us anyway.
  3234. */
  3235. freez(hdr);
  3236. mark_server_socket_tainted(csp);
  3237. return;
  3238. }
  3239. }
  3240. }
  3241. /* we're finished with the server's header */
  3242. freez(hdr);
  3243. server_body = 1;
  3244. /*
  3245. * If this was a MS IIS/5 hack then it means the server
  3246. * has already closed the connection. Nothing more to read.
  3247. * Time to bail.
  3248. */
  3249. if (ms_iis5_hack)
  3250. {
  3251. log_error(LOG_LEVEL_ERROR,
  3252. "Closed server connection detected. "
  3253. "Applying the MS IIS5 hack didn't help.");
  3254. log_error(LOG_LEVEL_CLF,
  3255. "%s - - [%T] \"%s\" 502 0", csp->ip_addr_str, http->cmd);
  3256. #ifdef FEATURE_HTTPS_INSPECTION
  3257. /*
  3258. * Sending data with standard or secured connection (HTTP/HTTPS)
  3259. */
  3260. if (client_use_ssl(csp))
  3261. {
  3262. ssl_send_data_delayed(&(csp->ssl_client_attr),
  3263. (const unsigned char *)INVALID_SERVER_HEADERS_RESPONSE,
  3264. strlen(INVALID_SERVER_HEADERS_RESPONSE),
  3265. get_write_delay(csp));
  3266. }
  3267. else
  3268. #endif /* def FEATURE_HTTPS_INSPECTION */
  3269. {
  3270. write_socket_delayed(csp->cfd, INVALID_SERVER_HEADERS_RESPONSE,
  3271. strlen(INVALID_SERVER_HEADERS_RESPONSE), write_delay);
  3272. }
  3273. mark_server_socket_tainted(csp);
  3274. #ifdef FEATURE_HTTPS_INSPECTION
  3275. close_client_and_server_ssl_connections(csp);
  3276. #endif
  3277. return;
  3278. }
  3279. }
  3280. continue;
  3281. }
  3282. mark_server_socket_tainted(csp);
  3283. #ifdef FEATURE_HTTPS_INSPECTION
  3284. close_client_and_server_ssl_connections(csp);
  3285. #endif
  3286. return; /* huh? we should never get here */
  3287. }
  3288. if (csp->content_length == 0)
  3289. {
  3290. /*
  3291. * If Privoxy didn't recalculate the Content-Length,
  3292. * byte_count is still correct.
  3293. */
  3294. csp->content_length = byte_count;
  3295. }
  3296. #ifdef FEATURE_CONNECTION_KEEP_ALIVE
  3297. if ((csp->flags & CSP_FLAG_CONTENT_LENGTH_SET)
  3298. && (csp->expected_content_length != byte_count))
  3299. {
  3300. log_error(LOG_LEVEL_CONNECT,
  3301. "Received %llu bytes while expecting %llu.",
  3302. byte_count, csp->expected_content_length);
  3303. mark_server_socket_tainted(csp);
  3304. }
  3305. #endif
  3306. #ifdef FEATURE_HTTPS_INSPECTION
  3307. if (client_use_ssl(csp))
  3308. {
  3309. log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s https://%s%s %s\" 200 %llu",
  3310. csp->ip_addr_str, http->gpc, http->hostport, http->path,
  3311. http->version, csp->content_length);
  3312. }
  3313. else
  3314. #endif
  3315. {
  3316. log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 200 %llu",
  3317. csp->ip_addr_str, http->ocmd, csp->content_length);
  3318. }
  3319. csp->server_connection.timestamp = time(NULL);
  3320. }
  3321. /*********************************************************************
  3322. *
  3323. * Function : chat
  3324. *
  3325. * Description : Once a connection from the client has been accepted,
  3326. * this function is called (via serve()) to handle the
  3327. * main business of the communication. This function
  3328. * returns after dealing with a single request. It can
  3329. * be called multiple times with the same client socket
  3330. * if the client is keeping the connection alive.
  3331. *
  3332. * The decision whether or not a client connection will
  3333. * be kept alive is up to the caller which also must
  3334. * close the client socket when done.
  3335. *
  3336. * FIXME: chat is nearly thousand lines long.
  3337. * Ridiculous.
  3338. *
  3339. * Parameters :
  3340. * 1 : csp = Current client state (buffers, headers, etc...)
  3341. *
  3342. * Returns : Nothing.
  3343. *
  3344. *********************************************************************/
  3345. static void chat(struct client_state *csp)
  3346. {
  3347. const struct forward_spec *fwd;
  3348. struct http_request *http;
  3349. /* Skeleton for HTTP response, if we should intercept the request */
  3350. struct http_response *rsp;
  3351. #ifdef FEATURE_HTTPS_INSPECTION
  3352. int use_ssl_tunnel = 0;
  3353. #endif
  3354. http = csp->http;
  3355. if (receive_client_request(csp) != JB_ERR_OK)
  3356. {
  3357. return;
  3358. }
  3359. if (parse_client_request(csp) != JB_ERR_OK)
  3360. {
  3361. return;
  3362. }
  3363. /* decide how to route the HTTP request */
  3364. fwd = forward_url(csp, http);
  3365. #ifdef FEATURE_HTTPS_INSPECTION
  3366. /*
  3367. * Setting flags to use old solution with SSL tunnel and to disable
  3368. * certificate verification.
  3369. */
  3370. if (csp->http->ssl && !(csp->action->flags & ACTION_HTTPS_INSPECTION)
  3371. && !cgi_page_requested(csp->http->host))
  3372. {
  3373. use_ssl_tunnel = 1;
  3374. }
  3375. if (http->ssl && csp->action->flags & ACTION_IGNORE_CERTIFICATE_ERRORS)
  3376. {
  3377. csp->dont_verify_certificate = 1;
  3378. }
  3379. #endif
  3380. /*
  3381. * build the http request to send to the server
  3382. * we have to do one of the following:
  3383. *
  3384. * create = use the original HTTP request to create a new
  3385. * HTTP request that has either the path component
  3386. * without the http://domainspec (w/path) or the
  3387. * full orininal URL (w/url)
  3388. * Note that the path and/or the HTTP version may
  3389. * have been altered by now.
  3390. *
  3391. * SSL proxy = Open a socket to the host:port of the server
  3392. * and create TLS/SSL connection with server and
  3393. * with client. Then behave like mediator between
  3394. * client and server over TLS/SSL.
  3395. *
  3396. * SSL proxy = Pass the request unchanged if forwarding a CONNECT
  3397. * with request to a parent proxy. Note that we'll be sending
  3398. * forwarding the CFAIL message ourselves if connecting to the parent
  3399. * fails, but we won't send a CSUCCEED message if it works,
  3400. * since that would result in a double message (ours and the
  3401. * parent's). After sending the request to the parent, we
  3402. * must parse answer and send it to client. If connection
  3403. * with server is established, we do TLS/SSL proxy. Otherwise
  3404. * we send parent response to client and close connections.
  3405. *
  3406. * here's the matrix:
  3407. * SSL
  3408. * 0 1
  3409. * +--------+--------+
  3410. * | | |
  3411. * 0 | create | SSL |
  3412. * | w/path | proxy |
  3413. * Forwarding +--------+--------+
  3414. * | | SSL |
  3415. * 1 | create | proxy |
  3416. * | w/url |+forward|
  3417. * +--------+--------+
  3418. *
  3419. */
  3420. #ifdef FEATURE_HTTPS_INSPECTION
  3421. /*
  3422. * Presetting SSL client and server flags
  3423. */
  3424. if (http->ssl && !use_ssl_tunnel)
  3425. {
  3426. http->client_ssl = 1;
  3427. http->server_ssl = 1;
  3428. }
  3429. else
  3430. {
  3431. http->client_ssl = 0;
  3432. http->server_ssl = 0;
  3433. }
  3434. #endif
  3435. #ifdef FEATURE_HTTPS_INSPECTION
  3436. /*
  3437. * Log the request unless we're https inspecting
  3438. * in which case we don't have the path yet and
  3439. * will log the request later.
  3440. */
  3441. if (!client_use_ssl(csp))
  3442. #endif
  3443. {
  3444. log_error(LOG_LEVEL_REQUEST, "%s%s", http->hostport, http->path);
  3445. }
  3446. if (http->ssl && connect_port_is_forbidden(csp))
  3447. {
  3448. const char *acceptable_connect_ports =
  3449. csp->action->string[ACTION_STRING_LIMIT_CONNECT];
  3450. assert(NULL != acceptable_connect_ports);
  3451. log_error(LOG_LEVEL_INFO, "Request from %s marked for blocking. "
  3452. "limit-connect{%s} doesn't allow CONNECT requests to %s",
  3453. csp->ip_addr_str, acceptable_connect_ports, csp->http->hostport);
  3454. csp->action->flags |= ACTION_BLOCK;
  3455. http->ssl = 0;
  3456. #ifdef FEATURE_HTTPS_INSPECTION
  3457. http->client_ssl = 0;
  3458. http->server_ssl = 0;
  3459. #endif
  3460. }
  3461. freez(csp->headers->first->str);
  3462. build_request_line(csp, fwd, &csp->headers->first->str);
  3463. /*
  3464. * We have a request. Check if one of the crunchers wants it
  3465. * unless the client wants to use TLS/SSL in which case we
  3466. * haven't setup the TLS context yet and will send the crunch
  3467. * response later.
  3468. */
  3469. if (
  3470. #ifdef FEATURE_HTTPS_INSPECTION
  3471. !client_use_ssl(csp) &&
  3472. #endif
  3473. crunch_response_triggered(csp, crunchers_all))
  3474. {
  3475. /*
  3476. * Yes. The client got the crunch response and we're done here.
  3477. */
  3478. return;
  3479. }
  3480. log_applied_actions(csp->action);
  3481. if (fwd->forward_host)
  3482. {
  3483. log_error(LOG_LEVEL_CONNECT, "via [%s]:%d to: %s",
  3484. fwd->forward_host, fwd->forward_port, http->hostport);
  3485. }
  3486. else
  3487. {
  3488. log_error(LOG_LEVEL_CONNECT, "to %s", http->hostport);
  3489. }
  3490. /* here we connect to the server, gateway, or the forwarder */
  3491. #ifdef FEATURE_CONNECTION_KEEP_ALIVE
  3492. if ((csp->server_connection.sfd != JB_INVALID_SOCKET)
  3493. && socket_is_still_alive(csp->server_connection.sfd)
  3494. && connection_destination_matches(&csp->server_connection, http, fwd))
  3495. {
  3496. log_error(LOG_LEVEL_CONNECT,
  3497. "Reusing server socket %d connected to %s. Total requests: %u.",
  3498. csp->server_connection.sfd, csp->server_connection.host,
  3499. csp->server_connection.requests_sent_total);
  3500. }
  3501. else
  3502. {
  3503. if (csp->server_connection.sfd != JB_INVALID_SOCKET)
  3504. {
  3505. #ifdef FEATURE_CONNECTION_SHARING
  3506. if (csp->config->feature_flags & RUNTIME_FEATURE_CONNECTION_SHARING
  3507. #ifdef FEATURE_HTTPS_INSPECTION
  3508. && !server_use_ssl(csp)
  3509. #endif
  3510. )
  3511. {
  3512. remember_connection(&csp->server_connection);
  3513. }
  3514. else
  3515. #endif /* def FEATURE_CONNECTION_SHARING */
  3516. {
  3517. log_error(LOG_LEVEL_CONNECT,
  3518. "Closing server socket %d connected to %s. Total requests: %u.",
  3519. csp->server_connection.sfd, csp->server_connection.host,
  3520. csp->server_connection.requests_sent_total);
  3521. close_socket(csp->server_connection.sfd);
  3522. }
  3523. mark_connection_closed(&csp->server_connection);
  3524. }
  3525. #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
  3526. #ifdef FEATURE_HTTPS_INSPECTION
  3527. if (http->ssl && !use_ssl_tunnel)
  3528. {
  3529. int ret;
  3530. /*
  3531. * Creating a SSL proxy.
  3532. *
  3533. * By sending the CSUCCEED message we're lying to the client as
  3534. * the connection hasn't actually been established yet. We don't
  3535. * establish the connection until we have seen and parsed the
  3536. * encrypted client headers.
  3537. */
  3538. if (write_socket_delayed(csp->cfd, CSUCCEED,
  3539. strlen(CSUCCEED), get_write_delay(csp)) != 0)
  3540. {
  3541. log_error(LOG_LEVEL_ERROR, "Sending SUCCEED to client failed");
  3542. return;
  3543. }
  3544. ret = create_client_ssl_connection(csp);
  3545. if (ret != 0)
  3546. {
  3547. log_error(LOG_LEVEL_ERROR,
  3548. "Failed to open a secure connection with the client");
  3549. return;
  3550. }
  3551. if (JB_ERR_OK != process_encrypted_request(csp))
  3552. {
  3553. close_client_ssl_connection(csp);
  3554. return;
  3555. }
  3556. /*
  3557. * We have an encrypted request. Check if one of the crunchers now
  3558. * wants it (for example because the previously invisible path was
  3559. * required to match).
  3560. */
  3561. if (crunch_response_triggered(csp, crunchers_all))
  3562. {
  3563. /*
  3564. * Yes. The client got the crunch response and we're done here.
  3565. */
  3566. return;
  3567. }
  3568. }
  3569. #endif
  3570. /*
  3571. * Connecting to destination server
  3572. */
  3573. csp->server_connection.sfd = forwarded_connect(fwd, http, csp);
  3574. if (csp->server_connection.sfd == JB_INVALID_SOCKET)
  3575. {
  3576. if (fwd->type != SOCKS_NONE)
  3577. {
  3578. /* Socks error. */
  3579. rsp = error_response(csp, "forwarding-failed");
  3580. }
  3581. else if (errno == EINVAL)
  3582. {
  3583. rsp = error_response(csp, "no-such-domain");
  3584. }
  3585. else
  3586. {
  3587. rsp = error_response(csp, "connect-failed");
  3588. }
  3589. /* Write the answer to the client */
  3590. if (rsp != NULL)
  3591. {
  3592. send_crunch_response(csp, rsp);
  3593. }
  3594. /*
  3595. * Temporary workaround to prevent already-read client
  3596. * bodies from being parsed as new requests. For now we
  3597. * err on the safe side and throw all the following
  3598. * requests under the bus, even if no client body has been
  3599. * buffered. A compliant client will repeat the dropped
  3600. * requests on an untainted connection.
  3601. *
  3602. * The proper fix is to discard the no longer needed
  3603. * client body in the buffer (if there is one) and to
  3604. * continue parsing the bytes that follow.
  3605. */
  3606. #ifdef FEATURE_HTTPS_INSPECTION
  3607. close_client_ssl_connection(csp);
  3608. #endif
  3609. drain_and_close_socket(csp->cfd);
  3610. csp->cfd = JB_INVALID_SOCKET;
  3611. return;
  3612. }
  3613. #ifdef FEATURE_HTTPS_INSPECTION
  3614. /*
  3615. * Creating TLS/SSL connections with destination server or parent
  3616. * proxy. If forwarding is enabled, we must send client request to
  3617. * parent proxy and receive, parse and resend parent proxy answer.
  3618. */
  3619. if (http->ssl && !use_ssl_tunnel)
  3620. {
  3621. if (fwd->forward_host != NULL)
  3622. {
  3623. char server_response[BUFFER_SIZE];
  3624. int ret = 0;
  3625. int len = 0;
  3626. char *hdr = list_to_text(csp->headers);
  3627. memset(server_response, 0, sizeof(server_response));
  3628. if (hdr == NULL)
  3629. {
  3630. log_error(LOG_LEVEL_FATAL,
  3631. "Out of memory parsing client header");
  3632. }
  3633. list_remove_all(csp->headers);
  3634. /*
  3635. * Sending client's CONNECT request to the parent proxy
  3636. */
  3637. ret = write_socket(csp->server_connection.sfd, hdr, strlen(hdr));
  3638. freez(hdr);
  3639. if (ret != 0)
  3640. {
  3641. log_error(LOG_LEVEL_CONNECT,
  3642. "Sending request headers to: %s failed", http->hostport);
  3643. mark_server_socket_tainted(csp);
  3644. close_client_ssl_connection(csp);
  3645. return;
  3646. }
  3647. /* Waiting for parent proxy server response */
  3648. len = read_socket(csp->server_connection.sfd, server_response,
  3649. sizeof(server_response)-1);
  3650. if (len <= 0)
  3651. {
  3652. log_error(LOG_LEVEL_ERROR, "No response from parent proxy "
  3653. "server on socket %d.", csp->server_connection.sfd);
  3654. rsp = error_response(csp, "no-server-data");
  3655. if (rsp)
  3656. {
  3657. send_crunch_response(csp, rsp);
  3658. }
  3659. mark_server_socket_tainted(csp);
  3660. close_client_ssl_connection(csp);
  3661. return;
  3662. }
  3663. /*
  3664. * Test if the connection to the destination server was
  3665. * established successfully by the parent proxy.
  3666. */
  3667. if (!tunnel_established_successfully(server_response, (unsigned int)len))
  3668. {
  3669. log_error(LOG_LEVEL_ERROR,
  3670. "The forwarder %s failed to establish a connection with %s",
  3671. fwd->forward_host, http->host);
  3672. rsp = error_response(csp, "connect-failed");
  3673. if (rsp)
  3674. {
  3675. send_crunch_response(csp, rsp);
  3676. }
  3677. mark_server_socket_tainted(csp);
  3678. close_client_ssl_connection(csp);
  3679. return;
  3680. }
  3681. } /* -END- if (fwd->forward_host != NULL) */
  3682. /*
  3683. * We can now create the TLS/SSL connection with the destination server.
  3684. */
  3685. int ret = create_server_ssl_connection(csp);
  3686. if (ret != 0)
  3687. {
  3688. if (csp->server_cert_verification_result != SSL_CERT_VALID &&
  3689. csp->server_cert_verification_result != SSL_CERT_NOT_VERIFIED)
  3690. {
  3691. /*
  3692. * If the server certificate is invalid, we must inform
  3693. * the client and then close connection to the client.
  3694. */
  3695. ssl_send_certificate_error(csp);
  3696. close_client_and_server_ssl_connections(csp);
  3697. return;
  3698. }
  3699. if (csp->server_cert_verification_result == SSL_CERT_NOT_VERIFIED
  3700. || csp->server_cert_verification_result == SSL_CERT_VALID)
  3701. {
  3702. /*
  3703. * The TLS/SSL connection wasn't created but an invalid
  3704. * certificate wasn't detected. Report it as connection
  3705. * failure.
  3706. */
  3707. rsp = error_response(csp, "connect-failed");
  3708. if (rsp)
  3709. {
  3710. send_crunch_response(csp, rsp);
  3711. }
  3712. close_client_and_server_ssl_connections(csp);
  3713. return;
  3714. }
  3715. }
  3716. }/* -END- if (http->ssl) */
  3717. #endif /* def FEATURE_HTTPS_INSPECTION */
  3718. #ifdef FEATURE_CONNECTION_KEEP_ALIVE
  3719. save_connection_destination(csp->server_connection.sfd,
  3720. http, fwd, &csp->server_connection);
  3721. csp->server_connection.keep_alive_timeout =
  3722. (unsigned)csp->config->keep_alive_timeout;
  3723. }
  3724. #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
  3725. csp->server_connection.requests_sent_total++;
  3726. if ((fwd->type == SOCKS_5T) && (NULL == csp->headers->first))
  3727. {
  3728. /* Client headers have been sent optimistically */
  3729. assert(csp->headers->last == NULL);
  3730. }
  3731. else if (http->ssl == 0 || (fwd->forward_host
  3732. #ifdef FEATURE_HTTPS_INSPECTION
  3733. && use_ssl_tunnel
  3734. #endif
  3735. ))
  3736. {
  3737. if (send_http_request(csp))
  3738. {
  3739. rsp = error_response(csp, "connect-failed");
  3740. if (rsp)
  3741. {
  3742. send_crunch_response(csp, rsp);
  3743. }
  3744. return;
  3745. }
  3746. }
  3747. else
  3748. {
  3749. /*
  3750. * Using old solution with SSL tunnel or new solution with SSL proxy
  3751. */
  3752. list_remove_all(csp->headers);
  3753. #ifdef FEATURE_HTTPS_INSPECTION
  3754. if (use_ssl_tunnel)
  3755. #endif
  3756. {
  3757. /*
  3758. * We're running an SSL tunnel and we're not forwarding,
  3759. * so just ditch the client headers, send the "connect succeeded"
  3760. * message to the client, flush the rest, and get out of the way.
  3761. */
  3762. if (write_socket_delayed(csp->cfd, CSUCCEED,
  3763. strlen(CSUCCEED), get_write_delay(csp)))
  3764. {
  3765. return;
  3766. }
  3767. }
  3768. #ifdef FEATURE_HTTPS_INSPECTION
  3769. else
  3770. {
  3771. /*
  3772. * If server certificate has been verified and is invalid,
  3773. * we must inform the client and then close the connection
  3774. * with client and server.
  3775. */
  3776. if (csp->server_cert_verification_result != SSL_CERT_VALID &&
  3777. csp->server_cert_verification_result != SSL_CERT_NOT_VERIFIED)
  3778. {
  3779. ssl_send_certificate_error(csp);
  3780. close_client_and_server_ssl_connections(csp);
  3781. return;
  3782. }
  3783. if (send_https_request(csp))
  3784. {
  3785. rsp = error_response(csp, "connect-failed");
  3786. if (rsp)
  3787. {
  3788. send_crunch_response(csp, rsp);
  3789. }
  3790. close_client_and_server_ssl_connections(csp);
  3791. return;
  3792. }
  3793. }
  3794. #endif /* def FEATURE_HTTPS_INSPECTION */
  3795. clear_iob(csp->client_iob);
  3796. }/* -END- else ... if (http->ssl == 1) */
  3797. log_error(LOG_LEVEL_CONNECT, "to %s successful", http->hostport);
  3798. /* XXX: should the time start earlier for optimistically sent data? */
  3799. csp->server_connection.request_sent = time(NULL);
  3800. handle_established_connection(csp);
  3801. freez(csp->receive_buffer);
  3802. }
  3803. #ifdef FUZZ
  3804. /*********************************************************************
  3805. *
  3806. * Function : fuzz_server_response
  3807. *
  3808. * Description : Treat the input as a whole server response.
  3809. *
  3810. * Parameters :
  3811. * 1 : csp = Current client state (buffers, headers, etc...)
  3812. * 2 : fuzz_input_file = File to read the input from.
  3813. *
  3814. * Returns : 0
  3815. *
  3816. *********************************************************************/
  3817. extern int fuzz_server_response(struct client_state *csp, char *fuzz_input_file)
  3818. {
  3819. static struct forward_spec fwd; /* Zero'd due to being static */
  3820. csp->cfd = 0;
  3821. if (strcmp(fuzz_input_file, "-") == 0)
  3822. {
  3823. /* XXX: Doesn't work yet. */
  3824. csp->server_connection.sfd = 0;
  3825. }
  3826. else
  3827. {
  3828. csp->server_connection.sfd = open(fuzz_input_file, O_RDONLY);
  3829. if (csp->server_connection.sfd == -1)
  3830. {
  3831. log_error(LOG_LEVEL_FATAL, "Failed to open %s: %E",
  3832. fuzz_input_file);
  3833. }
  3834. }
  3835. csp->fwd = &fwd;
  3836. csp->content_type |= CT_GIF;
  3837. csp->action->flags |= ACTION_DEANIMATE;
  3838. csp->action->string[ACTION_STRING_DEANIMATE] = "last";
  3839. csp->http->path = strdup_or_die("/");
  3840. csp->http->host = strdup_or_die("fuzz.example.org");
  3841. csp->http->hostport = strdup_or_die("fuzz.example.org:80");
  3842. /* Prevent client socket monitoring */
  3843. csp->flags |= CSP_FLAG_PIPELINED_REQUEST_WAITING;
  3844. csp->flags |= CSP_FLAG_CHUNKED;
  3845. csp->config->feature_flags |= RUNTIME_FEATURE_CONNECTION_KEEP_ALIVE;
  3846. csp->flags |= CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE;
  3847. csp->content_type |= CT_DECLARED|CT_GIF;
  3848. csp->config->socket_timeout = 0;
  3849. cgi_init_error_messages();
  3850. handle_established_connection(csp);
  3851. freez(csp->receive_buffer);
  3852. return 0;
  3853. }
  3854. #endif
  3855. #ifdef FEATURE_CONNECTION_KEEP_ALIVE
  3856. /*********************************************************************
  3857. *
  3858. * Function : prepare_csp_for_next_request
  3859. *
  3860. * Description : Put the csp in a mostly vergin state.
  3861. *
  3862. * Parameters :
  3863. * 1 : csp = Current client state (buffers, headers, etc...)
  3864. *
  3865. * Returns : N/A
  3866. *
  3867. *********************************************************************/
  3868. static void prepare_csp_for_next_request(struct client_state *csp)
  3869. {
  3870. csp->content_type = 0;
  3871. csp->content_length = 0;
  3872. csp->expected_content_length = 0;
  3873. csp->expected_client_content_length = 0;
  3874. list_remove_all(csp->headers);
  3875. clear_iob(csp->iob);
  3876. freez(csp->error_message);
  3877. free_http_request(csp->http);
  3878. destroy_list(csp->headers);
  3879. #ifdef FEATURE_HTTPS_INSPECTION
  3880. destroy_list(csp->https_headers);
  3881. #endif
  3882. destroy_list(csp->tags);
  3883. #ifdef FEATURE_CLIENT_TAGS
  3884. destroy_list(csp->client_tags);
  3885. freez(csp->client_address);
  3886. #endif
  3887. free_current_action(csp->action);
  3888. if (NULL != csp->fwd)
  3889. {
  3890. unload_forward_spec(csp->fwd);
  3891. csp->fwd = NULL;
  3892. }
  3893. /* XXX: Store per-connection flags someplace else. */
  3894. csp->flags = (CSP_FLAG_ACTIVE | CSP_FLAG_REUSED_CLIENT_CONNECTION);
  3895. #ifdef FEATURE_TOGGLE
  3896. if (global_toggle_state)
  3897. #endif /* def FEATURE_TOGGLE */
  3898. {
  3899. csp->flags |= CSP_FLAG_TOGGLED_ON;
  3900. }
  3901. if (csp->client_iob->eod > csp->client_iob->cur)
  3902. {
  3903. long bytes_to_shift = csp->client_iob->cur - csp->client_iob->buf;
  3904. size_t data_length = (size_t)(csp->client_iob->eod - csp->client_iob->cur);
  3905. assert(bytes_to_shift > 0);
  3906. assert(data_length > 0);
  3907. log_error(LOG_LEVEL_CONNECT, "Shifting %lu pipelined bytes by %ld bytes",
  3908. data_length, bytes_to_shift);
  3909. memmove(csp->client_iob->buf, csp->client_iob->cur, data_length);
  3910. csp->client_iob->cur = csp->client_iob->buf;
  3911. assert(csp->client_iob->eod == csp->client_iob->buf + bytes_to_shift + data_length);
  3912. csp->client_iob->eod = csp->client_iob->buf + data_length;
  3913. memset(csp->client_iob->eod, '\0', (size_t)bytes_to_shift);
  3914. csp->flags |= CSP_FLAG_PIPELINED_REQUEST_WAITING;
  3915. }
  3916. else
  3917. {
  3918. /*
  3919. * We mainly care about resetting client_iob->cur so we don't
  3920. * waste buffer space at the beginning and don't mess up the
  3921. * request restoration done by cgi_show_request().
  3922. *
  3923. * Freeing the buffer itself isn't technically necessary,
  3924. * but makes debugging more convenient.
  3925. */
  3926. clear_iob(csp->client_iob);
  3927. }
  3928. }
  3929. #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
  3930. /*********************************************************************
  3931. *
  3932. * Function : serve
  3933. *
  3934. * Description : This is little more than chat. We only "serve" to
  3935. * to close (or remember) any socket that chat may have
  3936. * opened.
  3937. *
  3938. * Parameters :
  3939. * 1 : csp = Current client state (buffers, headers, etc...)
  3940. *
  3941. * Returns : N/A
  3942. *
  3943. *********************************************************************/
  3944. static void serve(struct client_state *csp)
  3945. {
  3946. int config_file_change_detected = 0; /* Only used for debugging */
  3947. #ifdef FEATURE_CONNECTION_KEEP_ALIVE
  3948. #ifdef FEATURE_CONNECTION_SHARING
  3949. static int monitor_thread_running = 0;
  3950. #endif /* def FEATURE_CONNECTION_SHARING */
  3951. int continue_chatting = 0;
  3952. log_error(LOG_LEVEL_CONNECT, "Accepted connection from %s on socket %d",
  3953. csp->ip_addr_str, csp->cfd);
  3954. do
  3955. {
  3956. unsigned int latency;
  3957. #ifdef FEATURE_HTTPS_INSPECTION
  3958. if (continue_chatting && client_use_ssl(csp))
  3959. {
  3960. continue_https_chat(csp);
  3961. }
  3962. else
  3963. #endif
  3964. {
  3965. chat(csp);
  3966. }
  3967. /*
  3968. * If the request has been crunched,
  3969. * the calculated latency is zero.
  3970. */
  3971. latency = (unsigned)(csp->server_connection.response_received -
  3972. csp->server_connection.request_sent) / 2;
  3973. if ((csp->flags & CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE)
  3974. && (csp->flags & CSP_FLAG_CRUNCHED)
  3975. && (csp->expected_client_content_length != 0))
  3976. {
  3977. csp->flags |= CSP_FLAG_SERVER_SOCKET_TAINTED;
  3978. log_error(LOG_LEVEL_CONNECT,
  3979. "Tainting client socket %d due to unread data.", csp->cfd);
  3980. }
  3981. continue_chatting = (csp->config->feature_flags
  3982. & RUNTIME_FEATURE_CONNECTION_KEEP_ALIVE)
  3983. && !(csp->flags & CSP_FLAG_SERVER_SOCKET_TAINTED)
  3984. && (csp->cfd != JB_INVALID_SOCKET)
  3985. && (csp->flags & CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE)
  3986. && ((csp->flags & CSP_FLAG_SERVER_CONTENT_LENGTH_SET)
  3987. || (csp->flags & CSP_FLAG_CHUNKED));
  3988. if (!(csp->flags & CSP_FLAG_CRUNCHED)
  3989. && (csp->server_connection.sfd != JB_INVALID_SOCKET))
  3990. {
  3991. if (!(csp->flags & CSP_FLAG_SERVER_KEEP_ALIVE_TIMEOUT_SET))
  3992. {
  3993. csp->server_connection.keep_alive_timeout = csp->config->default_server_timeout;
  3994. }
  3995. if (!(csp->flags & CSP_FLAG_SERVER_CONNECTION_KEEP_ALIVE)
  3996. || (csp->flags & CSP_FLAG_SERVER_SOCKET_TAINTED)
  3997. || !socket_is_still_alive(csp->server_connection.sfd)
  3998. || !(latency < csp->server_connection.keep_alive_timeout))
  3999. {
  4000. log_error(LOG_LEVEL_CONNECT,
  4001. "Closing server socket %d connected to %s. "
  4002. "Keep-alive: %u. Tainted: %u. Socket alive: %u. Timeout: %u.",
  4003. csp->server_connection.sfd, csp->server_connection.host,
  4004. 0 != (csp->flags & CSP_FLAG_SERVER_CONNECTION_KEEP_ALIVE),
  4005. 0 != (csp->flags & CSP_FLAG_SERVER_SOCKET_TAINTED),
  4006. socket_is_still_alive(csp->server_connection.sfd),
  4007. csp->server_connection.keep_alive_timeout);
  4008. #ifdef FEATURE_CONNECTION_SHARING
  4009. if (csp->config->feature_flags & RUNTIME_FEATURE_CONNECTION_SHARING)
  4010. {
  4011. forget_connection(csp->server_connection.sfd);
  4012. }
  4013. #endif /* def FEATURE_CONNECTION_SHARING */
  4014. #ifdef FEATURE_HTTPS_INSPECTION
  4015. close_server_ssl_connection(csp);
  4016. #endif
  4017. close_socket(csp->server_connection.sfd);
  4018. mark_connection_closed(&csp->server_connection);
  4019. }
  4020. }
  4021. if (continue_chatting && any_loaded_file_changed(csp))
  4022. {
  4023. continue_chatting = 0;
  4024. config_file_change_detected = 1;
  4025. }
  4026. #ifdef FEATURE_HTTPS_INSPECTION
  4027. if (continue_chatting && client_use_ssl(csp) &&
  4028. csp->ssl_with_client_is_opened == 0)
  4029. {
  4030. continue_chatting = 0;
  4031. log_error(LOG_LEVEL_CONNECT, "Client socket %d is no longer usable. "
  4032. "The TLS session has been terminated.", csp->cfd);
  4033. }
  4034. #endif
  4035. if (continue_chatting)
  4036. {
  4037. if (((csp->flags & CSP_FLAG_PIPELINED_REQUEST_WAITING) != 0)
  4038. && socket_is_still_alive(csp->cfd))
  4039. {
  4040. log_error(LOG_LEVEL_CONNECT, "Client request %d has been "
  4041. "pipelined on socket %d and the socket is still alive.",
  4042. csp->requests_received_total+1, csp->cfd);
  4043. prepare_csp_for_next_request(csp);
  4044. continue;
  4045. }
  4046. if (0 != (csp->flags & CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE))
  4047. {
  4048. if (csp->server_connection.sfd != JB_INVALID_SOCKET)
  4049. {
  4050. log_error(LOG_LEVEL_CONNECT,
  4051. "Waiting for the next client request on socket %d. "
  4052. "Keeping the server socket %d to %s open.",
  4053. csp->cfd, csp->server_connection.sfd, csp->server_connection.host);
  4054. }
  4055. else
  4056. {
  4057. log_error(LOG_LEVEL_CONNECT,
  4058. "Waiting for the next client request on socket %d. "
  4059. "No server socket to keep open.", csp->cfd);
  4060. }
  4061. }
  4062. if ((csp->flags & CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE)
  4063. && data_is_available(csp->cfd, (int)csp->config->keep_alive_timeout)
  4064. && socket_is_still_alive(csp->cfd))
  4065. {
  4066. log_error(LOG_LEVEL_CONNECT,
  4067. "Data arrived in time on client socket %d. Requests so far: %u",
  4068. csp->cfd, csp->requests_received_total);
  4069. prepare_csp_for_next_request(csp);
  4070. }
  4071. else
  4072. {
  4073. #ifdef FEATURE_CONNECTION_SHARING
  4074. if ((csp->config->feature_flags & RUNTIME_FEATURE_CONNECTION_SHARING)
  4075. && (csp->server_connection.sfd != JB_INVALID_SOCKET)
  4076. && (socket_is_still_alive(csp->server_connection.sfd))
  4077. #ifdef FEATURE_HTTPS_INSPECTION
  4078. && !server_use_ssl(csp)
  4079. #endif
  4080. )
  4081. {
  4082. time_t time_open = time(NULL) - csp->server_connection.timestamp;
  4083. if (csp->server_connection.keep_alive_timeout < time_open - (time_t)latency)
  4084. {
  4085. break;
  4086. }
  4087. remember_connection(&csp->server_connection);
  4088. csp->server_connection.sfd = JB_INVALID_SOCKET;
  4089. drain_and_close_socket(csp->cfd);
  4090. csp->cfd = JB_INVALID_SOCKET;
  4091. privoxy_mutex_lock(&connection_reuse_mutex);
  4092. if (!monitor_thread_running)
  4093. {
  4094. monitor_thread_running = 1;
  4095. privoxy_mutex_unlock(&connection_reuse_mutex);
  4096. wait_for_alive_connections();
  4097. privoxy_mutex_lock(&connection_reuse_mutex);
  4098. monitor_thread_running = 0;
  4099. }
  4100. privoxy_mutex_unlock(&connection_reuse_mutex);
  4101. }
  4102. #endif /* def FEATURE_CONNECTION_SHARING */
  4103. break;
  4104. }
  4105. }
  4106. else if (csp->server_connection.sfd != JB_INVALID_SOCKET)
  4107. {
  4108. log_error(LOG_LEVEL_CONNECT,
  4109. "Closing server socket %d connected to %s. Keep-alive: %u. "
  4110. "Tainted: %u. Socket alive: %u. Timeout: %u. "
  4111. "Configuration file change detected: %u",
  4112. csp->server_connection.sfd, csp->server_connection.host,
  4113. 0 != (csp->flags & CSP_FLAG_SERVER_CONNECTION_KEEP_ALIVE),
  4114. 0 != (csp->flags & CSP_FLAG_SERVER_SOCKET_TAINTED),
  4115. socket_is_still_alive(csp->server_connection.sfd),
  4116. csp->server_connection.keep_alive_timeout,
  4117. config_file_change_detected);
  4118. }
  4119. } while (continue_chatting);
  4120. #else
  4121. chat(csp);
  4122. #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
  4123. if (csp->cfd != JB_INVALID_SOCKET)
  4124. {
  4125. log_error(LOG_LEVEL_CONNECT, "Closing client socket %d. "
  4126. "Keep-alive: %u. Socket alive: %u. Data available: %u. "
  4127. "Configuration file change detected: %u. Requests received: %u.",
  4128. csp->cfd, 0 != (csp->flags & CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE),
  4129. socket_is_still_alive(csp->cfd), data_is_available(csp->cfd, 0),
  4130. config_file_change_detected, csp->requests_received_total);
  4131. #ifdef FEATURE_HTTPS_INSPECTION
  4132. close_client_ssl_connection(csp);
  4133. #endif
  4134. drain_and_close_socket(csp->cfd);
  4135. }
  4136. if (csp->server_connection.sfd != JB_INVALID_SOCKET)
  4137. {
  4138. #ifdef FEATURE_CONNECTION_SHARING
  4139. if (csp->config->feature_flags & RUNTIME_FEATURE_CONNECTION_SHARING)
  4140. {
  4141. forget_connection(csp->server_connection.sfd);
  4142. }
  4143. #endif /* def FEATURE_CONNECTION_SHARING */
  4144. #ifdef FEATURE_HTTPS_INSPECTION
  4145. close_server_ssl_connection(csp);
  4146. #endif /* def FEATURE_HTTPS_INSPECTION */
  4147. close_socket(csp->server_connection.sfd);
  4148. }
  4149. #ifdef FEATURE_CONNECTION_KEEP_ALIVE
  4150. mark_connection_closed(&csp->server_connection);
  4151. #endif
  4152. free_csp_resources(csp);
  4153. csp->flags &= ~CSP_FLAG_ACTIVE;
  4154. }
  4155. #ifdef __BEOS__
  4156. /*********************************************************************
  4157. *
  4158. * Function : server_thread
  4159. *
  4160. * Description : We only exist to call `serve' in a threaded environment.
  4161. *
  4162. * Parameters :
  4163. * 1 : data = Current client state (buffers, headers, etc...)
  4164. *
  4165. * Returns : Always 0.
  4166. *
  4167. *********************************************************************/
  4168. static int32 server_thread(void *data)
  4169. {
  4170. serve((struct client_state *) data);
  4171. return 0;
  4172. }
  4173. #endif
  4174. #if !defined(_WIN32) || defined(_WIN_CONSOLE)
  4175. /*********************************************************************
  4176. *
  4177. * Function : usage
  4178. *
  4179. * Description : Print usage info & exit.
  4180. *
  4181. * Parameters : Pointer to argv[0] for identifying ourselves
  4182. *
  4183. * Returns : No. ,-)
  4184. *
  4185. *********************************************************************/
  4186. static void usage(const char *name)
  4187. {
  4188. printf("Privoxy version " VERSION " (" HOME_PAGE_URL ")\n"
  4189. "Usage: %s [--config-test] "
  4190. #if defined(unix)
  4191. "[--chroot] "
  4192. #endif /* defined(unix) */
  4193. "[--help] "
  4194. #if defined(unix)
  4195. "[--no-daemon] [--pidfile pidfile] [--pre-chroot-nslookup hostname] [--user user[.group]] "
  4196. #endif /* defined(unix) */
  4197. "[--version] [configfile]\n",
  4198. name);
  4199. #ifdef FUZZ
  4200. show_fuzz_usage(name);
  4201. #endif
  4202. printf("Aborting\n");
  4203. exit(2);
  4204. }
  4205. #endif /* #if !defined(_WIN32) || defined(_WIN_CONSOLE) */
  4206. #ifdef MUTEX_LOCKS_AVAILABLE
  4207. /*********************************************************************
  4208. *
  4209. * Function : privoxy_mutex_lock
  4210. *
  4211. * Description : Locks a mutex.
  4212. *
  4213. * Parameters :
  4214. * 1 : mutex = The mutex to lock.
  4215. *
  4216. * Returns : Void. May exit in case of errors.
  4217. *
  4218. *********************************************************************/
  4219. void privoxy_mutex_lock(privoxy_mutex_t *mutex)
  4220. {
  4221. #ifdef FEATURE_PTHREAD
  4222. int err = pthread_mutex_lock(mutex);
  4223. if (err)
  4224. {
  4225. if (mutex != &log_mutex)
  4226. {
  4227. log_error(LOG_LEVEL_FATAL,
  4228. "Mutex locking failed: %s.\n", strerror(err));
  4229. }
  4230. exit(1);
  4231. }
  4232. #else
  4233. EnterCriticalSection(mutex);
  4234. #endif /* def FEATURE_PTHREAD */
  4235. }
  4236. /*********************************************************************
  4237. *
  4238. * Function : privoxy_mutex_unlock
  4239. *
  4240. * Description : Unlocks a mutex.
  4241. *
  4242. * Parameters :
  4243. * 1 : mutex = The mutex to unlock.
  4244. *
  4245. * Returns : Void. May exit in case of errors.
  4246. *
  4247. *********************************************************************/
  4248. void privoxy_mutex_unlock(privoxy_mutex_t *mutex)
  4249. {
  4250. #ifdef FEATURE_PTHREAD
  4251. int err = pthread_mutex_unlock(mutex);
  4252. if (err)
  4253. {
  4254. if (mutex != &log_mutex)
  4255. {
  4256. log_error(LOG_LEVEL_FATAL,
  4257. "Mutex unlocking failed: %s.\n", strerror(err));
  4258. }
  4259. exit(1);
  4260. }
  4261. #else
  4262. LeaveCriticalSection(mutex);
  4263. #endif /* def FEATURE_PTHREAD */
  4264. }
  4265. /*********************************************************************
  4266. *
  4267. * Function : privoxy_mutex_init
  4268. *
  4269. * Description : Prepares a mutex.
  4270. *
  4271. * Parameters :
  4272. * 1 : mutex = The mutex to initialize.
  4273. *
  4274. * Returns : Void. May exit in case of errors.
  4275. *
  4276. *********************************************************************/
  4277. static void privoxy_mutex_init(privoxy_mutex_t *mutex)
  4278. {
  4279. #ifdef FEATURE_PTHREAD
  4280. int err = pthread_mutex_init(mutex, 0);
  4281. if (err)
  4282. {
  4283. printf("Fatal error. Mutex initialization failed: %s.\n",
  4284. strerror(err));
  4285. exit(1);
  4286. }
  4287. #else
  4288. InitializeCriticalSection(mutex);
  4289. #endif /* def FEATURE_PTHREAD */
  4290. }
  4291. #endif /* def MUTEX_LOCKS_AVAILABLE */
  4292. /*********************************************************************
  4293. *
  4294. * Function : initialize_mutexes
  4295. *
  4296. * Description : Prepares mutexes if mutex support is available.
  4297. *
  4298. * Parameters : None
  4299. *
  4300. * Returns : Void, exits in case of errors.
  4301. *
  4302. *********************************************************************/
  4303. static void initialize_mutexes(void)
  4304. {
  4305. #ifdef MUTEX_LOCKS_AVAILABLE
  4306. /*
  4307. * Prepare global mutex semaphores
  4308. */
  4309. #ifdef FEATURE_HTTPS_INSPECTION
  4310. privoxy_mutex_init(&certificate_mutex);
  4311. privoxy_mutex_init(&ssl_init_mutex);
  4312. #endif
  4313. privoxy_mutex_init(&log_mutex);
  4314. privoxy_mutex_init(&log_init_mutex);
  4315. privoxy_mutex_init(&connection_reuse_mutex);
  4316. #ifdef FEATURE_EXTERNAL_FILTERS
  4317. privoxy_mutex_init(&external_filter_mutex);
  4318. #endif
  4319. #ifdef FEATURE_CLIENT_TAGS
  4320. privoxy_mutex_init(&client_tags_mutex);
  4321. #endif
  4322. #ifdef FEATURE_EXTENDED_STATISTICS
  4323. privoxy_mutex_init(&filter_statistics_mutex);
  4324. privoxy_mutex_init(&block_statistics_mutex);
  4325. #endif
  4326. /*
  4327. * XXX: The assumptions below are a bit naive
  4328. * and can cause locks that aren't necessary.
  4329. *
  4330. * For example older FreeBSD versions (< 6.x?)
  4331. * have no gethostbyname_r, but gethostbyname is
  4332. * thread safe.
  4333. */
  4334. #if !defined(HAVE_GETHOSTBYADDR_R) || !defined(HAVE_GETHOSTBYNAME_R)
  4335. privoxy_mutex_init(&resolver_mutex);
  4336. #endif /* !defined(HAVE_GETHOSTBYADDR_R) || !defined(HAVE_GETHOSTBYNAME_R) */
  4337. /*
  4338. * XXX: should we use a single mutex for
  4339. * localtime() and gmtime() as well?
  4340. */
  4341. #ifndef HAVE_GMTIME_R
  4342. privoxy_mutex_init(&gmtime_mutex);
  4343. #endif /* ndef HAVE_GMTIME_R */
  4344. #ifndef HAVE_LOCALTIME_R
  4345. privoxy_mutex_init(&localtime_mutex);
  4346. #endif /* ndef HAVE_GMTIME_R */
  4347. #if !defined(HAVE_ARC4RANDOM) && !defined(HAVE_RANDOM)
  4348. privoxy_mutex_init(&rand_mutex);
  4349. #endif /* !defined(HAVE_ARC4RANDOM) && !defined(HAVE_RANDOM) */
  4350. #endif /* def MUTEX_LOCKS_AVAILABLE */
  4351. }
  4352. /*********************************************************************
  4353. *
  4354. * Function : main
  4355. *
  4356. * Description : Load the config file and start the listen loop.
  4357. * This function is a lot more *sane* with the `load_config'
  4358. * and `listen_loop' functions; although it stills does
  4359. * a *little* too much for my taste.
  4360. *
  4361. * Parameters :
  4362. * 1 : argc = Number of parameters (including $0).
  4363. * 2 : argv = Array of (char *)'s to the parameters.
  4364. *
  4365. * Returns : 1 if : can't open config file, unrecognized directive,
  4366. * stats requested in multi-thread mode, can't open the
  4367. * log file, can't open the jar file, listen port is invalid,
  4368. * any load fails, and can't bind port.
  4369. *
  4370. * Else main never returns, the process must be signaled
  4371. * to terminate execution. Or, on Windows, use the
  4372. * "File", "Exit" menu option.
  4373. *
  4374. *********************************************************************/
  4375. #ifdef __MINGW32__
  4376. int real_main(int argc, char **argv)
  4377. #else
  4378. int main(int argc, char **argv)
  4379. #endif
  4380. {
  4381. int argc_pos = 0;
  4382. int do_config_test = 0;
  4383. #ifndef HAVE_ARC4RANDOM
  4384. unsigned int random_seed;
  4385. #endif
  4386. #ifdef unix
  4387. struct passwd *pw = NULL;
  4388. struct group *grp = NULL;
  4389. int do_chroot = 0;
  4390. char *pre_chroot_nslookup_to_load_resolver = NULL;
  4391. #endif
  4392. #ifdef FUZZ
  4393. char *fuzz_input_type = NULL;
  4394. char *fuzz_input_file = NULL;
  4395. #endif
  4396. Argc = argc;
  4397. Argv = argv;
  4398. configfile =
  4399. #if !defined(_WIN32)
  4400. "config"
  4401. #else
  4402. "config.txt"
  4403. #endif
  4404. ;
  4405. /* Prepare mutexes if supported and necessary. */
  4406. initialize_mutexes();
  4407. /* Enable logging until further notice. */
  4408. init_log_module();
  4409. /*
  4410. * Parse the command line arguments
  4411. *
  4412. * XXX: simply printing usage information in case of
  4413. * invalid arguments isn't particularly user friendly.
  4414. */
  4415. while (++argc_pos < argc)
  4416. {
  4417. #ifdef _WIN32
  4418. /* Check to see if the service must be installed or uninstalled */
  4419. if (strncmp(argv[argc_pos], "--install", 9) == 0)
  4420. {
  4421. const char *pName = argv[argc_pos] + 9;
  4422. if (*pName == ':')
  4423. pName++;
  4424. exit((install_service(pName)) ? 0 : 1);
  4425. }
  4426. else if (strncmp(argv[argc_pos], "--uninstall", 11) == 0)
  4427. {
  4428. const char *pName = argv[argc_pos] + 11;
  4429. if (*pName == ':')
  4430. pName++;
  4431. exit((uninstall_service(pName)) ? 0 : 1);
  4432. }
  4433. else if (strcmp(argv[argc_pos], "--service") == 0)
  4434. {
  4435. bRunAsService = TRUE;
  4436. w32_set_service_cwd();
  4437. atexit(w32_service_exit_notify);
  4438. }
  4439. else
  4440. #endif /* defined(_WIN32) */
  4441. #if !defined(_WIN32) || defined(_WIN_CONSOLE)
  4442. if (strcmp(argv[argc_pos], "--help") == 0)
  4443. {
  4444. usage(argv[0]);
  4445. }
  4446. else if (strcmp(argv[argc_pos], "--version") == 0)
  4447. {
  4448. printf("Privoxy version " VERSION " (" HOME_PAGE_URL ")\n");
  4449. exit(0);
  4450. }
  4451. #if defined(unix)
  4452. else if (strcmp(argv[argc_pos], "--no-daemon") == 0)
  4453. {
  4454. set_debug_level(LOG_LEVEL_FATAL | LOG_LEVEL_ERROR | LOG_LEVEL_INFO);
  4455. daemon_mode = 0;
  4456. }
  4457. else if (strcmp(argv[argc_pos], "--pidfile") == 0)
  4458. {
  4459. if (++argc_pos == argc) usage(argv[0]);
  4460. pidfile = strdup_or_die(argv[argc_pos]);
  4461. }
  4462. else if (strcmp(argv[argc_pos], "--user") == 0)
  4463. {
  4464. char *user_arg;
  4465. char *group_name;
  4466. if (++argc_pos == argc) usage(argv[argc_pos]);
  4467. user_arg = strdup_or_die(argv[argc_pos]);
  4468. group_name = strchr(user_arg, '.');
  4469. if (NULL != group_name)
  4470. {
  4471. /* Nul-terminate the user name */
  4472. *group_name = '\0';
  4473. /* Skip the former delimiter to actually reach the group name */
  4474. group_name++;
  4475. grp = getgrnam(group_name);
  4476. if (NULL == grp)
  4477. {
  4478. log_error(LOG_LEVEL_FATAL, "Group '%s' not found.", group_name);
  4479. }
  4480. }
  4481. pw = getpwnam(user_arg);
  4482. if (NULL == pw)
  4483. {
  4484. log_error(LOG_LEVEL_FATAL, "User '%s' not found.", user_arg);
  4485. }
  4486. freez(user_arg);
  4487. }
  4488. else if (strcmp(argv[argc_pos], "--pre-chroot-nslookup") == 0)
  4489. {
  4490. if (++argc_pos == argc) usage(argv[0]);
  4491. pre_chroot_nslookup_to_load_resolver = strdup_or_die(argv[argc_pos]);
  4492. }
  4493. else if (strcmp(argv[argc_pos], "--chroot") == 0)
  4494. {
  4495. do_chroot = 1;
  4496. }
  4497. #endif /* defined(unix) */
  4498. else if (strcmp(argv[argc_pos], "--config-test") == 0)
  4499. {
  4500. do_config_test = 1;
  4501. }
  4502. #ifdef FUZZ
  4503. else if (strcmp(argv[argc_pos], "--fuzz") == 0)
  4504. {
  4505. argc_pos++;
  4506. if (argc < argc_pos + 2) usage(argv[0]);
  4507. fuzz_input_type = argv[argc_pos];
  4508. argc_pos++;
  4509. fuzz_input_file = argv[argc_pos];
  4510. }
  4511. else if (strcmp(argv[argc_pos], "--stfu") == 0)
  4512. {
  4513. set_debug_level(LOG_LEVEL_STFU);
  4514. }
  4515. #endif
  4516. else if (argc_pos + 1 != argc)
  4517. {
  4518. /*
  4519. * This is neither the last command line
  4520. * option, nor was it recognized before,
  4521. * therefore it must be invalid.
  4522. */
  4523. usage(argv[0]);
  4524. }
  4525. else
  4526. #endif /* defined(_WIN32) && !defined(_WIN_CONSOLE) */
  4527. {
  4528. configfile = argv[argc_pos];
  4529. }
  4530. } /* -END- while (more arguments) */
  4531. show_version(Argv[0]);
  4532. #if defined(unix)
  4533. if (*configfile != '/')
  4534. {
  4535. char cwd[BUFFER_SIZE];
  4536. char *abs_file;
  4537. size_t abs_file_size;
  4538. /* make config-filename absolute here */
  4539. if (NULL == getcwd(cwd, sizeof(cwd)))
  4540. {
  4541. perror("failed to get current working directory");
  4542. exit(1);
  4543. }
  4544. basedir = strdup_or_die(cwd);
  4545. /* XXX: why + 5? */
  4546. abs_file_size = strlen(cwd) + strlen(configfile) + 5;
  4547. abs_file = malloc_or_die(abs_file_size);
  4548. strlcpy(abs_file, basedir, abs_file_size);
  4549. strlcat(abs_file, "/", abs_file_size);
  4550. strlcat(abs_file, configfile, abs_file_size);
  4551. configfile = abs_file;
  4552. }
  4553. #endif /* defined unix */
  4554. files->next = NULL;
  4555. clients->next = NULL;
  4556. /* XXX: factor out initialising after the next stable release. */
  4557. #ifdef _WIN32
  4558. InitWin32();
  4559. #endif
  4560. #ifndef HAVE_ARC4RANDOM
  4561. random_seed = (unsigned int)time(NULL);
  4562. #ifdef HAVE_RANDOM
  4563. srandom(random_seed);
  4564. #else
  4565. srand(random_seed);
  4566. #endif /* ifdef HAVE_RANDOM */
  4567. #endif /* ifndef HAVE_ARC4RANDOM */
  4568. /*
  4569. * Unix signal handling
  4570. *
  4571. * Catch the abort, interrupt and terminate signals for a graceful exit
  4572. * Catch the hangup signal so the errlog can be reopened.
  4573. *
  4574. * Ignore the broken pipe signal as connection failures
  4575. * are handled when and where they occur without relying
  4576. * on a signal.
  4577. */
  4578. #if !defined(_WIN32)
  4579. {
  4580. int idx;
  4581. const int catched_signals[] = { SIGTERM, SIGINT, SIGHUP };
  4582. for (idx = 0; idx < SZ(catched_signals); idx++)
  4583. {
  4584. #ifdef sun /* FIXME: Is it safe to check for HAVE_SIGSET instead? */
  4585. if (sigset(catched_signals[idx], sig_handler) == SIG_ERR)
  4586. #else
  4587. if (signal(catched_signals[idx], sig_handler) == SIG_ERR)
  4588. #endif /* ifdef sun */
  4589. {
  4590. log_error(LOG_LEVEL_FATAL, "Can't set signal-handler for signal %d: %E", catched_signals[idx]);
  4591. }
  4592. }
  4593. if (signal(SIGPIPE, SIG_IGN) == SIG_ERR)
  4594. {
  4595. log_error(LOG_LEVEL_FATAL, "Can't set ignore-handler for SIGPIPE: %E");
  4596. }
  4597. }
  4598. #else /* ifdef _WIN32 */
  4599. # ifdef _WIN_CONSOLE
  4600. /*
  4601. * We *are* in a windows console app.
  4602. * Print a verbose messages about FAQ's and such
  4603. */
  4604. printf("%s", win32_blurb);
  4605. # endif /* def _WIN_CONSOLE */
  4606. #endif /* def _WIN32 */
  4607. #ifdef FUZZ
  4608. if (fuzz_input_type != NULL)
  4609. {
  4610. exit(process_fuzzed_input(fuzz_input_type, fuzz_input_file));
  4611. }
  4612. log_error(LOG_LEVEL_FATAL,
  4613. "When compiled with fuzzing support, Privoxy should only be used for fuzzing. "
  4614. "Various data structures are static which is unsafe when using threads.");
  4615. #endif
  4616. if (do_config_test)
  4617. {
  4618. exit(NULL == load_config());
  4619. }
  4620. /* Initialize the CGI subsystem */
  4621. cgi_init_error_messages();
  4622. /*
  4623. * If running on unix and without the --no-daemon
  4624. * option, become a daemon. I.e. fork, detach
  4625. * from tty and get process group leadership
  4626. */
  4627. #if defined(unix)
  4628. {
  4629. if (daemon_mode)
  4630. {
  4631. int fd;
  4632. pid_t pid = fork();
  4633. if (pid < 0) /* error */
  4634. {
  4635. perror("fork");
  4636. exit(3);
  4637. }
  4638. else if (pid != 0) /* parent */
  4639. {
  4640. int status;
  4641. pid_t wpid;
  4642. /*
  4643. * must check for errors
  4644. * child died due to missing files aso
  4645. */
  4646. sleep(1);
  4647. wpid = waitpid(pid, &status, WNOHANG);
  4648. if (wpid != 0)
  4649. {
  4650. exit(1);
  4651. }
  4652. exit(0);
  4653. }
  4654. /* child */
  4655. setsid();
  4656. /*
  4657. * stderr (fd 2) will be closed later on,
  4658. * when the config file has been parsed.
  4659. */
  4660. close(0);
  4661. close(1);
  4662. /*
  4663. * Reserve fd 0 and 1 to prevent abort() and friends
  4664. * from sending stuff to the clients or servers.
  4665. */
  4666. fd = open("/dev/null", O_RDONLY);
  4667. if (fd == -1)
  4668. {
  4669. log_error(LOG_LEVEL_FATAL, "Failed to open /dev/null: %E");
  4670. }
  4671. else if (fd != 0)
  4672. {
  4673. if (dup2(fd, 0) == -1)
  4674. {
  4675. log_error(LOG_LEVEL_FATAL, "Failed to reserve fd 0: %E");
  4676. }
  4677. close(fd);
  4678. }
  4679. fd = open("/dev/null", O_WRONLY);
  4680. if (fd == -1)
  4681. {
  4682. log_error(LOG_LEVEL_FATAL, "Failed to open /dev/null: %E");
  4683. }
  4684. else if (fd != 1)
  4685. {
  4686. if (dup2(fd, 1) == -1)
  4687. {
  4688. log_error(LOG_LEVEL_FATAL, "Failed to reserve fd 1: %E");
  4689. }
  4690. close(fd);
  4691. }
  4692. #ifdef FEATURE_EXTERNAL_FILTERS
  4693. for (fd = 0; fd < 3; fd++)
  4694. {
  4695. mark_socket_for_close_on_execute(fd);
  4696. }
  4697. #endif
  4698. chdir("/");
  4699. } /* -END- if (daemon_mode) */
  4700. /*
  4701. * As soon as we have written the PID file, we can switch
  4702. * to the user and group ID indicated by the --user option
  4703. */
  4704. if (pidfile != NULL)
  4705. {
  4706. write_pid_file(pidfile);
  4707. }
  4708. if (NULL != pw)
  4709. {
  4710. if (setgid((NULL != grp) ? grp->gr_gid : pw->pw_gid))
  4711. {
  4712. log_error(LOG_LEVEL_FATAL, "Cannot setgid(): Insufficient permissions.");
  4713. }
  4714. if (NULL != grp)
  4715. {
  4716. if (setgroups(1, &grp->gr_gid))
  4717. {
  4718. log_error(LOG_LEVEL_FATAL, "setgroups() failed: %E");
  4719. }
  4720. }
  4721. else if (initgroups(pw->pw_name, pw->pw_gid))
  4722. {
  4723. log_error(LOG_LEVEL_FATAL, "initgroups() failed: %E");
  4724. }
  4725. if (do_chroot)
  4726. {
  4727. if (!pw->pw_dir)
  4728. {
  4729. log_error(LOG_LEVEL_FATAL, "Home directory for %s undefined", pw->pw_name);
  4730. }
  4731. /* Read the time zone file from /etc before doing chroot. */
  4732. tzset();
  4733. if (NULL != pre_chroot_nslookup_to_load_resolver
  4734. && '\0' != pre_chroot_nslookup_to_load_resolver[0])
  4735. {
  4736. /* Initialize resolver library. */
  4737. (void) resolve_hostname_to_ip(pre_chroot_nslookup_to_load_resolver);
  4738. }
  4739. if (chroot(pw->pw_dir) < 0)
  4740. {
  4741. log_error(LOG_LEVEL_FATAL, "Cannot chroot to %s", pw->pw_dir);
  4742. }
  4743. if (chdir ("/"))
  4744. {
  4745. log_error(LOG_LEVEL_FATAL, "Cannot chdir /");
  4746. }
  4747. }
  4748. if (setuid(pw->pw_uid))
  4749. {
  4750. log_error(LOG_LEVEL_FATAL, "Cannot setuid(): Insufficient permissions.");
  4751. }
  4752. if (do_chroot)
  4753. {
  4754. char putenv_dummy[64];
  4755. strlcpy(putenv_dummy, "HOME=/", sizeof(putenv_dummy));
  4756. if (putenv(putenv_dummy) != 0)
  4757. {
  4758. log_error(LOG_LEVEL_FATAL, "Cannot putenv(): HOME");
  4759. }
  4760. snprintf(putenv_dummy, sizeof(putenv_dummy), "USER=%s", pw->pw_name);
  4761. if (putenv(putenv_dummy) != 0)
  4762. {
  4763. log_error(LOG_LEVEL_FATAL, "Cannot putenv(): USER");
  4764. }
  4765. }
  4766. }
  4767. else if (do_chroot)
  4768. {
  4769. log_error(LOG_LEVEL_FATAL, "Cannot chroot without --user argument.");
  4770. }
  4771. }
  4772. #endif /* defined unix */
  4773. #ifdef _WIN32
  4774. /* This will be FALSE unless the command line specified --service
  4775. */
  4776. if (bRunAsService)
  4777. {
  4778. /* Yup, so now we must attempt to establish a connection
  4779. * with the service dispatcher. This will only work if this
  4780. * process was launched by the service control manager to
  4781. * actually run as a service. If this isn't the case, i've
  4782. * known it take around 30 seconds or so for the call to return.
  4783. */
  4784. /* The StartServiceCtrlDispatcher won't return until the service is stopping */
  4785. if (w32_start_service_ctrl_dispatcher(w32ServiceDispatchTable))
  4786. {
  4787. /* Service has run, and at this point is now being stopped, so just return */
  4788. return 0;
  4789. }
  4790. #ifdef _WIN_CONSOLE
  4791. printf("Warning: Failed to connect to Service Control Dispatcher\nwhen starting as a service!\n");
  4792. #endif
  4793. /* An error occurred. Usually it's because --service was wrongly specified
  4794. * and we were unable to connect to the Service Control Dispatcher because
  4795. * it wasn't expecting us and is therefore not listening.
  4796. *
  4797. * For now, just continue below to call the listen_loop function.
  4798. */
  4799. }
  4800. #endif /* def _WIN32 */
  4801. listen_loop();
  4802. /* NOTREACHED */
  4803. return(-1);
  4804. }
  4805. /*********************************************************************
  4806. *
  4807. * Function : bind_port_helper
  4808. *
  4809. * Description : Bind the listen port. Handles logging, and aborts
  4810. * on failure.
  4811. *
  4812. * Parameters :
  4813. * 1 : haddr = Host address to bind to. Use NULL to bind to
  4814. * INADDR_ANY.
  4815. * 2 : hport = Specifies port to bind to.
  4816. * 3 : backlog = Listen backlog.
  4817. *
  4818. * Returns : Port that was opened.
  4819. *
  4820. *********************************************************************/
  4821. static jb_socket bind_port_helper(const char *haddr, int hport, int backlog)
  4822. {
  4823. int result;
  4824. jb_socket bfd;
  4825. result = bind_port(haddr, hport, backlog, &bfd);
  4826. if (result < 0)
  4827. {
  4828. const char *bind_address = (NULL != haddr) ? haddr : "INADDR_ANY";
  4829. switch(result)
  4830. {
  4831. case -3:
  4832. log_error(LOG_LEVEL_FATAL,
  4833. "can't bind to %s:%d: There may be another Privoxy "
  4834. "or some other proxy running on port %d",
  4835. bind_address, hport, hport);
  4836. case -2:
  4837. log_error(LOG_LEVEL_FATAL,
  4838. "can't bind to %s:%d: The hostname is not resolvable",
  4839. bind_address, hport);
  4840. default:
  4841. log_error(LOG_LEVEL_FATAL, "can't bind to %s:%d: %E",
  4842. bind_address, hport);
  4843. }
  4844. /* shouldn't get here */
  4845. return JB_INVALID_SOCKET;
  4846. }
  4847. #ifndef HAVE_POLL
  4848. #ifndef _WIN32
  4849. if (bfd >= FD_SETSIZE)
  4850. {
  4851. log_error(LOG_LEVEL_FATAL,
  4852. "Bind socket number too high to use select(): %d >= %d",
  4853. bfd, FD_SETSIZE);
  4854. }
  4855. #endif
  4856. #endif
  4857. if (haddr == NULL)
  4858. {
  4859. log_error(LOG_LEVEL_INFO, "Listening on port %d on all IP addresses",
  4860. hport);
  4861. }
  4862. else
  4863. {
  4864. log_error(LOG_LEVEL_INFO, "Listening on port %d on IP address %s",
  4865. hport, haddr);
  4866. }
  4867. return bfd;
  4868. }
  4869. /*********************************************************************
  4870. *
  4871. * Function : bind_ports_helper
  4872. *
  4873. * Description : Bind the listen ports. Handles logging, and aborts
  4874. * on failure.
  4875. *
  4876. * Parameters :
  4877. * 1 : config = Privoxy configuration. Specifies ports
  4878. * to bind to.
  4879. * 2 : sockets = Preallocated array of opened sockets
  4880. * corresponding to specification in config.
  4881. * All non-opened sockets will be set to
  4882. * JB_INVALID_SOCKET.
  4883. *
  4884. * Returns : Nothing. Inspect sockets argument.
  4885. *
  4886. *********************************************************************/
  4887. static void bind_ports_helper(struct configuration_spec * config,
  4888. jb_socket sockets[])
  4889. {
  4890. int i;
  4891. for (i = 0; i < MAX_LISTENING_SOCKETS; i++)
  4892. {
  4893. if (config->hport[i])
  4894. {
  4895. sockets[i] = bind_port_helper(config->haddr[i],
  4896. config->hport[i], config->listen_backlog);
  4897. #if defined(FEATURE_ACCEPT_FILTER) && defined(SO_ACCEPTFILTER)
  4898. if (config->enable_accept_filter && sockets[i] != JB_INVALID_SOCKET)
  4899. {
  4900. struct accept_filter_arg af_options;
  4901. bzero(&af_options, sizeof(af_options));
  4902. strlcpy(af_options.af_name, "httpready", sizeof(af_options.af_name));
  4903. if (setsockopt(sockets[i], SOL_SOCKET, SO_ACCEPTFILTER, &af_options,
  4904. sizeof(af_options)))
  4905. {
  4906. log_error(LOG_LEVEL_ERROR,
  4907. "Enabling accept filter for socket %d failed: %E", sockets[i]);
  4908. }
  4909. }
  4910. #endif
  4911. }
  4912. else
  4913. {
  4914. sockets[i] = JB_INVALID_SOCKET;
  4915. }
  4916. }
  4917. config->need_bind = 0;
  4918. }
  4919. /*********************************************************************
  4920. *
  4921. * Function : close_ports_helper
  4922. *
  4923. * Description : Close listenings ports.
  4924. *
  4925. * Parameters :
  4926. * 1 : sockets = Array of opened and non-opened sockets to
  4927. * close. All sockets will be set to
  4928. * JB_INVALID_SOCKET.
  4929. *
  4930. * Returns : Nothing.
  4931. *
  4932. *********************************************************************/
  4933. static void close_ports_helper(jb_socket sockets[])
  4934. {
  4935. int i;
  4936. for (i = 0; i < MAX_LISTENING_SOCKETS; i++)
  4937. {
  4938. if (JB_INVALID_SOCKET != sockets[i])
  4939. {
  4940. close_socket(sockets[i]);
  4941. }
  4942. sockets[i] = JB_INVALID_SOCKET;
  4943. }
  4944. }
  4945. #ifdef _WIN32
  4946. /* Without this simple workaround we get this compiler warning from _beginthread
  4947. * warning C4028: formal parameter 1 different from declaration
  4948. */
  4949. void w32_service_listen_loop(void *p)
  4950. {
  4951. listen_loop();
  4952. }
  4953. #endif /* def _WIN32 */
  4954. /*********************************************************************
  4955. *
  4956. * Function : listen_loop
  4957. *
  4958. * Description : bind the listen port and enter a "FOREVER" listening loop.
  4959. *
  4960. * Parameters : N/A
  4961. *
  4962. * Returns : Never.
  4963. *
  4964. *********************************************************************/
  4965. static void listen_loop(void)
  4966. {
  4967. struct client_states *csp_list = NULL;
  4968. struct client_state *csp = NULL;
  4969. jb_socket bfds[MAX_LISTENING_SOCKETS];
  4970. struct configuration_spec *config;
  4971. unsigned int active_threads = 0;
  4972. #if defined(FEATURE_PTHREAD)
  4973. pthread_attr_t attrs;
  4974. pthread_attr_init(&attrs);
  4975. pthread_attr_setdetachstate(&attrs, PTHREAD_CREATE_DETACHED);
  4976. #endif
  4977. config = load_config();
  4978. #ifdef FEATURE_CONNECTION_SHARING
  4979. /*
  4980. * XXX: Should be relocated once it no
  4981. * longer needs to emit log messages.
  4982. */
  4983. initialize_reusable_connections();
  4984. #endif /* def FEATURE_CONNECTION_SHARING */
  4985. bind_ports_helper(config, bfds);
  4986. #ifdef FEATURE_GRACEFUL_TERMINATION
  4987. while (!g_terminate)
  4988. #else
  4989. for (;;)
  4990. #endif
  4991. {
  4992. #if !defined(FEATURE_PTHREAD) && !defined(_WIN32) && !defined(__BEOS__)
  4993. while (waitpid(-1, NULL, WNOHANG) > 0)
  4994. {
  4995. /* zombie children */
  4996. }
  4997. #endif /* !defined(FEATURE_PTHREAD) && !defined(_WIN32) && !defined(__BEOS__) */
  4998. /*
  4999. * Free data that was used by died threads
  5000. */
  5001. active_threads = sweep();
  5002. #if defined(unix)
  5003. /*
  5004. * Re-open the errlog after HUP signal
  5005. */
  5006. if (received_hup_signal)
  5007. {
  5008. if (NULL != config->logfile)
  5009. {
  5010. init_error_log(Argv[0], config->logfile);
  5011. }
  5012. received_hup_signal = 0;
  5013. }
  5014. #endif
  5015. csp_list = zalloc_or_die(sizeof(*csp_list));
  5016. csp = &csp_list->csp;
  5017. log_error(LOG_LEVEL_CONNECT,
  5018. "Waiting for the next client connection. Currently active threads: %u",
  5019. active_threads);
  5020. /*
  5021. * This config may be outdated, but for accept_connection()
  5022. * it's fresh enough.
  5023. */
  5024. csp->config = config;
  5025. if (!accept_connection(csp, bfds))
  5026. {
  5027. log_error(LOG_LEVEL_CONNECT, "accept failed: %E");
  5028. freez(csp_list);
  5029. continue;
  5030. }
  5031. csp->flags |= CSP_FLAG_ACTIVE;
  5032. csp->server_connection.sfd = JB_INVALID_SOCKET;
  5033. csp->config = config = load_config();
  5034. if (config->need_bind)
  5035. {
  5036. /*
  5037. * Since we were listening to the "old port", we will not see
  5038. * a "listen" param change until the next request. So, at
  5039. * least 1 more request must be made for us to find the new
  5040. * setting. I am simply closing the old socket and binding the
  5041. * new one.
  5042. *
  5043. * Which-ever is correct, we will serve 1 more page via the
  5044. * old settings. This should probably be a "show-status"
  5045. * request. This should not be a so common of an operation
  5046. * that this will hurt people's feelings.
  5047. */
  5048. close_ports_helper(bfds);
  5049. bind_ports_helper(config, bfds);
  5050. }
  5051. #ifdef FEATURE_TOGGLE
  5052. if (global_toggle_state)
  5053. #endif /* def FEATURE_TOGGLE */
  5054. {
  5055. csp->flags |= CSP_FLAG_TOGGLED_ON;
  5056. }
  5057. if (run_loader(csp))
  5058. {
  5059. log_error(LOG_LEVEL_FATAL, "a loader failed - must exit");
  5060. /* Never get here - LOG_LEVEL_FATAL causes program exit */
  5061. }
  5062. #ifdef FEATURE_ACL
  5063. if (block_acl(NULL,csp))
  5064. {
  5065. log_error(LOG_LEVEL_CONNECT,
  5066. "Connection from %s on %s (socket %d) dropped due to ACL",
  5067. csp->ip_addr_str, csp->listen_addr_str, csp->cfd);
  5068. close_socket(csp->cfd);
  5069. freez(csp->ip_addr_str);
  5070. freez(csp->listen_addr_str);
  5071. freez(csp_list);
  5072. continue;
  5073. }
  5074. #endif /* def FEATURE_ACL */
  5075. if ((0 != config->max_client_connections)
  5076. && (active_threads >= config->max_client_connections))
  5077. {
  5078. log_error(LOG_LEVEL_CONNECT,
  5079. "Rejecting connection from %s. Maximum number of connections reached.",
  5080. csp->ip_addr_str);
  5081. write_socket_delayed(csp->cfd, TOO_MANY_CONNECTIONS_RESPONSE,
  5082. strlen(TOO_MANY_CONNECTIONS_RESPONSE), get_write_delay(csp));
  5083. close_socket(csp->cfd);
  5084. freez(csp->ip_addr_str);
  5085. freez(csp->listen_addr_str);
  5086. freez(csp_list);
  5087. continue;
  5088. }
  5089. /* add it to the list of clients */
  5090. csp_list->next = clients->next;
  5091. clients->next = csp_list;
  5092. if (config->multi_threaded)
  5093. {
  5094. int child_id;
  5095. /* this is a switch () statement in the C preprocessor - ugh */
  5096. #undef SELECTED_ONE_OPTION
  5097. /* Use Pthreads in preference to native code */
  5098. #if defined(FEATURE_PTHREAD) && !defined(SELECTED_ONE_OPTION)
  5099. #define SELECTED_ONE_OPTION
  5100. {
  5101. pthread_t the_thread;
  5102. int ret;
  5103. ret = pthread_create(&the_thread, &attrs,
  5104. (void * (*)(void *))serve, csp);
  5105. child_id = ret ? -1 : 0;
  5106. }
  5107. #endif
  5108. #if defined(_WIN32) && !defined(_CYGWIN) && !defined(SELECTED_ONE_OPTION)
  5109. #define SELECTED_ONE_OPTION
  5110. child_id = _beginthread(
  5111. (void (*)(void *))serve,
  5112. 64 * 1024,
  5113. csp);
  5114. #endif
  5115. #if defined(__BEOS__) && !defined(SELECTED_ONE_OPTION)
  5116. #define SELECTED_ONE_OPTION
  5117. {
  5118. thread_id tid = spawn_thread
  5119. (server_thread, "server", B_NORMAL_PRIORITY, csp);
  5120. if ((tid >= 0) && (resume_thread(tid) == B_OK))
  5121. {
  5122. child_id = (int) tid;
  5123. }
  5124. else
  5125. {
  5126. child_id = -1;
  5127. }
  5128. }
  5129. #endif
  5130. #if !defined(SELECTED_ONE_OPTION)
  5131. child_id = fork();
  5132. /* This block is only needed when using fork().
  5133. * When using threads, the server thread was
  5134. * created and run by the call to _beginthread().
  5135. */
  5136. if (child_id == 0) /* child */
  5137. {
  5138. int rc = 0;
  5139. #ifdef FEATURE_TOGGLE
  5140. int inherited_toggle_state = global_toggle_state;
  5141. #endif /* def FEATURE_TOGGLE */
  5142. serve(csp);
  5143. /*
  5144. * If we've been toggled or we've blocked the request, tell Mom
  5145. */
  5146. #ifdef FEATURE_TOGGLE
  5147. if (inherited_toggle_state != global_toggle_state)
  5148. {
  5149. rc |= RC_FLAG_TOGGLED;
  5150. }
  5151. #endif /* def FEATURE_TOGGLE */
  5152. #ifdef FEATURE_STATISTICS
  5153. if (csp->flags & CSP_FLAG_REJECTED)
  5154. {
  5155. rc |= RC_FLAG_BLOCKED;
  5156. }
  5157. #endif /* ndef FEATURE_STATISTICS */
  5158. _exit(rc);
  5159. }
  5160. else if (child_id > 0) /* parent */
  5161. {
  5162. /* in a fork()'d environment, the parent's
  5163. * copy of the client socket and the CSP
  5164. * are not used.
  5165. */
  5166. int child_status;
  5167. #if !defined(_WIN32) && !defined(__CYGWIN__)
  5168. wait(&child_status);
  5169. /*
  5170. * Evaluate child's return code: If the child has
  5171. * - been toggled, toggle ourselves
  5172. * - blocked its request, bump up the stats counter
  5173. */
  5174. #ifdef FEATURE_TOGGLE
  5175. if (WIFEXITED(child_status) && (WEXITSTATUS(child_status) & RC_FLAG_TOGGLED))
  5176. {
  5177. global_toggle_state = !global_toggle_state;
  5178. }
  5179. #endif /* def FEATURE_TOGGLE */
  5180. #ifdef FEATURE_STATISTICS
  5181. urls_read++;
  5182. if (WIFEXITED(child_status) && (WEXITSTATUS(child_status) & RC_FLAG_BLOCKED))
  5183. {
  5184. urls_rejected++;
  5185. }
  5186. #endif /* def FEATURE_STATISTICS */
  5187. #endif /* !defined(_WIN32) && defined(__CYGWIN__) */
  5188. close_socket(csp->cfd);
  5189. csp->flags &= ~CSP_FLAG_ACTIVE;
  5190. }
  5191. #endif
  5192. #undef SELECTED_ONE_OPTION
  5193. /* end of cpp switch () */
  5194. if (child_id < 0)
  5195. {
  5196. /*
  5197. * Spawning the child failed, assume it's because
  5198. * there are too many children running already.
  5199. * XXX: If you assume ...
  5200. */
  5201. log_error(LOG_LEVEL_ERROR,
  5202. "Unable to take any additional connections: %E. Active threads: %u",
  5203. active_threads);
  5204. write_socket_delayed(csp->cfd, TOO_MANY_CONNECTIONS_RESPONSE,
  5205. strlen(TOO_MANY_CONNECTIONS_RESPONSE), get_write_delay(csp));
  5206. close_socket(csp->cfd);
  5207. csp->flags &= ~CSP_FLAG_ACTIVE;
  5208. }
  5209. }
  5210. else
  5211. {
  5212. serve(csp);
  5213. }
  5214. }
  5215. #if defined(FEATURE_PTHREAD)
  5216. pthread_attr_destroy(&attrs);
  5217. #endif
  5218. /* NOTREACHED unless FEATURE_GRACEFUL_TERMINATION is defined */
  5219. #ifdef FEATURE_HTTPS_INSPECTION
  5220. /* Clean up. Aim: free all memory (no leaks) */
  5221. ssl_release();
  5222. #endif
  5223. #ifdef FEATURE_GRACEFUL_TERMINATION
  5224. log_error(LOG_LEVEL_INFO, "Graceful termination requested");
  5225. unload_current_config_file();
  5226. unload_current_actions_file();
  5227. unload_current_re_filterfile();
  5228. #ifdef FEATURE_TRUST
  5229. unload_current_trust_file();
  5230. #endif
  5231. if (config->multi_threaded)
  5232. {
  5233. int i = 60;
  5234. do
  5235. {
  5236. sleep(1);
  5237. sweep();
  5238. } while ((clients->next != NULL) && (--i > 0));
  5239. if (i <= 0)
  5240. {
  5241. log_error(LOG_LEVEL_ERROR, "Graceful termination failed - still some live clients after 1 minute wait.");
  5242. }
  5243. }
  5244. sweep();
  5245. sweep();
  5246. #if defined(unix)
  5247. freez(basedir);
  5248. #endif
  5249. #if defined(_WIN32) && !defined(_WIN_CONSOLE)
  5250. /* Cleanup - remove taskbar icon etc. */
  5251. TermLogWindow();
  5252. #endif
  5253. exit(0);
  5254. #endif /* FEATURE_GRACEFUL_TERMINATION */
  5255. }
  5256. /*
  5257. Local Variables:
  5258. tab-width: 3
  5259. end:
  5260. */