/* void getInterfaces (out PRUint32 count, [array, size_is (count),
   retval] out nsIIDPtr array); */
NS_IMETHODIMP
WSPProxy::GetInterfaces(PRUint32 *count, nsIID * **array)
{
  if (!mIID) {
    return NS_ERROR_NOT_INITIALIZED;
  }

  *count = 2;
  nsIID** iids = static_cast<nsIID**>(nsMemory::Alloc(2 * sizeof(nsIID*)));
  if (!iids) {
    return NS_ERROR_OUT_OF_MEMORY;
  }

  iids[0] = static_cast<nsIID *>(nsMemory::Clone(mIID, sizeof(nsIID)));
  if (NS_UNLIKELY(!iids[0])) {
    NS_FREE_XPCOM_ALLOCATED_POINTER_ARRAY(0, iids);
    return NS_ERROR_OUT_OF_MEMORY;
  }
  const nsIID& wsiid = NS_GET_IID(nsIWebServiceProxy);
  iids[1] = static_cast<nsIID *>(nsMemory::Clone(&wsiid, sizeof(nsIID)));
  if (NS_UNLIKELY(!iids[1])) {
    NS_FREE_XPCOM_ALLOCATED_POINTER_ARRAY(1, iids);
    return NS_ERROR_OUT_OF_MEMORY;
  }

  *array = iids;

  return NS_OK;
}
/* void Suggest (in wstring word, [array, size_is (count)] out wstring suggestions, out PRUint32 count); */
NS_IMETHODIMP mozHunspell::Suggest(const PRUnichar *aWord, PRUnichar ***aSuggestions, PRUint32 *aSuggestionCount)
{
  NS_ENSURE_ARG_POINTER(aSuggestions);
  NS_ENSURE_ARG_POINTER(aSuggestionCount);
  NS_ENSURE_TRUE(mHunspell, NS_ERROR_FAILURE);

  nsresult rv;
  *aSuggestionCount = 0;

  nsXPIDLCString charsetWord;
  rv = ConvertCharset(aWord, getter_Copies(charsetWord));
  NS_ENSURE_SUCCESS(rv, rv);

  char ** wlst;
  *aSuggestionCount = mHunspell->suggest(&wlst, charsetWord);

  if (*aSuggestionCount) {
    *aSuggestions  = (PRUnichar **)nsMemory::Alloc(*aSuggestionCount * sizeof(PRUnichar *));
    if (*aSuggestions) {
      PRUint32 index = 0;
      for (index = 0; index < *aSuggestionCount && NS_SUCCEEDED(rv); ++index) {
        // Convert the suggestion to utf16
        PRInt32 inLength = nsCRT::strlen(wlst[index]);
        PRInt32 outLength;
        rv = mDecoder->GetMaxLength(wlst[index], inLength, &outLength);
        if (NS_SUCCEEDED(rv))
        {
          (*aSuggestions)[index] = (PRUnichar *) nsMemory::Alloc(sizeof(PRUnichar) * (outLength+1));
          if ((*aSuggestions)[index])
          {
            rv = mDecoder->Convert(wlst[index], &inLength, (*aSuggestions)[index], &outLength);
            if (NS_SUCCEEDED(rv))
              (*aSuggestions)[index][outLength] = 0;
          }
          else
            rv = NS_ERROR_OUT_OF_MEMORY;
        }
      }

      if (NS_FAILED(rv))
        NS_FREE_XPCOM_ALLOCATED_POINTER_ARRAY(index, *aSuggestions); // free the PRUnichar strings up to the point at which the error occurred
    }
    else // if (*aSuggestions)
      rv = NS_ERROR_OUT_OF_MEMORY;
  }

  NS_FREE_XPCOM_ALLOCATED_POINTER_ARRAY(*aSuggestionCount, wlst);
  return rv;
}
NS_IMETHODIMP
nsDOMOfflineResourceList::GetMozItems(nsIDOMDOMStringList **aItems)
{
  *aItems = nsnull;

  nsRefPtr<nsDOMStringList> items = new nsDOMStringList();
  NS_ENSURE_TRUE(items, NS_ERROR_OUT_OF_MEMORY);

  // If we are not associated with an application cache, return an
  // empty list.
  nsCOMPtr<nsIApplicationCache> appCache = GetDocumentAppCache();
  if (!appCache) {
    NS_ADDREF(*aItems = items);
    return NS_OK;
  }

  nsresult rv = Init();
  NS_ENSURE_SUCCESS(rv, rv);

  PRUint32 length;
  char **keys;
  rv = appCache->GatherEntries(nsIApplicationCache::ITEM_DYNAMIC,
                               &length, &keys);
  NS_ENSURE_SUCCESS(rv, rv);

  for (PRUint32 i = 0; i < length; i++) {
    items->Add(NS_ConvertUTF8toUTF16(keys[i]));
  }

  NS_FREE_XPCOM_ALLOCATED_POINTER_ARRAY(length, keys);

  NS_ADDREF(*aItems = items);
  return NS_OK;
}
Exemple #4
0
NS_IMETHODIMP
nsMsgAccount::ClearAllValues()
{
    nsresult rv;
    nsCAutoString rootPref("mail.account.");
    rootPref += m_accountKey;
    rootPref += '.';

    rv = getPrefService();
    if (NS_FAILED(rv))
        return rv;

    PRUint32 cntChild, i;
    char **childArray;
 
    rv = m_prefs->GetChildList(rootPref.get(), &cntChild, &childArray);
    if (NS_SUCCEEDED(rv)) {
        for (i = 0; i < cntChild; i++)
            m_prefs->ClearUserPref(childArray[i]);

        NS_FREE_XPCOM_ALLOCATED_POINTER_ARRAY(cntChild, childArray);
    }

    return rv;
}
Exemple #5
0
void
nsHyphenationManager::LoadAliases()
{
  nsresult rv;
  nsCOMPtr<nsIPrefBranch> prefBranch =
    do_GetService(NS_PREFSERVICE_CONTRACTID, &rv);
  if (NS_FAILED(rv)) {
    return;
  }
  PRUint32 prefCount;
  char **prefNames;
  rv = prefBranch->GetChildList(INTL_HYPHENATIONALIAS_PREFIX,
                                &prefCount, &prefNames);
  if (NS_SUCCEEDED(rv) && prefCount > 0) {
    for (PRUint32 i = 0; i < prefCount; ++i) {
      char *prefValue;
      rv = prefBranch->GetCharPref(prefNames[i], &prefValue);
      if (NS_SUCCEEDED(rv)) {
        nsCAutoString alias(prefNames[i]);
        alias.Cut(0, strlen(INTL_HYPHENATIONALIAS_PREFIX));
        ToLowerCase(alias);
        nsCAutoString value(prefValue);
        ToLowerCase(value);
        nsCOMPtr<nsIAtom> aliasAtom = do_GetAtom(alias);
        nsCOMPtr<nsIAtom> valueAtom = do_GetAtom(value);
        mHyphAliases.Put(aliasAtom, valueAtom);
        NS_Free(prefValue);
      }
    }
    NS_FREE_XPCOM_ALLOCATED_POINTER_ARRAY(prefCount, prefNames);
  }
}
NS_IMETHODIMP 
mozSpellChecker::CheckWord(const nsAString &aWord, bool *aIsMisspelled, nsTArray<nsString> *aSuggestions)
{
  nsresult result;
  bool correct;
  if(!mSpellCheckingEngine)
    return NS_ERROR_NULL_POINTER;

  *aIsMisspelled = false;
  result = mSpellCheckingEngine->Check(PromiseFlatString(aWord).get(), &correct);
  NS_ENSURE_SUCCESS(result, result);
  if(!correct){
    if(aSuggestions){
      uint32_t count,i;
      PRUnichar **words;
      
      result = mSpellCheckingEngine->Suggest(PromiseFlatString(aWord).get(), &words, &count);
      NS_ENSURE_SUCCESS(result, result); 
      for(i=0;i<count;i++){
        aSuggestions->AppendElement(nsDependentString(words[i]));
      }
      
      if (count)
        NS_FREE_XPCOM_ALLOCATED_POINTER_ARRAY(count, words);
    }
    *aIsMisspelled = true;
  }
  return NS_OK;
}
Exemple #7
0
static nsresult dir_GetPrefs(nsVoidArray **list)
{
    nsresult rv;
    nsCOMPtr<nsIPrefBranch> pPref(do_GetService(NS_PREFSERVICE_CONTRACTID, &rv));
    if (NS_FAILED(rv))
        return rv;

    (*list) = new nsVoidArray();
    if (!(*list))
        return NS_ERROR_OUT_OF_MEMORY;

    char **children;
    PRUint32 prefCount;

    rv = dir_GetChildList(NS_LITERAL_CSTRING(PREF_LDAP_SERVER_TREE_NAME "."),
                          &prefCount, &children);
    if (NS_FAILED(rv))
        return rv;

    /* TBD: Temporary code to read broken "ldap" preferences tree.
     *      Remove line with if statement after M10.
     */
    if (dir_UserId == 0)
        pPref->GetIntPref(PREF_LDAP_GLOBAL_TREE_NAME".user_id", &dir_UserId);

    for (PRUint32 i = 0; i < prefCount; ++i)
    {
        DIR_Server *server;

        server = (DIR_Server *)PR_Calloc(1, sizeof(DIR_Server));
        if (server)
        {
            DIR_InitServer(server);
            server->prefName = strdup(children[i]);
            DIR_GetPrefsForOneServer(server);
            if (server->description && server->description[0] && 
                ((server->dirType == PABDirectory ||
                  server->dirType == IMDirectory ||
                  server->dirType == MAPIDirectory ||
                  server->dirType == FixedQueryLDAPDirectory ||  // this one might go away
                  server->dirType == LDAPDirectory)))
            {
                if (!dir_IsServerDeleted(server))
                {
                    (*list)->AppendElement(server);
                }
                else
                    DIR_DeleteServer(server);
            }
            else
            {
                DIR_DeleteServer(server);
            }
        }
    }

    NS_FREE_XPCOM_ALLOCATED_POINTER_ARRAY(prefCount, children);

    return NS_OK;
}
Exemple #8
0
nsresult nsAbLDAPDirectory::SplitStringList(
    const nsACString& aString,
    PRUint32 *aCount,
    char ***aValues)
{
    NS_ENSURE_ARG_POINTER(aCount);
    NS_ENSURE_ARG_POINTER(aValues);

    nsTArray<nsCString> strarr;
    ParseString(aString, ',', strarr);

    char **cArray = nsnull;
    if (!(cArray = static_cast<char **>(nsMemory::Alloc(
                                            strarr.Length() * sizeof(char *)))))
        return NS_ERROR_OUT_OF_MEMORY;

    for (PRUint32 i = 0; i < strarr.Length(); ++i)
    {
        if (!(cArray[i] = ToNewCString(strarr[i])))
        {
            NS_FREE_XPCOM_ALLOCATED_POINTER_ARRAY(strarr.Length(), cArray);
            return NS_ERROR_OUT_OF_MEMORY;
        }
    }

    *aCount = strarr.Length();
    *aValues = cArray;
    return NS_OK;
}
/* void getKeyForTag (in wstring tag); */
NS_IMETHODIMP nsMsgTagService::GetKeyForTag(const nsAString &aTag, nsACString &aKey)
{
  uint32_t count;
  char **prefList;
  nsresult rv = m_tagPrefBranch->GetChildList("", &count, &prefList);
  NS_ENSURE_SUCCESS(rv, rv);
  // traverse the list, and look for a pref with the desired tag value.
  for (uint32_t i = count; i--;)
  {
    // We are returned the tag prefs in the form "<key>.<tag_data_type>", but
    // since we only want the tags, just check that the string ends with "tag".
    nsDependentCString prefName(prefList[i]);
    if (StringEndsWith(prefName, NS_LITERAL_CSTRING(TAG_PREF_SUFFIX_TAG)))
    {
      nsAutoString curTag;
      GetUnicharPref(prefList[i], curTag);
      if (aTag.Equals(curTag))
      {
        aKey = Substring(prefName, 0, prefName.Length() - STRLEN(TAG_PREF_SUFFIX_TAG));
        break;
      }
    }
  }
  NS_FREE_XPCOM_ALLOCATED_POINTER_ARRAY(count, prefList);
  ToLowerCase(aKey);
  return NS_OK;
}
nsresult
nsLDAPSyncQuery::OnLDAPSearchEntry(nsILDAPMessage *aMessage)
{
  uint32_t attrCount;
  char** attributes;
  nsresult rv = aMessage->GetAttributes(&attrCount, &attributes);
  if (NS_FAILED(rv))
  {
    NS_WARNING("nsLDAPSyncQuery:OnLDAPSearchEntry(): "
               "aMessage->GetAttributes() failed");
    FinishLDAPQuery();
    return rv;
  }

  // Iterate through the attributes received in this message
  for (uint32_t i = 0; i < attrCount; i++)
  {
    PRUnichar **vals;
    uint32_t valueCount;

    // Get the values of this attribute.
    // XXX better failure handling
    rv = aMessage->GetValues(attributes[i], &valueCount, &vals);
    if (NS_FAILED(rv))
    {
      NS_WARNING("nsLDAPSyncQuery:OnLDAPSearchEntry(): "
                 "aMessage->GetValues() failed\n");
      FinishLDAPQuery();
      break;
    }

    // Store all values of this attribute in the mResults.
    for (uint32_t j = 0; j < valueCount; j++) {
      mResults.Append(PRUnichar('\n'));
      mResults.AppendASCII(attributes[i]);
      mResults.Append(PRUnichar('='));
      mResults.Append(vals[j]);
    }

    NS_FREE_XPCOM_ALLOCATED_POINTER_ARRAY(valueCount, vals);
  }
  NS_FREE_XPCOM_ALLOCATED_POINTER_ARRAY(attrCount, attributes);

  return rv;
}
void
nsDOMOfflineResourceList::ClearCachedKeys()
{
  if (mCachedKeys) {
    NS_FREE_XPCOM_ALLOCATED_POINTER_ARRAY(mCachedKeysCount, mCachedKeys);
    mCachedKeys = nsnull;
    mCachedKeysCount = 0;
  }
}
NS_IMETHODIMP 
mozSpellChecker::GetDictionaryList(nsTArray<nsString> *aDictionaryList)
{
  nsresult rv;

  // For catching duplicates
  nsClassHashtable<nsStringHashKey, nsCString> dictionaries;

  nsCOMArray<mozISpellCheckingEngine> spellCheckingEngines;
  rv = GetEngineList(&spellCheckingEngines);
  NS_ENSURE_SUCCESS(rv, rv);

  for (int32_t i = 0; i < spellCheckingEngines.Count(); i++) {
    nsCOMPtr<mozISpellCheckingEngine> engine = spellCheckingEngines[i];

    uint32_t count = 0;
    PRUnichar **words = nullptr;
    engine->GetDictionaryList(&words, &count);
    for (uint32_t k = 0; k < count; k++) {
      nsAutoString dictName;

      dictName.Assign(words[k]);

      // Skip duplicate dictionaries. Only take the first one
      // for each name.
      if (dictionaries.Get(dictName, nullptr))
        continue;

      dictionaries.Put(dictName, nullptr);

      if (!aDictionaryList->AppendElement(dictName)) {
        NS_FREE_XPCOM_ALLOCATED_POINTER_ARRAY(count, words);
        return NS_ERROR_OUT_OF_MEMORY;
      }
    }

    NS_FREE_XPCOM_ALLOCATED_POINTER_ARRAY(count, words);
  }

  return NS_OK;
}
Exemple #13
0
NS_IMETHODIMP
nsNSSCertificate::GetAllTokenNames(uint32_t *aLength, PRUnichar*** aTokenNames)
{
  nsNSSShutDownPreventionLock locker;
  if (isAlreadyShutDown())
    return NS_ERROR_NOT_AVAILABLE;

  NS_ENSURE_ARG(aLength);
  NS_ENSURE_ARG(aTokenNames);
  *aLength = 0;
  *aTokenNames = NULL;

  /* Get the slots from NSS */
  PK11SlotList *slots = NULL;
  PK11SlotListCleaner slotCleaner(slots);
  PR_LOG(gPIPNSSLog, PR_LOG_DEBUG, ("Getting slots for \"%s\"\n", mCert->nickname));
  slots = PK11_GetAllSlotsForCert(mCert, NULL);
  if (!slots) {
    if (PORT_GetError() == SEC_ERROR_NO_TOKEN)
      return NS_OK; // List of slots is empty, return empty array
    else
      return NS_ERROR_FAILURE;
  }

  /* read the token names from slots */
  PK11SlotListElement *le;

  for (le = slots->head; le; le = le->next) {
    ++(*aLength);
  }

  *aTokenNames = (PRUnichar **)nsMemory::Alloc(sizeof(PRUnichar *) * (*aLength));
  if (!*aTokenNames) {
    *aLength = 0;
    return NS_ERROR_OUT_OF_MEMORY;
  }

  uint32_t iToken;
  for (le = slots->head, iToken = 0; le; le = le->next, ++iToken) {
    char *token = PK11_GetTokenName(le->slot);
    (*aTokenNames)[iToken] = ToNewUnicode(NS_ConvertUTF8toUTF16(token));
    if (!(*aTokenNames)[iToken]) {
      NS_FREE_XPCOM_ALLOCATED_POINTER_ARRAY(iToken, *aTokenNames);
      *aLength = 0;
      *aTokenNames = NULL;
      return NS_ERROR_OUT_OF_MEMORY;
    }
  }

  return NS_OK;
}
nsresult
nsSeamonkeyProfileMigrator::CopyPasswords(PRBool aReplace)
{
  nsresult rv;

  nsCString signonsFileName;
  GetSignonFileName(aReplace, getter_Copies(signonsFileName));

  if (signonsFileName.IsEmpty())
    return NS_ERROR_FILE_NOT_FOUND;

  NS_ConvertASCIItoUTF16 fileName(signonsFileName);
  if (aReplace)
    rv = CopyFile(fileName, fileName);
  else {
    // Get the password manager, which is the destination for the passwords
    // being migrated. Also create a new instance of the legacy password
    // storage component, which we'll use to slurp in the signons from
    // Seamonkey's signons.txt.
    nsCOMPtr<nsILoginManager> pwmgr(
        do_GetService("@mozilla.org/login-manager;1"));
    nsCOMPtr<nsILoginManagerStorage> importer(
        do_CreateInstance("@mozilla.org/login-manager/storage/legacy;1"));

    nsCOMPtr<nsIFile> signonsFile;
    mSourceProfile->Clone(getter_AddRefs(signonsFile));
    signonsFile->Append(fileName);

    importer->InitWithFile(signonsFile, nsnull);

    PRUint32 count;
    nsILoginInfo **logins;

    rv = importer->GetAllLogins(&count, &logins);
    NS_ENSURE_SUCCESS(rv, rv);
    for (PRUint32 i = 0; i < count; i++) {
        pwmgr->AddLogin(logins[i]);
    }
    NS_FREE_XPCOM_ISUPPORTS_POINTER_ARRAY(count, logins);

    PRUnichar **hostnames;
    rv = importer->GetAllDisabledHosts(&count, &hostnames);
    NS_ENSURE_SUCCESS(rv, rv);
    for (PRUint32 i = 0; i < count; i++) {
        pwmgr->SetLoginSavingEnabled(nsDependentString(hostnames[i]),
                                     PR_FALSE);
    }
    NS_FREE_XPCOM_ALLOCATED_POINTER_ARRAY(count, hostnames);
  }
  return rv;
}
void
LoadExistingPrefs()
{
  uint32_t count;
  char** names;
  nsresult rv = Preferences::GetRootBranch()->
      GetChildList(kLoggingPrefPrefix, &count, &names);
  if (NS_SUCCEEDED(rv) && count) {
    for (size_t i = 0; i < count; i++) {
      LoadPrefValue(names[i]);
    }
    NS_FREE_XPCOM_ALLOCATED_POINTER_ARRAY(count, names);
  }
}
Exemple #16
0
/**
 * Export VirtualBox vrde server
 */
