Bug 458256. Use LoadLibraryW instead of LoadLibrary (patch by DougT). r+sr=vlad
[wine-gecko.git] / netwerk / base / src / nsIOService.cpp
blob7d3afaf896b37ed86e6c95f1454bb314d578691c
1 /* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
2 /* vim:set ts=4 sw=4 cindent et: */
3 /* ***** BEGIN LICENSE BLOCK *****
4 * Version: MPL 1.1/GPL 2.0/LGPL 2.1
6 * The contents of this file are subject to the Mozilla Public License Version
7 * 1.1 (the "License"); you may not use this file except in compliance with
8 * the License. You may obtain a copy of the License at
9 * http://www.mozilla.org/MPL/
11 * Software distributed under the License is distributed on an "AS IS" basis,
12 * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
13 * for the specific language governing rights and limitations under the
14 * License.
16 * The Original Code is mozilla.org code.
18 * The Initial Developer of the Original Code is
19 * Netscape Communications Corporation.
20 * Portions created by the Initial Developer are Copyright (C) 1998
21 * the Initial Developer. All Rights Reserved.
23 * Contributor(s):
24 * Prasad Sunkari <prasad@medhas.org>
26 * Alternatively, the contents of this file may be used under the terms of
27 * either the GNU General Public License Version 2 or later (the "GPL"), or
28 * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
29 * in which case the provisions of the GPL or the LGPL are applicable instead
30 * of those above. If you wish to allow use of your version of this file only
31 * under the terms of either the GPL or the LGPL, and not to allow others to
32 * use your version of this file under the terms of the MPL, indicate your
33 * decision by deleting the provisions above and replace them with the notice
34 * and other provisions required by the GPL or the LGPL. If you do not delete
35 * the provisions above, a recipient may use your version of this file under
36 * the terms of any one of the MPL, the GPL or the LGPL.
38 * ***** END LICENSE BLOCK ***** */
40 #include "nsIOService.h"
41 #include "nsIProtocolHandler.h"
42 #include "nsIFileProtocolHandler.h"
43 #include "nscore.h"
44 #include "nsIServiceManager.h"
45 #include "nsIURI.h"
46 #include "nsIStreamListener.h"
47 #include "prprf.h"
48 #include "prlog.h"
49 #include "nsLoadGroup.h"
50 #include "nsInputStreamChannel.h"
51 #include "nsXPIDLString.h"
52 #include "nsReadableUtils.h"
53 #include "nsIErrorService.h"
54 #include "netCore.h"
55 #include "nsIObserverService.h"
56 #include "nsIPrefService.h"
57 #include "nsIPrefBranch2.h"
58 #include "nsIPrefLocalizedString.h"
59 #include "nsICategoryManager.h"
60 #include "nsXPCOM.h"
61 #include "nsISupportsPrimitives.h"
62 #include "nsIProxiedProtocolHandler.h"
63 #include "nsIProxyInfo.h"
64 #include "nsITimelineService.h"
65 #include "nsEscape.h"
66 #include "nsNetCID.h"
67 #include "nsIRecyclingAllocator.h"
68 #include "nsISocketTransport.h"
69 #include "nsCRT.h"
70 #include "nsINestedURI.h"
71 #include "nsNetUtil.h"
72 #include "nsThreadUtils.h"
73 #include "nsIPermissionManager.h"
75 #if defined(XP_WIN)
76 #include "nsNativeConnectionHelper.h"
77 #endif
79 #define PORT_PREF_PREFIX "network.security.ports."
80 #define PORT_PREF(x) PORT_PREF_PREFIX x
81 #define AUTODIAL_PREF "network.autodial-helper.enabled"
83 #define MAX_RECURSION_COUNT 50
85 nsIOService* gIOService = nsnull;
87 // A general port blacklist. Connections to these ports will not be allowed unless
88 // the protocol overrides.
90 // TODO: I am sure that there are more ports to be added.
91 // This cut is based on the classic mozilla codebase
93 PRInt16 gBadPortList[] = {
94 1, // tcpmux
95 7, // echo
96 9, // discard
97 11, // systat
98 13, // daytime
99 15, // netstat
100 17, // qotd
101 19, // chargen
102 20, // ftp-data
103 21, // ftp-cntl
104 22, // ssh
105 23, // telnet
106 25, // smtp
107 37, // time
108 42, // name
109 43, // nicname
110 53, // domain
111 77, // priv-rjs
112 79, // finger
113 87, // ttylink
114 95, // supdup
115 101, // hostriame
116 102, // iso-tsap
117 103, // gppitnp
118 104, // acr-nema
119 109, // pop2
120 110, // pop3
121 111, // sunrpc
122 113, // auth
123 115, // sftp
124 117, // uucp-path
125 119, // nntp
126 123, // NTP
127 135, // loc-srv / epmap
128 139, // netbios
129 143, // imap2
130 179, // BGP
131 389, // ldap
132 465, // smtp+ssl
133 512, // print / exec
134 513, // login
135 514, // shell
136 515, // printer
137 526, // tempo
138 530, // courier
139 531, // Chat
140 532, // netnews
141 540, // uucp
142 556, // remotefs
143 563, // nntp+ssl
144 587, //
145 601, //
146 636, // ldap+ssl
147 993, // imap+ssl
148 995, // pop3+ssl
149 2049, // nfs
150 4045, // lockd
151 6000, // x11
152 0, // This MUST be zero so that we can populating the array
155 static const char kProfileChangeNetTeardownTopic[] = "profile-change-net-teardown";
156 static const char kProfileChangeNetRestoreTopic[] = "profile-change-net-restore";
158 // Necko buffer cache
159 nsIMemory* nsIOService::gBufferCache = nsnull;
161 ////////////////////////////////////////////////////////////////////////////////
163 nsIOService::nsIOService()
164 : mOffline(PR_FALSE)
165 , mOfflineForProfileChange(PR_FALSE)
166 , mManageOfflineStatus(PR_FALSE)
167 , mChannelEventSinks(NS_CHANNEL_EVENT_SINK_CATEGORY)
168 , mContentSniffers(NS_CONTENT_SNIFFER_CATEGORY)
170 // Get the allocator ready
171 if (!gBufferCache)
173 nsresult rv = NS_OK;
174 nsCOMPtr<nsIRecyclingAllocator> recyclingAllocator =
175 do_CreateInstance(NS_RECYCLINGALLOCATOR_CONTRACTID, &rv);
176 if (NS_FAILED(rv))
177 return;
178 rv = recyclingAllocator->Init(NS_NECKO_BUFFER_CACHE_COUNT,
179 NS_NECKO_15_MINS, "necko");
180 if (NS_FAILED(rv))
181 return;
183 nsCOMPtr<nsIMemory> eyeMemory = do_QueryInterface(recyclingAllocator);
184 gBufferCache = eyeMemory.get();
185 NS_IF_ADDREF(gBufferCache);
189 nsresult
190 nsIOService::Init()
192 nsresult rv;
194 // We need to get references to these services so that we can shut them
195 // down later. If we wait until the nsIOService is being shut down,
196 // GetService will fail at that point.
198 // TODO(darin): Load the Socket and DNS services lazily.
200 mSocketTransportService = do_GetService(NS_SOCKETTRANSPORTSERVICE_CONTRACTID, &rv);
201 if (NS_FAILED(rv)) {
202 NS_WARNING("failed to get socket transport service");
203 return rv;
206 mDNSService = do_GetService(NS_DNSSERVICE_CONTRACTID, &rv);
207 if (NS_FAILED(rv)) {
208 NS_WARNING("failed to get DNS service");
209 return rv;
212 // XXX hack until xpidl supports error info directly (bug 13423)
213 nsCOMPtr<nsIErrorService> errorService = do_GetService(NS_ERRORSERVICE_CONTRACTID);
214 if (errorService) {
215 errorService->RegisterErrorStringBundle(NS_ERROR_MODULE_NETWORK, NECKO_MSGS_URL);
217 else
218 NS_WARNING("failed to get error service");
220 // setup our bad port list stuff
221 for(int i=0; gBadPortList[i]; i++)
222 mRestrictedPortList.AppendElement(reinterpret_cast<void *>(gBadPortList[i]));
224 // Further modifications to the port list come from prefs
225 nsCOMPtr<nsIPrefBranch2> prefBranch;
226 GetPrefBranch(getter_AddRefs(prefBranch));
227 if (prefBranch) {
228 prefBranch->AddObserver(PORT_PREF_PREFIX, this, PR_TRUE);
229 prefBranch->AddObserver(AUTODIAL_PREF, this, PR_TRUE);
230 PrefsChanged(prefBranch);
233 // Register for profile change notifications
234 nsCOMPtr<nsIObserverService> observerService =
235 do_GetService("@mozilla.org/observer-service;1");
236 if (observerService) {
237 observerService->AddObserver(this, kProfileChangeNetTeardownTopic, PR_TRUE);
238 observerService->AddObserver(this, kProfileChangeNetRestoreTopic, PR_TRUE);
239 observerService->AddObserver(this, NS_XPCOM_SHUTDOWN_OBSERVER_ID, PR_TRUE);
240 observerService->AddObserver(this, NS_NETWORK_LINK_TOPIC, PR_TRUE);
242 else
243 NS_WARNING("failed to get observer service");
245 gIOService = this;
247 // go into managed mode if we can
248 mNetworkLinkService = do_GetService(NS_NETWORK_LINK_SERVICE_CONTRACTID);
249 if (mNetworkLinkService) {
250 mManageOfflineStatus = PR_TRUE;
251 TrackNetworkLinkStatusForOffline();
254 return NS_OK;
258 nsIOService::~nsIOService()
260 gIOService = nsnull;
263 nsIOService*
264 nsIOService::GetInstance() {
265 if (!gIOService) {
266 gIOService = new nsIOService();
267 if (!gIOService)
268 return nsnull;
269 NS_ADDREF(gIOService);
271 nsresult rv = gIOService->Init();
272 if (NS_FAILED(rv)) {
273 NS_RELEASE(gIOService);
274 return nsnull;
276 return gIOService;
278 NS_ADDREF(gIOService);
279 return gIOService;
282 NS_IMPL_THREADSAFE_ISUPPORTS6(nsIOService,
283 nsIIOService,
284 nsIIOService2,
285 nsINetUtil,
286 nsIObserver,
287 nsISupportsWeakReference,
288 nsINetUtil_MOZILLA_1_9_1)
290 ////////////////////////////////////////////////////////////////////////////////
292 nsresult
293 nsIOService::OnChannelRedirect(nsIChannel* oldChan, nsIChannel* newChan,
294 PRUint32 flags)
296 nsCOMPtr<nsIChannelEventSink> sink =
297 do_GetService(NS_GLOBAL_CHANNELEVENTSINK_CONTRACTID);
298 if (sink) {
299 nsresult rv = sink->OnChannelRedirect(oldChan, newChan, flags);
300 if (NS_FAILED(rv))
301 return rv;
304 // Finally, our category
305 const nsCOMArray<nsIChannelEventSink>& entries =
306 mChannelEventSinks.GetEntries();
307 PRInt32 len = entries.Count();
308 for (PRInt32 i = 0; i < len; ++i) {
309 nsresult rv = entries[i]->OnChannelRedirect(oldChan, newChan, flags);
310 if (NS_FAILED(rv))
311 return rv;
314 return NS_OK;
317 nsresult
318 nsIOService::CacheProtocolHandler(const char *scheme, nsIProtocolHandler *handler)
320 for (unsigned int i=0; i<NS_N(gScheme); i++)
322 if (!nsCRT::strcasecmp(scheme, gScheme[i]))
324 nsresult rv;
325 NS_ASSERTION(!mWeakHandler[i], "Protocol handler already cached");
326 // Make sure the handler supports weak references.
327 nsCOMPtr<nsISupportsWeakReference> factoryPtr = do_QueryInterface(handler, &rv);
328 if (!factoryPtr)
330 // Don't cache handlers that don't support weak reference as
331 // there is real danger of a circular reference.
332 #ifdef DEBUG_dp
333 printf("DEBUG: %s protcol handler doesn't support weak ref. Not cached.\n", scheme);
334 #endif /* DEBUG_dp */
335 return NS_ERROR_FAILURE;
337 mWeakHandler[i] = do_GetWeakReference(handler);
338 return NS_OK;
341 return NS_ERROR_FAILURE;
344 nsresult
345 nsIOService::GetCachedProtocolHandler(const char *scheme, nsIProtocolHandler **result, PRUint32 start, PRUint32 end)
347 PRUint32 len = end - start - 1;
348 for (unsigned int i=0; i<NS_N(gScheme); i++)
350 if (!mWeakHandler[i])
351 continue;
353 // handle unterminated strings
354 // start is inclusive, end is exclusive, len = end - start - 1
355 if (end ? (!nsCRT::strncasecmp(scheme + start, gScheme[i], len)
356 && gScheme[i][len] == '\0')
357 : (!nsCRT::strcasecmp(scheme, gScheme[i])))
359 return CallQueryReferent(mWeakHandler[i].get(), result);
362 return NS_ERROR_FAILURE;
365 NS_IMETHODIMP
366 nsIOService::GetProtocolHandler(const char* scheme, nsIProtocolHandler* *result)
368 nsresult rv;
370 NS_ENSURE_ARG_POINTER(scheme);
371 // XXX we may want to speed this up by introducing our own protocol
372 // scheme -> protocol handler mapping, avoiding the string manipulation
373 // and service manager stuff
375 rv = GetCachedProtocolHandler(scheme, result);
376 if (NS_SUCCEEDED(rv))
377 return rv;
379 PRBool externalProtocol = PR_FALSE;
380 PRBool listedProtocol = PR_TRUE;
381 nsCOMPtr<nsIPrefBranch2> prefBranch;
382 GetPrefBranch(getter_AddRefs(prefBranch));
383 if (prefBranch) {
384 nsCAutoString externalProtocolPref("network.protocol-handler.external.");
385 externalProtocolPref += scheme;
386 rv = prefBranch->GetBoolPref(externalProtocolPref.get(), &externalProtocol);
387 if (NS_FAILED(rv)) {
388 externalProtocol = PR_FALSE;
389 listedProtocol = PR_FALSE;
393 if (!externalProtocol) {
394 nsCAutoString contractID(NS_NETWORK_PROTOCOL_CONTRACTID_PREFIX);
395 contractID += scheme;
396 ToLowerCase(contractID);
398 rv = CallGetService(contractID.get(), result);
399 if (NS_SUCCEEDED(rv)) {
400 CacheProtocolHandler(scheme, *result);
401 return rv;
404 #ifdef MOZ_X11
405 // check to see whether GnomeVFS can handle this URI scheme. if it can
406 // create a nsIURI for the "scheme:", then we assume it has support for
407 // the requested protocol. otherwise, we failover to using the default
408 // protocol handler.
410 // XXX should this be generalized into something that searches a
411 // category? (see bug 234714)
413 rv = CallGetService(NS_NETWORK_PROTOCOL_CONTRACTID_PREFIX"moz-gnomevfs",
414 result);
415 if (NS_SUCCEEDED(rv)) {
416 nsCAutoString spec(scheme);
417 spec.Append(':');
419 nsIURI *uri;
420 rv = (*result)->NewURI(spec, nsnull, nsnull, &uri);
421 if (NS_SUCCEEDED(rv)) {
422 NS_RELEASE(uri);
423 return rv;
426 NS_RELEASE(*result);
428 #endif
431 // Okay we don't have a protocol handler to handle this url type, so use
432 // the default protocol handler. This will cause urls to get dispatched
433 // out to the OS ('cause we can't do anything with them) when we try to
434 // read from a channel created by the default protocol handler.
436 rv = CallGetService(NS_NETWORK_PROTOCOL_CONTRACTID_PREFIX"default",
437 result);
438 if (NS_FAILED(rv))
439 return NS_ERROR_UNKNOWN_PROTOCOL;
441 return rv;
444 NS_IMETHODIMP
445 nsIOService::ExtractScheme(const nsACString &inURI, nsACString &scheme)
447 return net_ExtractURLScheme(inURI, nsnull, nsnull, &scheme);
450 NS_IMETHODIMP
451 nsIOService::GetProtocolFlags(const char* scheme, PRUint32 *flags)
453 nsCOMPtr<nsIProtocolHandler> handler;
454 nsresult rv = GetProtocolHandler(scheme, getter_AddRefs(handler));
455 if (NS_FAILED(rv)) return rv;
457 rv = handler->GetProtocolFlags(flags);
458 return rv;
461 class AutoIncrement
463 public:
464 AutoIncrement(PRUint32 *var) : mVar(var)
466 ++*var;
468 ~AutoIncrement()
470 --*mVar;
472 private:
473 PRUint32 *mVar;
476 nsresult
477 nsIOService::NewURI(const nsACString &aSpec, const char *aCharset, nsIURI *aBaseURI, nsIURI **result)
479 NS_ASSERTION(NS_IsMainThread(), "wrong thread");
481 static PRUint32 recursionCount = 0;
482 if (recursionCount >= MAX_RECURSION_COUNT)
483 return NS_ERROR_MALFORMED_URI;
484 AutoIncrement inc(&recursionCount);
486 nsCAutoString scheme;
487 nsresult rv = ExtractScheme(aSpec, scheme);
488 if (NS_FAILED(rv)) {
489 // then aSpec is relative
490 if (!aBaseURI)
491 return NS_ERROR_MALFORMED_URI;
493 rv = aBaseURI->GetScheme(scheme);
494 if (NS_FAILED(rv)) return rv;
497 // now get the handler for this scheme
498 nsCOMPtr<nsIProtocolHandler> handler;
499 rv = GetProtocolHandler(scheme.get(), getter_AddRefs(handler));
500 if (NS_FAILED(rv)) return rv;
502 return handler->NewURI(aSpec, aCharset, aBaseURI, result);
506 NS_IMETHODIMP
507 nsIOService::NewFileURI(nsIFile *file, nsIURI **result)
509 nsresult rv;
510 NS_ENSURE_ARG_POINTER(file);
512 nsCOMPtr<nsIProtocolHandler> handler;
514 rv = GetProtocolHandler("file", getter_AddRefs(handler));
515 if (NS_FAILED(rv)) return rv;
517 nsCOMPtr<nsIFileProtocolHandler> fileHandler( do_QueryInterface(handler, &rv) );
518 if (NS_FAILED(rv)) return rv;
520 return fileHandler->NewFileURI(file, result);
523 NS_IMETHODIMP
524 nsIOService::NewChannelFromURI(nsIURI *aURI, nsIChannel **result)
526 nsresult rv;
527 NS_ENSURE_ARG_POINTER(aURI);
528 NS_TIMELINE_MARK_URI("nsIOService::NewChannelFromURI(%s)", aURI);
530 nsCAutoString scheme;
531 rv = aURI->GetScheme(scheme);
532 if (NS_FAILED(rv))
533 return rv;
535 nsCOMPtr<nsIProtocolHandler> handler;
536 rv = GetProtocolHandler(scheme.get(), getter_AddRefs(handler));
537 if (NS_FAILED(rv))
538 return rv;
540 PRUint32 protoFlags;
541 rv = handler->GetProtocolFlags(&protoFlags);
542 if (NS_FAILED(rv))
543 return rv;
545 // Talk to the PPS if the protocol handler allows proxying. Otherwise,
546 // skip this step. This allows us to lazily load the PPS at startup.
547 if (protoFlags & nsIProtocolHandler::ALLOWS_PROXY) {
548 nsCOMPtr<nsIProxyInfo> pi;
549 if (!mProxyService) {
550 mProxyService = do_GetService(NS_PROTOCOLPROXYSERVICE_CONTRACTID);
551 if (!mProxyService)
552 NS_WARNING("failed to get protocol proxy service");
554 if (mProxyService) {
555 rv = mProxyService->Resolve(aURI, 0, getter_AddRefs(pi));
556 if (NS_FAILED(rv))
557 pi = nsnull;
559 if (pi) {
560 nsCAutoString type;
561 if (NS_SUCCEEDED(pi->GetType(type)) && type.EqualsLiteral("http")) {
562 // we are going to proxy this channel using an http proxy
563 rv = GetProtocolHandler("http", getter_AddRefs(handler));
564 if (NS_FAILED(rv))
565 return rv;
567 nsCOMPtr<nsIProxiedProtocolHandler> pph = do_QueryInterface(handler);
568 if (pph)
569 return pph->NewProxiedChannel(aURI, pi, result);
573 return handler->NewChannel(aURI, result);
576 NS_IMETHODIMP
577 nsIOService::NewChannel(const nsACString &aSpec, const char *aCharset, nsIURI *aBaseURI, nsIChannel **result)
579 nsresult rv;
580 nsCOMPtr<nsIURI> uri;
581 rv = NewURI(aSpec, aCharset, aBaseURI, getter_AddRefs(uri));
582 if (NS_FAILED(rv)) return rv;
584 return NewChannelFromURI(uri, result);
587 NS_IMETHODIMP
588 nsIOService::GetOffline(PRBool *offline)
590 *offline = mOffline;
591 return NS_OK;
594 NS_IMETHODIMP
595 nsIOService::SetOffline(PRBool offline)
597 nsCOMPtr<nsIObserverService> observerService =
598 do_GetService("@mozilla.org/observer-service;1");
600 nsresult rv;
601 if (offline && !mOffline) {
602 NS_NAMED_LITERAL_STRING(offlineString, NS_IOSERVICE_OFFLINE);
603 mOffline = PR_TRUE; // indicate we're trying to shutdown
605 // don't care if notification fails
606 // this allows users to attempt a little cleanup before dns and socket transport are shut down.
607 if (observerService)
608 observerService->NotifyObservers(static_cast<nsIIOService *>(this),
609 NS_IOSERVICE_GOING_OFFLINE_TOPIC,
610 offlineString.get());
612 // be sure to try and shutdown both (even if the first fails)...
613 // shutdown dns service first, because it has callbacks for socket transport
614 if (mDNSService) {
615 rv = mDNSService->Shutdown();
616 NS_ASSERTION(NS_SUCCEEDED(rv), "DNS service shutdown failed");
618 if (mSocketTransportService) {
619 rv = mSocketTransportService->Shutdown();
620 NS_ASSERTION(NS_SUCCEEDED(rv), "socket transport service shutdown failed");
623 // don't care if notification fails
624 if (observerService)
625 observerService->NotifyObservers(static_cast<nsIIOService *>(this),
626 NS_IOSERVICE_OFFLINE_STATUS_TOPIC,
627 offlineString.get());
629 else if (!offline && mOffline) {
630 // go online
631 if (mDNSService) {
632 rv = mDNSService->Init();
633 NS_ASSERTION(NS_SUCCEEDED(rv), "DNS service init failed");
635 if (mSocketTransportService) {
636 rv = mSocketTransportService->Init();
637 NS_ASSERTION(NS_SUCCEEDED(rv), "socket transport service init failed");
639 mOffline = PR_FALSE; // indicate success only AFTER we've
640 // brought up the services
642 // trigger a PAC reload when we come back online
643 if (mProxyService)
644 mProxyService->ReloadPAC();
646 // don't care if notification fails
647 if (observerService)
648 observerService->NotifyObservers(static_cast<nsIIOService *>(this),
649 NS_IOSERVICE_OFFLINE_STATUS_TOPIC,
650 NS_LITERAL_STRING(NS_IOSERVICE_ONLINE).get());
652 return NS_OK;
656 NS_IMETHODIMP
657 nsIOService::AllowPort(PRInt32 inPort, const char *scheme, PRBool *_retval)
659 PRInt16 port = inPort;
660 if (port == -1) {
661 *_retval = PR_TRUE;
662 return NS_OK;
665 // first check to see if the port is in our blacklist:
666 PRInt32 badPortListCnt = mRestrictedPortList.Count();
667 for (int i=0; i<badPortListCnt; i++)
669 if (port == (PRInt32) NS_PTR_TO_INT32(mRestrictedPortList[i]))
671 *_retval = PR_FALSE;
673 // check to see if the protocol wants to override
674 if (!scheme)
675 return NS_OK;
677 nsCOMPtr<nsIProtocolHandler> handler;
678 nsresult rv = GetProtocolHandler(scheme, getter_AddRefs(handler));
679 if (NS_FAILED(rv)) return rv;
681 // let the protocol handler decide
682 return handler->AllowPort(port, scheme, _retval);
686 *_retval = PR_TRUE;
687 return NS_OK;
690 ////////////////////////////////////////////////////////////////////////////////
692 void
693 nsIOService::PrefsChanged(nsIPrefBranch *prefs, const char *pref)
695 if (!prefs) return;
697 // Look for extra ports to block
698 if (!pref || strcmp(pref, PORT_PREF("banned")) == 0)
699 ParsePortList(prefs, PORT_PREF("banned"), PR_FALSE);
701 // ...as well as previous blocks to remove.
702 if (!pref || strcmp(pref, PORT_PREF("banned.override")) == 0)
703 ParsePortList(prefs, PORT_PREF("banned.override"), PR_TRUE);
705 if (!pref || strcmp(pref, AUTODIAL_PREF) == 0) {
706 PRBool enableAutodial = PR_FALSE;
707 nsresult rv = prefs->GetBoolPref(AUTODIAL_PREF, &enableAutodial);
708 // If pref not found, default to disabled.
709 if (NS_SUCCEEDED(rv)) {
710 if (mSocketTransportService)
711 mSocketTransportService->SetAutodialEnabled(enableAutodial);
716 void
717 nsIOService::ParsePortList(nsIPrefBranch *prefBranch, const char *pref, PRBool remove)
719 nsXPIDLCString portList;
721 // Get a pref string and chop it up into a list of ports.
722 prefBranch->GetCharPref(pref, getter_Copies(portList));
723 if (portList) {
724 nsCStringArray portListArray;
725 portListArray.ParseString(portList.get(), ",");
726 PRInt32 index;
727 for (index=0; index < portListArray.Count(); index++) {
728 portListArray[index]->StripWhitespace();
729 PRInt32 aErrorCode, portBegin, portEnd;
731 if (PR_sscanf(portListArray[index]->get(), "%d-%d", &portBegin, &portEnd) == 2) {
732 if ((portBegin < 65536) && (portEnd < 65536)) {
733 PRInt32 curPort;
734 if (remove) {
735 for (curPort=portBegin; curPort <= portEnd; curPort++)
736 mRestrictedPortList.RemoveElement((void*)curPort);
737 } else {
738 for (curPort=portBegin; curPort <= portEnd; curPort++)
739 mRestrictedPortList.AppendElement((void*)curPort);
742 } else {
743 PRInt32 port = portListArray[index]->ToInteger(&aErrorCode);
744 if (NS_SUCCEEDED(aErrorCode) && port < 65536) {
745 if (remove)
746 mRestrictedPortList.RemoveElement((void*)port);
747 else
748 mRestrictedPortList.AppendElement((void*)port);
756 void
757 nsIOService::GetPrefBranch(nsIPrefBranch2 **result)
759 *result = nsnull;
760 CallGetService(NS_PREFSERVICE_CONTRACTID, result);
763 // nsIObserver interface
764 NS_IMETHODIMP
765 nsIOService::Observe(nsISupports *subject,
766 const char *topic,
767 const PRUnichar *data)
769 if (!strcmp(topic, NS_PREFBRANCH_PREFCHANGE_TOPIC_ID)) {
770 nsCOMPtr<nsIPrefBranch> prefBranch = do_QueryInterface(subject);
771 if (prefBranch)
772 PrefsChanged(prefBranch, NS_ConvertUTF16toUTF8(data).get());
774 else if (!strcmp(topic, kProfileChangeNetTeardownTopic)) {
775 if (!mOffline) {
776 SetOffline(PR_TRUE);
777 mOfflineForProfileChange = PR_TRUE;
780 else if (!strcmp(topic, kProfileChangeNetRestoreTopic)) {
781 if (mOfflineForProfileChange) {
782 mOfflineForProfileChange = PR_FALSE;
783 if (!mManageOfflineStatus ||
784 NS_FAILED(TrackNetworkLinkStatusForOffline())) {
785 SetOffline(PR_FALSE);
789 else if (!strcmp(topic, NS_XPCOM_SHUTDOWN_OBSERVER_ID)) {
790 SetOffline(PR_TRUE);
792 // Break circular reference.
793 mProxyService = nsnull;
795 else if (!strcmp(topic, NS_NETWORK_LINK_TOPIC)) {
796 if (!mOfflineForProfileChange && mManageOfflineStatus) {
797 TrackNetworkLinkStatusForOffline();
801 return NS_OK;
804 // nsINetUtil interface
805 NS_IMETHODIMP
806 nsIOService::ParseContentType(const nsACString &aTypeHeader,
807 nsACString &aCharset,
808 PRBool *aHadCharset,
809 nsACString &aContentType)
811 net_ParseContentType(aTypeHeader, aContentType, aCharset, aHadCharset);
812 return NS_OK;
815 NS_IMETHODIMP
816 nsIOService::ProtocolHasFlags(nsIURI *uri,
817 PRUint32 flags,
818 PRBool *result)
820 NS_ENSURE_ARG(uri);
822 *result = PR_FALSE;
823 nsCAutoString scheme;
824 nsresult rv = uri->GetScheme(scheme);
825 NS_ENSURE_SUCCESS(rv, rv);
827 PRUint32 protocolFlags;
828 rv = GetProtocolFlags(scheme.get(), &protocolFlags);
830 if (NS_SUCCEEDED(rv)) {
831 *result = (protocolFlags & flags) == flags;
834 return rv;
837 NS_IMETHODIMP
838 nsIOService::URIChainHasFlags(nsIURI *uri,
839 PRUint32 flags,
840 PRBool *result)
842 nsresult rv = ProtocolHasFlags(uri, flags, result);
843 NS_ENSURE_SUCCESS(rv, rv);
845 if (*result) {
846 return rv;
849 // Dig deeper into the chain. Note that this is not a do/while loop to
850 // avoid the extra addref/release on |uri| in the common (non-nested) case.
851 nsCOMPtr<nsINestedURI> nestedURI = do_QueryInterface(uri);
852 while (nestedURI) {
853 nsCOMPtr<nsIURI> innerURI;
854 rv = nestedURI->GetInnerURI(getter_AddRefs(innerURI));
855 NS_ENSURE_SUCCESS(rv, rv);
857 rv = ProtocolHasFlags(innerURI, flags, result);
859 if (*result) {
860 return rv;
863 nestedURI = do_QueryInterface(innerURI);
866 return rv;
869 NS_IMETHODIMP
870 nsIOService::ToImmutableURI(nsIURI* uri, nsIURI** result)
872 if (!uri) {
873 *result = nsnull;
874 return NS_OK;
877 nsresult rv = NS_EnsureSafeToReturn(uri, result);
878 NS_ENSURE_SUCCESS(rv, rv);
880 NS_TryToSetImmutable(*result);
881 return NS_OK;
884 NS_IMETHODIMP
885 nsIOService::SetManageOfflineStatus(PRBool aManage) {
886 PRBool wasManaged = mManageOfflineStatus;
887 mManageOfflineStatus = aManage;
888 if (mManageOfflineStatus && !wasManaged)
889 return TrackNetworkLinkStatusForOffline();
890 return NS_OK;
893 NS_IMETHODIMP
894 nsIOService::GetManageOfflineStatus(PRBool* aManage) {
895 *aManage = mManageOfflineStatus;
896 return NS_OK;
899 nsresult
900 nsIOService::TrackNetworkLinkStatusForOffline()
902 NS_ASSERTION(mManageOfflineStatus,
903 "Don't call this unless we're managing the offline status");
904 if (!mNetworkLinkService)
905 return NS_ERROR_FAILURE;
907 // check to make sure this won't collide with Autodial
908 if (mSocketTransportService) {
909 PRBool autodialEnabled = PR_FALSE;
910 mSocketTransportService->GetAutodialEnabled(&autodialEnabled);
911 // If autodialing-on-link-down is enabled, check if the OS auto dial
912 // option is set to always autodial. If so, then we are
913 // always up for the purposes of offline management.
914 if (autodialEnabled) {
915 #if defined(XP_WIN) && !defined(WINCE)
916 // On Windows, need to do some registry checking to see if
917 // autodial is enabled at the OS level. Only if that is
918 // enabled are we always up for the purposes of offline
919 // management.
920 if(nsNativeConnectionHelper::IsAutodialEnabled())
921 return SetOffline(PR_FALSE);
922 #else
923 return SetOffline(PR_FALSE);
924 #endif
928 PRBool isUp;
929 nsresult rv = mNetworkLinkService->GetIsLinkUp(&isUp);
930 NS_ENSURE_SUCCESS(rv, rv);
931 return SetOffline(!isUp);
934 NS_IMETHODIMP
935 nsIOService::EscapeString(const nsACString& aString,
936 PRUint32 aEscapeType,
937 nsACString& aResult)
939 NS_ENSURE_ARG_RANGE(aEscapeType, 0, 4);
941 nsCAutoString stringCopy(aString);
942 nsCString result;
944 if (!NS_Escape(stringCopy, result, (nsEscapeMask) aEscapeType))
945 return NS_ERROR_OUT_OF_MEMORY;
947 aResult.Assign(result);
949 return NS_OK;
952 NS_IMETHODIMP
953 nsIOService::EscapeURL(const nsACString &aStr,
954 PRUint32 aFlags, nsACString &aResult)
956 aResult.Truncate();
957 NS_EscapeURL(aStr.BeginReading(), aStr.Length(),
958 aFlags | esc_AlwaysCopy, aResult);
959 return NS_OK;
962 NS_IMETHODIMP
963 nsIOService::UnescapeString(const nsACString &aStr,
964 PRUint32 aFlags, nsACString &aResult)
966 aResult.Truncate();
967 NS_UnescapeURL(aStr.BeginReading(), aStr.Length(),
968 aFlags | esc_AlwaysCopy, aResult);
969 return NS_OK;
972 NS_IMETHODIMP
973 nsIOService::ExtractCharsetFromContentType(const nsACString &aTypeHeader,
974 nsACString &aCharset,
975 PRInt32 *aCharsetStart,
976 PRInt32 *aCharsetEnd,
977 PRBool *aHadCharset)
979 nsCAutoString ignored;
980 net_ParseContentType(aTypeHeader, ignored, aCharset, aHadCharset,
981 aCharsetStart, aCharsetEnd);
982 if (*aHadCharset && *aCharsetStart == *aCharsetEnd) {
983 *aHadCharset = PR_FALSE;
985 return NS_OK;
988 NS_IMETHODIMP
989 nsIOService::OfflineAppAllowed(nsIURI *aURI,
990 nsIPrefBranch *aPrefBranch,
991 PRBool *aAllowed)
993 *aAllowed = PR_FALSE;
995 nsCOMPtr<nsIURI> innerURI = NS_GetInnermostURI(aURI);
996 if (!innerURI)
997 return NS_OK;
999 // only http and https applications can use offline APIs.
1000 PRBool match;
1001 nsresult rv = innerURI->SchemeIs("http", &match);
1002 NS_ENSURE_SUCCESS(rv, rv);
1004 if (!match) {
1005 rv = innerURI->SchemeIs("https", &match);
1006 NS_ENSURE_SUCCESS(rv, rv);
1007 if (!match) {
1008 return NS_OK;
1012 nsCOMPtr<nsIPermissionManager> permissionManager =
1013 do_GetService(NS_PERMISSIONMANAGER_CONTRACTID);
1014 if (!permissionManager) {
1015 return NS_OK;
1018 PRUint32 perm;
1019 permissionManager->TestExactPermission(innerURI, "offline-app", &perm);
1021 if (perm == nsIPermissionManager::UNKNOWN_ACTION) {
1022 nsCOMPtr<nsIPrefBranch> branch = aPrefBranch;
1023 if (!branch) {
1024 branch = do_GetService(NS_PREFSERVICE_CONTRACTID);
1026 if (branch) {
1027 rv = branch->GetBoolPref("offline-apps.allow_by_default", aAllowed);
1028 NS_ENSURE_SUCCESS(rv, rv);
1031 return NS_OK;
1034 if (perm == nsIPermissionManager::DENY_ACTION) {
1035 return NS_OK;
1038 *aAllowed = PR_TRUE;
1040 return NS_OK;