Back to index

lightning-sunbird  0.9+nobinonly
nsIOService.cpp
Go to the documentation of this file.
00001 /* vim:set ts=4 sw=4 cindent et: */
00002 /* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
00003 /* ***** BEGIN LICENSE BLOCK *****
00004  * Version: MPL 1.1/GPL 2.0/LGPL 2.1
00005  *
00006  * The contents of this file are subject to the Mozilla Public License Version
00007  * 1.1 (the "License"); you may not use this file except in compliance with
00008  * the License. You may obtain a copy of the License at
00009  * http://www.mozilla.org/MPL/
00010  *
00011  * Software distributed under the License is distributed on an "AS IS" basis,
00012  * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
00013  * for the specific language governing rights and limitations under the
00014  * License.
00015  *
00016  * The Original Code is mozilla.org code.
00017  *
00018  * The Initial Developer of the Original Code is
00019  * Netscape Communications Corporation.
00020  * Portions created by the Initial Developer are Copyright (C) 1998
00021  * the Initial Developer. All Rights Reserved.
00022  *
00023  * Contributor(s):
00024  *
00025  * Alternatively, the contents of this file may be used under the terms of
00026  * either the GNU General Public License Version 2 or later (the "GPL"), or
00027  * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
00028  * in which case the provisions of the GPL or the LGPL are applicable instead
00029  * of those above. If you wish to allow use of your version of this file only
00030  * under the terms of either the GPL or the LGPL, and not to allow others to
00031  * use your version of this file under the terms of the MPL, indicate your
00032  * decision by deleting the provisions above and replace them with the notice
00033  * and other provisions required by the GPL or the LGPL. If you do not delete
00034  * the provisions above, a recipient may use your version of this file under
00035  * the terms of any one of the MPL, the GPL or the LGPL.
00036  *
00037  * ***** END LICENSE BLOCK ***** */
00038 
00039 #include "nsIOService.h"
00040 #include "nsIProtocolHandler.h"
00041 #include "nsIFileProtocolHandler.h"
00042 #include "nscore.h"
00043 #include "nsIServiceManager.h"
00044 #include "nsIEventQueueService.h"
00045 #include "nsIURI.h"
00046 #include "nsIStreamListener.h"
00047 #include "prprf.h"
00048 #include "prlog.h"
00049 #include "nsLoadGroup.h"
00050 #include "nsInputStreamChannel.h"
00051 #include "nsXPIDLString.h" 
00052 #include "nsReadableUtils.h"
00053 #include "nsIErrorService.h" 
00054 #include "netCore.h"
00055 #include "nsIObserverService.h"
00056 #include "nsIPrefService.h"
00057 #include "nsIPrefBranch2.h"
00058 #include "nsIPrefLocalizedString.h"
00059 #include "nsICategoryManager.h"
00060 #include "nsXPCOM.h"
00061 #include "nsISupportsPrimitives.h"
00062 #include "nsIProxiedProtocolHandler.h"
00063 #include "nsIProxyInfo.h"
00064 #include "nsITimelineService.h"
00065 #include "nsEscape.h"
00066 #include "nsNetCID.h"
00067 #include "nsIRecyclingAllocator.h"
00068 #include "nsISocketTransport.h"
00069 #include "nsCRT.h"
00070 
00071 #define PORT_PREF_PREFIX     "network.security.ports."
00072 #define PORT_PREF(x)         PORT_PREF_PREFIX x
00073 #define AUTODIAL_PREF        "network.autodial-helper.enabled"
00074 
00075 static NS_DEFINE_CID(kStreamTransportServiceCID, NS_STREAMTRANSPORTSERVICE_CID);
00076 static NS_DEFINE_CID(kSocketTransportServiceCID, NS_SOCKETTRANSPORTSERVICE_CID);
00077 static NS_DEFINE_CID(kDNSServiceCID, NS_DNSSERVICE_CID);
00078 static NS_DEFINE_CID(kErrorServiceCID, NS_ERRORSERVICE_CID);
00079 static NS_DEFINE_CID(kProtocolProxyServiceCID, NS_PROTOCOLPROXYSERVICE_CID);
00080 
00081 nsIOService* gIOService = nsnull;
00082 
00083 // A general port blacklist.  Connections to these ports will not be avoided unless 
00084 // the protocol overrides.
00085 //
00086 // TODO: I am sure that there are more ports to be added.  
00087 //       This cut is based on the classic mozilla codebase
00088 
00089 PRInt16 gBadPortList[] = { 
00090   1,    // tcpmux          
00091   7,    // echo     
00092   9,    // discard          
00093   11,   // systat   
00094   13,   // daytime          
00095   15,   // netstat  
00096   17,   // qotd             
00097   19,   // chargen  
00098   20,   // ftp-data         
00099   21,   // ftp-cntl 
00100   22,   // ssh              
00101   23,   // telnet   
00102   25,   // smtp     
00103   37,   // time     
00104   42,   // name     
00105   43,   // nicname  
00106   53,   // domain  
00107   77,   // priv-rjs 
00108   79,   // finger   
00109   87,   // ttylink  
00110   95,   // supdup   
00111   101,  // hostriame
00112   102,  // iso-tsap 
00113   103,  // gppitnp  
00114   104,  // acr-nema 
00115   109,  // pop2     
00116   110,  // pop3     
00117   111,  // sunrpc   
00118   113,  // auth     
00119   115,  // sftp     
00120   117,  // uucp-path
00121   119,  // nntp     
00122   123,  // NTP
00123   135,  // loc-srv / epmap         
00124   139,  // netbios
00125   143,  // imap2  
00126   179,  // BGP
00127   389,  // ldap        
00128   465,  // smtp+ssl
00129   512,  // print / exec          
00130   513,  // login         
00131   514,  // shell         
00132   515,  // printer         
00133   526,  // tempo         
00134   530,  // courier        
00135   531,  // Chat         
00136   532,  // netnews        
00137   540,  // uucp       
00138   556,  // remotefs    
00139   563,  // nntp+ssl
00140   587,  //
00141   601,  //       
00142   636,  // ldap+ssl
00143   993,  // imap+ssl
00144   995,  // pop3+ssl
00145   2049, // nfs
00146   4045, // lockd
00147   6000, // x11        
00148   0,    // This MUST be zero so that we can populating the array
00149 };
00150 
00151 static const char kProfileChangeNetTeardownTopic[] = "profile-change-net-teardown";
00152 static const char kProfileChangeNetRestoreTopic[] = "profile-change-net-restore";
00153 
00154 // Necko buffer cache
00155 nsIMemory* nsIOService::gBufferCache = nsnull;
00156 
00158 
00159 nsIOService::nsIOService()
00160     : mOffline(PR_FALSE)
00161     , mOfflineForProfileChange(PR_FALSE)
00162     , mManageOfflineStatus(PR_FALSE)
00163     , mChannelEventSinks(NS_CHANNEL_EVENT_SINK_CATEGORY)
00164     , mContentSniffers(NS_CONTENT_SNIFFER_CATEGORY)
00165 {
00166     // Get the allocator ready
00167     if (!gBufferCache)
00168     {
00169         nsresult rv = NS_OK;
00170         nsCOMPtr<nsIRecyclingAllocator> recyclingAllocator =
00171             do_CreateInstance(NS_RECYCLINGALLOCATOR_CONTRACTID, &rv);
00172         if (NS_FAILED(rv))
00173             return;
00174         rv = recyclingAllocator->Init(NS_NECKO_BUFFER_CACHE_COUNT,
00175                                       NS_NECKO_15_MINS, "necko");
00176         if (NS_FAILED(rv))
00177             return;
00178 
00179         nsCOMPtr<nsIMemory> eyeMemory = do_QueryInterface(recyclingAllocator);
00180         gBufferCache = eyeMemory.get();
00181         NS_IF_ADDREF(gBufferCache);
00182     }
00183 }
00184 
00185 nsresult
00186 nsIOService::Init()
00187 {
00188     nsresult rv;
00189     
00190     // Hold onto the eventQueue service.  We do not want any eventqueues to go away
00191     // when we shutdown until we process all remaining transports
00192 
00193     mEventQueueService = do_GetService(NS_EVENTQUEUESERVICE_CONTRACTID, &rv);
00194     if (NS_FAILED(rv))
00195         NS_WARNING("failed to get event queue service");
00196     
00197     // We need to get references to these services so that we can shut them
00198     // down later. If we wait until the nsIOService is being shut down,
00199     // GetService will fail at that point.
00200 
00201     // TODO(darin): Load the Socket and DNS services lazily.
00202 
00203     mSocketTransportService = do_GetService(kSocketTransportServiceCID, &rv);
00204     if (NS_FAILED(rv))
00205         NS_WARNING("failed to get socket transport service");
00206 
00207     mDNSService = do_GetService(kDNSServiceCID, &rv);
00208     if (NS_FAILED(rv))
00209         NS_WARNING("failed to get DNS service");
00210 
00211     // XXX hack until xpidl supports error info directly (bug 13423)
00212     nsCOMPtr<nsIErrorService> errorService = do_GetService(kErrorServiceCID);
00213     if (errorService) {
00214         errorService->RegisterErrorStringBundle(NS_ERROR_MODULE_NETWORK, NECKO_MSGS_URL);
00215     }
00216     else
00217         NS_WARNING("failed to get error service");
00218     
00219     // setup our bad port list stuff
00220     for(int i=0; gBadPortList[i]; i++)
00221         mRestrictedPortList.AppendElement(NS_REINTERPRET_CAST(void *, gBadPortList[i]));
00222 
00223     // Further modifications to the port list come from prefs
00224     nsCOMPtr<nsIPrefBranch2> prefBranch;
00225     GetPrefBranch(getter_AddRefs(prefBranch));
00226     if (prefBranch) {
00227         prefBranch->AddObserver(PORT_PREF_PREFIX, this, PR_TRUE);
00228         prefBranch->AddObserver(AUTODIAL_PREF, this, PR_TRUE);
00229         PrefsChanged(prefBranch);
00230     }
00231     
00232     // Register for profile change notifications
00233     nsCOMPtr<nsIObserverService> observerService =
00234         do_GetService("@mozilla.org/observer-service;1");
00235     if (observerService) {
00236         observerService->AddObserver(this, kProfileChangeNetTeardownTopic, PR_TRUE);
00237         observerService->AddObserver(this, kProfileChangeNetRestoreTopic, PR_TRUE);
00238         observerService->AddObserver(this, NS_XPCOM_SHUTDOWN_OBSERVER_ID, PR_TRUE);
00239         observerService->AddObserver(this, NS_NETWORK_LINK_TOPIC, PR_TRUE);
00240     }
00241     else
00242         NS_WARNING("failed to get observer service");
00243         
00244     gIOService = this;
00245     
00246     // go into managed mode if we can
00247     mNetworkLinkService = do_GetService(NS_NETWORK_LINK_SERVICE_CONTRACTID);
00248     if (mNetworkLinkService) {
00249         mManageOfflineStatus = PR_TRUE;
00250         TrackNetworkLinkStatusForOffline();
00251     }
00252 
00253     return NS_OK;
00254 }
00255 
00256 
00257 nsIOService::~nsIOService()
00258 {
00259     gIOService = nsnull;
00260 }   
00261 
00262 nsIOService*
00263 nsIOService::GetInstance() {
00264     if (!gIOService) {
00265         gIOService = new nsIOService();
00266         if (!gIOService)
00267             return nsnull;
00268         NS_ADDREF(gIOService);
00269 
00270         nsresult rv = gIOService->Init();
00271         if (NS_FAILED(rv)) {
00272             NS_RELEASE(gIOService);
00273             return nsnull;
00274         }
00275         return gIOService;
00276     }
00277     NS_ADDREF(gIOService);
00278     return gIOService;
00279 }
00280 
00281 NS_IMPL_THREADSAFE_ISUPPORTS5(nsIOService,
00282                               nsIIOService,
00283                               nsIIOService2,
00284                               nsINetUtil,
00285                               nsIObserver,
00286                               nsISupportsWeakReference)
00287 
00288 
00289 
00290 nsresult
00291 nsIOService::OnChannelRedirect(nsIChannel* oldChan, nsIChannel* newChan,
00292                                PRUint32 flags)
00293 {
00294     // Notify the registered observers
00295     const nsCOMArray<nsIChannelEventSink>& entries =
00296         mChannelEventSinks.GetEntries();
00297     PRInt32 len = entries.Count();
00298     for (PRInt32 i = 0; i < len; ++i) {
00299         nsresult rv = entries[i]->OnChannelRedirect(oldChan, newChan, flags);
00300         if (NS_FAILED(rv))
00301             return rv;
00302     }
00303 
00304     return NS_OK;
00305 }
00306 
00307 nsresult
00308 nsIOService::CacheProtocolHandler(const char *scheme, nsIProtocolHandler *handler)
00309 {
00310     for (unsigned int i=0; i<NS_N(gScheme); i++)
00311     {
00312         if (!nsCRT::strcasecmp(scheme, gScheme[i]))
00313         {
00314             nsresult rv;
00315             NS_ASSERTION(!mWeakHandler[i], "Protocol handler already cached");
00316             // Make sure the handler supports weak references.
00317             nsCOMPtr<nsISupportsWeakReference> factoryPtr = do_QueryInterface(handler, &rv);
00318             if (!factoryPtr)
00319             {
00320                 // Dont cache handlers that dont support weak reference as
00321                 // there is real danger of a circular reference.
00322 #ifdef DEBUG_dp
00323                 printf("DEBUG: %s protcol handler doesn't support weak ref. Not cached.\n", scheme);
00324 #endif /* DEBUG_dp */
00325                 return NS_ERROR_FAILURE;
00326             }
00327             mWeakHandler[i] = do_GetWeakReference(handler);
00328             return NS_OK;
00329         }
00330     }
00331     return NS_ERROR_FAILURE;
00332 }
00333 
00334 nsresult
00335 nsIOService::GetCachedProtocolHandler(const char *scheme, nsIProtocolHandler **result, PRUint32 start, PRUint32 end)
00336 {
00337     PRUint32 len = end - start - 1;
00338     for (unsigned int i=0; i<NS_N(gScheme); i++)
00339     {
00340         if (!mWeakHandler[i])
00341             continue;
00342 
00343         // handle unterminated strings
00344         // start is inclusive, end is exclusive, len = end - start - 1
00345         if (end ? (!nsCRT::strncasecmp(scheme + start, gScheme[i], len)
00346                    && gScheme[i][len] == '\0')
00347                 : (!nsCRT::strcasecmp(scheme, gScheme[i])))
00348         {
00349             return CallQueryReferent(mWeakHandler[i].get(), result);
00350         }
00351     }
00352     return NS_ERROR_FAILURE;
00353 }
00354  
00355 NS_IMETHODIMP
00356 nsIOService::GetProtocolHandler(const char* scheme, nsIProtocolHandler* *result)
00357 {
00358     nsresult rv;
00359 
00360     NS_ENSURE_ARG_POINTER(scheme);
00361     // XXX we may want to speed this up by introducing our own protocol 
00362     // scheme -> protocol handler mapping, avoiding the string manipulation
00363     // and service manager stuff
00364 
00365     rv = GetCachedProtocolHandler(scheme, result);
00366     if (NS_SUCCEEDED(rv))
00367         return rv;
00368 
00369     PRBool externalProtocol = PR_FALSE;
00370     PRBool listedProtocol   = PR_TRUE;
00371     nsCOMPtr<nsIPrefBranch2> prefBranch;
00372     GetPrefBranch(getter_AddRefs(prefBranch));
00373     if (prefBranch) {
00374         nsCAutoString externalProtocolPref("network.protocol-handler.external.");
00375         externalProtocolPref += scheme;
00376         rv = prefBranch->GetBoolPref(externalProtocolPref.get(), &externalProtocol);
00377         if (NS_FAILED(rv)) {
00378             externalProtocol = PR_FALSE;
00379             listedProtocol   = PR_FALSE;
00380         }
00381     }
00382 
00383     if (!externalProtocol) {
00384         nsCAutoString contractID(NS_NETWORK_PROTOCOL_CONTRACTID_PREFIX);
00385         contractID += scheme;
00386         ToLowerCase(contractID);
00387 
00388         rv = CallGetService(contractID.get(), result);
00389         if (NS_SUCCEEDED(rv)) {
00390             CacheProtocolHandler(scheme, *result);
00391             return rv;
00392         }
00393 
00394         // If the pref for this protocol was explicitly set to false, we want
00395         // to use our special "blocked protocol" handler.  That will ensure we
00396         // don't open any channels for this protocol.
00397         if (listedProtocol) {
00398             rv = CallGetService(NS_NETWORK_PROTOCOL_CONTRACTID_PREFIX"default-blocked",
00399                                 result);
00400             if (NS_FAILED(rv))
00401                 return NS_ERROR_UNKNOWN_PROTOCOL;
00402         }
00403     }
00404     
00405 #ifdef MOZ_X11
00406     // check to see whether GnomeVFS can handle this URI scheme.  if it can
00407     // create a nsIURI for the "scheme:", then we assume it has support for
00408     // the requested protocol.  otherwise, we failover to using the default
00409     // protocol handler.
00410 
00411     // XXX should this be generalized into something that searches a
00412     // category?  (see bug 234714)
00413 
00414     rv = CallGetService(NS_NETWORK_PROTOCOL_CONTRACTID_PREFIX"moz-gnomevfs",
00415                         result);
00416     if (NS_SUCCEEDED(rv)) {
00417         nsCAutoString spec(scheme);
00418         spec.Append(':');
00419 
00420         nsIURI *uri;
00421         rv = (*result)->NewURI(spec, nsnull, nsnull, &uri);
00422         if (NS_SUCCEEDED(rv)) {
00423             NS_RELEASE(uri);
00424             return rv;
00425         }
00426 
00427         NS_RELEASE(*result);
00428     }
00429 #endif
00430 
00431     // Okay we don't have a protocol handler to handle this url type, so use
00432     // the default protocol handler.  This will cause urls to get dispatched
00433     // out to the OS ('cause we can't do anything with them) when we try to
00434     // read from a channel created by the default protocol handler.
00435 
00436     rv = CallGetService(NS_NETWORK_PROTOCOL_CONTRACTID_PREFIX"default",
00437                         result);
00438     if (NS_FAILED(rv))
00439         return NS_ERROR_UNKNOWN_PROTOCOL;
00440 
00441     return rv;
00442 }
00443 
00444 NS_IMETHODIMP
00445 nsIOService::ExtractScheme(const nsACString &inURI, nsACString &scheme)
00446 {
00447     return net_ExtractURLScheme(inURI, nsnull, nsnull, &scheme);
00448 }
00449 
00450 NS_IMETHODIMP 
00451 nsIOService::GetProtocolFlags(const char* scheme, PRUint32 *flags)
00452 {
00453     nsCOMPtr<nsIProtocolHandler> handler;
00454     nsresult rv = GetProtocolHandler(scheme, getter_AddRefs(handler));
00455     if (NS_FAILED(rv)) return rv;
00456 
00457     rv = handler->GetProtocolFlags(flags);
00458     return rv;
00459 }
00460 
00461 nsresult
00462 nsIOService::NewURI(const nsACString &aSpec, const char *aCharset, nsIURI *aBaseURI, nsIURI **result)
00463 {
00464     nsresult rv;
00465     nsCAutoString scheme;
00466 
00467     rv = ExtractScheme(aSpec, scheme);
00468     if (NS_FAILED(rv)) {
00469         // then aSpec is relative
00470         if (!aBaseURI)
00471             return NS_ERROR_MALFORMED_URI;
00472 
00473         rv = aBaseURI->GetScheme(scheme);
00474         if (NS_FAILED(rv)) return rv;
00475     }
00476 
00477     // now get the handler for this scheme
00478     nsCOMPtr<nsIProtocolHandler> handler;
00479     rv = GetProtocolHandler(scheme.get(), getter_AddRefs(handler));
00480     if (NS_FAILED(rv)) return rv;
00481 
00482     return handler->NewURI(aSpec, aCharset, aBaseURI, result);
00483 }
00484 
00485 
00486 NS_IMETHODIMP 
00487 nsIOService::NewFileURI(nsIFile *file, nsIURI **result)
00488 {
00489     nsresult rv;
00490     NS_ENSURE_ARG_POINTER(file);
00491 
00492     nsCOMPtr<nsIProtocolHandler> handler;
00493 
00494     rv = GetProtocolHandler("file", getter_AddRefs(handler));
00495     if (NS_FAILED(rv)) return rv;
00496 
00497     nsCOMPtr<nsIFileProtocolHandler> fileHandler( do_QueryInterface(handler, &rv) );
00498     if (NS_FAILED(rv)) return rv;
00499     
00500     return fileHandler->NewFileURI(file, result);
00501 }
00502 
00503 NS_IMETHODIMP
00504 nsIOService::NewChannelFromURI(nsIURI *aURI, nsIChannel **result)
00505 {
00506     nsresult rv;
00507     NS_ENSURE_ARG_POINTER(aURI);
00508     NS_TIMELINE_MARK_URI("nsIOService::NewChannelFromURI(%s)", aURI);
00509 
00510     nsCAutoString scheme;
00511     rv = aURI->GetScheme(scheme);
00512     if (NS_FAILED(rv))
00513         return rv;
00514 
00515     nsCOMPtr<nsIProtocolHandler> handler;
00516     rv = GetProtocolHandler(scheme.get(), getter_AddRefs(handler));
00517     if (NS_FAILED(rv))
00518         return rv;
00519 
00520     PRUint32 protoFlags;
00521     rv = handler->GetProtocolFlags(&protoFlags);
00522     if (NS_FAILED(rv))
00523         return rv;
00524 
00525     // Talk to the PPS if the protocol handler allows proxying.  Otherwise,
00526     // skip this step.  This allows us to lazily load the PPS at startup.
00527     if (protoFlags & nsIProtocolHandler::ALLOWS_PROXY) {
00528         nsCOMPtr<nsIProxyInfo> pi;
00529         if (!mProxyService) {
00530             mProxyService = do_GetService(NS_PROTOCOLPROXYSERVICE_CONTRACTID);
00531             if (!mProxyService)
00532                 NS_WARNING("failed to get protocol proxy service");
00533         }
00534         if (mProxyService) {
00535             rv = mProxyService->Resolve(aURI, 0, getter_AddRefs(pi));
00536             if (NS_FAILED(rv))
00537                 pi = nsnull;
00538         }
00539         if (pi) {
00540             nsCAutoString type;
00541             if (NS_SUCCEEDED(pi->GetType(type)) && type.EqualsLiteral("http")) {
00542                 // we are going to proxy this channel using an http proxy
00543                 rv = GetProtocolHandler("http", getter_AddRefs(handler));
00544                 if (NS_FAILED(rv))
00545                     return rv;
00546             }
00547             nsCOMPtr<nsIProxiedProtocolHandler> pph = do_QueryInterface(handler);
00548             if (pph)
00549                 return pph->NewProxiedChannel(aURI, pi, result);
00550         }
00551     }
00552 
00553     return handler->NewChannel(aURI, result);
00554 }
00555 
00556 NS_IMETHODIMP
00557 nsIOService::NewChannel(const nsACString &aSpec, const char *aCharset, nsIURI *aBaseURI, nsIChannel **result)
00558 {
00559     nsresult rv;
00560     nsCOMPtr<nsIURI> uri;
00561     rv = NewURI(aSpec, aCharset, aBaseURI, getter_AddRefs(uri));
00562     if (NS_FAILED(rv)) return rv;
00563 
00564     return NewChannelFromURI(uri, result);
00565 }
00566 
00567 NS_IMETHODIMP
00568 nsIOService::GetOffline(PRBool *offline)
00569 {
00570     *offline = mOffline;
00571     return NS_OK;
00572 }
00573 
00574 NS_IMETHODIMP
00575 nsIOService::SetOffline(PRBool offline)
00576 {
00577     nsCOMPtr<nsIObserverService> observerService =
00578         do_GetService("@mozilla.org/observer-service;1");
00579     
00580     nsresult rv;
00581     if (offline && !mOffline) {
00582         NS_NAMED_LITERAL_STRING(offlineString, NS_IOSERVICE_OFFLINE);
00583         mOffline = PR_TRUE; // indicate we're trying to shutdown
00584 
00585         // don't care if notification fails
00586         // this allows users to attempt a little cleanup before dns and socket transport are shut down.
00587         if (observerService)
00588             observerService->NotifyObservers(NS_STATIC_CAST(nsIIOService *, this),
00589                                              NS_IOSERVICE_GOING_OFFLINE_TOPIC,
00590                                              offlineString.get());
00591 
00592         // be sure to try and shutdown both (even if the first fails)...
00593         // shutdown dns service first, because it has callbacks for socket transport
00594         if (mDNSService) {
00595             rv = mDNSService->Shutdown();
00596             NS_ASSERTION(NS_SUCCEEDED(rv), "DNS service shutdown failed");
00597         }
00598         if (mSocketTransportService) {
00599             rv = mSocketTransportService->Shutdown();
00600             NS_ASSERTION(NS_SUCCEEDED(rv), "socket transport service shutdown failed");
00601         }
00602 
00603         // don't care if notification fails
00604         if (observerService)
00605             observerService->NotifyObservers(NS_STATIC_CAST(nsIIOService *, this),
00606                                              NS_IOSERVICE_OFFLINE_STATUS_TOPIC,
00607                                              offlineString.get());
00608     }
00609     else if (!offline && mOffline) {
00610         // go online
00611         if (mDNSService) {
00612             rv = mDNSService->Init();
00613             NS_ASSERTION(NS_SUCCEEDED(rv), "DNS service init failed");
00614         }
00615         if (mSocketTransportService) {
00616             rv = mSocketTransportService->Init();
00617             NS_ASSERTION(NS_SUCCEEDED(rv), "socket transport service init failed");
00618         }
00619         mOffline = PR_FALSE;    // indicate success only AFTER we've
00620                                 // brought up the services
00621  
00622         // don't care if notification fails
00623         if (observerService)
00624             observerService->NotifyObservers(NS_STATIC_CAST(nsIIOService *, this),
00625                                              NS_IOSERVICE_OFFLINE_STATUS_TOPIC,
00626                                              NS_LITERAL_STRING(NS_IOSERVICE_ONLINE).get());
00627     }
00628     return NS_OK;
00629 }
00630 
00631 
00632 NS_IMETHODIMP
00633 nsIOService::AllowPort(PRInt32 inPort, const char *scheme, PRBool *_retval)
00634 {
00635     PRInt16 port = inPort;
00636     if (port == -1) {
00637         *_retval = PR_TRUE;
00638         return NS_OK;
00639     }
00640         
00641     // first check to see if the port is in our blacklist:
00642     PRInt32 badPortListCnt = mRestrictedPortList.Count();
00643     for (int i=0; i<badPortListCnt; i++)
00644     {
00645         if (port == (PRInt32) NS_PTR_TO_INT32(mRestrictedPortList[i]))
00646         {
00647             *_retval = PR_FALSE;
00648 
00649             // check to see if the protocol wants to override
00650             if (!scheme)
00651                 return NS_OK;
00652             
00653             nsCOMPtr<nsIProtocolHandler> handler;
00654             nsresult rv = GetProtocolHandler(scheme, getter_AddRefs(handler));
00655             if (NS_FAILED(rv)) return rv;
00656 
00657             // let the protocol handler decide
00658             return handler->AllowPort(port, scheme, _retval);
00659         }
00660     }
00661 
00662     *_retval = PR_TRUE;
00663     return NS_OK;
00664 }
00665 
00667 
00668 void
00669 nsIOService::PrefsChanged(nsIPrefBranch *prefs, const char *pref)
00670 {
00671     if (!prefs) return;
00672 
00673     // Look for extra ports to block
00674     if (!pref || strcmp(pref, PORT_PREF("banned")) == 0)
00675         ParsePortList(prefs, PORT_PREF("banned"), PR_FALSE);
00676 
00677     // ...as well as previous blocks to remove.
00678     if (!pref || strcmp(pref, PORT_PREF("banned.override")) == 0)
00679         ParsePortList(prefs, PORT_PREF("banned.override"), PR_TRUE);
00680 
00681     if (!pref || strcmp(pref, AUTODIAL_PREF) == 0) {
00682         PRBool enableAutodial = PR_FALSE;
00683         nsresult rv = prefs->GetBoolPref(AUTODIAL_PREF, &enableAutodial);
00684         // If pref not found, default to disabled.
00685         if (NS_SUCCEEDED(rv)) {
00686             if (mSocketTransportService)
00687                 mSocketTransportService->SetAutodialEnabled(enableAutodial);
00688         }
00689     }
00690 }
00691 
00692 void
00693 nsIOService::ParsePortList(nsIPrefBranch *prefBranch, const char *pref, PRBool remove)
00694 {
00695     nsXPIDLCString portList;
00696 
00697     // Get a pref string and chop it up into a list of ports.
00698     prefBranch->GetCharPref(pref, getter_Copies(portList));
00699     if (portList) {
00700         nsCStringArray portListArray;
00701         portListArray.ParseString(portList.get(), ",");
00702         PRInt32 index;
00703         for (index=0; index < portListArray.Count(); index++) {
00704             portListArray[index]->StripWhitespace();
00705             PRInt32 aErrorCode, portBegin, portEnd;
00706 
00707             if (PR_sscanf(portListArray[index]->get(), "%d-%d", &portBegin, &portEnd) == 2) {
00708                if ((portBegin < 65536) && (portEnd < 65536)) {
00709                    PRInt32 curPort;
00710                    if (remove) {
00711                         for (curPort=portBegin; curPort <= portEnd; curPort++)
00712                             mRestrictedPortList.RemoveElement((void*)curPort);
00713                    } else {
00714                         for (curPort=portBegin; curPort <= portEnd; curPort++)
00715                             mRestrictedPortList.AppendElement((void*)curPort);
00716                    }
00717                }
00718             } else {
00719                PRInt32 port = portListArray[index]->ToInteger(&aErrorCode);
00720                if (NS_SUCCEEDED(aErrorCode) && port < 65536) {
00721                    if (remove)
00722                        mRestrictedPortList.RemoveElement((void*)port);
00723                    else
00724                        mRestrictedPortList.AppendElement((void*)port);
00725                }
00726             }
00727 
00728         }
00729     }
00730 }
00731 
00732 void
00733 nsIOService::GetPrefBranch(nsIPrefBranch2 **result)
00734 {
00735     *result = nsnull;
00736     CallGetService(NS_PREFSERVICE_CONTRACTID, result);
00737 }
00738 
00739 // nsIObserver interface
00740 NS_IMETHODIMP
00741 nsIOService::Observe(nsISupports *subject,
00742                      const char *topic,
00743                      const PRUnichar *data)
00744 {
00745     if (!strcmp(topic, NS_PREFBRANCH_PREFCHANGE_TOPIC_ID)) {
00746         nsCOMPtr<nsIPrefBranch> prefBranch = do_QueryInterface(subject);
00747         if (prefBranch)
00748             PrefsChanged(prefBranch, NS_ConvertUCS2toUTF8(data).get());
00749     }
00750     else if (!strcmp(topic, kProfileChangeNetTeardownTopic)) {
00751         if (!mOffline) {
00752             SetOffline(PR_TRUE);
00753             mOfflineForProfileChange = PR_TRUE;
00754         }
00755     }
00756     else if (!strcmp(topic, kProfileChangeNetRestoreTopic)) {
00757         if (mOfflineForProfileChange) {
00758             mOfflineForProfileChange = PR_FALSE;
00759             if (!mManageOfflineStatus ||
00760                 NS_FAILED(TrackNetworkLinkStatusForOffline())) {
00761                 SetOffline(PR_FALSE);
00762             }
00763         }    
00764     }
00765     else if (!strcmp(topic, NS_XPCOM_SHUTDOWN_OBSERVER_ID)) {
00766         SetOffline(PR_TRUE);
00767 
00768         // Break circular reference.
00769         mProxyService = nsnull;
00770     }
00771     else if (!strcmp(topic, NS_NETWORK_LINK_TOPIC)) {
00772         if (!mOfflineForProfileChange && mManageOfflineStatus) {
00773             TrackNetworkLinkStatusForOffline();
00774         }
00775     }
00776 
00777     return NS_OK;
00778 }
00779 
00780 // nsINetUtil interface
00781 NS_IMETHODIMP
00782 nsIOService::ParseContentType(const nsACString &aTypeHeader,
00783                               nsACString &aCharset,
00784                               PRBool *aHadCharset,
00785                               nsACString &aContentType)
00786 {
00787     net_ParseContentType(aTypeHeader, aContentType, aCharset, aHadCharset);
00788     return NS_OK;
00789 }
00790 
00791 NS_IMETHODIMP
00792 nsIOService::SetManageOfflineStatus(PRBool aManage)
00793 {
00794     PRBool wasManaged = mManageOfflineStatus;
00795     mManageOfflineStatus = aManage;
00796     if (mManageOfflineStatus && !wasManaged)
00797         return TrackNetworkLinkStatusForOffline();
00798     return NS_OK;
00799 }
00800 
00801 NS_IMETHODIMP
00802 nsIOService::GetManageOfflineStatus(PRBool* aManage)
00803 {
00804     *aManage = mManageOfflineStatus;
00805     return NS_OK;
00806 }
00807 
00808 nsresult
00809 nsIOService::TrackNetworkLinkStatusForOffline()
00810 {
00811     NS_ASSERTION(mManageOfflineStatus,
00812                  "Don't call this unless we're managing the offline status");
00813     if (!mNetworkLinkService)
00814         return NS_ERROR_FAILURE;
00815   
00816     // check to make sure this won't collide with Autodial
00817     if (mSocketTransportService) {
00818         PRBool autodialEnabled = PR_FALSE;
00819         mSocketTransportService->GetAutodialEnabled(&autodialEnabled);
00820         // If autodialing-on-link-down is enabled, then pretend the link is
00821         // always up for the purposes of offline management.
00822         if (autodialEnabled)
00823             return SetOffline(PR_FALSE);
00824     }
00825   
00826     PRBool isUp;
00827     nsresult rv = mNetworkLinkService->GetIsLinkUp(&isUp);
00828     NS_ENSURE_SUCCESS(rv, rv);
00829     return SetOffline(!isUp);
00830 }