static void exportVirtualBoxVRDEServer(IVRDEServer *vrdeServer, xmlTextWriterPtr writer) {
	nsresult rc;

	// find info
	PRBool enabled = PR_FALSE;

	vrdeServer->GetEnabled(&enabled);

	// vrde enabled
	ADDXMLBOOL(vrdeServer->GetEnabled, "vrde");

	if (enabled == PR_TRUE) {
		// vrde extpack
		ADDXMLSTRING(vrdeServer->GetVRDEExtPack, "vrde.ext");

		// vrde auth lib
		ADDXMLSTRING(vrdeServer->GetAuthLibrary, "vrde.authlib");

		// vrde multicon
		ADDXMLBOOL(vrdeServer->GetAllowMultiConnection, "vrde.multicon");

		// vrde reusecon
		ADDXMLBOOL(vrdeServer->GetReuseSingleConnection, "vrde.reusecon");

		// vrde properties
		{
			PRUnichar **properties = nsnull;
			PRUint32 propertiesCount = 0;
			nsAutoString keyPrefix;

			rc = vrdeServer->GetVRDEProperties(&propertiesCount, &properties);
			if (NS_SUCCEEDED(rc)) {
				for (PRUint32 i = 0; i < propertiesCount; i++) {
					nsXPIDLString value;

					rc = vrdeServer->GetVRDEProperty(properties[i], getter_Copies(value));
					if (NS_SUCCEEDED(rc)) {
						nsCAutoString key("vrde.");

						key.AppendWithConversion(properties[i]);
						WRITEXMLSTRING(convertString(key).c_str(), convertString(value));
					}
				}

				NS_FREE_XPCOM_ALLOCATED_POINTER_ARRAY(propertiesCount, properties);
			}
		}
	}
}
// Convert the list of words in iwords to the same capitalization aWord and
// return them in owords.
NS_IMETHODIMP mozEnglishWordUtils::FromRootForm(const char16_t *aWord, const char16_t **iwords, uint32_t icount, char16_t ***owords, uint32_t *ocount)
{
  nsAutoString word(aWord);
  nsresult rv = NS_OK;

  int32_t length;
  char16_t **tmpPtr  = (char16_t **)moz_xmalloc(sizeof(char16_t *)*icount);
  if (!tmpPtr)
    return NS_ERROR_OUT_OF_MEMORY;

  mozEnglishWordUtils::myspCapitalization ct = captype(word);
  for(uint32_t i = 0; i < icount; ++i) {
    length = NS_strlen(iwords[i]);
    tmpPtr[i] = (char16_t *) moz_xmalloc(sizeof(char16_t) * (length + 1));
    if (MOZ_UNLIKELY(!tmpPtr[i])) {
      NS_FREE_XPCOM_ALLOCATED_POINTER_ARRAY(i, tmpPtr);
      return NS_ERROR_OUT_OF_MEMORY;
    }
    memcpy(tmpPtr[i], iwords[i], (length + 1) * sizeof(char16_t));

    nsAutoString capTest(tmpPtr[i]);
    mozEnglishWordUtils::myspCapitalization newCt=captype(capTest);
    if(newCt == NoCap){
      switch(ct)
        {
        case HuhCap:
        case NoCap:
          break;
        case AllCap:
          ToUpperCase(tmpPtr[i],tmpPtr[i],length);
          rv = NS_OK;
          break;
        case InitCap:
          ToUpperCase(tmpPtr[i],tmpPtr[i],1);
          rv = NS_OK;
          break;
        default:
          rv = NS_ERROR_FAILURE; // should never get here;
          break;

        }
    }
  }
  if (NS_SUCCEEDED(rv)){
    *owords = tmpPtr;
    *ocount = icount;
  }
  return rv;
}
nsresult
nsLDAPSyncQuery::OnLDAPSearchResult(nsILDAPMessage *aMessage)
{
    // We are done with the LDAP search.
    // Release the control variable for the eventloop and other members
    // 
    FinishLDAPQuery();
    
    // Release memory allocated for mAttrs
    
    if (mAttrCount > 0)
        NS_FREE_XPCOM_ALLOCATED_POINTER_ARRAY(mAttrCount, mAttrs);

    return NS_OK;
}
// Convert the list of words in iwords to the same capitalization aWord and 
// return them in owords.
NS_IMETHODIMP mozEnglishWordUtils::FromRootForm(const PRUnichar *aWord, const PRUnichar **iwords, PRUint32 icount, PRUnichar ***owords, PRUint32 *ocount)
{
  nsAutoString word(aWord);
  nsresult rv = NS_OK;

  PRInt32 length;
  PRUnichar **tmpPtr  = (PRUnichar **)nsMemory::Alloc(sizeof(PRUnichar *)*icount);
  if (!tmpPtr)
    return NS_ERROR_OUT_OF_MEMORY;

  mozEnglishWordUtils::myspCapitalization ct = captype(word);
  for(PRUint32 i = 0; i < icount; ++i) {
    length = nsCRT::strlen(iwords[i]);
    tmpPtr[i] = (PRUnichar *) nsMemory::Alloc(sizeof(PRUnichar) * (length + 1));
    if (NS_UNLIKELY(!tmpPtr[i])) {
      NS_FREE_XPCOM_ALLOCATED_POINTER_ARRAY(i, tmpPtr);
      return NS_ERROR_OUT_OF_MEMORY;
    }
    memcpy(tmpPtr[i], iwords[i], (length + 1) * sizeof(PRUnichar));

    nsAutoString capTest(tmpPtr[i]);
    mozEnglishWordUtils::myspCapitalization newCt=captype(capTest);
    if(newCt == NoCap){
      switch(ct) 
        {
        case HuhCap:
        case NoCap:
          break;
        case AllCap:
          rv = mCaseConv->ToUpper(tmpPtr[i],tmpPtr[i],length);
          break;
        case InitCap:  
          rv = mCaseConv->ToUpper(tmpPtr[i],tmpPtr[i],1);
          break;
        default:
          rv = NS_ERROR_FAILURE; // should never get here;
          break;

        }
    }
  }
  if (NS_SUCCEEDED(rv)){
    *owords = tmpPtr;
    *ocount = icount;
  }
  return rv;
}
Exemple #20
0
// we don't get to use exceptions, so we'll fake it.  this is an error
// handler for IterateAttributes().  
//
nsresult
nsLDAPMessage::IterateAttrErrHandler(PRInt32 aLderrno, PRUint32 *aAttrCount, 
                                     char** *aAttributes, BerElement *position)
{

    // if necessary, free the position holder used by 
    // ldap_{first,next}_attribute()  
    //
    if (position) {
        ldap_ber_free(position, 0);
    }

    // deallocate any entries in the array that have been allocated, then
    // the array itself
    //
    if (*aAttributes) {
        NS_FREE_XPCOM_ALLOCATED_POINTER_ARRAY(*aAttrCount, *aAttributes);
    }

    // possibly spit out a debugging message, then return an appropriate
    // error code
    //
    switch (aLderrno) {

    case LDAP_PARAM_ERROR:
        NS_WARNING("nsLDAPMessage::IterateAttributes() failure; probable bug "
                   "or memory corruption encountered");
        return NS_ERROR_UNEXPECTED;
        break;

    case LDAP_DECODING_ERROR:
        NS_WARNING("nsLDAPMessage::IterateAttributes(): decoding error");
        return NS_ERROR_LDAP_DECODING_ERROR;
        break;

    case LDAP_NO_MEMORY:
        return NS_ERROR_OUT_OF_MEMORY;
        break;

    }

    NS_WARNING("nsLDAPMessage::IterateAttributes(): LDAP C SDK returned "
               "unexpected value; possible bug or memory corruption");
    return NS_ERROR_UNEXPECTED;
}
NS_IMETHODIMP 
mozSpellChecker::GetDictionaryList(nsStringArray *aDictionaryList)
{
  nsAutoString temp;
  PRUint32 count,i;
  PRUnichar **words;
  
  if(!aDictionaryList || !mSpellCheckingEngine)
    return NS_ERROR_NULL_POINTER;
  mSpellCheckingEngine->GetDictionaryList(&words,&count);
  for(i=0;i<count;i++){
    temp.Assign(words[i]);
    aDictionaryList->AppendString(temp);
  }
  NS_FREE_XPCOM_ALLOCATED_POINTER_ARRAY(count, words);

  return NS_OK;
}
nsresult
nsLDAPSyncQuery::OnLDAPSearchEntry(nsILDAPMessage *aMessage)
{
    nsresult rv;       

    // Attributes are retrieved in StartLDAPSearch
    // iterate through them
    //
    for (PRUint32 i = 0; i < mAttrCount; i++) {

        PRUnichar **vals;
        PRUint32 valueCount;

        // get the values of this attribute
        // XXX better failure handling
        //
        rv = aMessage->GetValues(mAttrs[i], &valueCount, &vals);
        if (NS_FAILED(rv)) {
            NS_WARNING("nsLDAPSyncQuery:OnLDAPSearchEntry(): "
                       "aMessage->GetValues() failed\n");
            FinishLDAPQuery();
            return rv;;
        }

        // store  all values of this attribute in the mResults.
        //
        for (PRUint32 j = 0; j < valueCount; j++) {
            mResults.Append(PRUnichar('\n'));
            mResults.AppendASCII(mAttrs[i]);
            mResults.Append(PRUnichar('='));
            mResults.Append(vals[j]);
        }
        
        NS_FREE_XPCOM_ALLOCATED_POINTER_ARRAY(valueCount, vals);

    }

    return NS_OK;
}
NS_IMETHODIMP 
mozSpellChecker::CheckWord(const nsAString &aWord, PRBool *aIsMisspelled, nsStringArray *aSuggestions)
{
  nsresult result;
  PRBool correct;
  if(!mSpellCheckingEngine)
    return NS_ERROR_NULL_POINTER;

  // don't bother to check crazy words, also, myspell gets unhappy if you
  // give it too much data and crashes sometimes
  if (aWord.Length() > UNREASONABLE_WORD_LENGTH) {
    *aIsMisspelled = PR_TRUE;
    return NS_OK;
  }

  *aIsMisspelled = PR_FALSE;
  result = mSpellCheckingEngine->Check(PromiseFlatString(aWord).get(), &correct);
  NS_ENSURE_SUCCESS(result, result);
  if(!correct){
    if(aSuggestions){
      PRUint32 count,i;
      PRUnichar **words;
      
      result = mSpellCheckingEngine->Suggest(PromiseFlatString(aWord).get(), &words, &count);
      NS_ENSURE_SUCCESS(result, result); 
      for(i=0;i<count;i++){
        aSuggestions->AppendString(nsDependentString(words[i]));
      }
      
      if (count)
        NS_FREE_XPCOM_ALLOCATED_POINTER_ARRAY(count, words);
    }
    if(aIsMisspelled){
      *aIsMisspelled = PR_TRUE;
    }
  }
  return NS_OK;
}
/* void getAllTags (out unsigned long count, [array, size_is (count), retval] out nsIMsgTag tagArray); */
NS_IMETHODIMP nsMsgTagService::GetAllTags(uint32_t *aCount, nsIMsgTag ***aTagArray)
{
  NS_ENSURE_ARG_POINTER(aCount);
  NS_ENSURE_ARG_POINTER(aTagArray);

  // preset harmless default values
  *aCount = 0;
  *aTagArray = nullptr;

  // get the actual tag definitions
  nsresult rv;
  uint32_t prefCount;
  char **prefList;
  rv = m_tagPrefBranch->GetChildList("", &prefCount, &prefList);
  NS_ENSURE_SUCCESS(rv, rv);
  // sort them by key for ease of processing
  NS_QuickSort(prefList, prefCount, sizeof(char*), CompareMsgTagKeys, nullptr);

  // build an array of nsIMsgTag elements from the orderered list
  // it's at max the same size as the preflist, but usually only about half
  nsIMsgTag** tagArray = (nsIMsgTag**) NS_Alloc(sizeof(nsIMsgTag*) * prefCount);

  if (!tagArray)
  {
    NS_FREE_XPCOM_ALLOCATED_POINTER_ARRAY(prefCount, prefList);
    return NS_ERROR_OUT_OF_MEMORY;
  }
  uint32_t currentTagIndex = 0;
  nsMsgTag *newMsgTag;
  nsString tag;
  nsCString lastKey, color, ordinal;
  for (uint32_t i = prefCount; i--;)
  {
    // extract just the key from <key>.<info=tag|color|ordinal>
    char *info = strrchr(prefList[i], '.');
    if (info)
    {
      nsCAutoString key(Substring(prefList[i], info));
      if (key != lastKey)
      {
        if (!key.IsEmpty())
        {
          // .tag MUST exist (but may be empty)
          rv = GetTagForKey(key, tag);
          if (NS_SUCCEEDED(rv))
          {
            // .color MAY exist
            color.Truncate();
            GetColorForKey(key, color);
            // .ordinal MAY exist
            rv = GetOrdinalForKey(key, ordinal);
            if (NS_FAILED(rv))
              ordinal.Truncate();
            // store the tag info in our array
            newMsgTag = new nsMsgTag(key, tag, color, ordinal);
            if (!newMsgTag)
            {
              NS_FREE_XPCOM_ISUPPORTS_POINTER_ARRAY(currentTagIndex, tagArray);
              NS_FREE_XPCOM_ALLOCATED_POINTER_ARRAY(prefCount, prefList);
              return NS_ERROR_OUT_OF_MEMORY;
            }
            NS_ADDREF(tagArray[currentTagIndex++] = newMsgTag);
          }
        }
        lastKey = key;
      }
    }
  }
  NS_FREE_XPCOM_ALLOCATED_POINTER_ARRAY(prefCount, prefList);

  // sort the non-null entries by ordinal
  NS_QuickSort(tagArray, currentTagIndex, sizeof(nsMsgTag*), CompareMsgTags,
               nullptr);

  // All done, now return the values (the idl's size_is(count) parameter
  // ensures that the array is cut accordingly).
  *aCount = currentTagIndex;
  *aTagArray = tagArray;

  return NS_OK;
}
Exemple #25
0
/**
 * Export VirtualBox machine
 */
