modules/libpref/src/nsPrefBranch.cpp

Sat, 03 Jan 2015 20:18:00 +0100

author
Michael Schloh von Bennewitz <michael@schloh.com>
date
Sat, 03 Jan 2015 20:18:00 +0100
branch
TOR_BUG_3246
changeset 7
129ffea94266
permissions
-rw-r--r--

Conditionally enable double key logic according to:
private browsing mode or privacy.thirdparty.isolate preference and
implement in GetCookieStringCommon and FindCookie where it counts...
With some reservations of how to convince FindCookie users to test
condition and pass a nullptr when disabling double key logic.

     1 /* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
     2 /* This Source Code Form is subject to the terms of the Mozilla Public
     3  * License, v. 2.0. If a copy of the MPL was not distributed with this
     4  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
     6 #include "mozilla/dom/ContentChild.h"
     7 #include "nsXULAppAPI.h"
     9 #include "nsPrefBranch.h"
    10 #include "nsILocalFile.h" // nsILocalFile used for backwards compatibility
    11 #include "nsIObserverService.h"
    12 #include "nsXPCOM.h"
    13 #include "nsISupportsPrimitives.h"
    14 #include "nsIDirectoryService.h"
    15 #include "nsString.h"
    16 #include "nsReadableUtils.h"
    17 #include "nsXPIDLString.h"
    18 #include "nsPrintfCString.h"
    19 #include "nsIStringBundle.h"
    20 #include "prefapi.h"
    21 #include "pldhash.h"
    23 #include "nsCRT.h"
    24 #include "mozilla/Services.h"
    26 #include "prefapi_private_data.h"
    28 #ifdef MOZ_CRASHREPORTER
    29 #include "nsICrashReporter.h"
    30 #endif
    32 #include "nsIConsoleService.h"
    34 #ifdef DEBUG
    35 #define ENSURE_MAIN_PROCESS(message, pref) do {                                \
    36   if (GetContentChild()) {                                                     \
    37     nsPrintfCString msg("ENSURE_MAIN_PROCESS failed. %s %s", message, pref);   \
    38     NS_ERROR(msg.get());                                                       \
    39     return NS_ERROR_NOT_AVAILABLE;                                             \
    40   }                                                                            \
    41 } while (0);
    42 #else
    43 #define ENSURE_MAIN_PROCESS(message, pref)                                     \
    44   if (GetContentChild()) {                                                     \
    45     return NS_ERROR_NOT_AVAILABLE;                                             \
    46   }
    47 #endif
    49 // Definitions
    50 struct EnumerateData {
    51   const char  *parent;
    52   nsTArray<nsCString> *pref_list;
    53 };
    55 // Prototypes
    56 static PLDHashOperator
    57   pref_enumChild(PLDHashTable *table, PLDHashEntryHdr *heh,
    58                  uint32_t i, void *arg);
    60 using mozilla::dom::ContentChild;
    62 static ContentChild*
    63 GetContentChild()
    64 {
    65   if (XRE_GetProcessType() == GeckoProcessType_Content) {
    66     ContentChild* cpc = ContentChild::GetSingleton();
    67     if (!cpc) {
    68       NS_RUNTIMEABORT("Content Protocol is NULL!  We're going to crash!");
    69     }
    70     return cpc;
    71   }
    72   return nullptr;
    73 }
    75 /*
    76  * Constructor/Destructor
    77  */
    79 nsPrefBranch::nsPrefBranch(const char *aPrefRoot, bool aDefaultBranch)
    80 {
    81   mPrefRoot = aPrefRoot;
    82   mPrefRootLength = mPrefRoot.Length();
    83   mIsDefault = aDefaultBranch;
    84   mFreeingObserverList = false;
    86   nsCOMPtr<nsIObserverService> observerService =
    87     mozilla::services::GetObserverService();
    88   if (observerService) {
    89     ++mRefCnt;    // Our refcnt must be > 0 when we call this, or we'll get deleted!
    90     // add weak so we don't have to clean up at shutdown
    91     observerService->AddObserver(this, NS_XPCOM_SHUTDOWN_OBSERVER_ID, true);
    92     --mRefCnt;
    93   }
    94 }
    96 nsPrefBranch::~nsPrefBranch()
    97 {
    98   freeObserverList();
   100   nsCOMPtr<nsIObserverService> observerService =
   101     mozilla::services::GetObserverService();
   102   if (observerService)
   103     observerService->RemoveObserver(this, NS_XPCOM_SHUTDOWN_OBSERVER_ID);
   104 }
   107 /*
   108  * nsISupports Implementation
   109  */
   111 NS_IMPL_ADDREF(nsPrefBranch)
   112 NS_IMPL_RELEASE(nsPrefBranch)
   114 NS_INTERFACE_MAP_BEGIN(nsPrefBranch)
   115   NS_INTERFACE_MAP_ENTRY_AMBIGUOUS(nsISupports, nsIPrefBranch)
   116   NS_INTERFACE_MAP_ENTRY(nsIPrefBranch)
   117   NS_INTERFACE_MAP_ENTRY_CONDITIONAL(nsIPrefBranch2, !mIsDefault)
   118   NS_INTERFACE_MAP_ENTRY_CONDITIONAL(nsIPrefBranchInternal, !mIsDefault)
   119   NS_INTERFACE_MAP_ENTRY(nsIObserver)
   120   NS_INTERFACE_MAP_ENTRY(nsISupportsWeakReference)
   121 NS_INTERFACE_MAP_END
   124 /*
   125  * nsIPrefBranch Implementation
   126  */
   128 NS_IMETHODIMP nsPrefBranch::GetRoot(char **aRoot)
   129 {
   130   NS_ENSURE_ARG_POINTER(aRoot);
   131   mPrefRoot.Truncate(mPrefRootLength);
   132   *aRoot = ToNewCString(mPrefRoot);
   133   return NS_OK;
   134 }
   136 NS_IMETHODIMP nsPrefBranch::GetPrefType(const char *aPrefName, int32_t *_retval)
   137 {
   138   NS_ENSURE_ARG(aPrefName);
   139   const char *pref = getPrefName(aPrefName);
   140   *_retval = PREF_GetPrefType(pref);
   141   return NS_OK;
   142 }
   144 NS_IMETHODIMP nsPrefBranch::GetBoolPref(const char *aPrefName, bool *_retval)
   145 {
   146   NS_ENSURE_ARG(aPrefName);
   147   const char *pref = getPrefName(aPrefName);
   148   return PREF_GetBoolPref(pref, _retval, mIsDefault);
   149 }
   151 NS_IMETHODIMP nsPrefBranch::SetBoolPref(const char *aPrefName, bool aValue)
   152 {
   153   ENSURE_MAIN_PROCESS("Cannot SetBoolPref from content process:", aPrefName);
   154   NS_ENSURE_ARG(aPrefName);
   155   const char *pref = getPrefName(aPrefName);
   156   return PREF_SetBoolPref(pref, aValue, mIsDefault);
   157 }
   159 NS_IMETHODIMP nsPrefBranch::GetFloatPref(const char *aPrefName, float *_retval)
   160 {
   161   NS_ENSURE_ARG(aPrefName);
   162   const char *pref = getPrefName(aPrefName);
   163   nsAutoCString stringVal;
   164   nsresult rv = GetCharPref(pref, getter_Copies(stringVal));
   165   if (NS_SUCCEEDED(rv)) {
   166     *_retval = stringVal.ToFloat(&rv);
   167   }
   169   return rv;
   170 }
   172 NS_IMETHODIMP nsPrefBranch::GetCharPref(const char *aPrefName, char **_retval)
   173 {
   174   NS_ENSURE_ARG(aPrefName);
   175   const char *pref = getPrefName(aPrefName);
   176   return PREF_CopyCharPref(pref, _retval, mIsDefault);
   177 }
   179 NS_IMETHODIMP nsPrefBranch::SetCharPref(const char *aPrefName, const char *aValue)
   180 {
   181   nsresult rv = CheckSanityOfStringLength(aPrefName, aValue);
   182   if (NS_FAILED(rv)) {
   183     return rv;
   184   }
   185   return SetCharPrefInternal(aPrefName, aValue);
   186 }
   188 nsresult nsPrefBranch::SetCharPrefInternal(const char *aPrefName, const char *aValue)
   190 {
   191   ENSURE_MAIN_PROCESS("Cannot SetCharPref from content process:", aPrefName);
   192   NS_ENSURE_ARG(aPrefName);
   193   NS_ENSURE_ARG(aValue);
   194   const char *pref = getPrefName(aPrefName);
   195   return PREF_SetCharPref(pref, aValue, mIsDefault);
   196 }
   198 NS_IMETHODIMP nsPrefBranch::GetIntPref(const char *aPrefName, int32_t *_retval)
   199 {
   200   NS_ENSURE_ARG(aPrefName);
   201   const char *pref = getPrefName(aPrefName);
   202   return PREF_GetIntPref(pref, _retval, mIsDefault);
   203 }
   205 NS_IMETHODIMP nsPrefBranch::SetIntPref(const char *aPrefName, int32_t aValue)
   206 {
   207   ENSURE_MAIN_PROCESS("Cannot SetIntPref from content process:", aPrefName);
   208   NS_ENSURE_ARG(aPrefName);
   209   const char *pref = getPrefName(aPrefName);
   210   return PREF_SetIntPref(pref, aValue, mIsDefault);
   211 }
   213 NS_IMETHODIMP nsPrefBranch::GetComplexValue(const char *aPrefName, const nsIID & aType, void **_retval)
   214 {
   215   NS_ENSURE_ARG(aPrefName);
   217   nsresult       rv;
   218   nsXPIDLCString utf8String;
   220   // we have to do this one first because it's different than all the rest
   221   if (aType.Equals(NS_GET_IID(nsIPrefLocalizedString))) {
   222     nsCOMPtr<nsIPrefLocalizedString> theString(do_CreateInstance(NS_PREFLOCALIZEDSTRING_CONTRACTID, &rv));
   223     if (NS_FAILED(rv)) return rv;
   225     const char *pref = getPrefName(aPrefName);
   226     bool    bNeedDefault = false;
   228     if (mIsDefault) {
   229       bNeedDefault = true;
   230     } else {
   231       // if there is no user (or locked) value
   232       if (!PREF_HasUserPref(pref) && !PREF_PrefIsLocked(pref)) {
   233         bNeedDefault = true;
   234       }
   235     }
   237     // if we need to fetch the default value, do that instead, otherwise use the
   238     // value we pulled in at the top of this function
   239     if (bNeedDefault) {
   240       nsXPIDLString utf16String;
   241       rv = GetDefaultFromPropertiesFile(pref, getter_Copies(utf16String));
   242       if (NS_SUCCEEDED(rv)) {
   243         theString->SetData(utf16String.get());
   244       }
   245     } else {
   246       rv = GetCharPref(aPrefName, getter_Copies(utf8String));
   247       if (NS_SUCCEEDED(rv)) {
   248         theString->SetData(NS_ConvertUTF8toUTF16(utf8String).get());
   249       }
   250     }
   252     if (NS_SUCCEEDED(rv)) {
   253       theString.forget(reinterpret_cast<nsIPrefLocalizedString**>(_retval));
   254     }
   256     return rv;
   257   }
   259   // if we can't get the pref, there's no point in being here
   260   rv = GetCharPref(aPrefName, getter_Copies(utf8String));
   261   if (NS_FAILED(rv)) {
   262     return rv;
   263   }
   265   // also check nsILocalFile, for backwards compatibility
   266   if (aType.Equals(NS_GET_IID(nsIFile)) || aType.Equals(NS_GET_IID(nsILocalFile))) {
   267     if (GetContentChild()) {
   268       NS_ERROR("cannot get nsIFile pref from content process");
   269       return NS_ERROR_NOT_AVAILABLE;
   270     }
   272     nsCOMPtr<nsIFile> file(do_CreateInstance(NS_LOCAL_FILE_CONTRACTID, &rv));
   274     if (NS_SUCCEEDED(rv)) {
   275       rv = file->SetPersistentDescriptor(utf8String);
   276       if (NS_SUCCEEDED(rv)) {
   277         file.forget(reinterpret_cast<nsIFile**>(_retval));
   278         return NS_OK;
   279       }
   280     }
   281     return rv;
   282   }
   284   if (aType.Equals(NS_GET_IID(nsIRelativeFilePref))) {
   285     if (GetContentChild()) {
   286       NS_ERROR("cannot get nsIRelativeFilePref from content process");
   287       return NS_ERROR_NOT_AVAILABLE;
   288     }
   290     nsACString::const_iterator keyBegin, strEnd;
   291     utf8String.BeginReading(keyBegin);
   292     utf8String.EndReading(strEnd);    
   294     // The pref has the format: [fromKey]a/b/c
   295     if (*keyBegin++ != '[')        
   296       return NS_ERROR_FAILURE;
   297     nsACString::const_iterator keyEnd(keyBegin);
   298     if (!FindCharInReadable(']', keyEnd, strEnd))
   299       return NS_ERROR_FAILURE;
   300     nsAutoCString key(Substring(keyBegin, keyEnd));
   302     nsCOMPtr<nsIFile> fromFile;
   303     nsCOMPtr<nsIProperties> directoryService(do_GetService(NS_DIRECTORY_SERVICE_CONTRACTID, &rv));
   304     if (NS_FAILED(rv))
   305       return rv;
   306     rv = directoryService->Get(key.get(), NS_GET_IID(nsIFile), getter_AddRefs(fromFile));
   307     if (NS_FAILED(rv))
   308       return rv;
   310     nsCOMPtr<nsIFile> theFile;
   311     rv = NS_NewNativeLocalFile(EmptyCString(), true, getter_AddRefs(theFile));
   312     if (NS_FAILED(rv))
   313       return rv;
   314     rv = theFile->SetRelativeDescriptor(fromFile, Substring(++keyEnd, strEnd));
   315     if (NS_FAILED(rv))
   316       return rv;
   317     nsCOMPtr<nsIRelativeFilePref> relativePref;
   318     rv = NS_NewRelativeFilePref(theFile, key, getter_AddRefs(relativePref));
   319     if (NS_FAILED(rv))
   320       return rv;
   322     relativePref.forget(reinterpret_cast<nsIRelativeFilePref**>(_retval));
   323     return NS_OK;
   324   }
   326   if (aType.Equals(NS_GET_IID(nsISupportsString))) {
   327     nsCOMPtr<nsISupportsString> theString(do_CreateInstance(NS_SUPPORTS_STRING_CONTRACTID, &rv));
   329     if (NS_SUCCEEDED(rv)) {
   330       // Debugging to see why we end up with very long strings here with
   331       // some addons, see bug 836263.
   332       nsAutoString wdata;
   333       if (!AppendUTF8toUTF16(utf8String, wdata, mozilla::fallible_t())) {
   334 #ifdef MOZ_CRASHREPORTER
   335         nsCOMPtr<nsICrashReporter> cr =
   336           do_GetService("@mozilla.org/toolkit/crash-reporter;1");
   337         if (cr) {
   338           cr->AnnotateCrashReport(NS_LITERAL_CSTRING("bug836263-size"),
   339                                   nsPrintfCString("%x", utf8String.Length()));
   340           cr->RegisterAppMemory(uint64_t(utf8String.BeginReading()),
   341                                 std::min(0x1000U, utf8String.Length()));
   342         }
   343 #endif
   344         NS_RUNTIMEABORT("bug836263");
   345       }
   346       theString->SetData(wdata);
   347       theString.forget(reinterpret_cast<nsISupportsString**>(_retval));
   348     }
   349     return rv;
   350   }
   352   NS_WARNING("nsPrefBranch::GetComplexValue - Unsupported interface type");
   353   return NS_NOINTERFACE;
   354 }
   356 nsresult nsPrefBranch::CheckSanityOfStringLength(const char* aPrefName, const char* aValue) {
   357   if (!aValue) {
   358     return NS_OK;
   359   }
   360   return CheckSanityOfStringLength(aPrefName, strlen(aValue));
   361 }
   363 nsresult nsPrefBranch::CheckSanityOfStringLength(const char* aPrefName, const nsAString& aValue) {
   364   return CheckSanityOfStringLength(aPrefName, aValue.Length());
   365 }
   367 nsresult nsPrefBranch::CheckSanityOfStringLength(const char* aPrefName, const uint32_t aLength) {
   368   if (aLength > MAX_PREF_LENGTH) {
   369     return NS_ERROR_ILLEGAL_VALUE;
   370   }
   371   if (aLength <= MAX_ADVISABLE_PREF_LENGTH) {
   372     return NS_OK;
   373   }
   374   nsresult rv;
   375   nsCOMPtr<nsIConsoleService> console = do_GetService("@mozilla.org/consoleservice;1", &rv);
   376   if (NS_FAILED(rv)) {
   377     return rv;
   378   }
   379   nsAutoCString message(nsPrintfCString("Warning: attempting to write %d bytes to preference %s. This is bad for general performance and memory usage. Such an amount of data should rather be written to an external file.",
   380                                         aLength,
   381                                         aPrefName));
   382   rv = console->LogStringMessage(NS_ConvertUTF8toUTF16(message).get());
   383   if (NS_FAILED(rv)) {
   384     return rv;
   385   }
   386   return NS_OK;
   387 }
   390 NS_IMETHODIMP nsPrefBranch::SetComplexValue(const char *aPrefName, const nsIID & aType, nsISupports *aValue)
   391 {
   392   ENSURE_MAIN_PROCESS("Cannot SetComplexValue from content process:", aPrefName);
   393   NS_ENSURE_ARG(aPrefName);
   395   nsresult   rv = NS_NOINTERFACE;
   397   // also check nsILocalFile, for backwards compatibility
   398   if (aType.Equals(NS_GET_IID(nsIFile)) || aType.Equals(NS_GET_IID(nsILocalFile))) {
   399     nsCOMPtr<nsIFile> file = do_QueryInterface(aValue);
   400     if (!file)
   401       return NS_NOINTERFACE;
   402     nsAutoCString descriptorString;
   404     rv = file->GetPersistentDescriptor(descriptorString);
   405     if (NS_SUCCEEDED(rv)) {
   406       rv = SetCharPrefInternal(aPrefName, descriptorString.get());
   407     }
   408     return rv;
   409   }
   411   if (aType.Equals(NS_GET_IID(nsIRelativeFilePref))) {
   412     nsCOMPtr<nsIRelativeFilePref> relFilePref = do_QueryInterface(aValue);
   413     if (!relFilePref)
   414       return NS_NOINTERFACE;
   416     nsCOMPtr<nsIFile> file;
   417     relFilePref->GetFile(getter_AddRefs(file));
   418     if (!file)
   419       return NS_NOINTERFACE;
   420     nsAutoCString relativeToKey;
   421     (void) relFilePref->GetRelativeToKey(relativeToKey);
   423     nsCOMPtr<nsIFile> relativeToFile;
   424     nsCOMPtr<nsIProperties> directoryService(do_GetService(NS_DIRECTORY_SERVICE_CONTRACTID, &rv));
   425     if (NS_FAILED(rv))
   426       return rv;
   427     rv = directoryService->Get(relativeToKey.get(), NS_GET_IID(nsIFile), getter_AddRefs(relativeToFile));
   428     if (NS_FAILED(rv))
   429       return rv;
   431     nsAutoCString relDescriptor;
   432     rv = file->GetRelativeDescriptor(relativeToFile, relDescriptor);
   433     if (NS_FAILED(rv))
   434       return rv;
   436     nsAutoCString descriptorString;
   437     descriptorString.Append('[');
   438     descriptorString.Append(relativeToKey);
   439     descriptorString.Append(']');
   440     descriptorString.Append(relDescriptor);
   441     return SetCharPrefInternal(aPrefName, descriptorString.get());
   442   }
   444   if (aType.Equals(NS_GET_IID(nsISupportsString))) {
   445     nsCOMPtr<nsISupportsString> theString = do_QueryInterface(aValue);
   447     if (theString) {
   448       nsString wideString;
   450       rv = theString->GetData(wideString);
   451       if (NS_SUCCEEDED(rv)) {
   452         // Check sanity of string length before any lengthy conversion
   453         rv = CheckSanityOfStringLength(aPrefName, wideString);
   454         if (NS_FAILED(rv)) {
   455           return rv;
   456         }
   457         rv = SetCharPrefInternal(aPrefName, NS_ConvertUTF16toUTF8(wideString).get());
   458       }
   459     }
   460     return rv;
   461   }
   463   if (aType.Equals(NS_GET_IID(nsIPrefLocalizedString))) {
   464     nsCOMPtr<nsIPrefLocalizedString> theString = do_QueryInterface(aValue);
   466     if (theString) {
   467       nsXPIDLString wideString;
   469       rv = theString->GetData(getter_Copies(wideString));
   470       if (NS_SUCCEEDED(rv)) {
   471         // Check sanity of string length before any lengthy conversion
   472         rv = CheckSanityOfStringLength(aPrefName, wideString);
   473         if (NS_FAILED(rv)) {
   474           return rv;
   475         }
   476         rv = SetCharPrefInternal(aPrefName, NS_ConvertUTF16toUTF8(wideString).get());
   477       }
   478     }
   479     return rv;
   480   }
   482   NS_WARNING("nsPrefBranch::SetComplexValue - Unsupported interface type");
   483   return NS_NOINTERFACE;
   484 }
   486 NS_IMETHODIMP nsPrefBranch::ClearUserPref(const char *aPrefName)
   487 {
   488   ENSURE_MAIN_PROCESS("Cannot ClearUserPref from content process:", aPrefName);
   489   NS_ENSURE_ARG(aPrefName);
   490   const char *pref = getPrefName(aPrefName);
   491   return PREF_ClearUserPref(pref);
   492 }
   494 NS_IMETHODIMP nsPrefBranch::PrefHasUserValue(const char *aPrefName, bool *_retval)
   495 {
   496   NS_ENSURE_ARG_POINTER(_retval);
   497   NS_ENSURE_ARG(aPrefName);
   498   const char *pref = getPrefName(aPrefName);
   499   *_retval = PREF_HasUserPref(pref);
   500   return NS_OK;
   501 }
   503 NS_IMETHODIMP nsPrefBranch::LockPref(const char *aPrefName)
   504 {
   505   ENSURE_MAIN_PROCESS("Cannot LockPref from content process:", aPrefName);
   506   NS_ENSURE_ARG(aPrefName);
   507   const char *pref = getPrefName(aPrefName);
   508   return PREF_LockPref(pref, true);
   509 }
   511 NS_IMETHODIMP nsPrefBranch::PrefIsLocked(const char *aPrefName, bool *_retval)
   512 {
   513   ENSURE_MAIN_PROCESS("Cannot check PrefIsLocked from content process:", aPrefName);
   514   NS_ENSURE_ARG_POINTER(_retval);
   515   NS_ENSURE_ARG(aPrefName);
   516   const char *pref = getPrefName(aPrefName);
   517   *_retval = PREF_PrefIsLocked(pref);
   518   return NS_OK;
   519 }
   521 NS_IMETHODIMP nsPrefBranch::UnlockPref(const char *aPrefName)
   522 {
   523   ENSURE_MAIN_PROCESS("Cannot UnlockPref from content process:", aPrefName);
   524   NS_ENSURE_ARG(aPrefName);
   525   const char *pref = getPrefName(aPrefName);
   526   return PREF_LockPref(pref, false);
   527 }
   529 /* void resetBranch (in string startingAt); */
   530 NS_IMETHODIMP nsPrefBranch::ResetBranch(const char *aStartingAt)
   531 {
   532   return NS_ERROR_NOT_IMPLEMENTED;
   533 }
   535 NS_IMETHODIMP nsPrefBranch::DeleteBranch(const char *aStartingAt)
   536 {
   537   ENSURE_MAIN_PROCESS("Cannot DeleteBranch from content process:", aStartingAt);
   538   NS_ENSURE_ARG(aStartingAt);
   539   const char *pref = getPrefName(aStartingAt);
   540   return PREF_DeleteBranch(pref);
   541 }
   543 NS_IMETHODIMP nsPrefBranch::GetChildList(const char *aStartingAt, uint32_t *aCount, char ***aChildArray)
   544 {
   545   char            **outArray;
   546   int32_t         numPrefs;
   547   int32_t         dwIndex;
   548   EnumerateData   ed;
   549   nsAutoTArray<nsCString, 32> prefArray;
   551   NS_ENSURE_ARG(aStartingAt);
   552   NS_ENSURE_ARG_POINTER(aCount);
   553   NS_ENSURE_ARG_POINTER(aChildArray);
   555   *aChildArray = nullptr;
   556   *aCount = 0;
   558   if (!gHashTable.ops)
   559     return NS_ERROR_NOT_INITIALIZED;
   561   // this will contain a list of all the pref name strings
   562   // allocate on the stack for speed
   564   ed.parent = getPrefName(aStartingAt);
   565   ed.pref_list = &prefArray;
   566   PL_DHashTableEnumerate(&gHashTable, pref_enumChild, &ed);
   568   // now that we've built up the list, run the callback on
   569   // all the matching elements
   570   numPrefs = prefArray.Length();
   572   if (numPrefs) {
   573     outArray = (char **)nsMemory::Alloc(numPrefs * sizeof(char *));
   574     if (!outArray)
   575       return NS_ERROR_OUT_OF_MEMORY;
   577     for (dwIndex = 0; dwIndex < numPrefs; ++dwIndex) {
   578       // we need to lop off mPrefRoot in case the user is planning to pass this
   579       // back to us because if they do we are going to add mPrefRoot again.
   580       const nsCString& element = prefArray[dwIndex];
   581       outArray[dwIndex] = (char *)nsMemory::Clone(
   582         element.get() + mPrefRootLength, element.Length() - mPrefRootLength + 1);
   584       if (!outArray[dwIndex]) {
   585         // we ran out of memory... this is annoying
   586         NS_FREE_XPCOM_ALLOCATED_POINTER_ARRAY(dwIndex, outArray);
   587         return NS_ERROR_OUT_OF_MEMORY;
   588       }
   589     }
   590     *aChildArray = outArray;
   591   }
   592   *aCount = numPrefs;
   594   return NS_OK;
   595 }
   597 NS_IMETHODIMP nsPrefBranch::AddObserver(const char *aDomain, nsIObserver *aObserver, bool aHoldWeak)
   598 {
   599   PrefCallback *pCallback;
   600   const char *pref;
   602   NS_ENSURE_ARG(aDomain);
   603   NS_ENSURE_ARG(aObserver);
   605   // hold a weak reference to the observer if so requested
   606   if (aHoldWeak) {
   607     nsCOMPtr<nsISupportsWeakReference> weakRefFactory = do_QueryInterface(aObserver);
   608     if (!weakRefFactory) {
   609       // the caller didn't give us a object that supports weak reference... tell them
   610       return NS_ERROR_INVALID_ARG;
   611     }
   613     // Construct a PrefCallback with a weak reference to the observer.
   614     pCallback = new PrefCallback(aDomain, weakRefFactory, this);
   616   } else {
   617     // Construct a PrefCallback with a strong reference to the observer.
   618     pCallback = new PrefCallback(aDomain, aObserver, this);
   619   }
   621   if (mObservers.Get(pCallback)) {
   622     NS_WARNING("Ignoring duplicate observer.");
   623     delete pCallback;
   624     return NS_OK;
   625   }
   627   mObservers.Put(pCallback, pCallback);
   629   // We must pass a fully qualified preference name to the callback
   630   // aDomain == nullptr is the only possible failure, and we trapped it with
   631   // NS_ENSURE_ARG above.
   632   pref = getPrefName(aDomain);
   633   PREF_RegisterCallback(pref, NotifyObserver, pCallback);
   634   return NS_OK;
   635 }
   637 NS_IMETHODIMP nsPrefBranch::RemoveObserver(const char *aDomain, nsIObserver *aObserver)
   638 {
   639   NS_ENSURE_ARG(aDomain);
   640   NS_ENSURE_ARG(aObserver);
   642   nsresult rv = NS_OK;
   644   // If we're in the middle of a call to freeObserverList, don't process this
   645   // RemoveObserver call -- the observer in question will be removed soon, if
   646   // it hasn't been already.
   647   //
   648   // It's important that we don't touch mObservers in any way -- even a Get()
   649   // which retuns null might cause the hashtable to resize itself, which will
   650   // break the Enumerator in freeObserverList.
   651   if (mFreeingObserverList)
   652     return NS_OK;
   654   // Remove the relevant PrefCallback from mObservers and get an owning
   655   // pointer to it.  Unregister the callback first, and then let the owning
   656   // pointer go out of scope and destroy the callback.
   657   PrefCallback key(aDomain, aObserver, this);
   658   nsAutoPtr<PrefCallback> pCallback;
   659   mObservers.RemoveAndForget(&key, pCallback);
   660   if (pCallback) {
   661     // aDomain == nullptr is the only possible failure, trapped above
   662     const char *pref = getPrefName(aDomain);
   663     rv = PREF_UnregisterCallback(pref, NotifyObserver, pCallback);
   664   }
   666   return rv;
   667 }
   669 NS_IMETHODIMP nsPrefBranch::Observe(nsISupports *aSubject, const char *aTopic, const char16_t *someData)
   670 {
   671   // watch for xpcom shutdown and free our observers to eliminate any cyclic references
   672   if (!nsCRT::strcmp(aTopic, NS_XPCOM_SHUTDOWN_OBSERVER_ID)) {
   673     freeObserverList();
   674   }
   675   return NS_OK;
   676 }
   678 /* static */
   679 void nsPrefBranch::NotifyObserver(const char *newpref, void *data)
   680 {
   681   PrefCallback *pCallback = (PrefCallback *)data;
   683   nsCOMPtr<nsIObserver> observer = pCallback->GetObserver();
   684   if (!observer) {
   685     // The observer has expired.  Let's remove this callback.
   686     pCallback->GetPrefBranch()->RemoveExpiredCallback(pCallback);
   687     return;
   688   }
   690   // remove any root this string may contain so as to not confuse the observer
   691   // by passing them something other than what they passed us as a topic
   692   uint32_t len = pCallback->GetPrefBranch()->GetRootLength();
   693   nsAutoCString suffix(newpref + len);
   695   observer->Observe(static_cast<nsIPrefBranch *>(pCallback->GetPrefBranch()),
   696                     NS_PREFBRANCH_PREFCHANGE_TOPIC_ID,
   697                     NS_ConvertASCIItoUTF16(suffix).get());
   698 }
   700 PLDHashOperator
   701 FreeObserverFunc(PrefCallback *aKey,
   702                  nsAutoPtr<PrefCallback> &aCallback,
   703                  void *aArgs)
   704 {
   705   // Calling NS_RELEASE below might trigger a call to
   706   // nsPrefBranch::RemoveObserver, since some classes remove themselves from
   707   // the pref branch on destruction.  We don't need to worry about this causing
   708   // double-frees, however, because freeObserverList sets mFreeingObserverList
   709   // to true, which prevents RemoveObserver calls from doing anything.
   711   nsPrefBranch *prefBranch = aCallback->GetPrefBranch();
   712   const char *pref = prefBranch->getPrefName(aCallback->GetDomain().get());
   713   PREF_UnregisterCallback(pref, nsPrefBranch::NotifyObserver, aCallback);
   715   return PL_DHASH_REMOVE;
   716 }
   718 void nsPrefBranch::freeObserverList(void)
   719 {
   720   // We need to prevent anyone from modifying mObservers while we're
   721   // enumerating over it.  In particular, some clients will call
   722   // RemoveObserver() when they're destructed; we need to keep those calls from
   723   // touching mObservers.
   724   mFreeingObserverList = true;
   725   mObservers.Enumerate(&FreeObserverFunc, nullptr);
   726   mFreeingObserverList = false;
   727 }
   729 void
   730 nsPrefBranch::RemoveExpiredCallback(PrefCallback *aCallback)
   731 {
   732   NS_PRECONDITION(aCallback->IsExpired(), "Callback should be expired.");
   733   mObservers.Remove(aCallback);
   734 }
   736 nsresult nsPrefBranch::GetDefaultFromPropertiesFile(const char *aPrefName, char16_t **return_buf)
   737 {
   738   nsresult rv;
   740   // the default value contains a URL to a .properties file
   742   nsXPIDLCString propertyFileURL;
   743   rv = PREF_CopyCharPref(aPrefName, getter_Copies(propertyFileURL), true);
   744   if (NS_FAILED(rv))
   745     return rv;
   747   nsCOMPtr<nsIStringBundleService> bundleService =
   748     mozilla::services::GetStringBundleService();
   749   if (!bundleService)
   750     return NS_ERROR_FAILURE;
   752   nsCOMPtr<nsIStringBundle> bundle;
   753   rv = bundleService->CreateBundle(propertyFileURL,
   754                                    getter_AddRefs(bundle));
   755   if (NS_FAILED(rv))
   756     return rv;
   758   // string names are in unicode
   759   nsAutoString stringId;
   760   stringId.AssignASCII(aPrefName);
   762   return bundle->GetStringFromName(stringId.get(), return_buf);
   763 }
   765 const char *nsPrefBranch::getPrefName(const char *aPrefName)
   766 {
   767   NS_ASSERTION(aPrefName, "null pref name!");
   769   // for speed, avoid strcpy if we can:
   770   if (mPrefRoot.IsEmpty())
   771     return aPrefName;
   773   // isn't there a better way to do this? this is really kind of gross.
   774   mPrefRoot.Truncate(mPrefRootLength);
   775   mPrefRoot.Append(aPrefName);
   776   return mPrefRoot.get();
   777 }
   779 static PLDHashOperator
   780 pref_enumChild(PLDHashTable *table, PLDHashEntryHdr *heh,
   781                uint32_t i, void *arg)
   782 {
   783   PrefHashEntry *he = static_cast<PrefHashEntry*>(heh);
   784   EnumerateData *d = reinterpret_cast<EnumerateData *>(arg);
   785   if (strncmp(he->key, d->parent, strlen(d->parent)) == 0) {
   786     d->pref_list->AppendElement(he->key);
   787   }
   788   return PL_DHASH_NEXT;
   789 }
   791 //----------------------------------------------------------------------------
   792 // nsPrefLocalizedString
   793 //----------------------------------------------------------------------------
   795 nsPrefLocalizedString::nsPrefLocalizedString()
   796 {
   797 }
   799 nsPrefLocalizedString::~nsPrefLocalizedString()
   800 {
   801 }
   804 /*
   805  * nsISupports Implementation
   806  */
   808 NS_IMPL_ADDREF(nsPrefLocalizedString)
   809 NS_IMPL_RELEASE(nsPrefLocalizedString)
   811 NS_INTERFACE_MAP_BEGIN(nsPrefLocalizedString)
   812     NS_INTERFACE_MAP_ENTRY_AMBIGUOUS(nsISupports, nsIPrefLocalizedString)
   813     NS_INTERFACE_MAP_ENTRY(nsIPrefLocalizedString)
   814     NS_INTERFACE_MAP_ENTRY(nsISupportsString)
   815 NS_INTERFACE_MAP_END
   817 nsresult nsPrefLocalizedString::Init()
   818 {
   819   nsresult rv;
   820   mUnicodeString = do_CreateInstance(NS_SUPPORTS_STRING_CONTRACTID, &rv);
   822   return rv;
   823 }
   825 NS_IMETHODIMP
   826 nsPrefLocalizedString::GetData(char16_t **_retval)
   827 {
   828   nsAutoString data;
   830   nsresult rv = GetData(data);
   831   if (NS_FAILED(rv))
   832     return rv;
   834   *_retval = ToNewUnicode(data);
   835   if (!*_retval)
   836     return NS_ERROR_OUT_OF_MEMORY;
   838   return NS_OK;
   839 }
   841 NS_IMETHODIMP
   842 nsPrefLocalizedString::SetData(const char16_t *aData)
   843 {
   844   if (!aData)
   845     return SetData(EmptyString());
   846   return SetData(nsDependentString(aData));
   847 }
   849 NS_IMETHODIMP
   850 nsPrefLocalizedString::SetDataWithLength(uint32_t aLength,
   851                                          const char16_t *aData)
   852 {
   853   if (!aData)
   854     return SetData(EmptyString());
   855   return SetData(Substring(aData, aLength));
   856 }
   858 //----------------------------------------------------------------------------
   859 // nsRelativeFilePref
   860 //----------------------------------------------------------------------------
   862 NS_IMPL_ISUPPORTS(nsRelativeFilePref, nsIRelativeFilePref)
   864 nsRelativeFilePref::nsRelativeFilePref()
   865 {
   866 }
   868 nsRelativeFilePref::~nsRelativeFilePref()
   869 {
   870 }
   872 NS_IMETHODIMP nsRelativeFilePref::GetFile(nsIFile **aFile)
   873 {
   874   NS_ENSURE_ARG_POINTER(aFile);
   875   *aFile = mFile;
   876   NS_IF_ADDREF(*aFile);
   877   return NS_OK;
   878 }
   880 NS_IMETHODIMP nsRelativeFilePref::SetFile(nsIFile *aFile)
   881 {
   882   mFile = aFile;
   883   return NS_OK;
   884 }
   886 NS_IMETHODIMP nsRelativeFilePref::GetRelativeToKey(nsACString& aRelativeToKey)
   887 {
   888   aRelativeToKey.Assign(mRelativeToKey);
   889   return NS_OK;
   890 }
   892 NS_IMETHODIMP nsRelativeFilePref::SetRelativeToKey(const nsACString& aRelativeToKey)
   893 {
   894   mRelativeToKey.Assign(aRelativeToKey);
   895   return NS_OK;
   896 }
   898 #undef ENSURE_MAIN_PROCESS

mercurial