chrome_content_browser_client.cc 265 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743
  1. // Copyright (c) 2012 The Chromium Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style license that can be
  3. // found in the LICENSE file.
  4. #include "chrome/browser/chrome_content_browser_client.h"
  5. #include <iterator>
  6. #include <map>
  7. #include <memory>
  8. #include <set>
  9. #include <utility>
  10. #include <vector>
  11. #include "base/base_switches.h"
  12. #include "base/bind.h"
  13. #include "base/callback.h"
  14. #include "base/command_line.h"
  15. #include "base/dcheck_is_on.h"
  16. #include "base/i18n/base_i18n_switches.h"
  17. #include "base/i18n/character_encoding.h"
  18. #include "base/memory/raw_ptr.h"
  19. #include "base/metrics/field_trial_params.h"
  20. #include "base/metrics/histogram_macros.h"
  21. #include "base/no_destructor.h"
  22. #include "base/path_service.h"
  23. #include "base/strings/strcat.h"
  24. #include "base/strings/string_number_conversions.h"
  25. #include "base/strings/string_split.h"
  26. #include "base/strings/string_util.h"
  27. #include "base/strings/stringprintf.h"
  28. #include "base/values.h"
  29. #include "build/build_config.h"
  30. #include "build/chromeos_buildflags.h"
  31. #include "chrome/browser/accessibility/accessibility_labels_service.h"
  32. #include "chrome/browser/accessibility/accessibility_labels_service_factory.h"
  33. #include "chrome/browser/after_startup_task_utils.h"
  34. #include "chrome/browser/bluetooth/chrome_bluetooth_delegate_impl_client.h"
  35. #include "chrome/browser/browser_about_handler.h"
  36. #include "chrome/browser/browser_features.h"
  37. #include "chrome/browser/browser_process.h"
  38. #include "chrome/browser/browsing_topics/browsing_topics_service_factory.h"
  39. #include "chrome/browser/captive_portal/captive_portal_service_factory.h"
  40. #include "chrome/browser/chrome_content_browser_client_binder_policies.h"
  41. #include "chrome/browser/chrome_content_browser_client_parts.h"
  42. #include "chrome/browser/content_settings/cookie_settings_factory.h"
  43. #include "chrome/browser/content_settings/host_content_settings_map_factory.h"
  44. #include "chrome/browser/custom_handlers/protocol_handler_registry_factory.h"
  45. #include "chrome/browser/data_saver/data_saver.h"
  46. #include "chrome/browser/data_use_measurement/chrome_data_use_measurement.h"
  47. #include "chrome/browser/defaults.h"
  48. #include "chrome/browser/device_api/device_service_impl.h"
  49. #include "chrome/browser/device_api/managed_configuration_service.h"
  50. #include "chrome/browser/download/chrome_download_manager_delegate.h"
  51. #include "chrome/browser/download/download_prefs.h"
  52. #include "chrome/browser/enterprise/browser_management/management_service_factory.h"
  53. #include "chrome/browser/enterprise/connectors/connectors_service.h"
  54. #include "chrome/browser/enterprise/util/managed_browser_utils.h"
  55. #include "chrome/browser/extensions/chrome_extension_cookies.h"
  56. #include "chrome/browser/external_protocol/external_protocol_handler.h"
  57. #include "chrome/browser/favicon/favicon_utils.h"
  58. #include "chrome/browser/font_family_cache.h"
  59. #include "chrome/browser/gpu/chrome_browser_main_extra_parts_gpu.h"
  60. #include "chrome/browser/hid/chrome_hid_delegate.h"
  61. #include "chrome/browser/interstitials/enterprise_util.h"
  62. #include "chrome/browser/lifetime/browser_shutdown.h"
  63. #include "chrome/browser/lookalikes/lookalike_url_navigation_throttle.h"
  64. #include "chrome/browser/media/audio_service_util.h"
  65. #include "chrome/browser/media/router/media_router_feature.h"
  66. #include "chrome/browser/media/webrtc/audio_debug_recordings_handler.h"
  67. #include "chrome/browser/media/webrtc/capture_policy_utils.h"
  68. #include "chrome/browser/media/webrtc/chrome_screen_enumerator.h"
  69. #include "chrome/browser/media/webrtc/media_capture_devices_dispatcher.h"
  70. #include "chrome/browser/media/webrtc/webrtc_logging_controller.h"
  71. #include "chrome/browser/memory/chrome_browser_main_extra_parts_memory.h"
  72. #include "chrome/browser/metrics/chrome_browser_main_extra_parts_metrics.h"
  73. #include "chrome/browser/metrics/chrome_feature_list_creator.h"
  74. #include "chrome/browser/net/chrome_network_delegate.h"
  75. #include "chrome/browser/net/profile_network_context_service.h"
  76. #include "chrome/browser/net/profile_network_context_service_factory.h"
  77. #include "chrome/browser/net/system_network_context_manager.h"
  78. #include "chrome/browser/payments/payment_request_display_manager_factory.h"
  79. #include "chrome/browser/performance_manager/chrome_browser_main_extra_parts_performance_manager.h"
  80. #include "chrome/browser/performance_manager/chrome_content_browser_client_performance_manager_part.h"
  81. #include "chrome/browser/performance_monitor/chrome_browser_main_extra_parts_performance_monitor.h"
  82. #include "chrome/browser/plugins/pdf_iframe_navigation_throttle.h"
  83. #include "chrome/browser/plugins/plugin_utils.h"
  84. #include "chrome/browser/policy/profile_policy_connector.h"
  85. #include "chrome/browser/prefetch/prefetch_prefs.h"
  86. #include "chrome/browser/preloading/navigation_ablation_throttle.h"
  87. #include "chrome/browser/preloading/prefetch/no_state_prefetch/chrome_no_state_prefetch_contents_delegate.h"
  88. #include "chrome/browser/preloading/prefetch/no_state_prefetch/no_state_prefetch_manager_factory.h"
  89. #include "chrome/browser/preloading/prefetch/no_state_prefetch/no_state_prefetch_navigation_throttle.h"
  90. #include "chrome/browser/preloading/prefetch/prefetch_proxy/chrome_prefetch_service_delegate.h"
  91. #include "chrome/browser/preloading/prefetch/prefetch_proxy/chrome_speculation_host_delegate.h"
  92. #include "chrome/browser/preloading/prefetch/prefetch_proxy/prefetch_proxy_features.h"
  93. #include "chrome/browser/preloading/prefetch/prefetch_proxy/prefetch_proxy_service.h"
  94. #include "chrome/browser/preloading/prefetch/prefetch_proxy/prefetch_proxy_service_factory.h"
  95. #include "chrome/browser/preloading/prefetch/prefetch_proxy/prefetch_proxy_url_loader_interceptor.h"
  96. #include "chrome/browser/preloading/prefetch/search_prefetch/field_trial_settings.h"
  97. #include "chrome/browser/preloading/prefetch/search_prefetch/search_prefetch_url_loader.h"
  98. #include "chrome/browser/preloading/prefetch/search_prefetch/search_prefetch_url_loader_interceptor.h"
  99. #include "chrome/browser/privacy_sandbox/privacy_sandbox_settings_factory.h"
  100. #include "chrome/browser/profiles/chrome_browser_main_extra_parts_profiles.h"
  101. #include "chrome/browser/profiles/profile.h"
  102. #include "chrome/browser/profiles/profile_io_data.h"
  103. #include "chrome/browser/profiles/profile_manager.h"
  104. #include "chrome/browser/profiles/renderer_updater.h"
  105. #include "chrome/browser/profiles/renderer_updater_factory.h"
  106. #include "chrome/browser/profiling_host/chrome_browser_main_extra_parts_profiling.h"
  107. #include "chrome/browser/renderer_host/chrome_navigation_ui_data.h"
  108. #include "chrome/browser/renderer_preferences_util.h"
  109. #include "chrome/browser/safe_browsing/certificate_reporting_service.h"
  110. #include "chrome/browser/safe_browsing/certificate_reporting_service_factory.h"
  111. #include "chrome/browser/safe_browsing/cloud_content_scanning/deep_scanning_utils.h"
  112. #include "chrome/browser/safe_browsing/delayed_warning_navigation_throttle.h"
  113. #include "chrome/browser/safe_browsing/safe_browsing_service.h"
  114. #include "chrome/browser/safe_browsing/url_checker_delegate_impl.h"
  115. #include "chrome/browser/safe_browsing/url_lookup_service_factory.h"
  116. #include "chrome/browser/search/search.h"
  117. #include "chrome/browser/segmentation_platform/chrome_browser_main_extra_parts_segmentation_platform.h"
  118. #include "chrome/browser/sharing/sms/sms_remote_fetcher.h"
  119. #include "chrome/browser/signin/chrome_signin_proxying_url_loader_factory.h"
  120. #include "chrome/browser/signin/chrome_signin_url_loader_throttle.h"
  121. #include "chrome/browser/signin/header_modification_delegate_impl.h"
  122. #include "chrome/browser/speech/chrome_speech_recognition_manager_delegate.h"
  123. #include "chrome/browser/ssl/chrome_security_blocking_page_factory.h"
  124. #include "chrome/browser/ssl/https_defaulted_callbacks.h"
  125. #include "chrome/browser/ssl/https_only_mode_navigation_throttle.h"
  126. #include "chrome/browser/ssl/https_only_mode_upgrade_interceptor.h"
  127. #include "chrome/browser/ssl/sct_reporting_service.h"
  128. #include "chrome/browser/ssl/ssl_client_auth_metrics.h"
  129. #include "chrome/browser/ssl/ssl_client_certificate_selector.h"
  130. #include "chrome/browser/ssl/typed_navigation_upgrade_throttle.h"
  131. #include "chrome/browser/tracing/chrome_tracing_delegate.h"
  132. #include "chrome/browser/translate/translate_service.h"
  133. #include "chrome/browser/ui/blocked_content/blocked_window_params.h"
  134. #include "chrome/browser/ui/blocked_content/chrome_popup_navigation_delegate.h"
  135. #include "chrome/browser/ui/blocked_content/tab_under_navigation_throttle.h"
  136. #include "chrome/browser/ui/browser_navigator.h"
  137. #include "chrome/browser/ui/browser_navigator_params.h"
  138. #include "chrome/browser/ui/chrome_select_file_policy.h"
  139. #include "chrome/browser/ui/login/login_handler.h"
  140. #include "chrome/browser/ui/login/login_navigation_throttle.h"
  141. #include "chrome/browser/ui/login/login_tab_helper.h"
  142. #include "chrome/browser/ui/passwords/password_manager_navigation_throttle.h"
  143. #include "chrome/browser/ui/passwords/well_known_change_password_navigation_throttle.h"
  144. #include "chrome/browser/ui/prefs/pref_watcher.h"
  145. #include "chrome/browser/ui/tab_contents/chrome_web_contents_view_delegate.h"
  146. #include "chrome/browser/ui/ui_features.h"
  147. #include "chrome/browser/ui/webid/identity_dialog_controller.h"
  148. #include "chrome/browser/ui/webui/chrome_web_ui_controller_factory.h"
  149. #include "chrome/browser/ui/webui/log_web_ui_url.h"
  150. #include "chrome/browser/universal_web_contents_observers.h"
  151. #include "chrome/browser/usb/chrome_usb_delegate.h"
  152. #include "chrome/browser/vr/vr_tab_helper.h"
  153. #include "chrome/browser/webapps/web_app_offline.h"
  154. #include "chrome/browser/webauthn/webauthn_pref_names.h"
  155. #include "chrome/common/buildflags.h"
  156. #include "chrome/common/channel_info.h"
  157. #include "chrome/common/chrome_constants.h"
  158. #include "chrome/common/chrome_content_client.h"
  159. #include "chrome/common/chrome_features.h"
  160. #include "chrome/common/chrome_paths.h"
  161. #include "chrome/common/chrome_paths_internal.h"
  162. #include "chrome/common/chrome_switches.h"
  163. #include "chrome/common/env_vars.h"
  164. #include "chrome/common/google_url_loader_throttle.h"
  165. #include "chrome/common/logging_chrome.h"
  166. #include "chrome/common/pdf_util.h"
  167. #include "chrome/common/pref_names.h"
  168. #include "chrome/common/profiler/thread_profiler_configuration.h"
  169. #include "chrome/common/renderer_configuration.mojom.h"
  170. #include "chrome/common/secure_origin_allowlist.h"
  171. #include "chrome/common/url_constants.h"
  172. #include "chrome/common/webui_url_constants.h"
  173. #include "chrome/grit/generated_resources.h"
  174. #include "chrome/installer/util/google_update_settings.h"
  175. #include "components/autofill/core/common/autofill_switches.h"
  176. #include "components/blocked_content/popup_blocker.h"
  177. #include "components/browsing_topics/browsing_topics_service.h"
  178. #include "components/captive_portal/core/buildflags.h"
  179. #include "components/content_settings/browser/page_specific_content_settings.h"
  180. #include "components/content_settings/core/browser/cookie_settings.h"
  181. #include "components/content_settings/core/browser/host_content_settings_map.h"
  182. #include "components/content_settings/core/browser/private_network_settings.h"
  183. #include "components/content_settings/core/common/content_settings.h"
  184. #include "components/content_settings/core/common/content_settings_types.h"
  185. #include "components/custom_handlers/protocol_handler_registry.h"
  186. #include "components/custom_handlers/protocol_handler_throttle.h"
  187. #include "components/dom_distiller/core/dom_distiller_switches.h"
  188. #include "components/dom_distiller/core/url_constants.h"
  189. #include "components/embedder_support/content_settings_utils.h"
  190. #include "components/embedder_support/switches.h"
  191. #include "components/enterprise/content/clipboard_restriction_service.h"
  192. #include "components/enterprise/content/pref_names.h"
  193. #include "components/error_page/common/error.h"
  194. #include "components/error_page/common/error_page_switches.h"
  195. #include "components/error_page/common/localized_error.h"
  196. #include "components/error_page/content/browser/net_error_auto_reloader.h"
  197. #include "components/google/core/common/google_switches.h"
  198. #include "components/keep_alive_registry/keep_alive_types.h"
  199. #include "components/keep_alive_registry/scoped_keep_alive.h"
  200. #include "components/language/core/browser/pref_names.h"
  201. #include "components/live_caption/caption_util.h"
  202. #include "components/media_router/browser/presentation/presentation_service_delegate_impl.h"
  203. #include "components/media_router/browser/presentation/receiver_presentation_service_delegate_impl.h"
  204. #include "components/media_router/browser/presentation/web_contents_presentation_manager.h"
  205. #include "components/metrics/client_info.h"
  206. #include "components/metrics_services_manager/metrics_services_manager.h"
  207. #include "components/net_log/chrome_net_log.h"
  208. #include "components/no_state_prefetch/browser/no_state_prefetch_manager.h"
  209. #include "components/no_state_prefetch/common/no_state_prefetch_final_status.h"
  210. #include "components/no_state_prefetch/common/prerender_url_loader_throttle.h"
  211. #include "components/omnibox/common/omnibox_features.h"
  212. #include "components/page_load_metrics/browser/metrics_navigation_throttle.h"
  213. #include "components/page_load_metrics/browser/metrics_web_contents_observer.h"
  214. #include "components/payments/content/payment_handler_navigation_throttle.h"
  215. #include "components/payments/content/payment_request_display_manager.h"
  216. #include "components/performance_manager/embedder/performance_manager_registry.h"
  217. #include "components/permissions/bluetooth_delegate_impl.h"
  218. #include "components/permissions/permission_context_base.h"
  219. #include "components/permissions/quota_permission_context_impl.h"
  220. #include "components/policy/content/policy_blocklist_navigation_throttle.h"
  221. #include "components/policy/content/policy_blocklist_service.h"
  222. #include "components/policy/core/common/management/management_service.h"
  223. #include "components/policy/core/common/policy_pref_names.h"
  224. #include "components/pref_registry/pref_registry_syncable.h"
  225. #include "components/prefs/pref_registry_simple.h"
  226. #include "components/prefs/pref_service.h"
  227. #include "components/prefs/scoped_user_pref_update.h"
  228. #include "components/privacy_sandbox/privacy_sandbox_settings.h"
  229. #include "components/safe_browsing/buildflags.h"
  230. #include "components/safe_browsing/content/browser/browser_url_loader_throttle.h"
  231. #include "components/safe_browsing/content/browser/password_protection/password_protection_commit_deferring_condition.h"
  232. #include "components/safe_browsing/content/browser/safe_browsing_navigation_throttle.h"
  233. #include "components/safe_browsing/core/browser/realtime/policy_engine.h"
  234. #include "components/safe_browsing/core/browser/realtime/url_lookup_service.h"
  235. #include "components/safe_browsing/core/browser/url_checker_delegate.h"
  236. #include "components/safe_browsing/core/common/features.h"
  237. #include "components/safe_browsing/core/common/safe_browsing_prefs.h"
  238. #include "components/security_interstitials/content/insecure_form_navigation_throttle.h"
  239. #include "components/security_interstitials/content/ssl_cert_reporter.h"
  240. #include "components/security_interstitials/content/ssl_error_handler.h"
  241. #include "components/security_interstitials/content/ssl_error_navigation_throttle.h"
  242. #include "components/services/storage/public/cpp/storage_prefs.h"
  243. #include "components/site_isolation/pref_names.h"
  244. #include "components/site_isolation/preloaded_isolated_origins.h"
  245. #include "components/site_isolation/site_isolation_policy.h"
  246. #include "components/subresource_filter/content/browser/content_subresource_filter_throttle_manager.h"
  247. #include "components/translate/core/common/translate_switches.h"
  248. #include "components/url_param_filter/content/url_param_filter_throttle.h"
  249. #include "components/variations/variations_associated_data.h"
  250. #include "components/variations/variations_switches.h"
  251. #include "content/public/browser/browser_child_process_host.h"
  252. #include "content/public/browser/browser_context.h"
  253. #include "content/public/browser/browser_main_parts.h"
  254. #include "content/public/browser/browser_ppapi_host.h"
  255. #include "content/public/browser/browser_task_traits.h"
  256. #include "content/public/browser/browser_thread.h"
  257. #include "content/public/browser/browser_url_handler.h"
  258. #include "content/public/browser/certificate_request_result_type.h"
  259. #include "content/public/browser/child_process_data.h"
  260. #include "content/public/browser/child_process_security_policy.h"
  261. #include "content/public/browser/client_certificate_delegate.h"
  262. #include "content/public/browser/file_url_loader.h"
  263. #include "content/public/browser/navigation_handle.h"
  264. #include "content/public/browser/navigation_throttle.h"
  265. #include "content/public/browser/overlay_window.h"
  266. #include "content/public/browser/permission_controller.h"
  267. #include "content/public/browser/render_frame_host.h"
  268. #include "content/public/browser/render_process_host.h"
  269. #include "content/public/browser/site_isolation_mode.h"
  270. #include "content/public/browser/sms_fetcher.h"
  271. #include "content/public/browser/tts_controller.h"
  272. #include "content/public/browser/tts_platform.h"
  273. #include "content/public/browser/url_loader_request_interceptor.h"
  274. #include "content/public/browser/vpn_service_proxy.h"
  275. #include "content/public/browser/weak_document_ptr.h"
  276. #include "content/public/browser/web_contents.h"
  277. #include "content/public/browser/web_contents_delegate.h"
  278. #include "content/public/browser/web_contents_view_delegate.h"
  279. #include "content/public/browser/web_ui_url_loader_factory.h"
  280. #include "content/public/browser/webui_config_map.h"
  281. #include "content/public/common/content_descriptors.h"
  282. #include "content/public/common/content_features.h"
  283. #include "content/public/common/content_switches.h"
  284. #include "content/public/common/url_constants.h"
  285. #include "content/public/common/window_container_type.mojom-shared.h"
  286. #include "device/vr/buildflags/buildflags.h"
  287. #include "extensions/buildflags/buildflags.h"
  288. #include "google_apis/gaia/gaia_urls.h"
  289. #include "google_apis/google_api_keys.h"
  290. #include "gpu/config/gpu_switches.h"
  291. #include "media/base/media_switches.h"
  292. #include "media/media_buildflags.h"
  293. #include "media/mojo/buildflags.h"
  294. #include "mojo/public/cpp/bindings/remote.h"
  295. #include "net/base/features.h"
  296. #include "net/cookies/site_for_cookies.h"
  297. #include "net/ssl/client_cert_store.h"
  298. #include "net/ssl/ssl_cert_request_info.h"
  299. #include "net/ssl/ssl_private_key.h"
  300. #include "pdf/buildflags.h"
  301. #include "ppapi/buildflags/buildflags.h"
  302. #include "printing/buildflags/buildflags.h"
  303. #include "sandbox/policy/mojom/sandbox.mojom.h"
  304. #include "sandbox/policy/switches.h"
  305. #include "services/metrics/public/cpp/ukm_source_id.h"
  306. #include "services/network/public/cpp/is_potentially_trustworthy.h"
  307. #include "services/network/public/cpp/network_switches.h"
  308. #include "services/network/public/cpp/resource_request.h"
  309. #include "services/network/public/cpp/self_deleting_url_loader_factory.h"
  310. #include "services/network/public/cpp/web_sandbox_flags.h"
  311. #include "services/network/public/mojom/web_transport.mojom.h"
  312. #include "third_party/blink/public/common/features.h"
  313. #include "third_party/blink/public/common/loader/url_loader_throttle.h"
  314. #include "third_party/blink/public/common/navigation/navigation_policy.h"
  315. #include "third_party/blink/public/common/permissions/permission_utils.h"
  316. #include "third_party/blink/public/common/permissions_policy/permissions_policy.h"
  317. #include "third_party/blink/public/common/switches.h"
  318. #include "third_party/blink/public/mojom/browsing_topics/browsing_topics.mojom.h"
  319. #include "third_party/blink/public/public_buildflags.h"
  320. #include "third_party/widevine/cdm/buildflags.h"
  321. #include "ui/base/clipboard/clipboard_format_type.h"
  322. #include "ui/base/l10n/l10n_util.h"
  323. #include "ui/base/page_transition_types.h"
  324. #include "ui/base/resource/resource_bundle.h"
  325. #include "ui/native_theme/native_theme.h"
  326. #include "url/gurl.h"
  327. #include "url/origin.h"
  328. #include "url/third_party/mozilla/url_parse.h"
  329. #include "url/url_constants.h"
  330. #if BUILDFLAG(IS_WIN)
  331. #include "base/files/file_util.h"
  332. #include "base/strings/string_tokenizer.h"
  333. #include "base/win/win_util.h"
  334. #include "base/win/windows_version.h"
  335. #include "chrome/browser/chrome_browser_main_win.h"
  336. #include "chrome/browser/lifetime/application_lifetime.h"
  337. #include "chrome/install_static/install_util.h"
  338. #include "chrome/services/util_win/public/mojom/util_win.mojom.h"
  339. #include "sandbox/win/src/sandbox_policy.h"
  340. #elif BUILDFLAG(IS_MAC)
  341. #include "chrome/browser/browser_process_platform_part_mac.h"
  342. #include "chrome/browser/chrome_browser_main_mac.h"
  343. #include "chrome/browser/mac/auth_session_request.h"
  344. #include "chrome/browser/mac/chrome_browser_main_extra_parts_mac.h"
  345. #include "components/soda/constants.h"
  346. #include "sandbox/mac/seatbelt_exec.h"
  347. #include "sandbox/policy/mac/params.h"
  348. #include "sandbox/policy/mac/sandbox_mac.h"
  349. #elif BUILDFLAG(IS_CHROMEOS_ASH)
  350. #include "ash/constants/ash_pref_names.h"
  351. #include "ash/constants/ash_switches.h"
  352. #include "ash/public/cpp/new_window_delegate.h"
  353. #include "ash/public/cpp/tablet_mode.h"
  354. #include "ash/webui/camera_app_ui/url_constants.h"
  355. #include "ash/webui/scanning/url_constants.h"
  356. #include "chrome/app/chrome_crash_reporter_client.h"
  357. #include "chrome/browser/ash/arc/fileapi/arc_content_file_system_backend_delegate.h"
  358. #include "chrome/browser/ash/arc/fileapi/arc_documents_provider_backend_delegate.h"
  359. #include "chrome/browser/ash/chrome_browser_main_parts_ash.h"
  360. #include "chrome/browser/ash/drive/fileapi/drivefs_file_system_backend_delegate.h"
  361. #include "chrome/browser/ash/file_manager/app_id.h"
  362. #include "chrome/browser/ash/file_system_provider/fileapi/backend_delegate.h"
  363. #include "chrome/browser/ash/login/signin/merge_session_navigation_throttle.h"
  364. #include "chrome/browser/ash/login/signin/merge_session_throttling_utils.h"
  365. #include "chrome/browser/ash/login/signin_partition_manager.h"
  366. #include "chrome/browser/ash/login/startup_utils.h"
  367. #include "chrome/browser/ash/net/system_proxy_manager.h"
  368. #include "chrome/browser/ash/profiles/profile_helper.h"
  369. #include "chrome/browser/ash/smb_client/fileapi/smbfs_file_system_backend_delegate.h"
  370. #include "chrome/browser/ash/system/input_device_settings.h"
  371. #include "chrome/browser/ash/system_extensions/system_extensions_profile_utils.h"
  372. #include "chrome/browser/ash/system_extensions/system_extensions_provider.h"
  373. #include "chrome/browser/chromeos/fileapi/external_file_url_loader_factory.h"
  374. #include "chrome/browser/chromeos/fileapi/file_system_backend.h"
  375. #include "chrome/browser/chromeos/fileapi/mtp_file_system_backend_delegate.h"
  376. #include "chrome/browser/speech/tts_chromeos.h"
  377. #include "chrome/browser/ui/ash/chrome_browser_main_extra_parts_ash.h"
  378. #include "chrome/browser/ui/browser_dialogs.h"
  379. #include "chromeos/crosapi/cpp/lacros_startup_state.h"
  380. #include "components/crash/core/app/breakpad_linux.h"
  381. #include "components/user_manager/user.h"
  382. #include "components/user_manager/user_manager.h"
  383. #include "services/service_manager/public/mojom/interface_provider_spec.mojom.h"
  384. #include "storage/browser/file_system/external_mount_points.h"
  385. #elif BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS_LACROS)
  386. #include "chrome/browser/chrome_browser_main_linux.h"
  387. #elif BUILDFLAG(IS_ANDROID)
  388. #include "base/android/application_status_listener.h"
  389. #include "base/android/build_info.h"
  390. #include "base/feature_list.h"
  391. #include "chrome/android/features/dev_ui/buildflags.h"
  392. #include "chrome/browser/android/customtabs/client_data_header_web_contents_observer.h"
  393. #include "chrome/browser/android/devtools_manager_delegate_android.h"
  394. #include "chrome/browser/android/ntp/new_tab_page_url_handler.h"
  395. #include "chrome/browser/android/service_tab_launcher.h"
  396. #include "chrome/browser/android/tab_android.h"
  397. #include "chrome/browser/android/tab_web_contents_delegate_android.h"
  398. #include "chrome/browser/chrome_browser_main_android.h"
  399. #include "chrome/browser/download/android/available_offline_content_provider.h"
  400. #include "chrome/browser/download/android/intercept_oma_download_navigation_throttle.h"
  401. #include "chrome/browser/flags/android/chrome_feature_list.h"
  402. #include "chrome/browser/ui/android/tab_model/tab_model_list.h"
  403. #include "chrome/common/chrome_descriptors.h"
  404. #include "components/autofill_assistant/content/common/switches.h"
  405. #include "components/browser_ui/accessibility/android/font_size_prefs_android.h"
  406. #include "components/cdm/browser/cdm_message_filter_android.h"
  407. #include "components/crash/content/browser/child_exit_observer_android.h"
  408. #include "components/crash/content/browser/crash_memory_metrics_collector_android.h"
  409. #include "components/navigation_interception/intercept_navigation_delegate.h"
  410. #include "components/viz/common/features.h"
  411. #include "components/viz/common/viz_utils.h"
  412. #include "content/public/browser/android/java_interfaces.h"
  413. #include "services/service_manager/public/cpp/interface_provider.h"
  414. #include "ui/base/resource/resource_bundle_android.h"
  415. #include "ui/base/ui_base_paths.h"
  416. #include "ui/display/util/display_util.h"
  417. #if BUILDFLAG(DFMIFY_DEV_UI)
  418. #include "chrome/browser/dev_ui/android/dev_ui_loader_throttle.h"
  419. #endif // BUILDFLAG(DFMIFY_DEV_UI)
  420. #elif BUILDFLAG(IS_POSIX)
  421. #include "chrome/browser/chrome_browser_main_posix.h"
  422. #elif BUILDFLAG(IS_FUCHSIA)
  423. #include "chrome/browser/fuchsia/chrome_browser_main_parts_fuchsia.h"
  424. #endif
  425. #if !BUILDFLAG(IS_CHROMEOS_ASH)
  426. #include "ui/accessibility/accessibility_features.h"
  427. #endif // !BUILDFLAG(IS_CHROMEOS_ASH)
  428. #if BUILDFLAG(IS_CHROMEOS)
  429. #include "chrome/browser/chromeos/policy/dlp/dlp_scoped_file_access_delegate.h"
  430. #include "chrome/browser/chromeos/tablet_mode/chrome_content_browser_client_tablet_mode_part.h"
  431. #include "chrome/browser/policy/networking/policy_cert_service.h"
  432. #include "chrome/browser/policy/networking/policy_cert_service_factory.h"
  433. #include "chrome/common/chromeos/extensions/chromeos_system_extension_info.h"
  434. #include "third_party/cros_system_api/switches/chrome_switches.h"
  435. #endif
  436. #if !BUILDFLAG(IS_ANDROID)
  437. #include "chrome/browser/devtools/chrome_devtools_manager_delegate.h"
  438. #include "chrome/browser/devtools/devtools_window.h"
  439. #include "chrome/browser/media/unified_autoplay_config.h"
  440. #include "chrome/browser/new_tab_page/new_tab_page_util.h"
  441. #include "chrome/browser/page_info/about_this_site_side_panel_throttle.h"
  442. #include "chrome/browser/search/instant_service.h"
  443. #include "chrome/browser/search/instant_service_factory.h"
  444. #include "chrome/browser/serial/chrome_serial_delegate.h"
  445. #include "chrome/browser/task_manager/task_manager_interface.h"
  446. #include "chrome/browser/ui/browser.h"
  447. #include "chrome/browser/ui/browser_dialogs.h"
  448. #include "chrome/browser/ui/browser_finder.h"
  449. #include "chrome/browser/ui/search/new_tab_page_navigation_throttle.h"
  450. #include "chrome/browser/web_applications/policy/web_app_policy_manager.h"
  451. #include "chrome/browser/web_applications/web_app_helpers.h"
  452. #include "chrome/browser/web_applications/web_app_provider.h"
  453. #include "chrome/browser/web_applications/web_app_registrar.h"
  454. #include "chrome/browser/webauthn/authenticator_request_scheduler.h"
  455. #include "chrome/browser/webauthn/chrome_authenticator_request_delegate.h"
  456. #include "chrome/grit/chrome_unscaled_resources.h" // nogncheck crbug.com/1125897
  457. #include "components/commerce/core/commerce_feature_list.h"
  458. #include "third_party/blink/public/mojom/permissions_policy/permissions_policy_feature.mojom.h"
  459. #endif // !BUILDFLAG(IS_ANDROID)
  460. // TODO(crbug.com/1052397): Revisit the macro expression once build flag switch
  461. // of lacros-chrome is complete.
  462. #if BUILDFLAG(IS_WIN) || BUILDFLAG(IS_MAC) || \
  463. (BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS_LACROS))
  464. #include "chrome/browser/browser_switcher/browser_switcher_navigation_throttle.h"
  465. #endif
  466. #if BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS)
  467. #include "components/crash/core/app/crash_switches.h"
  468. #include "components/crash/core/app/crashpad.h"
  469. #endif
  470. #if BUILDFLAG(IS_POSIX) && !BUILDFLAG(IS_MAC)
  471. #if !BUILDFLAG(IS_ANDROID)
  472. #include "base/debug/leak_annotations.h"
  473. #include "components/crash/core/app/breakpad_linux.h"
  474. #endif // !BUILDFLAG(IS_ANDROID)
  475. #include "components/crash/content/browser/crash_handler_host_linux.h"
  476. #endif
  477. #if BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_MAC) || BUILDFLAG(IS_WIN)
  478. #include "chrome/browser/ui/webui/app_settings/web_app_settings_navigation_throttle.h"
  479. #endif
  480. #if BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_MAC) || BUILDFLAG(IS_WIN) || \
  481. BUILDFLAG(IS_CHROMEOS_ASH)
  482. #include "chrome/browser/enterprise/connectors/device_trust/navigation_throttle.h"
  483. #endif // BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_MAC) || BUILDFLAG(IS_WIN) ||
  484. // BUILDFLAG(IS_CHROMEOS_ASH)
  485. // TODO(crbug.com/939205): Once the upcoming App Service is available, use a
  486. // single navigation throttle to display the intent picker on all platforms.
  487. #if !BUILDFLAG(IS_ANDROID)
  488. #if BUILDFLAG(IS_CHROMEOS)
  489. #include "chrome/browser/apps/intent_helper/common_apps_navigation_throttle.h"
  490. #include "chrome/browser/policy/system_features_disable_list_policy_handler.h"
  491. #else
  492. #include "chrome/browser/apps/intent_helper/apps_navigation_throttle.h"
  493. #endif
  494. #endif
  495. #if defined(TOOLKIT_VIEWS)
  496. #include "chrome/browser/ui/side_search/side_search_side_contents_helper.h"
  497. #include "chrome/browser/ui/side_search/side_search_utils.h"
  498. #include "chrome/browser/ui/views/chrome_browser_main_extra_parts_views.h"
  499. #endif
  500. // TODO(crbug.com/1052397): Revisit the macro expression once build flag switch
  501. // of lacros-chrome is complete.
  502. #if BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS_LACROS)
  503. #include "chrome/browser/ui/views/chrome_browser_main_extra_parts_views_linux.h"
  504. #endif
  505. #if BUILDFLAG(IS_LINUX)
  506. #include "chrome/browser/chrome_browser_main_extra_parts_linux.h"
  507. #elif defined(USE_OZONE)
  508. #include "chrome/browser/chrome_browser_main_extra_parts_ozone.h"
  509. #endif
  510. #if BUILDFLAG(ENABLE_CAPTIVE_PORTAL_DETECTION)
  511. #include "components/captive_portal/content/captive_portal_tab_helper.h"
  512. #include "components/captive_portal/content/captive_portal_url_loader_throttle.h"
  513. #endif
  514. #if BUILDFLAG(ENABLE_NACL)
  515. #include "components/nacl/browser/nacl_host_message_filter.h"
  516. #include "components/nacl/browser/nacl_process_host.h"
  517. #include "components/nacl/common/nacl_process_type.h"
  518. #include "components/nacl/common/nacl_switches.h"
  519. #endif
  520. #if BUILDFLAG(ENABLE_EXTENSIONS)
  521. #include "chrome/browser/accessibility/animation_policy_prefs.h"
  522. #include "chrome/browser/apps/platform_apps/platform_app_navigation_redirector.h"
  523. #include "chrome/browser/extensions/chrome_content_browser_client_extensions_part.h"
  524. #include "chrome/browser/extensions/chrome_extension_web_contents_observer.h"
  525. #include "chrome/browser/extensions/extension_util.h"
  526. #include "chrome/browser/extensions/user_script_listener.h"
  527. #include "chrome/browser/speech/extension_api/tts_engine_extension_api.h"
  528. #include "chrome/browser/ui/web_applications/app_browser_controller.h"
  529. #include "chrome/browser/web_applications/isolation_prefs_utils.h"
  530. #include "chrome/browser/web_applications/web_app_utils.h"
  531. #include "content/public/browser/site_isolation_policy.h"
  532. #include "extensions/browser/api/web_request/web_request_api.h"
  533. #include "extensions/browser/api/web_request/web_request_proxying_webtransport.h"
  534. #include "extensions/browser/content_script_tracker.h"
  535. #include "extensions/browser/extension_navigation_throttle.h"
  536. #include "extensions/browser/extension_protocols.h"
  537. #include "extensions/browser/extension_registry.h"
  538. #include "extensions/browser/extension_util.h"
  539. #include "extensions/browser/guest_view/web_view/web_view_guest.h"
  540. #include "extensions/browser/guest_view/web_view/web_view_permission_helper.h"
  541. #include "extensions/browser/guest_view/web_view/web_view_renderer_state.h"
  542. #include "extensions/browser/process_map.h"
  543. #include "extensions/common/constants.h"
  544. #include "extensions/common/extension.h"
  545. #include "extensions/common/extension_set.h"
  546. #include "extensions/common/manifest_handlers/background_info.h"
  547. #include "extensions/common/permissions/permissions_data.h"
  548. #include "extensions/common/switches.h"
  549. #endif // BUILDFLAG(ENABLE_EXTENSIONS)
  550. #if BUILDFLAG(ENABLE_PLUGINS)
  551. #include "chrome/browser/plugins/chrome_content_browser_client_plugins_part.h"
  552. #include "chrome/browser/plugins/plugin_response_interceptor_url_loader_throttle.h"
  553. #endif
  554. #if BUILDFLAG(ENABLE_PDF)
  555. #include "chrome/browser/pdf/chrome_pdf_stream_delegate.h"
  556. #include "components/pdf/browser/pdf_navigation_throttle.h"
  557. #include "components/pdf/browser/pdf_url_loader_request_interceptor.h"
  558. #include "components/pdf/common/internal_plugin_helpers.h"
  559. #endif // BUILDFLAG(ENABLE_PDF)
  560. #if BUILDFLAG(ENABLE_SUPERVISED_USERS)
  561. #include "chrome/browser/supervised_user/supervised_user_google_auth_navigation_throttle.h"
  562. #endif
  563. #if BUILDFLAG(IS_CHROMEOS_ASH)
  564. #include "chrome/browser/chromeos/app_mode/kiosk_settings_navigation_throttle.h"
  565. #include "chrome/browser/speech/tts_controller_delegate_impl.h"
  566. #endif // BUILDFLAG(IS_CHROMEOS_ASH)
  567. #if BUILDFLAG(ENABLE_MEDIA_REMOTING)
  568. #include "chrome/browser/media/cast_remoting_connector.h"
  569. #endif
  570. #if BUILDFLAG(ENABLE_SUPERVISED_USERS)
  571. #include "chrome/browser/supervised_user/supervised_user_navigation_throttle.h"
  572. #endif
  573. #if BUILDFLAG(SAFE_BROWSING_AVAILABLE)
  574. #include "chrome/browser/safe_browsing/chrome_password_protection_service.h"
  575. #endif
  576. #if BUILDFLAG(SAFE_BROWSING_DB_LOCAL)
  577. #include "chrome/browser/safe_browsing/chrome_enterprise_url_lookup_service.h" // nogncheck crbug.com/1125897
  578. #include "chrome/browser/safe_browsing/chrome_enterprise_url_lookup_service_factory.h" // nogncheck crbug.com/1125897
  579. #endif
  580. #if BUILDFLAG(ENABLE_OFFLINE_PAGES)
  581. #include "chrome/browser/offline_pages/offline_page_navigation_throttle.h"
  582. #include "chrome/browser/offline_pages/offline_page_tab_helper.h"
  583. #include "chrome/browser/offline_pages/offline_page_url_loader_request_interceptor.h"
  584. #endif
  585. #if BUILDFLAG(ENABLE_WEBUI_TAB_STRIP)
  586. #include "chrome/browser/ui/webui/tab_strip/chrome_content_browser_client_tab_strip_part.h"
  587. #endif
  588. #if BUILDFLAG(FULL_SAFE_BROWSING)
  589. #include "chrome/browser/enterprise/connectors/analysis/content_analysis_delegate.h"
  590. #endif
  591. #if BUILDFLAG(ENABLE_VR)
  592. #include "chrome/browser/vr/chrome_xr_integration_client.h"
  593. #endif
  594. #if BUILDFLAG(IS_CHROMEOS_LACROS)
  595. #include "chrome/browser/chrome_browser_main_parts_lacros.h"
  596. #include "chrome/browser/lacros/chrome_browser_main_extra_parts_lacros.h"
  597. #include "chrome/browser/speech/tts_lacros.h"
  598. #include "chrome/browser/ui/views/chrome_browser_main_extra_parts_views_lacros.h"
  599. #include "chromeos/constants/chromeos_features.h"
  600. #include "chromeos/lacros/lacros_service.h"
  601. #include "ui/base/ui_base_switches.h"
  602. #endif
  603. #if BUILDFLAG(USE_MINIKIN_HYPHENATION) && !BUILDFLAG(IS_ANDROID)
  604. #include "chrome/browser/component_updater/hyphenation_component_installer.h"
  605. #endif
  606. // This should be after all other #includes.
  607. #if defined(_WINDOWS_) // Detect whether windows.h was included.
  608. #include "base/win/windows_h_disallowed.h"
  609. #endif // defined(_WINDOWS_)
  610. #if BUILDFLAG(ENABLE_SCREEN_AI_SERVICE)
  611. #include "components/services/screen_ai/public/cpp/utilities.h"
  612. #endif
  613. using blink::mojom::EffectiveConnectionType;
  614. using blink::web_pref::WebPreferences;
  615. using content::BrowserThread;
  616. using content::BrowserURLHandler;
  617. using content::ChildProcessSecurityPolicy;
  618. using content::QuotaPermissionContext;
  619. using content::RenderFrameHost;
  620. using content::SiteInstance;
  621. using content::WebContents;
  622. #if BUILDFLAG(IS_POSIX)
  623. using content::PosixFileDescriptorInfo;
  624. #endif
  625. #if BUILDFLAG(ENABLE_EXTENSIONS)
  626. using extensions::APIPermission;
  627. using extensions::ChromeContentBrowserClientExtensionsPart;
  628. using extensions::Extension;
  629. using extensions::Manifest;
  630. using extensions::mojom::APIPermissionID;
  631. #endif
  632. #if BUILDFLAG(ENABLE_PLUGINS)
  633. using plugins::ChromeContentBrowserClientPluginsPart;
  634. #endif
  635. namespace {
  636. #if BUILDFLAG(IS_WIN) && !defined(COMPONENT_BUILD) && \
  637. !defined(ADDRESS_SANITIZER)
  638. // Enables pre-launch Code Integrity Guard (CIG) for Chrome renderers, when
  639. // running on Windows 10 1511 and above. See
  640. // https://blogs.windows.com/blog/tag/code-integrity-guard/.
  641. const base::Feature kRendererCodeIntegrity{"RendererCodeIntegrity",
  642. base::FEATURE_ENABLED_BY_DEFAULT};
  643. // Enables pre-launch Code Integrity Guard (CIG) for Chrome network service
  644. // process, when running on Windows 10 1511 and above. This has no effect if
  645. // NetworkServiceSandbox feature is disabled. See
  646. // https://blogs.windows.com/blog/tag/code-integrity-guard/.
  647. const base::Feature kNetworkServiceCodeIntegrity{
  648. "NetworkServiceCodeIntegrity", base::FEATURE_DISABLED_BY_DEFAULT};
  649. #endif // BUILDFLAG(IS_WIN) && !defined(COMPONENT_BUILD) &&
  650. // !defined(ADDRESS_SANITIZER)
  651. #if BUILDFLAG(IS_ANDROID)
  652. // Kill switch that allows falling back to the legacy behavior on Android when
  653. // it comes to site isolation for Gaia's origin (|GaiaUrls::gaia_origin()|).
  654. const base::Feature kAllowGaiaOriginIsolationOnAndroid{
  655. "AllowGaiaOriginIsolationOnAndroid", base::FEATURE_ENABLED_BY_DEFAULT};
  656. #endif // BUILDFLAG(IS_ANDROID)
  657. // A small ChromeBrowserMainExtraParts that invokes a callback when threads are
  658. // ready. Used to initialize ChromeContentBrowserClient data that needs the UI
  659. // thread.
  660. class ChromeBrowserMainExtraPartsThreadNotifier final
  661. : public ChromeBrowserMainExtraParts {
  662. public:
  663. explicit ChromeBrowserMainExtraPartsThreadNotifier(
  664. base::OnceClosure threads_ready_closure)
  665. : threads_ready_closure_(std::move(threads_ready_closure)) {}
  666. // ChromeBrowserMainExtraParts:
  667. void PostCreateThreads() final { std::move(threads_ready_closure_).Run(); }
  668. private:
  669. base::OnceClosure threads_ready_closure_;
  670. };
  671. bool IsSSLErrorOverrideAllowedForOrigin(const GURL& request_url,
  672. PrefService* prefs) {
  673. DCHECK(request_url.SchemeIsCryptographic());
  674. if (prefs->GetBoolean(prefs::kSSLErrorOverrideAllowed))
  675. return true;
  676. const base::Value::List& allow_list_urls =
  677. prefs->GetValueList(prefs::kSSLErrorOverrideAllowedForOrigins);
  678. if (allow_list_urls.empty())
  679. return false;
  680. for (auto const& value : allow_list_urls) {
  681. ContentSettingsPattern pattern =
  682. ContentSettingsPattern::FromString(value.GetString());
  683. if (pattern == ContentSettingsPattern::Wildcard() || !pattern.IsValid())
  684. continue;
  685. // Despite |request_url| being a GURL, the path is ignored when matching.
  686. if (pattern.Matches(request_url))
  687. return true;
  688. }
  689. return false;
  690. }
  691. // Wrapper for SSLErrorHandler::HandleSSLError() that supplies //chrome-level
  692. // parameters.
  693. void HandleSSLErrorWrapper(
  694. content::WebContents* web_contents,
  695. int cert_error,
  696. const net::SSLInfo& ssl_info,
  697. const GURL& request_url,
  698. std::unique_ptr<SSLCertReporter> ssl_cert_reporter,
  699. SSLErrorHandler::BlockingPageReadyCallback blocking_page_ready_callback) {
  700. Profile* profile =
  701. Profile::FromBrowserContext(web_contents->GetBrowserContext());
  702. // Profile should always outlive a WebContents
  703. DCHECK(profile);
  704. captive_portal::CaptivePortalService* captive_portal_service = nullptr;
  705. #if BUILDFLAG(ENABLE_CAPTIVE_PORTAL_DETECTION)
  706. captive_portal_service = CaptivePortalServiceFactory::GetForProfile(profile);
  707. #endif
  708. SSLErrorHandler::HandleSSLError(
  709. web_contents, cert_error, ssl_info, request_url,
  710. std::move(ssl_cert_reporter), std::move(blocking_page_ready_callback),
  711. g_browser_process->network_time_tracker(), captive_portal_service,
  712. std::make_unique<ChromeSecurityBlockingPageFactory>(),
  713. IsSSLErrorOverrideAllowedForOrigin(request_url, profile->GetPrefs()));
  714. }
  715. enum AppLoadedInTabSource {
  716. // A platform app page tried to load one of its own URLs in a tab.
  717. APP_LOADED_IN_TAB_SOURCE_APP = 0,
  718. // A platform app background page tried to load one of its own URLs in a tab.
  719. APP_LOADED_IN_TAB_SOURCE_BACKGROUND_PAGE,
  720. // An extension or app tried to load a resource of a different platform app in
  721. // a tab.
  722. APP_LOADED_IN_TAB_SOURCE_OTHER_EXTENSION,
  723. // A non-app and non-extension page tried to load a platform app in a tab.
  724. APP_LOADED_IN_TAB_SOURCE_OTHER,
  725. APP_LOADED_IN_TAB_SOURCE_MAX
  726. };
  727. // Cached version of the locale so we can return the locale on the I/O
  728. // thread.
  729. std::string& GetIOThreadApplicationLocale() {
  730. static base::NoDestructor<std::string> s;
  731. return *s;
  732. }
  733. // Returns a copy of the given url with its host set to given host and path set
  734. // to given path. Other parts of the url will be the same.
  735. GURL ReplaceURLHostAndPath(const GURL& url,
  736. const std::string& host,
  737. const std::string& path) {
  738. GURL::Replacements replacements;
  739. replacements.SetHostStr(host);
  740. replacements.SetPathStr(path);
  741. return url.ReplaceComponents(replacements);
  742. }
  743. // Handles the rewriting of the new tab page URL based on group policy.
  744. bool HandleNewTabPageLocationOverride(
  745. GURL* url,
  746. content::BrowserContext* browser_context) {
  747. if (!url->SchemeIs(content::kChromeUIScheme) ||
  748. url->host() != chrome::kChromeUINewTabHost) {
  749. return false;
  750. }
  751. Profile* profile = Profile::FromBrowserContext(browser_context);
  752. // Don't change the URL when incognito mode.
  753. if (profile->IsOffTheRecord())
  754. return false;
  755. std::string ntp_location =
  756. profile->GetPrefs()->GetString(prefs::kNewTabPageLocationOverride);
  757. if (ntp_location.empty())
  758. return false;
  759. url::Component scheme;
  760. if (!url::ExtractScheme(ntp_location.data(),
  761. static_cast<int>(ntp_location.length()), &scheme)) {
  762. ntp_location = base::StrCat(
  763. {url::kHttpsScheme, url::kStandardSchemeSeparator, ntp_location});
  764. }
  765. *url = GURL(ntp_location);
  766. return true;
  767. }
  768. #if !BUILDFLAG(IS_ANDROID)
  769. // Check if the current url is allowlisted based on a list of allowlisted urls.
  770. bool IsURLAllowlisted(const GURL& current_url,
  771. const base::Value::List& allowlisted_urls) {
  772. // Only check on HTTP and HTTPS pages.
  773. if (!current_url.SchemeIsHTTPOrHTTPS())
  774. return false;
  775. for (auto const& value : allowlisted_urls) {
  776. ContentSettingsPattern pattern =
  777. ContentSettingsPattern::FromString(value.GetString());
  778. if (pattern == ContentSettingsPattern::Wildcard() || !pattern.IsValid())
  779. continue;
  780. if (pattern.Matches(current_url))
  781. return true;
  782. }
  783. return false;
  784. }
  785. // Check if autoplay is allowed by policy configuration.
  786. bool IsAutoplayAllowedByPolicy(content::WebContents* contents,
  787. PrefService* prefs) {
  788. DCHECK(prefs);
  789. // Check if we have globally allowed autoplay by policy.
  790. if (prefs->GetBoolean(prefs::kAutoplayAllowed) &&
  791. prefs->IsManagedPreference(prefs::kAutoplayAllowed)) {
  792. return true;
  793. }
  794. if (!contents)
  795. return false;
  796. // Check if the current URL matches a URL pattern on the allowlist.
  797. const base::Value::List& autoplay_allowlist =
  798. prefs->GetValueList(prefs::kAutoplayAllowlist);
  799. return prefs->IsManagedPreference(prefs::kAutoplayAllowlist) &&
  800. IsURLAllowlisted(contents->GetURL(), autoplay_allowlist);
  801. }
  802. #endif
  803. blink::mojom::AutoplayPolicy GetAutoplayPolicyForWebContents(
  804. WebContents* web_contents) {
  805. const base::CommandLine& command_line =
  806. *base::CommandLine::ForCurrentProcess();
  807. std::string autoplay_policy = media::GetEffectiveAutoplayPolicy(command_line);
  808. auto result = blink::mojom::AutoplayPolicy::kDocumentUserActivationRequired;
  809. if (autoplay_policy == switches::autoplay::kNoUserGestureRequiredPolicy) {
  810. result = blink::mojom::AutoplayPolicy::kNoUserGestureRequired;
  811. } else if (autoplay_policy ==
  812. switches::autoplay::kUserGestureRequiredPolicy) {
  813. result = blink::mojom::AutoplayPolicy::kUserGestureRequired;
  814. } else if (autoplay_policy ==
  815. switches::autoplay::kDocumentUserActivationRequiredPolicy) {
  816. result = blink::mojom::AutoplayPolicy::kDocumentUserActivationRequired;
  817. } else {
  818. NOTREACHED();
  819. }
  820. #if !BUILDFLAG(IS_ANDROID)
  821. Profile* profile =
  822. Profile::FromBrowserContext(web_contents->GetBrowserContext());
  823. PrefService* prefs = profile->GetPrefs();
  824. // Override autoplay policy used in internal switch in case of enabling
  825. // features such as policy, allowlisting or disabling from settings.
  826. if (IsAutoplayAllowedByPolicy(web_contents, prefs)) {
  827. result = blink::mojom::AutoplayPolicy::kNoUserGestureRequired;
  828. } else if (base::FeatureList::IsEnabled(media::kAutoplayDisableSettings) &&
  829. result == blink::mojom::AutoplayPolicy::
  830. kDocumentUserActivationRequired) {
  831. result = UnifiedAutoplayConfig::ShouldBlockAutoplay(profile)
  832. ? blink::mojom::AutoplayPolicy::kDocumentUserActivationRequired
  833. : blink::mojom::AutoplayPolicy::kNoUserGestureRequired;
  834. } else if (web_contents->GetPrimaryMainFrame()->IsFeatureEnabled(
  835. blink::mojom::PermissionsPolicyFeature::kAutoplay) &&
  836. IsAutoplayAllowedByPolicy(web_contents->GetOuterWebContents(),
  837. prefs)) {
  838. // If the domain policy allows autoplay and has delegated that to an iframe,
  839. // allow autoplay within the iframe. Only allow a nesting of single depth.
  840. result = blink::mojom::AutoplayPolicy::kNoUserGestureRequired;
  841. }
  842. #endif // !BUILDFLAG(IS_ANDROID)
  843. return result;
  844. }
  845. #if BUILDFLAG(IS_ANDROID)
  846. int GetCrashSignalFD(const base::CommandLine& command_line) {
  847. return crashpad::CrashHandlerHost::Get()->GetDeathSignalSocket();
  848. }
  849. #elif BUILDFLAG(IS_POSIX) && !BUILDFLAG(IS_MAC)
  850. breakpad::CrashHandlerHostLinux* CreateCrashHandlerHost(
  851. const std::string& process_type) {
  852. base::FilePath dumps_path;
  853. base::PathService::Get(chrome::DIR_CRASH_DUMPS, &dumps_path);
  854. {
  855. ANNOTATE_SCOPED_MEMORY_LEAK;
  856. bool upload = !getenv(env_vars::kHeadless);
  857. breakpad::CrashHandlerHostLinux* crash_handler =
  858. new breakpad::CrashHandlerHostLinux(process_type, dumps_path, upload);
  859. crash_handler->StartUploaderThread();
  860. return crash_handler;
  861. }
  862. }
  863. int GetCrashSignalFD(const base::CommandLine& command_line) {
  864. if (crash_reporter::IsCrashpadEnabled()) {
  865. int fd;
  866. pid_t pid;
  867. return crash_reporter::GetHandlerSocket(&fd, &pid) ? fd : -1;
  868. }
  869. // Extensions have the same process type as renderers.
  870. if (command_line.HasSwitch(extensions::switches::kExtensionProcess)) {
  871. static breakpad::CrashHandlerHostLinux* crash_handler = nullptr;
  872. if (!crash_handler)
  873. crash_handler = CreateCrashHandlerHost("extension");
  874. return crash_handler->GetDeathSignalSocket();
  875. }
  876. std::string process_type =
  877. command_line.GetSwitchValueASCII(switches::kProcessType);
  878. if (process_type == switches::kRendererProcess) {
  879. static breakpad::CrashHandlerHostLinux* crash_handler = nullptr;
  880. if (!crash_handler)
  881. crash_handler = CreateCrashHandlerHost(process_type);
  882. return crash_handler->GetDeathSignalSocket();
  883. }
  884. if (process_type == switches::kPpapiPluginProcess) {
  885. static breakpad::CrashHandlerHostLinux* crash_handler = nullptr;
  886. if (!crash_handler)
  887. crash_handler = CreateCrashHandlerHost(process_type);
  888. return crash_handler->GetDeathSignalSocket();
  889. }
  890. if (process_type == switches::kGpuProcess) {
  891. static breakpad::CrashHandlerHostLinux* crash_handler = nullptr;
  892. if (!crash_handler)
  893. crash_handler = CreateCrashHandlerHost(process_type);
  894. return crash_handler->GetDeathSignalSocket();
  895. }
  896. if (process_type == switches::kUtilityProcess) {
  897. static breakpad::CrashHandlerHostLinux* crash_handler = nullptr;
  898. if (!crash_handler)
  899. crash_handler = CreateCrashHandlerHost(process_type);
  900. return crash_handler->GetDeathSignalSocket();
  901. }
  902. return -1;
  903. }
  904. #endif // BUILDFLAG(IS_ANDROID)
  905. void SetApplicationLocaleOnIOThread(const std::string& locale) {
  906. DCHECK_CURRENTLY_ON(BrowserThread::IO);
  907. GetIOThreadApplicationLocale() = locale;
  908. }
  909. // An implementation of the SSLCertReporter interface used by
  910. // SSLErrorHandler. Uses CertificateReportingService to send reports. The
  911. // service handles queueing and re-sending of failed reports. Each certificate
  912. // error creates a new instance of this class.
  913. class CertificateReportingServiceCertReporter : public SSLCertReporter {
  914. public:
  915. explicit CertificateReportingServiceCertReporter(
  916. content::WebContents* web_contents)
  917. : service_(CertificateReportingServiceFactory::GetForBrowserContext(
  918. web_contents->GetBrowserContext())) {}
  919. CertificateReportingServiceCertReporter(
  920. const CertificateReportingServiceCertReporter&) = delete;
  921. CertificateReportingServiceCertReporter& operator=(
  922. const CertificateReportingServiceCertReporter&) = delete;
  923. ~CertificateReportingServiceCertReporter() override {}
  924. // SSLCertReporter implementation
  925. void ReportInvalidCertificateChain(
  926. const std::string& serialized_report) override {
  927. service_->Send(serialized_report);
  928. }
  929. private:
  930. raw_ptr<CertificateReportingService> service_;
  931. };
  932. #if BUILDFLAG(ENABLE_EXTENSIONS)
  933. AppLoadedInTabSource ClassifyAppLoadedInTabSource(
  934. const GURL& opener_url,
  935. const extensions::Extension* target_platform_app) {
  936. if (!opener_url.SchemeIs(extensions::kExtensionScheme)) {
  937. // The forbidden app URL was being opened by a non-extension page (e.g.
  938. // http).
  939. return APP_LOADED_IN_TAB_SOURCE_OTHER;
  940. }
  941. if (opener_url.host_piece() != target_platform_app->id()) {
  942. // The forbidden app URL was being opened by a different app or extension.
  943. return APP_LOADED_IN_TAB_SOURCE_OTHER_EXTENSION;
  944. }
  945. // This platform app was trying to window.open() one of its own URLs.
  946. if (opener_url ==
  947. extensions::BackgroundInfo::GetBackgroundURL(target_platform_app)) {
  948. // Source was the background page.
  949. return APP_LOADED_IN_TAB_SOURCE_BACKGROUND_PAGE;
  950. }
  951. // Source was a different page inside the app.
  952. return APP_LOADED_IN_TAB_SOURCE_APP;
  953. }
  954. // Returns true if there is is an extension matching `url` in
  955. // `render_process_id` with `permission`.
  956. //
  957. // GetExtensionOrAppByURL requires a full URL in order to match with a hosted
  958. // app, even though normal extensions just use the host.
  959. bool URLHasExtensionPermission(extensions::ProcessMap* process_map,
  960. extensions::ExtensionRegistry* registry,
  961. const GURL& url,
  962. int render_process_id,
  963. APIPermissionID permission) {
  964. // Includes web URLs that are part of an extension's web extent.
  965. const Extension* extension =
  966. registry->enabled_extensions().GetExtensionOrAppByURL(url);
  967. return extension &&
  968. extension->permissions_data()->HasAPIPermission(permission) &&
  969. process_map->Contains(extension->id(), render_process_id);
  970. }
  971. #endif
  972. mojo::PendingRemote<prerender::mojom::PrerenderCanceler> GetPrerenderCanceler(
  973. base::OnceCallback<content::WebContents*()> wc_getter) {
  974. mojo::PendingRemote<prerender::mojom::PrerenderCanceler> canceler;
  975. prerender::ChromeNoStatePrefetchContentsDelegate::FromWebContents(
  976. std::move(wc_getter).Run())
  977. ->AddPrerenderCancelerReceiver(canceler.InitWithNewPipeAndPassReceiver());
  978. return canceler;
  979. }
  980. bool ShouldHonorPolicies() {
  981. #if BUILDFLAG(IS_WIN)
  982. return policy::ManagementServiceFactory::GetForPlatform()
  983. ->GetManagementAuthorityTrustworthiness() >=
  984. policy::ManagementAuthorityTrustworthiness::TRUSTED;
  985. #else
  986. return true;
  987. #endif
  988. }
  989. // Used by Enterprise policy. Disable blocking of navigations toward external
  990. // applications from a sandboxed iframe.
  991. // https://chromestatus.com/feature/5680742077038592
  992. const char kDisableSandboxExternalProtocolSwitch[] =
  993. "disable-sandbox-external-protocols";
  994. void LaunchURL(base::WeakPtr<ChromeContentBrowserClient> client,
  995. const GURL& url,
  996. content::WebContents::Getter web_contents_getter,
  997. ui::PageTransition page_transition,
  998. bool is_primary_main_frame,
  999. bool is_in_fenced_frame_tree,
  1000. network::mojom::WebSandboxFlags sandbox_flags,
  1001. bool has_user_gesture,
  1002. const absl::optional<url::Origin>& initiating_origin,
  1003. content::WeakDocumentPtr initiator_document) {
  1004. // If there is no longer a WebContents, the request may have raced with tab
  1005. // closing. Don't fire the external request. (It may have been a prerender.)
  1006. content::WebContents* web_contents = web_contents_getter.Run();
  1007. if (!web_contents)
  1008. return;
  1009. // Do not launch external requests attached to unswapped no-state prefetchers.
  1010. prerender::NoStatePrefetchContents* no_state_prefetch_contents =
  1011. prerender::ChromeNoStatePrefetchContentsDelegate::FromWebContents(
  1012. web_contents);
  1013. if (no_state_prefetch_contents) {
  1014. no_state_prefetch_contents->Destroy(
  1015. prerender::FINAL_STATUS_UNSUPPORTED_SCHEME);
  1016. return;
  1017. }
  1018. // Do not launch external requests for schemes that have a handler registered.
  1019. custom_handlers::ProtocolHandlerRegistry* protocol_handler_registry =
  1020. ProtocolHandlerRegistryFactory::GetForBrowserContext(
  1021. web_contents->GetBrowserContext());
  1022. if (protocol_handler_registry &&
  1023. protocol_handler_registry->IsHandledProtocol(url.scheme()))
  1024. return;
  1025. // Sandbox flags
  1026. // =============
  1027. //
  1028. // Navigations to external protocol in iframe can be seen as "top-level"
  1029. // navigations somehow, because they cause the user to switch from Chrome's
  1030. // page toward a different application.
  1031. //
  1032. // Internally in Chrome, they are seen as aborted iframe navigation, so the
  1033. // regular sandbox logic do not really apply.
  1034. //
  1035. // This block adds an extra logic, gating external protocol in iframes to have
  1036. // one of:
  1037. // - 'allow-top-navigation'
  1038. // - 'allow-top-navigation-to-custom-protocols'
  1039. // - 'allow-top-navigation-by-user-navigation' + user-activation
  1040. // - 'allow-popups'
  1041. //
  1042. // See https://crbug.com/1148777
  1043. if (!is_primary_main_frame) {
  1044. using SandboxFlags = network::mojom::WebSandboxFlags;
  1045. auto allow = [&](SandboxFlags flag) {
  1046. return (sandbox_flags & flag) == SandboxFlags::kNone;
  1047. };
  1048. bool allowed = (allow(SandboxFlags::kTopNavigationToCustomProtocols)) ||
  1049. (allow(SandboxFlags::kTopNavigationByUserActivation) &&
  1050. has_user_gesture);
  1051. if (!allowed) {
  1052. content::RenderFrameHost* rfh = web_contents->GetPrimaryMainFrame();
  1053. if (client) {
  1054. client->LogWebFeatureForCurrentPage(
  1055. rfh, blink::mojom::WebFeature::kExternalProtocolBlockedBySandbox);
  1056. }
  1057. if (!base::CommandLine::ForCurrentProcess()->HasSwitch(
  1058. kDisableSandboxExternalProtocolSwitch)) {
  1059. if (base::FeatureList::IsEnabled(
  1060. features::kSandboxExternalProtocolBlocked)) {
  1061. rfh->AddMessageToConsole(
  1062. blink::mojom::ConsoleMessageLevel::kError,
  1063. "Navigation to external protocol blocked by sandbox, because it "
  1064. "doesn't contain any of: "
  1065. "'allow-top-navigation-to-custom-protocols', "
  1066. "'allow-top-navigation-by-user-activation', "
  1067. "'allow-top-navigation', or "
  1068. "'allow-popups'. See "
  1069. "https://chromestatus.com/feature/5680742077038592 and "
  1070. "https://chromeenterprise.google/policies/"
  1071. "#SandboxExternalProtocolBlocked");
  1072. return;
  1073. }
  1074. if (base::FeatureList::IsEnabled(
  1075. features::kSandboxExternalProtocolBlockedWarning)) {
  1076. rfh->AddMessageToConsole(
  1077. blink::mojom::ConsoleMessageLevel::kError,
  1078. "After Chrome M103, navigation toward external protocol "
  1079. "will be blocked by sandbox, if it doesn't contain any of:"
  1080. "'allow-top-navigation-to-custom-protocols', "
  1081. "'allow-top-navigation-by-user-activation', "
  1082. "'allow-top-navigation', or "
  1083. "'allow-popups'. See "
  1084. "https://chromestatus.com/feature/5680742077038592 and "
  1085. "https://chromeenterprise.google/policies/"
  1086. "#SandboxExternalProtocolBlocked");
  1087. }
  1088. }
  1089. }
  1090. }
  1091. bool is_allowlisted = false;
  1092. PolicyBlocklistService* service =
  1093. PolicyBlocklistFactory::GetForBrowserContext(
  1094. web_contents->GetBrowserContext());
  1095. if (ShouldHonorPolicies() && service) {
  1096. const policy::URLBlocklist::URLBlocklistState url_state =
  1097. service->GetURLBlocklistState(url);
  1098. is_allowlisted =
  1099. url_state == policy::URLBlocklist::URLBlocklistState::URL_IN_ALLOWLIST;
  1100. }
  1101. // If the URL is in allowlist, we launch it without asking the user and
  1102. // without any additional security checks. Since the URL is allowlisted,
  1103. // we assume it can be executed.
  1104. if (is_allowlisted) {
  1105. ExternalProtocolHandler::LaunchUrlWithoutSecurityCheck(
  1106. url, web_contents, std::move(initiator_document));
  1107. } else {
  1108. ExternalProtocolHandler::LaunchUrl(
  1109. url, std::move(web_contents_getter), page_transition, has_user_gesture,
  1110. is_in_fenced_frame_tree, initiating_origin,
  1111. std::move(initiator_document));
  1112. }
  1113. }
  1114. void MaybeAppendSecureOriginsAllowlistSwitch(base::CommandLine* cmdline) {
  1115. // |allowlist| combines pref/policy + cmdline switch in the browser process.
  1116. // For renderer and utility (e.g. NetworkService) processes the switch is the
  1117. // only available source, so below the combined (pref/policy + cmdline)
  1118. // allowlist of secure origins is injected into |cmdline| for these other
  1119. // processes.
  1120. std::vector<std::string> allowlist =
  1121. network::SecureOriginAllowlist::GetInstance().GetCurrentAllowlist();
  1122. if (!allowlist.empty()) {
  1123. cmdline->AppendSwitchASCII(
  1124. network::switches::kUnsafelyTreatInsecureOriginAsSecure,
  1125. base::JoinString(allowlist, ","));
  1126. }
  1127. }
  1128. #if BUILDFLAG(IS_WIN) && !defined(COMPONENT_BUILD) && \
  1129. !defined(ADDRESS_SANITIZER)
  1130. // Returns the full path to |module_name|. Both dev builds (where |module_name|
  1131. // is in the current executable's directory) and proper installs (where
  1132. // |module_name| is in a versioned sub-directory of the current executable's
  1133. // directory) are supported. The identified file is not guaranteed to exist.
  1134. base::FilePath GetModulePath(base::WStringPiece module_name) {
  1135. base::FilePath exe_dir;
  1136. const bool has_path = base::PathService::Get(base::DIR_EXE, &exe_dir);
  1137. DCHECK(has_path);
  1138. // Look for the module in a versioned sub-directory of the current
  1139. // executable's directory and return the path if it can be read. This is the
  1140. // expected location of modules for proper installs.
  1141. const base::FilePath module_path =
  1142. exe_dir.AppendASCII(chrome::kChromeVersion).Append(module_name);
  1143. if (base::PathExists(module_path))
  1144. return module_path;
  1145. // Otherwise, return the path to the module in the current executable's
  1146. // directory. This is the expected location of modules for dev builds.
  1147. return exe_dir.Append(module_name);
  1148. }
  1149. #endif // BUILDFLAG(IS_WIN) && !defined(COMPONENT_BUILD) &&
  1150. // !defined(ADDRESS_SANITIZER)
  1151. void MaybeAddThrottle(
  1152. std::unique_ptr<content::NavigationThrottle> maybe_throttle,
  1153. std::vector<std::unique_ptr<content::NavigationThrottle>>* throttles) {
  1154. if (maybe_throttle)
  1155. throttles->push_back(std::move(maybe_throttle));
  1156. }
  1157. void MaybeAddCondition(
  1158. std::unique_ptr<content::CommitDeferringCondition> maybe_condition,
  1159. std::vector<std::unique_ptr<content::CommitDeferringCondition>>*
  1160. conditions) {
  1161. if (maybe_condition)
  1162. conditions->push_back(std::move(maybe_condition));
  1163. }
  1164. void MaybeAddThrottles(
  1165. std::vector<std::unique_ptr<content::NavigationThrottle>> additional,
  1166. std::vector<std::unique_ptr<content::NavigationThrottle>>* combined) {
  1167. combined->insert(combined->end(), std::make_move_iterator(additional.begin()),
  1168. std::make_move_iterator(additional.end()));
  1169. }
  1170. // Returns whether |web_contents| is within a hosted app.
  1171. bool IsInHostedApp(WebContents* web_contents) {
  1172. #if BUILDFLAG(ENABLE_EXTENSIONS)
  1173. Browser* browser = chrome::FindBrowserWithWebContents(web_contents);
  1174. return web_app::AppBrowserController::IsWebApp(browser);
  1175. #else
  1176. return false;
  1177. #endif
  1178. }
  1179. bool IsErrorPageAutoReloadEnabled() {
  1180. const base::CommandLine& command_line =
  1181. *base::CommandLine::ForCurrentProcess();
  1182. if (command_line.HasSwitch(switches::kEnableAutomation))
  1183. return false;
  1184. if (command_line.HasSwitch(embedder_support::kEnableAutoReload))
  1185. return true;
  1186. if (command_line.HasSwitch(embedder_support::kDisableAutoReload))
  1187. return false;
  1188. return true;
  1189. }
  1190. bool IsTopChromeWebUIURL(const GURL& url) {
  1191. return url.SchemeIs(content::kChromeUIScheme) &&
  1192. base::EndsWith(url.host_piece(), chrome::kChromeUITopChromeDomain);
  1193. }
  1194. bool DoesGaiaOriginRequireDedicatedProcess() {
  1195. #if !BUILDFLAG(IS_ANDROID)
  1196. return true;
  1197. #else
  1198. // Sign-in process isolation is not strictly needed on Android, see
  1199. // https://crbug.com/739418. On Android, it's more optional but it does
  1200. // improve security generally and specifically it allows the exposure of
  1201. // certain optional privileged APIs.
  1202. // Kill switch that falls back to the legacy behavior.
  1203. if (!base::FeatureList::IsEnabled(kAllowGaiaOriginIsolationOnAndroid)) {
  1204. return false;
  1205. }
  1206. if (site_isolation::SiteIsolationPolicy::
  1207. ShouldDisableSiteIsolationDueToMemoryThreshold(
  1208. content::SiteIsolationMode::kPartialSiteIsolation)) {
  1209. // Insufficient memory to isolate Gaia's origin.
  1210. return false;
  1211. }
  1212. return true;
  1213. #endif // !BUILDFLAG(IS_ANDROID)
  1214. }
  1215. } // namespace
  1216. ChromeContentBrowserClient::ChromeContentBrowserClient() {
  1217. #if BUILDFLAG(ENABLE_PLUGINS)
  1218. extra_parts_.push_back(new ChromeContentBrowserClientPluginsPart);
  1219. #endif
  1220. #if BUILDFLAG(IS_CHROMEOS)
  1221. extra_parts_.push_back(new ChromeContentBrowserClientTabletModePart);
  1222. #endif // BUILDFLAG(IS_CHROMEOS)
  1223. #if BUILDFLAG(ENABLE_WEBUI_TAB_STRIP)
  1224. extra_parts_.push_back(new ChromeContentBrowserClientTabStripPart);
  1225. #endif
  1226. #if BUILDFLAG(ENABLE_EXTENSIONS)
  1227. extra_parts_.push_back(new ChromeContentBrowserClientExtensionsPart);
  1228. #endif
  1229. extra_parts_.push_back(new ChromeContentBrowserClientPerformanceManagerPart);
  1230. }
  1231. ChromeContentBrowserClient::~ChromeContentBrowserClient() {
  1232. for (int i = static_cast<int>(extra_parts_.size()) - 1; i >= 0; --i)
  1233. delete extra_parts_[i];
  1234. extra_parts_.clear();
  1235. }
  1236. // static
  1237. void ChromeContentBrowserClient::RegisterLocalStatePrefs(
  1238. PrefRegistrySimple* registry) {
  1239. registry->RegisterFilePathPref(prefs::kDiskCacheDir, base::FilePath());
  1240. registry->RegisterIntegerPref(prefs::kDiskCacheSize, 0);
  1241. registry->RegisterStringPref(prefs::kIsolateOrigins, std::string());
  1242. registry->RegisterBooleanPref(prefs::kSitePerProcess, false);
  1243. registry->RegisterBooleanPref(prefs::kTabFreezingEnabled, true);
  1244. registry->RegisterIntegerPref(prefs::kSCTAuditingHashdanceReportCount, 0);
  1245. }
  1246. // static
  1247. void ChromeContentBrowserClient::RegisterProfilePrefs(
  1248. user_prefs::PrefRegistrySyncable* registry) {
  1249. registry->RegisterBooleanPref(prefs::kDisable3DAPIs, false);
  1250. registry->RegisterBooleanPref(prefs::kEnableHyperlinkAuditing, true);
  1251. // Register user prefs for mapping SitePerProcess and IsolateOrigins in
  1252. // user policy in addition to the same named ones in Local State (which are
  1253. // used for mapping the command-line flags).
  1254. registry->RegisterStringPref(prefs::kIsolateOrigins, std::string());
  1255. registry->RegisterBooleanPref(prefs::kSitePerProcess, false);
  1256. registry->RegisterListPref(
  1257. site_isolation::prefs::kUserTriggeredIsolatedOrigins);
  1258. registry->RegisterDictionaryPref(
  1259. site_isolation::prefs::kWebTriggeredIsolatedOrigins);
  1260. registry->RegisterDictionaryPref(
  1261. prefs::kDevToolsBackgroundServicesExpirationDict);
  1262. registry->RegisterBooleanPref(prefs::kSignedHTTPExchangeEnabled, true);
  1263. #if !BUILDFLAG(IS_ANDROID)
  1264. registry->RegisterBooleanPref(prefs::kAutoplayAllowed, false);
  1265. registry->RegisterListPref(prefs::kAutoplayAllowlist);
  1266. registry->RegisterIntegerPref(prefs::kFetchKeepaliveDurationOnShutdown, 0);
  1267. registry->RegisterBooleanPref(
  1268. prefs::kSharedArrayBufferUnrestrictedAccessAllowed, false);
  1269. #endif
  1270. registry->RegisterBooleanPref(prefs::kSandboxExternalProtocolBlocked, true);
  1271. registry->RegisterBooleanPref(prefs::kDisplayCapturePermissionsPolicyEnabled,
  1272. true);
  1273. registry->RegisterBooleanPref(prefs::kSSLErrorOverrideAllowed, true);
  1274. registry->RegisterListPref(prefs::kSSLErrorOverrideAllowedForOrigins);
  1275. registry->RegisterBooleanPref(
  1276. prefs::kSuppressDifferentOriginSubframeJSDialogs, true);
  1277. registry->RegisterBooleanPref(
  1278. policy::policy_prefs::kSetTimeoutWithout1MsClampEnabled, false);
  1279. registry->RegisterBooleanPref(
  1280. policy::policy_prefs::kUnthrottledNestedTimeoutEnabled, false);
  1281. #if BUILDFLAG(IS_ANDROID)
  1282. registry->RegisterBooleanPref(prefs::kWebXRImmersiveArEnabled, true);
  1283. #endif
  1284. registry->RegisterBooleanPref(prefs::kPromptOnMultipleMatchingCertificates,
  1285. false);
  1286. registry->RegisterBooleanPref(prefs::kCorsNonWildcardRequestHeadersSupport,
  1287. true);
  1288. registry->RegisterDictionaryPref(
  1289. enterprise::content::kCopyPreventionSettings);
  1290. registry->RegisterIntegerPref(
  1291. prefs::kUserAgentReduction,
  1292. static_cast<int>(
  1293. embedder_support::UserAgentReductionEnterprisePolicyState::kDefault));
  1294. registry->RegisterBooleanPref(prefs::kOriginAgentClusterDefaultEnabled, true);
  1295. registry->RegisterIntegerPref(
  1296. prefs::kForceMajorVersionToMinorPositionInUserAgent,
  1297. static_cast<int>(
  1298. embedder_support::ForceMajorVersionToMinorPosition::kDefault));
  1299. registry->RegisterBooleanPref(
  1300. policy::policy_prefs::kIsolatedAppsDeveloperModeAllowed, true);
  1301. // TODO(crbug.com/1277431): Disable it by default in M109.
  1302. registry->RegisterBooleanPref(policy::policy_prefs::kEventPathEnabled, true);
  1303. }
  1304. // static
  1305. void ChromeContentBrowserClient::SetApplicationLocale(
  1306. const std::string& locale) {
  1307. // The common case is that this function is called early in Chrome startup
  1308. // before any threads are created or registered. When there are no threads,
  1309. // we can just set the string without worrying about threadsafety.
  1310. if (!BrowserThread::IsThreadInitialized(BrowserThread::IO)) {
  1311. GetIOThreadApplicationLocale() = locale;
  1312. return;
  1313. }
  1314. // Otherwise we're being called to change the locale. In this case set it on
  1315. // the IO thread.
  1316. DCHECK_CURRENTLY_ON(BrowserThread::UI);
  1317. content::GetIOThreadTaskRunner({})->PostTask(
  1318. FROM_HERE, base::BindOnce(&SetApplicationLocaleOnIOThread, locale));
  1319. }
  1320. std::unique_ptr<content::BrowserMainParts>
  1321. ChromeContentBrowserClient::CreateBrowserMainParts(bool is_integration_test) {
  1322. std::unique_ptr<ChromeBrowserMainParts> main_parts;
  1323. // Construct the Main browser parts based on the OS type.
  1324. #if BUILDFLAG(IS_WIN)
  1325. main_parts = std::make_unique<ChromeBrowserMainPartsWin>(is_integration_test,
  1326. &startup_data_);
  1327. #elif BUILDFLAG(IS_MAC)
  1328. main_parts = std::make_unique<ChromeBrowserMainPartsMac>(is_integration_test,
  1329. &startup_data_);
  1330. #elif BUILDFLAG(IS_CHROMEOS_ASH)
  1331. main_parts = std::make_unique<ash::ChromeBrowserMainPartsAsh>(
  1332. is_integration_test, &startup_data_);
  1333. #elif BUILDFLAG(IS_CHROMEOS_LACROS)
  1334. main_parts = std::make_unique<ChromeBrowserMainPartsLacros>(
  1335. is_integration_test, &startup_data_);
  1336. #elif BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS_LACROS)
  1337. main_parts = std::make_unique<ChromeBrowserMainPartsLinux>(
  1338. is_integration_test, &startup_data_);
  1339. #elif BUILDFLAG(IS_ANDROID)
  1340. main_parts = std::make_unique<ChromeBrowserMainPartsAndroid>(
  1341. is_integration_test, &startup_data_);
  1342. #elif BUILDFLAG(IS_POSIX)
  1343. main_parts = std::make_unique<ChromeBrowserMainPartsPosix>(
  1344. is_integration_test, &startup_data_);
  1345. #elif BUILDFLAG(IS_FUCHSIA)
  1346. main_parts = std::make_unique<ChromeBrowserMainPartsFuchsia>(
  1347. is_integration_test, &startup_data_);
  1348. #else
  1349. NOTREACHED();
  1350. main_parts = std::make_unique<ChromeBrowserMainParts>(is_integration_test,
  1351. &startup_data_);
  1352. #endif
  1353. main_parts->AddParts(
  1354. std::make_unique<ChromeBrowserMainExtraPartsThreadNotifier>(
  1355. base::BindOnce(&ChromeContentBrowserClient::InitOnUIThread,
  1356. weak_factory_.GetWeakPtr())));
  1357. bool add_profiles_extra_parts = true;
  1358. #if BUILDFLAG(IS_ANDROID)
  1359. if (startup_data_.HasBuiltProfilePrefService())
  1360. add_profiles_extra_parts = false;
  1361. #endif
  1362. if (add_profiles_extra_parts)
  1363. chrome::AddProfilesExtraParts(main_parts.get());
  1364. // Construct additional browser parts. Stages are called in the order in
  1365. // which they are added.
  1366. #if defined(TOOLKIT_VIEWS)
  1367. #if BUILDFLAG(IS_CHROMEOS_LACROS)
  1368. main_parts->AddParts(
  1369. std::make_unique<ChromeBrowserMainExtraPartsViewsLacros>());
  1370. // TODO(crbug.com/1052397): Revisit the macro expression once build flag switch
  1371. // of lacros-chrome is complete.
  1372. #elif BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS_LACROS)
  1373. main_parts->AddParts(
  1374. std::make_unique<ChromeBrowserMainExtraPartsViewsLinux>());
  1375. #else
  1376. main_parts->AddParts(std::make_unique<ChromeBrowserMainExtraPartsViews>());
  1377. #endif
  1378. #endif
  1379. #if BUILDFLAG(IS_MAC)
  1380. main_parts->AddParts(std::make_unique<ChromeBrowserMainExtraPartsMac>());
  1381. #endif
  1382. #if BUILDFLAG(IS_CHROMEOS_ASH)
  1383. // TODO(jamescook): Combine with `ChromeBrowserMainPartsAsh`.
  1384. main_parts->AddParts(std::make_unique<ChromeBrowserMainExtraPartsAsh>());
  1385. #endif
  1386. #if BUILDFLAG(IS_CHROMEOS_LACROS)
  1387. main_parts->AddParts(std::make_unique<ChromeBrowserMainExtraPartsLacros>());
  1388. #endif
  1389. #if BUILDFLAG(IS_LINUX)
  1390. main_parts->AddParts(std::make_unique<ChromeBrowserMainExtraPartsLinux>());
  1391. #elif defined(USE_OZONE)
  1392. main_parts->AddParts(std::make_unique<ChromeBrowserMainExtraPartsOzone>());
  1393. #endif
  1394. main_parts->AddParts(
  1395. std::make_unique<ChromeBrowserMainExtraPartsPerformanceMonitor>());
  1396. main_parts->AddParts(
  1397. std::make_unique<ChromeBrowserMainExtraPartsPerformanceManager>());
  1398. main_parts->AddParts(
  1399. std::make_unique<ChromeBrowserMainExtraPartsProfiling>());
  1400. main_parts->AddParts(std::make_unique<ChromeBrowserMainExtraPartsMemory>());
  1401. chrome::AddMetricsExtraParts(main_parts.get());
  1402. // Always add ChromeBrowserMainExtraPartsGpu last to make sure
  1403. // GpuDataManager initialization could pick up about:flags settings.
  1404. main_parts->AddParts(std::make_unique<ChromeBrowserMainExtraPartsGpu>());
  1405. main_parts->AddParts(
  1406. std::make_unique<ChromeBrowserMainExtraPartsSegmentationPlatform>());
  1407. return main_parts;
  1408. }
  1409. void ChromeContentBrowserClient::PostAfterStartupTask(
  1410. const base::Location& from_here,
  1411. const scoped_refptr<base::SequencedTaskRunner>& task_runner,
  1412. base::OnceClosure task) {
  1413. AfterStartupTaskUtils::PostTask(from_here, task_runner, std::move(task));
  1414. }
  1415. bool ChromeContentBrowserClient::IsBrowserStartupComplete() {
  1416. return AfterStartupTaskUtils::IsBrowserStartupComplete();
  1417. }
  1418. void ChromeContentBrowserClient::SetBrowserStartupIsCompleteForTesting() {
  1419. AfterStartupTaskUtils::SetBrowserStartupIsCompleteForTesting();
  1420. }
  1421. bool ChromeContentBrowserClient::IsShuttingDown() {
  1422. return browser_shutdown::HasShutdownStarted();
  1423. }
  1424. content::StoragePartitionConfig
  1425. ChromeContentBrowserClient::GetStoragePartitionConfigForSite(
  1426. content::BrowserContext* browser_context,
  1427. const GURL& site) {
  1428. // Default to the browser-wide storage partition and override based on |site|
  1429. // below.
  1430. content::StoragePartitionConfig storage_partition_config =
  1431. content::StoragePartitionConfig::CreateDefault(browser_context);
  1432. #if BUILDFLAG(ENABLE_EXTENSIONS)
  1433. // TODO(crbug.com/1212263): Isolated PWAs are tracked by origin, but this
  1434. // function takes a site, so it will only work correctly when the site equals
  1435. // the full origin.
  1436. if (content::SiteIsolationPolicy::ShouldUrlUseApplicationIsolationLevel(
  1437. browser_context, site)) {
  1438. Profile* profile = Profile::FromBrowserContext(browser_context);
  1439. const std::string* isolation_key = web_app::GetStorageIsolationKey(
  1440. profile->GetPrefs(), url::Origin::Create(site));
  1441. CHECK(isolation_key);
  1442. // |in_memory| and |partition_name| are only used in guest schemes, so they
  1443. // are cleared here.
  1444. return content::StoragePartitionConfig::Create(
  1445. browser_context, *isolation_key,
  1446. /*partition_name=*/std::string(),
  1447. /*in_memory=*/false);
  1448. }
  1449. if (site.SchemeIs(extensions::kExtensionScheme)) {
  1450. // The host in an extension site URL is the extension_id.
  1451. CHECK(site.has_host());
  1452. return extensions::util::GetStoragePartitionConfigForExtensionId(
  1453. site.host(), browser_context);
  1454. }
  1455. #endif
  1456. return storage_partition_config;
  1457. }
  1458. std::unique_ptr<content::WebContentsViewDelegate>
  1459. ChromeContentBrowserClient::GetWebContentsViewDelegate(
  1460. content::WebContents* web_contents) {
  1461. if (auto* registry =
  1462. performance_manager::PerformanceManagerRegistry::GetInstance()) {
  1463. registry->MaybeCreatePageNodeForWebContents(web_contents);
  1464. }
  1465. return CreateWebContentsViewDelegate(web_contents);
  1466. }
  1467. bool ChromeContentBrowserClient::AllowGpuLaunchRetryOnIOThread() {
  1468. #if BUILDFLAG(IS_ANDROID)
  1469. const base::android::ApplicationState app_state =
  1470. base::android::ApplicationStatusListener::GetState();
  1471. return base::android::APPLICATION_STATE_UNKNOWN == app_state ||
  1472. base::android::APPLICATION_STATE_HAS_RUNNING_ACTIVITIES == app_state ||
  1473. base::android::APPLICATION_STATE_HAS_PAUSED_ACTIVITIES == app_state;
  1474. #else
  1475. return true;
  1476. #endif
  1477. }
  1478. void ChromeContentBrowserClient::RenderProcessWillLaunch(
  1479. content::RenderProcessHost* host) {
  1480. Profile* profile = Profile::FromBrowserContext(host->GetBrowserContext());
  1481. WebRtcLoggingController::AttachToRenderProcessHost(
  1482. host, g_browser_process->webrtc_log_uploader());
  1483. // The audio manager outlives the host, so it's safe to hand a raw pointer to
  1484. // it to the AudioDebugRecordingsHandler, which is owned by the host.
  1485. AudioDebugRecordingsHandler* audio_debug_recordings_handler =
  1486. new AudioDebugRecordingsHandler(profile);
  1487. host->SetUserData(
  1488. AudioDebugRecordingsHandler::kAudioDebugRecordingsHandlerKey,
  1489. std::make_unique<base::UserDataAdapter<AudioDebugRecordingsHandler>>(
  1490. audio_debug_recordings_handler));
  1491. #if BUILDFLAG(ENABLE_NACL)
  1492. host->AddFilter(new nacl::NaClHostMessageFilter(
  1493. host->GetID(), profile->IsOffTheRecord(), profile->GetPath()));
  1494. #endif
  1495. #if BUILDFLAG(IS_ANDROID)
  1496. // Data cannot be persisted if the profile is off the record.
  1497. host->AddFilter(
  1498. new cdm::CdmMessageFilterAndroid(!profile->IsOffTheRecord(), false));
  1499. // Register CrashMemoryMetricsCollector to report oom related metrics.
  1500. host->SetUserData(
  1501. CrashMemoryMetricsCollector::kCrashMemoryMetricsCollectorKey,
  1502. std::make_unique<CrashMemoryMetricsCollector>(host));
  1503. #endif
  1504. RendererUpdaterFactory::GetForProfile(profile)->InitializeRenderer(host);
  1505. for (size_t i = 0; i < extra_parts_.size(); ++i)
  1506. extra_parts_[i]->RenderProcessWillLaunch(host);
  1507. }
  1508. GURL ChromeContentBrowserClient::GetEffectiveURL(
  1509. content::BrowserContext* browser_context,
  1510. const GURL& url) {
  1511. Profile* profile = Profile::FromBrowserContext(browser_context);
  1512. if (!profile)
  1513. return url;
  1514. #if !BUILDFLAG(IS_ANDROID)
  1515. // If the input |url| should be assigned to the Instant renderer, make its
  1516. // effective URL distinct from other URLs on the search provider's domain.
  1517. // This needs to happen even if |url| corresponds to an isolated origin; see
  1518. // https://crbug.com/755595.
  1519. if (search::ShouldAssignURLToInstantRenderer(url, profile))
  1520. return search::GetEffectiveURLForInstant(url, profile);
  1521. #endif
  1522. #if BUILDFLAG(ENABLE_EXTENSIONS)
  1523. return ChromeContentBrowserClientExtensionsPart::GetEffectiveURL(profile,
  1524. url);
  1525. #else
  1526. return url;
  1527. #endif
  1528. }
  1529. bool ChromeContentBrowserClient::
  1530. ShouldCompareEffectiveURLsForSiteInstanceSelection(
  1531. content::BrowserContext* browser_context,
  1532. content::SiteInstance* candidate_site_instance,
  1533. bool is_main_frame,
  1534. const GURL& candidate_url,
  1535. const GURL& destination_url) {
  1536. DCHECK(browser_context);
  1537. DCHECK(candidate_site_instance);
  1538. #if BUILDFLAG(ENABLE_EXTENSIONS)
  1539. return ChromeContentBrowserClientExtensionsPart::
  1540. ShouldCompareEffectiveURLsForSiteInstanceSelection(
  1541. browser_context, candidate_site_instance, is_main_frame,
  1542. candidate_url, destination_url);
  1543. #else
  1544. return true;
  1545. #endif
  1546. }
  1547. bool ChromeContentBrowserClient::ShouldUseMobileFlingCurve() {
  1548. #if BUILDFLAG(IS_ANDROID)
  1549. return true;
  1550. #elif BUILDFLAG(IS_CHROMEOS_ASH)
  1551. return ash::TabletMode::IsInTabletMode();
  1552. #else
  1553. return false;
  1554. #endif // BUILDFLAG(IS_ANDROID)
  1555. }
  1556. bool ChromeContentBrowserClient::ShouldUseProcessPerSite(
  1557. content::BrowserContext* browser_context,
  1558. const GURL& site_url) {
  1559. Profile* profile = Profile::FromBrowserContext(browser_context);
  1560. if (!profile)
  1561. return false;
  1562. // NTP should use process-per-site. This is a performance optimization to
  1563. // reduce process count associated with NTP tabs.
  1564. if (site_url == GURL(chrome::kChromeUINewTabURL) ||
  1565. site_url == GURL(chrome::kChromeUINewTabPageURL)) {
  1566. return true;
  1567. }
  1568. #if !BUILDFLAG(IS_ANDROID)
  1569. if (search::ShouldUseProcessPerSiteForInstantSiteURL(site_url, profile))
  1570. return true;
  1571. #endif
  1572. #if BUILDFLAG(ENABLE_EXTENSIONS)
  1573. if (ChromeContentBrowserClientExtensionsPart::ShouldUseProcessPerSite(
  1574. profile, site_url))
  1575. return true;
  1576. #endif
  1577. // Non-extension, non-NTP URLs should generally use process-per-site-instance
  1578. // (rather than process-per-site).
  1579. return false;
  1580. }
  1581. bool ChromeContentBrowserClient::ShouldUseSpareRenderProcessHost(
  1582. content::BrowserContext* browser_context,
  1583. const GURL& site_url) {
  1584. Profile* profile = Profile::FromBrowserContext(browser_context);
  1585. if (!profile)
  1586. return false;
  1587. // Top Chrome WebUI should share a RendererProcessHost. Return false here to
  1588. // ensure the Spare Renderer is not assigned.
  1589. if (IsTopChromeWebUIURL(site_url))
  1590. return false;
  1591. #if !BUILDFLAG(IS_ANDROID)
  1592. // Instant renderers should not use a spare process, because they require
  1593. // passing switches::kInstantProcess to the renderer process when it
  1594. // launches. A spare process is launched earlier, before it is known which
  1595. // navigation will use it, so it lacks this flag.
  1596. if (search::ShouldAssignURLToInstantRenderer(site_url, profile))
  1597. return false;
  1598. #endif
  1599. #if BUILDFLAG(ENABLE_EXTENSIONS)
  1600. return ChromeContentBrowserClientExtensionsPart::
  1601. ShouldUseSpareRenderProcessHost(profile, site_url);
  1602. #else
  1603. return true;
  1604. #endif
  1605. }
  1606. bool ChromeContentBrowserClient::DoesSiteRequireDedicatedProcess(
  1607. content::BrowserContext* browser_context,
  1608. const GURL& effective_site_url) {
  1609. DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
  1610. #if BUILDFLAG(ENABLE_EXTENSIONS)
  1611. if (ChromeContentBrowserClientExtensionsPart::DoesSiteRequireDedicatedProcess(
  1612. browser_context, effective_site_url)) {
  1613. return true;
  1614. }
  1615. #endif
  1616. return false;
  1617. }
  1618. bool ChromeContentBrowserClient::DoesWebUISchemeRequireProcessLock(
  1619. base::StringPiece scheme) {
  1620. // Note: This method can be called from multiple threads. It is not safe to
  1621. // assume it runs only on the UI thread.
  1622. // chrome-search: documents commit only in the NTP instant process and are not
  1623. // locked to chrome-search: origin. Locking to chrome-search would kill
  1624. // processes upon legitimate requests for cookies from the search engine's
  1625. // domain.
  1626. if (scheme == chrome::kChromeSearchScheme)
  1627. return false;
  1628. // All other WebUIs must be locked to origin.
  1629. return true;
  1630. }
  1631. bool ChromeContentBrowserClient::ShouldTreatURLSchemeAsFirstPartyWhenTopLevel(
  1632. base::StringPiece scheme,
  1633. bool is_embedded_origin_secure) {
  1634. // This is needed to bypass the normal SameSite rules for any chrome:// page
  1635. // embedding a secure origin, regardless of the registrable domains of any
  1636. // intervening frames. For example, this is needed for browser UI to interact
  1637. // with SameSite cookies on accounts.google.com, which are used for logging
  1638. // into Cloud Print from chrome://print, for displaying a list of available
  1639. // accounts on the NTP (chrome://new-tab-page), etc.
  1640. if (is_embedded_origin_secure && scheme == content::kChromeUIScheme)
  1641. return true;
  1642. #if BUILDFLAG(ENABLE_EXTENSIONS)
  1643. return scheme == extensions::kExtensionScheme;
  1644. #else
  1645. return false;
  1646. #endif
  1647. }
  1648. bool ChromeContentBrowserClient::
  1649. ShouldIgnoreSameSiteCookieRestrictionsWhenTopLevel(
  1650. base::StringPiece scheme,
  1651. bool is_embedded_origin_secure) {
  1652. return is_embedded_origin_secure && scheme == content::kChromeUIScheme;
  1653. }
  1654. // TODO(crbug.com/1087559): This is based on SubframeTask::GetTitle()
  1655. // implementation. Find a general solution to avoid code duplication.
  1656. std::string ChromeContentBrowserClient::GetSiteDisplayNameForCdmProcess(
  1657. content::BrowserContext* browser_context,
  1658. const GURL& site_url) {
  1659. // By default, use the |site_url| spec as the display name.
  1660. std::string name = site_url.spec();
  1661. #if BUILDFLAG(ENABLE_EXTENSIONS)
  1662. // If |site_url| wraps a chrome extension ID, we can display the extension
  1663. // name instead, which is more human-readable.
  1664. if (site_url.SchemeIs(extensions::kExtensionScheme)) {
  1665. const extensions::Extension* extension =
  1666. extensions::ExtensionRegistry::Get(browser_context)
  1667. ->enabled_extensions()
  1668. .GetExtensionOrAppByURL(site_url);
  1669. if (extension)
  1670. name = extension->name();
  1671. }
  1672. #endif // BUILDFLAG(ENABLE_EXTENSIONS)
  1673. return name;
  1674. }
  1675. void ChromeContentBrowserClient::OverrideURLLoaderFactoryParams(
  1676. content::BrowserContext* browser_context,
  1677. const url::Origin& origin,
  1678. bool is_for_isolated_world,
  1679. network::mojom::URLLoaderFactoryParams* factory_params) {
  1680. #if BUILDFLAG(ENABLE_EXTENSIONS)
  1681. ChromeContentBrowserClientExtensionsPart::OverrideURLLoaderFactoryParams(
  1682. browser_context, origin, is_for_isolated_world, factory_params);
  1683. #endif
  1684. }
  1685. // These are treated as WebUI schemes but do not get WebUI bindings. Also,
  1686. // view-source is allowed for these schemes.
  1687. void ChromeContentBrowserClient::GetAdditionalWebUISchemes(
  1688. std::vector<std::string>* additional_schemes) {
  1689. additional_schemes->emplace_back(chrome::kChromeSearchScheme);
  1690. additional_schemes->emplace_back(dom_distiller::kDomDistillerScheme);
  1691. additional_schemes->emplace_back(content::kChromeDevToolsScheme);
  1692. }
  1693. void ChromeContentBrowserClient::GetAdditionalViewSourceSchemes(
  1694. std::vector<std::string>* additional_schemes) {
  1695. GetAdditionalWebUISchemes(additional_schemes);
  1696. #if BUILDFLAG(ENABLE_EXTENSIONS)
  1697. additional_schemes->push_back(extensions::kExtensionScheme);
  1698. #endif
  1699. }
  1700. network::mojom::IPAddressSpace
  1701. ChromeContentBrowserClient::DetermineAddressSpaceFromURL(const GURL& url) {
  1702. if (url.SchemeIs(chrome::kChromeSearchScheme))
  1703. return network::mojom::IPAddressSpace::kLocal;
  1704. if (url.SchemeIs(dom_distiller::kDomDistillerScheme))
  1705. return network::mojom::IPAddressSpace::kPublic;
  1706. #if BUILDFLAG(ENABLE_EXTENSIONS)
  1707. if (url.SchemeIs(extensions::kExtensionScheme))
  1708. return network::mojom::IPAddressSpace::kLocal;
  1709. #endif
  1710. return network::mojom::IPAddressSpace::kUnknown;
  1711. }
  1712. bool ChromeContentBrowserClient::LogWebUIUrl(const GURL& web_ui_url) {
  1713. return webui::LogWebUIUrl(web_ui_url);
  1714. }
  1715. bool ChromeContentBrowserClient::IsWebUIAllowedToMakeNetworkRequests(
  1716. const url::Origin& origin) {
  1717. return ChromeWebUIControllerFactory::IsWebUIAllowedToMakeNetworkRequests(
  1718. origin);
  1719. }
  1720. bool ChromeContentBrowserClient::IsHandledURL(const GURL& url) {
  1721. return ProfileIOData::IsHandledURL(url);
  1722. }
  1723. bool ChromeContentBrowserClient::HasCustomSchemeHandler(
  1724. content::BrowserContext* browser_context,
  1725. const std::string& scheme) {
  1726. if (custom_handlers::ProtocolHandlerRegistry* protocol_handler_registry =
  1727. ProtocolHandlerRegistryFactory::GetForBrowserContext(
  1728. browser_context)) {
  1729. return protocol_handler_registry->IsHandledProtocol(scheme);
  1730. }
  1731. return false;
  1732. }
  1733. bool ChromeContentBrowserClient::CanCommitURL(
  1734. content::RenderProcessHost* process_host,
  1735. const GURL& url) {
  1736. #if BUILDFLAG(ENABLE_EXTENSIONS)
  1737. return ChromeContentBrowserClientExtensionsPart::CanCommitURL(process_host,
  1738. url);
  1739. #else
  1740. return true;
  1741. #endif
  1742. }
  1743. void ChromeContentBrowserClient::OverrideNavigationParams(
  1744. SiteInstance* site_instance,
  1745. ui::PageTransition* transition,
  1746. bool* is_renderer_initiated,
  1747. content::Referrer* referrer,
  1748. absl::optional<url::Origin>* initiator_origin) {
  1749. DCHECK(transition);
  1750. DCHECK(is_renderer_initiated);
  1751. DCHECK(referrer);
  1752. // While using SiteInstance::GetSiteURL() is unreliable and the wrong thing to
  1753. // use for making security decisions 99.44% of the time, for detecting the NTP
  1754. // it is reliable and the correct way. See http://crbug.com/624410.
  1755. if (site_instance && search::IsNTPURL(site_instance->GetSiteURL()) &&
  1756. ui::PageTransitionCoreTypeIs(*transition, ui::PAGE_TRANSITION_LINK)) {
  1757. // Clicks on tiles of the new tab page should be treated as if a user
  1758. // clicked on a bookmark. This is consistent with native implementations
  1759. // like Android's. This also helps ensure that security features (like
  1760. // Sec-Fetch-Site and SameSite-cookies) will treat the navigation as
  1761. // browser-initiated.
  1762. *transition = ui::PAGE_TRANSITION_AUTO_BOOKMARK;
  1763. *is_renderer_initiated = false;
  1764. *referrer = content::Referrer();
  1765. *initiator_origin = absl::nullopt;
  1766. }
  1767. }
  1768. bool ChromeContentBrowserClient::ShouldStayInParentProcessForNTP(
  1769. const GURL& url,
  1770. SiteInstance* parent_site_instance) {
  1771. // While using SiteInstance::GetSiteURL() is unreliable and the wrong thing to
  1772. // use for making security decisions 99.44% of the time, for detecting the NTP
  1773. // it is reliable and the correct way. See http://crbug.com/624410.
  1774. return url.SchemeIs(chrome::kChromeSearchScheme) && parent_site_instance &&
  1775. search::IsNTPURL(parent_site_instance->GetSiteURL());
  1776. }
  1777. bool ChromeContentBrowserClient::IsSuitableHost(
  1778. content::RenderProcessHost* process_host,
  1779. const GURL& site_url) {
  1780. Profile* profile =
  1781. Profile::FromBrowserContext(process_host->GetBrowserContext());
  1782. // This may be nullptr during tests. In that case, just assume any site can
  1783. // share any host.
  1784. if (!profile)
  1785. return true;
  1786. #if !BUILDFLAG(IS_ANDROID)
  1787. // Instant URLs should only be in the instant process and instant process
  1788. // should only have Instant URLs.
  1789. InstantService* instant_service =
  1790. InstantServiceFactory::GetForProfile(profile);
  1791. if (instant_service) {
  1792. bool is_instant_process =
  1793. instant_service->IsInstantProcess(process_host->GetID());
  1794. bool should_be_in_instant_process =
  1795. search::ShouldAssignURLToInstantRenderer(site_url, profile);
  1796. if (is_instant_process || should_be_in_instant_process)
  1797. return is_instant_process && should_be_in_instant_process;
  1798. }
  1799. #endif
  1800. #if BUILDFLAG(ENABLE_EXTENSIONS)
  1801. return ChromeContentBrowserClientExtensionsPart::IsSuitableHost(
  1802. profile, process_host, site_url);
  1803. #else
  1804. return true;
  1805. #endif
  1806. }
  1807. bool ChromeContentBrowserClient::MayReuseHost(
  1808. content::RenderProcessHost* process_host) {
  1809. // If there is currently a no-state prefetcher in progress for the host
  1810. // provided, it may not be shared. We require prefetchers to be by themselves
  1811. // in a separate process so that we can monitor their resource usage.
  1812. prerender::NoStatePrefetchManager* no_state_prefetch_manager =
  1813. prerender::NoStatePrefetchManagerFactory::GetForBrowserContext(
  1814. process_host->GetBrowserContext());
  1815. if (no_state_prefetch_manager &&
  1816. !no_state_prefetch_manager->MayReuseProcessHost(process_host)) {
  1817. return false;
  1818. }
  1819. return true;
  1820. }
  1821. size_t ChromeContentBrowserClient::GetProcessCountToIgnoreForLimit() {
  1822. #if BUILDFLAG(ENABLE_EXTENSIONS)
  1823. return ChromeContentBrowserClientExtensionsPart::
  1824. GetProcessCountToIgnoreForLimit();
  1825. #else
  1826. return 0;
  1827. #endif
  1828. }
  1829. blink::ParsedPermissionsPolicy
  1830. ChromeContentBrowserClient::GetPermissionsPolicyForIsolatedApp(
  1831. content::BrowserContext* browser_context,
  1832. const url::Origin& app_origin) {
  1833. #if !BUILDFLAG(IS_ANDROID)
  1834. Profile* profile = Profile::FromBrowserContext(browser_context);
  1835. auto& registrar =
  1836. web_app::WebAppProvider::GetForWebApps(profile)->registrar();
  1837. std::vector<web_app::AppId> app_ids_for_origin =
  1838. registrar.FindAppsInScope(app_origin.GetURL());
  1839. if (app_ids_for_origin.empty()) {
  1840. return blink::ParsedPermissionsPolicy();
  1841. }
  1842. return registrar.GetPermissionsPolicy(app_ids_for_origin[0]);
  1843. #else
  1844. NOTIMPLEMENTED();
  1845. return blink::ParsedPermissionsPolicy();
  1846. #endif
  1847. }
  1848. bool ChromeContentBrowserClient::ShouldTryToUseExistingProcessHost(
  1849. content::BrowserContext* browser_context,
  1850. const GURL& url) {
  1851. // Top Chrome WebUI should try to share a RenderProcessHost with other
  1852. // existing Top Chrome WebUI.
  1853. if (IsTopChromeWebUIURL(url))
  1854. return true;
  1855. return false;
  1856. }
  1857. bool ChromeContentBrowserClient::ShouldEmbeddedFramesTryToReuseExistingProcess(
  1858. content::RenderFrameHost* outermost_main_frame) {
  1859. #if BUILDFLAG(ENABLE_EXTENSIONS)
  1860. return ChromeContentBrowserClientExtensionsPart::
  1861. ShouldEmbeddedFramesTryToReuseExistingProcess(outermost_main_frame);
  1862. #else
  1863. return true;
  1864. #endif
  1865. }
  1866. void ChromeContentBrowserClient::SiteInstanceGotProcess(
  1867. SiteInstance* site_instance) {
  1868. CHECK(site_instance->HasProcess());
  1869. Profile* profile =
  1870. Profile::FromBrowserContext(site_instance->GetBrowserContext());
  1871. if (!profile)
  1872. return;
  1873. #if !BUILDFLAG(IS_ANDROID)
  1874. // Remember the ID of the Instant process to signal the renderer process
  1875. // on startup in |AppendExtraCommandLineSwitches| below.
  1876. if (search::ShouldAssignURLToInstantRenderer(site_instance->GetSiteURL(),
  1877. profile)) {
  1878. InstantService* instant_service =
  1879. InstantServiceFactory::GetForProfile(profile);
  1880. if (instant_service)
  1881. instant_service->AddInstantProcess(site_instance->GetProcess()->GetID());
  1882. }
  1883. #endif
  1884. for (size_t i = 0; i < extra_parts_.size(); ++i)
  1885. extra_parts_[i]->SiteInstanceGotProcess(site_instance);
  1886. }
  1887. void ChromeContentBrowserClient::SiteInstanceDeleting(
  1888. SiteInstance* site_instance) {
  1889. if (!site_instance->HasProcess())
  1890. return;
  1891. for (size_t i = 0; i < extra_parts_.size(); ++i)
  1892. extra_parts_[i]->SiteInstanceDeleting(site_instance);
  1893. }
  1894. bool ChromeContentBrowserClient::ShouldSwapBrowsingInstancesForNavigation(
  1895. SiteInstance* site_instance,
  1896. const GURL& current_effective_url,
  1897. const GURL& destination_effective_url) {
  1898. #if BUILDFLAG(ENABLE_EXTENSIONS)
  1899. return ChromeContentBrowserClientExtensionsPart::
  1900. ShouldSwapBrowsingInstancesForNavigation(
  1901. site_instance, current_effective_url, destination_effective_url);
  1902. #else
  1903. return false;
  1904. #endif
  1905. }
  1906. bool ChromeContentBrowserClient::ShouldIsolateErrorPage(bool in_main_frame) {
  1907. // TODO(nasko): Consider supporting error page isolation in subframes if
  1908. // Site Isolation is enabled.
  1909. return in_main_frame;
  1910. }
  1911. bool ChromeContentBrowserClient::ShouldAssignSiteForURL(const GURL& url) {
  1912. return !url.SchemeIs(chrome::kChromeNativeScheme);
  1913. }
  1914. std::vector<url::Origin>
  1915. ChromeContentBrowserClient::GetOriginsRequiringDedicatedProcess() {
  1916. std::vector<url::Origin> isolated_origin_list;
  1917. if (DoesGaiaOriginRequireDedicatedProcess()) {
  1918. isolated_origin_list.push_back(GaiaUrls::GetInstance()->gaia_origin());
  1919. }
  1920. #if BUILDFLAG(ENABLE_EXTENSIONS)
  1921. auto origins_from_extensions = ChromeContentBrowserClientExtensionsPart::
  1922. GetOriginsRequiringDedicatedProcess();
  1923. std::move(std::begin(origins_from_extensions),
  1924. std::end(origins_from_extensions),
  1925. std::back_inserter(isolated_origin_list));
  1926. #endif
  1927. // Include additional origins preloaded with specific browser configurations,
  1928. // if any. For example, this is used on Google Chrome for Android to preload
  1929. // a list of important sites to isolate.
  1930. auto built_in_origins =
  1931. site_isolation::GetBrowserSpecificBuiltInIsolatedOrigins();
  1932. std::move(std::begin(built_in_origins), std::end(built_in_origins),
  1933. std::back_inserter(isolated_origin_list));
  1934. return isolated_origin_list;
  1935. }
  1936. bool ChromeContentBrowserClient::ShouldEnableStrictSiteIsolation() {
  1937. return base::FeatureList::IsEnabled(features::kSitePerProcess);
  1938. }
  1939. bool ChromeContentBrowserClient::ShouldDisableSiteIsolation(
  1940. content::SiteIsolationMode site_isolation_mode) {
  1941. return site_isolation::SiteIsolationPolicy::
  1942. ShouldDisableSiteIsolationDueToMemoryThreshold(site_isolation_mode);
  1943. }
  1944. std::vector<std::string>
  1945. ChromeContentBrowserClient::GetAdditionalSiteIsolationModes() {
  1946. std::vector<std::string> modes;
  1947. if (site_isolation::SiteIsolationPolicy::IsIsolationForPasswordSitesEnabled())
  1948. modes.push_back("Password Sites");
  1949. if (site_isolation::SiteIsolationPolicy::IsIsolationForOAuthSitesEnabled())
  1950. modes.push_back("Logged-in Sites");
  1951. return modes;
  1952. }
  1953. void ChromeContentBrowserClient::PersistIsolatedOrigin(
  1954. content::BrowserContext* context,
  1955. const url::Origin& origin,
  1956. content::ChildProcessSecurityPolicy::IsolatedOriginSource source) {
  1957. site_isolation::SiteIsolationPolicy::PersistIsolatedOrigin(context, origin,
  1958. source);
  1959. }
  1960. bool ChromeContentBrowserClient::ShouldUrlUseApplicationIsolationLevel(
  1961. content::BrowserContext* browser_context,
  1962. const GURL& url) {
  1963. #if BUILDFLAG(ENABLE_EXTENSIONS)
  1964. if (content::SiteIsolationPolicy::IsApplicationIsolationLevelEnabled()) {
  1965. Profile* profile = Profile::FromBrowserContext(browser_context);
  1966. return web_app::GetStorageIsolationKey(profile->GetPrefs(),
  1967. url::Origin::Create(url));
  1968. }
  1969. #endif
  1970. return false;
  1971. }
  1972. bool ChromeContentBrowserClient::IsIsolatedAppsDeveloperModeAllowed(
  1973. content::BrowserContext* context) {
  1974. Profile* profile = Profile::FromBrowserContext(context);
  1975. return profile &&
  1976. profile->GetPrefs()->GetBoolean(
  1977. policy::policy_prefs::kIsolatedAppsDeveloperModeAllowed);
  1978. }
  1979. bool ChromeContentBrowserClient::IsGetDisplayMediaSetSelectAllScreensAllowed(
  1980. content::BrowserContext* context,
  1981. const url::Origin& origin) {
  1982. return capture_policy::IsGetDisplayMediaSetSelectAllScreensAllowed(
  1983. context, origin.GetURL());
  1984. }
  1985. bool ChromeContentBrowserClient::IsFileAccessAllowed(
  1986. const base::FilePath& path,
  1987. const base::FilePath& absolute_path,
  1988. const base::FilePath& profile_path) {
  1989. return ChromeNetworkDelegate::IsAccessAllowed(path, absolute_path,
  1990. profile_path);
  1991. }
  1992. namespace {
  1993. void MaybeAppendBlinkSettingsSwitchForFieldTrial(
  1994. const base::CommandLine& browser_command_line,
  1995. base::CommandLine* command_line) {
  1996. // List of field trials that modify the blink-settings command line flag. No
  1997. // two field trials in the list should specify the same keys, otherwise one
  1998. // field trial may overwrite another. See Source/core/frame/Settings.in in
  1999. // Blink for the list of valid keys.
  2000. static const char* const kBlinkSettingsFieldTrials[] = {
  2001. // Keys: disallowFetchForDocWrittenScriptsInMainFrame
  2002. // disallowFetchForDocWrittenScriptsInMainFrameOnSlowConnections
  2003. // disallowFetchForDocWrittenScriptsInMainFrameIfEffectively2G
  2004. "DisallowFetchForDocWrittenScriptsInMainFrame",
  2005. };
  2006. std::vector<std::string> blink_settings;
  2007. for (const char* field_trial_name : kBlinkSettingsFieldTrials) {
  2008. // Each blink-settings field trial should include a forcing_flag group,
  2009. // to make sure that clients that specify the blink-settings flag on the
  2010. // command line are excluded from the experiment groups. To make
  2011. // sure we assign clients that specify this flag to the forcing_flag
  2012. // group, we must call GetVariationParams for each field trial first
  2013. // (for example, before checking HasSwitch() and returning), since
  2014. // GetVariationParams has the side-effect of assigning the client to
  2015. // a field trial group.
  2016. std::map<std::string, std::string> params;
  2017. if (variations::GetVariationParams(field_trial_name, &params)) {
  2018. for (const auto& param : params) {
  2019. blink_settings.push_back(base::StringPrintf(
  2020. "%s=%s", param.first.c_str(), param.second.c_str()));
  2021. }
  2022. }
  2023. }
  2024. if (blink_settings.empty()) {
  2025. return;
  2026. }
  2027. if (browser_command_line.HasSwitch(blink::switches::kBlinkSettings) ||
  2028. command_line->HasSwitch(blink::switches::kBlinkSettings)) {
  2029. // The field trials should be configured to force users that specify the
  2030. // blink-settings flag into a group with no params, and we return
  2031. // above if no params were specified, so it's an error if we reach
  2032. // this point.
  2033. LOG(WARNING) << "Received field trial params, "
  2034. "but blink-settings switch already specified.";
  2035. return;
  2036. }
  2037. command_line->AppendSwitchASCII(blink::switches::kBlinkSettings,
  2038. base::JoinString(blink_settings, ","));
  2039. }
  2040. } // namespace
  2041. void ChromeContentBrowserClient::AppendExtraCommandLineSwitches(
  2042. base::CommandLine* command_line,
  2043. int child_process_id) {
  2044. #if BUILDFLAG(IS_MAC)
  2045. std::unique_ptr<metrics::ClientInfo> client_info =
  2046. GoogleUpdateSettings::LoadMetricsClientInfo();
  2047. if (client_info) {
  2048. command_line->AppendSwitchASCII(switches::kMetricsClientID,
  2049. client_info->client_id);
  2050. }
  2051. #elif BUILDFLAG(IS_POSIX)
  2052. #if BUILDFLAG(IS_ANDROID)
  2053. bool enable_crash_reporter = true;
  2054. #else
  2055. bool enable_crash_reporter = false;
  2056. if (crash_reporter::IsCrashpadEnabled()) {
  2057. command_line->AppendSwitch(switches::kEnableCrashpad);
  2058. enable_crash_reporter = true;
  2059. int fd;
  2060. pid_t pid;
  2061. if (crash_reporter::GetHandlerSocket(&fd, &pid)) {
  2062. command_line->AppendSwitchASCII(
  2063. crash_reporter::switches::kCrashpadHandlerPid,
  2064. base::NumberToString(pid));
  2065. }
  2066. } else {
  2067. enable_crash_reporter = breakpad::IsCrashReporterEnabled();
  2068. }
  2069. #endif
  2070. if (enable_crash_reporter) {
  2071. std::string switch_value;
  2072. std::unique_ptr<metrics::ClientInfo> client_info =
  2073. GoogleUpdateSettings::LoadMetricsClientInfo();
  2074. if (client_info)
  2075. switch_value = client_info->client_id;
  2076. switch_value.push_back(',');
  2077. switch_value.append(
  2078. chrome::GetChannelName(chrome::WithExtendedStable(true)));
  2079. command_line->AppendSwitchASCII(switches::kEnableCrashReporter,
  2080. switch_value);
  2081. }
  2082. #endif
  2083. if (logging::DialogsAreSuppressed())
  2084. command_line->AppendSwitch(switches::kNoErrorDialogs);
  2085. std::string process_type =
  2086. command_line->GetSwitchValueASCII(switches::kProcessType);
  2087. const base::CommandLine& browser_command_line =
  2088. *base::CommandLine::ForCurrentProcess();
  2089. static const char* const kCommonSwitchNames[] = {
  2090. embedder_support::kUserAgent,
  2091. switches::kUserDataDir, // Make logs go to the right file.
  2092. };
  2093. command_line->CopySwitchesFrom(browser_command_line, kCommonSwitchNames,
  2094. std::size(kCommonSwitchNames));
  2095. static const char* const kDinosaurEasterEggSwitches[] = {
  2096. error_page::switches::kDisableDinosaurEasterEgg,
  2097. };
  2098. command_line->CopySwitchesFrom(browser_command_line,
  2099. kDinosaurEasterEggSwitches,
  2100. std::size(kDinosaurEasterEggSwitches));
  2101. #if BUILDFLAG(IS_CHROMEOS_ASH)
  2102. // On Chrome OS need to pass primary user homedir (in multi-profiles session).
  2103. base::FilePath homedir;
  2104. base::PathService::Get(base::DIR_HOME, &homedir);
  2105. command_line->AppendSwitchASCII(ash::switches::kHomedir,
  2106. homedir.value().c_str());
  2107. #endif
  2108. if (process_type == switches::kRendererProcess) {
  2109. content::RenderProcessHost* process =
  2110. content::RenderProcessHost::FromID(child_process_id);
  2111. Profile* profile =
  2112. process ? Profile::FromBrowserContext(process->GetBrowserContext())
  2113. : nullptr;
  2114. for (size_t i = 0; i < extra_parts_.size(); ++i) {
  2115. extra_parts_[i]->AppendExtraRendererCommandLineSwitches(command_line,
  2116. process, profile);
  2117. }
  2118. #if BUILDFLAG(IS_CHROMEOS_ASH)
  2119. const std::string& login_profile =
  2120. browser_command_line.GetSwitchValueASCII(ash::switches::kLoginProfile);
  2121. if (!login_profile.empty())
  2122. command_line->AppendSwitchASCII(ash::switches::kLoginProfile,
  2123. login_profile);
  2124. #endif
  2125. MaybeCopyDisableWebRtcEncryptionSwitch(command_line, browser_command_line,
  2126. chrome::GetChannel());
  2127. if (process) {
  2128. PrefService* prefs = profile->GetPrefs();
  2129. // Currently this pref is only registered if applied via a policy.
  2130. if (prefs->HasPrefPath(prefs::kDisable3DAPIs) &&
  2131. prefs->GetBoolean(prefs::kDisable3DAPIs)) {
  2132. // Turn this policy into a command line switch.
  2133. command_line->AppendSwitch(switches::kDisable3DAPIs);
  2134. }
  2135. if (prefs->GetBoolean(prefs::kPrintPreviewDisabled))
  2136. command_line->AppendSwitch(switches::kDisablePrintPreview);
  2137. // This passes the preference set by an enterprise policy on to a blink
  2138. // switch so that we know whether to force WebSQL/WebSQL in non-secure
  2139. // context to be enabled.
  2140. if (prefs->GetBoolean(storage::kWebSQLAccess)) {
  2141. command_line->AppendSwitch(blink::switches::kWebSQLAccess);
  2142. }
  2143. if (prefs->GetBoolean(storage::kWebSQLNonSecureContextEnabled)) {
  2144. command_line->AppendSwitch(
  2145. blink::switches::kWebSQLNonSecureContextEnabled);
  2146. }
  2147. // Enable persistent quota if enabled by enterprise policy.
  2148. if (prefs->GetBoolean(storage::kPersistentQuotaEnabled)) {
  2149. command_line->AppendSwitch(blink::switches::kPersistentQuotaEnabled);
  2150. }
  2151. // Enable legacy quota API if enabled by enterprise policy.
  2152. if (prefs->GetBoolean(storage::kPrefixedStorageInfoEnabled)) {
  2153. command_line->AppendSwitch(
  2154. blink::switches::kPrefixedStorageInfoEnabled);
  2155. }
  2156. #if !BUILDFLAG(IS_ANDROID)
  2157. InstantService* instant_service =
  2158. InstantServiceFactory::GetForProfile(profile);
  2159. if (instant_service &&
  2160. instant_service->IsInstantProcess(process->GetID())) {
  2161. command_line->AppendSwitch(switches::kInstantProcess);
  2162. }
  2163. // Enable SharedArrayBuffer on desktop if allowed by Enterprise Policy.
  2164. // TODO(crbug.com/1144104) Remove when migration to COOP+COEP is complete.
  2165. if (prefs->GetBoolean(
  2166. prefs::kSharedArrayBufferUnrestrictedAccessAllowed)) {
  2167. command_line->AppendSwitch(
  2168. switches::kSharedArrayBufferUnrestrictedAccessAllowed);
  2169. }
  2170. #endif
  2171. if (!prefs->GetBoolean(prefs::kSandboxExternalProtocolBlocked))
  2172. command_line->AppendSwitch(kDisableSandboxExternalProtocolSwitch);
  2173. if (prefs->GetBoolean(prefs::kDisplayCapturePermissionsPolicyEnabled)) {
  2174. command_line->AppendSwitch(
  2175. switches::kDisplayCapturePermissionsPolicyAllowed);
  2176. }
  2177. if (prefs->HasPrefPath(prefs::kAllowDinosaurEasterEgg) &&
  2178. !prefs->GetBoolean(prefs::kAllowDinosaurEasterEgg)) {
  2179. command_line->AppendSwitch(
  2180. error_page::switches::kDisableDinosaurEasterEgg);
  2181. }
  2182. MaybeAppendSecureOriginsAllowlistSwitch(command_line);
  2183. if (prefs->HasPrefPath(prefs::kScrollToTextFragmentEnabled) &&
  2184. !prefs->GetBoolean(prefs::kScrollToTextFragmentEnabled)) {
  2185. command_line->AppendSwitch(switches::kDisableScrollToTextFragment);
  2186. }
  2187. // Override SetTimeoutWithoutClamp feature if its Enterprise Policy
  2188. // is specified.
  2189. if (prefs->HasPrefPath(
  2190. policy::policy_prefs::kSetTimeoutWithout1MsClampEnabled)) {
  2191. command_line->AppendSwitchASCII(
  2192. blink::switches::kSetTimeoutWithout1MsClampPolicy,
  2193. prefs->GetBoolean(
  2194. policy::policy_prefs::kSetTimeoutWithout1MsClampEnabled)
  2195. ? blink::switches::kSetTimeoutWithout1MsClampPolicy_ForceEnable
  2196. : blink::switches::
  2197. kSetTimeoutWithout1MsClampPolicy_ForceDisable);
  2198. }
  2199. // Override MaxUnthrottledTimeoutNestingLevel feature if its Enterprise
  2200. // Policy is specified.
  2201. if (prefs->HasPrefPath(
  2202. policy::policy_prefs::kUnthrottledNestedTimeoutEnabled)) {
  2203. command_line->AppendSwitchASCII(
  2204. blink::switches::kUnthrottledNestedTimeoutPolicy,
  2205. prefs->GetBoolean(
  2206. policy::policy_prefs::kUnthrottledNestedTimeoutEnabled)
  2207. ? blink::switches::kUnthrottledNestedTimeoutPolicy_ForceEnable
  2208. : blink::switches::
  2209. kUnthrottledNestedTimeoutPolicy_ForceDisable);
  2210. }
  2211. // Override EventPath feature if its Enterprise Policy is specified.
  2212. if (prefs->HasPrefPath(policy::policy_prefs::kEventPathEnabled)) {
  2213. command_line->AppendSwitchASCII(
  2214. blink::switches::kEventPathPolicy,
  2215. prefs->GetBoolean(policy::policy_prefs::kEventPathEnabled)
  2216. ? blink::switches::kEventPathPolicy_ForceEnable
  2217. : blink::switches::kEventPathPolicy_ForceDisable);
  2218. } else if (chrome::GetChannel() < version_info::Channel::BETA) {
  2219. // When its Enterprise Policy is unspecified, disable Event.path by
  2220. // default on Canary and Dev to help the deprecation and removal.
  2221. // See crbug.com/1277431 for more details.
  2222. command_line->AppendSwitchASCII(
  2223. blink::switches::kEventPathPolicy,
  2224. blink::switches::kEventPathPolicy_ForceDisable);
  2225. }
  2226. // The IntensiveWakeUpThrottling feature is typically managed via a
  2227. // base::Feature, but it has a managed policy override. The override is
  2228. // communicated to blink via a custom command-line flag. See
  2229. // PageSchedulerImpl for the other half of related logic.
  2230. PrefService* local_state = g_browser_process->local_state();
  2231. const PrefService::Preference* pref = local_state->FindPreference(
  2232. policy::policy_prefs::kIntensiveWakeUpThrottlingEnabled);
  2233. if (pref && pref->IsManaged()) {
  2234. command_line->AppendSwitchASCII(
  2235. blink::switches::kIntensiveWakeUpThrottlingPolicy,
  2236. pref->GetValue()->GetBool()
  2237. ? blink::switches::kIntensiveWakeUpThrottlingPolicy_ForceEnable
  2238. : blink::switches::
  2239. kIntensiveWakeUpThrottlingPolicy_ForceDisable);
  2240. }
  2241. #if BUILDFLAG(IS_ANDROID)
  2242. // Communicating to content/ for BackForwardCache.
  2243. if (prefs->HasPrefPath(policy::policy_prefs::kBackForwardCacheEnabled) &&
  2244. !prefs->GetBoolean(policy::policy_prefs::kBackForwardCacheEnabled)) {
  2245. command_line->AppendSwitch(switches::kDisableBackForwardCache);
  2246. }
  2247. #endif // BUILDFLAG(IS_ANDROID)
  2248. #if !BUILDFLAG(IS_ANDROID)
  2249. // Make the WebAuthenticationRemoteProxiedRequestsAllowed policy enable
  2250. // the experimental WebAuthenticationRemoteDesktopSupport Blink runtime
  2251. // feature.
  2252. if (prefs->GetBoolean(
  2253. webauthn::pref_names::kRemoteProxiedRequestsAllowed)) {
  2254. command_line->AppendSwitch(switches::kWebAuthRemoteDesktopSupport);
  2255. }
  2256. if (IsCartModuleEnabled()) {
  2257. command_line->AppendSwitch(commerce::switches::kEnableChromeCart);
  2258. }
  2259. #endif
  2260. }
  2261. MaybeAppendBlinkSettingsSwitchForFieldTrial(browser_command_line,
  2262. command_line);
  2263. #if BUILDFLAG(IS_ANDROID)
  2264. // If the platform is Android, force the distillability service on.
  2265. command_line->AppendSwitch(switches::kEnableDistillabilityService);
  2266. #endif
  2267. // Please keep this in alphabetical order.
  2268. static const char* const kSwitchNames[] = {
  2269. autofill::switches::kIgnoreAutocompleteOffForAutofill,
  2270. autofill::switches::kShowAutofillSignatures,
  2271. #if BUILDFLAG(IS_CHROMEOS_ASH)
  2272. switches::kShortMergeSessionTimeoutForTest, // For tests only.
  2273. #endif
  2274. #if BUILDFLAG(ENABLE_EXTENSIONS)
  2275. extensions::switches::kAllowHTTPBackgroundPage,
  2276. extensions::switches::kAllowLegacyExtensionManifests,
  2277. extensions::switches::kDisableExtensionsHttpThrottling,
  2278. extensions::switches::kEnableExperimentalExtensionApis,
  2279. extensions::switches::kExtensionsOnChromeURLs,
  2280. extensions::switches::kSetExtensionThrottleTestParams, // For tests only.
  2281. extensions::switches::kAllowlistedExtensionID,
  2282. extensions::switches::kDEPRECATED_AllowlistedExtensionID,
  2283. #endif
  2284. switches::kAllowInsecureLocalhost,
  2285. switches::kAppsGalleryURL,
  2286. switches::kDisableJavaScriptHarmonyShipping,
  2287. variations::switches::kEnableBenchmarking,
  2288. switches::kEnableDistillabilityService,
  2289. switches::kEnableNaCl,
  2290. #if BUILDFLAG(ENABLE_NACL)
  2291. switches::kEnableNaClDebug,
  2292. #endif
  2293. switches::kEnableNetBenchmarking,
  2294. #if BUILDFLAG(IS_CHROMEOS)
  2295. chromeos::switches::
  2296. kTelemetryExtensionPwaOriginOverrideForTesting, // For tests only.
  2297. switches::kForceAppMode,
  2298. #endif
  2299. #if BUILDFLAG(ENABLE_NACL)
  2300. switches::kForcePNaClSubzero,
  2301. #endif
  2302. switches::kForceUIDirection,
  2303. switches::kIgnoreGooglePortNumbers,
  2304. switches::kJavaScriptHarmony,
  2305. switches::kEnableExperimentalWebAssemblyFeatures,
  2306. embedder_support::kOriginTrialDisabledFeatures,
  2307. embedder_support::kOriginTrialDisabledTokens,
  2308. embedder_support::kOriginTrialPublicKey,
  2309. switches::kReaderModeHeuristics,
  2310. translate::switches::kTranslateSecurityOrigin,
  2311. };
  2312. command_line->CopySwitchesFrom(browser_command_line, kSwitchNames,
  2313. std::size(kSwitchNames));
  2314. } else if (process_type == switches::kUtilityProcess) {
  2315. #if BUILDFLAG(ENABLE_EXTENSIONS)
  2316. static const char* const kSwitchNames[] = {
  2317. extensions::switches::kAllowHTTPBackgroundPage,
  2318. extensions::switches::kEnableExperimentalExtensionApis,
  2319. extensions::switches::kExtensionsOnChromeURLs,
  2320. extensions::switches::kAllowlistedExtensionID,
  2321. extensions::switches::kDEPRECATED_AllowlistedExtensionID,
  2322. };
  2323. command_line->CopySwitchesFrom(browser_command_line, kSwitchNames,
  2324. std::size(kSwitchNames));
  2325. #endif
  2326. MaybeAppendSecureOriginsAllowlistSwitch(command_line);
  2327. } else if (process_type == switches::kZygoteProcess) {
  2328. // Load (in-process) Pepper plugins in-process in the zygote pre-sandbox.
  2329. #if BUILDFLAG(ENABLE_NACL)
  2330. static const char* const kSwitchNames[] = {
  2331. switches::kEnableNaClDebug,
  2332. switches::kForcePNaClSubzero,
  2333. switches::kVerboseLoggingInNacl,
  2334. };
  2335. command_line->CopySwitchesFrom(browser_command_line, kSwitchNames,
  2336. std::size(kSwitchNames));
  2337. #endif
  2338. #if BUILDFLAG(IS_CHROMEOS_LACROS)
  2339. // Ensure zygote loads the resource bundle for the right locale.
  2340. static const char* const kMoreSwitchNames[] = {switches::kLang};
  2341. command_line->CopySwitchesFrom(browser_command_line, kMoreSwitchNames,
  2342. std::size(kMoreSwitchNames));
  2343. #endif
  2344. #if BUILDFLAG(IS_CHROMEOS)
  2345. // This is called before feature flags are parsed, so pass them in their raw
  2346. // form.
  2347. static const char* const kMoreCrOSSwitchNames[] = {
  2348. chromeos::switches::kFeatureFlags};
  2349. command_line->CopySwitchesFrom(browser_command_line, kMoreCrOSSwitchNames,
  2350. std::size(kMoreCrOSSwitchNames));
  2351. #endif
  2352. } else if (process_type == switches::kGpuProcess) {
  2353. // If --ignore-gpu-blocklist is passed in, don't send in crash reports
  2354. // because GPU is expected to be unreliable.
  2355. if (browser_command_line.HasSwitch(switches::kIgnoreGpuBlocklist) &&
  2356. !command_line->HasSwitch(switches::kDisableBreakpad))
  2357. command_line->AppendSwitch(switches::kDisableBreakpad);
  2358. }
  2359. #if BUILDFLAG(IS_CHROMEOS_ASH)
  2360. if (ChromeCrashReporterClient::ShouldPassCrashLoopBefore(process_type)) {
  2361. static const char* const kSwitchNames[] = {
  2362. crash_reporter::switches::kCrashLoopBefore,
  2363. };
  2364. command_line->CopySwitchesFrom(browser_command_line, kSwitchNames,
  2365. std::size(kSwitchNames));
  2366. }
  2367. #endif
  2368. ThreadProfilerConfiguration::Get()->AppendCommandLineSwitchForChildProcess(
  2369. command_line);
  2370. #if BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS_ASH)
  2371. // Opt into a hardened stack canary mitigation if it hasn't already been
  2372. // force-disabled.
  2373. if (!browser_command_line.HasSwitch(switches::kChangeStackGuardOnFork)) {
  2374. command_line->AppendSwitchASCII(switches::kChangeStackGuardOnFork,
  2375. switches::kChangeStackGuardOnForkEnabled);
  2376. }
  2377. #endif // BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS)
  2378. #if BUILDFLAG(IS_ANDROID)
  2379. if (browser_command_line.HasSwitch(
  2380. autofill_assistant::switches::kAutofillAssistantDebugAnnotateDom)) {
  2381. command_line->AppendSwitch(
  2382. autofill_assistant::switches::kAutofillAssistantDebugAnnotateDom);
  2383. }
  2384. #endif // BUILDFLAG(IS_ANDROID)
  2385. }
  2386. std::string
  2387. ChromeContentBrowserClient::GetApplicationClientGUIDForQuarantineCheck() {
  2388. return std::string(chrome::kApplicationClientIDStringForAVScanning);
  2389. }
  2390. download::QuarantineConnectionCallback
  2391. ChromeContentBrowserClient::GetQuarantineConnectionCallback() {
  2392. return base::BindRepeating(
  2393. &ChromeDownloadManagerDelegate::ConnectToQuarantineService);
  2394. }
  2395. std::string ChromeContentBrowserClient::GetApplicationLocale() {
  2396. if (BrowserThread::CurrentlyOn(BrowserThread::IO))
  2397. return GetIOThreadApplicationLocale();
  2398. return g_browser_process->GetApplicationLocale();
  2399. }
  2400. std::string ChromeContentBrowserClient::GetAcceptLangs(
  2401. content::BrowserContext* context) {
  2402. Profile* profile = Profile::FromBrowserContext(context);
  2403. return profile->GetPrefs()->GetString(language::prefs::kAcceptLanguages);
  2404. }
  2405. gfx::ImageSkia ChromeContentBrowserClient::GetDefaultFavicon() {
  2406. return favicon::GetDefaultFavicon().AsImageSkia();
  2407. }
  2408. bool ChromeContentBrowserClient::IsDataSaverEnabled(
  2409. content::BrowserContext* browser_context) {
  2410. if (!browser_context || browser_context->IsOffTheRecord())
  2411. return false;
  2412. return data_saver::IsDataSaverEnabled(browser_context);
  2413. }
  2414. void ChromeContentBrowserClient::UpdateRendererPreferencesForWorker(
  2415. content::BrowserContext* browser_context,
  2416. blink::RendererPreferences* out_prefs) {
  2417. DCHECK(browser_context);
  2418. DCHECK(out_prefs);
  2419. renderer_preferences_util::UpdateFromSystemSettings(
  2420. out_prefs, Profile::FromBrowserContext(browser_context));
  2421. }
  2422. content::AllowServiceWorkerResult
  2423. ChromeContentBrowserClient::AllowServiceWorker(
  2424. const GURL& scope,
  2425. const net::SiteForCookies& site_for_cookies,
  2426. const absl::optional<url::Origin>& top_frame_origin,
  2427. const GURL& script_url,
  2428. content::BrowserContext* context) {
  2429. DCHECK(context);
  2430. DCHECK_CURRENTLY_ON(BrowserThread::UI);
  2431. GURL first_party_url = top_frame_origin ? top_frame_origin->GetURL() : GURL();
  2432. #if BUILDFLAG(ENABLE_EXTENSIONS)
  2433. // Check if this is an extension-related service worker, and, if so, if it's
  2434. // allowed (this can return false if, e.g., the extension is disabled).
  2435. // If it's not allowed, return immediately. We deliberately do *not* report
  2436. // to the PageSpecificContentSettings, since the service worker is blocked
  2437. // because of the extension, rather than because of the user's content
  2438. // settings.
  2439. if (!ChromeContentBrowserClientExtensionsPart::AllowServiceWorker(
  2440. scope, first_party_url, script_url, context)) {
  2441. return content::AllowServiceWorkerResult::No();
  2442. }
  2443. #endif
  2444. Profile* profile = Profile::FromBrowserContext(context);
  2445. return embedder_support::AllowServiceWorker(
  2446. scope, site_for_cookies, top_frame_origin,
  2447. CookieSettingsFactory::GetForProfile(profile).get(),
  2448. HostContentSettingsMapFactory::GetForProfile(profile));
  2449. }
  2450. void ChromeContentBrowserClient::
  2451. UpdateEnabledBlinkRuntimeFeaturesInIsolatedWorker(
  2452. content::BrowserContext* context,
  2453. const GURL& script_url,
  2454. std::vector<std::string>& out_forced_enabled_runtime_features) {
  2455. DCHECK(context);
  2456. #if BUILDFLAG(IS_CHROMEOS_ASH)
  2457. auto* profile = Profile::FromBrowserContext(context);
  2458. if (!ash::IsSystemExtensionsEnabled(profile))
  2459. return;
  2460. ash::SystemExtensionsProvider::Get(profile)
  2461. .UpdateEnabledBlinkRuntimeFeaturesInIsolatedWorker(
  2462. script_url, out_forced_enabled_runtime_features);
  2463. #endif // BUILDFLAG(IS_CHROMEOS_ASH)
  2464. }
  2465. bool ChromeContentBrowserClient::AllowSharedWorker(
  2466. const GURL& worker_url,
  2467. const net::SiteForCookies& site_for_cookies,
  2468. const absl::optional<url::Origin>& top_frame_origin,
  2469. const std::string& name,
  2470. const blink::StorageKey& storage_key,
  2471. content::BrowserContext* context,
  2472. int render_process_id,
  2473. int render_frame_id) {
  2474. DCHECK_CURRENTLY_ON(BrowserThread::UI);
  2475. // Check if cookies are allowed.
  2476. return embedder_support::AllowSharedWorker(
  2477. worker_url, site_for_cookies, top_frame_origin, name, storage_key,
  2478. render_process_id, render_frame_id,
  2479. CookieSettingsFactory::GetForProfile(Profile::FromBrowserContext(context))
  2480. .get());
  2481. }
  2482. bool ChromeContentBrowserClient::DoesSchemeAllowCrossOriginSharedWorker(
  2483. const std::string& scheme) {
  2484. #if BUILDFLAG(ENABLE_EXTENSIONS)
  2485. // Extensions are allowed to start cross-origin shared workers.
  2486. if (scheme == extensions::kExtensionScheme)
  2487. return true;
  2488. #endif
  2489. return false;
  2490. }
  2491. bool ChromeContentBrowserClient::AllowSignedExchange(
  2492. content::BrowserContext* browser_context) {
  2493. DCHECK_CURRENTLY_ON(BrowserThread::UI);
  2494. Profile* profile = Profile::FromBrowserContext(browser_context);
  2495. return profile->GetPrefs()->GetBoolean(prefs::kSignedHTTPExchangeEnabled);
  2496. }
  2497. void ChromeContentBrowserClient::RequestFilesAccess(
  2498. const std::vector<base::FilePath>& files,
  2499. const GURL& destination_url,
  2500. base::OnceCallback<void(file_access::ScopedFileAccess)>
  2501. continuation_callback) {
  2502. DCHECK_CURRENTLY_ON(BrowserThread::UI);
  2503. #if BUILDFLAG(IS_CHROMEOS)
  2504. auto* delegate = policy::DlpScopedFileAccessDelegate::Get();
  2505. if (delegate) {
  2506. delegate->RequestFilesAccess(files, destination_url,
  2507. std::move(continuation_callback));
  2508. } else {
  2509. std::move(continuation_callback)
  2510. .Run(file_access::ScopedFileAccess::Allowed());
  2511. }
  2512. #else
  2513. std::move(continuation_callback)
  2514. .Run(file_access::ScopedFileAccess::Allowed());
  2515. #endif
  2516. }
  2517. void ChromeContentBrowserClient::AllowWorkerFileSystem(
  2518. const GURL& url,
  2519. content::BrowserContext* browser_context,
  2520. const std::vector<content::GlobalRenderFrameHostId>& render_frames,
  2521. base::OnceCallback<void(bool)> callback) {
  2522. // An empty list is passed for render_frames here since we manually notify
  2523. // PageSpecificContentSettings that the file system was accessed below.
  2524. bool allow = embedder_support::AllowWorkerFileSystem(
  2525. url, {},
  2526. CookieSettingsFactory::GetForProfile(
  2527. Profile::FromBrowserContext(browser_context))
  2528. .get());
  2529. #if BUILDFLAG(ENABLE_EXTENSIONS)
  2530. GuestPermissionRequestHelper(url, render_frames, std::move(callback), allow);
  2531. #else
  2532. FileSystemAccessed(url, render_frames, std::move(callback), allow);
  2533. #endif
  2534. }
  2535. #if BUILDFLAG(ENABLE_EXTENSIONS)
  2536. void ChromeContentBrowserClient::GuestPermissionRequestHelper(
  2537. const GURL& url,
  2538. const std::vector<content::GlobalRenderFrameHostId>& render_frames,
  2539. base::OnceCallback<void(bool)> callback,
  2540. bool allow) {
  2541. DCHECK_CURRENTLY_ON(BrowserThread::UI);
  2542. std::map<int, int> process_map;
  2543. bool has_web_view_guest = false;
  2544. // Record access to file system for potential display in UI.
  2545. for (const auto& it : render_frames) {
  2546. if (process_map.find(it.child_id) != process_map.end())
  2547. continue;
  2548. process_map.insert(std::pair<int, int>(it.child_id, it.frame_routing_id));
  2549. if (extensions::WebViewRendererState::GetInstance()->IsGuest(it.child_id))
  2550. has_web_view_guest = true;
  2551. }
  2552. if (!has_web_view_guest) {
  2553. FileSystemAccessed(url, render_frames, std::move(callback), allow);
  2554. return;
  2555. }
  2556. DCHECK_EQ(1U, process_map.size());
  2557. std::map<int, int>::const_iterator it = process_map.begin();
  2558. extensions::WebViewPermissionHelper* web_view_permission_helper =
  2559. extensions::WebViewPermissionHelper::FromFrameID(it->first, it->second);
  2560. web_view_permission_helper->RequestFileSystemPermission(
  2561. url, allow,
  2562. base::BindOnce(&ChromeContentBrowserClient::FileSystemAccessed,
  2563. weak_factory_.GetWeakPtr(), url, render_frames,
  2564. std::move(callback)));
  2565. }
  2566. #endif
  2567. void ChromeContentBrowserClient::FileSystemAccessed(
  2568. const GURL& url,
  2569. const std::vector<content::GlobalRenderFrameHostId>& render_frames,
  2570. base::OnceCallback<void(bool)> callback,
  2571. bool allow) {
  2572. // Record access to file system for potential display in UI.
  2573. for (const auto& it : render_frames) {
  2574. content_settings::PageSpecificContentSettings::StorageAccessed(
  2575. content_settings::mojom::ContentSettingsManager::StorageType::
  2576. FILE_SYSTEM,
  2577. it.child_id, it.frame_routing_id, url, !allow);
  2578. }
  2579. std::move(callback).Run(allow);
  2580. }
  2581. bool ChromeContentBrowserClient::AllowWorkerIndexedDB(
  2582. const GURL& url,
  2583. content::BrowserContext* browser_context,
  2584. const std::vector<content::GlobalRenderFrameHostId>& render_frames) {
  2585. return embedder_support::AllowWorkerIndexedDB(
  2586. url, render_frames,
  2587. CookieSettingsFactory::GetForProfile(
  2588. Profile::FromBrowserContext(browser_context))
  2589. .get());
  2590. }
  2591. bool ChromeContentBrowserClient::AllowWorkerCacheStorage(
  2592. const GURL& url,
  2593. content::BrowserContext* browser_context,
  2594. const std::vector<content::GlobalRenderFrameHostId>& render_frames) {
  2595. return embedder_support::AllowWorkerCacheStorage(
  2596. url, render_frames,
  2597. CookieSettingsFactory::GetForProfile(
  2598. Profile::FromBrowserContext(browser_context))
  2599. .get());
  2600. }
  2601. bool ChromeContentBrowserClient::AllowWorkerWebLocks(
  2602. const GURL& url,
  2603. content::BrowserContext* browser_context,
  2604. const std::vector<content::GlobalRenderFrameHostId>& render_frames) {
  2605. return embedder_support::AllowWorkerWebLocks(
  2606. url, CookieSettingsFactory::GetForProfile(
  2607. Profile::FromBrowserContext(browser_context))
  2608. .get());
  2609. }
  2610. ChromeContentBrowserClient::AllowWebBluetoothResult
  2611. ChromeContentBrowserClient::AllowWebBluetooth(
  2612. content::BrowserContext* browser_context,
  2613. const url::Origin& requesting_origin,
  2614. const url::Origin& embedding_origin) {
  2615. // TODO(crbug.com/598890): Don't disable if
  2616. // base::CommandLine::ForCurrentProcess()->
  2617. // HasSwitch(switches::kEnableWebBluetooth) is true.
  2618. if (variations::GetVariationParamValue(
  2619. permissions::PermissionContextBase::kPermissionsKillSwitchFieldStudy,
  2620. "Bluetooth") ==
  2621. permissions::PermissionContextBase::kPermissionsKillSwitchBlockedValue) {
  2622. // The kill switch is enabled for this permission. Block requests.
  2623. return AllowWebBluetoothResult::BLOCK_GLOBALLY_DISABLED;
  2624. }
  2625. const HostContentSettingsMap* const content_settings =
  2626. HostContentSettingsMapFactory::GetForProfile(
  2627. Profile::FromBrowserContext(browser_context));
  2628. if (content_settings->GetContentSetting(
  2629. requesting_origin.GetURL(), embedding_origin.GetURL(),
  2630. ContentSettingsType::BLUETOOTH_GUARD) == CONTENT_SETTING_BLOCK) {
  2631. return AllowWebBluetoothResult::BLOCK_POLICY;
  2632. }
  2633. return AllowWebBluetoothResult::ALLOW;
  2634. }
  2635. std::string ChromeContentBrowserClient::GetWebBluetoothBlocklist() {
  2636. return variations::GetVariationParamValue("WebBluetoothBlocklist",
  2637. "blocklist_additions");
  2638. }
  2639. bool ChromeContentBrowserClient::IsInterestGroupAPIAllowed(
  2640. content::RenderFrameHost* render_frame_host,
  2641. InterestGroupApiOperation operation,
  2642. const url::Origin& top_frame_origin,
  2643. const url::Origin& api_origin) {
  2644. Profile* profile =
  2645. Profile::FromBrowserContext(render_frame_host->GetBrowserContext());
  2646. auto* privacy_sandbox_settings =
  2647. PrivacySandboxSettingsFactory::GetForProfile(profile);
  2648. DCHECK(privacy_sandbox_settings);
  2649. // Join operations are subject to an additional check.
  2650. bool join_blocked =
  2651. operation == InterestGroupApiOperation::kJoin
  2652. ? !privacy_sandbox_settings->IsFledgeJoiningAllowed(top_frame_origin)
  2653. : false;
  2654. bool allowed =
  2655. privacy_sandbox_settings->IsFledgeAllowed(top_frame_origin, api_origin) &&
  2656. !join_blocked;
  2657. if (operation == InterestGroupApiOperation::kJoin) {
  2658. content_settings::PageSpecificContentSettings::InterestGroupJoined(
  2659. render_frame_host, api_origin, !allowed);
  2660. }
  2661. return allowed;
  2662. }
  2663. bool ChromeContentBrowserClient::IsConversionMeasurementOperationAllowed(
  2664. content::BrowserContext* browser_context,
  2665. ConversionMeasurementOperation operation,
  2666. const url::Origin* impression_origin,
  2667. const url::Origin* conversion_origin,
  2668. const url::Origin* reporting_origin) {
  2669. Profile* profile = Profile::FromBrowserContext(browser_context);
  2670. auto* privacy_sandbox_settings =
  2671. PrivacySandboxSettingsFactory::GetForProfile(profile);
  2672. if (!privacy_sandbox_settings)
  2673. return false;
  2674. switch (operation) {
  2675. case ConversionMeasurementOperation::kImpression:
  2676. DCHECK(impression_origin);
  2677. DCHECK(reporting_origin);
  2678. return privacy_sandbox_settings->IsConversionMeasurementAllowed(
  2679. *impression_origin, *reporting_origin);
  2680. case ConversionMeasurementOperation::kConversion:
  2681. DCHECK(conversion_origin);
  2682. DCHECK(reporting_origin);
  2683. return privacy_sandbox_settings->IsConversionMeasurementAllowed(
  2684. *conversion_origin, *reporting_origin);
  2685. case ConversionMeasurementOperation::kReport:
  2686. DCHECK(impression_origin);
  2687. DCHECK(conversion_origin);
  2688. DCHECK(reporting_origin);
  2689. return privacy_sandbox_settings->ShouldSendConversionReport(
  2690. *impression_origin, *conversion_origin, *reporting_origin);
  2691. case ConversionMeasurementOperation::kAny:
  2692. return privacy_sandbox_settings->IsPrivacySandboxEnabled();
  2693. }
  2694. }
  2695. bool ChromeContentBrowserClient::IsSharedStorageAllowed(
  2696. content::BrowserContext* browser_context,
  2697. const url::Origin& top_frame_origin,
  2698. const url::Origin& accessing_origin) {
  2699. Profile* profile = Profile::FromBrowserContext(browser_context);
  2700. auto* privacy_sandbox_settings =
  2701. PrivacySandboxSettingsFactory::GetForProfile(profile);
  2702. DCHECK(privacy_sandbox_settings);
  2703. return privacy_sandbox_settings->IsSharedStorageAllowed(top_frame_origin,
  2704. accessing_origin);
  2705. }
  2706. bool ChromeContentBrowserClient::IsPrivateAggregationAllowed(
  2707. content::BrowserContext* browser_context,
  2708. const url::Origin& top_frame_origin,
  2709. const url::Origin& reporting_origin) {
  2710. Profile* profile = Profile::FromBrowserContext(browser_context);
  2711. auto* privacy_sandbox_settings =
  2712. PrivacySandboxSettingsFactory::GetForProfile(profile);
  2713. DCHECK(privacy_sandbox_settings);
  2714. return privacy_sandbox_settings->IsPrivateAggregationAllowed(
  2715. top_frame_origin, reporting_origin);
  2716. }
  2717. #if BUILDFLAG(IS_CHROMEOS)
  2718. void ChromeContentBrowserClient::OnTrustAnchorUsed(
  2719. content::BrowserContext* browser_context) {
  2720. policy::PolicyCertService* service =
  2721. policy::PolicyCertServiceFactory::GetForProfile(
  2722. Profile::FromBrowserContext(browser_context));
  2723. if (!service) {
  2724. NOTREACHED();
  2725. return;
  2726. }
  2727. service->SetUsedPolicyCertificates();
  2728. }
  2729. #endif
  2730. bool ChromeContentBrowserClient::CanSendSCTAuditingReport(
  2731. content::BrowserContext* browser_context) {
  2732. return SCTReportingService::CanSendSCTAuditingReport();
  2733. }
  2734. void ChromeContentBrowserClient::OnNewSCTAuditingReportSent(
  2735. content::BrowserContext* browser_context) {
  2736. SCTReportingService::OnNewSCTAuditingReportSent();
  2737. }
  2738. scoped_refptr<network::SharedURLLoaderFactory>
  2739. ChromeContentBrowserClient::GetSystemSharedURLLoaderFactory() {
  2740. DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI) ||
  2741. !BrowserThread::IsThreadInitialized(BrowserThread::UI));
  2742. if (!SystemNetworkContextManager::GetInstance())
  2743. return nullptr;
  2744. return SystemNetworkContextManager::GetInstance()
  2745. ->GetSharedURLLoaderFactory();
  2746. }
  2747. network::mojom::NetworkContext*
  2748. ChromeContentBrowserClient::GetSystemNetworkContext() {
  2749. DCHECK_CURRENTLY_ON(BrowserThread::UI);
  2750. DCHECK(g_browser_process->system_network_context_manager());
  2751. return g_browser_process->system_network_context_manager()->GetContext();
  2752. }
  2753. std::string ChromeContentBrowserClient::GetGeolocationApiKey() {
  2754. return google_apis::GetAPIKey();
  2755. }
  2756. device::GeolocationManager*
  2757. ChromeContentBrowserClient::GetGeolocationManager() {
  2758. #if BUILDFLAG(IS_MAC)
  2759. return g_browser_process->platform_part()->geolocation_manager();
  2760. #else
  2761. return nullptr;
  2762. #endif
  2763. }
  2764. #if BUILDFLAG(IS_ANDROID)
  2765. bool ChromeContentBrowserClient::ShouldUseGmsCoreGeolocationProvider() {
  2766. // Indicate that Chrome uses the GMS core location provider.
  2767. return true;
  2768. }
  2769. #endif
  2770. scoped_refptr<content::QuotaPermissionContext>
  2771. ChromeContentBrowserClient::CreateQuotaPermissionContext() {
  2772. return new permissions::QuotaPermissionContextImpl();
  2773. }
  2774. content::GeneratedCodeCacheSettings
  2775. ChromeContentBrowserClient::GetGeneratedCodeCacheSettings(
  2776. content::BrowserContext* context) {
  2777. base::FilePath cache_path;
  2778. chrome::GetUserCacheDirectory(context->GetPath(), &cache_path);
  2779. // If we pass 0 for size, disk_cache will pick a default size using the
  2780. // heuristics based on available disk size. These are implemented in
  2781. // disk_cache::PreferredCacheSize in net/disk_cache/cache_util.cc.
  2782. int64_t size_in_bytes = 0;
  2783. DCHECK(g_browser_process);
  2784. PrefService* local_state = g_browser_process->local_state();
  2785. if (local_state) {
  2786. size_in_bytes = local_state->GetInteger(prefs::kDiskCacheSize);
  2787. base::FilePath disk_cache_dir =
  2788. local_state->GetFilePath(prefs::kDiskCacheDir);
  2789. if (!disk_cache_dir.empty())
  2790. cache_path = disk_cache_dir.Append(cache_path.BaseName());
  2791. }
  2792. return content::GeneratedCodeCacheSettings(true, size_in_bytes, cache_path);
  2793. }
  2794. void ChromeContentBrowserClient::AllowCertificateError(
  2795. content::WebContents* web_contents,
  2796. int cert_error,
  2797. const net::SSLInfo& ssl_info,
  2798. const GURL& request_url,
  2799. bool is_primary_main_frame_request,
  2800. bool strict_enforcement,
  2801. base::OnceCallback<void(content::CertificateRequestResultType)> callback) {
  2802. DCHECK(web_contents);
  2803. if (!is_primary_main_frame_request) {
  2804. // A sub-resource has a certificate error. The user doesn't really
  2805. // have a context for making the right decision, so block the
  2806. // request hard, without an info bar to allow showing the insecure
  2807. // content.
  2808. if (!callback.is_null())
  2809. std::move(callback).Run(content::CERTIFICATE_REQUEST_RESULT_TYPE_DENY);
  2810. return;
  2811. }
  2812. // If the tab is being no-state prefetched, cancel the prefetcher and the
  2813. // request.
  2814. prerender::NoStatePrefetchContents* no_state_prefetch_contents =
  2815. prerender::ChromeNoStatePrefetchContentsDelegate::FromWebContents(
  2816. web_contents);
  2817. if (no_state_prefetch_contents) {
  2818. no_state_prefetch_contents->Destroy(prerender::FINAL_STATUS_SSL_ERROR);
  2819. if (!callback.is_null()) {
  2820. std::move(callback).Run(content::CERTIFICATE_REQUEST_RESULT_TYPE_CANCEL);
  2821. }
  2822. return;
  2823. }
  2824. std::move(callback).Run(content::CERTIFICATE_REQUEST_RESULT_TYPE_DENY);
  2825. return;
  2826. }
  2827. #if !BUILDFLAG(IS_ANDROID)
  2828. bool ChromeContentBrowserClient::ShouldDenyRequestOnCertificateError(
  2829. const GURL main_page_url) {
  2830. // Desktop Reader Mode pages should never load resources with certificate
  2831. // errors. Desktop Reader Mode is more strict about security than Reader Mode
  2832. // on Android: the desktop version has its own security indicator and
  2833. // is not downgraded to a WARNING, whereas Android will show "Not secure"
  2834. // in the omnibox (for low-end devices which show the omnibox on Reader Mode
  2835. // pages).
  2836. return main_page_url.SchemeIs(dom_distiller::kDomDistillerScheme);
  2837. }
  2838. #endif
  2839. namespace {
  2840. #if !BUILDFLAG(IS_ANDROID)
  2841. blink::mojom::PreferredColorScheme ToBlinkPreferredColorScheme(
  2842. ui::NativeTheme::PreferredColorScheme native_theme_scheme) {
  2843. switch (native_theme_scheme) {
  2844. case ui::NativeTheme::PreferredColorScheme::kDark:
  2845. return blink::mojom::PreferredColorScheme::kDark;
  2846. case ui::NativeTheme::PreferredColorScheme::kLight:
  2847. return blink::mojom::PreferredColorScheme::kLight;
  2848. }
  2849. NOTREACHED();
  2850. }
  2851. #endif // !BUILDFLAG(IS_ANDROID)
  2852. // Returns true if preferred color scheme is modified based on at least one of
  2853. // the following -
  2854. // |url| - Last committed url.
  2855. // |web_contents| - For Android based on IsNightModeEnabled().
  2856. // |native_theme| - For other platforms based on native theme scheme.
  2857. bool UpdatePreferredColorScheme(WebPreferences* web_prefs,
  2858. const GURL& url,
  2859. WebContents* web_contents,
  2860. const ui::NativeTheme* native_theme) {
  2861. auto old_preferred_color_scheme = web_prefs->preferred_color_scheme;
  2862. #if BUILDFLAG(IS_ANDROID)
  2863. auto* delegate = TabAndroid::FromWebContents(web_contents)
  2864. ? static_cast<android::TabWebContentsDelegateAndroid*>(
  2865. web_contents->GetDelegate())
  2866. : nullptr;
  2867. if (delegate) {
  2868. web_prefs->preferred_color_scheme =
  2869. delegate->IsNightModeEnabled()
  2870. ? blink::mojom::PreferredColorScheme::kDark
  2871. : blink::mojom::PreferredColorScheme::kLight;
  2872. }
  2873. #else
  2874. // Update based on native theme scheme.
  2875. web_prefs->preferred_color_scheme =
  2876. ToBlinkPreferredColorScheme(native_theme->GetPreferredColorScheme());
  2877. #endif // BUILDFLAG(IS_ANDROID)
  2878. bool force_light = false;
  2879. // Force a light preferred color scheme on certain URLs if kWebUIDarkMode is
  2880. // disabled; some of the UI is not yet correctly themed.
  2881. if (!base::FeatureList::IsEnabled(features::kWebUIDarkMode)) {
  2882. // Update based on last committed url.
  2883. force_light = force_light || url.SchemeIs(content::kChromeUIScheme);
  2884. force_light = force_light || IsPdfExtensionOrigin(url::Origin::Create(url));
  2885. }
  2886. // Reauth WebUI doesn't support dark mode yet because it shares the dialog
  2887. // with GAIA web contents that is not correctly themed.
  2888. force_light =
  2889. force_light || (url.SchemeIs(content::kChromeUIScheme) &&
  2890. url.host_piece() == chrome::kChromeUISigninReauthHost);
  2891. if (force_light) {
  2892. web_prefs->preferred_color_scheme =
  2893. blink::mojom::PreferredColorScheme::kLight;
  2894. }
  2895. return old_preferred_color_scheme != web_prefs->preferred_color_scheme;
  2896. }
  2897. // Returns whether the user can be prompted to select a client certificate after
  2898. // no certificate got auto-selected.
  2899. bool CanPromptWithNonmatchingCertificates(const Profile* profile) {
  2900. #if BUILDFLAG(IS_CHROMEOS_ASH)
  2901. if (ash::ProfileHelper::IsSigninProfile(profile) ||
  2902. ash::ProfileHelper::IsLockScreenProfile(profile) ||
  2903. ash::ProfileHelper::IsLockScreenAppProfile(profile)) {
  2904. // On non-regular profiles (e.g. sign-in profile or lock-screen profile),
  2905. // never show certificate selection to the user. A client certificate is an
  2906. // identifier that can be stable for a long time, so only the administrator
  2907. // is allowed to decide which endpoints should see it.
  2908. // This also returns false for the lock screen app profile which can
  2909. // not use client certificates anyway - to be on the safe side in case
  2910. // support for client certificates is added later.
  2911. return false;
  2912. }
  2913. #endif
  2914. return true;
  2915. }
  2916. // Returns whether the user should be prompted to select a client certificate
  2917. // when multiple certificates got auto-selected.
  2918. bool ShouldPromptOnMultipleMatchingCertificates(const Profile* profile) {
  2919. const PrefService* const prefs = profile->GetPrefs();
  2920. DCHECK(prefs);
  2921. const PrefService::Preference* pref =
  2922. prefs->FindPreference(prefs::kPromptOnMultipleMatchingCertificates);
  2923. if (pref && pref->IsManaged() && pref->GetValue()->is_bool())
  2924. return pref->GetValue()->GetBool();
  2925. return false;
  2926. }
  2927. } // namespace
  2928. base::OnceClosure ChromeContentBrowserClient::SelectClientCertificate(
  2929. content::WebContents* web_contents,
  2930. net::SSLCertRequestInfo* cert_request_info,
  2931. net::ClientCertIdentityList client_certs,
  2932. std::unique_ptr<content::ClientCertificateDelegate> delegate) {
  2933. prerender::NoStatePrefetchContents* no_state_prefetch_contents =
  2934. prerender::ChromeNoStatePrefetchContentsDelegate::FromWebContents(
  2935. web_contents);
  2936. if (no_state_prefetch_contents) {
  2937. no_state_prefetch_contents->Destroy(
  2938. prerender::FINAL_STATUS_SSL_CLIENT_CERTIFICATE_REQUESTED);
  2939. return base::OnceClosure();
  2940. }
  2941. GURL requesting_url("https://" + cert_request_info->host_and_port.ToString());
  2942. DCHECK(requesting_url.is_valid())
  2943. << "Invalid URL string: https://"
  2944. << cert_request_info->host_and_port.ToString();
  2945. Profile* profile =
  2946. Profile::FromBrowserContext(web_contents->GetBrowserContext());
  2947. #if BUILDFLAG(IS_CHROMEOS_ASH)
  2948. // On the sign-in or lock screen profile, only allow client certs in the
  2949. // context of the sign-in frame.
  2950. // Note that this is explicitly not happening for the lock screen app profile
  2951. // which does not support a gaia / SAML IdP sign-in frame.
  2952. if (ash::ProfileHelper::IsSigninProfile(profile) ||
  2953. ash::ProfileHelper::IsLockScreenProfile(profile)) {
  2954. const char* profile_name = ash::ProfileHelper::IsSigninProfile(profile)
  2955. ? "sign-in"
  2956. : "lock screen";
  2957. content::StoragePartition* storage_partition =
  2958. profile->GetStoragePartition(web_contents->GetSiteInstance());
  2959. auto* signin_partition_manager =
  2960. ash::login::SigninPartitionManager::Factory::GetForBrowserContext(
  2961. profile);
  2962. if (!signin_partition_manager->IsCurrentSigninStoragePartition(
  2963. storage_partition)) {
  2964. LOG(WARNING) << "Client cert requested in " << profile_name
  2965. << " profile in wrong context.";
  2966. // Continue without client certificate. We do this to mimic the case of no
  2967. // client certificate being present in the profile's certificate store.
  2968. delegate->ContinueWithCertificate(nullptr, nullptr);
  2969. return base::OnceClosure();
  2970. }
  2971. VLOG(1) << "Client cert requested in " << profile_name << " profile.";
  2972. }
  2973. #endif // BUILDFLAG(IS_CHROMEOS_ASH)
  2974. net::ClientCertIdentityList matching_certificates, nonmatching_certificates;
  2975. chrome::enterprise_util::AutoSelectCertificates(
  2976. profile, requesting_url, std::move(client_certs), &matching_certificates,
  2977. &nonmatching_certificates);
  2978. if (matching_certificates.size() == 1 ||
  2979. (matching_certificates.size() > 1 &&
  2980. !ShouldPromptOnMultipleMatchingCertificates(profile))) {
  2981. // Always take the first certificate, even if multiple ones matched -
  2982. // there's no other criteria available for tie-breaking, and user prompts
  2983. // aren't enabled.
  2984. std::unique_ptr<net::ClientCertIdentity> auto_selected_identity =
  2985. std::move(matching_certificates[0]);
  2986. // The callback will own |auto_selected_identity| and |delegate|, keeping
  2987. // them alive until after ContinueWithCertificate is called.
  2988. scoped_refptr<net::X509Certificate> cert =
  2989. auto_selected_identity->certificate();
  2990. net::ClientCertIdentity::SelfOwningAcquirePrivateKey(
  2991. std::move(auto_selected_identity),
  2992. base::BindOnce(
  2993. &content::ClientCertificateDelegate::ContinueWithCertificate,
  2994. std::move(delegate), std::move(cert)));
  2995. LogClientAuthResult(ClientCertSelectionResult::kAutoSelect);
  2996. return base::OnceClosure();
  2997. }
  2998. if (matching_certificates.empty() &&
  2999. !CanPromptWithNonmatchingCertificates(profile)) {
  3000. LOG(WARNING) << "No client cert matched by policy and user selection is "
  3001. "not allowed.";
  3002. LogClientAuthResult(ClientCertSelectionResult::kNoSelectionAllowed);
  3003. // Continue without client certificate. We do this to mimic the case of no
  3004. // client certificate being present in the profile's certificate store.
  3005. delegate->ContinueWithCertificate(nullptr, nullptr);
  3006. return base::OnceClosure();
  3007. }
  3008. // Note: It can happen that both lists are empty, still the selector needs to
  3009. // be shown - see the comment in SSLClientAuthHandler::DidGetClientCerts()
  3010. // about platforms not having a client cert store.
  3011. net::ClientCertIdentityList client_cert_choices =
  3012. !matching_certificates.empty() ? std::move(matching_certificates)
  3013. : std::move(nonmatching_certificates);
  3014. return chrome::ShowSSLClientCertificateSelector(
  3015. web_contents, cert_request_info, std::move(client_cert_choices),
  3016. std::move(delegate));
  3017. }
  3018. content::MediaObserver* ChromeContentBrowserClient::GetMediaObserver() {
  3019. return MediaCaptureDevicesDispatcher::GetInstance();
  3020. }
  3021. content::FeatureObserverClient*
  3022. ChromeContentBrowserClient::GetFeatureObserverClient() {
  3023. return ChromeBrowserMainExtraPartsPerformanceManager::GetInstance()
  3024. ->GetFeatureObserverClient();
  3025. }
  3026. bool ChromeContentBrowserClient::CanCreateWindow(
  3027. RenderFrameHost* opener,
  3028. const GURL& opener_url,
  3029. const GURL& opener_top_level_frame_url,
  3030. const url::Origin& source_origin,
  3031. content::mojom::WindowContainerType container_type,
  3032. const GURL& target_url,
  3033. const content::Referrer& referrer,
  3034. const std::string& frame_name,
  3035. WindowOpenDisposition disposition,
  3036. const blink::mojom::WindowFeatures& features,
  3037. bool user_gesture,
  3038. bool opener_suppressed,
  3039. bool* no_javascript_access) {
  3040. DCHECK_CURRENTLY_ON(BrowserThread::UI);
  3041. DCHECK(opener);
  3042. content::WebContents* web_contents =
  3043. content::WebContents::FromRenderFrameHost(opener);
  3044. Profile* profile =
  3045. Profile::FromBrowserContext(web_contents->GetBrowserContext());
  3046. DCHECK(profile);
  3047. *no_javascript_access = false;
  3048. // If the opener is trying to create a background window but doesn't have
  3049. // the appropriate permission, fail the attempt.
  3050. if (container_type == content::mojom::WindowContainerType::BACKGROUND) {
  3051. #if BUILDFLAG(ENABLE_EXTENSIONS)
  3052. auto* process_map = extensions::ProcessMap::Get(profile);
  3053. auto* registry = extensions::ExtensionRegistry::Get(profile);
  3054. if (!URLHasExtensionPermission(process_map, registry, opener_url,
  3055. opener->GetProcess()->GetID(),
  3056. APIPermissionID::kBackground)) {
  3057. return false;
  3058. }
  3059. // Note: this use of GetExtensionOrAppByURL is safe but imperfect. It may
  3060. // return a recently installed Extension even if this CanCreateWindow call
  3061. // was made by an old copy of the page in a normal web process. That's ok,
  3062. // because the permission check above would have caused an early return
  3063. // already. We must use the full URL to find hosted apps, though, and not
  3064. // just the origin.
  3065. const Extension* extension =
  3066. registry->enabled_extensions().GetExtensionOrAppByURL(opener_url);
  3067. if (extension && !extensions::BackgroundInfo::AllowJSAccess(extension))
  3068. *no_javascript_access = true;
  3069. #endif
  3070. return true;
  3071. }
  3072. #if BUILDFLAG(ENABLE_EXTENSIONS)
  3073. if (extensions::WebViewRendererState::GetInstance()->IsGuest(
  3074. opener->GetProcess()->GetID())) {
  3075. return true;
  3076. }
  3077. if (target_url.SchemeIs(extensions::kExtensionScheme)) {
  3078. // Intentionally duplicating |registry| code from above because we want to
  3079. // reduce calls to retrieve them as this function is a SYNC IPC handler.
  3080. auto* registry = extensions::ExtensionRegistry::Get(profile);
  3081. const Extension* extension =
  3082. registry->enabled_extensions().GetExtensionOrAppByURL(target_url);
  3083. if (extension && extension->is_platform_app()) {
  3084. UMA_HISTOGRAM_ENUMERATION(
  3085. "Extensions.AppLoadedInTab",
  3086. ClassifyAppLoadedInTabSource(opener_url, extension),
  3087. APP_LOADED_IN_TAB_SOURCE_MAX);
  3088. // window.open() may not be used to load v2 apps in a regular tab.
  3089. return false;
  3090. }
  3091. }
  3092. #endif
  3093. DCHECK(!prerender::ChromeNoStatePrefetchContentsDelegate::FromWebContents(
  3094. web_contents));
  3095. BlockedWindowParams blocked_params(
  3096. target_url, source_origin, opener->GetSiteInstance(), referrer,
  3097. frame_name, disposition, features, user_gesture, opener_suppressed);
  3098. NavigateParams nav_params =
  3099. blocked_params.CreateNavigateParams(opener->GetProcess(), web_contents);
  3100. return blocked_content::MaybeBlockPopup(
  3101. web_contents, &opener_top_level_frame_url,
  3102. std::make_unique<ChromePopupNavigationDelegate>(
  3103. std::move(nav_params)),
  3104. nullptr /*=open_url_params*/, blocked_params.features(),
  3105. HostContentSettingsMapFactory::GetForProfile(profile)) != nullptr;
  3106. }
  3107. content::SpeechRecognitionManagerDelegate*
  3108. ChromeContentBrowserClient::CreateSpeechRecognitionManagerDelegate() {
  3109. return new speech::ChromeSpeechRecognitionManagerDelegate();
  3110. }
  3111. #if BUILDFLAG(IS_CHROMEOS_ASH)
  3112. content::TtsControllerDelegate*
  3113. ChromeContentBrowserClient::GetTtsControllerDelegate() {
  3114. return TtsControllerDelegateImpl::GetInstance();
  3115. }
  3116. #endif
  3117. void ChromeContentBrowserClient::MaybeOverrideManifest(
  3118. content::RenderFrameHost* render_frame_host,
  3119. blink::mojom::ManifestPtr& manifest) {
  3120. #if BUILDFLAG(IS_CHROMEOS)
  3121. Profile* profile =
  3122. Profile::FromBrowserContext(render_frame_host->GetBrowserContext());
  3123. auto* provider = web_app::WebAppProvider::GetForWebApps(profile);
  3124. if (provider)
  3125. provider->policy_manager().MaybeOverrideManifest(render_frame_host,
  3126. manifest);
  3127. #endif
  3128. }
  3129. content::TtsPlatform* ChromeContentBrowserClient::GetTtsPlatform() {
  3130. #if !BUILDFLAG(IS_ANDROID)
  3131. content::TtsController::GetInstance()->SetTtsEngineDelegate(
  3132. TtsExtensionEngine::GetInstance());
  3133. #endif
  3134. #if BUILDFLAG(IS_CHROMEOS_ASH)
  3135. return TtsPlatformImplChromeOs::GetInstance();
  3136. #elif BUILDFLAG(IS_CHROMEOS_LACROS)
  3137. return TtsPlatformImplLacros::GetInstance();
  3138. #else
  3139. return nullptr;
  3140. #endif
  3141. }
  3142. void ChromeContentBrowserClient::OverrideWebkitPrefs(
  3143. WebContents* web_contents,
  3144. WebPreferences* web_prefs) {
  3145. Profile* profile =
  3146. Profile::FromBrowserContext(web_contents->GetBrowserContext());
  3147. PrefService* prefs = profile->GetPrefs();
  3148. // Fill font preferences. These are not registered on Android
  3149. // - http://crbug.com/308033, http://crbug.com/696364.
  3150. #if !BUILDFLAG(IS_ANDROID)
  3151. FontFamilyCache::FillFontFamilyMap(profile,
  3152. prefs::kWebKitStandardFontFamilyMap,
  3153. &web_prefs->standard_font_family_map);
  3154. FontFamilyCache::FillFontFamilyMap(profile, prefs::kWebKitFixedFontFamilyMap,
  3155. &web_prefs->fixed_font_family_map);
  3156. FontFamilyCache::FillFontFamilyMap(profile, prefs::kWebKitSerifFontFamilyMap,
  3157. &web_prefs->serif_font_family_map);
  3158. FontFamilyCache::FillFontFamilyMap(profile,
  3159. prefs::kWebKitSansSerifFontFamilyMap,
  3160. &web_prefs->sans_serif_font_family_map);
  3161. FontFamilyCache::FillFontFamilyMap(profile,
  3162. prefs::kWebKitCursiveFontFamilyMap,
  3163. &web_prefs->cursive_font_family_map);
  3164. FontFamilyCache::FillFontFamilyMap(profile,
  3165. prefs::kWebKitFantasyFontFamilyMap,
  3166. &web_prefs->fantasy_font_family_map);
  3167. FontFamilyCache::FillFontFamilyMap(profile, prefs::kWebKitMathFontFamilyMap,
  3168. &web_prefs->math_font_family_map);
  3169. web_prefs->default_font_size =
  3170. prefs->GetInteger(prefs::kWebKitDefaultFontSize);
  3171. web_prefs->default_fixed_font_size =
  3172. prefs->GetInteger(prefs::kWebKitDefaultFixedFontSize);
  3173. web_prefs->minimum_font_size =
  3174. prefs->GetInteger(prefs::kWebKitMinimumFontSize);
  3175. web_prefs->minimum_logical_font_size =
  3176. prefs->GetInteger(prefs::kWebKitMinimumLogicalFontSize);
  3177. #endif
  3178. web_prefs->default_encoding = prefs->GetString(prefs::kDefaultCharset);
  3179. web_prefs->dom_paste_enabled =
  3180. prefs->GetBoolean(prefs::kWebKitDomPasteEnabled);
  3181. web_prefs->javascript_can_access_clipboard =
  3182. prefs->GetBoolean(prefs::kWebKitJavascriptCanAccessClipboard);
  3183. web_prefs->tabs_to_links = prefs->GetBoolean(prefs::kWebkitTabsToLinks);
  3184. if (!prefs->GetBoolean(prefs::kWebKitJavascriptEnabled))
  3185. web_prefs->javascript_enabled = false;
  3186. if (!prefs->GetBoolean(prefs::kWebKitWebSecurityEnabled))
  3187. web_prefs->web_security_enabled = false;
  3188. if (!prefs->GetBoolean(prefs::kWebKitPluginsEnabled))
  3189. web_prefs->plugins_enabled = false;
  3190. web_prefs->loads_images_automatically =
  3191. prefs->GetBoolean(prefs::kWebKitLoadsImagesAutomatically);
  3192. if (prefs->GetBoolean(prefs::kDisable3DAPIs)) {
  3193. web_prefs->webgl1_enabled = false;
  3194. web_prefs->webgl2_enabled = false;
  3195. }
  3196. web_prefs->allow_running_insecure_content =
  3197. prefs->GetBoolean(prefs::kWebKitAllowRunningInsecureContent);
  3198. #if BUILDFLAG(IS_ANDROID)
  3199. web_prefs->font_scale_factor = static_cast<float>(
  3200. prefs->GetDouble(browser_ui::prefs::kWebKitFontScaleFactor));
  3201. web_prefs->force_enable_zoom =
  3202. prefs->GetBoolean(browser_ui::prefs::kWebKitForceEnableZoom);
  3203. #endif
  3204. web_prefs->force_dark_mode_enabled =
  3205. prefs->GetBoolean(prefs::kWebKitForceDarkModeEnabled);
  3206. #if BUILDFLAG(IS_CHROMEOS_ASH)
  3207. web_prefs->always_show_focus =
  3208. prefs->GetBoolean(ash::prefs::kAccessibilityFocusHighlightEnabled);
  3209. #else
  3210. if (features::IsAccessibilityFocusHighlightEnabled()) {
  3211. web_prefs->always_show_focus =
  3212. prefs->GetBoolean(prefs::kAccessibilityFocusHighlightEnabled);
  3213. }
  3214. #endif
  3215. #if BUILDFLAG(IS_ANDROID)
  3216. web_prefs->password_echo_enabled =
  3217. prefs->GetBoolean(prefs::kWebKitPasswordEchoEnabled);
  3218. #else
  3219. web_prefs->password_echo_enabled = browser_defaults::kPasswordEchoEnabled;
  3220. #endif
  3221. web_prefs->text_areas_are_resizable =
  3222. prefs->GetBoolean(prefs::kWebKitTextAreasAreResizable);
  3223. web_prefs->hyperlink_auditing_enabled =
  3224. prefs->GetBoolean(prefs::kEnableHyperlinkAuditing);
  3225. #if BUILDFLAG(ENABLE_EXTENSIONS)
  3226. std::string image_animation_policy =
  3227. prefs->GetString(prefs::kAnimationPolicy);
  3228. if (image_animation_policy == kAnimationPolicyOnce) {
  3229. web_prefs->animation_policy =
  3230. blink::mojom::ImageAnimationPolicy::kImageAnimationPolicyAnimateOnce;
  3231. } else if (image_animation_policy == kAnimationPolicyNone) {
  3232. web_prefs->animation_policy =
  3233. blink::mojom::ImageAnimationPolicy::kImageAnimationPolicyNoAnimation;
  3234. } else {
  3235. web_prefs->animation_policy =
  3236. blink::mojom::ImageAnimationPolicy::kImageAnimationPolicyAllowed;
  3237. }
  3238. #endif
  3239. // Make sure we will set the default_encoding with canonical encoding name.
  3240. web_prefs->default_encoding =
  3241. base::GetCanonicalEncodingNameByAliasName(web_prefs->default_encoding);
  3242. if (web_prefs->default_encoding.empty()) {
  3243. prefs->ClearPref(prefs::kDefaultCharset);
  3244. web_prefs->default_encoding = prefs->GetString(prefs::kDefaultCharset);
  3245. }
  3246. DCHECK(!web_prefs->default_encoding.empty());
  3247. if (base::CommandLine::ForCurrentProcess()->HasSwitch(
  3248. switches::kEnablePotentiallyAnnoyingSecurityFeatures)) {
  3249. web_prefs->disable_reading_from_canvas = true;
  3250. web_prefs->strict_mixed_content_checking = true;
  3251. web_prefs->strict_powerful_feature_restrictions = true;
  3252. }
  3253. // See crbug.com/1238157: the Native Client flag (chrome://flags/#enable-nacl)
  3254. // can be manually re-enabled. In that case, we also need to return the full
  3255. // plugins list, for compat.
  3256. web_prefs->allow_non_empty_navigator_plugins |=
  3257. base::CommandLine::ForCurrentProcess()->HasSwitch(switches::kEnableNaCl);
  3258. web_prefs->data_saver_enabled = IsDataSaverEnabled(profile);
  3259. if (web_contents) {
  3260. #if BUILDFLAG(IS_ANDROID)
  3261. auto* delegate = TabAndroid::FromWebContents(web_contents)
  3262. ? static_cast<android::TabWebContentsDelegateAndroid*>(
  3263. web_contents->GetDelegate())
  3264. : nullptr;
  3265. if (delegate) {
  3266. web_prefs->embedded_media_experience_enabled =
  3267. delegate->ShouldEnableEmbeddedMediaExperience();
  3268. web_prefs->picture_in_picture_enabled =
  3269. delegate->IsPictureInPictureEnabled();
  3270. web_prefs->force_dark_mode_enabled =
  3271. delegate->IsForceDarkWebContentEnabled();
  3272. }
  3273. #endif // BUILDFLAG(IS_ANDROID)
  3274. // web_app_scope value is platform specific.
  3275. #if BUILDFLAG(IS_ANDROID)
  3276. if (delegate)
  3277. web_prefs->web_app_scope = delegate->GetManifestScope();
  3278. #elif BUILDFLAG(ENABLE_EXTENSIONS)
  3279. {
  3280. web_prefs->web_app_scope = GURL();
  3281. // Set |web_app_scope| based on the app associated with the app window if
  3282. // any. Note that the app associated with the window never changes, even
  3283. // if the app navigates off scope. This is not a problem because we still
  3284. // want to use the scope of the app associated with the window, not the
  3285. // WebContents.
  3286. Browser* browser = chrome::FindBrowserWithWebContents(web_contents);
  3287. if (browser && browser->app_controller()) {
  3288. web_app::WebAppProvider* const web_app_provider =
  3289. web_app::WebAppProvider::GetForLocalAppsUnchecked(profile);
  3290. const web_app::AppId& app_id = browser->app_controller()->app_id();
  3291. const web_app::WebAppRegistrar& registrar =
  3292. web_app_provider->registrar();
  3293. if (registrar.IsLocallyInstalled(app_id))
  3294. web_prefs->web_app_scope = registrar.GetAppScope(app_id);
  3295. #if BUILDFLAG(IS_CHROMEOS_ASH)
  3296. auto* system_app = browser->app_controller()->system_app();
  3297. if (system_app) {
  3298. web_prefs->allow_scripts_to_close_windows =
  3299. system_app->ShouldAllowScriptsToCloseWindows();
  3300. }
  3301. #endif // BUILDFLAG(IS_CHROMEOS_ASH)
  3302. }
  3303. }
  3304. #endif
  3305. web_prefs->immersive_mode_enabled = vr::VrTabHelper::IsInVr(web_contents);
  3306. }
  3307. web_prefs->lazy_load_enabled =
  3308. !web_contents || !web_contents->GetDelegate() ||
  3309. web_contents->GetDelegate()->ShouldAllowLazyLoad();
  3310. if (base::FeatureList::IsEnabled(features::kLazyFrameLoading)) {
  3311. const char* param_name =
  3312. web_prefs->data_saver_enabled
  3313. ? "lazy_frame_loading_distance_thresholds_px_by_ect"
  3314. : "lazy_frame_loading_distance_thresholds_px_by_ect_with_data_"
  3315. "saver_enabled";
  3316. base::StringPairs pairs;
  3317. base::SplitStringIntoKeyValuePairs(
  3318. base::GetFieldTrialParamValueByFeature(features::kLazyFrameLoading,
  3319. param_name),
  3320. ':', ',', &pairs);
  3321. for (const auto& pair : pairs) {
  3322. absl::optional<net::EffectiveConnectionType> effective_connection_type =
  3323. net::GetEffectiveConnectionTypeForName(pair.first);
  3324. int value = 0;
  3325. if (effective_connection_type && base::StringToInt(pair.second, &value)) {
  3326. web_prefs->lazy_frame_loading_distance_thresholds_px[static_cast<
  3327. EffectiveConnectionType>(effective_connection_type.value())] =
  3328. value;
  3329. }
  3330. }
  3331. }
  3332. if (base::FeatureList::IsEnabled(features::kLazyImageLoading)) {
  3333. const char* param_name =
  3334. web_prefs->data_saver_enabled
  3335. ? "lazy_image_loading_distance_thresholds_px_by_ect"
  3336. : "lazy_image_loading_distance_thresholds_px_by_ect_with_data_"
  3337. "saver_enabled";
  3338. base::StringPairs pairs;
  3339. base::SplitStringIntoKeyValuePairs(
  3340. base::GetFieldTrialParamValueByFeature(features::kLazyImageLoading,
  3341. param_name),
  3342. ':', ',', &pairs);
  3343. for (const auto& pair : pairs) {
  3344. absl::optional<net::EffectiveConnectionType> effective_connection_type =
  3345. net::GetEffectiveConnectionTypeForName(pair.first);
  3346. int value = 0;
  3347. if (effective_connection_type && base::StringToInt(pair.second, &value)) {
  3348. web_prefs->lazy_image_loading_distance_thresholds_px[static_cast<
  3349. EffectiveConnectionType>(effective_connection_type.value())] =
  3350. value;
  3351. }
  3352. }
  3353. pairs.clear();
  3354. base::SplitStringIntoKeyValuePairs(
  3355. base::GetFieldTrialParamValueByFeature(features::kLazyImageLoading,
  3356. "lazy_image_first_k_fully_load"),
  3357. ':', ',', &pairs);
  3358. for (const auto& pair : pairs) {
  3359. absl::optional<net::EffectiveConnectionType> effective_connection_type =
  3360. net::GetEffectiveConnectionTypeForName(pair.first);
  3361. int value = 0;
  3362. if (effective_connection_type && base::StringToInt(pair.second, &value)) {
  3363. web_prefs->lazy_image_first_k_fully_load[static_cast<
  3364. EffectiveConnectionType>(effective_connection_type.value())] =
  3365. value;
  3366. }
  3367. }
  3368. }
  3369. if (base::FeatureList::IsEnabled(
  3370. features::kNetworkQualityEstimatorWebHoldback)) {
  3371. std::string effective_connection_type_param =
  3372. base::GetFieldTrialParamValueByFeature(
  3373. features::kNetworkQualityEstimatorWebHoldback,
  3374. "web_effective_connection_type_override");
  3375. absl::optional<net::EffectiveConnectionType> effective_connection_type =
  3376. net::GetEffectiveConnectionTypeForName(effective_connection_type_param);
  3377. DCHECK(effective_connection_type_param.empty() ||
  3378. effective_connection_type);
  3379. if (effective_connection_type) {
  3380. DCHECK_NE(net::EFFECTIVE_CONNECTION_TYPE_UNKNOWN,
  3381. effective_connection_type.value());
  3382. web_prefs->network_quality_estimator_web_holdback =
  3383. static_cast<EffectiveConnectionType>(
  3384. effective_connection_type.value());
  3385. }
  3386. }
  3387. web_prefs->autoplay_policy = GetAutoplayPolicyForWebContents(web_contents);
  3388. switch (GetWebTheme()->GetPreferredContrast()) {
  3389. case ui::NativeTheme::PreferredContrast::kNoPreference:
  3390. web_prefs->preferred_contrast =
  3391. blink::mojom::PreferredContrast::kNoPreference;
  3392. break;
  3393. case ui::NativeTheme::PreferredContrast::kMore:
  3394. web_prefs->preferred_contrast = blink::mojom::PreferredContrast::kMore;
  3395. break;
  3396. case ui::NativeTheme::PreferredContrast::kLess:
  3397. web_prefs->preferred_contrast = blink::mojom::PreferredContrast::kLess;
  3398. break;
  3399. case ui::NativeTheme::PreferredContrast::kCustom:
  3400. web_prefs->preferred_contrast = blink::mojom::PreferredContrast::kCustom;
  3401. break;
  3402. }
  3403. UpdatePreferredColorScheme(
  3404. web_prefs,
  3405. web_contents->GetPrimaryMainFrame()->GetSiteInstance()->GetSiteURL(),
  3406. web_contents, GetWebTheme());
  3407. web_prefs->translate_service_available = TranslateService::IsAvailable(prefs);
  3408. absl::optional<ui::CaptionStyle> style =
  3409. captions::GetCaptionStyleFromUserSettings(prefs,
  3410. true /* record_metrics */);
  3411. if (style) {
  3412. web_prefs->text_track_background_color = style->background_color;
  3413. web_prefs->text_track_text_color = style->text_color;
  3414. web_prefs->text_track_text_size = style->text_size;
  3415. web_prefs->text_track_text_shadow = style->text_shadow;
  3416. web_prefs->text_track_font_family = style->font_family;
  3417. web_prefs->text_track_font_variant = style->font_variant;
  3418. web_prefs->text_track_window_color = style->window_color;
  3419. web_prefs->text_track_window_radius = style->window_radius;
  3420. }
  3421. #if BUILDFLAG(IS_ANDROID)
  3422. // If the pref is not set, the default value (true) will be used:
  3423. web_prefs->webxr_immersive_ar_allowed =
  3424. prefs->GetBoolean(prefs::kWebXRImmersiveArEnabled);
  3425. // APIs for Web Authentication are not available prior to N.
  3426. web_prefs->disable_webauthn =
  3427. base::android::BuildInfo::GetInstance()->sdk_int() <
  3428. base::android::SDK_VERSION_NOUGAT;
  3429. #endif
  3430. for (ChromeContentBrowserClientParts* parts : extra_parts_)
  3431. parts->OverrideWebkitPrefs(web_contents, web_prefs);
  3432. }
  3433. bool ChromeContentBrowserClientParts::OverrideWebPreferencesAfterNavigation(
  3434. WebContents* web_contents,
  3435. WebPreferences* web_prefs) {
  3436. return false;
  3437. }
  3438. bool ChromeContentBrowserClient::OverrideWebPreferencesAfterNavigation(
  3439. WebContents* web_contents,
  3440. WebPreferences* prefs) {
  3441. const auto autoplay_policy = GetAutoplayPolicyForWebContents(web_contents);
  3442. const bool new_autoplay_policy_needed =
  3443. prefs->autoplay_policy != autoplay_policy;
  3444. if (new_autoplay_policy_needed)
  3445. prefs->autoplay_policy = autoplay_policy;
  3446. bool extra_parts_need_update = false;
  3447. for (ChromeContentBrowserClientParts* parts : extra_parts_) {
  3448. extra_parts_need_update |=
  3449. parts->OverrideWebPreferencesAfterNavigation(web_contents, prefs);
  3450. }
  3451. bool preferred_color_scheme_updated = UpdatePreferredColorScheme(
  3452. prefs, web_contents->GetLastCommittedURL(), web_contents, GetWebTheme());
  3453. #if BUILDFLAG(IS_ANDROID)
  3454. bool force_dark_mode_changed = false;
  3455. auto* delegate = TabAndroid::FromWebContents(web_contents)
  3456. ? static_cast<android::TabWebContentsDelegateAndroid*>(
  3457. web_contents->GetDelegate())
  3458. : nullptr;
  3459. if (delegate) {
  3460. bool force_dark_mode_new_state = delegate->IsForceDarkWebContentEnabled();
  3461. force_dark_mode_changed =
  3462. prefs->force_dark_mode_enabled != force_dark_mode_new_state;
  3463. prefs->force_dark_mode_enabled = force_dark_mode_new_state;
  3464. }
  3465. #endif
  3466. return new_autoplay_policy_needed || extra_parts_need_update ||
  3467. #if BUILDFLAG(IS_ANDROID)
  3468. force_dark_mode_changed ||
  3469. #endif
  3470. preferred_color_scheme_updated;
  3471. }
  3472. void ChromeContentBrowserClient::BrowserURLHandlerCreated(
  3473. BrowserURLHandler* handler) {
  3474. // The group policy NTP URL handler must be registered before the other NTP
  3475. // URL handlers below. Also register it before the "parts" handlers, so the
  3476. // NTP policy takes precedence over extensions that override the NTP.
  3477. handler->AddHandlerPair(&HandleNewTabPageLocationOverride,
  3478. BrowserURLHandler::null_handler());
  3479. for (size_t i = 0; i < extra_parts_.size(); ++i)
  3480. extra_parts_[i]->BrowserURLHandlerCreated(handler);
  3481. // Handler to rewrite chrome://about and chrome://sync URLs.
  3482. handler->AddHandlerPair(&HandleChromeAboutAndChromeSyncRewrite,
  3483. BrowserURLHandler::null_handler());
  3484. #if BUILDFLAG(IS_ANDROID)
  3485. // Handler to rewrite chrome://newtab on Android.
  3486. handler->AddHandlerPair(&chrome::android::HandleAndroidNativePageURL,
  3487. BrowserURLHandler::null_handler());
  3488. #else // BUILDFLAG(IS_ANDROID)
  3489. // Handler to rewrite chrome://newtab for InstantExtended.
  3490. handler->AddHandlerPair(&search::HandleNewTabURLRewrite,
  3491. &search::HandleNewTabURLReverseRewrite);
  3492. #endif // BUILDFLAG(IS_ANDROID)
  3493. // chrome: & friends.
  3494. handler->AddHandlerPair(&ChromeContentBrowserClient::HandleWebUI,
  3495. &ChromeContentBrowserClient::HandleWebUIReverse);
  3496. }
  3497. base::FilePath ChromeContentBrowserClient::GetDefaultDownloadDirectory() {
  3498. return DownloadPrefs::GetDefaultDownloadDirectory();
  3499. }
  3500. std::string ChromeContentBrowserClient::GetDefaultDownloadName() {
  3501. return l10n_util::GetStringUTF8(IDS_DEFAULT_DOWNLOAD_FILENAME);
  3502. }
  3503. base::FilePath ChromeContentBrowserClient::GetFontLookupTableCacheDir() {
  3504. base::FilePath user_data_dir;
  3505. base::PathService::Get(chrome::DIR_USER_DATA, &user_data_dir);
  3506. DCHECK(!user_data_dir.empty());
  3507. return user_data_dir.Append(FILE_PATH_LITERAL("FontLookupTableCache"));
  3508. }
  3509. base::FilePath ChromeContentBrowserClient::GetShaderDiskCacheDirectory() {
  3510. base::FilePath user_data_dir;
  3511. base::PathService::Get(chrome::DIR_USER_DATA, &user_data_dir);
  3512. DCHECK(!user_data_dir.empty());
  3513. return user_data_dir.Append(FILE_PATH_LITERAL("ShaderCache"));
  3514. }
  3515. base::FilePath ChromeContentBrowserClient::GetGrShaderDiskCacheDirectory() {
  3516. base::FilePath user_data_dir;
  3517. base::PathService::Get(chrome::DIR_USER_DATA, &user_data_dir);
  3518. DCHECK(!user_data_dir.empty());
  3519. return user_data_dir.Append(FILE_PATH_LITERAL("GrShaderCache"));
  3520. }
  3521. base::FilePath ChromeContentBrowserClient::GetNetLogDefaultDirectory() {
  3522. base::FilePath user_data_dir;
  3523. base::PathService::Get(chrome::DIR_USER_DATA, &user_data_dir);
  3524. DCHECK(!user_data_dir.empty());
  3525. return user_data_dir;
  3526. }
  3527. base::FilePath ChromeContentBrowserClient::GetFirstPartySetsDirectory() {
  3528. base::FilePath user_data_dir;
  3529. base::PathService::Get(chrome::DIR_USER_DATA, &user_data_dir);
  3530. DCHECK(!user_data_dir.empty());
  3531. return user_data_dir;
  3532. }
  3533. void ChromeContentBrowserClient::DidCreatePpapiPlugin(
  3534. content::BrowserPpapiHost* browser_host) {
  3535. #if BUILDFLAG(ENABLE_PLUGINS)
  3536. ChromeContentBrowserClientPluginsPart::DidCreatePpapiPlugin(browser_host);
  3537. #endif
  3538. }
  3539. content::BrowserPpapiHost*
  3540. ChromeContentBrowserClient::GetExternalBrowserPpapiHost(int plugin_process_id) {
  3541. #if BUILDFLAG(ENABLE_NACL)
  3542. content::BrowserChildProcessHostIterator iter(PROCESS_TYPE_NACL_LOADER);
  3543. while (!iter.Done()) {
  3544. nacl::NaClProcessHost* host =
  3545. static_cast<nacl::NaClProcessHost*>(iter.GetDelegate());
  3546. if (host->process() && host->process()->GetData().id == plugin_process_id) {
  3547. // Found the plugin.
  3548. return host->browser_ppapi_host();
  3549. }
  3550. ++iter;
  3551. }
  3552. #endif
  3553. return nullptr;
  3554. }
  3555. bool ChromeContentBrowserClient::AllowPepperSocketAPI(
  3556. content::BrowserContext* browser_context,
  3557. const GURL& url,
  3558. bool private_api,
  3559. const content::SocketPermissionRequest* params) {
  3560. #if BUILDFLAG(ENABLE_PLUGINS) && BUILDFLAG(ENABLE_EXTENSIONS)
  3561. return ChromeContentBrowserClientPluginsPart::AllowPepperSocketAPI(
  3562. browser_context, url, private_api, params);
  3563. #else
  3564. return false;
  3565. #endif
  3566. }
  3567. bool ChromeContentBrowserClient::IsPepperVpnProviderAPIAllowed(
  3568. content::BrowserContext* browser_context,
  3569. const GURL& url) {
  3570. #if BUILDFLAG(ENABLE_PLUGINS) && BUILDFLAG(ENABLE_EXTENSIONS)
  3571. return ChromeContentBrowserClientPluginsPart::IsPepperVpnProviderAPIAllowed(
  3572. browser_context, url);
  3573. #else
  3574. return false;
  3575. #endif
  3576. }
  3577. std::unique_ptr<content::VpnServiceProxy>
  3578. ChromeContentBrowserClient::GetVpnServiceProxy(
  3579. content::BrowserContext* browser_context) {
  3580. #if BUILDFLAG(ENABLE_EXTENSIONS)
  3581. return ChromeContentBrowserClientExtensionsPart::GetVpnServiceProxy(
  3582. browser_context);
  3583. #else
  3584. return nullptr;
  3585. #endif
  3586. }
  3587. std::unique_ptr<ui::SelectFilePolicy>
  3588. ChromeContentBrowserClient::CreateSelectFilePolicy(WebContents* web_contents) {
  3589. return std::make_unique<ChromeSelectFilePolicy>(web_contents);
  3590. }
  3591. void ChromeContentBrowserClient::GetAdditionalAllowedSchemesForFileSystem(
  3592. std::vector<std::string>* additional_allowed_schemes) {
  3593. ContentBrowserClient::GetAdditionalAllowedSchemesForFileSystem(
  3594. additional_allowed_schemes);
  3595. additional_allowed_schemes->push_back(content::kChromeDevToolsScheme);
  3596. additional_allowed_schemes->push_back(content::kChromeUIScheme);
  3597. additional_allowed_schemes->push_back(content::kChromeUIUntrustedScheme);
  3598. for (auto*& extra_part : extra_parts_) {
  3599. extra_part->GetAdditionalAllowedSchemesForFileSystem(
  3600. additional_allowed_schemes);
  3601. }
  3602. }
  3603. void ChromeContentBrowserClient::GetSchemesBypassingSecureContextCheckAllowlist(
  3604. std::set<std::string>* schemes) {
  3605. *schemes = secure_origin_allowlist::GetSchemesBypassingSecureContextCheck();
  3606. }
  3607. void ChromeContentBrowserClient::GetURLRequestAutoMountHandlers(
  3608. std::vector<storage::URLRequestAutoMountHandler>* handlers) {
  3609. for (size_t i = 0; i < extra_parts_.size(); ++i)
  3610. extra_parts_[i]->GetURLRequestAutoMountHandlers(handlers);
  3611. }
  3612. void ChromeContentBrowserClient::GetAdditionalFileSystemBackends(
  3613. content::BrowserContext* browser_context,
  3614. const base::FilePath& storage_partition_path,
  3615. std::vector<std::unique_ptr<storage::FileSystemBackend>>*
  3616. additional_backends) {
  3617. #if BUILDFLAG(IS_CHROMEOS_ASH)
  3618. storage::ExternalMountPoints* external_mount_points =
  3619. browser_context->GetMountPoints();
  3620. DCHECK(external_mount_points);
  3621. auto backend = std::make_unique<chromeos::FileSystemBackend>(
  3622. Profile::FromBrowserContext(browser_context),
  3623. std::make_unique<ash::file_system_provider::BackendDelegate>(),
  3624. std::make_unique<chromeos::MTPFileSystemBackendDelegate>(
  3625. storage_partition_path),
  3626. std::make_unique<arc::ArcContentFileSystemBackendDelegate>(),
  3627. std::make_unique<arc::ArcDocumentsProviderBackendDelegate>(),
  3628. std::make_unique<drive::DriveFsFileSystemBackendDelegate>(
  3629. Profile::FromBrowserContext(browser_context)),
  3630. std::make_unique<ash::smb_client::SmbFsFileSystemBackendDelegate>(
  3631. Profile::FromBrowserContext(browser_context)),
  3632. external_mount_points, storage::ExternalMountPoints::GetSystemInstance());
  3633. backend->AddSystemMountPoints();
  3634. DCHECK(backend->CanHandleType(storage::kFileSystemTypeExternal));
  3635. additional_backends->push_back(std::move(backend));
  3636. #endif
  3637. for (size_t i = 0; i < extra_parts_.size(); ++i) {
  3638. extra_parts_[i]->GetAdditionalFileSystemBackends(
  3639. browser_context, storage_partition_path,
  3640. GetQuarantineConnectionCallback(), additional_backends);
  3641. }
  3642. }
  3643. #if BUILDFLAG(IS_POSIX) && !BUILDFLAG(IS_MAC)
  3644. void ChromeContentBrowserClient::GetAdditionalMappedFilesForChildProcess(
  3645. const base::CommandLine& command_line,
  3646. int child_process_id,
  3647. PosixFileDescriptorInfo* mappings) {
  3648. #if BUILDFLAG(IS_ANDROID)
  3649. base::MemoryMappedFile::Region region;
  3650. int fd = ui::GetMainAndroidPackFd(&region);
  3651. mappings->ShareWithRegion(kAndroidUIResourcesPakDescriptor, fd, region);
  3652. // For Android: Native resources for DFMs should only be used by the browser
  3653. // process. Their file descriptors and memory mapped file regions are not
  3654. // passed to child processes.
  3655. fd = ui::GetCommonResourcesPackFd(&region);
  3656. mappings->ShareWithRegion(kAndroidChrome100PercentPakDescriptor, fd, region);
  3657. fd = ui::GetLocalePackFd(&region);
  3658. mappings->ShareWithRegion(kAndroidLocalePakDescriptor, fd, region);
  3659. // Optional secondary locale .pak file.
  3660. fd = ui::GetSecondaryLocalePackFd(&region);
  3661. if (fd != -1) {
  3662. mappings->ShareWithRegion(kAndroidSecondaryLocalePakDescriptor, fd, region);
  3663. }
  3664. base::FilePath app_data_path;
  3665. base::PathService::Get(base::DIR_ANDROID_APP_DATA, &app_data_path);
  3666. DCHECK(!app_data_path.empty());
  3667. #endif // BUILDFLAG(IS_ANDROID)
  3668. int crash_signal_fd = GetCrashSignalFD(command_line);
  3669. if (crash_signal_fd >= 0) {
  3670. mappings->Share(kCrashDumpSignal, crash_signal_fd);
  3671. }
  3672. }
  3673. #endif // BUILDFLAG(IS_POSIX) && !BUILDFLAG(IS_MAC)
  3674. #if BUILDFLAG(IS_WIN)
  3675. std::wstring ChromeContentBrowserClient::GetAppContainerSidForSandboxType(
  3676. sandbox::mojom::Sandbox sandbox_type,
  3677. AppContainerFlags flags) {
  3678. // TODO(wfh): Add support for more process types here. crbug.com/499523
  3679. switch (sandbox_type) {
  3680. case sandbox::mojom::Sandbox::kRenderer:
  3681. if (flags & AppContainerFlags::kAppContainerFlagDisableAppContainer)
  3682. return std::wstring();
  3683. return std::wstring(install_static::GetSandboxSidPrefix()) + L"129201922";
  3684. case sandbox::mojom::Sandbox::kUtility:
  3685. return std::wstring();
  3686. case sandbox::mojom::Sandbox::kGpu:
  3687. return std::wstring();
  3688. #if BUILDFLAG(ENABLE_PLUGINS)
  3689. case sandbox::mojom::Sandbox::kPpapi:
  3690. #endif
  3691. case sandbox::mojom::Sandbox::kNoSandbox:
  3692. case sandbox::mojom::Sandbox::kNoSandboxAndElevatedPrivileges:
  3693. case sandbox::mojom::Sandbox::kXrCompositing:
  3694. case sandbox::mojom::Sandbox::kNetwork:
  3695. case sandbox::mojom::Sandbox::kCdm:
  3696. #if BUILDFLAG(ENABLE_PRINTING)
  3697. case sandbox::mojom::Sandbox::kPrintBackend:
  3698. #endif
  3699. case sandbox::mojom::Sandbox::kPrintCompositor:
  3700. case sandbox::mojom::Sandbox::kAudio:
  3701. case sandbox::mojom::Sandbox::kSpeechRecognition:
  3702. case sandbox::mojom::Sandbox::kPdfConversion:
  3703. case sandbox::mojom::Sandbox::kService:
  3704. case sandbox::mojom::Sandbox::kServiceWithJit:
  3705. case sandbox::mojom::Sandbox::kIconReader:
  3706. case sandbox::mojom::Sandbox::kMediaFoundationCdm:
  3707. case sandbox::mojom::Sandbox::kWindowsSystemProxyResolver:
  3708. // Should never reach here.
  3709. CHECK(0);
  3710. return std::wstring();
  3711. }
  3712. }
  3713. bool ChromeContentBrowserClient::IsRendererAppContainerDisabled() {
  3714. DCHECK_CURRENTLY_ON(BrowserThread::UI);
  3715. PrefService* local_state = g_browser_process->local_state();
  3716. const PrefService::Preference* pref =
  3717. local_state->FindPreference(prefs::kRendererAppContainerEnabled);
  3718. // App Container is disabled if managed pref is set to false.
  3719. if (pref && pref->IsManaged() && !pref->GetValue()->GetBool())
  3720. return true;
  3721. return false;
  3722. }
  3723. std::wstring
  3724. ChromeContentBrowserClient::GetLPACCapabilityNameForNetworkService() {
  3725. // Use a different LPAC capability name for each Chrome channel so network
  3726. // service data between hannels is isolated.
  3727. version_info::Channel channel = chrome::GetChannel();
  3728. switch (channel) {
  3729. case version_info::Channel::CANARY:
  3730. return std::wstring(L"lpacChromeCanaryNetworkSandbox");
  3731. case version_info::Channel::BETA:
  3732. return std::wstring(L"lpacChromeBetaNetworkSandbox");
  3733. case version_info::Channel::DEV:
  3734. return std::wstring(L"lpacChromeDevNetworkSandbox");
  3735. case version_info::Channel::STABLE:
  3736. return std::wstring(L"lpacChromeStableNetworkSandbox");
  3737. case version_info::Channel::UNKNOWN:
  3738. return std::wstring(L"lpacChromeNetworkSandbox");
  3739. }
  3740. }
  3741. // Note: Only use sparingly to add Chrome specific sandbox functionality here.
  3742. // Other code should reside in the content layer. Changes to this function
  3743. // should be reviewed by the security team.
  3744. bool ChromeContentBrowserClient::PreSpawnChild(
  3745. sandbox::TargetPolicy* policy,
  3746. sandbox::mojom::Sandbox sandbox_type,
  3747. ChildSpawnFlags flags) {
  3748. // Does not work under component build because all the component DLLs would need
  3749. // to be manually added and maintained. Does not work under ASAN build because
  3750. // ASAN has not yet fully initialized its instrumentation by the time the CIG
  3751. // intercepts run.
  3752. #if !defined(COMPONENT_BUILD) && !defined(ADDRESS_SANITIZER)
  3753. bool enforce_code_integrity = false;
  3754. switch (sandbox_type) {
  3755. case sandbox::mojom::Sandbox::kRenderer:
  3756. enforce_code_integrity =
  3757. ((flags & ChildSpawnFlags::kChildSpawnFlagRendererCodeIntegrity) &&
  3758. base::FeatureList::IsEnabled(kRendererCodeIntegrity));
  3759. break;
  3760. case sandbox::mojom::Sandbox::kNetwork:
  3761. enforce_code_integrity =
  3762. base::FeatureList::IsEnabled(kNetworkServiceCodeIntegrity);
  3763. break;
  3764. case sandbox::mojom::Sandbox::kServiceWithJit:
  3765. enforce_code_integrity = true;
  3766. break;
  3767. case sandbox::mojom::Sandbox::kUtility:
  3768. case sandbox::mojom::Sandbox::kGpu:
  3769. #if BUILDFLAG(ENABLE_PLUGINS)
  3770. case sandbox::mojom::Sandbox::kPpapi:
  3771. #endif
  3772. case sandbox::mojom::Sandbox::kNoSandbox:
  3773. case sandbox::mojom::Sandbox::kNoSandboxAndElevatedPrivileges:
  3774. case sandbox::mojom::Sandbox::kXrCompositing:
  3775. case sandbox::mojom::Sandbox::kCdm:
  3776. #if BUILDFLAG(ENABLE_PRINTING)
  3777. case sandbox::mojom::Sandbox::kPrintBackend:
  3778. #endif
  3779. case sandbox::mojom::Sandbox::kPrintCompositor:
  3780. case sandbox::mojom::Sandbox::kAudio:
  3781. case sandbox::mojom::Sandbox::kSpeechRecognition:
  3782. case sandbox::mojom::Sandbox::kPdfConversion:
  3783. case sandbox::mojom::Sandbox::kService:
  3784. case sandbox::mojom::Sandbox::kIconReader:
  3785. case sandbox::mojom::Sandbox::kMediaFoundationCdm:
  3786. case sandbox::mojom::Sandbox::kWindowsSystemProxyResolver:
  3787. break;
  3788. }
  3789. #if !defined(OFFICIAL_BUILD)
  3790. // Disable renderer code integrity when Application Verifier or pageheap are
  3791. // enabled for chrome.exe to avoid renderer crashes. https://crbug.com/1004989
  3792. if (base::win::IsAppVerifierEnabled(chrome::kBrowserProcessExecutableName))
  3793. enforce_code_integrity = false;
  3794. #endif // !defined(OFFICIAL_BUILD)
  3795. if (!enforce_code_integrity)
  3796. return true;
  3797. // Only enable signing mitigation if launching from chrome.exe.
  3798. base::FilePath exe_path;
  3799. if (!base::PathService::Get(base::FILE_EXE, &exe_path))
  3800. return true;
  3801. if (chrome::kBrowserProcessExecutableName != exe_path.BaseName().value())
  3802. return true;
  3803. sandbox::MitigationFlags mitigations = policy->GetProcessMitigations();
  3804. mitigations |= sandbox::MITIGATION_FORCE_MS_SIGNED_BINS;
  3805. sandbox::ResultCode result = policy->SetProcessMitigations(mitigations);
  3806. if (result != sandbox::SBOX_ALL_OK)
  3807. return false;
  3808. if (policy->GetConfig()->IsConfigured())
  3809. return true;
  3810. // Allow loading Chrome's DLLs.
  3811. for (const auto* dll : {chrome::kBrowserResourcesDll, chrome::kElfDll}) {
  3812. result = policy->GetConfig()->AddRule(sandbox::SubSystem::kSignedBinary,
  3813. sandbox::Semantics::kSignedAllowLoad,
  3814. GetModulePath(dll).value().c_str());
  3815. if (result != sandbox::SBOX_ALL_OK)
  3816. return false;
  3817. }
  3818. #endif // !defined(COMPONENT_BUILD) && !defined(ADDRESS_SANITIZER)
  3819. return true;
  3820. }
  3821. bool ChromeContentBrowserClient::IsRendererCodeIntegrityEnabled() {
  3822. PrefService* local_state = g_browser_process->local_state();
  3823. if (local_state &&
  3824. local_state->HasPrefPath(prefs::kRendererCodeIntegrityEnabled) &&
  3825. !local_state->GetBoolean(prefs::kRendererCodeIntegrityEnabled))
  3826. return false;
  3827. return true;
  3828. }
  3829. // Note: Only use sparingly to add Chrome specific sandbox functionality here.
  3830. // Other code should reside in the content layer. Changes to this function
  3831. // should be reviewed by the security team.
  3832. bool ChromeContentBrowserClient::IsUtilityCetCompatible(
  3833. const std::string& utility_sub_type) {
  3834. if (utility_sub_type == chrome::mojom::UtilWin::Name_)
  3835. return false;
  3836. return true;
  3837. }
  3838. void ChromeContentBrowserClient::SessionEnding() {
  3839. chrome::SessionEnding();
  3840. }
  3841. bool ChromeContentBrowserClient::ShouldEnableAudioProcessHighPriority() {
  3842. return IsAudioProcessHighPriorityEnabled();
  3843. }
  3844. #endif // BUILDFLAG(IS_WIN)
  3845. void ChromeContentBrowserClient::
  3846. RegisterMojoBinderPoliciesForSameOriginPrerendering(
  3847. content::MojoBinderPolicyMap& policy_map) {
  3848. // Changes to `policy_map` should be made in
  3849. // RegisterChromeMojoBinderPoliciesForSameOriginPrerendering() which requires
  3850. // security review.
  3851. RegisterChromeMojoBinderPoliciesForSameOriginPrerendering(policy_map);
  3852. }
  3853. void ChromeContentBrowserClient::OpenURL(
  3854. content::SiteInstance* site_instance,
  3855. const content::OpenURLParams& params,
  3856. base::OnceCallback<void(content::WebContents*)> callback) {
  3857. DCHECK_CURRENTLY_ON(BrowserThread::UI);
  3858. content::BrowserContext* browser_context = site_instance->GetBrowserContext();
  3859. #if BUILDFLAG(IS_ANDROID)
  3860. ServiceTabLauncher::GetInstance()->LaunchTab(browser_context, params,
  3861. std::move(callback));
  3862. #else
  3863. NavigateParams nav_params(Profile::FromBrowserContext(browser_context),
  3864. params.url, params.transition);
  3865. nav_params.FillNavigateParamsFromOpenURLParams(params);
  3866. Navigate(&nav_params);
  3867. std::move(callback).Run(nav_params.navigated_or_inserted_contents);
  3868. #endif
  3869. }
  3870. content::ControllerPresentationServiceDelegate*
  3871. ChromeContentBrowserClient::GetControllerPresentationServiceDelegate(
  3872. content::WebContents* web_contents) {
  3873. if (media_router::MediaRouterEnabled(web_contents->GetBrowserContext())) {
  3874. return media_router::PresentationServiceDelegateImpl::
  3875. GetOrCreateForWebContents(web_contents);
  3876. }
  3877. return nullptr;
  3878. }
  3879. content::ReceiverPresentationServiceDelegate*
  3880. ChromeContentBrowserClient::GetReceiverPresentationServiceDelegate(
  3881. content::WebContents* web_contents) {
  3882. if (media_router::MediaRouterEnabled(web_contents->GetBrowserContext())) {
  3883. // ReceiverPresentationServiceDelegateImpl exists only for WebContents
  3884. // created for offscreen presentations. The WebContents must belong to
  3885. // an incognito profile.
  3886. if (auto* impl = media_router::ReceiverPresentationServiceDelegateImpl::
  3887. FromWebContents(web_contents)) {
  3888. DCHECK(web_contents->GetBrowserContext()->IsOffTheRecord());
  3889. return impl;
  3890. }
  3891. }
  3892. return nullptr;
  3893. }
  3894. void ChromeContentBrowserClient::AddPresentationObserver(
  3895. content::PresentationObserver* observer,
  3896. content::WebContents* web_contents) {
  3897. if (media_router::MediaRouterEnabled(web_contents->GetBrowserContext())) {
  3898. media_router::WebContentsPresentationManager::Get(web_contents)
  3899. ->AddObserver(observer);
  3900. }
  3901. }
  3902. void ChromeContentBrowserClient::RemovePresentationObserver(
  3903. content::PresentationObserver* observer,
  3904. content::WebContents* web_contents) {
  3905. if (media_router::MediaRouterEnabled(web_contents->GetBrowserContext())) {
  3906. media_router::WebContentsPresentationManager::Get(web_contents)
  3907. ->RemoveObserver(observer);
  3908. }
  3909. }
  3910. std::vector<std::unique_ptr<content::NavigationThrottle>>
  3911. ChromeContentBrowserClient::CreateThrottlesForNavigation(
  3912. content::NavigationHandle* handle) {
  3913. std::vector<std::unique_ptr<content::NavigationThrottle>> throttles;
  3914. // MetricsNavigationThrottle requires that it runs before NavigationThrottles
  3915. // that may delay or cancel navigations, so only NavigationThrottles that
  3916. // don't delay or cancel navigations (e.g. throttles that are only observing
  3917. // callbacks without affecting navigation behavior) should be added before
  3918. // MetricsNavigationThrottle.
  3919. if (handle->IsInMainFrame()) {
  3920. throttles.push_back(
  3921. page_load_metrics::MetricsNavigationThrottle::Create(handle));
  3922. }
  3923. #if BUILDFLAG(ENABLE_SUPERVISED_USERS)
  3924. MaybeAddThrottle(
  3925. SupervisedUserNavigationThrottle::MaybeCreateThrottleFor(handle),
  3926. &throttles);
  3927. #endif
  3928. #if BUILDFLAG(IS_ANDROID)
  3929. // TODO(davidben): This is insufficient to integrate with prerender properly.
  3930. // https://crbug.com/370595
  3931. prerender::NoStatePrefetchContents* no_state_prefetch_contents =
  3932. prerender::ChromeNoStatePrefetchContentsDelegate::FromWebContents(
  3933. handle->GetWebContents());
  3934. if (!no_state_prefetch_contents) {
  3935. MaybeAddThrottle(
  3936. navigation_interception::InterceptNavigationDelegate::
  3937. MaybeCreateThrottleFor(
  3938. handle, navigation_interception::SynchronyMode::kAsync),
  3939. &throttles);
  3940. }
  3941. throttles.push_back(InterceptOMADownloadNavigationThrottle::Create(handle));
  3942. #if BUILDFLAG(DFMIFY_DEV_UI)
  3943. // If the DevUI DFM is already installed, then this is a no-op, except for the
  3944. // side effect of ensuring that the DevUI DFM is loaded.
  3945. MaybeAddThrottle(dev_ui::DevUiLoaderThrottle::MaybeCreateThrottleFor(handle),
  3946. &throttles);
  3947. #endif // BUILDFLAG(DFMIFY_DEV_UI)
  3948. #elif BUILDFLAG(ENABLE_EXTENSIONS)
  3949. // Redirect some navigations to apps that have registered matching URL
  3950. // handlers ('url_handlers' in the manifest).
  3951. MaybeAddThrottle(
  3952. PlatformAppNavigationRedirector::MaybeCreateThrottleFor(handle),
  3953. &throttles);
  3954. #endif
  3955. #if BUILDFLAG(IS_CHROMEOS_ASH)
  3956. // Check if we need to add merge session throttle. This throttle will postpone
  3957. // loading of main frames.
  3958. if (handle->IsInMainFrame()) {
  3959. // Add interstitial page while merge session process (cookie reconstruction
  3960. // from OAuth2 refresh token in ChromeOS login) is still in progress while
  3961. // we are attempting to load a google property.
  3962. if (ash::merge_session_throttling_utils::ShouldAttachNavigationThrottle() &&
  3963. !ash::merge_session_throttling_utils::AreAllSessionMergedAlready() &&
  3964. handle->GetURL().SchemeIsHTTPOrHTTPS()) {
  3965. throttles.push_back(ash::MergeSessionNavigationThrottle::Create(handle));
  3966. }
  3967. }
  3968. #endif
  3969. #if !BUILDFLAG(IS_ANDROID)
  3970. auto url_to_apps_throttle =
  3971. #if BUILDFLAG(IS_CHROMEOS)
  3972. apps::CommonAppsNavigationThrottle::MaybeCreate(handle);
  3973. #else
  3974. apps::AppsNavigationThrottle::MaybeCreate(handle);
  3975. #endif
  3976. if (url_to_apps_throttle)
  3977. throttles.push_back(std::move(url_to_apps_throttle));
  3978. #endif
  3979. #if BUILDFLAG(ENABLE_EXTENSIONS)
  3980. throttles.push_back(
  3981. std::make_unique<extensions::ExtensionNavigationThrottle>(handle));
  3982. MaybeAddThrottle(extensions::ExtensionsBrowserClient::Get()
  3983. ->GetUserScriptListener()
  3984. ->CreateNavigationThrottle(handle),
  3985. &throttles);
  3986. #endif
  3987. #if BUILDFLAG(ENABLE_SUPERVISED_USERS)
  3988. MaybeAddThrottle(
  3989. SupervisedUserGoogleAuthNavigationThrottle::MaybeCreate(handle),
  3990. &throttles);
  3991. #endif
  3992. if (auto* throttle_manager =
  3993. subresource_filter::ContentSubresourceFilterThrottleManager::
  3994. FromNavigationHandle(*handle)) {
  3995. throttle_manager->MaybeAppendNavigationThrottles(handle, &throttles);
  3996. }
  3997. MaybeAddThrottle(
  3998. LookalikeUrlNavigationThrottle::MaybeCreateNavigationThrottle(handle),
  3999. &throttles);
  4000. MaybeAddThrottle(PDFIFrameNavigationThrottle::MaybeCreateThrottleFor(handle),
  4001. &throttles);
  4002. #if BUILDFLAG(ENABLE_PDF)
  4003. MaybeAddThrottle(pdf::PdfNavigationThrottle::MaybeCreateThrottleFor(
  4004. handle, std::make_unique<ChromePdfStreamDelegate>()),
  4005. &throttles);
  4006. #endif // BUILDFLAG(ENABLE_PDF)
  4007. MaybeAddThrottle(TabUnderNavigationThrottle::MaybeCreate(handle), &throttles);
  4008. MaybeAddThrottle(
  4009. WellKnownChangePasswordNavigationThrottle::MaybeCreateThrottleFor(handle),
  4010. &throttles);
  4011. MaybeAddThrottle(
  4012. PasswordManagerNavigationThrottle::MaybeCreateThrottleFor(handle),
  4013. &throttles);
  4014. throttles.push_back(std::make_unique<PolicyBlocklistNavigationThrottle>(
  4015. handle, handle->GetWebContents()->GetBrowserContext()));
  4016. // Before setting up SSL error detection, configure SSLErrorHandler to invoke
  4017. // the relevant extension API whenever an SSL interstitial is shown.
  4018. SSLErrorHandler::SetClientCallbackOnInterstitialsShown(
  4019. base::BindRepeating(&MaybeTriggerSecurityInterstitialShownEvent));
  4020. content::WebContents* web_contents = handle->GetWebContents();
  4021. throttles.push_back(std::make_unique<SSLErrorNavigationThrottle>(
  4022. handle,
  4023. std::make_unique<CertificateReportingServiceCertReporter>(web_contents),
  4024. base::BindOnce(&HandleSSLErrorWrapper), base::BindOnce(&IsInHostedApp),
  4025. base::BindOnce(
  4026. &ShouldIgnoreSslInterstitialBecauseNavigationDefaultedToHttps)));
  4027. throttles.push_back(std::make_unique<LoginNavigationThrottle>(handle));
  4028. if (base::FeatureList::IsEnabled(omnibox::kDefaultTypedNavigationsToHttps)) {
  4029. MaybeAddThrottle(
  4030. TypedNavigationUpgradeThrottle::MaybeCreateThrottleFor(handle),
  4031. &throttles);
  4032. }
  4033. #if BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_MAC) || BUILDFLAG(IS_WIN)
  4034. MaybeAddThrottle(
  4035. WebAppSettingsNavigationThrottle::MaybeCreateThrottleFor(handle),
  4036. &throttles);
  4037. #endif // BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_MAC) || BUILDFLAG(IS_WIN)
  4038. #if BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_MAC) || BUILDFLAG(IS_WIN) || \
  4039. BUILDFLAG(IS_CHROMEOS_ASH)
  4040. MaybeAddThrottle(enterprise_connectors::DeviceTrustNavigationThrottle::
  4041. MaybeCreateThrottleFor(handle),
  4042. &throttles);
  4043. #endif // BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_MAC) || BUILDFLAG(IS_WIN) ||
  4044. // BUILDFLAG(IS_CHROMEOS_ASH)
  4045. #if !BUILDFLAG(IS_ANDROID)
  4046. MaybeAddThrottle(DevToolsWindow::MaybeCreateNavigationThrottle(handle),
  4047. &throttles);
  4048. MaybeAddThrottle(NewTabPageNavigationThrottle::MaybeCreateThrottleFor(handle),
  4049. &throttles);
  4050. #endif
  4051. // g_browser_process->safe_browsing_service() may be null in unittests.
  4052. safe_browsing::SafeBrowsingUIManager* ui_manager =
  4053. g_browser_process->safe_browsing_service()
  4054. ? g_browser_process->safe_browsing_service()->ui_manager().get()
  4055. : nullptr;
  4056. MaybeAddThrottle(
  4057. safe_browsing::SafeBrowsingNavigationThrottle::MaybeCreateThrottleFor(
  4058. handle, ui_manager),
  4059. &throttles);
  4060. if (base::FeatureList::IsEnabled(safe_browsing::kDelayedWarnings)) {
  4061. throttles.push_back(
  4062. std::make_unique<safe_browsing::DelayedWarningNavigationThrottle>(
  4063. handle));
  4064. }
  4065. // TODO(crbug.com/1052397): Revisit the macro expression once build flag switch
  4066. // of lacros-chrome is complete.
  4067. #if BUILDFLAG(IS_WIN) || BUILDFLAG(IS_MAC) || \
  4068. (BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS_LACROS))
  4069. MaybeAddThrottle(browser_switcher::BrowserSwitcherNavigationThrottle::
  4070. MaybeCreateThrottleFor(handle),
  4071. &throttles);
  4072. #endif
  4073. #if BUILDFLAG(IS_CHROMEOS_ASH)
  4074. MaybeAddThrottle(
  4075. chromeos::KioskSettingsNavigationThrottle::MaybeCreateThrottleFor(handle),
  4076. &throttles);
  4077. #endif
  4078. #if BUILDFLAG(IS_MAC)
  4079. if (__builtin_available(macOS 10.15, *)) {
  4080. MaybeAddThrottle(MaybeCreateAuthSessionThrottleFor(handle), &throttles);
  4081. }
  4082. #endif
  4083. auto* performance_manager_registry =
  4084. performance_manager::PerformanceManagerRegistry::GetInstance();
  4085. if (performance_manager_registry) {
  4086. MaybeAddThrottles(
  4087. performance_manager_registry->CreateThrottlesForNavigation(handle),
  4088. &throttles);
  4089. }
  4090. Profile* profile = Profile::FromBrowserContext(
  4091. handle->GetWebContents()->GetBrowserContext());
  4092. if (profile && profile->GetPrefs()) {
  4093. MaybeAddThrottle(
  4094. security_interstitials::InsecureFormNavigationThrottle::
  4095. MaybeCreateNavigationThrottle(
  4096. handle, std::make_unique<ChromeSecurityBlockingPageFactory>(),
  4097. profile->GetPrefs()),
  4098. &throttles);
  4099. }
  4100. if (IsErrorPageAutoReloadEnabled()) {
  4101. MaybeAddThrottle(
  4102. error_page::NetErrorAutoReloader::MaybeCreateThrottleFor(handle),
  4103. &throttles);
  4104. }
  4105. MaybeAddThrottle(
  4106. payments::PaymentHandlerNavigationThrottle::MaybeCreateThrottleFor(
  4107. handle),
  4108. &throttles);
  4109. MaybeAddThrottle(
  4110. prerender::NoStatePrefetchNavigationThrottle::MaybeCreateThrottleFor(
  4111. handle),
  4112. &throttles);
  4113. #if defined(TOOLKIT_VIEWS)
  4114. if (profile && IsSideSearchEnabled(profile)) {
  4115. MaybeAddThrottle(
  4116. SideSearchSideContentsHelper::MaybeCreateThrottleFor(handle),
  4117. &throttles);
  4118. }
  4119. #endif
  4120. #if BUILDFLAG(ENABLE_OFFLINE_PAGES)
  4121. MaybeAddThrottle(
  4122. offline_pages::OfflinePageNavigationThrottle::MaybeCreateThrottleFor(
  4123. handle),
  4124. &throttles);
  4125. #endif
  4126. if (profile && profile->GetPrefs()) {
  4127. MaybeAddThrottle(
  4128. HttpsOnlyModeNavigationThrottle::MaybeCreateThrottleFor(
  4129. handle, std::make_unique<ChromeSecurityBlockingPageFactory>(),
  4130. profile->GetPrefs()),
  4131. &throttles);
  4132. }
  4133. MaybeAddThrottle(MaybeCreateNavigationAblationThrottle(handle), &throttles);
  4134. #if !BUILDFLAG(IS_ANDROID)
  4135. MaybeAddThrottle(MaybeCreateAboutThisSiteThrottleFor(handle), &throttles);
  4136. #endif
  4137. return throttles;
  4138. }
  4139. std::vector<std::unique_ptr<content::CommitDeferringCondition>>
  4140. ChromeContentBrowserClient::CreateCommitDeferringConditionsForNavigation(
  4141. content::NavigationHandle* navigation_handle,
  4142. content::CommitDeferringCondition::NavigationType navigation_type) {
  4143. auto conditions =
  4144. std::vector<std::unique_ptr<content::CommitDeferringCondition>>();
  4145. #if BUILDFLAG(SAFE_BROWSING_AVAILABLE)
  4146. MaybeAddCondition(
  4147. safe_browsing::MaybeCreateCommitDeferringCondition(*navigation_handle),
  4148. &conditions);
  4149. #endif
  4150. return conditions;
  4151. }
  4152. std::unique_ptr<content::NavigationUIData>
  4153. ChromeContentBrowserClient::GetNavigationUIData(
  4154. content::NavigationHandle* navigation_handle) {
  4155. return std::make_unique<ChromeNavigationUIData>(navigation_handle);
  4156. }
  4157. std::unique_ptr<media::ScreenEnumerator>
  4158. ChromeContentBrowserClient::CreateScreenEnumerator() const {
  4159. return std::make_unique<ChromeScreenEnumerator>();
  4160. }
  4161. std::unique_ptr<content::DevToolsManagerDelegate>
  4162. ChromeContentBrowserClient::CreateDevToolsManagerDelegate() {
  4163. #if BUILDFLAG(IS_ANDROID)
  4164. return std::make_unique<DevToolsManagerDelegateAndroid>();
  4165. #else
  4166. return std::make_unique<ChromeDevToolsManagerDelegate>();
  4167. #endif
  4168. }
  4169. void ChromeContentBrowserClient::UpdateDevToolsBackgroundServiceExpiration(
  4170. content::BrowserContext* browser_context,
  4171. int service,
  4172. base::Time expiration_time) {
  4173. Profile* profile = Profile::FromBrowserContext(browser_context);
  4174. DCHECK(profile);
  4175. auto* pref_service = profile->GetPrefs();
  4176. DCHECK(pref_service);
  4177. DictionaryPrefUpdate pref_update(
  4178. pref_service, prefs::kDevToolsBackgroundServicesExpirationDict);
  4179. base::Value* exp_dict = pref_update.Get();
  4180. // Convert |expiration_time| to minutes since that is the most granular
  4181. // option that returns an int. base::Value does not accept int64.
  4182. int expiration_time_minutes =
  4183. expiration_time.ToDeltaSinceWindowsEpoch().InMinutes();
  4184. exp_dict->SetIntKey(base::NumberToString(service), expiration_time_minutes);
  4185. }
  4186. base::flat_map<int, base::Time>
  4187. ChromeContentBrowserClient::GetDevToolsBackgroundServiceExpirations(
  4188. content::BrowserContext* browser_context) {
  4189. Profile* profile = Profile::FromBrowserContext(browser_context);
  4190. DCHECK(profile);
  4191. auto* pref_service = profile->GetPrefs();
  4192. DCHECK(pref_service);
  4193. const auto& expiration_dict = pref_service->GetValueDict(
  4194. prefs::kDevToolsBackgroundServicesExpirationDict);
  4195. base::flat_map<int, base::Time> expiration_times;
  4196. for (auto it : expiration_dict) {
  4197. // key.
  4198. int service = 0;
  4199. bool did_convert = base::StringToInt(it.first, &service);
  4200. DCHECK(did_convert);
  4201. // value.
  4202. DCHECK(it.second.is_int());
  4203. base::TimeDelta delta = base::Minutes(it.second.GetInt());
  4204. base::Time expiration_time = base::Time::FromDeltaSinceWindowsEpoch(delta);
  4205. expiration_times[service] = expiration_time;
  4206. }
  4207. return expiration_times;
  4208. }
  4209. content::TracingDelegate* ChromeContentBrowserClient::GetTracingDelegate() {
  4210. return new ChromeTracingDelegate();
  4211. }
  4212. bool ChromeContentBrowserClient::IsPluginAllowedToCallRequestOSFileHandle(
  4213. content::BrowserContext* browser_context,
  4214. const GURL& url) {
  4215. #if BUILDFLAG(ENABLE_PLUGINS) && BUILDFLAG(ENABLE_EXTENSIONS)
  4216. return ChromeContentBrowserClientPluginsPart::
  4217. IsPluginAllowedToCallRequestOSFileHandle(browser_context, url);
  4218. #else
  4219. return false;
  4220. #endif
  4221. }
  4222. bool ChromeContentBrowserClient::IsPluginAllowedToUseDevChannelAPIs(
  4223. content::BrowserContext* browser_context,
  4224. const GURL& url) {
  4225. #if BUILDFLAG(ENABLE_PLUGINS) && BUILDFLAG(ENABLE_EXTENSIONS)
  4226. return ChromeContentBrowserClientPluginsPart::
  4227. IsPluginAllowedToUseDevChannelAPIs(browser_context, url);
  4228. #else
  4229. return false;
  4230. #endif
  4231. }
  4232. void ChromeContentBrowserClient::OverridePageVisibilityState(
  4233. RenderFrameHost* render_frame_host,
  4234. content::PageVisibilityState* visibility_state) {
  4235. DCHECK_CURRENTLY_ON(BrowserThread::UI);
  4236. WebContents* web_contents =
  4237. WebContents::FromRenderFrameHost(render_frame_host);
  4238. DCHECK(web_contents);
  4239. prerender::NoStatePrefetchManager* no_state_prefetch_manager =
  4240. prerender::NoStatePrefetchManagerFactory::GetForBrowserContext(
  4241. web_contents->GetBrowserContext());
  4242. if (no_state_prefetch_manager &&
  4243. no_state_prefetch_manager->IsWebContentsPrefetching(web_contents)) {
  4244. *visibility_state = content::PageVisibilityState::kHiddenButPainting;
  4245. }
  4246. }
  4247. void ChromeContentBrowserClient::InitOnUIThread() {
  4248. DCHECK_CURRENTLY_ON(BrowserThread::UI);
  4249. safe_browsing_service_ = g_browser_process->safe_browsing_service();
  4250. // Initialize `network_contexts_parent_directory_`.
  4251. base::FilePath user_data_dir;
  4252. base::PathService::Get(chrome::DIR_USER_DATA, &user_data_dir);
  4253. DCHECK(!user_data_dir.empty());
  4254. network_contexts_parent_directory_.push_back(user_data_dir);
  4255. base::FilePath cache_dir;
  4256. chrome::GetUserCacheDirectory(user_data_dir, &cache_dir);
  4257. DCHECK(!cache_dir.empty());
  4258. // On some platforms, the cache is a child of the user_data_dir so only
  4259. // return the one path.
  4260. if (!user_data_dir.IsParent(cache_dir))
  4261. network_contexts_parent_directory_.push_back(cache_dir);
  4262. // If the cache location has been overridden by a switch or preference,
  4263. // include that as well.
  4264. if (auto* local_state = g_browser_process->local_state()) {
  4265. base::FilePath pref_cache_dir =
  4266. local_state->GetFilePath(prefs::kDiskCacheDir);
  4267. if (!pref_cache_dir.empty() && !user_data_dir.IsParent(cache_dir))
  4268. network_contexts_parent_directory_.push_back(pref_cache_dir);
  4269. }
  4270. }
  4271. void ChromeContentBrowserClient::MaybeCopyDisableWebRtcEncryptionSwitch(
  4272. base::CommandLine* to_command_line,
  4273. const base::CommandLine& from_command_line,
  4274. version_info::Channel channel) {
  4275. #if BUILDFLAG(IS_ANDROID)
  4276. const version_info::Channel kMaxDisableEncryptionChannel =
  4277. version_info::Channel::BETA;
  4278. #else
  4279. const version_info::Channel kMaxDisableEncryptionChannel =
  4280. version_info::Channel::DEV;
  4281. #endif
  4282. if (channel <= kMaxDisableEncryptionChannel) {
  4283. static const char* const kWebRtcDevSwitchNames[] = {
  4284. switches::kDisableWebRtcEncryption,
  4285. };
  4286. to_command_line->CopySwitchesFrom(from_command_line, kWebRtcDevSwitchNames,
  4287. std::size(kWebRtcDevSwitchNames));
  4288. }
  4289. }
  4290. #if BUILDFLAG(ENABLE_MEDIA_REMOTING)
  4291. void ChromeContentBrowserClient::CreateMediaRemoter(
  4292. content::RenderFrameHost* render_frame_host,
  4293. mojo::PendingRemote<media::mojom::RemotingSource> source,
  4294. mojo::PendingReceiver<media::mojom::Remoter> receiver) {
  4295. CastRemotingConnector::CreateMediaRemoter(
  4296. render_frame_host, std::move(source), std::move(receiver));
  4297. }
  4298. #endif // BUILDFLAG(ENABLE_MEDIA_REMOTING)
  4299. base::FilePath ChromeContentBrowserClient::GetLoggingFileName(
  4300. const base::CommandLine& command_line) {
  4301. return logging::GetLogFileName(command_line);
  4302. }
  4303. std::vector<std::unique_ptr<blink::URLLoaderThrottle>>
  4304. ChromeContentBrowserClient::CreateURLLoaderThrottles(
  4305. const network::ResourceRequest& request,
  4306. content::BrowserContext* browser_context,
  4307. const base::RepeatingCallback<content::WebContents*()>& wc_getter,
  4308. content::NavigationUIData* navigation_ui_data,
  4309. int frame_tree_node_id) {
  4310. DCHECK_CURRENTLY_ON(BrowserThread::UI);
  4311. std::vector<std::unique_ptr<blink::URLLoaderThrottle>> result;
  4312. DCHECK(browser_context);
  4313. Profile* profile = Profile::FromBrowserContext(browser_context);
  4314. DCHECK(profile);
  4315. ChromeNavigationUIData* chrome_navigation_ui_data =
  4316. static_cast<ChromeNavigationUIData*>(navigation_ui_data);
  4317. url_param_filter::UrlParamFilterThrottle::MaybeCreateThrottle(
  4318. profile->GetPrefs()->GetBoolean(
  4319. policy::policy_prefs::kUrlParamFilterEnabled),
  4320. wc_getter.Run(), request, &result);
  4321. #if BUILDFLAG(SAFE_BROWSING_AVAILABLE)
  4322. bool matches_enterprise_allowlist = safe_browsing::IsURLAllowlistedByPolicy(
  4323. request.url, *profile->GetPrefs());
  4324. if (!matches_enterprise_allowlist) {
  4325. #if BUILDFLAG(SAFE_BROWSING_DB_LOCAL)
  4326. auto* connectors_service =
  4327. enterprise_connectors::ConnectorsServiceFactory::GetForBrowserContext(
  4328. browser_context);
  4329. bool has_valid_dm_token =
  4330. connectors_service &&
  4331. connectors_service->GetDMTokenForRealTimeUrlCheck().has_value();
  4332. bool is_enterprise_lookup_enabled =
  4333. safe_browsing::RealTimePolicyEngine::CanPerformEnterpriseFullURLLookup(
  4334. profile->GetPrefs(), has_valid_dm_token, profile->IsOffTheRecord());
  4335. #else
  4336. bool is_enterprise_lookup_enabled = false;
  4337. #endif
  4338. bool is_consumer_lookup_enabled =
  4339. safe_browsing::RealTimePolicyEngine::CanPerformFullURLLookup(
  4340. profile->GetPrefs(), profile->IsOffTheRecord(),
  4341. g_browser_process->variations_service());
  4342. // |url_lookup_service| is used when real time url check is enabled.
  4343. safe_browsing::RealTimeUrlLookupServiceBase* url_lookup_service =
  4344. GetUrlLookupService(browser_context, is_enterprise_lookup_enabled,
  4345. is_consumer_lookup_enabled);
  4346. result.push_back(safe_browsing::BrowserURLLoaderThrottle::Create(
  4347. base::BindOnce(
  4348. &ChromeContentBrowserClient::GetSafeBrowsingUrlCheckerDelegate,
  4349. base::Unretained(this),
  4350. safe_browsing::IsSafeBrowsingEnabled(*profile->GetPrefs()),
  4351. // Should check for enterprise when safe browsing is disabled.
  4352. /*should_check_on_sb_disabled=*/is_enterprise_lookup_enabled,
  4353. safe_browsing::GetURLAllowlistByPolicy(profile->GetPrefs())),
  4354. wc_getter, frame_tree_node_id,
  4355. url_lookup_service ? url_lookup_service->GetWeakPtr() : nullptr));
  4356. }
  4357. #endif
  4358. #if BUILDFLAG(ENABLE_CAPTIVE_PORTAL_DETECTION)
  4359. result.push_back(
  4360. std::make_unique<captive_portal::CaptivePortalURLLoaderThrottle>(
  4361. wc_getter.Run()));
  4362. #endif
  4363. if (chrome_navigation_ui_data &&
  4364. chrome_navigation_ui_data->is_no_state_prefetching()) {
  4365. result.push_back(std::make_unique<prerender::PrerenderURLLoaderThrottle>(
  4366. chrome_navigation_ui_data->prerender_histogram_prefix(),
  4367. GetPrerenderCanceler(wc_getter)));
  4368. }
  4369. #if BUILDFLAG(IS_ANDROID)
  4370. std::string client_data_header;
  4371. bool is_tab_large_enough = false;
  4372. bool is_custom_tab = false;
  4373. if (frame_tree_node_id != content::RenderFrameHost::kNoFrameTreeNodeId) {
  4374. auto* web_contents = WebContents::FromFrameTreeNodeId(frame_tree_node_id);
  4375. // Could be null if the FrameTreeNode's RenderFrameHost is shutting down.
  4376. if (web_contents) {
  4377. auto* client_data_header_observer =
  4378. customtabs::ClientDataHeaderWebContentsObserver::FromWebContents(
  4379. web_contents);
  4380. if (client_data_header_observer)
  4381. client_data_header = client_data_header_observer->header();
  4382. auto* delegate =
  4383. TabAndroid::FromWebContents(web_contents)
  4384. ? static_cast<android::TabWebContentsDelegateAndroid*>(
  4385. web_contents->GetDelegate())
  4386. : nullptr;
  4387. if (delegate) {
  4388. is_tab_large_enough = delegate->IsTabLargeEnoughForDesktopSite();
  4389. is_custom_tab = delegate->IsCustomTab();
  4390. }
  4391. }
  4392. }
  4393. #endif
  4394. chrome::mojom::DynamicParams dynamic_params = {
  4395. profile->GetPrefs()->GetBoolean(prefs::kForceGoogleSafeSearch),
  4396. profile->GetPrefs()->GetInteger(prefs::kForceYouTubeRestrict),
  4397. profile->GetPrefs()->GetString(prefs::kAllowedDomainsForApps)};
  4398. result.push_back(std::make_unique<GoogleURLLoaderThrottle>(
  4399. #if BUILDFLAG(IS_ANDROID)
  4400. client_data_header, is_tab_large_enough,
  4401. #endif
  4402. std::move(dynamic_params)));
  4403. {
  4404. auto* factory =
  4405. ProtocolHandlerRegistryFactory::GetForBrowserContext(browser_context);
  4406. // null in unit tests.
  4407. if (factory) {
  4408. result.push_back(
  4409. std::make_unique<custom_handlers::ProtocolHandlerThrottle>(*factory));
  4410. }
  4411. }
  4412. #if BUILDFLAG(ENABLE_PLUGINS)
  4413. result.push_back(std::make_unique<PluginResponseInterceptorURLLoaderThrottle>(
  4414. request.destination, frame_tree_node_id));
  4415. #endif
  4416. #if BUILDFLAG(IS_ANDROID)
  4417. auto delegate = std::make_unique<signin::HeaderModificationDelegateImpl>(
  4418. profile, /*incognito_enabled=*/!is_custom_tab);
  4419. #else
  4420. auto delegate =
  4421. std::make_unique<signin::HeaderModificationDelegateImpl>(profile);
  4422. #endif
  4423. auto signin_throttle =
  4424. signin::URLLoaderThrottle::MaybeCreate(std::move(delegate), wc_getter);
  4425. if (signin_throttle)
  4426. result.push_back(std::move(signin_throttle));
  4427. return result;
  4428. }
  4429. void ChromeContentBrowserClient::RegisterNonNetworkNavigationURLLoaderFactories(
  4430. int frame_tree_node_id,
  4431. ukm::SourceIdObj ukm_source_id,
  4432. NonNetworkURLLoaderFactoryMap* factories) {
  4433. #if BUILDFLAG(ENABLE_EXTENSIONS) || BUILDFLAG(IS_CHROMEOS_ASH)
  4434. content::WebContents* web_contents =
  4435. content::WebContents::FromFrameTreeNodeId(frame_tree_node_id);
  4436. #if BUILDFLAG(ENABLE_EXTENSIONS)
  4437. factories->emplace(
  4438. extensions::kExtensionScheme,
  4439. extensions::CreateExtensionNavigationURLLoaderFactory(
  4440. web_contents->GetBrowserContext(), ukm_source_id,
  4441. !!extensions::WebViewGuest::FromWebContents(web_contents)));
  4442. #endif // BUILDFLAG(ENABLE_EXTENSIONS)
  4443. #if BUILDFLAG(IS_CHROMEOS_ASH)
  4444. Profile* profile =
  4445. Profile::FromBrowserContext(web_contents->GetBrowserContext());
  4446. factories->emplace(content::kExternalFileScheme,
  4447. chromeos::ExternalFileURLLoaderFactory::Create(
  4448. profile, content::ChildProcessHost::kInvalidUniqueID));
  4449. #endif // BUILDFLAG(IS_CHROMEOS_ASH)
  4450. #endif // BUILDFLAG(ENABLE_EXTENSIONS) || BUILDFLAG(IS_CHROMEOS_ASH)
  4451. }
  4452. void ChromeContentBrowserClient::
  4453. RegisterNonNetworkWorkerMainResourceURLLoaderFactories(
  4454. content::BrowserContext* browser_context,
  4455. NonNetworkURLLoaderFactoryMap* factories) {
  4456. DCHECK(browser_context);
  4457. DCHECK(factories);
  4458. #if BUILDFLAG(ENABLE_EXTENSIONS)
  4459. factories->emplace(
  4460. extensions::kExtensionScheme,
  4461. extensions::CreateExtensionWorkerMainResourceURLLoaderFactory(
  4462. browser_context));
  4463. #endif // BUILDFLAG(ENABLE_EXTENSIONS)
  4464. }
  4465. void ChromeContentBrowserClient::
  4466. RegisterNonNetworkServiceWorkerUpdateURLLoaderFactories(
  4467. content::BrowserContext* browser_context,
  4468. NonNetworkURLLoaderFactoryMap* factories) {
  4469. DCHECK(browser_context);
  4470. DCHECK(factories);
  4471. #if BUILDFLAG(ENABLE_EXTENSIONS)
  4472. factories->emplace(
  4473. extensions::kExtensionScheme,
  4474. extensions::CreateExtensionServiceWorkerScriptURLLoaderFactory(
  4475. browser_context));
  4476. #endif // BUILDFLAG(ENABLE_EXTENSIONS)
  4477. }
  4478. namespace {
  4479. // The SpecialAccessFileURLLoaderFactory provided to the extension background
  4480. // pages. Checks with the ChildProcessSecurityPolicy to validate the file
  4481. // access.
  4482. class SpecialAccessFileURLLoaderFactory
  4483. : public network::SelfDeletingURLLoaderFactory {
  4484. public:
  4485. // Returns mojo::PendingRemote to a newly constructed
  4486. // SpecialAccessFileURLLoaderFactory. The factory is self-owned - it will
  4487. // delete itself once there are no more receivers (including the receiver
  4488. // associated with the returned mojo::PendingRemote and the receivers bound by
  4489. // the Clone method).
  4490. static mojo::PendingRemote<network::mojom::URLLoaderFactory> Create(
  4491. int child_id) {
  4492. mojo::PendingRemote<network::mojom::URLLoaderFactory> pending_remote;
  4493. // The SpecialAccessFileURLLoaderFactory will delete itself when there are
  4494. // no more receivers - see the
  4495. // network::SelfDeletingURLLoaderFactory::OnDisconnect method.
  4496. new SpecialAccessFileURLLoaderFactory(
  4497. child_id, pending_remote.InitWithNewPipeAndPassReceiver());
  4498. return pending_remote;
  4499. }
  4500. SpecialAccessFileURLLoaderFactory(const SpecialAccessFileURLLoaderFactory&) =
  4501. delete;
  4502. SpecialAccessFileURLLoaderFactory& operator=(
  4503. const SpecialAccessFileURLLoaderFactory&) = delete;
  4504. private:
  4505. explicit SpecialAccessFileURLLoaderFactory(
  4506. int child_id,
  4507. mojo::PendingReceiver<network::mojom::URLLoaderFactory> factory_receiver)
  4508. : network::SelfDeletingURLLoaderFactory(std::move(factory_receiver)),
  4509. child_id_(child_id) {}
  4510. // network::mojom::URLLoaderFactory:
  4511. void CreateLoaderAndStart(
  4512. mojo::PendingReceiver<network::mojom::URLLoader> loader,
  4513. int32_t request_id,
  4514. uint32_t options,
  4515. const network::ResourceRequest& request,
  4516. mojo::PendingRemote<network::mojom::URLLoaderClient> client,
  4517. const net::MutableNetworkTrafficAnnotationTag& traffic_annotation)
  4518. override {
  4519. if (!content::ChildProcessSecurityPolicy::GetInstance()->CanRequestURL(
  4520. child_id_, request.url)) {
  4521. mojo::Remote<network::mojom::URLLoaderClient>(std::move(client))
  4522. ->OnComplete(
  4523. network::URLLoaderCompletionStatus(net::ERR_ACCESS_DENIED));
  4524. return;
  4525. }
  4526. content::CreateFileURLLoaderBypassingSecurityChecks(
  4527. request, std::move(loader), std::move(client),
  4528. /*observer=*/nullptr,
  4529. /* allow_directory_listing */ true);
  4530. }
  4531. int child_id_;
  4532. };
  4533. #if BUILDFLAG(IS_CHROMEOS)
  4534. bool IsSystemFeatureDisabled(policy::SystemFeature system_feature) {
  4535. return policy::SystemFeaturesDisableListPolicyHandler::
  4536. IsSystemFeatureDisabled(system_feature, g_browser_process->local_state());
  4537. }
  4538. bool IsSystemFeatureURLDisabled(const GURL& url) {
  4539. if (!url.SchemeIs(content::kChromeUIScheme) &&
  4540. !url.SchemeIs(content::kChromeUIUntrustedScheme)) {
  4541. return false;
  4542. }
  4543. // chrome://os-settings/pwa.html shouldn't be replaced to let the settings app
  4544. // installation complete successfully.
  4545. if (url.DomainIs(chrome::kChromeUIOSSettingsHost) &&
  4546. url.path() != "/pwa.html") {
  4547. return IsSystemFeatureDisabled(policy::SystemFeature::kOsSettings);
  4548. }
  4549. if (url.DomainIs(chrome::kChromeUISettingsHost)) {
  4550. return IsSystemFeatureDisabled(policy::SystemFeature::kBrowserSettings);
  4551. }
  4552. #if BUILDFLAG(IS_CHROMEOS_ASH)
  4553. if (url.DomainIs(chrome::kChromeUIUntrustedCroshHost)) {
  4554. return IsSystemFeatureDisabled(policy::SystemFeature::kCrosh);
  4555. }
  4556. if (url.DomainIs(ash::kChromeUIScanningAppHost)) {
  4557. return IsSystemFeatureDisabled(policy::SystemFeature::kScanning);
  4558. }
  4559. if (url.DomainIs(ash::kChromeUICameraAppHost)) {
  4560. return IsSystemFeatureDisabled(policy::SystemFeature::kCamera);
  4561. }
  4562. #endif
  4563. return false;
  4564. }
  4565. #endif
  4566. #if BUILDFLAG(ENABLE_EXTENSIONS)
  4567. void InitializeFileURLLoaderFactoryForExtension(
  4568. int render_process_id,
  4569. content::BrowserContext* browser_context,
  4570. const extensions::Extension* extension,
  4571. ChromeContentBrowserClient::NonNetworkURLLoaderFactoryMap* factories) {
  4572. // Extensions with the necessary permissions get access to file:// URLs that
  4573. // gets approval from ChildProcessSecurityPolicy. Keep this logic in sync with
  4574. // ExtensionWebContentsObserver::RenderFrameCreated.
  4575. Manifest::Type type = extension->GetType();
  4576. if ((type == Manifest::TYPE_EXTENSION ||
  4577. type == Manifest::TYPE_LEGACY_PACKAGED_APP) &&
  4578. extensions::util::AllowFileAccess(extension->id(), browser_context)) {
  4579. factories->emplace(
  4580. url::kFileScheme,
  4581. SpecialAccessFileURLLoaderFactory::Create(render_process_id));
  4582. }
  4583. }
  4584. void AddChromeSchemeFactories(
  4585. int render_process_id,
  4586. content::RenderFrameHost* frame_host,
  4587. content::WebContents* web_contents,
  4588. const extensions::Extension* extension,
  4589. ChromeContentBrowserClient::NonNetworkURLLoaderFactoryMap* factories) {
  4590. Profile* profile =
  4591. Profile::FromBrowserContext(web_contents->GetBrowserContext());
  4592. InstantService* instant_service =
  4593. InstantServiceFactory::GetForProfile(profile);
  4594. // The test below matches when a remote 3P NTP is loaded. The effective
  4595. // URL is chrome-search://remote-ntp. This is to allow the use of the NTP
  4596. // public api and to embed most-visited tiles
  4597. // (chrome-search://most-visited/title.html).
  4598. if (instant_service->IsInstantProcess(render_process_id)) {
  4599. factories->emplace(
  4600. chrome::kChromeSearchScheme,
  4601. content::CreateWebUIURLLoaderFactory(
  4602. frame_host, chrome::kChromeSearchScheme,
  4603. /*allowed_webui_hosts=*/base::flat_set<std::string>()));
  4604. }
  4605. extensions::ChromeExtensionWebContentsObserver* web_observer =
  4606. extensions::ChromeExtensionWebContentsObserver::FromWebContents(
  4607. web_contents);
  4608. // There is nothing to do if no ChromeExtensionWebContentsObserver is attached
  4609. // to the |web_contents| or no enabled extension exists.
  4610. if (!web_observer || !extension)
  4611. return;
  4612. std::vector<std::string> allowed_webui_hosts;
  4613. // Support for chrome:// scheme if appropriate.
  4614. if ((extension->is_extension() || extension->is_platform_app()) &&
  4615. Manifest::IsComponentLocation(extension->location())) {
  4616. // Components of chrome that are implemented as extensions or platform apps
  4617. // are allowed to use chrome://resources/ and chrome://theme/ URLs.
  4618. allowed_webui_hosts.emplace_back(content::kChromeUIResourcesHost);
  4619. allowed_webui_hosts.emplace_back(chrome::kChromeUIThemeHost);
  4620. // For testing purposes chrome://webui-test/ is also allowed.
  4621. allowed_webui_hosts.emplace_back(chrome::kChromeUIWebUITestHost);
  4622. }
  4623. if (extension->is_extension() || extension->is_legacy_packaged_app() ||
  4624. (extension->is_platform_app() &&
  4625. Manifest::IsComponentLocation(extension->location()))) {
  4626. // Extensions, legacy packaged apps, and component platform apps are allowed
  4627. // to use chrome://favicon/, chrome://extension-icon/ and chrome://app-icon
  4628. // URLs. Hosted apps are not allowed because they are served via web servers
  4629. // (and are generally never given access to Chrome APIs).
  4630. allowed_webui_hosts.emplace_back(chrome::kChromeUIExtensionIconHost);
  4631. allowed_webui_hosts.emplace_back(chrome::kChromeUIFaviconHost);
  4632. allowed_webui_hosts.emplace_back(chrome::kChromeUIAppIconHost);
  4633. }
  4634. if (!allowed_webui_hosts.empty()) {
  4635. factories->emplace(content::kChromeUIScheme,
  4636. content::CreateWebUIURLLoaderFactory(
  4637. frame_host, content::kChromeUIScheme,
  4638. std::move(allowed_webui_hosts)));
  4639. }
  4640. }
  4641. #endif // BUILDFLAG(ENABLE_EXTENSIONS)
  4642. } // namespace
  4643. void ChromeContentBrowserClient::
  4644. RegisterNonNetworkSubresourceURLLoaderFactories(
  4645. int render_process_id,
  4646. int render_frame_id,
  4647. const absl::optional<url::Origin>& request_initiator_origin,
  4648. NonNetworkURLLoaderFactoryMap* factories) {
  4649. #if BUILDFLAG(IS_CHROMEOS_ASH) || BUILDFLAG(ENABLE_EXTENSIONS)
  4650. content::RenderFrameHost* frame_host =
  4651. RenderFrameHost::FromID(render_process_id, render_frame_id);
  4652. WebContents* web_contents = WebContents::FromRenderFrameHost(frame_host);
  4653. #endif // BUILDFLAG(IS_CHROMEOS_ASH) || BUILDFLAG(ENABLE_EXTENSIONS)
  4654. #if BUILDFLAG(IS_CHROMEOS_ASH)
  4655. if (web_contents) {
  4656. Profile* profile =
  4657. Profile::FromBrowserContext(web_contents->GetBrowserContext());
  4658. factories->emplace(content::kExternalFileScheme,
  4659. chromeos::ExternalFileURLLoaderFactory::Create(
  4660. profile, render_process_id));
  4661. }
  4662. #endif // BUILDFLAG(IS_CHROMEOS_ASH)
  4663. #if BUILDFLAG(ENABLE_EXTENSIONS)
  4664. factories->emplace(extensions::kExtensionScheme,
  4665. extensions::CreateExtensionURLLoaderFactory(
  4666. render_process_id, render_frame_id));
  4667. content::BrowserContext* browser_context =
  4668. content::RenderProcessHost::FromID(render_process_id)
  4669. ->GetBrowserContext();
  4670. const extensions::Extension* extension = nullptr;
  4671. if (request_initiator_origin != absl::nullopt) {
  4672. extension = extensions::ExtensionRegistry::Get(browser_context)
  4673. ->enabled_extensions()
  4674. .GetExtensionOrAppByURL(request_initiator_origin->GetURL());
  4675. }
  4676. // For service worker contexts, we only allow file access. The remainder of
  4677. // this code is used to allow extensions to access chrome:-scheme
  4678. // resources, which we are moving away from.
  4679. // TODO(crbug.com/1280411) Factories should not be created for unloaded
  4680. // extensions.
  4681. if (extension) {
  4682. InitializeFileURLLoaderFactoryForExtension(
  4683. render_process_id, browser_context, extension, factories);
  4684. }
  4685. // This logic should match
  4686. // ChromeExtensionWebContentsObserver::RenderFrameCreated.
  4687. if (web_contents) {
  4688. AddChromeSchemeFactories(render_process_id, frame_host, web_contents,
  4689. extension, factories);
  4690. }
  4691. #endif // BUILDFLAG(ENABLE_EXTENSIONS)
  4692. }
  4693. bool ChromeContentBrowserClient::WillCreateURLLoaderFactory(
  4694. content::BrowserContext* browser_context,
  4695. content::RenderFrameHost* frame,
  4696. int render_process_id,
  4697. URLLoaderFactoryType type,
  4698. const url::Origin& request_initiator,
  4699. absl::optional<int64_t> navigation_id,
  4700. ukm::SourceIdObj ukm_source_id,
  4701. mojo::PendingReceiver<network::mojom::URLLoaderFactory>* factory_receiver,
  4702. mojo::PendingRemote<network::mojom::TrustedURLLoaderHeaderClient>*
  4703. header_client,
  4704. bool* bypass_redirect_checks,
  4705. bool* disable_secure_dns,
  4706. network::mojom::URLLoaderFactoryOverridePtr* factory_override) {
  4707. bool use_proxy = false;
  4708. #if BUILDFLAG(ENABLE_EXTENSIONS)
  4709. auto* web_request_api =
  4710. extensions::BrowserContextKeyedAPIFactory<extensions::WebRequestAPI>::Get(
  4711. browser_context);
  4712. // NOTE: Some unit test environments do not initialize
  4713. // BrowserContextKeyedAPI factories for e.g. WebRequest.
  4714. if (web_request_api) {
  4715. bool use_proxy_for_web_request =
  4716. web_request_api->MaybeProxyURLLoaderFactory(
  4717. browser_context, frame, render_process_id, type,
  4718. std::move(navigation_id), ukm_source_id, factory_receiver,
  4719. header_client, request_initiator);
  4720. if (bypass_redirect_checks)
  4721. *bypass_redirect_checks = use_proxy_for_web_request;
  4722. use_proxy |= use_proxy_for_web_request;
  4723. }
  4724. #endif
  4725. use_proxy |= signin::ProxyingURLLoaderFactory::MaybeProxyRequest(
  4726. frame, type == URLLoaderFactoryType::kNavigation, request_initiator,
  4727. factory_receiver);
  4728. auto* prefetch_proxy_service = PrefetchProxyServiceFactory::GetForProfile(
  4729. Profile::FromBrowserContext(browser_context));
  4730. // |frame| is null when |type| is service worker.
  4731. if (frame && prefetch_proxy_service) {
  4732. use_proxy |= prefetch_proxy_service->MaybeProxyURLLoaderFactory(
  4733. frame, render_process_id, type, factory_receiver);
  4734. }
  4735. #if BUILDFLAG(ENABLE_CAPTIVE_PORTAL_DETECTION)
  4736. if (disable_secure_dns) {
  4737. WebContents* web_contents = WebContents::FromRenderFrameHost(frame);
  4738. *disable_secure_dns =
  4739. web_contents &&
  4740. captive_portal::CaptivePortalTabHelper::FromWebContents(web_contents) &&
  4741. captive_portal::CaptivePortalTabHelper::FromWebContents(web_contents)
  4742. ->is_captive_portal_window();
  4743. }
  4744. #endif
  4745. return use_proxy;
  4746. }
  4747. std::vector<std::unique_ptr<content::URLLoaderRequestInterceptor>>
  4748. ChromeContentBrowserClient::WillCreateURLLoaderRequestInterceptors(
  4749. content::NavigationUIData* navigation_ui_data,
  4750. int frame_tree_node_id,
  4751. const scoped_refptr<network::SharedURLLoaderFactory>&
  4752. network_loader_factory) {
  4753. std::vector<std::unique_ptr<content::URLLoaderRequestInterceptor>>
  4754. interceptors;
  4755. #if BUILDFLAG(ENABLE_OFFLINE_PAGES)
  4756. interceptors.push_back(
  4757. std::make_unique<offline_pages::OfflinePageURLLoaderRequestInterceptor>(
  4758. navigation_ui_data, frame_tree_node_id));
  4759. #endif
  4760. #if BUILDFLAG(ENABLE_PDF)
  4761. {
  4762. std::unique_ptr<content::URLLoaderRequestInterceptor> pdf_interceptor =
  4763. pdf::PdfURLLoaderRequestInterceptor::MaybeCreateInterceptor(
  4764. frame_tree_node_id, std::make_unique<ChromePdfStreamDelegate>());
  4765. if (pdf_interceptor)
  4766. interceptors.push_back(std::move(pdf_interceptor));
  4767. }
  4768. #endif
  4769. if (base::FeatureList::IsEnabled(features::kIsolatePrerenders)) {
  4770. interceptors.push_back(std::make_unique<PrefetchProxyURLLoaderInterceptor>(
  4771. frame_tree_node_id));
  4772. }
  4773. interceptors.push_back(
  4774. std::make_unique<SearchPrefetchURLLoaderInterceptor>(frame_tree_node_id));
  4775. if (base::FeatureList::IsEnabled(features::kHttpsOnlyMode)) {
  4776. interceptors.push_back(
  4777. std::make_unique<HttpsOnlyModeUpgradeInterceptor>(frame_tree_node_id));
  4778. }
  4779. return interceptors;
  4780. }
  4781. content::ContentBrowserClient::URLLoaderRequestHandler
  4782. ChromeContentBrowserClient::
  4783. CreateURLLoaderHandlerForServiceWorkerNavigationPreload(
  4784. int frame_tree_node_id,
  4785. const network::ResourceRequest& resource_request) {
  4786. content::ContentBrowserClient::URLLoaderRequestHandler callback;
  4787. std::unique_ptr<SearchPrefetchURLLoader> loader =
  4788. SearchPrefetchURLLoaderInterceptor::MaybeCreateLoaderForRequest(
  4789. resource_request, frame_tree_node_id);
  4790. if (!loader) {
  4791. return callback;
  4792. }
  4793. auto* raw_loader = loader.get();
  4794. // Hand ownership of the loader to the callback, when it runs, mojo will
  4795. // manage it. If the callback is deleted, the loader will be deleted.
  4796. callback = raw_loader->ServingResponseHandler(std::move(loader));
  4797. return callback;
  4798. }
  4799. bool ChromeContentBrowserClient::WillInterceptWebSocket(
  4800. content::RenderFrameHost* frame) {
  4801. #if BUILDFLAG(ENABLE_EXTENSIONS)
  4802. if (!frame) {
  4803. return false;
  4804. }
  4805. const auto* web_request_api =
  4806. extensions::BrowserContextKeyedAPIFactory<extensions::WebRequestAPI>::Get(
  4807. frame->GetBrowserContext());
  4808. // NOTE: Some unit test environments do not initialize
  4809. // BrowserContextKeyedAPI factories for e.g. WebRequest.
  4810. if (!web_request_api)
  4811. return false;
  4812. return web_request_api->MayHaveProxies();
  4813. #else
  4814. return false;
  4815. #endif
  4816. }
  4817. void ChromeContentBrowserClient::CreateWebSocket(
  4818. content::RenderFrameHost* frame,
  4819. WebSocketFactory factory,
  4820. const GURL& url,
  4821. const net::SiteForCookies& site_for_cookies,
  4822. const absl::optional<std::string>& user_agent,
  4823. mojo::PendingRemote<network::mojom::WebSocketHandshakeClient>
  4824. handshake_client) {
  4825. #if BUILDFLAG(ENABLE_EXTENSIONS)
  4826. // TODO(crbug.com/1243518): Request w/o a frame also should be proxied.
  4827. if (!frame) {
  4828. return;
  4829. }
  4830. auto* web_request_api =
  4831. extensions::BrowserContextKeyedAPIFactory<extensions::WebRequestAPI>::Get(
  4832. frame->GetBrowserContext());
  4833. DCHECK(web_request_api);
  4834. web_request_api->ProxyWebSocket(frame, std::move(factory), url,
  4835. site_for_cookies, user_agent,
  4836. std::move(handshake_client));
  4837. #endif
  4838. }
  4839. void ChromeContentBrowserClient::WillCreateWebTransport(
  4840. int process_id,
  4841. int frame_routing_id,
  4842. const GURL& url,
  4843. const url::Origin& initiator_origin,
  4844. mojo::PendingRemote<network::mojom::WebTransportHandshakeClient>
  4845. handshake_client,
  4846. WillCreateWebTransportCallback callback) {
  4847. #if BUILDFLAG(SAFE_BROWSING_AVAILABLE)
  4848. content::RenderFrameHost* frame =
  4849. content::RenderFrameHost::FromID(process_id, frame_routing_id);
  4850. if (frame) {
  4851. int frame_tree_node_id = frame->GetFrameTreeNodeId();
  4852. content::WebContents* web_contents =
  4853. content::WebContents::FromFrameTreeNodeId(frame_tree_node_id);
  4854. DCHECK(web_contents);
  4855. Profile* profile =
  4856. Profile::FromBrowserContext(web_contents->GetBrowserContext());
  4857. DCHECK(profile);
  4858. auto checker = std::make_unique<safe_browsing::WebApiHandshakeChecker>(
  4859. base::BindOnce(
  4860. &ChromeContentBrowserClient::GetSafeBrowsingUrlCheckerDelegate,
  4861. base::Unretained(this),
  4862. safe_browsing::IsSafeBrowsingEnabled(*profile->GetPrefs()),
  4863. /*should_check_on_sb_disabled=*/false,
  4864. safe_browsing::GetURLAllowlistByPolicy(profile->GetPrefs())),
  4865. base::BindRepeating(&content::WebContents::FromFrameTreeNodeId,
  4866. frame_tree_node_id),
  4867. frame_tree_node_id);
  4868. auto* raw_checker = checker.get();
  4869. raw_checker->Check(
  4870. url,
  4871. base::BindOnce(
  4872. &ChromeContentBrowserClient::SafeBrowsingWebApiHandshakeChecked,
  4873. weak_factory_.GetWeakPtr(), std::move(checker), process_id,
  4874. frame_routing_id, url, initiator_origin,
  4875. std::move(handshake_client), std::move(callback)));
  4876. return;
  4877. }
  4878. #endif
  4879. MaybeInterceptWebTransport(process_id, frame_routing_id, url,
  4880. initiator_origin, std::move(handshake_client),
  4881. std::move(callback));
  4882. }
  4883. void ChromeContentBrowserClient::SafeBrowsingWebApiHandshakeChecked(
  4884. std::unique_ptr<safe_browsing::WebApiHandshakeChecker> checker,
  4885. int process_id,
  4886. int frame_routing_id,
  4887. const GURL& url,
  4888. const url::Origin& initiator_origin,
  4889. mojo::PendingRemote<network::mojom::WebTransportHandshakeClient>
  4890. handshake_client,
  4891. WillCreateWebTransportCallback callback,
  4892. safe_browsing::WebApiHandshakeChecker::CheckResult result) {
  4893. if (result == safe_browsing::WebApiHandshakeChecker::CheckResult::kProceed) {
  4894. MaybeInterceptWebTransport(process_id, frame_routing_id, url,
  4895. initiator_origin, std::move(handshake_client),
  4896. std::move(callback));
  4897. } else {
  4898. std::move(callback).Run(std::move(handshake_client),
  4899. network::mojom::WebTransportError::New(
  4900. net::ERR_ABORTED, quic::QUIC_INTERNAL_ERROR,
  4901. "SafeBrowsing check failed", false));
  4902. }
  4903. }
  4904. void ChromeContentBrowserClient::MaybeInterceptWebTransport(
  4905. int process_id,
  4906. int frame_routing_id,
  4907. const GURL& url,
  4908. const url::Origin& initiator_origin,
  4909. mojo::PendingRemote<network::mojom::WebTransportHandshakeClient>
  4910. handshake_client,
  4911. WillCreateWebTransportCallback callback) {
  4912. #if BUILDFLAG(ENABLE_EXTENSIONS)
  4913. DCHECK_CURRENTLY_ON(BrowserThread::UI);
  4914. // TODO(1243518): Add a unit test which calls
  4915. // ChromeContentBrowserClient::WillCreateWebTransport() with invalid process
  4916. // id and routing id.
  4917. auto* render_process_host = content::RenderProcessHost::FromID(process_id);
  4918. if (!render_process_host) {
  4919. std::move(callback).Run(std::move(handshake_client), absl::nullopt);
  4920. return;
  4921. }
  4922. content::BrowserContext* browser_context =
  4923. render_process_host->GetBrowserContext();
  4924. auto* web_request_api =
  4925. extensions::BrowserContextKeyedAPIFactory<extensions::WebRequestAPI>::Get(
  4926. browser_context);
  4927. // NOTE: Some unit test environments do not initialize BrowserContextKeyedAPI
  4928. // factories like WebRequestAPI.
  4929. if (!web_request_api) {
  4930. std::move(callback).Run(std::move(handshake_client), absl::nullopt);
  4931. return;
  4932. }
  4933. web_request_api->ProxyWebTransport(
  4934. *render_process_host, frame_routing_id, url, initiator_origin,
  4935. std::move(handshake_client), std::move(callback));
  4936. #else
  4937. std::move(callback).Run(std::move(handshake_client), absl::nullopt);
  4938. #endif
  4939. }
  4940. bool ChromeContentBrowserClient::WillCreateRestrictedCookieManager(
  4941. network::mojom::RestrictedCookieManagerRole role,
  4942. content::BrowserContext* browser_context,
  4943. const url::Origin& origin,
  4944. const net::IsolationInfo& isolation_info,
  4945. bool is_service_worker,
  4946. int process_id,
  4947. int routing_id,
  4948. mojo::PendingReceiver<network::mojom::RestrictedCookieManager>* receiver) {
  4949. DCHECK_CURRENTLY_ON(BrowserThread::UI);
  4950. #if BUILDFLAG(ENABLE_EXTENSIONS)
  4951. if (origin.scheme() == extensions::kExtensionScheme) {
  4952. DCHECK_EQ(network::mojom::RestrictedCookieManagerRole::SCRIPT, role);
  4953. extensions::ChromeExtensionCookies::Get(browser_context)
  4954. ->CreateRestrictedCookieManager(origin, isolation_info,
  4955. std::move(*receiver));
  4956. return true;
  4957. }
  4958. #endif
  4959. return false;
  4960. }
  4961. void ChromeContentBrowserClient::OnNetworkServiceCreated(
  4962. network::mojom::NetworkService* network_service) {
  4963. PrefService* local_state;
  4964. if (g_browser_process) {
  4965. DCHECK(g_browser_process->local_state());
  4966. local_state = g_browser_process->local_state();
  4967. } else {
  4968. DCHECK(startup_data_.chrome_feature_list_creator()->local_state());
  4969. local_state = startup_data_.chrome_feature_list_creator()->local_state();
  4970. }
  4971. // Create SystemNetworkContextManager if it has not been created yet. We need
  4972. // to set up global NetworkService state before anything else uses it and this
  4973. // is the first opportunity to initialize SystemNetworkContextManager with the
  4974. // NetworkService.
  4975. if (!SystemNetworkContextManager::HasInstance())
  4976. SystemNetworkContextManager::CreateInstance(local_state);
  4977. SystemNetworkContextManager::GetInstance()->OnNetworkServiceCreated(
  4978. network_service);
  4979. }
  4980. void ChromeContentBrowserClient::ConfigureNetworkContextParams(
  4981. content::BrowserContext* context,
  4982. bool in_memory,
  4983. const base::FilePath& relative_partition_path,
  4984. network::mojom::NetworkContextParams* network_context_params,
  4985. cert_verifier::mojom::CertVerifierCreationParams*
  4986. cert_verifier_creation_params) {
  4987. ProfileNetworkContextService* service =
  4988. ProfileNetworkContextServiceFactory::GetForContext(context);
  4989. if (service) {
  4990. service->ConfigureNetworkContextParams(in_memory, relative_partition_path,
  4991. network_context_params,
  4992. cert_verifier_creation_params);
  4993. } else {
  4994. // Set default params.
  4995. network_context_params->user_agent = GetUserAgentBasedOnPolicy(context);
  4996. network_context_params->accept_language = GetApplicationLocale();
  4997. }
  4998. }
  4999. std::vector<base::FilePath>
  5000. ChromeContentBrowserClient::GetNetworkContextsParentDirectory() {
  5001. DCHECK(!network_contexts_parent_directory_.empty());
  5002. return network_contexts_parent_directory_;
  5003. }
  5004. base::Value::Dict ChromeContentBrowserClient::GetNetLogConstants() {
  5005. return net_log::GetPlatformConstantsForNetLog(
  5006. base::CommandLine::ForCurrentProcess()->GetCommandLineString(),
  5007. chrome::GetChannelName(chrome::WithExtendedStable(true)));
  5008. }
  5009. bool ChromeContentBrowserClient::AllowRenderingMhtmlOverHttp(
  5010. content::NavigationUIData* navigation_ui_data) {
  5011. #if BUILDFLAG(ENABLE_OFFLINE_PAGES)
  5012. // It is OK to load the saved offline copy, in MHTML format.
  5013. ChromeNavigationUIData* chrome_navigation_ui_data =
  5014. static_cast<ChromeNavigationUIData*>(navigation_ui_data);
  5015. if (!chrome_navigation_ui_data)
  5016. return false;
  5017. offline_pages::OfflinePageNavigationUIData* offline_page_data =
  5018. chrome_navigation_ui_data->GetOfflinePageNavigationUIData();
  5019. return offline_page_data && offline_page_data->is_offline_page();
  5020. #else
  5021. return false;
  5022. #endif
  5023. }
  5024. bool ChromeContentBrowserClient::ShouldForceDownloadResource(
  5025. const GURL& url,
  5026. const std::string& mime_type) {
  5027. #if BUILDFLAG(ENABLE_EXTENSIONS)
  5028. // Special-case user scripts to get downloaded instead of viewed.
  5029. return extensions::UserScript::IsURLUserScript(url, mime_type);
  5030. #else
  5031. return false;
  5032. #endif
  5033. }
  5034. content::BluetoothDelegate* ChromeContentBrowserClient::GetBluetoothDelegate() {
  5035. if (!bluetooth_delegate_) {
  5036. bluetooth_delegate_ = std::make_unique<permissions::BluetoothDelegateImpl>(
  5037. std::make_unique<ChromeBluetoothDelegateImplClient>());
  5038. }
  5039. return bluetooth_delegate_.get();
  5040. }
  5041. #if !BUILDFLAG(IS_ANDROID)
  5042. void ChromeContentBrowserClient::CreateDeviceInfoService(
  5043. content::RenderFrameHost* render_frame_host,
  5044. mojo::PendingReceiver<blink::mojom::DeviceAPIService> receiver) {
  5045. DCHECK(render_frame_host);
  5046. DeviceServiceImpl::Create(render_frame_host, std::move(receiver));
  5047. }
  5048. void ChromeContentBrowserClient::CreateManagedConfigurationService(
  5049. content::RenderFrameHost* render_frame_host,
  5050. mojo::PendingReceiver<blink::mojom::ManagedConfigurationService> receiver) {
  5051. DCHECK(render_frame_host);
  5052. ManagedConfigurationServiceImpl::Create(render_frame_host,
  5053. std::move(receiver));
  5054. }
  5055. content::SerialDelegate* ChromeContentBrowserClient::GetSerialDelegate() {
  5056. if (!serial_delegate_)
  5057. serial_delegate_ = std::make_unique<ChromeSerialDelegate>();
  5058. return serial_delegate_.get();
  5059. }
  5060. content::HidDelegate* ChromeContentBrowserClient::GetHidDelegate() {
  5061. if (!hid_delegate_)
  5062. hid_delegate_ = std::make_unique<ChromeHidDelegate>();
  5063. return hid_delegate_.get();
  5064. }
  5065. content::UsbDelegate* ChromeContentBrowserClient::GetUsbDelegate() {
  5066. if (!usb_delegate_)
  5067. usb_delegate_ = std::make_unique<ChromeUsbDelegate>();
  5068. return usb_delegate_.get();
  5069. }
  5070. content::WebAuthenticationDelegate*
  5071. ChromeContentBrowserClient::GetWebAuthenticationDelegate() {
  5072. if (!web_authentication_delegate_) {
  5073. web_authentication_delegate_ =
  5074. std::make_unique<ChromeWebAuthenticationDelegate>();
  5075. }
  5076. return web_authentication_delegate_.get();
  5077. }
  5078. std::unique_ptr<content::AuthenticatorRequestClientDelegate>
  5079. ChromeContentBrowserClient::GetWebAuthenticationRequestDelegate(
  5080. content::RenderFrameHost* render_frame_host) {
  5081. return AuthenticatorRequestScheduler::CreateRequestDelegate(
  5082. render_frame_host);
  5083. }
  5084. #endif
  5085. std::unique_ptr<net::ClientCertStore>
  5086. ChromeContentBrowserClient::CreateClientCertStore(
  5087. content::BrowserContext* browser_context) {
  5088. return ProfileNetworkContextServiceFactory::GetForContext(browser_context)
  5089. ->CreateClientCertStore();
  5090. }
  5091. std::unique_ptr<content::LoginDelegate>
  5092. ChromeContentBrowserClient::CreateLoginDelegate(
  5093. const net::AuthChallengeInfo& auth_info,
  5094. content::WebContents* web_contents,
  5095. const content::GlobalRequestID& request_id,
  5096. bool is_request_for_primary_main_frame,
  5097. const GURL& url,
  5098. scoped_refptr<net::HttpResponseHeaders> response_headers,
  5099. bool first_auth_attempt,
  5100. LoginAuthRequiredCallback auth_required_callback) {
  5101. #if BUILDFLAG(IS_CHROMEOS_ASH)
  5102. auto* system_proxy_manager = ash::SystemProxyManager::Get();
  5103. // For Managed Guest Session and Kiosk devices, the credentials configured
  5104. // via the policy SystemProxySettings may be used for proxy authentication.
  5105. // Note: |system_proxy_manager| may be missing in tests.
  5106. if (system_proxy_manager && system_proxy_manager->CanUsePolicyCredentials(
  5107. auth_info, first_auth_attempt)) {
  5108. return system_proxy_manager->CreateLoginDelegate(
  5109. std::move(auth_required_callback));
  5110. }
  5111. #endif // BUILDFLAG(IS_CHROMEOS_ASH)
  5112. // For subresources, create a LoginHandler directly, which may show a login
  5113. // prompt to the user. Main frame resources go through LoginTabHelper, which
  5114. // manages a more complicated flow to avoid confusion about which website is
  5115. // showing the prompt.
  5116. if (is_request_for_primary_main_frame) {
  5117. LoginTabHelper::CreateForWebContents(web_contents);
  5118. return LoginTabHelper::FromWebContents(web_contents)
  5119. ->CreateAndStartMainFrameLoginDelegate(
  5120. auth_info, web_contents, request_id, url, response_headers,
  5121. std::move(auth_required_callback));
  5122. }
  5123. std::unique_ptr<LoginHandler> login_handler = LoginHandler::Create(
  5124. auth_info, web_contents, std::move(auth_required_callback));
  5125. login_handler->StartSubresource(request_id, url, response_headers);
  5126. return login_handler;
  5127. }
  5128. bool ChromeContentBrowserClient::HandleExternalProtocol(
  5129. const GURL& url,
  5130. content::WebContents::Getter web_contents_getter,
  5131. int frame_tree_node_id,
  5132. content::NavigationUIData* navigation_data,
  5133. bool is_primary_main_frame,
  5134. bool is_in_fenced_frame_tree,
  5135. network::mojom::WebSandboxFlags sandbox_flags,
  5136. ui::PageTransition page_transition,
  5137. bool has_user_gesture,
  5138. const absl::optional<url::Origin>& initiating_origin,
  5139. content::RenderFrameHost* initiator_document,
  5140. mojo::PendingRemote<network::mojom::URLLoaderFactory>* out_factory) {
  5141. #if BUILDFLAG(ENABLE_EXTENSIONS)
  5142. // External protocols are disabled for guests. An exception is made for the
  5143. // "mailto" protocol, so that pages that utilize it work properly in a
  5144. // WebView.
  5145. ChromeNavigationUIData* chrome_data =
  5146. static_cast<ChromeNavigationUIData*>(navigation_data);
  5147. if ((chrome_data &&
  5148. chrome_data->GetExtensionNavigationUIData()->is_web_view()) &&
  5149. !url.SchemeIs(url::kMailToScheme)) {
  5150. return false;
  5151. }
  5152. #endif // BUILDFLAG(ENABLE_EXTENSIONS)
  5153. #if BUILDFLAG(IS_ANDROID)
  5154. // Main frame external protocols are handled by
  5155. // InterceptNavigationResourceThrottle.
  5156. if (is_primary_main_frame)
  5157. return false;
  5158. #endif // defined(ANDROID)
  5159. auto weak_initiator_document = initiator_document
  5160. ? initiator_document->GetWeakDocumentPtr()
  5161. : content::WeakDocumentPtr();
  5162. content::GetUIThreadTaskRunner({})->PostTask(
  5163. FROM_HERE,
  5164. base::BindOnce(&LaunchURL, weak_factory_.GetWeakPtr(), url,
  5165. std::move(web_contents_getter), page_transition,
  5166. is_primary_main_frame, is_in_fenced_frame_tree,
  5167. sandbox_flags, has_user_gesture, initiating_origin,
  5168. std::move(weak_initiator_document)));
  5169. return true;
  5170. }
  5171. std::unique_ptr<content::VideoOverlayWindow>
  5172. ChromeContentBrowserClient::CreateWindowForVideoPictureInPicture(
  5173. content::VideoPictureInPictureWindowController* controller) {
  5174. // Note: content::VideoOverlayWindow::Create() is defined by platform-specific
  5175. // implementation in chrome/browser/ui/views. This layering hack, which goes
  5176. // through //content and ContentBrowserClient, allows us to work around the
  5177. // dependency constraints that disallow directly calling
  5178. // chrome/browser/ui/views code either from here or from other code in
  5179. // chrome/browser.
  5180. return content::VideoOverlayWindow::Create(controller);
  5181. }
  5182. std::unique_ptr<content::DocumentOverlayWindow>
  5183. ChromeContentBrowserClient::CreateWindowForDocumentPictureInPicture(
  5184. content::DocumentPictureInPictureWindowController* controller) {
  5185. // Note: content::DocumentOverlayWindow::Create() is defined by
  5186. // platform-specific implementation in chrome/browser/ui/views. This layering
  5187. // hack, which goes through //content and ContentBrowserClient, allows us to
  5188. // work around the dependency constraints that disallow directly calling
  5189. // chrome/browser/ui/views code either from here or from other code in
  5190. // chrome/browser.
  5191. return content::DocumentOverlayWindow::Create(controller);
  5192. }
  5193. void ChromeContentBrowserClient::RegisterRendererPreferenceWatcher(
  5194. content::BrowserContext* browser_context,
  5195. mojo::PendingRemote<blink::mojom::RendererPreferenceWatcher> watcher) {
  5196. Profile* profile = Profile::FromBrowserContext(browser_context);
  5197. PrefWatcher::Get(profile)->RegisterRendererPreferenceWatcher(
  5198. std::move(watcher));
  5199. }
  5200. // Static; handles rewriting Web UI URLs.
  5201. bool ChromeContentBrowserClient::HandleWebUI(
  5202. GURL* url,
  5203. content::BrowserContext* browser_context) {
  5204. DCHECK(browser_context);
  5205. // Rewrite chrome://help to chrome://settings/help.
  5206. if (url->SchemeIs(content::kChromeUIScheme) &&
  5207. url->host() == chrome::kChromeUIHelpHost) {
  5208. *url = ReplaceURLHostAndPath(*url, chrome::kChromeUISettingsHost,
  5209. chrome::kChromeUIHelpHost);
  5210. }
  5211. if (base::FeatureList::IsEnabled(
  5212. features::kConsolidatedSiteStorageControls)) {
  5213. // Replace deprecated Site Data page URL with the All Sites page, which
  5214. // contains storage controls for sites.
  5215. if (url->SchemeIs(content::kChromeUIScheme) &&
  5216. url->host() == chrome::kChromeUISettingsHost) {
  5217. if (url->path() == chrome::kChromeUISiteDataDeprecatedPath) {
  5218. *url = ReplaceURLHostAndPath(*url, chrome::kChromeUISettingsHost,
  5219. chrome::kChromeUIAllSitesPath);
  5220. UMA_HISTOGRAM_BOOLEAN("Settings.AllSites.DeprecatedRedirect", true);
  5221. } else if (url->path() == chrome::kChromeUIAllSitesPath) {
  5222. // Log un-redirected navigations to the page as well to provide context
  5223. // for the raw number of redirects.
  5224. UMA_HISTOGRAM_BOOLEAN("Settings.AllSites.DeprecatedRedirect", false);
  5225. }
  5226. }
  5227. }
  5228. #if BUILDFLAG(IS_WIN)
  5229. // TODO(crbug.com/1003960): Remove when issue is resolved.
  5230. if (url->SchemeIs(content::kChromeUIScheme) &&
  5231. url->host() == chrome::kChromeUIWelcomeWin10Host) {
  5232. *url =
  5233. ReplaceURLHostAndPath(*url, chrome::kChromeUIWelcomeHost, url->path());
  5234. return true;
  5235. }
  5236. #endif // BUILDFLAG(IS_WIN)
  5237. if (!ChromeWebUIControllerFactory::GetInstance()->UseWebUIForURL(
  5238. browser_context, *url) &&
  5239. !content::WebUIConfigMap::GetInstance().GetConfig(
  5240. browser_context, url::Origin::Create(*url))) {
  5241. return false;
  5242. }
  5243. #if BUILDFLAG(IS_CHROMEOS_ASH)
  5244. // Special case : in ChromeOS in Guest mode bookmarks and history are
  5245. // disabled for security reasons. New tab page explains the reasons, so
  5246. // we redirect user to new tab page.
  5247. if (user_manager::UserManager::Get()->IsLoggedInAsGuest()) {
  5248. if (url->SchemeIs(content::kChromeUIScheme) &&
  5249. (url->DomainIs(chrome::kChromeUIBookmarksHost) ||
  5250. url->DomainIs(chrome::kChromeUIHistoryHost))) {
  5251. // Rewrite with new tab URL
  5252. *url = GURL(chrome::kChromeUINewTabURL);
  5253. }
  5254. }
  5255. #endif
  5256. #if BUILDFLAG(IS_CHROMEOS)
  5257. if (IsSystemFeatureURLDisabled(*url)) {
  5258. *url = GURL(chrome::kChromeUIAppDisabledURL);
  5259. return true;
  5260. }
  5261. #endif
  5262. return true;
  5263. }
  5264. bool ChromeContentBrowserClient::ShowPaymentHandlerWindow(
  5265. content::BrowserContext* browser_context,
  5266. const GURL& url,
  5267. base::OnceCallback<void(bool, int, int)> callback) {
  5268. #if BUILDFLAG(IS_ANDROID)
  5269. return false;
  5270. #else
  5271. payments::PaymentRequestDisplayManagerFactory::GetInstance()
  5272. ->GetForBrowserContext(browser_context)
  5273. ->ShowPaymentHandlerWindow(url, std::move(callback));
  5274. return true;
  5275. #endif
  5276. }
  5277. // static
  5278. bool ChromeContentBrowserClient::HandleWebUIReverse(
  5279. GURL* url,
  5280. content::BrowserContext* browser_context) {
  5281. #if BUILDFLAG(IS_WIN)
  5282. // TODO(crbug.com/1003960): Remove when issue is resolved.
  5283. // No need to actually reverse-rewrite the URL, but return true to update the
  5284. // displayed URL when rewriting chrome://welcome-win10 to chrome://welcome.
  5285. if (url->SchemeIs(content::kChromeUIScheme) &&
  5286. url->host() == chrome::kChromeUIWelcomeHost) {
  5287. return true;
  5288. }
  5289. #endif // BUILDFLAG(IS_WIN)
  5290. // No need to actually reverse-rewrite the URL, but return true to update the
  5291. // displayed URL when rewriting chrome://help to chrome://settings/help.
  5292. return url->SchemeIs(content::kChromeUIScheme) &&
  5293. url->host() == chrome::kChromeUISettingsHost;
  5294. }
  5295. const ui::NativeTheme* ChromeContentBrowserClient::GetWebTheme() const {
  5296. return ui::NativeTheme::GetInstanceForWeb();
  5297. }
  5298. scoped_refptr<safe_browsing::UrlCheckerDelegate>
  5299. ChromeContentBrowserClient::GetSafeBrowsingUrlCheckerDelegate(
  5300. bool safe_browsing_enabled_for_profile,
  5301. bool should_check_on_sb_disabled,
  5302. const std::vector<std::string>& allowlist_domains) {
  5303. DCHECK_CURRENTLY_ON(BrowserThread::IO);
  5304. // Should not bypass safe browsing check if the check is for enterprise
  5305. // lookup.
  5306. if (!safe_browsing_enabled_for_profile && !should_check_on_sb_disabled)
  5307. return nullptr;
  5308. // |safe_browsing_service_| may be unavailable in tests.
  5309. if (safe_browsing_service_ && !safe_browsing_url_checker_delegate_) {
  5310. safe_browsing_url_checker_delegate_ =
  5311. base::MakeRefCounted<safe_browsing::UrlCheckerDelegateImpl>(
  5312. safe_browsing_service_->database_manager(),
  5313. safe_browsing_service_->ui_manager());
  5314. }
  5315. // Update allowlist domains.
  5316. if (safe_browsing_url_checker_delegate_) {
  5317. safe_browsing_url_checker_delegate_->SetPolicyAllowlistDomains(
  5318. allowlist_domains);
  5319. }
  5320. return safe_browsing_url_checker_delegate_;
  5321. }
  5322. safe_browsing::RealTimeUrlLookupServiceBase*
  5323. ChromeContentBrowserClient::GetUrlLookupService(
  5324. content::BrowserContext* browser_context,
  5325. bool is_enterprise_lookup_enabled,
  5326. bool is_consumer_lookup_enabled) {
  5327. // |safe_browsing_service_| may be unavailable in tests.
  5328. if (!safe_browsing_service_) {
  5329. return nullptr;
  5330. }
  5331. Profile* profile = Profile::FromBrowserContext(browser_context);
  5332. #if BUILDFLAG(SAFE_BROWSING_DB_LOCAL)
  5333. if (is_enterprise_lookup_enabled) {
  5334. return safe_browsing::ChromeEnterpriseRealTimeUrlLookupServiceFactory::
  5335. GetForProfile(profile);
  5336. }
  5337. #endif
  5338. if (is_consumer_lookup_enabled) {
  5339. return safe_browsing::RealTimeUrlLookupServiceFactory::GetForProfile(
  5340. profile);
  5341. }
  5342. return nullptr;
  5343. }
  5344. bool ChromeContentBrowserClient::CanAcceptUntrustedExchangesIfNeeded() {
  5345. // We require --user-data-dir flag too so that no dangerous changes are made
  5346. // in the user's regular profile.
  5347. return base::CommandLine::ForCurrentProcess()->HasSwitch(
  5348. switches::kUserDataDir);
  5349. }
  5350. void ChromeContentBrowserClient::OnNetworkServiceDataUseUpdate(
  5351. content::GlobalRenderFrameHostId render_frame_host_id,
  5352. int32_t network_traffic_annotation_id_hash,
  5353. int64_t recv_bytes,
  5354. int64_t sent_bytes) {
  5355. #if !BUILDFLAG(IS_ANDROID)
  5356. task_manager::TaskManagerInterface::UpdateAccumulatedStatsNetworkForRoute(
  5357. render_frame_host_id, recv_bytes, sent_bytes);
  5358. #endif
  5359. ChromeDataUseMeasurement::GetInstance().ReportNetworkServiceDataUse(
  5360. network_traffic_annotation_id_hash, recv_bytes, sent_bytes);
  5361. }
  5362. base::FilePath
  5363. ChromeContentBrowserClient::GetSandboxedStorageServiceDataDirectory() {
  5364. if (!g_browser_process || !g_browser_process->profile_manager())
  5365. return base::FilePath();
  5366. return g_browser_process->profile_manager()->user_data_dir();
  5367. }
  5368. bool ChromeContentBrowserClient::ShouldSandboxAudioService() {
  5369. return IsAudioServiceSandboxEnabled();
  5370. }
  5371. bool ChromeContentBrowserClient::ShouldSandboxNetworkService() {
  5372. return SystemNetworkContextManager::IsNetworkSandboxEnabled();
  5373. }
  5374. void ChromeContentBrowserClient::LogWebFeatureForCurrentPage(
  5375. content::RenderFrameHost* render_frame_host,
  5376. blink::mojom::WebFeature feature) {
  5377. DCHECK_CURRENTLY_ON(BrowserThread::UI);
  5378. page_load_metrics::MetricsWebContentsObserver::RecordFeatureUsage(
  5379. render_frame_host, feature);
  5380. }
  5381. std::string ChromeContentBrowserClient::GetProduct() {
  5382. return version_info::GetProductNameAndVersionForUserAgent();
  5383. }
  5384. std::string ChromeContentBrowserClient::GetUserAgent() {
  5385. return embedder_support::GetUserAgent();
  5386. }
  5387. std::string ChromeContentBrowserClient::GetUserAgentBasedOnPolicy(
  5388. content::BrowserContext* context) {
  5389. const PrefService* prefs = Profile::FromBrowserContext(context)->GetPrefs();
  5390. embedder_support::ForceMajorVersionToMinorPosition
  5391. force_major_version_to_minor =
  5392. embedder_support::GetMajorToMinorFromPrefs(prefs);
  5393. embedder_support::UserAgentReductionEnterprisePolicyState
  5394. user_agent_reduction =
  5395. embedder_support::GetUserAgentReductionFromPrefs(prefs);
  5396. switch (user_agent_reduction) {
  5397. case embedder_support::UserAgentReductionEnterprisePolicyState::
  5398. kForceDisabled:
  5399. return embedder_support::GetFullUserAgent(force_major_version_to_minor);
  5400. case embedder_support::UserAgentReductionEnterprisePolicyState::
  5401. kForceEnabled:
  5402. return embedder_support::GetReducedUserAgent(
  5403. force_major_version_to_minor);
  5404. case embedder_support::UserAgentReductionEnterprisePolicyState::kDefault:
  5405. default:
  5406. return embedder_support::GetUserAgent(force_major_version_to_minor,
  5407. user_agent_reduction);
  5408. }
  5409. }
  5410. std::string ChromeContentBrowserClient::GetFullUserAgent() {
  5411. return embedder_support::GetFullUserAgent();
  5412. }
  5413. std::string ChromeContentBrowserClient::GetReducedUserAgent() {
  5414. return embedder_support::GetReducedUserAgent();
  5415. }
  5416. blink::UserAgentMetadata ChromeContentBrowserClient::GetUserAgentMetadata() {
  5417. DCHECK_CURRENTLY_ON(BrowserThread::UI);
  5418. return embedder_support::GetUserAgentMetadata(
  5419. g_browser_process->local_state());
  5420. }
  5421. absl::optional<gfx::ImageSkia> ChromeContentBrowserClient::GetProductLogo() {
  5422. // This icon is available on Android, but adds 19KiB to the APK. Since it
  5423. // isn't used on Android we exclude it to avoid bloat.
  5424. #if !BUILDFLAG(IS_ANDROID)
  5425. return absl::optional<gfx::ImageSkia>(
  5426. *ui::ResourceBundle::GetSharedInstance().GetImageSkiaNamed(
  5427. IDR_PRODUCT_LOGO_256));
  5428. #else
  5429. return absl::nullopt;
  5430. #endif
  5431. }
  5432. bool ChromeContentBrowserClient::IsBuiltinComponent(
  5433. content::BrowserContext* browser_context,
  5434. const url::Origin& origin) {
  5435. #if BUILDFLAG(ENABLE_EXTENSIONS)
  5436. return ChromeContentBrowserClientExtensionsPart::IsBuiltinComponent(
  5437. browser_context, origin);
  5438. #else
  5439. return false;
  5440. #endif
  5441. }
  5442. bool ChromeContentBrowserClient::ShouldBlockRendererDebugURL(
  5443. const GURL& url,
  5444. content::BrowserContext* context) {
  5445. PolicyBlocklistService* service =
  5446. PolicyBlocklistFactory::GetForBrowserContext(context);
  5447. using URLBlocklistState = policy::URLBlocklist::URLBlocklistState;
  5448. URLBlocklistState blocklist_state = service->GetURLBlocklistState(url);
  5449. return blocklist_state == URLBlocklistState::URL_IN_BLOCKLIST;
  5450. }
  5451. ui::AXMode ChromeContentBrowserClient::GetAXModeForBrowserContext(
  5452. content::BrowserContext* browser_context) {
  5453. Profile* profile = Profile::FromBrowserContext(browser_context);
  5454. return AccessibilityLabelsServiceFactory::GetForProfile(profile)->GetAXMode();
  5455. }
  5456. #if BUILDFLAG(IS_ANDROID)
  5457. content::ContentBrowserClient::WideColorGamutHeuristic
  5458. ChromeContentBrowserClient::GetWideColorGamutHeuristic() {
  5459. if (viz::AlwaysUseWideColorGamut() ||
  5460. features::IsDynamicColorGamutEnabled()) {
  5461. return WideColorGamutHeuristic::kUseDisplay;
  5462. }
  5463. if (display::HasForceDisplayColorProfile() &&
  5464. display::GetForcedDisplayColorProfile() ==
  5465. gfx::ColorSpace::CreateDisplayP3D65()) {
  5466. return WideColorGamutHeuristic::kUseDisplay;
  5467. }
  5468. return WideColorGamutHeuristic::kNone;
  5469. }
  5470. #endif
  5471. base::flat_set<std::string>
  5472. ChromeContentBrowserClient::GetPluginMimeTypesWithExternalHandlers(
  5473. content::BrowserContext* browser_context) {
  5474. base::flat_set<std::string> mime_types;
  5475. #if BUILDFLAG(ENABLE_PLUGINS)
  5476. auto map = PluginUtils::GetMimeTypeToExtensionIdMap(browser_context);
  5477. for (const auto& pair : map)
  5478. mime_types.insert(pair.first);
  5479. #endif
  5480. #if BUILDFLAG(ENABLE_PDF)
  5481. mime_types.insert(pdf::kInternalPluginMimeType);
  5482. #endif
  5483. return mime_types;
  5484. }
  5485. void ChromeContentBrowserClient::AugmentNavigationDownloadPolicy(
  5486. content::RenderFrameHost* frame_host,
  5487. bool user_gesture,
  5488. blink::NavigationDownloadPolicy* download_policy) {
  5489. const auto* throttle_manager =
  5490. subresource_filter::ContentSubresourceFilterThrottleManager::FromPage(
  5491. frame_host->GetPage());
  5492. if (throttle_manager &&
  5493. throttle_manager->IsRenderFrameHostTaggedAsAd(frame_host)) {
  5494. download_policy->SetAllowed(blink::NavigationDownloadType::kAdFrame);
  5495. if (!user_gesture) {
  5496. if (base::FeatureList::IsEnabled(
  5497. blink::features::
  5498. kBlockingDownloadsInAdFrameWithoutUserActivation)) {
  5499. download_policy->SetDisallowed(
  5500. blink::NavigationDownloadType::kAdFrameNoGesture);
  5501. } else {
  5502. download_policy->SetAllowed(
  5503. blink::NavigationDownloadType::kAdFrameNoGesture);
  5504. }
  5505. }
  5506. }
  5507. }
  5508. std::vector<blink::mojom::EpochTopicPtr>
  5509. ChromeContentBrowserClient::GetBrowsingTopicsForJsApi(
  5510. const url::Origin& context_origin,
  5511. content::RenderFrameHost* main_frame) {
  5512. browsing_topics::BrowsingTopicsService* browsing_topics_service =
  5513. browsing_topics::BrowsingTopicsServiceFactory::GetForProfile(
  5514. Profile::FromBrowserContext(
  5515. content::WebContents::FromRenderFrameHost(main_frame)
  5516. ->GetBrowserContext()));
  5517. if (!browsing_topics_service)
  5518. return {};
  5519. auto topics = browsing_topics_service->GetBrowsingTopicsForJsApi(
  5520. context_origin, main_frame);
  5521. // Compare the provided topics to the real (i.e. non random) topics available
  5522. // for the site, this allows filtering out of the randomly generated topics
  5523. // for passing to the Page Specific Content Settings.
  5524. auto real_topics = browsing_topics_service->GetTopicsForSiteForDisplay(
  5525. main_frame->GetLastCommittedOrigin());
  5526. // |topics| and |real_topics| will contain only a handful of entries,
  5527. // and |topics| order must be preserved. A simple loop is thus appropriate.
  5528. for (const auto& topic : topics) {
  5529. int taxonomy_version = 0;
  5530. base::StringToInt(topic->taxonomy_version, &taxonomy_version);
  5531. DCHECK(taxonomy_version);
  5532. privacy_sandbox::CanonicalTopic canonical_topic(
  5533. browsing_topics::Topic(topic->topic), taxonomy_version);
  5534. if (base::Contains(real_topics, canonical_topic)) {
  5535. content_settings::PageSpecificContentSettings::TopicAccessed(
  5536. main_frame, context_origin, /*blocked_by_policy=*/false,
  5537. canonical_topic);
  5538. }
  5539. }
  5540. return topics;
  5541. }
  5542. bool ChromeContentBrowserClient::IsBluetoothScanningBlocked(
  5543. content::BrowserContext* browser_context,
  5544. const url::Origin& requesting_origin,
  5545. const url::Origin& embedding_origin) {
  5546. const HostContentSettingsMap* const content_settings =
  5547. HostContentSettingsMapFactory::GetForProfile(
  5548. Profile::FromBrowserContext(browser_context));
  5549. if (content_settings->GetContentSetting(
  5550. requesting_origin.GetURL(), embedding_origin.GetURL(),
  5551. ContentSettingsType::BLUETOOTH_SCANNING) == CONTENT_SETTING_BLOCK) {
  5552. return true;
  5553. }
  5554. return false;
  5555. }
  5556. void ChromeContentBrowserClient::BlockBluetoothScanning(
  5557. content::BrowserContext* browser_context,
  5558. const url::Origin& requesting_origin,
  5559. const url::Origin& embedding_origin) {
  5560. HostContentSettingsMap* const content_settings =
  5561. HostContentSettingsMapFactory::GetForProfile(
  5562. Profile::FromBrowserContext(browser_context));
  5563. content_settings->SetContentSettingDefaultScope(
  5564. requesting_origin.GetURL(), embedding_origin.GetURL(),
  5565. ContentSettingsType::BLUETOOTH_SCANNING, CONTENT_SETTING_BLOCK);
  5566. }
  5567. bool ChromeContentBrowserClient::ArePersistentMediaDeviceIDsAllowed(
  5568. content::BrowserContext* browser_context,
  5569. const GURL& url,
  5570. const net::SiteForCookies& site_for_cookies,
  5571. const absl::optional<url::Origin>& top_frame_origin) {
  5572. // Persistent MediaDevice IDs are allowed if cookies are allowed.
  5573. return CookieSettingsFactory::GetForProfile(
  5574. Profile::FromBrowserContext(browser_context))
  5575. ->IsFullCookieAccessAllowed(
  5576. url, site_for_cookies, top_frame_origin,
  5577. content_settings::CookieSettings::QueryReason::kSiteStorage);
  5578. }
  5579. #if !BUILDFLAG(IS_ANDROID)
  5580. base::OnceClosure ChromeContentBrowserClient::FetchRemoteSms(
  5581. content::WebContents* web_contents,
  5582. const std::vector<url::Origin>& origin_list,
  5583. base::OnceCallback<void(absl::optional<std::vector<url::Origin>>,
  5584. absl::optional<std::string>,
  5585. absl::optional<content::SmsFetchFailureType>)>
  5586. callback) {
  5587. return ::FetchRemoteSms(web_contents, origin_list, std::move(callback));
  5588. }
  5589. #endif
  5590. bool ChromeContentBrowserClient::IsClipboardPasteAllowed(
  5591. content::RenderFrameHost* render_frame_host) {
  5592. DCHECK(render_frame_host);
  5593. // Paste requires either (1) user activation, ...
  5594. if (render_frame_host->HasTransientUserActivation())
  5595. return true;
  5596. // (2) granted web permission, ...
  5597. content::BrowserContext* browser_context =
  5598. render_frame_host->GetBrowserContext();
  5599. content::PermissionController* permission_controller =
  5600. browser_context->GetPermissionController();
  5601. blink::mojom::PermissionStatus status =
  5602. permission_controller->GetPermissionStatusForCurrentDocument(
  5603. blink::PermissionType::CLIPBOARD_READ_WRITE, render_frame_host);
  5604. if (status == blink::mojom::PermissionStatus::GRANTED)
  5605. return true;
  5606. #if BUILDFLAG(ENABLE_EXTENSIONS)
  5607. // (3) origination directly from a Chrome extension, ...
  5608. Profile* profile = Profile::FromBrowserContext(browser_context);
  5609. DCHECK(profile);
  5610. const GURL& url =
  5611. render_frame_host->GetMainFrame()->GetLastCommittedOrigin().GetURL();
  5612. auto* registry = extensions::ExtensionRegistry::Get(profile);
  5613. if (url.SchemeIs(extensions::kExtensionScheme)) {
  5614. return URLHasExtensionPermission(extensions::ProcessMap::Get(profile),
  5615. registry, url,
  5616. render_frame_host->GetProcess()->GetID(),
  5617. APIPermissionID::kClipboardRead);
  5618. }
  5619. // or (4) origination from a process that at least might be running a
  5620. // content script from an extension with the clipboardRead permission.
  5621. extensions::ExtensionIdSet extension_ids =
  5622. extensions::ContentScriptTracker::GetExtensionsThatRanScriptsInProcess(
  5623. *render_frame_host->GetProcess());
  5624. for (const auto& extension_id : extension_ids) {
  5625. const Extension* extension =
  5626. registry->enabled_extensions().GetByID(extension_id);
  5627. if (extension && extension->permissions_data()->HasAPIPermission(
  5628. APIPermissionID::kClipboardRead)) {
  5629. return true;
  5630. }
  5631. }
  5632. #endif // BUILDFLAG(ENABLE_EXTENSIONS)
  5633. return false;
  5634. }
  5635. void ChromeContentBrowserClient::IsClipboardPasteContentAllowed(
  5636. content::WebContents* web_contents,
  5637. const GURL& url,
  5638. const ui::ClipboardFormatType& data_type,
  5639. const std::string& data,
  5640. IsClipboardPasteContentAllowedCallback callback) {
  5641. #if BUILDFLAG(FULL_SAFE_BROWSING)
  5642. // Safe browsing does not support images, so accept without checking.
  5643. // TODO(crbug.com/1013584): check policy on what to do about unsupported
  5644. // types when it is implemented.
  5645. if (data_type == ui::ClipboardFormatType::BitmapType()) {
  5646. std::move(callback).Run(ClipboardPasteContentAllowed(true));
  5647. return;
  5648. }
  5649. Profile* profile =
  5650. Profile::FromBrowserContext(web_contents->GetBrowserContext());
  5651. enterprise_connectors::ContentAnalysisDelegate::Data dialog_data;
  5652. if (enterprise_connectors::ContentAnalysisDelegate::IsEnabled(
  5653. profile, web_contents->GetLastCommittedURL(), &dialog_data,
  5654. enterprise_connectors::AnalysisConnector::BULK_DATA_ENTRY)) {
  5655. dialog_data.text.push_back(data);
  5656. enterprise_connectors::ContentAnalysisDelegate::CreateForWebContents(
  5657. web_contents, std::move(dialog_data),
  5658. base::BindOnce(
  5659. [](IsClipboardPasteContentAllowedCallback callback,
  5660. const enterprise_connectors::ContentAnalysisDelegate::Data& data,
  5661. const enterprise_connectors::ContentAnalysisDelegate::Result&
  5662. result) {
  5663. std::move(callback).Run(
  5664. ClipboardPasteContentAllowed(result.text_results[0]));
  5665. },
  5666. std::move(callback)),
  5667. safe_browsing::DeepScanAccessPoint::PASTE);
  5668. } else {
  5669. std::move(callback).Run(ClipboardPasteContentAllowed(true));
  5670. }
  5671. #else
  5672. std::move(callback).Run(ClipboardPasteContentAllowed(true));
  5673. #endif // BUILDFLAG(FULL_SAFE_BROWSING)
  5674. }
  5675. bool ChromeContentBrowserClient::IsClipboardCopyAllowed(
  5676. content::BrowserContext* browser_context,
  5677. const GURL& url,
  5678. size_t data_size_in_bytes,
  5679. std::u16string& replacement_data) {
  5680. ClipboardRestrictionService* service =
  5681. ClipboardRestrictionServiceFactory::GetInstance()->GetForBrowserContext(
  5682. browser_context);
  5683. return service->IsUrlAllowedToCopy(url, data_size_in_bytes,
  5684. &replacement_data);
  5685. }
  5686. #if BUILDFLAG(ENABLE_VR)
  5687. content::XrIntegrationClient*
  5688. ChromeContentBrowserClient::GetXrIntegrationClient() {
  5689. if (!xr_integration_client_)
  5690. xr_integration_client_ = std::make_unique<vr::ChromeXrIntegrationClient>(
  5691. base::PassKey<ChromeContentBrowserClient>());
  5692. return xr_integration_client_.get();
  5693. }
  5694. #endif // BUILDFLAG(ENABLE_VR)
  5695. void ChromeContentBrowserClient::BindBrowserControlInterface(
  5696. mojo::ScopedMessagePipeHandle pipe) {
  5697. #if BUILDFLAG(IS_CHROMEOS_LACROS)
  5698. chromeos::LacrosService::Get()->BindReceiver(
  5699. chrome::GetVersionString(chrome::WithExtendedStable(true)));
  5700. #endif
  5701. }
  5702. bool ChromeContentBrowserClient::
  5703. ShouldInheritCrossOriginEmbedderPolicyImplicitly(const GURL& url) {
  5704. #if BUILDFLAG(ENABLE_EXTENSIONS)
  5705. return url.SchemeIs(extensions::kExtensionScheme);
  5706. #else
  5707. return false;
  5708. #endif
  5709. }
  5710. bool ChromeContentBrowserClient::ShouldAllowInsecurePrivateNetworkRequests(
  5711. content::BrowserContext* browser_context,
  5712. const url::Origin& origin) {
  5713. return content_settings::ShouldAllowInsecurePrivateNetworkRequests(
  5714. HostContentSettingsMapFactory::GetForProfile(browser_context), origin);
  5715. }
  5716. bool ChromeContentBrowserClient::IsJitDisabledForSite(
  5717. content::BrowserContext* browser_context,
  5718. const GURL& site_url) {
  5719. Profile* profile = Profile::FromBrowserContext(browser_context);
  5720. auto* map = HostContentSettingsMapFactory::GetForProfile(profile);
  5721. // Special case to determine if any policy is set.
  5722. if (site_url.is_empty()) {
  5723. return map->GetDefaultContentSetting(ContentSettingsType::JAVASCRIPT_JIT,
  5724. nullptr) == CONTENT_SETTING_BLOCK;
  5725. }
  5726. // Only disable JIT for web schemes.
  5727. if (!site_url.SchemeIsHTTPOrHTTPS())
  5728. return false;
  5729. return (map->GetContentSetting(site_url, site_url,
  5730. ContentSettingsType::JAVASCRIPT_JIT) ==
  5731. CONTENT_SETTING_BLOCK);
  5732. }
  5733. ukm::UkmService* ChromeContentBrowserClient::GetUkmService() {
  5734. return g_browser_process->GetMetricsServicesManager()->GetUkmService();
  5735. }
  5736. void ChromeContentBrowserClient::OnKeepaliveRequestStarted(
  5737. content::BrowserContext* context) {
  5738. #if !BUILDFLAG(IS_ANDROID)
  5739. DVLOG(1) << "OnKeepaliveRequestStarted: " << num_keepalive_requests_
  5740. << " ==> " << num_keepalive_requests_ + 1;
  5741. ++num_keepalive_requests_;
  5742. DCHECK_GT(num_keepalive_requests_, 0u);
  5743. if (!context) {
  5744. // We somehow failed to associate the request and the BrowserContext. Bail
  5745. // out.
  5746. return;
  5747. }
  5748. const auto now = base::TimeTicks::Now();
  5749. const auto timeout = GetKeepaliveTimerTimeout(context);
  5750. keepalive_deadline_ = std::max(keepalive_deadline_, now + timeout);
  5751. if (keepalive_deadline_ > now && !keepalive_timer_.IsRunning()) {
  5752. DVLOG(1) << "Starting a keepalive timer(" << timeout.InSecondsF()
  5753. << " seconds)";
  5754. keepalive_timer_.Start(
  5755. FROM_HERE, keepalive_deadline_ - now,
  5756. base::BindOnce(
  5757. &ChromeContentBrowserClient::OnKeepaliveTimerFired,
  5758. weak_factory_.GetWeakPtr(),
  5759. std::make_unique<ScopedKeepAlive>(
  5760. KeepAliveOrigin::BROWSER, KeepAliveRestartOption::DISABLED)));
  5761. }
  5762. #endif // !BUILDFLAG(IS_ANDROID)
  5763. }
  5764. void ChromeContentBrowserClient::OnKeepaliveRequestFinished() {
  5765. #if !BUILDFLAG(IS_ANDROID)
  5766. DCHECK_GT(num_keepalive_requests_, 0u);
  5767. DVLOG(1) << "OnKeepaliveRequestFinished: " << num_keepalive_requests_
  5768. << " ==> " << num_keepalive_requests_ - 1;
  5769. --num_keepalive_requests_;
  5770. if (num_keepalive_requests_ == 0) {
  5771. DVLOG(1) << "Stopping the keepalive timer";
  5772. keepalive_timer_.Stop();
  5773. // This deletes the keep alive handle attached to the timer function and
  5774. // unblock the shutdown sequence.
  5775. }
  5776. #endif // !BUILDFLAG(IS_ANDROID)
  5777. }
  5778. #if BUILDFLAG(IS_MAC)
  5779. bool ChromeContentBrowserClient::SetupEmbedderSandboxParameters(
  5780. sandbox::mojom::Sandbox sandbox_type,
  5781. sandbox::SeatbeltExecClient* client) {
  5782. if (sandbox_type == sandbox::mojom::Sandbox::kSpeechRecognition) {
  5783. base::FilePath soda_component_path = speech::GetSodaDirectory();
  5784. CHECK(!soda_component_path.empty());
  5785. CHECK(client->SetParameter(sandbox::policy::kParamSodaComponentPath,
  5786. soda_component_path.value()));
  5787. base::FilePath soda_language_pack_path =
  5788. speech::GetSodaLanguagePacksDirectory();
  5789. CHECK(!soda_language_pack_path.empty());
  5790. CHECK(client->SetParameter(sandbox::policy::kParamSodaLanguagePackPath,
  5791. soda_language_pack_path.value()));
  5792. return true;
  5793. } else if (sandbox_type == sandbox::mojom::Sandbox::kScreenAI) {
  5794. #if BUILDFLAG(ENABLE_SCREEN_AI_SERVICE)
  5795. // ScreenAI service needs read access to ScreenAI component path, so that it
  5796. // would be able to find the latest downloaded version, and load its binary
  5797. // and all enclosed model files.
  5798. base::FilePath screen_ai_component_dir = screen_ai::GetComponentDir();
  5799. if (screen_ai_component_dir.empty()) {
  5800. VLOG(1) << "Screen AI component not found.";
  5801. return false;
  5802. }
  5803. CHECK(client->SetParameter(sandbox::policy::kParamScreenAiComponentPath,
  5804. screen_ai_component_dir.value()));
  5805. return true;
  5806. #endif
  5807. }
  5808. return false;
  5809. }
  5810. #endif // BUILDFLAG(IS_MAC)
  5811. void ChromeContentBrowserClient::GetHyphenationDictionary(
  5812. base::OnceCallback<void(const base::FilePath&)> callback) {
  5813. #if BUILDFLAG(USE_MINIKIN_HYPHENATION) && !BUILDFLAG(IS_ANDROID)
  5814. component_updater::HyphenationComponentInstallerPolicy::
  5815. GetHyphenationDictionary(std::move(callback));
  5816. #endif
  5817. }
  5818. bool ChromeContentBrowserClient::HasErrorPage(int http_status_code) {
  5819. // Use an internal error page, if we have one for the status code.
  5820. return error_page::LocalizedError::HasStrings(
  5821. error_page::Error::kHttpErrorDomain, http_status_code);
  5822. }
  5823. std::unique_ptr<content::IdentityRequestDialogController>
  5824. ChromeContentBrowserClient::CreateIdentityRequestDialogController() {
  5825. return std::make_unique<IdentityDialogController>();
  5826. }
  5827. bool ChromeContentBrowserClient::SuppressDifferentOriginSubframeJSDialogs(
  5828. content::BrowserContext* browser_context) {
  5829. Profile* profile = Profile::FromBrowserContext(browser_context);
  5830. if (!profile->GetPrefs()->GetBoolean(
  5831. prefs::kSuppressDifferentOriginSubframeJSDialogs)) {
  5832. return false;
  5833. }
  5834. return ContentBrowserClient::SuppressDifferentOriginSubframeJSDialogs(
  5835. browser_context);
  5836. }
  5837. bool ChromeContentBrowserClient::IsFindInPageDisabledForOrigin(
  5838. const url::Origin& origin) {
  5839. #if BUILDFLAG(ENABLE_PDF)
  5840. // For PDF viewing with the PPAPI-free PDF Viewer, find-in-page should only
  5841. // display results from the PDF content, and not from the UI.
  5842. return IsPdfExtensionOrigin(origin);
  5843. #else
  5844. return false;
  5845. #endif
  5846. }
  5847. std::unique_ptr<content::SpeculationHostDelegate>
  5848. ChromeContentBrowserClient::CreateSpeculationHostDelegate(
  5849. content::RenderFrameHost& render_frame_host) {
  5850. return std::make_unique<ChromeSpeculationHostDelegate>(render_frame_host);
  5851. }
  5852. std::unique_ptr<content::PrefetchServiceDelegate>
  5853. ChromeContentBrowserClient::CreatePrefetchServiceDelegate(
  5854. content::BrowserContext* browser_context) {
  5855. return std::make_unique<ChromePrefetchServiceDelegate>(browser_context);
  5856. }
  5857. void ChromeContentBrowserClient::OnWebContentsCreated(
  5858. content::WebContents* web_contents) {
  5859. // NOTE: Please don't add additional code to this method - attaching universal
  5860. // WebContentsObservers goes through the separate function, to ensure that the
  5861. // (rare) additions of universal helpers are code reviewed by separate OWNERS.
  5862. AttachUniversalWebContentsObservers(web_contents);
  5863. }
  5864. #if !BUILDFLAG(IS_ANDROID)
  5865. base::TimeDelta ChromeContentBrowserClient::GetKeepaliveTimerTimeout(
  5866. content::BrowserContext* context) {
  5867. Profile* profile = Profile::FromBrowserContext(context);
  5868. PrefService* prefs = profile->GetPrefs();
  5869. if (!prefs) {
  5870. return base::TimeDelta();
  5871. }
  5872. const int seconds =
  5873. prefs->GetInteger(prefs::kFetchKeepaliveDurationOnShutdown);
  5874. // The preference is set only be the corresponding enterprise policy, and
  5875. // we have minimum/maximum values on it.
  5876. DCHECK_LE(0, seconds);
  5877. DCHECK_LE(seconds, 5);
  5878. return base::Seconds(seconds);
  5879. }
  5880. void ChromeContentBrowserClient::OnKeepaliveTimerFired(
  5881. std::unique_ptr<ScopedKeepAlive> keep_alive_handle) {
  5882. const auto now = base::TimeTicks::Now();
  5883. const auto then = keepalive_deadline_;
  5884. if (now < then) {
  5885. keepalive_timer_.Start(
  5886. FROM_HERE, then - now,
  5887. base::BindOnce(&ChromeContentBrowserClient::OnKeepaliveTimerFired,
  5888. weak_factory_.GetWeakPtr(),
  5889. std::move(keep_alive_handle)));
  5890. }
  5891. }
  5892. #endif
  5893. bool ChromeContentBrowserClient::ShouldPreconnectNavigation(
  5894. content::BrowserContext* browser_context) {
  5895. #if BUILDFLAG(ENABLE_EXTENSIONS)
  5896. // An extension could be blocking connections for privacy reasons, so skip
  5897. // optimization if there are any extensions with WebRequest permissions.
  5898. const auto* web_request_api =
  5899. extensions::BrowserContextKeyedAPIFactory<extensions::WebRequestAPI>::Get(
  5900. browser_context);
  5901. if (!web_request_api || web_request_api->MayHaveProxies())
  5902. return false;
  5903. #endif
  5904. // Preloading is sometimes disabled globally in Chrome via Finch to monitor
  5905. // its impact. However, we do not want to evaluate the impact of preconnecting
  5906. // at the start of navigation as part of the preloading holdback, so ignore
  5907. // the Finch setting here.
  5908. return prefetch::IsSomePreloadingEnabledIgnoringFinch(
  5909. *Profile::FromBrowserContext(browser_context)->GetPrefs());
  5910. }
  5911. bool ChromeContentBrowserClient::ShouldDisableOriginAgentClusterDefault(
  5912. content::BrowserContext* browser_context) {
  5913. // The enterprise policy for kOriginAgentClusterDefaultEnabled defaults to
  5914. // true to defer to Chromium's decision. If it is set to false, it should
  5915. // override Chromium's decision and use site-keyed agent clusters by default
  5916. // instead.
  5917. return !Profile::FromBrowserContext(browser_context)
  5918. ->GetPrefs()
  5919. ->GetBoolean(prefs::kOriginAgentClusterDefaultEnabled);
  5920. }
  5921. bool ChromeContentBrowserClient::WillProvidePublicFirstPartySets() {
  5922. return !base::CommandLine::ForCurrentProcess()->HasSwitch(
  5923. switches::kDisableComponentUpdate) &&
  5924. base::FeatureList::IsEnabled(features::kFirstPartySets);
  5925. }
  5926. content::mojom::AlternativeErrorPageOverrideInfoPtr
  5927. ChromeContentBrowserClient::GetAlternativeErrorPageOverrideInfo(
  5928. const GURL& url,
  5929. content::RenderFrameHost* render_frame_host,
  5930. content::BrowserContext* browser_context,
  5931. int32_t error_code) {
  5932. if (error_code != net::ERR_INTERNET_DISCONNECTED)
  5933. return nullptr;
  5934. #if BUILDFLAG(IS_ANDROID)
  5935. if (!base::FeatureList::IsEnabled(features::kAndroidPWAsDefaultOfflinePage)) {
  5936. #else
  5937. if (!base::FeatureList::IsEnabled(features::kDesktopPWAsDefaultOfflinePage)) {
  5938. #endif // BUILDFLAG(IS_ANDROID)
  5939. return nullptr;
  5940. }
  5941. return web_app::GetOfflinePageInfo(url, render_frame_host, browser_context);
  5942. }
  5943. bool ChromeContentBrowserClient::OpenExternally(
  5944. content::RenderFrameHost* opener,
  5945. const GURL& url,
  5946. WindowOpenDisposition disposition) {
  5947. #if BUILDFLAG(IS_CHROMEOS_ASH)
  5948. // If Lacros is the primary browser, we intercept requests from Ash WebUIs and
  5949. // redirect them to Lacros via crosapi. This is to make window.open and <a
  5950. // href target="_blank"> links in WebUIs (e.g. ChromeOS Settings app) open in
  5951. // Lacros rather than in Ash. NOTE: This is breaking change for calls to
  5952. // window.open, as the return value will always be null. By excluding popups
  5953. // and devtools:// and chrome:// URLs, we exclude the existing uses of
  5954. // window.open that make use of the return value (these will have to be dealt
  5955. // with separately) as well as some existing links that currently must remain
  5956. // in Ash.
  5957. bool should_open_in_lacros =
  5958. crosapi::lacros_startup_state::IsLacrosEnabled() &&
  5959. crosapi::lacros_startup_state::IsLacrosPrimaryEnabled() &&
  5960. opener->GetWebUI() != nullptr &&
  5961. disposition != WindowOpenDisposition::NEW_POPUP &&
  5962. !url.SchemeIs(content::kChromeDevToolsScheme) &&
  5963. !url.SchemeIs(content::kChromeUIScheme) &&
  5964. // Terminal's tabs must remain in Ash.
  5965. !url.SchemeIs(content::kChromeUIUntrustedScheme) &&
  5966. // OS Settings's Accessibility section links to chrome-extensions:// URLs
  5967. // for Text-to-Speech engines that are installed in Ash.
  5968. !url.SchemeIs(extensions::kExtensionScheme);
  5969. if (should_open_in_lacros) {
  5970. ash::NewWindowDelegate::GetPrimary()->OpenUrl(
  5971. url, ash::NewWindowDelegate::OpenUrlFrom::kUserInteraction,
  5972. ash::NewWindowDelegate::Disposition::kNewForegroundTab);
  5973. return true;
  5974. }
  5975. #endif
  5976. return false;
  5977. }