void exportVirtualBoxMachine(IVirtualBox *virtualBox, IMachine *machine, xmlTextWriterPtr writer) {
	nsCOMPtr<ISystemProperties> systemProperties;
	nsresult rc = virtualBox->GetSystemProperties(getter_AddRefs(systemProperties));

	if (NS_SUCCEEDED(rc)) {
		xmlTextWriterStartElement(writer, TOXMLCHAR("machine"));

			// uuid
			ADDXMLSTRING(machine->GetId, "id");

			// name
			ADDXMLSTRING(machine->GetName, "name");

			// description
			ADDXMLSTRING(machine->GetDescription, "description");

			// os type
			ADDXMLSTRING(machine->GetOSTypeId, "ostype");

			// settings file
			ADDXMLSTRING(machine->GetSettingsFilePath, "path");

			// hardware uuid
			ADDXMLSTRING(machine->GetHardwareUUID, "hardwareuuid");

			// memory size
			ADDXMLINT32U(machine->GetMemorySize, "memory");

			// memory balloon size
			ADDXMLINT32U(machine->GetMemoryBalloonSize, "memoryballoon");

			// page fusion
			ADDXMLBOOL(machine->GetPageFusionEnabled, "pagefusion");

			// vram size
			ADDXMLINT32U(machine->GetVRAMSize, "vram");

			// hpet
			ADDXMLBOOL(machine->GetHPETEnabled, "hpet");

			// cpu count
			ADDXMLINT32U(machine->GetCPUCount, "cpus");

			// cpu execution cap
			ADDXMLINT32U(machine->GetCPUExecutionCap, "cpucap");

			// cpu hotplug
			ADDXMLBOOL(machine->GetCPUHotPlugEnabled, "cpuhotplug");

			// synthcpu
			// {
			// 	PRBool value;

			// 	rc = machine->GetCPUProperty(CPUPropertyType_Synthetic, &value);
			// 	if (NS_SUCCEEDED(rc)) {
			// 		WRITEXMLBOOL("synthcpu", value);
			// 	}
			// }

			// firmware type
			ADDXMLENUM(machine->GetFirmwareType, "firmware", firmwareTypeConverter);

			// bios settings
			{
				nsCOMPtr<IBIOSSettings> value;

				rc = machine->GetBIOSSettings(getter_AddRefs(value));
				if (NS_SUCCEEDED(rc)) {
					exportVirtualBoxBIOSSettings(value, writer);
				}
			}

			// boot order
			{
				PRUint32 bootPositions;

				rc = systemProperties->GetMaxBootPosition(&bootPositions);
				if (NS_SUCCEEDED(rc)) {
					for (PRUint32 i = 1; i <= bootPositions; i++) {
						PRUint32 value;

						rc = machine->GetBootOrder(i, &value);
						if (NS_SUCCEEDED(rc)) {
							char name[256];

							sprintf(name, "boot%d", i);
							WRITEXMLENUM(name, value, deviceTypeConverter);
						}
					}
				}
			}

			// pae
			{
				PRBool value;

				rc = machine->GetCPUProperty(CPUPropertyType_PAE, &value);
				if (NS_SUCCEEDED(rc)) {
					WRITEXMLBOOL("pae", value);
				}
			}

			// rtc use utc
			ADDXMLBOOL(machine->GetRTCUseUTC, "rtcuseutc");

			// monitor count
			ADDXMLINT32U(machine->GetMonitorCount, "monitorcount");

			// accelerate 3D
			ADDXMLBOOL(machine->GetAccelerate3DEnabled, "accelerate3d");

			// accelerate 2D video
			ADDXMLBOOL(machine->GetAccelerate2DVideoEnabled, "accelerate2dvideo");

			// hwvirtex
			{
				PRBool value;

				rc = machine->GetCPUProperty(HWVirtExPropertyType_Enabled, &value);
				if (NS_SUCCEEDED(rc)) {
					WRITEXMLBOOL("hwvirtex", value);
				}
			}

			// vtxvpid
			{
				PRBool value;

				rc = machine->GetHWVirtExProperty(HWVirtExPropertyType_VPID, &value);
				if (NS_SUCCEEDED(rc)) {
					WRITEXMLBOOL("vtxvpid", value);
				}
			}

			// nestedpaging
			{
				PRBool value;

				rc = machine->GetHWVirtExProperty(HWVirtExPropertyType_NestedPaging, &value);
				if (NS_SUCCEEDED(rc)) {
					WRITEXMLBOOL("nestedpaging", value);
				}
			}

			// unrestrictedexec
			{
				PRBool value;

				rc = machine->GetHWVirtExProperty(HWVirtExPropertyType_UnrestrictedExecution, &value);
				if (NS_SUCCEEDED(rc)) {
					WRITEXMLBOOL("unrestrictedexec", value);
				}
			}

			// largepages
			{
				PRBool value;

				rc = machine->GetHWVirtExProperty(HWVirtExPropertyType_LargePages, &value);
				if (NS_SUCCEEDED(rc)) {
					WRITEXMLBOOL("largepages", value);
				}
			}

			// force
			{
				PRBool value;

				rc = machine->GetHWVirtExProperty(HWVirtExPropertyType_Force, &value);
				if (NS_SUCCEEDED(rc)) {
					WRITEXMLBOOL("hwforce", value);
				}
			}

			// io cache
			ADDXMLBOOL(machine->GetIOCacheEnabled, "iocache");

			// io cache size
			ADDXMLINT32U(machine->GetIOCacheSize, "iocachesize");

			// chipset type
			ADDXMLENUM(machine->GetChipsetType, "chipset", chipsetTypeConverter);

			// pointing hid type
			ADDXMLENUM(machine->GetPointingHIDType, "mouse", pointingHidTypeConverter);

			// keyboard hid type
			ADDXMLENUM(machine->GetKeyboardHIDType, "keyboard", keyboardHidTypeConverter);

			// clipboard mode
			ADDXMLENUM(machine->GetClipboardMode, "clipboard", clipboardModeConverter);

			// vm state
			ADDXMLENUM(machine->GetState, "state", stateConverter);

			// vm state change
			ADDXMLTIMESTAMP(machine->GetLastStateChange, "statechanged");

			// teleporterenabled, teleporterport, teleporteraddress, teleporterpassword

			// storage controller
			{
				IStorageController **storageControllers = nsnull;
				PRUint32 storageControllersCount = 0;

				rc = machine->GetStorageControllers(&storageControllersCount, &storageControllers);
				if (NS_SUCCEEDED(rc)) {
					for (PRUint32 i = 0; i < storageControllersCount; i++) {
						exportVirtualBoxStorageController(storageControllers[i], i, writer);
					}
				}

				NS_FREE_XPCOM_ISUPPORTS_POINTER_ARRAY(storageControllersCount, storageControllers);
			}

			// medium attachments
			{
				IMediumAttachment **mediumAttachments = nsnull;
				PRUint32 mediumAttachmentsCount = 0;

				rc = machine->GetMediumAttachments(&mediumAttachmentsCount, &mediumAttachments);
				if (NS_SUCCEEDED(rc)) {
					for (PRUint32 i = 0; i < mediumAttachmentsCount; i++) {
						exportVirtualBoxMediumAttachment(mediumAttachments[i], writer);
					}
				}

				NS_FREE_XPCOM_ISUPPORTS_POINTER_ARRAY(mediumAttachmentsCount, mediumAttachments);
			}

			// network adapters
			{
				PRUint32 networkAdaptersCount;
				PRUint32 chipsetType;

				rc = machine->GetChipsetType(&chipsetType);
				if (NS_SUCCEEDED(rc)) {
					rc = systemProperties->GetMaxNetworkAdapters(chipsetType, &networkAdaptersCount);
					if (NS_SUCCEEDED(rc)) {
						for (PRUint32 i = 0; i < networkAdaptersCount; i++) {
							nsCOMPtr<INetworkAdapter> networkAdapter;

							rc = machine->GetNetworkAdapter(i, getter_AddRefs(networkAdapter));
							if (NS_SUCCEEDED(rc)) {
								exportVirtualBoxNetworkAdapter(networkAdapter, i + 1, writer);
							}
						}
					}
				}
			}

			// uartX

			// audio adapter
			{
				nsCOMPtr<IAudioAdapter> value;

				rc = machine->GetAudioAdapter(getter_AddRefs(value));
				if (NS_SUCCEEDED(rc)) {
					exportVirtualBoxAudioAdapter(value, writer);
				}
			}

			// vrde server
			{
				nsCOMPtr<IVRDEServer> value;

				rc = machine->GetVRDEServer(getter_AddRefs(value));
				if (NS_SUCCEEDED(rc)) {
					exportVirtualBoxVRDEServer(value, writer);
				}
			}

			// usb controllers
			// {
			// 	nsCOMPtr<IUSBController> value;

			// 	rc = machine->GetUSBController(getter_AddRefs(value));
			// 	if (NS_SUCCEEDED(rc)) {
			// 		exportVirtualBoxUSBController(value, writer);
			// 	}
			// }

			// guest properties
			{
				PRUnichar **names = nsnull;
				PRUnichar **values = nsnull;
				PRInt64 *timestamps = nsnull;
				PRUnichar **flags = nsnull;
				PRUint32 namesCount = 0;
				PRUint32 valuesCount = 0;
				PRUint32 timestampsCount = 0;
				PRUint32 flagsCount = 0;

				rc = machine->EnumerateGuestProperties((const PRUnichar*)nsnull, &namesCount, &names, &valuesCount, &values, &timestampsCount, &timestamps, &flagsCount, &flags);
				if (NS_SUCCEEDED(rc)) {
					for (PRUint32 i = 0; i < namesCount; i++) {
						nsAutoString name(names[i]);
						nsAutoString value(values[i]);
						PRUint64 timestamp = timestamps[i];
						nsAutoString flag(flags[i]);

						WRITEXMLSTRING(convertString(name).c_str(), convertString(value));
					}
				}

				NS_FREE_XPCOM_ALLOCATED_POINTER_ARRAY(namesCount, names);
				NS_FREE_XPCOM_ALLOCATED_POINTER_ARRAY(valuesCount, values);
				nsMemory::Free(timestamps);
				NS_FREE_XPCOM_ALLOCATED_POINTER_ARRAY(flagsCount, flags);
			}

		xmlTextWriterEndElement(writer);
	}
}
Exemple #26
0
/**
 * Export VirtualBox network adapter
 */
