Bug 458861. Validate TrueType headers before activating downloaded font. r=roc, sr...
[wine-gecko.git] / netwerk / base / src / nsIOService.cpp
blob3838ca673a452ce8af926d97f1731ce27a6be7df
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_ISUPPORTS5(nsIOService,
283 nsIIOService,
284 nsIIOService2,
285 nsINetUtil,
286 nsIObserver,
287 nsISupportsWeakReference)
289 ////////////////////////////////////////////////////////////////////////////////
291 nsresult
292 nsIOService::OnChannelRedirect(nsIChannel* oldChan, nsIChannel* newChan,
293 PRUint32 flags)
295 nsCOMPtr<nsIChannelEventSink> sink =
296 do_GetService(NS_GLOBAL_CHANNELEVENTSINK_CONTRACTID);
297 if (sink) {
298 nsresult rv = sink->OnChannelRedirect(oldChan, newChan, flags);
299 if (NS_FAILED(rv))
300 return rv;
303 // Finally, our category
304 const nsCOMArray<nsIChannelEventSink>& entries =
305 mChannelEventSinks.GetEntries();
306 PRInt32 len = entries.Count();
307 for (PRInt32 i = 0; i < len; ++i) {
308 nsresult rv = entries[i]->OnChannelRedirect(oldChan, newChan, flags);
309 if (NS_FAILED(rv))
310 return rv;
313 return NS_OK;
316 nsresult
317 nsIOService::CacheProtocolHandler(const char *scheme, nsIProtocolHandler *handler)
319 for (unsigned int i=0; i<NS_N(gScheme); i++)
321 if (!nsCRT::strcasecmp(scheme, gScheme[i]))
323 nsresult rv;
324 NS_ASSERTION(!mWeakHandler[i], "Protocol handler already cached");
325 // Make sure the handler supports weak references.
326 nsCOMPtr<nsISupportsWeakReference> factoryPtr = do_QueryInterface(handler, &rv);
327 if (!factoryPtr)
329 // Don't cache handlers that don't support weak reference as
330 // there is real danger of a circular reference.
331 #ifdef DEBUG_dp
332 printf("DEBUG: %s protcol handler doesn't support weak ref. Not cached.\n", scheme);
333 #endif /* DEBUG_dp */
334 return NS_ERROR_FAILURE;
336 mWeakHandler[i] = do_GetWeakReference(handler);
337 return NS_OK;
340 return NS_ERROR_FAILURE;
343 nsresult
344 nsIOService::GetCachedProtocolHandler(const char *scheme, nsIProtocolHandler **result, PRUint32 start, PRUint32 end)
346 PRUint32 len = end - start - 1;
347 for (unsigned int i=0; i<NS_N(gScheme); i++)
349 if (!mWeakHandler[i])
350 continue;
352 // handle unterminated strings
353 // start is inclusive, end is exclusive, len = end - start - 1
354 if (end ? (!nsCRT::strncasecmp(scheme + start, gScheme[i], len)
355 && gScheme[i][len] == '\0')
356 : (!nsCRT::strcasecmp(scheme, gScheme[i])))
358 return CallQueryReferent(mWeakHandler[i].get(), result);
361 return NS_ERROR_FAILURE;
364 NS_IMETHODIMP
365 nsIOService::GetProtocolHandler(const char* scheme, nsIProtocolHandler* *result)
367 nsresult rv;
369 NS_ENSURE_ARG_POINTER(scheme);
370 // XXX we may want to speed this up by introducing our own protocol
371 // scheme -> protocol handler mapping, avoiding the string manipulation
372 // and service manager stuff
374 rv = GetCachedProtocolHandler(scheme, result);
375 if (NS_SUCCEEDED(rv))
376 return rv;
378 PRBool externalProtocol = PR_FALSE;
379 PRBool listedProtocol = PR_TRUE;
380 nsCOMPtr<nsIPrefBranch2> prefBranch;
381 GetPrefBranch(getter_AddRefs(prefBranch));
382 if (prefBranch) {
383 nsCAutoString externalProtocolPref("network.protocol-handler.external.");
384 externalProtocolPref += scheme;
385 rv = prefBranch->GetBoolPref(externalProtocolPref.get(), &externalProtocol);
386 if (NS_FAILED(rv)) {
387 externalProtocol = PR_FALSE;
388 listedProtocol = PR_FALSE;
392 if (!externalProtocol) {
393 nsCAutoString contractID(NS_NETWORK_PROTOCOL_CONTRACTID_PREFIX);
394 contractID += scheme;
395 ToLowerCase(contractID);
397 rv = CallGetService(contractID.get(), result);
398 if (NS_SUCCEEDED(rv)) {
399 CacheProtocolHandler(scheme, *result);
400 return rv;
403 #ifdef MOZ_X11
404 // check to see whether GnomeVFS can handle this URI scheme. if it can
405 // create a nsIURI for the "scheme:", then we assume it has support for
406 // the requested protocol. otherwise, we failover to using the default
407 // protocol handler.
409 // XXX should this be generalized into something that searches a
410 // category? (see bug 234714)
412 rv = CallGetService(NS_NETWORK_PROTOCOL_CONTRACTID_PREFIX"moz-gnomevfs",
413 result);
414 if (NS_SUCCEEDED(rv)) {
415 nsCAutoString spec(scheme);
416 spec.Append(':');
418 nsIURI *uri;
419 rv = (*result)->NewURI(spec, nsnull, nsnull, &uri);
420 if (NS_SUCCEEDED(rv)) {
421 NS_RELEASE(uri);
422 return rv;
425 NS_RELEASE(*result);
427 #endif
430 // Okay we don't have a protocol handler to handle this url type, so use
431 // the default protocol handler. This will cause urls to get dispatched
432 // out to the OS ('cause we can't do anything with them) when we try to
433 // read from a channel created by the default protocol handler.
435 rv = CallGetService(NS_NETWORK_PROTOCOL_CONTRACTID_PREFIX"default",
436 result);
437 if (NS_FAILED(rv))
438 return NS_ERROR_UNKNOWN_PROTOCOL;
440 return rv;
443 NS_IMETHODIMP
444 nsIOService::ExtractScheme(const nsACString &inURI, nsACString &scheme)
446 return net_ExtractURLScheme(inURI, nsnull, nsnull, &scheme);
449 NS_IMETHODIMP
450 nsIOService::GetProtocolFlags(const char* scheme, PRUint32 *flags)
452 nsCOMPtr<nsIProtocolHandler> handler;
453 nsresult rv = GetProtocolHandler(scheme, getter_AddRefs(handler));
454 if (NS_FAILED(rv)) return rv;
456 rv = handler->GetProtocolFlags(flags);
457 return rv;
460 class AutoIncrement
462 public:
463 AutoIncrement(PRUint32 *var) : mVar(var)
465 ++*var;
467 ~AutoIncrement()
469 --*mVar;
471 private:
472 PRUint32 *mVar;
475 nsresult
476 nsIOService::NewURI(const nsACString &aSpec, const char *aCharset, nsIURI *aBaseURI, nsIURI **result)
478 NS_ASSERTION(NS_IsMainThread(), "wrong thread");
480 static PRUint32 recursionCount = 0;
481 if (recursionCount >= MAX_RECURSION_COUNT)
482 return NS_ERROR_MALFORMED_URI;
483 AutoIncrement inc(&recursionCount);
485 nsCAutoString scheme;
486 nsresult rv = ExtractScheme(aSpec, scheme);
487 if (NS_FAILED(rv)) {
488 // then aSpec is relative
489 if (!aBaseURI)
490 return NS_ERROR_MALFORMED_URI;
492 rv = aBaseURI->GetScheme(scheme);
493 if (NS_FAILED(rv)) return rv;
496 // now get the handler for this scheme
497 nsCOMPtr<nsIProtocolHandler> handler;
498 rv = GetProtocolHandler(scheme.get(), getter_AddRefs(handler));
499 if (NS_FAILED(rv)) return rv;
501 return handler->NewURI(aSpec, aCharset, aBaseURI, result);
505 NS_IMETHODIMP
506 nsIOService::NewFileURI(nsIFile *file, nsIURI **result)
508 nsresult rv;
509 NS_ENSURE_ARG_POINTER(file);
511 nsCOMPtr<nsIProtocolHandler> handler;
513 rv = GetProtocolHandler("file", getter_AddRefs(handler));
514 if (NS_FAILED(rv)) return rv;
516 nsCOMPtr<nsIFileProtocolHandler> fileHandler( do_QueryInterface(handler, &rv) );
517 if (NS_FAILED(rv)) return rv;
519 return fileHandler->NewFileURI(file, result);
522 NS_IMETHODIMP
523 nsIOService::NewChannelFromURI(nsIURI *aURI, nsIChannel **result)
525 nsresult rv;
526 NS_ENSURE_ARG_POINTER(aURI);
527 NS_TIMELINE_MARK_URI("nsIOService::NewChannelFromURI(%s)", aURI);
529 nsCAutoString scheme;
530 rv = aURI->GetScheme(scheme);
531 if (NS_FAILED(rv))
532 return rv;
534 nsCOMPtr<nsIProtocolHandler> handler;
535 rv = GetProtocolHandler(scheme.get(), getter_AddRefs(handler));
536 if (NS_FAILED(rv))
537 return rv;
539 PRUint32 protoFlags;
540 rv = handler->GetProtocolFlags(&protoFlags);
541 if (NS_FAILED(rv))
542 return rv;
544 // Talk to the PPS if the protocol handler allows proxying. Otherwise,
545 // skip this step. This allows us to lazily load the PPS at startup.
546 if (protoFlags & nsIProtocolHandler::ALLOWS_PROXY) {
547 nsCOMPtr<nsIProxyInfo> pi;
548 if (!mProxyService) {
549 mProxyService = do_GetService(NS_PROTOCOLPROXYSERVICE_CONTRACTID);
550 if (!mProxyService)
551 NS_WARNING("failed to get protocol proxy service");
553 if (mProxyService) {
554 rv = mProxyService->Resolve(aURI, 0, getter_AddRefs(pi));
555 if (NS_FAILED(rv))
556 pi = nsnull;
558 if (pi) {
559 nsCAutoString type;
560 if (NS_SUCCEEDED(pi->GetType(type)) && type.EqualsLiteral("http")) {
561 // we are going to proxy this channel using an http proxy
562 rv = GetProtocolHandler("http", getter_AddRefs(handler));
563 if (NS_FAILED(rv))
564 return rv;
566 nsCOMPtr<nsIProxiedProtocolHandler> pph = do_QueryInterface(handler);
567 if (pph)
568 return pph->NewProxiedChannel(aURI, pi, result);
572 return handler->NewChannel(aURI, result);
575 NS_IMETHODIMP
576 nsIOService::NewChannel(const nsACString &aSpec, const char *aCharset, nsIURI *aBaseURI, nsIChannel **result)
578 nsresult rv;
579 nsCOMPtr<nsIURI> uri;
580 rv = NewURI(aSpec, aCharset, aBaseURI, getter_AddRefs(uri));
581 if (NS_FAILED(rv)) return rv;
583 return NewChannelFromURI(uri, result);
586 NS_IMETHODIMP
587 nsIOService::GetOffline(PRBool *offline)
589 *offline = mOffline;
590 return NS_OK;
593 NS_IMETHODIMP
594 nsIOService::SetOffline(PRBool offline)
596 nsCOMPtr<nsIObserverService> observerService =
597 do_GetService("@mozilla.org/observer-service;1");
599 nsresult rv;
600 if (offline && !mOffline) {
601 NS_NAMED_LITERAL_STRING(offlineString, NS_IOSERVICE_OFFLINE);
602 mOffline = PR_TRUE; // indicate we're trying to shutdown
604 // don't care if notification fails
605 // this allows users to attempt a little cleanup before dns and socket transport are shut down.
606 if (observerService)
607 observerService->NotifyObservers(static_cast<nsIIOService *>(this),
608 NS_IOSERVICE_GOING_OFFLINE_TOPIC,
609 offlineString.get());
611 // be sure to try and shutdown both (even if the first fails)...
612 // shutdown dns service first, because it has callbacks for socket transport
613 if (mDNSService) {
614 rv = mDNSService->Shutdown();
615 NS_ASSERTION(NS_SUCCEEDED(rv), "DNS service shutdown failed");
617 if (mSocketTransportService) {
618 rv = mSocketTransportService->Shutdown();
619 NS_ASSERTION(NS_SUCCEEDED(rv), "socket transport service shutdown failed");
622 // don't care if notification fails
623 if (observerService)
624 observerService->NotifyObservers(static_cast<nsIIOService *>(this),
625 NS_IOSERVICE_OFFLINE_STATUS_TOPIC,
626 offlineString.get());
628 else if (!offline && mOffline) {
629 // go online
630 if (mDNSService) {
631 rv = mDNSService->Init();
632 NS_ASSERTION(NS_SUCCEEDED(rv), "DNS service init failed");
634 if (mSocketTransportService) {
635 rv = mSocketTransportService->Init();
636 NS_ASSERTION(NS_SUCCEEDED(rv), "socket transport service init failed");
638 mOffline = PR_FALSE; // indicate success only AFTER we've
639 // brought up the services
641 // trigger a PAC reload when we come back online
642 if (mProxyService)
643 mProxyService->ReloadPAC();
645 // don't care if notification fails
646 if (observerService)
647 observerService->NotifyObservers(static_cast<nsIIOService *>(this),
648 NS_IOSERVICE_OFFLINE_STATUS_TOPIC,
649 NS_LITERAL_STRING(NS_IOSERVICE_ONLINE).get());
651 return NS_OK;
655 NS_IMETHODIMP
656 nsIOService::AllowPort(PRInt32 inPort, const char *scheme, PRBool *_retval)
658 PRInt16 port = inPort;
659 if (port == -1) {
660 *_retval = PR_TRUE;
661 return NS_OK;
664 // first check to see if the port is in our blacklist:
665 PRInt32 badPortListCnt = mRestrictedPortList.Count();
666 for (int i=0; i<badPortListCnt; i++)
668 if (port == (PRInt32) NS_PTR_TO_INT32(mRestrictedPortList[i]))
670 *_retval = PR_FALSE;
672 // check to see if the protocol wants to override
673 if (!scheme)
674 return NS_OK;
676 nsCOMPtr<nsIProtocolHandler> handler;
677 nsresult rv = GetProtocolHandler(scheme, getter_AddRefs(handler));
678 if (NS_FAILED(rv)) return rv;
680 // let the protocol handler decide
681 return handler->AllowPort(port, scheme, _retval);
685 *_retval = PR_TRUE;
686 return NS_OK;
689 ////////////////////////////////////////////////////////////////////////////////
691 void
692 nsIOService::PrefsChanged(nsIPrefBranch *prefs, const char *pref)
694 if (!prefs) return;
696 // Look for extra ports to block
697 if (!pref || strcmp(pref, PORT_PREF("banned")) == 0)
698 ParsePortList(prefs, PORT_PREF("banned"), PR_FALSE);
700 // ...as well as previous blocks to remove.
701 if (!pref || strcmp(pref, PORT_PREF("banned.override")) == 0)
702 ParsePortList(prefs, PORT_PREF("banned.override"), PR_TRUE);
704 if (!pref || strcmp(pref, AUTODIAL_PREF) == 0) {
705 PRBool enableAutodial = PR_FALSE;
706 nsresult rv = prefs->GetBoolPref(AUTODIAL_PREF, &enableAutodial);
707 // If pref not found, default to disabled.
708 if (NS_SUCCEEDED(rv)) {
709 if (mSocketTransportService)
710 mSocketTransportService->SetAutodialEnabled(enableAutodial);
715 void
716 nsIOService::ParsePortList(nsIPrefBranch *prefBranch, const char *pref, PRBool remove)
718 nsXPIDLCString portList;
720 // Get a pref string and chop it up into a list of ports.
721 prefBranch->GetCharPref(pref, getter_Copies(portList));
722 if (portList) {
723 nsCStringArray portListArray;
724 portListArray.ParseString(portList.get(), ",");
725 PRInt32 index;
726 for (index=0; index < portListArray.Count(); index++) {
727 portListArray[index]->StripWhitespace();
728 PRInt32 aErrorCode, portBegin, portEnd;
730 if (PR_sscanf(portListArray[index]->get(), "%d-%d", &portBegin, &portEnd) == 2) {
731 if ((portBegin < 65536) && (portEnd < 65536)) {
732 PRInt32 curPort;
733 if (remove) {
734 for (curPort=portBegin; curPort <= portEnd; curPort++)
735 mRestrictedPortList.RemoveElement((void*)curPort);
736 } else {
737 for (curPort=portBegin; curPort <= portEnd; curPort++)
738 mRestrictedPortList.AppendElement((void*)curPort);
741 } else {
742 PRInt32 port = portListArray[index]->ToInteger(&aErrorCode);
743 if (NS_SUCCEEDED(aErrorCode) && port < 65536) {
744 if (remove)
745 mRestrictedPortList.RemoveElement((void*)port);
746 else
747 mRestrictedPortList.AppendElement((void*)port);
755 void
756 nsIOService::GetPrefBranch(nsIPrefBranch2 **result)
758 *result = nsnull;
759 CallGetService(NS_PREFSERVICE_CONTRACTID, result);
762 // nsIObserver interface
763 NS_IMETHODIMP
764 nsIOService::Observe(nsISupports *subject,
765 const char *topic,
766 const PRUnichar *data)
768 if (!strcmp(topic, NS_PREFBRANCH_PREFCHANGE_TOPIC_ID)) {
769 nsCOMPtr<nsIPrefBranch> prefBranch = do_QueryInterface(subject);
770 if (prefBranch)
771 PrefsChanged(prefBranch, NS_ConvertUTF16toUTF8(data).get());
773 else if (!strcmp(topic, kProfileChangeNetTeardownTopic)) {
774 if (!mOffline) {
775 SetOffline(PR_TRUE);
776 mOfflineForProfileChange = PR_TRUE;
779 else if (!strcmp(topic, kProfileChangeNetRestoreTopic)) {
780 if (mOfflineForProfileChange) {
781 mOfflineForProfileChange = PR_FALSE;
782 if (!mManageOfflineStatus ||
783 NS_FAILED(TrackNetworkLinkStatusForOffline())) {
784 SetOffline(PR_FALSE);
788 else if (!strcmp(topic, NS_XPCOM_SHUTDOWN_OBSERVER_ID)) {
789 SetOffline(PR_TRUE);
791 // Break circular reference.
792 mProxyService = nsnull;
794 else if (!strcmp(topic, NS_NETWORK_LINK_TOPIC)) {
795 if (!mOfflineForProfileChange && mManageOfflineStatus) {
796 TrackNetworkLinkStatusForOffline();
800 return NS_OK;
803 // nsINetUtil interface
804 NS_IMETHODIMP
805 nsIOService::ParseContentType(const nsACString &aTypeHeader,
806 nsACString &aCharset,
807 PRBool *aHadCharset,
808 nsACString &aContentType)
810 net_ParseContentType(aTypeHeader, aContentType, aCharset, aHadCharset);
811 return NS_OK;
814 NS_IMETHODIMP
815 nsIOService::ProtocolHasFlags(nsIURI *uri,
816 PRUint32 flags,
817 PRBool *result)
819 NS_ENSURE_ARG(uri);
821 *result = PR_FALSE;
822 nsCAutoString scheme;
823 nsresult rv = uri->GetScheme(scheme);
824 NS_ENSURE_SUCCESS(rv, rv);
826 PRUint32 protocolFlags;
827 rv = GetProtocolFlags(scheme.get(), &protocolFlags);
829 if (NS_SUCCEEDED(rv)) {
830 *result = (protocolFlags & flags) == flags;
833 return rv;
836 NS_IMETHODIMP
837 nsIOService::URIChainHasFlags(nsIURI *uri,
838 PRUint32 flags,
839 PRBool *result)
841 nsresult rv = ProtocolHasFlags(uri, flags, result);
842 NS_ENSURE_SUCCESS(rv, rv);
844 if (*result) {
845 return rv;
848 // Dig deeper into the chain. Note that this is not a do/while loop to
849 // avoid the extra addref/release on |uri| in the common (non-nested) case.
850 nsCOMPtr<nsINestedURI> nestedURI = do_QueryInterface(uri);
851 while (nestedURI) {
852 nsCOMPtr<nsIURI> innerURI;
853 rv = nestedURI->GetInnerURI(getter_AddRefs(innerURI));
854 NS_ENSURE_SUCCESS(rv, rv);
856 rv = ProtocolHasFlags(innerURI, flags, result);
858 if (*result) {
859 return rv;
862 nestedURI = do_QueryInterface(innerURI);
865 return rv;
868 NS_IMETHODIMP
869 nsIOService::ToImmutableURI(nsIURI* uri, nsIURI** result)
871 if (!uri) {
872 *result = nsnull;
873 return NS_OK;
876 nsresult rv = NS_EnsureSafeToReturn(uri, result);
877 NS_ENSURE_SUCCESS(rv, rv);
879 NS_TryToSetImmutable(*result);
880 return NS_OK;
883 NS_IMETHODIMP
884 nsIOService::SetManageOfflineStatus(PRBool aManage) {
885 PRBool wasManaged = mManageOfflineStatus;
886 mManageOfflineStatus = aManage;
887 if (mManageOfflineStatus && !wasManaged)
888 return TrackNetworkLinkStatusForOffline();
889 return NS_OK;
892 NS_IMETHODIMP
893 nsIOService::GetManageOfflineStatus(PRBool* aManage) {
894 *aManage = mManageOfflineStatus;
895 return NS_OK;
898 nsresult
899 nsIOService::TrackNetworkLinkStatusForOffline()
901 NS_ASSERTION(mManageOfflineStatus,
902 "Don't call this unless we're managing the offline status");
903 if (!mNetworkLinkService)
904 return NS_ERROR_FAILURE;
906 // check to make sure this won't collide with Autodial
907 if (mSocketTransportService) {
908 PRBool autodialEnabled = PR_FALSE;
909 mSocketTransportService->GetAutodialEnabled(&autodialEnabled);
910 // If autodialing-on-link-down is enabled, check if the OS auto dial
911 // option is set to always autodial. If so, then we are
912 // always up for the purposes of offline management.
913 if (autodialEnabled) {
914 #if defined(XP_WIN) && !defined(WINCE)
915 // On Windows, need to do some registry checking to see if
916 // autodial is enabled at the OS level. Only if that is
917 // enabled are we always up for the purposes of offline
918 // management.
919 if(nsNativeConnectionHelper::IsAutodialEnabled())
920 return SetOffline(PR_FALSE);
921 #else
922 return SetOffline(PR_FALSE);
923 #endif
927 PRBool isUp;
928 nsresult rv = mNetworkLinkService->GetIsLinkUp(&isUp);
929 NS_ENSURE_SUCCESS(rv, rv);
930 return SetOffline(!isUp);
933 NS_IMETHODIMP
934 nsIOService::EscapeString(const nsACString& aString,
935 PRUint32 aEscapeType,
936 nsACString& aResult)
938 NS_ENSURE_ARG_RANGE(aEscapeType, 0, 4);
940 nsCAutoString stringCopy(aString);
941 nsCString result;
943 if (!NS_Escape(stringCopy, result, (nsEscapeMask) aEscapeType))
944 return NS_ERROR_OUT_OF_MEMORY;
946 aResult.Assign(result);
948 return NS_OK;
951 NS_IMETHODIMP
952 nsIOService::EscapeURL(const nsACString &aStr,
953 PRUint32 aFlags, nsACString &aResult)
955 aResult.Truncate();
956 NS_EscapeURL(aStr.BeginReading(), aStr.Length(),
957 aFlags | esc_AlwaysCopy, aResult);
958 return NS_OK;
961 NS_IMETHODIMP
962 nsIOService::UnescapeString(const nsACString &aStr,
963 PRUint32 aFlags, nsACString &aResult)
965 aResult.Truncate();
966 NS_UnescapeURL(aStr.BeginReading(), aStr.Length(),
967 aFlags | esc_AlwaysCopy, aResult);
968 return NS_OK;
971 NS_IMETHODIMP
972 nsIOService::ExtractCharsetFromContentType(const nsACString &aTypeHeader,
973 nsACString &aCharset,
974 PRInt32 *aCharsetStart,
975 PRInt32 *aCharsetEnd,
976 PRBool *aHadCharset)
978 nsCAutoString ignored;
979 net_ParseContentType(aTypeHeader, ignored, aCharset, aHadCharset,
980 aCharsetStart, aCharsetEnd);
981 if (*aHadCharset && *aCharsetStart == *aCharsetEnd) {
982 *aHadCharset = PR_FALSE;
984 return NS_OK;