nsIOService.cpp 63 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895
  1. /* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
  2. /* vim:set ts=4 sw=4 cindent et: */
  3. /* This Source Code Form is subject to the terms of the Mozilla Public
  4. * License, v. 2.0. If a copy of the MPL was not distributed with this
  5. * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
  6. #include "mozilla/ArrayUtils.h"
  7. #include "mozilla/DebugOnly.h"
  8. #include "nsIOService.h"
  9. #include "nsIDOMNode.h"
  10. #include "nsIProtocolHandler.h"
  11. #include "nsIFileProtocolHandler.h"
  12. #include "nscore.h"
  13. #include "nsIURI.h"
  14. #include "prprf.h"
  15. #include "nsIErrorService.h"
  16. #include "netCore.h"
  17. #include "nsIObserverService.h"
  18. #include "nsIPrefService.h"
  19. #include "nsXPCOM.h"
  20. #include "nsIProxiedProtocolHandler.h"
  21. #include "nsIProxyInfo.h"
  22. #include "nsEscape.h"
  23. #include "nsNetUtil.h"
  24. #include "nsNetCID.h"
  25. #include "nsCRT.h"
  26. #include "nsSecCheckWrapChannel.h"
  27. #include "nsSimpleNestedURI.h"
  28. #include "nsTArray.h"
  29. #include "nsIConsoleService.h"
  30. #include "nsIUploadChannel2.h"
  31. #include "nsXULAppAPI.h"
  32. #include "nsIScriptError.h"
  33. #include "nsIScriptSecurityManager.h"
  34. #include "nsIProtocolProxyCallback.h"
  35. #include "nsICancelable.h"
  36. #include "nsINetworkLinkService.h"
  37. #include "nsPISocketTransportService.h"
  38. #include "nsAsyncRedirectVerifyHelper.h"
  39. #include "nsURLHelper.h"
  40. #include "nsPIDNSService.h"
  41. #include "nsIProtocolProxyService2.h"
  42. #include "MainThreadUtils.h"
  43. #include "nsINode.h"
  44. #include "nsIWidget.h"
  45. #include "nsThreadUtils.h"
  46. #include "mozilla/LoadInfo.h"
  47. #include "mozilla/net/NeckoCommon.h"
  48. #include "mozilla/Services.h"
  49. #include "mozilla/net/DNS.h"
  50. #include "mozilla/ipc/URIUtils.h"
  51. #include "mozilla/net/NeckoChild.h"
  52. #include "mozilla/dom/ContentParent.h"
  53. #include "mozilla/net/CaptivePortalService.h"
  54. #include "ReferrerPolicy.h"
  55. #include "nsContentSecurityManager.h"
  56. #include "nsContentUtils.h"
  57. #include "xpcpublic.h"
  58. namespace mozilla {
  59. namespace net {
  60. #define PORT_PREF_PREFIX "network.security.ports."
  61. #define PORT_PREF(x) PORT_PREF_PREFIX x
  62. #define MANAGE_OFFLINE_STATUS_PREF "network.manage-offline-status"
  63. #define OFFLINE_MIRRORS_CONNECTIVITY "network.offline-mirrors-connectivity"
  64. // Nb: these have been misnomers since bug 715770 removed the buffer cache.
  65. // "network.segment.count" and "network.segment.size" would be better names,
  66. // but the old names are still used to preserve backward compatibility.
  67. #define NECKO_BUFFER_CACHE_COUNT_PREF "network.buffer.cache.count"
  68. #define NECKO_BUFFER_CACHE_SIZE_PREF "network.buffer.cache.size"
  69. #define NETWORK_NOTIFY_CHANGED_PREF "network.notify.changed"
  70. #define NETWORK_CAPTIVE_PORTAL_PREF "network.captive-portal-service.enabled"
  71. #define MAX_RECURSION_COUNT 50
  72. nsIOService* gIOService = nullptr;
  73. static bool gHasWarnedUploadChannel2;
  74. static bool gCaptivePortalEnabled = false;
  75. static LazyLogModule gIOServiceLog("nsIOService");
  76. #undef LOG
  77. #define LOG(args) MOZ_LOG(gIOServiceLog, LogLevel::Debug, args)
  78. // A general port blacklist. Connections to these ports will not be allowed
  79. // unless the protocol overrides.
  80. //
  81. // TODO: I am sure that there are more ports to be added.
  82. // This cut is based on the classic mozilla codebase
  83. int16_t gBadPortList[] = {
  84. 1, // tcpmux
  85. 7, // echo
  86. 9, // discard
  87. 11, // systat
  88. 13, // daytime
  89. 15, // netstat
  90. 17, // qotd
  91. 19, // chargen
  92. 20, // ftp-data
  93. 21, // ftp-cntl
  94. 22, // ssh
  95. 23, // telnet
  96. 25, // smtp
  97. 37, // time
  98. 42, // name
  99. 43, // nicname
  100. 53, // domain
  101. 69, // TFTP
  102. 77, // priv-rjs
  103. 79, // finger
  104. 87, // ttylink
  105. 95, // supdup
  106. 101, // hostriame
  107. 102, // iso-tsap
  108. 103, // gppitnp
  109. 104, // acr-nema
  110. 109, // pop2
  111. 110, // pop3
  112. 111, // sunrpc
  113. 113, // auth
  114. 115, // sftp
  115. 117, // uucp-path
  116. 119, // nntp
  117. 123, // NTP
  118. 135, // loc-srv / epmap
  119. 137, // netbios
  120. 139, // netbios
  121. 143, // imap2
  122. 161, // SNMP
  123. 179, // BGP
  124. 389, // ldap
  125. 465, // smtp+ssl
  126. 512, // print / exec
  127. 513, // login
  128. 514, // shell
  129. 515, // printer
  130. 526, // tempo
  131. 530, // courier
  132. 531, // Chat
  133. 532, // netnews
  134. 540, // uucp
  135. 554, // rtsp
  136. 556, // remotefs
  137. 563, // nntp+ssl
  138. 587, // smtp (outgoing)
  139. 601, // syslog-conn
  140. 636, // ldap+ssl
  141. 993, // imap+ssl
  142. 995, // pop3+ssl
  143. 1719, // h323 (RAS)
  144. 1720, // h323 (hostcall)
  145. 1723, // pptp
  146. 2049, // nfs
  147. 3659, // apple-sasl / PasswordServer
  148. 4045, // lockd
  149. 5060, // sip
  150. 5061, // sips
  151. 6000, // x11
  152. 6566, // SANE
  153. 6665, // Alternate IRC [Apple addition]
  154. 6666, // Alternate IRC [Apple addition]
  155. 6667, // Standard IRC [Apple addition]
  156. 6668, // Alternate IRC [Apple addition]
  157. 6669, // Alternate IRC [Apple addition]
  158. // 10080,// (Amanda) too many collisions with other services, disabled for now.
  159. 0, // Sentinel value: This MUST be zero
  160. };
  161. static const char kProfileChangeNetTeardownTopic[] = "profile-change-net-teardown";
  162. static const char kProfileChangeNetRestoreTopic[] = "profile-change-net-restore";
  163. static const char kProfileDoChange[] = "profile-do-change";
  164. // Necko buffer defaults
  165. uint32_t nsIOService::gDefaultSegmentSize = 4096;
  166. uint32_t nsIOService::gDefaultSegmentCount = 24;
  167. bool nsIOService::sBlockToplevelDataUriNavigations = false;
  168. bool nsIOService::sBlockFTPSubresources = false;
  169. ////////////////////////////////////////////////////////////////////////////////
  170. nsIOService::nsIOService()
  171. : mOffline(true)
  172. , mOfflineForProfileChange(false)
  173. , mManageLinkStatus(false)
  174. , mConnectivity(true)
  175. , mOfflineMirrorsConnectivity(true)
  176. , mSettingOffline(false)
  177. , mSetOfflineValue(false)
  178. , mShutdown(false)
  179. , mHttpHandlerAlreadyShutingDown(false)
  180. , mNetworkLinkServiceInitialized(false)
  181. , mChannelEventSinks(NS_CHANNEL_EVENT_SINK_CATEGORY)
  182. , mNetworkNotifyChanged(true)
  183. , mNetTearingDownStarted(0)
  184. {
  185. }
  186. nsresult
  187. nsIOService::Init()
  188. {
  189. nsresult rv;
  190. // We need to get references to the DNS service so that we can shut it
  191. // down later. If we wait until the nsIOService is being shut down,
  192. // GetService will fail at that point.
  193. mDNSService = do_GetService(NS_DNSSERVICE_CONTRACTID, &rv);
  194. if (NS_FAILED(rv)) {
  195. NS_WARNING("failed to get DNS service");
  196. return rv;
  197. }
  198. // XXX hack until xpidl supports error info directly (bug 13423)
  199. nsCOMPtr<nsIErrorService> errorService = do_GetService(NS_ERRORSERVICE_CONTRACTID);
  200. if (errorService) {
  201. errorService->RegisterErrorStringBundle(NS_ERROR_MODULE_NETWORK, NECKO_MSGS_URL);
  202. }
  203. else
  204. NS_WARNING("failed to get error service");
  205. InitializeCaptivePortalService();
  206. // setup our bad port list stuff
  207. for(int i=0; gBadPortList[i]; i++)
  208. mRestrictedPortList.AppendElement(gBadPortList[i]);
  209. // Further modifications to the port list come from prefs
  210. nsCOMPtr<nsIPrefBranch> prefBranch;
  211. GetPrefBranch(getter_AddRefs(prefBranch));
  212. if (prefBranch) {
  213. prefBranch->AddObserver(PORT_PREF_PREFIX, this, true);
  214. prefBranch->AddObserver(MANAGE_OFFLINE_STATUS_PREF, this, true);
  215. prefBranch->AddObserver(NECKO_BUFFER_CACHE_COUNT_PREF, this, true);
  216. prefBranch->AddObserver(NECKO_BUFFER_CACHE_SIZE_PREF, this, true);
  217. prefBranch->AddObserver(NETWORK_NOTIFY_CHANGED_PREF, this, true);
  218. prefBranch->AddObserver(NETWORK_CAPTIVE_PORTAL_PREF, this, true);
  219. PrefsChanged(prefBranch);
  220. }
  221. // Register for profile change notifications
  222. nsCOMPtr<nsIObserverService> observerService = services::GetObserverService();
  223. if (observerService) {
  224. observerService->AddObserver(this, kProfileChangeNetTeardownTopic, true);
  225. observerService->AddObserver(this, kProfileChangeNetRestoreTopic, true);
  226. observerService->AddObserver(this, kProfileDoChange, true);
  227. observerService->AddObserver(this, NS_XPCOM_SHUTDOWN_OBSERVER_ID, true);
  228. observerService->AddObserver(this, NS_NETWORK_LINK_TOPIC, true);
  229. observerService->AddObserver(this, NS_WIDGET_WAKE_OBSERVER_TOPIC, true);
  230. }
  231. else
  232. NS_WARNING("failed to get observer service");
  233. Preferences::AddBoolVarCache(&sBlockToplevelDataUriNavigations,
  234. "security.data_uri.block_toplevel_data_uri_navigations", false);
  235. Preferences::AddBoolVarCache(&sBlockFTPSubresources,
  236. "security.block_ftp_subresources", true);
  237. Preferences::AddBoolVarCache(&mOfflineMirrorsConnectivity, OFFLINE_MIRRORS_CONNECTIVITY, true);
  238. gIOService = this;
  239. InitializeNetworkLinkService();
  240. SetOffline(false);
  241. return NS_OK;
  242. }
  243. nsIOService::~nsIOService()
  244. {
  245. gIOService = nullptr;
  246. }
  247. nsresult
  248. nsIOService::InitializeCaptivePortalService()
  249. {
  250. if (XRE_GetProcessType() != GeckoProcessType_Default) {
  251. // We only initalize a captive portal service in the main process
  252. return NS_OK;
  253. }
  254. mCaptivePortalService = do_GetService(NS_CAPTIVEPORTAL_CID);
  255. if (mCaptivePortalService) {
  256. return static_cast<CaptivePortalService*>(mCaptivePortalService.get())->Initialize();
  257. }
  258. return NS_OK;
  259. }
  260. nsresult
  261. nsIOService::InitializeSocketTransportService()
  262. {
  263. nsresult rv = NS_OK;
  264. if (!mSocketTransportService) {
  265. mSocketTransportService = do_GetService(NS_SOCKETTRANSPORTSERVICE_CONTRACTID, &rv);
  266. if (NS_FAILED(rv)) {
  267. NS_WARNING("failed to get socket transport service");
  268. }
  269. }
  270. if (mSocketTransportService) {
  271. rv = mSocketTransportService->Init();
  272. NS_ASSERTION(NS_SUCCEEDED(rv), "socket transport service init failed");
  273. mSocketTransportService->SetOffline(false);
  274. }
  275. return rv;
  276. }
  277. nsresult
  278. nsIOService::InitializeNetworkLinkService()
  279. {
  280. nsresult rv = NS_OK;
  281. if (mNetworkLinkServiceInitialized)
  282. return rv;
  283. if (!NS_IsMainThread()) {
  284. NS_WARNING("Network link service should be created on main thread");
  285. return NS_ERROR_FAILURE;
  286. }
  287. // go into managed mode if we can, and chrome process
  288. if (XRE_IsParentProcess())
  289. {
  290. mNetworkLinkService = do_GetService(NS_NETWORK_LINK_SERVICE_CONTRACTID, &rv);
  291. }
  292. if (mNetworkLinkService) {
  293. mNetworkLinkServiceInitialized = true;
  294. }
  295. // After initializing the networkLinkService, query the connectivity state
  296. OnNetworkLinkEvent(NS_NETWORK_LINK_DATA_UNKNOWN);
  297. return rv;
  298. }
  299. nsIOService*
  300. nsIOService::GetInstance() {
  301. if (!gIOService) {
  302. gIOService = new nsIOService();
  303. if (!gIOService)
  304. return nullptr;
  305. NS_ADDREF(gIOService);
  306. nsresult rv = gIOService->Init();
  307. if (NS_FAILED(rv)) {
  308. NS_RELEASE(gIOService);
  309. return nullptr;
  310. }
  311. return gIOService;
  312. }
  313. NS_ADDREF(gIOService);
  314. return gIOService;
  315. }
  316. NS_IMPL_ISUPPORTS(nsIOService,
  317. nsIIOService,
  318. nsIIOService2,
  319. nsINetUtil,
  320. nsISpeculativeConnect,
  321. nsIObserver,
  322. nsIIOServiceInternal,
  323. nsISupportsWeakReference)
  324. ////////////////////////////////////////////////////////////////////////////////
  325. nsresult
  326. nsIOService::RecheckCaptivePortal()
  327. {
  328. MOZ_ASSERT(NS_IsMainThread(), "Must be called on the main thread");
  329. if (mCaptivePortalService) {
  330. mCaptivePortalService->RecheckCaptivePortal();
  331. }
  332. return NS_OK;
  333. }
  334. nsresult
  335. nsIOService::RecheckCaptivePortalIfLocalRedirect(nsIChannel* newChan)
  336. {
  337. nsresult rv;
  338. if (!mCaptivePortalService) {
  339. return NS_OK;
  340. }
  341. nsCOMPtr<nsIURI> uri;
  342. rv = newChan->GetURI(getter_AddRefs(uri));
  343. if (NS_FAILED(rv)) {
  344. return rv;
  345. }
  346. nsCString host;
  347. rv = uri->GetHost(host);
  348. if (NS_FAILED(rv)) {
  349. return rv;
  350. }
  351. PRNetAddr prAddr;
  352. if (PR_StringToNetAddr(host.BeginReading(), &prAddr) != PR_SUCCESS) {
  353. // The redirect wasn't to an IP literal, so there's probably no need
  354. // to trigger the captive portal detection right now. It can wait.
  355. return NS_OK;
  356. }
  357. NetAddr netAddr;
  358. PRNetAddrToNetAddr(&prAddr, &netAddr);
  359. if (IsIPAddrLocal(&netAddr)) {
  360. // Redirects to local IP addresses are probably captive portals
  361. mCaptivePortalService->RecheckCaptivePortal();
  362. }
  363. return NS_OK;
  364. }
  365. nsresult
  366. nsIOService::AsyncOnChannelRedirect(nsIChannel* oldChan, nsIChannel* newChan,
  367. uint32_t flags,
  368. nsAsyncRedirectVerifyHelper *helper)
  369. {
  370. // If a redirect to a local network address occurs, then chances are we
  371. // are in a captive portal, so we trigger a recheck.
  372. RecheckCaptivePortalIfLocalRedirect(newChan);
  373. // This is silly. I wish there was a simpler way to get at the global
  374. // reference of the contentSecurityManager. But it lives in the XPCOM
  375. // service registry.
  376. nsCOMPtr<nsIChannelEventSink> sink =
  377. do_GetService(NS_CONTENTSECURITYMANAGER_CONTRACTID);
  378. if (sink) {
  379. nsresult rv = helper->DelegateOnChannelRedirect(sink, oldChan,
  380. newChan, flags);
  381. if (NS_FAILED(rv))
  382. return rv;
  383. }
  384. // Finally, our category
  385. nsCOMArray<nsIChannelEventSink> entries;
  386. mChannelEventSinks.GetEntries(entries);
  387. int32_t len = entries.Count();
  388. for (int32_t i = 0; i < len; ++i) {
  389. nsresult rv = helper->DelegateOnChannelRedirect(entries[i], oldChan,
  390. newChan, flags);
  391. if (NS_FAILED(rv))
  392. return rv;
  393. }
  394. return NS_OK;
  395. }
  396. nsresult
  397. nsIOService::CacheProtocolHandler(const char *scheme, nsIProtocolHandler *handler)
  398. {
  399. MOZ_ASSERT(NS_IsMainThread());
  400. for (unsigned int i=0; i<NS_N(gScheme); i++)
  401. {
  402. if (!nsCRT::strcasecmp(scheme, gScheme[i]))
  403. {
  404. nsresult rv;
  405. NS_ASSERTION(!mWeakHandler[i], "Protocol handler already cached");
  406. // Make sure the handler supports weak references.
  407. nsCOMPtr<nsISupportsWeakReference> factoryPtr = do_QueryInterface(handler, &rv);
  408. if (!factoryPtr)
  409. {
  410. // Don't cache handlers that don't support weak reference as
  411. // there is real danger of a circular reference.
  412. #ifdef DEBUG_dp
  413. printf("DEBUG: %s protcol handler doesn't support weak ref. Not cached.\n", scheme);
  414. #endif /* DEBUG_dp */
  415. return NS_ERROR_FAILURE;
  416. }
  417. mWeakHandler[i] = do_GetWeakReference(handler);
  418. return NS_OK;
  419. }
  420. }
  421. return NS_ERROR_FAILURE;
  422. }
  423. nsresult
  424. nsIOService::GetCachedProtocolHandler(const char *scheme, nsIProtocolHandler **result, uint32_t start, uint32_t end)
  425. {
  426. MOZ_ASSERT(NS_IsMainThread());
  427. uint32_t len = end - start - 1;
  428. for (unsigned int i=0; i<NS_N(gScheme); i++)
  429. {
  430. if (!mWeakHandler[i])
  431. continue;
  432. // handle unterminated strings
  433. // start is inclusive, end is exclusive, len = end - start - 1
  434. if (end ? (!nsCRT::strncasecmp(scheme + start, gScheme[i], len)
  435. && gScheme[i][len] == '\0')
  436. : (!nsCRT::strcasecmp(scheme, gScheme[i])))
  437. {
  438. return CallQueryReferent(mWeakHandler[i].get(), result);
  439. }
  440. }
  441. return NS_ERROR_FAILURE;
  442. }
  443. static bool
  444. UsesExternalProtocolHandler(const char* aScheme)
  445. {
  446. if (NS_LITERAL_CSTRING("file").Equals(aScheme) ||
  447. NS_LITERAL_CSTRING("chrome").Equals(aScheme) ||
  448. NS_LITERAL_CSTRING("resource").Equals(aScheme)) {
  449. // Don't allow file:, chrome: or resource: URIs to be handled with
  450. // nsExternalProtocolHandler, since internally we rely on being able to
  451. // use and read from these URIs.
  452. return false;
  453. }
  454. nsAutoCString pref("network.protocol-handler.external.");
  455. pref += aScheme;
  456. return Preferences::GetBool(pref.get(), false);
  457. }
  458. NS_IMETHODIMP
  459. nsIOService::GetProtocolHandler(const char* scheme, nsIProtocolHandler* *result)
  460. {
  461. nsresult rv;
  462. NS_ENSURE_ARG_POINTER(scheme);
  463. // XXX we may want to speed this up by introducing our own protocol
  464. // scheme -> protocol handler mapping, avoiding the string manipulation
  465. // and service manager stuff
  466. rv = GetCachedProtocolHandler(scheme, result);
  467. if (NS_SUCCEEDED(rv))
  468. return rv;
  469. if (!UsesExternalProtocolHandler(scheme)) {
  470. nsAutoCString contractID(NS_NETWORK_PROTOCOL_CONTRACTID_PREFIX);
  471. contractID += scheme;
  472. ToLowerCase(contractID);
  473. rv = CallGetService(contractID.get(), result);
  474. if (NS_SUCCEEDED(rv)) {
  475. CacheProtocolHandler(scheme, *result);
  476. return rv;
  477. }
  478. #ifdef MOZ_ENABLE_GIO
  479. // check to see whether GVFS can handle this URI scheme. if it can
  480. // create a nsIURI for the "scheme:", then we assume it has support for
  481. // the requested protocol. otherwise, we failover to using the default
  482. // protocol handler.
  483. rv = CallGetService(NS_NETWORK_PROTOCOL_CONTRACTID_PREFIX"moz-gio",
  484. result);
  485. if (NS_SUCCEEDED(rv)) {
  486. nsAutoCString spec(scheme);
  487. spec.Append(':');
  488. nsIURI *uri;
  489. rv = (*result)->NewURI(spec, nullptr, nullptr, &uri);
  490. if (NS_SUCCEEDED(rv)) {
  491. NS_RELEASE(uri);
  492. return rv;
  493. }
  494. NS_RELEASE(*result);
  495. }
  496. #endif
  497. }
  498. // Okay we don't have a protocol handler to handle this url type, so use
  499. // the default protocol handler. This will cause urls to get dispatched
  500. // out to the OS ('cause we can't do anything with them) when we try to
  501. // read from a channel created by the default protocol handler.
  502. rv = CallGetService(NS_NETWORK_PROTOCOL_CONTRACTID_PREFIX"default",
  503. result);
  504. if (NS_FAILED(rv))
  505. return NS_ERROR_UNKNOWN_PROTOCOL;
  506. return rv;
  507. }
  508. NS_IMETHODIMP
  509. nsIOService::ExtractScheme(const nsACString &inURI, nsACString &scheme)
  510. {
  511. return net_ExtractURLScheme(inURI, scheme);
  512. }
  513. NS_IMETHODIMP
  514. nsIOService::GetProtocolFlags(const char* scheme, uint32_t *flags)
  515. {
  516. nsCOMPtr<nsIProtocolHandler> handler;
  517. nsresult rv = GetProtocolHandler(scheme, getter_AddRefs(handler));
  518. if (NS_FAILED(rv)) return rv;
  519. // We can't call DoGetProtocolFlags here because we don't have a URI. This
  520. // API is used by (and only used by) extensions, which is why it's still
  521. // around. Calling this on a scheme with dynamic flags will throw.
  522. rv = handler->GetProtocolFlags(flags);
  523. return rv;
  524. }
  525. class AutoIncrement
  526. {
  527. public:
  528. explicit AutoIncrement(uint32_t *var) : mVar(var)
  529. {
  530. ++*var;
  531. }
  532. ~AutoIncrement()
  533. {
  534. --*mVar;
  535. }
  536. private:
  537. uint32_t *mVar;
  538. };
  539. nsresult
  540. nsIOService::NewURI(const nsACString &aSpec, const char *aCharset, nsIURI *aBaseURI, nsIURI **result)
  541. {
  542. NS_ASSERTION(NS_IsMainThread(), "wrong thread");
  543. static uint32_t recursionCount = 0;
  544. if (recursionCount >= MAX_RECURSION_COUNT)
  545. return NS_ERROR_MALFORMED_URI;
  546. AutoIncrement inc(&recursionCount);
  547. nsAutoCString scheme;
  548. nsresult rv = ExtractScheme(aSpec, scheme);
  549. if (NS_FAILED(rv)) {
  550. // then aSpec is relative
  551. if (!aBaseURI)
  552. return NS_ERROR_MALFORMED_URI;
  553. if (!aSpec.IsEmpty() && aSpec[0] == '#') {
  554. // Looks like a reference instead of a fully-specified URI.
  555. // --> initialize |uri| as a clone of |aBaseURI|, with ref appended.
  556. return aBaseURI->CloneWithNewRef(aSpec, result);
  557. }
  558. rv = aBaseURI->GetScheme(scheme);
  559. if (NS_FAILED(rv)) return rv;
  560. }
  561. // now get the handler for this scheme
  562. nsCOMPtr<nsIProtocolHandler> handler;
  563. rv = GetProtocolHandler(scheme.get(), getter_AddRefs(handler));
  564. if (NS_FAILED(rv)) return rv;
  565. return handler->NewURI(aSpec, aCharset, aBaseURI, result);
  566. }
  567. NS_IMETHODIMP
  568. nsIOService::NewFileURI(nsIFile *file, nsIURI **result)
  569. {
  570. nsresult rv;
  571. NS_ENSURE_ARG_POINTER(file);
  572. nsCOMPtr<nsIProtocolHandler> handler;
  573. rv = GetProtocolHandler("file", getter_AddRefs(handler));
  574. if (NS_FAILED(rv)) return rv;
  575. nsCOMPtr<nsIFileProtocolHandler> fileHandler( do_QueryInterface(handler, &rv) );
  576. if (NS_FAILED(rv)) return rv;
  577. return fileHandler->NewFileURI(file, result);
  578. }
  579. NS_IMETHODIMP
  580. nsIOService::NewChannelFromURI2(nsIURI* aURI,
  581. nsIDOMNode* aLoadingNode,
  582. nsIPrincipal* aLoadingPrincipal,
  583. nsIPrincipal* aTriggeringPrincipal,
  584. uint32_t aSecurityFlags,
  585. uint32_t aContentPolicyType,
  586. nsIChannel** result)
  587. {
  588. return NewChannelFromURIWithProxyFlags2(aURI,
  589. nullptr, // aProxyURI
  590. 0, // aProxyFlags
  591. aLoadingNode,
  592. aLoadingPrincipal,
  593. aTriggeringPrincipal,
  594. aSecurityFlags,
  595. aContentPolicyType,
  596. result);
  597. }
  598. /* ***** DEPRECATED *****
  599. * please use NewChannelFromURI2 providing the right arguments for:
  600. * * aLoadingNode
  601. * * aLoadingPrincipal
  602. * * aTriggeringPrincipal
  603. * * aSecurityFlags
  604. * * aContentPolicyType
  605. *
  606. * See nsIIoService.idl for a detailed description of those arguments
  607. */
  608. NS_IMETHODIMP
  609. nsIOService::NewChannelFromURI(nsIURI *aURI, nsIChannel **result)
  610. {
  611. NS_ASSERTION(false, "Deprecated, use NewChannelFromURI2 providing loadInfo arguments!");
  612. const char16_t* params[] = {
  613. u"nsIOService::NewChannelFromURI()",
  614. u"nsIOService::NewChannelFromURI2()"
  615. };
  616. nsContentUtils::ReportToConsole(nsIScriptError::warningFlag,
  617. NS_LITERAL_CSTRING("Security by Default"),
  618. nullptr, // aDocument
  619. nsContentUtils::eNECKO_PROPERTIES,
  620. "APIDeprecationWarning",
  621. params, ArrayLength(params));
  622. return NewChannelFromURI2(aURI,
  623. nullptr, // aLoadingNode
  624. nsContentUtils::GetSystemPrincipal(),
  625. nullptr, // aTriggeringPrincipal
  626. nsILoadInfo::SEC_ALLOW_CROSS_ORIGIN_DATA_IS_NULL,
  627. nsIContentPolicy::TYPE_OTHER,
  628. result);
  629. }
  630. NS_IMETHODIMP
  631. nsIOService::NewChannelFromURIWithLoadInfo(nsIURI* aURI,
  632. nsILoadInfo* aLoadInfo,
  633. nsIChannel** result)
  634. {
  635. return NewChannelFromURIWithProxyFlagsInternal(aURI,
  636. nullptr, // aProxyURI
  637. 0, // aProxyFlags
  638. aLoadInfo,
  639. result);
  640. }
  641. nsresult
  642. nsIOService::NewChannelFromURIWithProxyFlagsInternal(nsIURI* aURI,
  643. nsIURI* aProxyURI,
  644. uint32_t aProxyFlags,
  645. nsILoadInfo* aLoadInfo,
  646. nsIChannel** result)
  647. {
  648. nsresult rv;
  649. NS_ENSURE_ARG_POINTER(aURI);
  650. nsAutoCString scheme;
  651. rv = aURI->GetScheme(scheme);
  652. if (NS_FAILED(rv))
  653. return rv;
  654. nsCOMPtr<nsIProtocolHandler> handler;
  655. rv = GetProtocolHandler(scheme.get(), getter_AddRefs(handler));
  656. if (NS_FAILED(rv))
  657. return rv;
  658. uint32_t protoFlags;
  659. rv = handler->DoGetProtocolFlags(aURI, &protoFlags);
  660. if (NS_FAILED(rv))
  661. return rv;
  662. // Ideally we are creating new channels by calling NewChannel2 (NewProxiedChannel2).
  663. // Keep in mind that Addons can implement their own Protocolhandlers, hence
  664. // NewChannel2() might *not* be implemented.
  665. // We do not want to break those addons, therefore we first try to create a channel
  666. // calling NewChannel2(); if that fails:
  667. // * we fall back to creating a channel by calling NewChannel()
  668. // * wrap the addon channel
  669. // * and attach the loadInfo to the channel wrapper
  670. nsCOMPtr<nsIChannel> channel;
  671. nsCOMPtr<nsIProxiedProtocolHandler> pph = do_QueryInterface(handler);
  672. if (pph) {
  673. rv = pph->NewProxiedChannel2(aURI, nullptr, aProxyFlags, aProxyURI,
  674. aLoadInfo, getter_AddRefs(channel));
  675. // if calling NewProxiedChannel2() fails we try to fall back to
  676. // creating a new proxied channel by calling NewProxiedChannel().
  677. if (NS_FAILED(rv)) {
  678. rv = pph->NewProxiedChannel(aURI, nullptr, aProxyFlags, aProxyURI,
  679. getter_AddRefs(channel));
  680. NS_ENSURE_SUCCESS(rv, rv);
  681. // The protocol handler does not implement NewProxiedChannel2, so
  682. // maybe we need to wrap the channel (see comment in MaybeWrap
  683. // function).
  684. channel = nsSecCheckWrapChannel::MaybeWrap(channel, aLoadInfo);
  685. }
  686. }
  687. else {
  688. rv = handler->NewChannel2(aURI, aLoadInfo, getter_AddRefs(channel));
  689. // if calling newChannel2() fails we try to fall back to
  690. // creating a new channel by calling NewChannel().
  691. if (NS_FAILED(rv)) {
  692. rv = handler->NewChannel(aURI, getter_AddRefs(channel));
  693. if (NS_FAILED(rv)) {
  694. return rv;
  695. }
  696. // The protocol handler does not implement NewChannel2, so
  697. // maybe we need to wrap the channel (see comment in MaybeWrap
  698. // function).
  699. channel = nsSecCheckWrapChannel::MaybeWrap(channel, aLoadInfo);
  700. }
  701. }
  702. // Make sure that all the individual protocolhandlers attach a loadInfo.
  703. if (aLoadInfo) {
  704. // make sure we have the same instance of loadInfo on the newly created channel
  705. nsCOMPtr<nsILoadInfo> loadInfo = channel->GetLoadInfo();
  706. if (aLoadInfo != loadInfo) {
  707. MOZ_ASSERT(false, "newly created channel must have a loadinfo attached");
  708. return NS_ERROR_UNEXPECTED;
  709. }
  710. // If we're sandboxed, make sure to clear any owner the channel
  711. // might already have.
  712. if (loadInfo->GetLoadingSandboxed()) {
  713. channel->SetOwner(nullptr);
  714. }
  715. }
  716. // Some extensions override the http protocol handler and provide their own
  717. // implementation. The channels returned from that implementation doesn't
  718. // seem to always implement the nsIUploadChannel2 interface, presumably
  719. // because it's a new interface.
  720. // Eventually we should remove this and simply require that http channels
  721. // implement the new interface.
  722. // See bug 529041
  723. if (!gHasWarnedUploadChannel2 && scheme.EqualsLiteral("http")) {
  724. nsCOMPtr<nsIUploadChannel2> uploadChannel2 = do_QueryInterface(channel);
  725. if (!uploadChannel2) {
  726. nsCOMPtr<nsIConsoleService> consoleService =
  727. do_GetService(NS_CONSOLESERVICE_CONTRACTID);
  728. if (consoleService) {
  729. consoleService->LogStringMessage(NS_LITERAL_STRING(
  730. "Http channel implementation doesn't support nsIUploadChannel2. An extension has supplied a non-functional http protocol handler. This will break behavior and in future releases not work at all."
  731. ).get());
  732. }
  733. gHasWarnedUploadChannel2 = true;
  734. }
  735. }
  736. channel.forget(result);
  737. return NS_OK;
  738. }
  739. NS_IMETHODIMP
  740. nsIOService::NewChannelFromURIWithProxyFlags2(nsIURI* aURI,
  741. nsIURI* aProxyURI,
  742. uint32_t aProxyFlags,
  743. nsIDOMNode* aLoadingNode,
  744. nsIPrincipal* aLoadingPrincipal,
  745. nsIPrincipal* aTriggeringPrincipal,
  746. uint32_t aSecurityFlags,
  747. uint32_t aContentPolicyType,
  748. nsIChannel** result)
  749. {
  750. // Ideally all callers of NewChannelFromURIWithProxyFlags2 provide the
  751. // necessary arguments to create a loadinfo. Keep in mind that addons
  752. // might still call NewChannelFromURIWithProxyFlags() which forwards
  753. // its calls to NewChannelFromURIWithProxyFlags2 using *null* values
  754. // as the arguments for aLoadingNode, aLoadingPrincipal, and also
  755. // aTriggeringPrincipal.
  756. // We do not want to break those addons, hence we only create a Loadinfo
  757. // if 'aLoadingNode' or 'aLoadingPrincipal' are provided. Note, that
  758. // either aLoadingNode or aLoadingPrincipal is required to succesfully
  759. // create a LoadInfo object.
  760. // Except in the case of top level TYPE_DOCUMENT loads, where the
  761. // loadingNode and loadingPrincipal are allowed to have null values.
  762. nsCOMPtr<nsILoadInfo> loadInfo;
  763. // TYPE_DOCUMENT loads don't require a loadingNode or principal, but other
  764. // types do.
  765. if (aLoadingNode || aLoadingPrincipal ||
  766. aContentPolicyType == nsIContentPolicy::TYPE_DOCUMENT) {
  767. nsCOMPtr<nsINode> loadingNode(do_QueryInterface(aLoadingNode));
  768. loadInfo = new LoadInfo(aLoadingPrincipal,
  769. aTriggeringPrincipal,
  770. loadingNode,
  771. aSecurityFlags,
  772. aContentPolicyType);
  773. }
  774. NS_ASSERTION(loadInfo, "Please pass security info when creating a channel");
  775. return NewChannelFromURIWithProxyFlagsInternal(aURI,
  776. aProxyURI,
  777. aProxyFlags,
  778. loadInfo,
  779. result);
  780. }
  781. /* ***** DEPRECATED *****
  782. * please use NewChannelFromURIWithProxyFlags2 providing the right arguments for:
  783. * * aLoadingNode
  784. * * aLoadingPrincipal
  785. * * aTriggeringPrincipal
  786. * * aSecurityFlags
  787. * * aContentPolicyType
  788. *
  789. * See nsIIoService.idl for a detailed description of those arguments
  790. */
  791. NS_IMETHODIMP
  792. nsIOService::NewChannelFromURIWithProxyFlags(nsIURI *aURI,
  793. nsIURI *aProxyURI,
  794. uint32_t aProxyFlags,
  795. nsIChannel **result)
  796. {
  797. NS_ASSERTION(false, "Deprecated, use NewChannelFromURIWithProxyFlags2 providing loadInfo arguments!");
  798. const char16_t* params[] = {
  799. u"nsIOService::NewChannelFromURIWithProxyFlags()",
  800. u"nsIOService::NewChannelFromURIWithProxyFlags2()"
  801. };
  802. nsContentUtils::ReportToConsole(nsIScriptError::warningFlag,
  803. NS_LITERAL_CSTRING("Security by Default"),
  804. nullptr, // aDocument
  805. nsContentUtils::eNECKO_PROPERTIES,
  806. "APIDeprecationWarning",
  807. params, ArrayLength(params));
  808. return NewChannelFromURIWithProxyFlags2(aURI,
  809. aProxyURI,
  810. aProxyFlags,
  811. nullptr, // aLoadingNode
  812. nsContentUtils::GetSystemPrincipal(),
  813. nullptr, // aTriggeringPrincipal
  814. nsILoadInfo::SEC_ALLOW_CROSS_ORIGIN_DATA_IS_NULL,
  815. nsIContentPolicy::TYPE_OTHER,
  816. result);
  817. }
  818. NS_IMETHODIMP
  819. nsIOService::NewChannel2(const nsACString& aSpec,
  820. const char* aCharset,
  821. nsIURI* aBaseURI,
  822. nsIDOMNode* aLoadingNode,
  823. nsIPrincipal* aLoadingPrincipal,
  824. nsIPrincipal* aTriggeringPrincipal,
  825. uint32_t aSecurityFlags,
  826. uint32_t aContentPolicyType,
  827. nsIChannel** result)
  828. {
  829. nsresult rv;
  830. nsCOMPtr<nsIURI> uri;
  831. rv = NewURI(aSpec, aCharset, aBaseURI, getter_AddRefs(uri));
  832. if (NS_FAILED(rv)) return rv;
  833. return NewChannelFromURI2(uri,
  834. aLoadingNode,
  835. aLoadingPrincipal,
  836. aTriggeringPrincipal,
  837. aSecurityFlags,
  838. aContentPolicyType,
  839. result);
  840. }
  841. /* ***** DEPRECATED *****
  842. * please use NewChannel2 providing the right arguments for:
  843. * * aLoadingNode
  844. * * aLoadingPrincipal
  845. * * aTriggeringPrincipal
  846. * * aSecurityFlags
  847. * * aContentPolicyType
  848. *
  849. * See nsIIoService.idl for a detailed description of those arguments
  850. */
  851. NS_IMETHODIMP
  852. nsIOService::NewChannel(const nsACString &aSpec, const char *aCharset, nsIURI *aBaseURI, nsIChannel **result)
  853. {
  854. NS_ASSERTION(false, "Deprecated, use NewChannel2 providing loadInfo arguments!");
  855. const char16_t* params[] = {
  856. u"nsIOService::NewChannel()",
  857. u"nsIOService::NewChannel2()"
  858. };
  859. nsContentUtils::ReportToConsole(nsIScriptError::warningFlag,
  860. NS_LITERAL_CSTRING("Security by Default"),
  861. nullptr, // aDocument
  862. nsContentUtils::eNECKO_PROPERTIES,
  863. "APIDeprecationWarning",
  864. params, ArrayLength(params));
  865. // Call NewChannel2 providing default arguments for the loadInfo.
  866. return NewChannel2(aSpec,
  867. aCharset,
  868. aBaseURI,
  869. nullptr, // aLoadingNode
  870. nsContentUtils::GetSystemPrincipal(), // aLoadingPrincipal
  871. nullptr, // aTriggeringPrincipal
  872. nsILoadInfo::SEC_ALLOW_CROSS_ORIGIN_DATA_IS_NULL,
  873. nsIContentPolicy::TYPE_OTHER,
  874. result);
  875. }
  876. bool
  877. nsIOService::IsLinkUp()
  878. {
  879. InitializeNetworkLinkService();
  880. if (!mNetworkLinkService) {
  881. // We cannot decide, assume the link is up
  882. return true;
  883. }
  884. bool isLinkUp;
  885. nsresult rv;
  886. rv = mNetworkLinkService->GetIsLinkUp(&isLinkUp);
  887. if (NS_FAILED(rv)) {
  888. return true;
  889. }
  890. return isLinkUp;
  891. }
  892. NS_IMETHODIMP
  893. nsIOService::GetOffline(bool *offline)
  894. {
  895. if (mOfflineMirrorsConnectivity) {
  896. *offline = mOffline || !mConnectivity;
  897. } else {
  898. *offline = mOffline;
  899. }
  900. return NS_OK;
  901. }
  902. NS_IMETHODIMP
  903. nsIOService::SetOffline(bool offline)
  904. {
  905. LOG(("nsIOService::SetOffline offline=%d\n", offline));
  906. // When someone wants to go online (!offline) after we got XPCOM shutdown
  907. // throw ERROR_NOT_AVAILABLE to prevent return to online state.
  908. if ((mShutdown || mOfflineForProfileChange) && !offline)
  909. return NS_ERROR_NOT_AVAILABLE;
  910. // SetOffline() may re-enter while it's shutting down services.
  911. // If that happens, save the most recent value and it will be
  912. // processed when the first SetOffline() call is done bringing
  913. // down the service.
  914. mSetOfflineValue = offline;
  915. if (mSettingOffline) {
  916. return NS_OK;
  917. }
  918. mSettingOffline = true;
  919. nsCOMPtr<nsIObserverService> observerService = services::GetObserverService();
  920. NS_ASSERTION(observerService, "The observer service should not be null");
  921. if (XRE_IsParentProcess()) {
  922. if (observerService) {
  923. (void)observerService->NotifyObservers(nullptr,
  924. NS_IPC_IOSERVICE_SET_OFFLINE_TOPIC, offline ?
  925. u"true" :
  926. u"false");
  927. }
  928. }
  929. nsIIOService *subject = static_cast<nsIIOService *>(this);
  930. while (mSetOfflineValue != mOffline) {
  931. offline = mSetOfflineValue;
  932. if (offline && !mOffline) {
  933. NS_NAMED_LITERAL_STRING(offlineString, NS_IOSERVICE_OFFLINE);
  934. mOffline = true; // indicate we're trying to shutdown
  935. // don't care if notifications fail
  936. if (observerService)
  937. observerService->NotifyObservers(subject,
  938. NS_IOSERVICE_GOING_OFFLINE_TOPIC,
  939. offlineString.get());
  940. if (mSocketTransportService)
  941. mSocketTransportService->SetOffline(true);
  942. if (observerService)
  943. observerService->NotifyObservers(subject,
  944. NS_IOSERVICE_OFFLINE_STATUS_TOPIC,
  945. offlineString.get());
  946. }
  947. else if (!offline && mOffline) {
  948. // go online
  949. if (mDNSService) {
  950. DebugOnly<nsresult> rv = mDNSService->Init();
  951. NS_ASSERTION(NS_SUCCEEDED(rv), "DNS service init failed");
  952. }
  953. InitializeSocketTransportService();
  954. mOffline = false; // indicate success only AFTER we've
  955. // brought up the services
  956. // trigger a PAC reload when we come back online
  957. if (mProxyService)
  958. mProxyService->ReloadPAC();
  959. // don't care if notification fails
  960. // Only send the ONLINE notification if there is connectivity
  961. if (observerService && mConnectivity) {
  962. observerService->NotifyObservers(subject,
  963. NS_IOSERVICE_OFFLINE_STATUS_TOPIC,
  964. (u"" NS_IOSERVICE_ONLINE));
  965. }
  966. }
  967. }
  968. // Don't notify here, as the above notifications (if used) suffice.
  969. if ((mShutdown || mOfflineForProfileChange) && mOffline) {
  970. // be sure to try and shutdown both (even if the first fails)...
  971. // shutdown dns service first, because it has callbacks for socket transport
  972. if (mDNSService) {
  973. DebugOnly<nsresult> rv = mDNSService->Shutdown();
  974. NS_ASSERTION(NS_SUCCEEDED(rv), "DNS service shutdown failed");
  975. }
  976. if (mSocketTransportService) {
  977. DebugOnly<nsresult> rv = mSocketTransportService->Shutdown(mShutdown);
  978. NS_ASSERTION(NS_SUCCEEDED(rv), "socket transport service shutdown failed");
  979. }
  980. }
  981. mSettingOffline = false;
  982. return NS_OK;
  983. }
  984. NS_IMETHODIMP
  985. nsIOService::GetConnectivity(bool *aConnectivity)
  986. {
  987. *aConnectivity = mConnectivity;
  988. return NS_OK;
  989. }
  990. NS_IMETHODIMP
  991. nsIOService::SetConnectivity(bool aConnectivity)
  992. {
  993. LOG(("nsIOService::SetConnectivity aConnectivity=%d\n", aConnectivity));
  994. // This should only be called from ContentChild to pass the connectivity
  995. // value from the chrome process to the content process.
  996. if (XRE_IsParentProcess()) {
  997. return NS_ERROR_NOT_AVAILABLE;
  998. }
  999. return SetConnectivityInternal(aConnectivity);
  1000. }
  1001. nsresult
  1002. nsIOService::SetConnectivityInternal(bool aConnectivity)
  1003. {
  1004. LOG(("nsIOService::SetConnectivityInternal aConnectivity=%d\n", aConnectivity));
  1005. if (mConnectivity == aConnectivity) {
  1006. // Nothing to do here.
  1007. return NS_OK;
  1008. }
  1009. mConnectivity = aConnectivity;
  1010. if (mCaptivePortalService) {
  1011. if (aConnectivity && !xpc::AreNonLocalConnectionsDisabled() && gCaptivePortalEnabled) {
  1012. // This will also trigger a captive portal check for the new network
  1013. static_cast<CaptivePortalService*>(mCaptivePortalService.get())->Start();
  1014. } else {
  1015. static_cast<CaptivePortalService*>(mCaptivePortalService.get())->Stop();
  1016. }
  1017. }
  1018. nsCOMPtr<nsIObserverService> observerService = services::GetObserverService();
  1019. if (!observerService) {
  1020. return NS_OK;
  1021. }
  1022. // This notification sends the connectivity to the child processes
  1023. if (XRE_IsParentProcess()) {
  1024. observerService->NotifyObservers(nullptr,
  1025. NS_IPC_IOSERVICE_SET_CONNECTIVITY_TOPIC, aConnectivity ?
  1026. u"true" :
  1027. u"false");
  1028. }
  1029. if (mOffline) {
  1030. // We don't need to send any notifications if we're offline
  1031. return NS_OK;
  1032. }
  1033. if (aConnectivity) {
  1034. // If we were previously offline due to connectivity=false,
  1035. // send the ONLINE notification
  1036. observerService->NotifyObservers(
  1037. static_cast<nsIIOService *>(this),
  1038. NS_IOSERVICE_OFFLINE_STATUS_TOPIC,
  1039. (u"" NS_IOSERVICE_ONLINE));
  1040. } else {
  1041. // If we were previously online and lost connectivity
  1042. // send the OFFLINE notification
  1043. const nsLiteralString offlineString(u"" NS_IOSERVICE_OFFLINE);
  1044. observerService->NotifyObservers(static_cast<nsIIOService *>(this),
  1045. NS_IOSERVICE_GOING_OFFLINE_TOPIC,
  1046. offlineString.get());
  1047. observerService->NotifyObservers(static_cast<nsIIOService *>(this),
  1048. NS_IOSERVICE_OFFLINE_STATUS_TOPIC,
  1049. offlineString.get());
  1050. }
  1051. return NS_OK;
  1052. }
  1053. NS_IMETHODIMP
  1054. nsIOService::AllowPort(int32_t inPort, const char *scheme, bool *_retval)
  1055. {
  1056. int32_t port = inPort;
  1057. if (port == -1) {
  1058. *_retval = true;
  1059. return NS_OK;
  1060. }
  1061. // Ensure the port number is within a valid range
  1062. if (port <= 0 || port > std::numeric_limits<uint16_t>::max()) {
  1063. *_retval = false;
  1064. return NS_OK;
  1065. }
  1066. // first check to see if the port is in our blacklist:
  1067. int32_t badPortListCnt = mRestrictedPortList.Length();
  1068. for (int i=0; i<badPortListCnt; i++)
  1069. {
  1070. if (port == mRestrictedPortList[i])
  1071. {
  1072. *_retval = false;
  1073. // check to see if the protocol wants to override
  1074. if (!scheme)
  1075. return NS_OK;
  1076. nsCOMPtr<nsIProtocolHandler> handler;
  1077. nsresult rv = GetProtocolHandler(scheme, getter_AddRefs(handler));
  1078. if (NS_FAILED(rv)) return rv;
  1079. // let the protocol handler decide
  1080. return handler->AllowPort(port, scheme, _retval);
  1081. }
  1082. }
  1083. *_retval = true;
  1084. return NS_OK;
  1085. }
  1086. ////////////////////////////////////////////////////////////////////////////////
  1087. void
  1088. nsIOService::PrefsChanged(nsIPrefBranch *prefs, const char *pref)
  1089. {
  1090. if (!prefs) return;
  1091. // Look for extra ports to block
  1092. if (!pref || strcmp(pref, PORT_PREF("banned")) == 0)
  1093. ParsePortList(prefs, PORT_PREF("banned"), false);
  1094. // ...as well as previous blocks to remove.
  1095. if (!pref || strcmp(pref, PORT_PREF("banned.override")) == 0)
  1096. ParsePortList(prefs, PORT_PREF("banned.override"), true);
  1097. if (!pref || strcmp(pref, MANAGE_OFFLINE_STATUS_PREF) == 0) {
  1098. bool manage;
  1099. if (mNetworkLinkServiceInitialized &&
  1100. NS_SUCCEEDED(prefs->GetBoolPref(MANAGE_OFFLINE_STATUS_PREF,
  1101. &manage))) {
  1102. LOG(("nsIOService::PrefsChanged ManageOfflineStatus manage=%d\n", manage));
  1103. SetManageOfflineStatus(manage);
  1104. }
  1105. }
  1106. if (!pref || strcmp(pref, NECKO_BUFFER_CACHE_COUNT_PREF) == 0) {
  1107. int32_t count;
  1108. if (NS_SUCCEEDED(prefs->GetIntPref(NECKO_BUFFER_CACHE_COUNT_PREF,
  1109. &count)))
  1110. /* check for bogus values and default if we find such a value */
  1111. if (count > 0)
  1112. gDefaultSegmentCount = count;
  1113. }
  1114. if (!pref || strcmp(pref, NECKO_BUFFER_CACHE_SIZE_PREF) == 0) {
  1115. int32_t size;
  1116. if (NS_SUCCEEDED(prefs->GetIntPref(NECKO_BUFFER_CACHE_SIZE_PREF,
  1117. &size)))
  1118. /* check for bogus values and default if we find such a value
  1119. * the upper limit here is arbitrary. having a 1mb segment size
  1120. * is pretty crazy. if you remove this, consider adding some
  1121. * integer rollover test.
  1122. */
  1123. if (size > 0 && size < 1024*1024)
  1124. gDefaultSegmentSize = size;
  1125. NS_WARNING_ASSERTION(!(size & (size - 1)),
  1126. "network segment size is not a power of 2!");
  1127. }
  1128. if (!pref || strcmp(pref, NETWORK_NOTIFY_CHANGED_PREF) == 0) {
  1129. bool allow;
  1130. nsresult rv = prefs->GetBoolPref(NETWORK_NOTIFY_CHANGED_PREF, &allow);
  1131. if (NS_SUCCEEDED(rv)) {
  1132. mNetworkNotifyChanged = allow;
  1133. }
  1134. }
  1135. if (!pref || strcmp(pref, NETWORK_CAPTIVE_PORTAL_PREF) == 0) {
  1136. nsresult rv = prefs->GetBoolPref(NETWORK_CAPTIVE_PORTAL_PREF, &gCaptivePortalEnabled);
  1137. if (NS_SUCCEEDED(rv) && mCaptivePortalService) {
  1138. if (gCaptivePortalEnabled && !xpc::AreNonLocalConnectionsDisabled()) {
  1139. static_cast<CaptivePortalService*>(mCaptivePortalService.get())->Start();
  1140. } else {
  1141. static_cast<CaptivePortalService*>(mCaptivePortalService.get())->Stop();
  1142. }
  1143. }
  1144. }
  1145. }
  1146. void
  1147. nsIOService::ParsePortList(nsIPrefBranch *prefBranch, const char *pref, bool remove)
  1148. {
  1149. nsXPIDLCString portList;
  1150. // Get a pref string and chop it up into a list of ports.
  1151. prefBranch->GetCharPref(pref, getter_Copies(portList));
  1152. if (portList) {
  1153. nsTArray<nsCString> portListArray;
  1154. ParseString(portList, ',', portListArray);
  1155. uint32_t index;
  1156. for (index=0; index < portListArray.Length(); index++) {
  1157. portListArray[index].StripWhitespace();
  1158. int32_t portBegin, portEnd;
  1159. if (PR_sscanf(portListArray[index].get(), "%d-%d", &portBegin, &portEnd) == 2) {
  1160. if ((portBegin < 65536) && (portEnd < 65536)) {
  1161. int32_t curPort;
  1162. if (remove) {
  1163. for (curPort=portBegin; curPort <= portEnd; curPort++)
  1164. mRestrictedPortList.RemoveElement(curPort);
  1165. } else {
  1166. for (curPort=portBegin; curPort <= portEnd; curPort++)
  1167. mRestrictedPortList.AppendElement(curPort);
  1168. }
  1169. }
  1170. } else {
  1171. nsresult aErrorCode;
  1172. int32_t port = portListArray[index].ToInteger(&aErrorCode);
  1173. if (NS_SUCCEEDED(aErrorCode) && port < 65536) {
  1174. if (remove)
  1175. mRestrictedPortList.RemoveElement(port);
  1176. else
  1177. mRestrictedPortList.AppendElement(port);
  1178. }
  1179. }
  1180. }
  1181. }
  1182. }
  1183. void
  1184. nsIOService::GetPrefBranch(nsIPrefBranch **result)
  1185. {
  1186. *result = nullptr;
  1187. CallGetService(NS_PREFSERVICE_CONTRACTID, result);
  1188. }
  1189. class nsWakeupNotifier : public Runnable
  1190. {
  1191. public:
  1192. explicit nsWakeupNotifier(nsIIOServiceInternal *ioService)
  1193. :mIOService(ioService)
  1194. { }
  1195. NS_IMETHOD Run() override
  1196. {
  1197. return mIOService->NotifyWakeup();
  1198. }
  1199. private:
  1200. virtual ~nsWakeupNotifier() { }
  1201. nsCOMPtr<nsIIOServiceInternal> mIOService;
  1202. };
  1203. NS_IMETHODIMP
  1204. nsIOService::NotifyWakeup()
  1205. {
  1206. nsCOMPtr<nsIObserverService> observerService = services::GetObserverService();
  1207. NS_ASSERTION(observerService, "The observer service should not be null");
  1208. if (observerService && mNetworkNotifyChanged) {
  1209. (void)observerService->
  1210. NotifyObservers(nullptr,
  1211. NS_NETWORK_LINK_TOPIC,
  1212. (u"" NS_NETWORK_LINK_DATA_CHANGED));
  1213. }
  1214. RecheckCaptivePortal();
  1215. return NS_OK;
  1216. }
  1217. void
  1218. nsIOService::SetHttpHandlerAlreadyShutingDown()
  1219. {
  1220. if (!mShutdown && !mOfflineForProfileChange) {
  1221. mNetTearingDownStarted = PR_IntervalNow();
  1222. mHttpHandlerAlreadyShutingDown = true;
  1223. }
  1224. }
  1225. // nsIObserver interface
  1226. NS_IMETHODIMP
  1227. nsIOService::Observe(nsISupports *subject,
  1228. const char *topic,
  1229. const char16_t *data)
  1230. {
  1231. if (!strcmp(topic, NS_PREFBRANCH_PREFCHANGE_TOPIC_ID)) {
  1232. nsCOMPtr<nsIPrefBranch> prefBranch = do_QueryInterface(subject);
  1233. if (prefBranch)
  1234. PrefsChanged(prefBranch, NS_ConvertUTF16toUTF8(data).get());
  1235. } else if (!strcmp(topic, kProfileChangeNetTeardownTopic)) {
  1236. if (!mHttpHandlerAlreadyShutingDown) {
  1237. mNetTearingDownStarted = PR_IntervalNow();
  1238. }
  1239. mHttpHandlerAlreadyShutingDown = false;
  1240. if (!mOffline) {
  1241. mOfflineForProfileChange = true;
  1242. SetOffline(true);
  1243. }
  1244. } else if (!strcmp(topic, kProfileChangeNetRestoreTopic)) {
  1245. if (mOfflineForProfileChange) {
  1246. mOfflineForProfileChange = false;
  1247. SetOffline(false);
  1248. }
  1249. } else if (!strcmp(topic, kProfileDoChange)) {
  1250. if (data && NS_LITERAL_STRING("startup").Equals(data)) {
  1251. // Lazy initialization of network link service (see bug 620472)
  1252. InitializeNetworkLinkService();
  1253. // Set up the initilization flag regardless the actuall result.
  1254. // If we fail here, we will fail always on.
  1255. mNetworkLinkServiceInitialized = true;
  1256. // And now reflect the preference setting
  1257. nsCOMPtr<nsIPrefBranch> prefBranch;
  1258. GetPrefBranch(getter_AddRefs(prefBranch));
  1259. PrefsChanged(prefBranch, MANAGE_OFFLINE_STATUS_PREF);
  1260. }
  1261. } else if (!strcmp(topic, NS_XPCOM_SHUTDOWN_OBSERVER_ID)) {
  1262. // Remember we passed XPCOM shutdown notification to prevent any
  1263. // changes of the offline status from now. We must not allow going
  1264. // online after this point.
  1265. mShutdown = true;
  1266. if (!mHttpHandlerAlreadyShutingDown && !mOfflineForProfileChange) {
  1267. mNetTearingDownStarted = PR_IntervalNow();
  1268. }
  1269. mHttpHandlerAlreadyShutingDown = false;
  1270. SetOffline(true);
  1271. if (mCaptivePortalService) {
  1272. static_cast<CaptivePortalService*>(mCaptivePortalService.get())->Stop();
  1273. mCaptivePortalService = nullptr;
  1274. }
  1275. // Break circular reference.
  1276. mProxyService = nullptr;
  1277. } else if (!strcmp(topic, NS_NETWORK_LINK_TOPIC)) {
  1278. OnNetworkLinkEvent(NS_ConvertUTF16toUTF8(data).get());
  1279. } else if (!strcmp(topic, NS_WIDGET_WAKE_OBSERVER_TOPIC)) {
  1280. // coming back alive from sleep
  1281. // this indirection brought to you by:
  1282. // https://bugzilla.mozilla.org/show_bug.cgi?id=1152048#c19
  1283. nsCOMPtr<nsIRunnable> wakeupNotifier = new nsWakeupNotifier(this);
  1284. NS_DispatchToMainThread(wakeupNotifier);
  1285. }
  1286. return NS_OK;
  1287. }
  1288. // nsINetUtil interface
  1289. NS_IMETHODIMP
  1290. nsIOService::ParseRequestContentType(const nsACString &aTypeHeader,
  1291. nsACString &aCharset,
  1292. bool *aHadCharset,
  1293. nsACString &aContentType)
  1294. {
  1295. net_ParseRequestContentType(aTypeHeader, aContentType, aCharset, aHadCharset);
  1296. return NS_OK;
  1297. }
  1298. // nsINetUtil interface
  1299. NS_IMETHODIMP
  1300. nsIOService::ParseResponseContentType(const nsACString &aTypeHeader,
  1301. nsACString &aCharset,
  1302. bool *aHadCharset,
  1303. nsACString &aContentType)
  1304. {
  1305. net_ParseContentType(aTypeHeader, aContentType, aCharset, aHadCharset);
  1306. return NS_OK;
  1307. }
  1308. NS_IMETHODIMP
  1309. nsIOService::ProtocolHasFlags(nsIURI *uri,
  1310. uint32_t flags,
  1311. bool *result)
  1312. {
  1313. NS_ENSURE_ARG(uri);
  1314. *result = false;
  1315. nsAutoCString scheme;
  1316. nsresult rv = uri->GetScheme(scheme);
  1317. NS_ENSURE_SUCCESS(rv, rv);
  1318. // Grab the protocol flags from the URI.
  1319. uint32_t protocolFlags;
  1320. nsCOMPtr<nsIProtocolHandler> handler;
  1321. rv = GetProtocolHandler(scheme.get(), getter_AddRefs(handler));
  1322. NS_ENSURE_SUCCESS(rv, rv);
  1323. rv = handler->DoGetProtocolFlags(uri, &protocolFlags);
  1324. NS_ENSURE_SUCCESS(rv, rv);
  1325. *result = (protocolFlags & flags) == flags;
  1326. return NS_OK;
  1327. }
  1328. NS_IMETHODIMP
  1329. nsIOService::URIChainHasFlags(nsIURI *uri,
  1330. uint32_t flags,
  1331. bool *result)
  1332. {
  1333. nsresult rv = ProtocolHasFlags(uri, flags, result);
  1334. NS_ENSURE_SUCCESS(rv, rv);
  1335. if (*result) {
  1336. return rv;
  1337. }
  1338. // Dig deeper into the chain. Note that this is not a do/while loop to
  1339. // avoid the extra addref/release on |uri| in the common (non-nested) case.
  1340. nsCOMPtr<nsINestedURI> nestedURI = do_QueryInterface(uri);
  1341. while (nestedURI) {
  1342. nsCOMPtr<nsIURI> innerURI;
  1343. rv = nestedURI->GetInnerURI(getter_AddRefs(innerURI));
  1344. NS_ENSURE_SUCCESS(rv, rv);
  1345. rv = ProtocolHasFlags(innerURI, flags, result);
  1346. if (*result) {
  1347. return rv;
  1348. }
  1349. nestedURI = do_QueryInterface(innerURI);
  1350. }
  1351. return rv;
  1352. }
  1353. NS_IMETHODIMP
  1354. nsIOService::ToImmutableURI(nsIURI* uri, nsIURI** result)
  1355. {
  1356. if (!uri) {
  1357. *result = nullptr;
  1358. return NS_OK;
  1359. }
  1360. nsresult rv = NS_EnsureSafeToReturn(uri, result);
  1361. NS_ENSURE_SUCCESS(rv, rv);
  1362. NS_TryToSetImmutable(*result);
  1363. return NS_OK;
  1364. }
  1365. NS_IMETHODIMP
  1366. nsIOService::NewSimpleNestedURI(nsIURI* aURI, nsIURI** aResult)
  1367. {
  1368. NS_ENSURE_ARG(aURI);
  1369. nsCOMPtr<nsIURI> safeURI;
  1370. nsresult rv = NS_EnsureSafeToReturn(aURI, getter_AddRefs(safeURI));
  1371. NS_ENSURE_SUCCESS(rv, rv);
  1372. NS_IF_ADDREF(*aResult = new nsSimpleNestedURI(safeURI));
  1373. return *aResult ? NS_OK : NS_ERROR_OUT_OF_MEMORY;
  1374. }
  1375. NS_IMETHODIMP
  1376. nsIOService::SetManageOfflineStatus(bool aManage)
  1377. {
  1378. LOG(("nsIOService::SetManageOfflineStatus aManage=%d\n", aManage));
  1379. mManageLinkStatus = aManage;
  1380. // When detection is not activated, the default connectivity state is true.
  1381. if (!mManageLinkStatus) {
  1382. SetConnectivityInternal(true);
  1383. return NS_OK;
  1384. }
  1385. InitializeNetworkLinkService();
  1386. // If the NetworkLinkService is already initialized, it does not call
  1387. // OnNetworkLinkEvent. This is needed, when mManageLinkStatus goes from
  1388. // false to true.
  1389. OnNetworkLinkEvent(NS_NETWORK_LINK_DATA_UNKNOWN);
  1390. return NS_OK;
  1391. }
  1392. NS_IMETHODIMP
  1393. nsIOService::GetManageOfflineStatus(bool* aManage)
  1394. {
  1395. *aManage = mManageLinkStatus;
  1396. return NS_OK;
  1397. }
  1398. // input argument 'data' is already UTF8'ed
  1399. nsresult
  1400. nsIOService::OnNetworkLinkEvent(const char *data)
  1401. {
  1402. LOG(("nsIOService::OnNetworkLinkEvent data:%s\n", data));
  1403. if (!mNetworkLinkService)
  1404. return NS_ERROR_FAILURE;
  1405. if (mShutdown)
  1406. return NS_ERROR_NOT_AVAILABLE;
  1407. if (!mManageLinkStatus) {
  1408. LOG(("nsIOService::OnNetworkLinkEvent mManageLinkStatus=false\n"));
  1409. return NS_OK;
  1410. }
  1411. bool isUp = true;
  1412. if (!strcmp(data, NS_NETWORK_LINK_DATA_CHANGED)) {
  1413. // CHANGED means UP/DOWN didn't change
  1414. // but the status of the captive portal may have changed.
  1415. RecheckCaptivePortal();
  1416. return NS_OK;
  1417. } else if (!strcmp(data, NS_NETWORK_LINK_DATA_DOWN)) {
  1418. isUp = false;
  1419. } else if (!strcmp(data, NS_NETWORK_LINK_DATA_UP)) {
  1420. isUp = true;
  1421. } else if (!strcmp(data, NS_NETWORK_LINK_DATA_UNKNOWN)) {
  1422. nsresult rv = mNetworkLinkService->GetIsLinkUp(&isUp);
  1423. NS_ENSURE_SUCCESS(rv, rv);
  1424. } else {
  1425. NS_WARNING("Unhandled network event!");
  1426. return NS_OK;
  1427. }
  1428. return SetConnectivityInternal(isUp);
  1429. }
  1430. NS_IMETHODIMP
  1431. nsIOService::EscapeString(const nsACString& aString,
  1432. uint32_t aEscapeType,
  1433. nsACString& aResult)
  1434. {
  1435. NS_ENSURE_ARG_MAX(aEscapeType, 4);
  1436. nsAutoCString stringCopy(aString);
  1437. nsCString result;
  1438. if (!NS_Escape(stringCopy, result, (nsEscapeMask) aEscapeType))
  1439. return NS_ERROR_OUT_OF_MEMORY;
  1440. aResult.Assign(result);
  1441. return NS_OK;
  1442. }
  1443. NS_IMETHODIMP
  1444. nsIOService::EscapeURL(const nsACString &aStr,
  1445. uint32_t aFlags, nsACString &aResult)
  1446. {
  1447. aResult.Truncate();
  1448. NS_EscapeURL(aStr.BeginReading(), aStr.Length(),
  1449. aFlags | esc_AlwaysCopy, aResult);
  1450. return NS_OK;
  1451. }
  1452. NS_IMETHODIMP
  1453. nsIOService::UnescapeString(const nsACString &aStr,
  1454. uint32_t aFlags, nsACString &aResult)
  1455. {
  1456. aResult.Truncate();
  1457. NS_UnescapeURL(aStr.BeginReading(), aStr.Length(),
  1458. aFlags | esc_AlwaysCopy, aResult);
  1459. return NS_OK;
  1460. }
  1461. NS_IMETHODIMP
  1462. nsIOService::ExtractCharsetFromContentType(const nsACString &aTypeHeader,
  1463. nsACString &aCharset,
  1464. int32_t *aCharsetStart,
  1465. int32_t *aCharsetEnd,
  1466. bool *aHadCharset)
  1467. {
  1468. nsAutoCString ignored;
  1469. net_ParseContentType(aTypeHeader, ignored, aCharset, aHadCharset,
  1470. aCharsetStart, aCharsetEnd);
  1471. if (*aHadCharset && *aCharsetStart == *aCharsetEnd) {
  1472. *aHadCharset = false;
  1473. }
  1474. return NS_OK;
  1475. }
  1476. // parse policyString to policy enum value (see ReferrerPolicy.h)
  1477. NS_IMETHODIMP
  1478. nsIOService::ParseAttributePolicyString(const nsAString& policyString,
  1479. uint32_t *outPolicyEnum)
  1480. {
  1481. NS_ENSURE_ARG(outPolicyEnum);
  1482. *outPolicyEnum = (uint32_t)AttributeReferrerPolicyFromString(policyString);
  1483. return NS_OK;
  1484. }
  1485. // nsISpeculativeConnect
  1486. class IOServiceProxyCallback final : public nsIProtocolProxyCallback
  1487. {
  1488. ~IOServiceProxyCallback() {}
  1489. public:
  1490. NS_DECL_ISUPPORTS
  1491. NS_DECL_NSIPROTOCOLPROXYCALLBACK
  1492. IOServiceProxyCallback(nsIInterfaceRequestor *aCallbacks,
  1493. nsIOService *aIOService)
  1494. : mCallbacks(aCallbacks)
  1495. , mIOService(aIOService)
  1496. { }
  1497. private:
  1498. RefPtr<nsIInterfaceRequestor> mCallbacks;
  1499. RefPtr<nsIOService> mIOService;
  1500. };
  1501. NS_IMPL_ISUPPORTS(IOServiceProxyCallback, nsIProtocolProxyCallback)
  1502. NS_IMETHODIMP
  1503. IOServiceProxyCallback::OnProxyAvailable(nsICancelable *request, nsIChannel *channel,
  1504. nsIProxyInfo *pi, nsresult status)
  1505. {
  1506. // Checking proxy status for speculative connect
  1507. nsAutoCString type;
  1508. if (NS_SUCCEEDED(status) && pi &&
  1509. NS_SUCCEEDED(pi->GetType(type)) &&
  1510. !type.EqualsLiteral("direct")) {
  1511. // proxies dont do speculative connect
  1512. return NS_OK;
  1513. }
  1514. nsCOMPtr<nsIURI> uri;
  1515. nsresult rv = channel->GetURI(getter_AddRefs(uri));
  1516. if (NS_FAILED(rv)) {
  1517. return NS_OK;
  1518. }
  1519. nsAutoCString scheme;
  1520. rv = uri->GetScheme(scheme);
  1521. if (NS_FAILED(rv))
  1522. return NS_OK;
  1523. nsCOMPtr<nsIProtocolHandler> handler;
  1524. rv = mIOService->GetProtocolHandler(scheme.get(),
  1525. getter_AddRefs(handler));
  1526. if (NS_FAILED(rv))
  1527. return NS_OK;
  1528. nsCOMPtr<nsISpeculativeConnect> speculativeHandler =
  1529. do_QueryInterface(handler);
  1530. if (!speculativeHandler)
  1531. return NS_OK;
  1532. nsCOMPtr<nsILoadInfo> loadInfo = channel->GetLoadInfo();
  1533. nsCOMPtr<nsIPrincipal> principal;
  1534. if (loadInfo) {
  1535. principal = loadInfo->LoadingPrincipal();
  1536. }
  1537. nsLoadFlags loadFlags = 0;
  1538. channel->GetLoadFlags(&loadFlags);
  1539. if (loadFlags & nsIRequest::LOAD_ANONYMOUS) {
  1540. speculativeHandler->SpeculativeAnonymousConnect2(uri, principal, mCallbacks);
  1541. } else {
  1542. speculativeHandler->SpeculativeConnect2(uri, principal, mCallbacks);
  1543. }
  1544. return NS_OK;
  1545. }
  1546. nsresult
  1547. nsIOService::SpeculativeConnectInternal(nsIURI *aURI,
  1548. nsIPrincipal *aPrincipal,
  1549. nsIInterfaceRequestor *aCallbacks,
  1550. bool aAnonymous)
  1551. {
  1552. if (IsNeckoChild()) {
  1553. ipc::URIParams params;
  1554. SerializeURI(aURI, params);
  1555. gNeckoChild->SendSpeculativeConnect(params,
  1556. IPC::Principal(aPrincipal),
  1557. aAnonymous);
  1558. return NS_OK;
  1559. }
  1560. // Check for proxy information. If there is a proxy configured then a
  1561. // speculative connect should not be performed because the potential
  1562. // reward is slim with tcp peers closely located to the browser.
  1563. nsresult rv;
  1564. nsCOMPtr<nsIProtocolProxyService> pps =
  1565. do_GetService(NS_PROTOCOLPROXYSERVICE_CONTRACTID, &rv);
  1566. NS_ENSURE_SUCCESS(rv, rv);
  1567. nsCOMPtr<nsIPrincipal> loadingPrincipal = aPrincipal;
  1568. // If the principal is given, we use this prinicpal directly. Otherwise,
  1569. // we fallback to use the system principal.
  1570. if (!aPrincipal) {
  1571. nsCOMPtr<nsIScriptSecurityManager> secMan(
  1572. do_GetService(NS_SCRIPTSECURITYMANAGER_CONTRACTID, &rv));
  1573. NS_ENSURE_SUCCESS(rv, rv);
  1574. rv = secMan->GetSystemPrincipal(getter_AddRefs(loadingPrincipal));
  1575. NS_ENSURE_SUCCESS(rv, rv);
  1576. }
  1577. // dummy channel used to create a TCP connection.
  1578. // we perform security checks on the *real* channel, responsible
  1579. // for any network loads. this real channel just checks the TCP
  1580. // pool if there is an available connection created by the
  1581. // channel we create underneath - hence it's safe to use
  1582. // the systemPrincipal as the loadingPrincipal for this channel.
  1583. nsCOMPtr<nsIChannel> channel;
  1584. rv = NewChannelFromURI2(aURI,
  1585. nullptr, // aLoadingNode,
  1586. loadingPrincipal,
  1587. nullptr, //aTriggeringPrincipal,
  1588. nsILoadInfo::SEC_ALLOW_CROSS_ORIGIN_DATA_IS_NULL,
  1589. nsIContentPolicy::TYPE_OTHER,
  1590. getter_AddRefs(channel));
  1591. NS_ENSURE_SUCCESS(rv, rv);
  1592. if (aAnonymous) {
  1593. nsLoadFlags loadFlags = 0;
  1594. channel->GetLoadFlags(&loadFlags);
  1595. loadFlags |= nsIRequest::LOAD_ANONYMOUS;
  1596. channel->SetLoadFlags(loadFlags);
  1597. }
  1598. nsCOMPtr<nsICancelable> cancelable;
  1599. RefPtr<IOServiceProxyCallback> callback =
  1600. new IOServiceProxyCallback(aCallbacks, this);
  1601. nsCOMPtr<nsIProtocolProxyService2> pps2 = do_QueryInterface(pps);
  1602. if (pps2) {
  1603. return pps2->AsyncResolve2(channel, 0, callback, getter_AddRefs(cancelable));
  1604. }
  1605. return pps->AsyncResolve(channel, 0, callback, getter_AddRefs(cancelable));
  1606. }
  1607. NS_IMETHODIMP
  1608. nsIOService::SpeculativeConnect(nsIURI *aURI,
  1609. nsIInterfaceRequestor *aCallbacks)
  1610. {
  1611. return SpeculativeConnectInternal(aURI, nullptr, aCallbacks, false);
  1612. }
  1613. NS_IMETHODIMP
  1614. nsIOService::SpeculativeConnect2(nsIURI *aURI,
  1615. nsIPrincipal *aPrincipal,
  1616. nsIInterfaceRequestor *aCallbacks)
  1617. {
  1618. return SpeculativeConnectInternal(aURI, aPrincipal, aCallbacks, false);
  1619. }
  1620. NS_IMETHODIMP
  1621. nsIOService::SpeculativeAnonymousConnect(nsIURI *aURI,
  1622. nsIInterfaceRequestor *aCallbacks)
  1623. {
  1624. return SpeculativeConnectInternal(aURI, nullptr, aCallbacks, true);
  1625. }
  1626. NS_IMETHODIMP
  1627. nsIOService::SpeculativeAnonymousConnect2(nsIURI *aURI,
  1628. nsIPrincipal *aPrincipal,
  1629. nsIInterfaceRequestor *aCallbacks)
  1630. {
  1631. return SpeculativeConnectInternal(aURI, aPrincipal, aCallbacks, true);
  1632. }
  1633. /*static*/ bool
  1634. nsIOService::BlockToplevelDataUriNavigations()
  1635. {
  1636. return sBlockToplevelDataUriNavigations;
  1637. }
  1638. /*static*/ bool
  1639. nsIOService::BlockFTPSubresources()
  1640. {
  1641. return sBlockFTPSubresources;
  1642. }
  1643. } // namespace net
  1644. } // namespace mozilla