static void exportVirtualBoxNetworkAdapter(INetworkAdapter *networkAdapter, PRUint32 index, xmlTextWriterPtr writer) {
	char name[256];
	nsresult rc;

	// find info
	PRUint32 attachmentType = 0;

	networkAdapter->GetAttachmentType(&attachmentType);

	// attachment type
	sprintf(name, "nic%d", index);
	ADDXMLENUM(networkAdapter->GetAttachmentType, name, networkAttachmentTypeConverter);

	// specific configuration
	switch (attachmentType) {
	case NetworkAttachmentType_NAT:
		// nat network
		sprintf(name, "natnet%d", index);
		ADDXMLSTRING(networkAdapter->GetNATNetwork, name);
		break;

	case NetworkAttachmentType_Bridged:
		// bridge adapter
		sprintf(name, "bridgeadapter%d", index);
		ADDXMLSTRING(networkAdapter->GetBridgedInterface, name);
		break;

	case NetworkAttachmentType_Internal:
		// internal network
		sprintf(name, "intnet%d", index);
		ADDXMLSTRING(networkAdapter->GetInternalNetwork, name);
		break;

	case NetworkAttachmentType_HostOnly:
		// host adapter
		sprintf(name, "hostonlyadapter%d", index);
		ADDXMLSTRING(networkAdapter->GetHostOnlyInterface, name);
		break;

	case NetworkAttachmentType_Generic:
		// generic adapter
		sprintf(name, "genericadapter%d", index);
		ADDXMLSTRING(networkAdapter->GetGenericDriver, name);
		break;
	}

	switch (attachmentType) {
	case NetworkAttachmentType_NAT:
	case NetworkAttachmentType_Bridged:
	case NetworkAttachmentType_Internal:
	case NetworkAttachmentType_HostOnly:
	case NetworkAttachmentType_Generic:
		// enabled
		sprintf(name, "nicenabled%d", index);
		ADDXMLBOOL(networkAdapter->GetEnabled, name);

		// enabled
		sprintf(name, "nicpriority%d", index);
		ADDXMLINT32U(networkAdapter->GetBootPriority, name);

		// adapter type
		sprintf(name, "nictype%d", index);
		ADDXMLENUM(networkAdapter->GetAdapterType, name, networkAdapterTypeConverter);

		// mac address
		sprintf(name, "macaddress%d", index);
		ADDXMLSTRING(networkAdapter->GetMACAddress, name);

		// cable connected
		sprintf(name, "cableconnected%d", index);
		ADDXMLBOOL(networkAdapter->GetCableConnected, name);

		// speed
		sprintf(name, "nicspeed%d", index);
		ADDXMLINT32U(networkAdapter->GetLineSpeed, name);
		break;

		// promisc policy
		sprintf(name, "nicpromisc%d", index);
		ADDXMLENUM(networkAdapter->GetPromiscModePolicy, name, promiscModePolicyConverter);

		// extra properties
		{
			PRUnichar **propertyNames = nsnull;
			PRUnichar **propertyValues = nsnull;
			PRUint32 propertyNamesCount = 0;
			PRUint32 propertyValuesCount = 0;

			sprintf(name, "nic%d_", index);

			rc = networkAdapter->GetProperties(NS_LITERAL_STRING("").get(), &propertyNamesCount, &propertyNames, &propertyValuesCount, &propertyValues);
			if (NS_SUCCEEDED(rc)) {
				for (PRUint32 i = 0; i < propertyNamesCount && i < propertyValuesCount; i++) {
					nsCAutoString key(name);
					nsString value(propertyValues[i]);

					key.AppendWithConversion(propertyNames[i]);
					WRITEXMLSTRING(convertString(key).c_str(), convertString(value));
				}

				NS_FREE_XPCOM_ALLOCATED_POINTER_ARRAY(propertyNamesCount, propertyNames);
				NS_FREE_XPCOM_ALLOCATED_POINTER_ARRAY(propertyValuesCount, propertyValues);
			}
		}
	}
}
// static
XPCNativeSet*
XPCNativeSet::GetNewOrUsed(XPCCallContext& ccx, nsIClassInfo* classInfo)
{
    AutoMarkingNativeSetPtr set(ccx);
    XPCJSRuntime* rt = ccx.GetRuntime();

    ClassInfo2NativeSetMap* map = rt->GetClassInfo2NativeSetMap();
    if (!map)
        return nsnull;

    {   // scoped lock
        XPCAutoLock lock(rt->GetMapLock());
        set = map->Find(classInfo);
    }

    if (set)
        return set;

    nsIID** iidArray = nsnull;
    AutoMarkingNativeInterfacePtrArrayPtr interfaceArray(ccx);
    PRUint32 iidCount = 0;

    if (NS_FAILED(classInfo->GetInterfaces(&iidCount, &iidArray))) {
        // Note: I'm making it OK for this call to fail so that one can add
        // nsIClassInfo to classes implemented in script without requiring this
        // method to be implemented.

        // Make sure these are set correctly...
        iidArray = nsnull;
        iidCount = 0;
    }

    NS_ASSERTION((iidCount && iidArray) || !(iidCount || iidArray), "GetInterfaces returned bad array");

    // !!! from here on we only exit through the 'out' label !!!

    if (iidCount) {
        AutoMarkingNativeInterfacePtrArrayPtr
            arr(ccx, new XPCNativeInterface*[iidCount], iidCount, true);
        if (!arr)
            goto out;

        interfaceArray = arr;

        XPCNativeInterface** currentInterface = interfaceArray;
        nsIID**              currentIID = iidArray;
        PRUint16             interfaceCount = 0;

        for (PRUint32 i = 0; i < iidCount; i++) {
            nsIID* iid = *(currentIID++);
            if (!iid) {
                NS_ERROR("Null found in classinfo interface list");
                continue;
            }

            XPCNativeInterface* iface =
                XPCNativeInterface::GetNewOrUsed(ccx, iid);

            if (!iface) {
                // XXX warn here
                continue;
            }

            *(currentInterface++) = iface;
            interfaceCount++;
        }

        if (interfaceCount) {
            set = NewInstance(ccx, interfaceArray, interfaceCount);
            if (set) {
                NativeSetMap* map2 = rt->GetNativeSetMap();
                if (!map2)
                    goto out;

                XPCNativeSetKey key(set, nsnull, 0);

                {   // scoped lock
                    XPCAutoLock lock(rt->GetMapLock());
                    XPCNativeSet* set2 = map2->Add(&key, set);
                    if (!set2) {
                        NS_ERROR("failed to add our set!");
                        DestroyInstance(set);
                        set = nsnull;
                        goto out;
                    }
                    if (set2 != set) {
                        DestroyInstance(set);
                        set = set2;
                    }
                }
            }
        } else
            set = GetNewOrUsed(ccx, &NS_GET_IID(nsISupports));
    } else
        set = GetNewOrUsed(ccx, &NS_GET_IID(nsISupports));

    if (set)
    {   // scoped lock
        XPCAutoLock lock(rt->GetMapLock());

#ifdef DEBUG
        XPCNativeSet* set2 =
#endif
          map->Add(classInfo, set);
        NS_ASSERTION(set2, "failed to add our set!");
        NS_ASSERTION(set2 == set, "hashtables inconsistent!");
    }

out:
    if (iidArray)
        NS_FREE_XPCOM_ALLOCATED_POINTER_ARRAY(iidCount, iidArray);
    if (interfaceArray)
        delete [] interfaceArray.get();

    return set;
}
Exemple #28
0
NS_IMETHODIMP
nsLDAPOperation::SearchExt(const nsACString& aBaseDn, PRInt32 aScope,
                           const nsACString& aFilter,
                           const nsACString &aAttributes,
                           PRIntervalTime aTimeOut, PRInt32 aSizeLimit)
{
    if (!mMessageListener) {
        NS_ERROR("nsLDAPOperation::SearchExt(): mMessageListener not set");
        return NS_ERROR_NOT_INITIALIZED;
    }

    // XXX add control logging
    PR_LOG(gLDAPLogModule, PR_LOG_DEBUG,
           ("nsLDAPOperation::SearchExt(): called with aBaseDn = '%s'; "
            "aFilter = '%s'; aAttributes = %s; aSizeLimit = %d",
            PromiseFlatCString(aBaseDn).get(),
            PromiseFlatCString(aFilter).get(),
            PromiseFlatCString(aAttributes).get(), aSizeLimit));

    LDAPControl **serverctls = 0;
    nsresult rv;
    if (mServerControls) {
        rv = convertControlArray(mServerControls, &serverctls);
        if (NS_FAILED(rv)) {
            PR_LOG(gLDAPLogModule, PR_LOG_ERROR,
                   ("nsLDAPOperation::SearchExt(): error converting server "
                    "control array: %x", rv));
            return rv;
        }
    }

    LDAPControl **clientctls = 0;
    if (mClientControls) {
        rv = convertControlArray(mClientControls, &clientctls);
        if (NS_FAILED(rv)) {
            PR_LOG(gLDAPLogModule, PR_LOG_ERROR,
                   ("nsLDAPOperation::SearchExt(): error converting client "
                    "control array: %x", rv));
            ldap_controls_free(serverctls);
            return rv;
        }
    }

    // Convert our comma separated string to one that the C-SDK will like, i.e.
    // convert to a char array and add a last NULL element.
    nsTArray<nsCString> attrArray;
    ParseString(aAttributes, ',', attrArray);
    char **attrs = nsnull;
    PRUint32 origLength = attrArray.Length();
    if (origLength)
    {
      attrs = static_cast<char **> (NS_Alloc((origLength + 1) * sizeof(char *)));
      if (!attrs)
        return NS_ERROR_OUT_OF_MEMORY;

      for (PRUint32 i = 0; i < origLength; ++i)
        attrs[i] = ToNewCString(attrArray[i]);

      attrs[origLength] = 0;
    }

    // XXX deal with timeout here
    int retVal = ldap_search_ext(mConnectionHandle,
                                 PromiseFlatCString(aBaseDn).get(),
                                 aScope, PromiseFlatCString(aFilter).get(),
                                 attrs, 0, serverctls, clientctls, 0,
                                 aSizeLimit, &mMsgID);

    // clean up
    ldap_controls_free(serverctls);
    ldap_controls_free(clientctls);
    // The last entry is null, so no need to free that.
    NS_FREE_XPCOM_ALLOCATED_POINTER_ARRAY(origLength, attrs);

    rv = TranslateLDAPErrorToNSError(retVal);
    NS_ENSURE_SUCCESS(rv, rv);

    // make sure the connection knows where to call back once the messages
    // for this operation start coming in
    //
    rv = mConnection->AddPendingOperation(mMsgID, this);
    if (NS_FAILED(rv)) {
        switch (rv) {
        case NS_ERROR_OUT_OF_MEMORY:
            (void)ldap_abandon_ext(mConnectionHandle, mMsgID, 0, 0);
            return NS_ERROR_OUT_OF_MEMORY;

        default:
            (void)ldap_abandon_ext(mConnectionHandle, mMsgID, 0, 0);
            NS_ERROR("nsLDAPOperation::SearchExt(): unexpected error in "
                     "mConnection->AddPendingOperation");
            return NS_ERROR_UNEXPECTED;
        }
    }

    return NS_OK;
}
Exemple #29
0
nsresult
GetSlotWithMechanism(uint32_t aMechanism, nsIInterfaceRequestor* m_ctx,
                     PK11SlotInfo** aSlot, nsNSSShutDownPreventionLock& /*proofOfLock*/)
{
    PK11SlotList * slotList = nullptr;
    char16_t** tokenNameList = nullptr;
    nsITokenDialogs * dialogs;
    char16_t *unicodeTokenChosen;
    PK11SlotListElement *slotElement, *tmpSlot;
    uint32_t numSlots = 0, i = 0;
    bool canceled;
    nsresult rv = NS_OK;

    *aSlot = nullptr;

    // Get the slot
    slotList = PK11_GetAllTokens(MapGenMechToAlgoMech(aMechanism), 
                                true, true, m_ctx);
    if (!slotList || !slotList->head) {
        rv = NS_ERROR_FAILURE;
        goto loser;
    }

    if (!slotList->head->next) {
        /* only one slot available, just return it */
        *aSlot = slotList->head->slot;
      } else {
        // Gerenate a list of slots and ask the user to choose //
        tmpSlot = slotList->head;
        while (tmpSlot) {
            numSlots++;
            tmpSlot = tmpSlot->next;
        }

        // Allocate the slot name buffer //
        tokenNameList = static_cast<char16_t**>(moz_xmalloc(sizeof(char16_t *) * numSlots));
        if (!tokenNameList) {
            rv = NS_ERROR_OUT_OF_MEMORY;
            goto loser;
        }

        i = 0;
        slotElement = PK11_GetFirstSafe(slotList);
        while (slotElement) {
            tokenNameList[i] = UTF8ToNewUnicode(nsDependentCString(PK11_GetTokenName(slotElement->slot)));
            slotElement = PK11_GetNextSafe(slotList, slotElement, false);
            if (tokenNameList[i])
                i++;
            else {
                // OOM. adjust numSlots so we don't free unallocated memory. 
                numSlots = i;
                PK11_FreeSlotListElement(slotList, slotElement);
                rv = NS_ERROR_OUT_OF_MEMORY;
                goto loser;
            }
        }

		/* Throw up the token list dialog and get back the token */
		rv = getNSSDialogs((void**)&dialogs,
			               NS_GET_IID(nsITokenDialogs),
                     NS_TOKENDIALOGS_CONTRACTID);

		if (NS_FAILED(rv)) goto loser;

    if (!tokenNameList || !*tokenNameList) {
        rv = NS_ERROR_OUT_OF_MEMORY;
    } else {
        rv = dialogs->ChooseToken(m_ctx, (const char16_t**)tokenNameList,
                                  numSlots, &unicodeTokenChosen, &canceled);
    }
		NS_RELEASE(dialogs);
		if (NS_FAILED(rv)) goto loser;

		if (canceled) { rv = NS_ERROR_NOT_AVAILABLE; goto loser; }

        // Get the slot //
        slotElement = PK11_GetFirstSafe(slotList);
        nsAutoString tokenStr(unicodeTokenChosen);
        while (slotElement) {
            if (tokenStr.Equals(NS_ConvertUTF8toUTF16(PK11_GetTokenName(slotElement->slot)))) {
                *aSlot = slotElement->slot;
                PK11_FreeSlotListElement(slotList, slotElement);
                break;
            }
            slotElement = PK11_GetNextSafe(slotList, slotElement, false);
        }
        if(!(*aSlot)) {
            rv = NS_ERROR_FAILURE;
            goto loser;
        }
      }

      // Get a reference to the slot //
      PK11_ReferenceSlot(*aSlot);
loser:
      if (slotList) {
          PK11_FreeSlotList(slotList);
      }
      if (tokenNameList) {
          NS_FREE_XPCOM_ALLOCATED_POINTER_ARRAY(numSlots, tokenNameList);
      }
      return rv;
}
Exemple #30
0
// wrapper for get_values_len
//
NS_IMETHODIMP 
nsLDAPMessage::GetBinaryValues(const char *aAttr, PRUint32 *aCount,
                               nsILDAPBERValue ***aValues)
{
    struct berval **values;

#if defined(DEBUG)
    // We only want this being logged for debug builds so as not to affect performance too much.
    PR_LOG(gLDAPLogModule, PR_LOG_DEBUG,
           ("nsLDAPMessage::GetBinaryValues(): called with aAttr = '%s'", 
            aAttr));
#endif

    values = ldap_get_values_len(mConnectionHandle, mMsgHandle, aAttr);

    // bail out if there was a problem
    //
    if (!values) {
        PRInt32 lderrno = ldap_get_lderrno(mConnectionHandle, 0, 0);

        if ( lderrno == LDAP_DECODING_ERROR ) {
            // this may not be an error; it could just be that the 
            // caller has asked for an attribute that doesn't exist.
            //
            PR_LOG(gLDAPLogModule, PR_LOG_WARNING, 
                   ("nsLDAPMessage::GetBinaryValues(): ldap_get_values "
                    "returned LDAP_DECODING_ERROR"));
            return NS_ERROR_LDAP_DECODING_ERROR;

        } else if ( lderrno == LDAP_PARAM_ERROR ) {
            NS_ERROR("nsLDAPMessage::GetBinaryValues(): internal error: 1");
            return NS_ERROR_UNEXPECTED;

        } else {
            NS_ERROR("nsLDAPMessage::GetBinaryValues(): internal error: 2");
            return NS_ERROR_UNEXPECTED;
        }
    }

    // count the values
    //
    PRUint32 numVals = ldap_count_values_len(values);

    // create the out array
    //
    *aValues = 
        static_cast<nsILDAPBERValue **>(nsMemory::Alloc(numVals * sizeof(nsILDAPBERValue)));
    if (!aValues) {
        ldap_value_free_len(values);
        return NS_ERROR_OUT_OF_MEMORY;
    }

    // clone the array (except for the trailing NULL entry) using the 
    // shared allocator for XPCOM correctness
    //
    PRUint32 i;
    nsresult rv;
    for ( i = 0 ; i < numVals ; i++ ) {

        // create an nsBERValue object
        //
        nsCOMPtr<nsILDAPBERValue> berValue = new nsLDAPBERValue();
        if (!berValue) {
            NS_ERROR("nsLDAPMessage::GetBinaryValues(): out of memory"
                     " creating nsLDAPBERValue object");
            NS_FREE_XPCOM_ALLOCATED_POINTER_ARRAY(i, aValues);
            ldap_value_free_len(values);
            return NS_ERROR_OUT_OF_MEMORY;
        }

        // copy the value from the struct into the nsBERValue
        //
        rv = berValue->Set(values[i]->bv_len, 
                           reinterpret_cast<PRUint8 *>(values[i]->bv_val));
        if (NS_FAILED(rv)) {
            NS_ERROR("nsLDAPMessage::GetBinaryValues(): error setting"
                     " nsBERValue");
            ldap_value_free_len(values);
            return rv == NS_ERROR_OUT_OF_MEMORY ? rv : NS_ERROR_UNEXPECTED;
        }

        // put the nsIBERValue object into the out array
        //
        NS_ADDREF( (*aValues)[i] = berValue.get() );
    }

    *aCount = numVals;
    ldap_value_free_len(values);
    return NS_OK;
}