Пример #1
0
XRemoteClient::~XRemoteClient()
{
  PR_LOG(sRemoteLm, PR_LOG_DEBUG, ("XRemoteClient::~XRemoteClient"));
  if (mInitialized)
    Shutdown();
}
Пример #2
0
NS_IMETHODIMP
nsMsgCopyService::CopyMessages(nsIMsgFolder* srcFolder, /* UI src folder */
                               nsIArray* messages,
                               nsIMsgFolder* dstFolder,
                               bool isMove,
                               nsIMsgCopyServiceListener* listener,
                               nsIMsgWindow* window,
                               bool allowUndo)
{
  NS_ENSURE_ARG_POINTER(srcFolder);
  NS_ENSURE_ARG_POINTER(messages);
  NS_ENSURE_ARG_POINTER(dstFolder);

  PR_LOG(gCopyServiceLog, PR_LOG_DEBUG, ("CopyMessages"));

  if (srcFolder == dstFolder)
  {
    NS_ERROR("src and dest folders for msg copy can't be the same");
    return NS_ERROR_FAILURE;
  }
  nsCopyRequest* copyRequest;
  nsCopySource* copySource = nullptr;
  nsCOMArray<nsIMsgDBHdr> msgArray;
  uint32_t cnt;
  nsCOMPtr<nsIMsgDBHdr> msg;
  nsCOMPtr<nsIMsgFolder> curFolder;
  nsCOMPtr<nsISupports> aSupport;
  nsresult rv;

  // XXX TODO
  // JUNK MAIL RELATED
  // make sure dest folder exists
  // and has proper flags, before we start copying?

  copyRequest = new nsCopyRequest();
  if (!copyRequest)
    return NS_ERROR_OUT_OF_MEMORY;

  aSupport = do_QueryInterface(srcFolder, &rv);

  rv = copyRequest->Init(nsCopyMessagesType, aSupport, dstFolder, isMove,
                        0 /* new msg flags, not used */, EmptyCString(), 
                        listener, window, allowUndo);
  if (NS_FAILED(rv))
    goto done;

  messages->GetLength(&cnt);

  if (PR_LOG_TEST(gCopyServiceLog, PR_LOG_ALWAYS))
    LogCopyRequest("CopyMessages request", copyRequest);

  // duplicate the message array so we could sort the messages by it's
  // folder easily
  for (uint32_t i = 0; i < cnt; i++)
  {
    nsCOMPtr<nsIMsgDBHdr> currMsg = do_QueryElementAt(messages, i);
    msgArray.AppendObject(currMsg);
  }

  cnt = msgArray.Count();

  while (cnt-- > 0)
  {
    msg = msgArray[cnt];
    rv = msg->GetFolder(getter_AddRefs(curFolder));

    if (NS_FAILED(rv))
      goto done;
    if (!copySource)
    {
      copySource = copyRequest->AddNewCopySource(curFolder);
      if (!copySource)
      {
         rv = NS_ERROR_OUT_OF_MEMORY;
         goto done;
      }
    }

    if (curFolder == copySource->m_msgFolder)
    {
      copySource->AddMessage(msg);
      msgArray.RemoveObjectAt(cnt);
    }

    if (cnt == 0)
    {
      cnt = msgArray.Count();
      if (cnt > 0)
        copySource = nullptr; // * force to create a new one and
                             // * continue grouping the messages
    }
  }

  // undo stuff
  if (NS_SUCCEEDED(rv) && copyRequest->m_allowUndo && copyRequest->m_copySourceArray.Length() > 1 &&
      copyRequest->m_txnMgr)
    copyRequest->m_txnMgr->BeginBatch();

done:

    if (NS_FAILED(rv))
      delete copyRequest;
    else
      rv = DoCopy(copyRequest);

    return rv;
}
Пример #3
0
// wrapper for ldap_get_values()
//
NS_IMETHODIMP
nsLDAPMessage::GetValues(const char *aAttr, uint32_t *aCount, 
                         PRUnichar ***aValues)
{
    char **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::GetValues(): called with aAttr = '%s'", aAttr));
#endif

    values = ldap_get_values(mConnectionHandle, mMsgHandle, aAttr);

    // bail out if there was a problem
    //
    if (!values) {
        int32_t 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::GetValues(): ldap_get_values returned "
                    "LDAP_DECODING_ERROR"));
            return NS_ERROR_LDAP_DECODING_ERROR;

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

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

    // count the values
    //
    uint32_t numVals = ldap_count_values(values);

    // create an array of the appropriate size
    //
    *aValues = static_cast<PRUnichar **>(nsMemory::Alloc(numVals * sizeof(PRUnichar *)));
    if (!*aValues) {
        ldap_value_free(values);
        return NS_ERROR_OUT_OF_MEMORY;
    }

    // clone the array (except for the trailing NULL entry) using the 
    // shared allocator for XPCOM correctness
    //
    uint32_t i;
    for ( i = 0 ; i < numVals ; i++ ) {
        nsDependentCString sValue(values[i]);
        if (IsUTF8(sValue))
            (*aValues)[i] = ToNewUnicode(NS_ConvertUTF8toUTF16(sValue));
        else
            (*aValues)[i] = ToNewUnicode(NS_ConvertASCIItoUTF16(sValue));
        if ( ! (*aValues)[i] ) {
            NS_FREE_XPCOM_ALLOCATED_POINTER_ARRAY(i, aValues);
            ldap_value_free(values);
            return NS_ERROR_OUT_OF_MEMORY;
        }
    }

    // now free our value array since we already cloned the values array 
    // to the 'aValues' results array.
    ldap_value_free(values);

    *aCount = numVals;
    return NS_OK;
}
Пример #4
0
void tracefunc (void *aClosure, const char *aStmt)
{
  PR_LOG(gStorageLog, PR_LOG_DEBUG, ("sqlite3_trace on %p for '%s'", aClosure,
                                     aStmt));
}
Пример #5
0
nsresult
nsCertTree::GetCertsByTypeFromCertList(CERTCertList *aCertList,
                                       PRUint32 aWantedType,
                                       nsCertCompareFunc  aCertCmpFn,
                                       void *aCertCmpFnArg)
{
  PR_LOG(gPIPNSSLog, PR_LOG_DEBUG, ("GetCertsByTypeFromCertList"));
  if (!aCertList)
    return NS_ERROR_FAILURE;

  if (!mOriginalOverrideService)
    return NS_ERROR_FAILURE;

  nsTHashtable<nsCStringHashKey> allHostPortOverrideKeys;
  if (!allHostPortOverrideKeys.Init())
    return NS_ERROR_OUT_OF_MEMORY;

  if (aWantedType == nsIX509Cert::SERVER_CERT) {
    mOriginalOverrideService->
      EnumerateCertOverrides(nsnull, 
                             CollectAllHostPortOverridesCallback, 
                             &allHostPortOverrideKeys);
  }

  CERTCertListNode *node;
  int count = 0;
  for (node = CERT_LIST_HEAD(aCertList);
       !CERT_LIST_END(node, aCertList);
       node = CERT_LIST_NEXT(node)) {

    bool wantThisCert = (aWantedType == nsIX509Cert2::ANY_CERT);
    bool wantThisCertIfNoOverrides = false;
    bool wantThisCertIfHaveOverrides = false;
    bool addOverrides = false;

    if (!wantThisCert) {
      PRUint32 thisCertType = getCertType(node->cert);

      // The output from getCertType is a "guess", which can be wrong.
      // The guess is based on stored trust flags, but for the host:port
      // overrides, we are storing certs without any trust flags associated.
      // So we must check whether the cert really belongs to the 
      // server, email or unknown tab. We will lookup the cert in the override
      // list to come to the decision. Unfortunately, the lookup in the
      // override list is quite expensive. Therefore we are using this 
      // lengthy if/else statement to minimize 
      // the number of override-list-lookups.

      if (aWantedType == nsIX509Cert::SERVER_CERT
          && thisCertType == nsIX509Cert::UNKNOWN_CERT) {
        // This unknown cert was stored without trust
        // Are there host:port based overrides stored?
        // If yes, display them.
        addOverrides = true;
      }
      else
      if (aWantedType == nsIX509Cert::UNKNOWN_CERT
          && thisCertType == nsIX509Cert::UNKNOWN_CERT) {
        // This unknown cert was stored without trust.
        // If there are associated overrides, do not show as unknown.
        // If there are no associated overrides, display as unknown.
        wantThisCertIfNoOverrides = true;
      }
      else
      if (aWantedType == nsIX509Cert::SERVER_CERT
          && thisCertType == nsIX509Cert::SERVER_CERT) {
        // This server cert is explicitly marked as a web site peer, 
        // with or without trust, but editable, so show it
        wantThisCert = true;
        // Are there host:port based overrides stored?
        // If yes, display them.
        addOverrides = true;
      }
      else
      if (aWantedType == nsIX509Cert::SERVER_CERT
          && thisCertType == nsIX509Cert::EMAIL_CERT) {
        // This cert might have been categorized as an email cert
        // because it carries an email address. But is it really one?
        // Our cert categorization is uncertain when it comes to
        // distinguish between email certs and web site certs.
        // So, let's see if we have an override for that cert
        // and if there is, conclude it's really a web site cert.
        addOverrides = true;
      }
      else
      if (aWantedType == nsIX509Cert::EMAIL_CERT
          && thisCertType == nsIX509Cert::EMAIL_CERT) {
        // This cert might have been categorized as an email cert
        // because it carries an email address. But is it really one?
        // Our cert categorization is uncertain when it comes to
        // distinguish between email certs and web site certs.
        // So, let's see if we have an override for that cert
        // and if there is, conclude it's really a web site cert.
        wantThisCertIfNoOverrides = true;
      }
      else
      if (thisCertType == aWantedType) {
        wantThisCert = true;
      }
    }

    nsCOMPtr<nsIX509Cert> pipCert = nsNSSCertificate::Create(node->cert);
    if (!pipCert)
      return NS_ERROR_OUT_OF_MEMORY;

    if (wantThisCertIfNoOverrides || wantThisCertIfHaveOverrides) {
      PRUint32 ocount = 0;
      nsresult rv = 
        mOverrideService->IsCertUsedForOverrides(pipCert, 
                                                 true, // we want temporaries
                                                 true, // we want permanents
                                                 &ocount);
      if (wantThisCertIfNoOverrides) {
        if (NS_FAILED(rv) || ocount == 0) {
          // no overrides for this cert
          wantThisCert = true;
        }
      }

      if (wantThisCertIfHaveOverrides) {
        if (NS_SUCCEEDED(rv) && ocount > 0) {
          // there are overrides for this cert
          wantThisCert = true;
        }
      }
    }

    nsRefPtr<nsCertAddonInfo> certai = new nsCertAddonInfo;
    if (!certai)
      return NS_ERROR_OUT_OF_MEMORY;

    certai->mCert = pipCert;
    certai->mUsageCount = 0;

    if (wantThisCert || addOverrides) {
      int InsertPosition = 0;
      for (; InsertPosition < count; ++InsertPosition) {
        nsCOMPtr<nsIX509Cert> cert = nsnull;
        nsRefPtr<nsCertTreeDispInfo> elem = mDispInfo.SafeElementAt(InsertPosition, NULL);
        if (elem && elem->mAddonInfo) {
          cert = elem->mAddonInfo->mCert;
        }
        if ((*aCertCmpFn)(aCertCmpFnArg, pipCert, cert) < 0) {
          break;
        }
      }
      if (wantThisCert) {
        nsCertTreeDispInfo *certdi = new nsCertTreeDispInfo;
        if (!certdi)
          return NS_ERROR_OUT_OF_MEMORY;

        certdi->mAddonInfo = certai;
        certai->mUsageCount++;
        certdi->mTypeOfEntry = nsCertTreeDispInfo::direct_db;
        // not necessary: certdi->mAsciiHost.Clear(); certdi->mPort = -1;
        certdi->mOverrideBits = nsCertOverride::ob_None;
        certdi->mIsTemporary = false;
        mDispInfo.InsertElementAt(InsertPosition, certdi);
        ++count;
        ++InsertPosition;
      }
      if (addOverrides) {
        nsCertAndArrayAndPositionAndCounterAndTracker cap;
        cap.certai = certai;
        cap.array = &mDispInfo;
        cap.position = InsertPosition;
        cap.counter = 0;
        cap.tracker = &allHostPortOverrideKeys;

        mOriginalOverrideService->
          EnumerateCertOverrides(pipCert, MatchingCertOverridesCallback, &cap);
        count += cap.counter;
      }
    }
  }

  if (aWantedType == nsIX509Cert::SERVER_CERT) {
    nsArrayAndPositionAndCounterAndTracker cap;
    cap.array = &mDispInfo;
    cap.position = 0;
    cap.counter = 0;
    cap.tracker = &allHostPortOverrideKeys;
    mOriginalOverrideService->
      EnumerateCertOverrides(nsnull, AddRemaningHostPortOverridesCallback, &cap);
  }

  return NS_OK;
}
Пример #6
0
txInstruction*
txStylesheet::findTemplate(const txXPathNode& aNode,
                           const txExpandedName& aMode,
                           txIMatchContext* aContext,
                           ImportFrame* aImportedBy,
                           ImportFrame** aImportFrame)
{
    NS_ASSERTION(aImportFrame, "missing ImportFrame pointer");

    *aImportFrame = nsnull;
    txInstruction* matchTemplate = nsnull;
    ImportFrame* endFrame = nsnull;
    txListIterator frameIter(&mImportFrames);

    if (aImportedBy) {
        ImportFrame* curr = static_cast<ImportFrame*>(frameIter.next());
        while (curr != aImportedBy) {
               curr = static_cast<ImportFrame*>(frameIter.next());
        }
        endFrame = aImportedBy->mFirstNotImported;
    }

#ifdef PR_LOGGING
    txPattern* match = 0;
#endif

    ImportFrame* frame;
    while (!matchTemplate &&
           (frame = static_cast<ImportFrame*>(frameIter.next())) &&
           frame != endFrame) {

        // get templatelist for this mode
        nsTArray<MatchableTemplate>* templates =
            frame->mMatchableTemplates.get(aMode);

        if (templates) {
            // Find template with highest priority
            PRUint32 i, len = templates->Length();
            for (i = 0; i < len && !matchTemplate; ++i) {
                MatchableTemplate& templ = (*templates)[i];
                if (templ.mMatch->matches(aNode, aContext)) {
                    matchTemplate = templ.mFirstInstruction;
                    *aImportFrame = frame;
#ifdef PR_LOGGING
                    match = templ.mMatch;
#endif
                }
            }
        }
    }

#ifdef PR_LOGGING
    nsAutoString mode, nodeName;
    if (aMode.mLocalName) {
        aMode.mLocalName->ToString(mode);
    }
    txXPathNodeUtils::getNodeName(aNode, nodeName);
    if (matchTemplate) {
        nsAutoString matchAttr;
#ifdef TX_TO_STRING
        match->toString(matchAttr);
#endif
        PR_LOG(txLog::xslt, PR_LOG_DEBUG,
               ("MatchTemplate, Pattern %s, Mode %s, Node %s\n",
                NS_LossyConvertUTF16toASCII(matchAttr).get(),
                NS_LossyConvertUTF16toASCII(mode).get(),
                NS_LossyConvertUTF16toASCII(nodeName).get()));
    }
    else {
        PR_LOG(txLog::xslt, PR_LOG_DEBUG,
               ("No match, Node %s, Mode %s\n", 
                NS_LossyConvertUTF16toASCII(nodeName).get(),
                NS_LossyConvertUTF16toASCII(mode).get()));
    }
#endif

    if (!matchTemplate) {
        // Test for these first since a node can be both a text node
        // and a root (if it is orphaned)
        if (txXPathNodeUtils::isAttribute(aNode) ||
            txXPathNodeUtils::isText(aNode)) {
            matchTemplate = mCharactersTemplate;
        }
        else if (txXPathNodeUtils::isElement(aNode) ||
                 txXPathNodeUtils::isRoot(aNode)) {
            matchTemplate = mContainerTemplate;
        }
        else {
            matchTemplate = mEmptyTemplate;
        }
    }

    return matchTemplate;
}
Пример #7
0
static inline void
LogWithCertID(const char* aMessage, const CertID& aCertID)
{
  PR_LOG(gCertVerifierLog, PR_LOG_DEBUG, (aMessage, &aCertID));
}
Пример #8
0
nsresult nsReadConfig::readConfigFile()
{
    nsresult rv = NS_OK;
    nsXPIDLCString lockFileName;
    nsXPIDLCString lockVendor;
    uint32_t fileNameLen = 0;
    
    nsCOMPtr<nsIPrefBranch> defaultPrefBranch;
    nsCOMPtr<nsIPrefService> prefService = 
        do_GetService(NS_PREFSERVICE_CONTRACTID, &rv);
    if (NS_FAILED(rv))
        return rv;

    rv = prefService->GetDefaultBranch(nullptr, getter_AddRefs(defaultPrefBranch));
    if (NS_FAILED(rv))
        return rv;
        
    // This preference is set in the all.js or all-ns.js (depending whether 
    // running mozilla or netscp6)

    rv = defaultPrefBranch->GetCharPref("general.config.filename", 
                                  getter_Copies(lockFileName));


    PR_LOG(MCD, PR_LOG_DEBUG, ("general.config.filename = %s\n", lockFileName.get()));
    if (NS_FAILED(rv))
        return rv;

    // This needs to be read only once.
    //
    if (!mRead) {
        // Initiate the new JS Context for Preference management
        
        rv = CentralizedAdminPrefManagerInit();
        if (NS_FAILED(rv))
            return rv;
        
        // Open and evaluate function calls to set/lock/unlock prefs
        rv = openAndEvaluateJSFile("prefcalls.js", 0, false, false);
        if (NS_FAILED(rv)) 
            return rv;

        // Evaluate platform specific directives
        rv = openAndEvaluateJSFile("platform.js", 0, false, false);
        if (NS_FAILED(rv)) 
            return rv;

        mRead = true;
    }
    // If the lockFileName is NULL return ok, because no lockFile will be used
  
  
    // Once the config file is read, we should check that the vendor name 
    // is consistent By checking for the vendor name after reading the config 
    // file we allow for the preference to be set (and locked) by the creator 
    // of the cfg file meaning the file can not be renamed (successfully).

    nsCOMPtr<nsIPrefBranch> prefBranch;
    rv = prefService->GetBranch(nullptr, getter_AddRefs(prefBranch));
    NS_ENSURE_SUCCESS(rv, rv);

    int32_t obscureValue = 0;
    (void) defaultPrefBranch->GetIntPref("general.config.obscure_value", &obscureValue);
    PR_LOG(MCD, PR_LOG_DEBUG, ("evaluating .cfg file %s with obscureValue %d\n", lockFileName.get(), obscureValue));
    rv = openAndEvaluateJSFile(lockFileName.get(), obscureValue, true, true);
    if (NS_FAILED(rv))
    {
      PR_LOG(MCD, PR_LOG_DEBUG, ("error evaluating .cfg file %s %x\n", lockFileName.get(), rv));
      return rv;
    }
    
    rv = prefBranch->GetCharPref("general.config.filename", 
                                  getter_Copies(lockFileName));
    if (NS_FAILED(rv))
        // There is NO REASON we should ever get here. This is POST reading 
        // of the config file.
        return NS_ERROR_FAILURE;

  
    rv = prefBranch->GetCharPref("general.config.vendor", 
                                  getter_Copies(lockVendor));
    // If vendor is not NULL, do this check
    if (NS_SUCCEEDED(rv)) {

        fileNameLen = PL_strlen(lockFileName);
    
        // lockVendor and lockFileName should be the same with the addtion of 
        // .cfg to the filename by checking this post reading of the cfg file 
        // this value can be set within the cfg file adding a level of security.
    
        if (PL_strncmp(lockFileName, lockVendor, fileNameLen - 4) != 0)
            return NS_ERROR_FAILURE;
    }
  
    // get the value of the autoconfig url
    nsXPIDLCString urlName;
    rv = prefBranch->GetCharPref("autoadmin.global_config_url",
                                  getter_Copies(urlName));
    if (NS_SUCCEEDED(rv) && !urlName.IsEmpty()) {

        // Instantiating nsAutoConfig object if the pref is present
        mAutoConfig = do_CreateInstance(NS_AUTOCONFIG_CONTRACTID, &rv);
        if (NS_FAILED(rv))
            return NS_ERROR_OUT_OF_MEMORY;

        rv = mAutoConfig->SetConfigURL(urlName);
        if (NS_FAILED(rv))
            return NS_ERROR_FAILURE;

    }
  
    return NS_OK;
} // ReadConfigFile
Пример #9
0
void
nsPNGDecoder::error_callback(png_structp png_ptr, png_const_charp error_msg)
{
  PR_LOG(GetPNGLog(), PR_LOG_ERROR, ("libpng error: %s\n", error_msg));
  longjmp(png_jmpbuf(png_ptr), 1);
}
Пример #10
0
// typedef PRBool
// (* nsHashtableEnumFunc)
//      (nsHashKey *aKey, void *aData, void* aClosure);
PRBool
CheckLDAPOperationResult(nsHashKey *aKey, void *aData, void* aClosure)
{
    int lderrno;
    nsresult rv;
    PRInt32 returnCode;
    LDAPMessage *msgHandle;
    nsCOMPtr<nsILDAPMessage> msg;
    PRBool operationFinished = PR_TRUE;
    struct timeval timeout = { 0, 0 }; 
    PRIntervalTime sleepTime = PR_MillisecondsToInterval(40);

    // we need to access some of the connection loop's objects
    //
    nsLDAPConnectionLoop *loop = 
        static_cast<nsLDAPConnectionLoop *>(aClosure);

    // get the console service so we can log messages
    //
    nsCOMPtr<nsIConsoleService> consoleSvc = 
        do_GetService(kConsoleServiceContractId, &rv);
    if (NS_FAILED(rv)) {
        NS_ERROR("CheckLDAPOperationResult() couldn't get console service");
        return NS_ERROR_FAILURE;
    }

    returnCode = ldap_result(loop->mRawConn->mConnectionHandle,
                             aKey->HashCode(), LDAP_MSG_ONE,
                                 &timeout, &msgHandle);

        // if we didn't error or timeout, create an nsILDAPMessage
        //      
        switch (returnCode) {

        case 0: // timeout

            // the connection may not exist yet.  sleep for a while
            // to avoid a problem where the LDAP connection/thread isn't 
            // ready quite yet, and we want to avoid a very busy loop.
            //
            PR_Sleep(sleepTime);
            return PR_TRUE;

        case -1: // something went wrong 

        lderrno = ldap_get_lderrno(loop->mRawConn->mConnectionHandle, 0, 0);

            // Sleep briefly, to avoid a very busy loop again.
            //
            PR_Sleep(sleepTime);

            switch (lderrno) {

            case LDAP_SERVER_DOWN:
                // We might want to shutdown the thread here, but it has
                // implications to the user of the nsLDAPConnection, so
                // for now we just ignore it. It's up to the owner of
                // the nsLDAPConnection to detect the error, and then
                // create a new connection.
                //
                PR_LOG(gLDAPLogModule, PR_LOG_DEBUG, 
                       ("CheckLDAPOperationResult(): ldap_result returned" 
                        " LDAP_SERVER_DOWN"));
                break;

            case LDAP_DECODING_ERROR:
                consoleSvc->LogStringMessage(
                    NS_LITERAL_STRING("LDAP: WARNING: decoding error; possible corrupt data received").get());
                NS_WARNING("CheckLDAPOperationResult(): ldaperrno = "
                           "LDAP_DECODING_ERROR after ldap_result()");
                break;

            case LDAP_NO_MEMORY:
                NS_ERROR("CheckLDAPOperationResult(): Couldn't allocate memory"
                         " while getting async operation result");
                // punt and hope things work out better next time around
                break;

            case LDAP_PARAM_ERROR:
                // I think it's possible to hit a race condition where we're
                // continuing to poll for a result after the C SDK connection
                // has removed the operation because the connection has gone
                // dead.  In theory we should fix this.  Practically, it's
                // unclear to me whether it matters.
                //
                NS_WARNING("CheckLDAPOperationResult(): ldap_result returned"
                           " LDAP_PARAM_ERROR");
                break;

            default:
                NS_ERROR("CheckLDAPOperationResult(): lderrno set to "
                           "unexpected value after ldap_result() "
                           "call in nsLDAPConnection::Run()");
                PR_LOG(gLDAPLogModule, PR_LOG_ERROR, 
                       ("lderrno = 0x%x", lderrno));
                break;
            }
            break;

        case LDAP_RES_SEARCH_ENTRY:
        case LDAP_RES_SEARCH_REFERENCE:
            // XXX what should we do with LDAP_RES_SEARCH_EXTENDED?

            // not done yet, so we shouldn't remove the op from the conn q
            operationFinished = PR_FALSE;

            // fall through to default case

        default: // initialize the message and call the callback

            // we want nsLDAPMessage specifically, not a compatible, since
            // we're sharing native objects used by the LDAP C SDK
            //
            nsLDAPMessage *rawMsg;
            NS_NEWXPCOM(rawMsg, nsLDAPMessage);
            if (!rawMsg) {
            NS_ERROR("CheckLDAPOperationResult(): couldn't allocate memory"
                     " for new LDAP message; search entry dropped");
                // punt and hope things work out better next time around
                break;
            }

            // initialize the message, using a protected method not available
            // through nsILDAPMessage (which is why we need the raw pointer)
            //
            rv = rawMsg->Init(loop->mRawConn, msgHandle);

            // now let the scoping mechanisms provided by nsCOMPtr manage
            // the reference for us.
            //
            msg = rawMsg;
            
            switch (rv) {

            case NS_OK: {
                PRInt32 errorCode;
                rawMsg->GetErrorCode(&errorCode);
                // maybe a version error, e.g., using v3 on a v2 server.
                // if we're using v3, try v2.
                //
                if (errorCode == LDAP_PROTOCOL_ERROR && 
                   loop->mRawConn->mVersion == nsILDAPConnection::VERSION3) {
                    nsCAutoString password;
                    loop->mRawConn->mVersion = nsILDAPConnection::VERSION2;
                    ldap_set_option(loop->mRawConn->mConnectionHandle,
                          LDAP_OPT_PROTOCOL_VERSION, &loop->mRawConn->mVersion);
                    nsCOMPtr <nsILDAPOperation> operation = 
                      static_cast<nsILDAPOperation *>(static_cast<nsISupports *>(aData));
                    // we pass in an empty password to tell the operation that 
                    // it should use the cached password.
                    //
                    rv = operation->SimpleBind(password);
                    if (NS_SUCCEEDED(rv)) {
                        operationFinished = PR_FALSE;
                        // we don't want to notify callers that we're done...
                        return PR_TRUE;
                    }
                }
                
                // If we're midway through a SASL Bind, we need to continue
                // without letting our caller know what we're up to!
                //
                if (errorCode == LDAP_SASL_BIND_IN_PROGRESS) {
                    struct berval *creds;
                    ldap_parse_sasl_bind_result(
                      loop->mRawConn->mConnectionHandle, msgHandle, 
                      &creds, 0);

                    nsCOMPtr <nsILDAPOperation> operation =
                      static_cast<nsILDAPOperation *>
                      (static_cast<nsISupports *>(aData));

                    rv = operation->SaslStep(creds->bv_val, creds->bv_len);
                    if (NS_SUCCEEDED(rv)) {
                        return PR_TRUE;
                    }
                }
            }
            break;

            case NS_ERROR_LDAP_DECODING_ERROR:
                consoleSvc->LogStringMessage(
                    NS_LITERAL_STRING("LDAP: WARNING: decoding error; possible corrupt data received").get());
            NS_WARNING("CheckLDAPOperationResult(): ldaperrno = "
                           "LDAP_DECODING_ERROR after ldap_result()");
            return PR_TRUE;

            case NS_ERROR_OUT_OF_MEMORY:
                // punt and hope things work out better next time around
            return PR_TRUE;

            case NS_ERROR_ILLEGAL_VALUE:
            case NS_ERROR_UNEXPECTED:
            default:
                // shouldn't happen; internal error
                //
            NS_ERROR("CheckLDAPOperationResult(): nsLDAPMessage::Init() "
                           "returned unexpected value.");

                // punt and hope things work out better next time around
            return PR_TRUE;
            }

            // invoke the callback on the nsILDAPOperation corresponding to 
            // this message
            //
        rv = loop->mRawConn->InvokeMessageCallback(msgHandle, msg, 
                                                    operationFinished);
            if (NS_FAILED(rv)) {
            NS_ERROR("CheckLDAPOperationResult(): error invoking message"
                     " callback");
                // punt and hope things work out better next time around
            return PR_TRUE;
            }

            break;
        }       

    return PR_TRUE;
}
Пример #11
0
// for nsIRunnable.  this thread spins in ldap_result() awaiting the next
// message.  once one arrives, it dispatches it to the nsILDAPMessageListener 
// on the main thread.
//
// XXX do all returns from this function need to do thread cleanup?
//
NS_IMETHODIMP
nsLDAPConnectionLoop::Run(void)
{
    PR_LOG(gLDAPLogModule, PR_LOG_DEBUG, 
           ("nsLDAPConnection::Run() entered\n"));

    // wait for results
    //
    while(1) {

        // Exit this thread if we no longer have an nsLDAPConnection
        // associated with it. We also aquire a lock here, to make sure
        // to avoid a possible race condition when the nsLDAPConnection
        // is destructed during the call to do_QueryReferent() (since that
        // function isn't MT safe).
        //
        nsresult rv;

        PR_Lock(mLock);
        nsCOMPtr<nsILDAPConnection> strongConn = 
            do_QueryReferent(mWeakConn, &rv);
        PR_Unlock(mLock);

        if (NS_FAILED(rv)) {
            mWeakConn = 0;
            return NS_OK;
        }
        // we use a raw connection because we need to call non-interface
        // methods
        mRawConn = static_cast<nsLDAPConnection *>(static_cast<nsILDAPConnection *>(strongConn.get()));

        // XXX deal with timeouts better
        //
        NS_ASSERTION(mRawConn->mConnectionHandle, "nsLDAPConnection::Run(): "
                     "no connection created.\n");

        // We can't enumerate over mPendingOperations itself, because the
        // callback needs to modify mPendingOperations.  So we clone it first,
        // and enumerate over the clone.  It kinda sucks that we need to do
        // this everytime we poll, but the hashtable will pretty much always
        // be small.
        //
        // only clone if the number of pending operations is non-zero
        // otherwise, put the LDAP connection thread to sleep (briefly)
        // until there is pending operations..
        if (mRawConn->mPendingOperations->Count()) {
          nsHashtable *hashtableCopy = mRawConn->mPendingOperations->Clone();
          if (hashtableCopy) {
            hashtableCopy->Enumerate(CheckLDAPOperationResult, this);
            delete hashtableCopy;
          } else {
            // punt and hope it works next time around
            NS_ERROR("nsLDAPConnectionLoop::Run() error cloning hashtable");
          }
        }
        else {
          PR_Sleep(PR_MillisecondsToInterval(40));
        }
    }

    // This will never happen, but here just in case.
    //
    return NS_OK;
}
Пример #12
0
nsresult
nsLDAPConnection::InvokeMessageCallback(LDAPMessage *aMsgHandle, 
                                        nsILDAPMessage *aMsg,
                                        PRBool aRemoveOpFromConnQ)
{
    PRInt32 msgId;
    nsresult rv;
    nsCOMPtr<nsILDAPOperation> operation;
    nsCOMPtr<nsILDAPMessageListener> listener;

#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, ("InvokeMessageCallback entered\n"));
#endif

    // get the message id corresponding to this operation
    //
    msgId = ldap_msgid(aMsgHandle);
    if (msgId == -1) {
        NS_ERROR("nsLDAPConnection::GetCallbackByMessage(): "
                 "ldap_msgid() failed\n");
        return NS_ERROR_FAILURE;
    }

    // get this in key form.  note that using nsVoidKey in this way assumes
    // that sizeof(void *) >= sizeof PRInt32
    //
    nsVoidKey *key = new nsVoidKey(reinterpret_cast<void *>(msgId));
    if (!key)
        return NS_ERROR_OUT_OF_MEMORY;

    // find the operation in question
    operation = getter_AddRefs(static_cast<nsILDAPOperation *>(mPendingOperations->Get(key)));
    if (!operation) {

        PR_LOG(gLDAPLogModule, PR_LOG_WARNING, 
               ("Warning: InvokeMessageCallback(): couldn't find "
                "nsILDAPOperation corresponding to this message id\n"));
        delete key;

        // this may well be ok, since it could just mean that the operation
        // was aborted while some number of messages were already in transit.
        //
        return NS_OK;
    }


    // Make sure the mOperation member is set to this operation before
    // we call the callback.
    //
    static_cast<nsLDAPMessage *>(aMsg)->mOperation = operation;

    // get the message listener object (this may be a proxy for a
    // callback which should happen on another thread)
    //
    rv = operation->GetMessageListener(getter_AddRefs(listener));
    if (NS_FAILED(rv)) {
        NS_ERROR("nsLDAPConnection::InvokeMessageCallback(): probable "
                 "memory corruption: GetMessageListener() returned error");
        delete key;
        return NS_ERROR_UNEXPECTED;
    }

    // invoke the callback 
    //
    if (listener) {
      listener->OnLDAPMessage(aMsg);
    }
    // if requested (ie the operation is done), remove the operation
    // from the connection queue.
    //
    if (aRemoveOpFromConnQ) {
        nsCOMPtr <nsLDAPOperation> operation = 
          getter_AddRefs(static_cast<nsLDAPOperation *>
                                    (mPendingOperations->Get(key)));
        // try to break cycles
        if (operation)
          operation->Clear();
        rv = mPendingOperations->Remove(key);
        if (NS_FAILED(rv)) {
            NS_ERROR("nsLDAPConnection::InvokeMessageCallback: unable to "
                     "remove operation from the connection queue\n");
            delete key;
            return NS_ERROR_UNEXPECTED;
        }

        PR_LOG(gLDAPLogModule, PR_LOG_DEBUG, 
               ("pending operation removed; total pending operations now ="
                " %d\n", mPendingOperations->Count()));
    }

    delete key;
    return NS_OK;
}
// Extracts whatever information we need out of fd (using SSL_*) and passes it
// to SSLServerCertVerificationJob::Dispatch. SSLServerCertVerificationJob should
// never do anything with fd except logging.
SECStatus
AuthCertificateHook(void *arg, PRFileDesc *fd, PRBool checkSig, PRBool isServer)
{
  // Runs on the socket transport thread

  PR_LOG(gPIPNSSLog, PR_LOG_DEBUG,
         ("[%p] starting AuthCertificateHook\n", fd));

  // Modern libssl always passes PR_TRUE for checkSig, and we have no means of
  // doing verification without checking signatures.
  NS_ASSERTION(checkSig, "AuthCertificateHook: checkSig unexpectedly false");

  // PSM never causes libssl to call this function with PR_TRUE for isServer,
  // and many things in PSM assume that we are a client.
  NS_ASSERTION(!isServer, "AuthCertificateHook: isServer unexpectedly true");

  nsNSSSocketInfo *socketInfo = static_cast<nsNSSSocketInfo*>(arg);
  
  if (socketInfo) {
    // This is the first callback during full handshakes.
    socketInfo->SetFirstServerHelloReceived();
  }

  ScopedCERTCertificate serverCert(SSL_PeerCertificate(fd));

  if (!checkSig || isServer || !socketInfo || !serverCert) {
      PR_SetError(PR_INVALID_STATE_ERROR, 0);
      return SECFailure;
  }
      
  if (BlockServerCertChangeForSpdy(socketInfo, serverCert) != SECSuccess)
    return SECFailure;

  bool onSTSThread;
  nsresult nrv;
  nsCOMPtr<nsIEventTarget> sts
    = do_GetService(NS_SOCKETTRANSPORTSERVICE_CONTRACTID, &nrv);
  if (NS_SUCCEEDED(nrv)) {
    nrv = sts->IsOnCurrentThread(&onSTSThread);
  }

  if (NS_FAILED(nrv)) {
    NS_ERROR("Could not get STS service or IsOnCurrentThread failed");
    PR_SetError(PR_UNKNOWN_ERROR, 0);
    return SECFailure;
  }

  uint32_t providerFlags = 0;
  socketInfo->GetProviderFlags(&providerFlags);

  if (onSTSThread) {

    // We *must* do certificate verification on a background thread because
    // we need the socket transport thread to be free for our OCSP requests,
    // and we *want* to do certificate verification on a background thread
    // because of the performance benefits of doing so.
    socketInfo->SetCertVerificationWaiting();
    SECStatus rv = SSLServerCertVerificationJob::Dispatch(
                           static_cast<const void *>(fd), socketInfo, serverCert,
                           providerFlags);
    return rv;
  }
  
  // We can't do certificate verification on a background thread, because the
  // thread doing the network I/O may not interrupt its network I/O on receipt
  // of our SSLServerCertVerificationResult event, and/or it might not even be
  // a non-blocking socket.
  SECStatus rv = AuthCertificate(socketInfo, serverCert, providerFlags);
  if (rv == SECSuccess) {
    return SECSuccess;
  }

  PRErrorCode error = PR_GetError();
  if (error != 0) {
    RefPtr<CertErrorRunnable> runnable(CreateCertErrorRunnable(
                    error, socketInfo, serverCert,
                    static_cast<const void *>(fd), providerFlags));
    if (!runnable) {
      // CreateCertErrorRunnable sets a new error code when it fails
      error = PR_GetError();
    } else {
      // We have to return SECSuccess or SECFailure based on the result of the
      // override processing, so we must block this thread waiting for it. The
      // CertErrorRunnable will NOT dispatch the result at all, since we passed
      // false for CreateCertErrorRunnable's async parameter
      nrv = runnable->DispatchToMainThreadAndWait();
      if (NS_FAILED(nrv)) {
        NS_ERROR("Failed to dispatch CertErrorRunnable");
        PR_SetError(PR_INVALID_STATE_ERROR, 0);
        return SECFailure;
      }

      if (!runnable->mResult) {
        NS_ERROR("CertErrorRunnable did not set result");
        PR_SetError(PR_INVALID_STATE_ERROR, 0);
        return SECFailure;
      }

      if (runnable->mResult->mErrorCode == 0) {
        return SECSuccess; // cert error override occurred.
      }

      // We must call SetCanceled here to set the error message type
      // in case it isn't PlainErrorMessage, which is what we would
      // default to if we just called
      // PR_SetError(runnable->mResult->mErrorCode, 0) and returned
      // SECFailure without doing this.
      socketInfo->SetCanceled(runnable->mResult->mErrorCode,
                              runnable->mResult->mErrorMessageType);
      error = runnable->mResult->mErrorCode;
    }
  }

  if (error == 0) {
    NS_ERROR("error code not set");
    error = PR_UNKNOWN_ERROR;
  }

  PR_SetError(error, 0);
  return SECFailure;
}
Пример #14
0
bool
XRemoteClient::WaitForResponse(Window aWindow, char **aResponse,
                               bool *aDestroyed, Atom aCommandAtom)
{
  bool done = false;
  bool accepted = false;

  while (!done) {
    XEvent event;
    XNextEvent (mDisplay, &event);
    if (event.xany.type == DestroyNotify &&
        event.xdestroywindow.window == aWindow) {
      /* Print to warn user...*/
      PR_LOG(sRemoteLm, PR_LOG_DEBUG,
             ("window 0x%x was destroyed.\n",
              (unsigned int) aWindow));
      *aResponse = strdup("Window was destroyed while reading response.");
      *aDestroyed = true;
      return false;
    }
    else if (event.xany.type == PropertyNotify &&
             event.xproperty.state == PropertyNewValue &&
             event.xproperty.window == aWindow &&
             event.xproperty.atom == mMozResponseAtom) {
      Atom actual_type;
      int actual_format;
      unsigned long nitems, bytes_after;
      unsigned char *data = 0;
      Bool result;
      result = XGetWindowProperty (mDisplay, aWindow, mMozResponseAtom,
                                   0, (65536 / sizeof (long)),
                                   True, /* atomic delete after */
                                   XA_STRING,
                                   &actual_type, &actual_format,
                                   &nitems, &bytes_after,
                                   &data);
      if (result != Success) {
        PR_LOG(sRemoteLm, PR_LOG_DEBUG,
               ("failed reading " MOZILLA_RESPONSE_PROP
                " from window 0x%0x.\n",
                (unsigned int) aWindow));
        *aResponse = strdup("Internal error reading response from window.");
        done = true;
      }
      else if (!data || strlen((char *) data) < 5) {
        PR_LOG(sRemoteLm, PR_LOG_DEBUG,
               ("invalid data on " MOZILLA_RESPONSE_PROP
                " property of window 0x%0x.\n",
                (unsigned int) aWindow));
        *aResponse = strdup("Server returned invalid data in response.");
        done = true;
      }
      else if (*data == '1') {  /* positive preliminary reply */
        PR_LOG(sRemoteLm, PR_LOG_DEBUG,  ("%s\n", data + 4));
        /* keep going */
        done = false;
      }

      else if (!strncmp ((char *)data, "200", 3)) { /* positive completion */
        *aResponse = strdup((char *)data);
        accepted = true;
        done = true;
      }

      else if (*data == '2') {  /* positive completion */
        PR_LOG(sRemoteLm, PR_LOG_DEBUG, ("%s\n", data + 4));
        *aResponse = strdup((char *)data);
        accepted = true;
        done = true;
      }

      else if (*data == '3') {  /* positive intermediate reply */
        PR_LOG(sRemoteLm, PR_LOG_DEBUG,
               ("internal error: "
                "server wants more information?  (%s)\n",
                data));
        *aResponse = strdup((char *)data);
        done = true;
      }

      else if (*data == '4' ||  /* transient negative completion */
               *data == '5') {  /* permanent negative completion */
        PR_LOG(sRemoteLm, PR_LOG_DEBUG, ("%s\n", data + 4));
        *aResponse = strdup((char *)data);
        done = true;
      }

      else {
        PR_LOG(sRemoteLm, PR_LOG_DEBUG,
               ("unrecognised " MOZILLA_RESPONSE_PROP
                " from window 0x%x: %s\n",
                (unsigned int) aWindow, data));
        *aResponse = strdup((char *)data);
        done = true;
      }

      if (data)
        XFree(data);
    }

    else if (event.xany.type == PropertyNotify &&
             event.xproperty.window == aWindow &&
             event.xproperty.state == PropertyDelete &&
             event.xproperty.atom == aCommandAtom) {
      PR_LOG(sRemoteLm, PR_LOG_DEBUG,
             ("(server 0x%x has accepted "
              MOZILLA_COMMAND_PROP ".)\n",
              (unsigned int) aWindow));
    }
    
  }

  return accepted;
}
Пример #15
0
nsresult nsMsgPurgeService::SearchFolderToPurge(nsIMsgFolder *folder, PRInt32 purgeInterval)
{
    nsresult rv;
    mSearchSession = do_CreateInstance(NS_MSGSEARCHSESSION_CONTRACTID, &rv);
    NS_ENSURE_SUCCESS(rv, rv);
    mSearchSession->RegisterListener(this,
                                     nsIMsgSearchSession::allNotifications);

    // update the time we attempted to purge this folder
    char dateBuf[100];
    dateBuf[0] = '\0';
    PRExplodedTime exploded;
    PR_ExplodeTime(PR_Now(), PR_LocalTimeParameters, &exploded);
    PR_FormatTimeUSEnglish(dateBuf, sizeof(dateBuf), "%a %b %d %H:%M:%S %Y", &exploded);
    folder->SetStringProperty("curJunkFolderLastPurgeTime", nsDependentCString(dateBuf));
    PR_LOG(MsgPurgeLogModule, PR_LOG_ALWAYS, ("curJunkFolderLastPurgeTime is now %s", dateBuf));

    nsCOMPtr<nsIMsgIncomingServer> server;
    rv = folder->GetServer(getter_AddRefs(server)); //we need to get the folder's server scope because imap can have local junk folder
    NS_ENSURE_SUCCESS(rv, rv);

    nsMsgSearchScopeValue searchScope;
    server->GetSearchScope(&searchScope);

    mSearchSession->AddScopeTerm(searchScope, folder);

    // look for messages older than the cutoff
    // you can't also search by junk status, see
    // nsMsgPurgeService::OnSearchHit()
    nsCOMPtr <nsIMsgSearchTerm> searchTerm;
    mSearchSession->CreateTerm(getter_AddRefs(searchTerm));
    if (searchTerm)
    {
        searchTerm->SetAttrib(nsMsgSearchAttrib::AgeInDays);
        searchTerm->SetOp(nsMsgSearchOp::IsGreaterThan);
        nsCOMPtr<nsIMsgSearchValue> searchValue;
        searchTerm->GetValue(getter_AddRefs(searchValue));
        if (searchValue)
        {
            searchValue->SetAttrib(nsMsgSearchAttrib::AgeInDays);
            searchValue->SetAge((PRUint32) purgeInterval);
            searchTerm->SetValue(searchValue);
        }
        searchTerm->SetBooleanAnd(PR_FALSE);
        mSearchSession->AppendTerm(searchTerm);
    }

    // we are about to search
    // create mHdrsToDelete array (if not previously created)
    if (!mHdrsToDelete)
    {
        mHdrsToDelete = do_CreateInstance(NS_ARRAY_CONTRACTID, &rv);
        NS_ENSURE_SUCCESS(rv, rv);
    }
    else
    {
        PRUint32 count;
        mHdrsToDelete->GetLength(&count);
        NS_ASSERTION(count == 0, "mHdrsToDelete is not empty");
        if (count > 0)
            mHdrsToDelete->Clear();  // this shouldn't happen
    }

    mSearchFolder = folder;
    return mSearchSession->Search(nsnull);
}
Пример #16
0
void
nsPNGDecoder::warning_callback(png_structp png_ptr, png_const_charp warning_msg)
{
  PR_LOG(GetPNGLog(), PR_LOG_WARNING, ("libpng warning: %s\n", warning_msg));
}
Пример #17
0
NS_IMETHODIMP nsMsgPurgeService::OnNewSearch()
{
    PR_LOG(MsgPurgeLogModule, PR_LOG_ALWAYS, ("on new search"));
    return NS_OK;
}
Пример #18
0
NS_IMETHODIMP 
XULContentSinkImpl::HandleStartElement(const PRUnichar *aName, 
                                       const PRUnichar **aAtts,
                                       uint32_t aAttsCount, 
                                       int32_t aIndex, 
                                       uint32_t aLineNumber)
{ 
  // XXX Hopefully the parser will flag this before we get here. If
  // we're in the epilog, there should be no new elements
  NS_PRECONDITION(mState != eInEpilog, "tag in XUL doc epilog");
  NS_PRECONDITION(aIndex >= -1, "Bogus aIndex");
  NS_PRECONDITION(aAttsCount % 2 == 0, "incorrect aAttsCount");
  // Adjust aAttsCount so it's the actual number of attributes
  aAttsCount /= 2;
  
  if (mState == eInEpilog)
      return NS_ERROR_UNEXPECTED;

  if (mState != eInScript) {
      FlushText();
  }

  int32_t nameSpaceID;
  nsCOMPtr<nsIAtom> prefix, localName;
  nsContentUtils::SplitExpatName(aName, getter_AddRefs(prefix),
                                 getter_AddRefs(localName), &nameSpaceID);

  nsCOMPtr<nsINodeInfo> nodeInfo;
  nodeInfo = mNodeInfoManager->GetNodeInfo(localName, prefix, nameSpaceID,
                                           nsIDOMNode::ELEMENT_NODE);
  NS_ENSURE_TRUE(nodeInfo, NS_ERROR_OUT_OF_MEMORY);
  
  nsresult rv = NS_OK;
  switch (mState) {
  case eInProlog:
      // We're the root document element
      rv = OpenRoot(aAtts, aAttsCount, nodeInfo);
      break;

  case eInDocumentElement:
      rv = OpenTag(aAtts, aAttsCount, aLineNumber, nodeInfo);
      break;

  case eInEpilog:
  case eInScript:
      PR_LOG(gLog, PR_LOG_WARNING,
             ("xul: warning: unexpected tags in epilog at line %d",
             aLineNumber));
      rv = NS_ERROR_UNEXPECTED; // XXX
      break;
  }

  // Set the ID attribute atom on the node info object for this node
  if (aIndex != -1 && NS_SUCCEEDED(rv)) {
    nsCOMPtr<nsIAtom> IDAttr = do_GetAtom(aAtts[aIndex]);

    if (IDAttr) {
      nodeInfo->SetIDAttributeAtom(IDAttr);
    }
  }

  return rv;
}
Пример #19
0
nsresult nsAutoConfig::downloadAutoConfig()
{
    nsresult rv;
    nsCAutoString emailAddr;
    nsXPIDLCString urlName;
    static bool firstTime = true;
    
    if (mConfigURL.IsEmpty()) {
        PR_LOG(MCD, PR_LOG_DEBUG, ("global config url is empty - did you set autoadmin.global_config_url?\n"));
        NS_WARNING("AutoConfig called without global_config_url");
        return NS_OK;
    }
    
    // If there is an email address appended as an argument to the ConfigURL
    // in the previous read, we need to remove it when timer kicks in and 
    // downloads the autoconfig file again. 
    // If necessary, the email address will be added again as an argument.
    PRInt32 index = mConfigURL.RFindChar((PRUnichar)'?');
    if (index != -1)
        mConfigURL.Truncate(index);

    // Clean up the previous read, the new read is going to use the same buffer
    if (!mBuf.IsEmpty())
        mBuf.Truncate(0);

    // Get the preferences branch and save it to the member variable
    if (!mPrefBranch) {
        nsCOMPtr<nsIPrefService> prefs =
            do_GetService(NS_PREFSERVICE_CONTRACTID, &rv);
        if (NS_FAILED(rv)) 
            return rv;
    
        rv = prefs->GetBranch(nsnull,getter_AddRefs(mPrefBranch));
        if (NS_FAILED(rv))
            return rv;
    }
    
    // Check to see if the network is online/offline 
    nsCOMPtr<nsIIOService> ios = do_GetService(NS_IOSERVICE_CONTRACTID, &rv);
    if (NS_FAILED(rv)) 
        return rv;
    
    bool offline;
    rv = ios->GetOffline(&offline);
    if (NS_FAILED(rv)) 
        return rv;
    
    if (offline) {
        bool offlineFailover;
        rv = mPrefBranch->GetBoolPref("autoadmin.offline_failover", 
                                      &offlineFailover);
        // Read the failover.jsc if the network is offline and the pref says so
        if (NS_SUCCEEDED(rv) && offlineFailover)
            return readOfflineFile();
    }

    /* Append user's identity at the end of the URL if the pref says so.
       First we are checking for the user's email address but if it is not
       available in the case where the client is used without messenger, user's
       profile name will be used as an unique identifier
    */
    bool appendMail;
    rv = mPrefBranch->GetBoolPref("autoadmin.append_emailaddr", &appendMail);
    if (NS_SUCCEEDED(rv) && appendMail) {
        rv = getEmailAddr(emailAddr);
        if (NS_SUCCEEDED(rv) && emailAddr.get()) {
            /* Adding the unique identifier at the end of autoconfig URL. 
               In this case the autoconfig URL is a script and 
               emailAddr as passed as an argument 
            */
            mConfigURL.Append("?");
            mConfigURL.Append(emailAddr); 
        }
    }
    
    // create a new url 
    nsCOMPtr<nsIURI> url;
    nsCOMPtr<nsIChannel> channel;
    
    rv = NS_NewURI(getter_AddRefs(url), mConfigURL.get(), nsnull, nsnull);
    if (NS_FAILED(rv))
    {
        PR_LOG(MCD, PR_LOG_DEBUG, ("failed to create URL - is autoadmin.global_config_url valid? - %s\n", mConfigURL.get()));
        return rv;
    }

    PR_LOG(MCD, PR_LOG_DEBUG, ("running MCD url %s\n", mConfigURL.get()));
    // open a channel for the url
    rv = NS_NewChannel(getter_AddRefs(channel),url, nsnull, nsnull, nsnull, nsIRequest::INHIBIT_PERSISTENT_CACHING | nsIRequest::LOAD_BYPASS_CACHE);
    if (NS_FAILED(rv)) 
        return rv;

    rv = channel->AsyncOpen(this, nsnull); 
    if (NS_FAILED(rv)) {
        readOfflineFile();
        return rv;
    }
    
    // Set a repeating timer if the pref is set.
    // This is to be done only once.
    // Also We are having the event queue processing only for the startup
    // It is not needed with the repeating timer.
    if (firstTime) {
        firstTime = PR_FALSE;
    
        // Getting the current thread. If we start an AsyncOpen, the thread
        // needs to wait before the reading of autoconfig is done

        nsCOMPtr<nsIThread> thread = do_GetCurrentThread();
        NS_ENSURE_STATE(thread);
    
        /* process events until we're finished. AutoConfig.jsc reading needs
           to be finished before the browser starts loading up
           We are waiting for the mLoaded which will be set through 
           onStopRequest or readOfflineFile methods
           There is a possibility of deadlock so we need to make sure
           that mLoaded will be set to true in any case (success/failure)
        */
        
        while (!mLoaded)
            NS_ENSURE_STATE(NS_ProcessNextEvent(thread));
        
        PRInt32 minutes;
        rv = mPrefBranch->GetIntPref("autoadmin.refresh_interval", 
                                     &minutes);
        if (NS_SUCCEEDED(rv) && minutes > 0) {
            // Create a new timer and pass this nsAutoConfig 
            // object as a timer callback. 
            mTimer = do_CreateInstance("@mozilla.org/timer;1",&rv);
            if (NS_FAILED(rv)) 
                return rv;
            rv = mTimer->InitWithCallback(this, minutes * 60 * 1000, 
                             nsITimer::TYPE_REPEATING_SLACK);
            if (NS_FAILED(rv)) 
                return rv;
        }
    } //first_time
    
    return NS_OK;
} // nsPref::downloadAutoConfig()
Пример #20
0
nsresult
XULContentSinkImpl::OpenTag(const PRUnichar** aAttributes, 
                            const uint32_t aAttrLen,
                            const uint32_t aLineNumber,
                            nsINodeInfo *aNodeInfo)
{
    nsresult rv;

    // Create the element
    nsXULPrototypeElement* element;
    rv = CreateElement(aNodeInfo, &element);

    if (NS_FAILED(rv)) {
#ifdef PR_LOGGING
        if (PR_LOG_TEST(gLog, PR_LOG_ERROR)) {
            nsAutoString anodeC;
            aNodeInfo->GetName(anodeC);
            PR_LOG(gLog, PR_LOG_ERROR,
                   ("xul: unable to create element '%s' at line %d",
                    NS_ConvertUTF16toUTF8(anodeC).get(),
                    aLineNumber));
        }
#endif

        return rv;
    }

    // Link this element to its parent.
    nsPrototypeArray* children = nullptr;
    rv = mContextStack.GetTopChildren(&children);
    if (NS_FAILED(rv)) {
        delete element;
        return rv;
    }

    // Add the attributes
    rv = AddAttributes(aAttributes, aAttrLen, element);
    if (NS_FAILED(rv)) return rv;

    children->AppendElement(element);

    if (aNodeInfo->Equals(nsGkAtoms::script, kNameSpaceID_XHTML) || 
        aNodeInfo->Equals(nsGkAtoms::script, kNameSpaceID_XUL)) {
        // Do scripty things now
        rv = OpenScript(aAttributes, aLineNumber);
        NS_ENSURE_SUCCESS(rv, rv);

        NS_ASSERTION(mState == eInScript || mState == eInDocumentElement,
                     "Unexpected state");
        if (mState == eInScript) {
            // OpenScript has pushed the nsPrototypeScriptElement onto the 
            // stack, so we're done.
            return NS_OK;
        }
    }

    // Push the element onto the context stack, so that child
    // containers will hook up to us as their parent.
    rv = mContextStack.Push(element, mState);
    if (NS_FAILED(rv)) return rv;

    mState = eInDocumentElement;
    return NS_OK;
}
nsresult
nsRDFConInstanceTestNode::FilterInstantiations(InstantiationSet& aInstantiations,
                                               bool* aCantHandleYet) const
{
    nsresult rv;

    if (aCantHandleYet)
        *aCantHandleYet = false;

    nsCOMPtr<nsIRDFContainerUtils> rdfc
        = do_GetService("@mozilla.org/rdf/container-utils;1");

    if (! rdfc)
        return NS_ERROR_FAILURE;

    nsIRDFDataSource* ds = mProcessor->GetDataSource();

    InstantiationSet::Iterator last = aInstantiations.Last();
    for (InstantiationSet::Iterator inst = aInstantiations.First(); inst != last; ++inst) {
        nsCOMPtr<nsIRDFNode> value;
        if (! inst->mAssignments.GetAssignmentFor(mContainerVariable, getter_AddRefs(value))) {
            NS_ERROR("can't do unbounded container testing");
            return NS_ERROR_UNEXPECTED;
        }

        nsCOMPtr<nsIRDFResource> valueres = do_QueryInterface(value);
        if (! valueres) {
            aInstantiations.Erase(inst--);
            continue;
        }

#ifdef PR_LOGGING
        if (PR_LOG_TEST(gXULTemplateLog, PR_LOG_DEBUG)) {
            const char* container = "(unbound)";
            valueres->GetValueConst(&container);

            PR_LOG(gXULTemplateLog, PR_LOG_DEBUG,
                   ("nsRDFConInstanceTestNode[%p]::FilterInstantiations() container=[%s]",
                    this, container));
        }
#endif

        nsCOMPtr<nsIRDFContainer> rdfcontainer;

        bool isRDFContainer;
        rv = rdfc->IsContainer(ds, valueres, &isRDFContainer);
        if (NS_FAILED(rv)) return rv;

        if (mEmpty != eDontCare || mContainer != eDontCare) {
            Test empty = eDontCare;
            Test container = eDontCare;

            if (isRDFContainer) {
                // It's an RDF container. Use the container utilities
                // to deduce what's in it.
                container = eTrue;

                // XXX should cache the factory
                rdfcontainer = do_CreateInstance("@mozilla.org/rdf/container;1", &rv);
                if (NS_FAILED(rv)) return rv;

                rv = rdfcontainer->Init(ds, valueres);
                if (NS_FAILED(rv)) return rv;

                int32_t count;
                rv = rdfcontainer->GetCount(&count);
                if (NS_FAILED(rv)) return rv;

                empty = (count == 0) ? eTrue : eFalse;
            } else {
                empty = eTrue;
                container = eFalse;

                // First do the simple check of finding some outward
                // arcs; there should be only a few containment arcs, so this can
                // save us time from dealing with an iterator later on
                nsResourceSet& containmentProps = mProcessor->ContainmentProperties();
                for (nsResourceSet::ConstIterator property = containmentProps.First();
                     property != containmentProps.Last();
                     ++property) {
                    nsCOMPtr<nsIRDFNode> target;
                    rv = ds->GetTarget(valueres, *property, true, getter_AddRefs(target));
                    if (NS_FAILED(rv)) return rv;

                    if (target != nullptr) {
                        // bingo. we found one.
                        empty = eFalse;
                        container = eTrue;
                        break;
                    }
                }

                // if we still don't think its a container, but we
                // want to know for sure whether it is or not, we need
                // to check ArcLabelsOut for potential container arcs.
                if (container == eFalse && mContainer != eDontCare) {
                    nsCOMPtr<nsISimpleEnumerator> arcsout;
                    rv = ds->ArcLabelsOut(valueres, getter_AddRefs(arcsout));
                    if (NS_FAILED(rv)) return rv;

                    while (1) {
                        bool hasmore;
                        rv = arcsout->HasMoreElements(&hasmore);
                        if (NS_FAILED(rv)) return rv;

                        if (! hasmore)
                            break;

                        nsCOMPtr<nsISupports> isupports;
                        rv = arcsout->GetNext(getter_AddRefs(isupports));
                        if (NS_FAILED(rv)) return rv;

                        nsCOMPtr<nsIRDFResource> property = do_QueryInterface(isupports);
                        NS_ASSERTION(property != nullptr, "not a property");
                        if (! property)
                            return NS_ERROR_UNEXPECTED;

                        if (mProcessor->ContainmentProperties().Contains(property)) {
                            container = eTrue;
                            break;
                        }
                    }
                }
            }

            PR_LOG(gXULTemplateLog, PR_LOG_DEBUG,
                   ("    empty => %s",
                    (empty == mEmpty) ? "consistent" : "inconsistent"));

            PR_LOG(gXULTemplateLog, PR_LOG_DEBUG,
                   ("    container => %s",
                    (container == mContainer) ? "consistent" : "inconsistent"));

            if (((mEmpty == empty) && (mContainer == container)) ||
                ((mEmpty == eDontCare) && (mContainer == container)) ||
                ((mContainer == eDontCare) && (mEmpty == empty)))
            {
                Element* element =
                    nsRDFConInstanceTestNode::Element::Create(valueres, container, empty);

                if (! element)
                    return NS_ERROR_OUT_OF_MEMORY;

                inst->AddSupportingElement(element);
            }
            else {
                aInstantiations.Erase(inst--);
            }
        }
    }

    return NS_OK;
}
Пример #22
0
// this is used to populate comp fields with Unicode data
nsresult nsMapiHook::PopulateCompFields(lpnsMapiMessage aMessage,
                                    nsIMsgCompFields * aCompFields)
{
  nsresult rv = NS_OK ;

  if (aMessage->lpOriginator)
    aCompFields->SetFrom (NS_ConvertASCIItoUTF16((char *) aMessage->lpOriginator->lpszAddress));

  nsAutoString To ;
  nsAutoString Cc ;
  nsAutoString Bcc ;

  NS_NAMED_LITERAL_STRING(Comma, ",");

  if (aMessage->lpRecips)
  {
    for (int i=0 ; i < (int) aMessage->nRecipCount ; i++)
    {
      if (aMessage->lpRecips[i].lpszAddress || aMessage->lpRecips[i].lpszName)
      {
        const char *addressWithoutType = (aMessage->lpRecips[i].lpszAddress)
          ? aMessage->lpRecips[i].lpszAddress : aMessage->lpRecips[i].lpszName;
        if (!PL_strncasecmp(addressWithoutType, "SMTP:", 5))
          addressWithoutType += 5;
        switch (aMessage->lpRecips[i].ulRecipClass)
        {
        case MAPI_TO :
          if (!To.IsEmpty())
            To += Comma;
          To.Append(NS_ConvertASCIItoUTF16(addressWithoutType));
          break;

        case MAPI_CC :
          if (!Cc.IsEmpty())
            Cc += Comma;
          Cc.Append(NS_ConvertASCIItoUTF16(addressWithoutType));
          break;

        case MAPI_BCC :
          if (!Bcc.IsEmpty())
            Bcc += Comma;
          Bcc.Append(NS_ConvertASCIItoUTF16(addressWithoutType));
          break;
        }
      }
    }
  }

  PR_LOG(MAPI, PR_LOG_DEBUG, ("to: %s cc: %s bcc: %s \n", NS_ConvertUTF16toUTF8(To).get(), NS_ConvertUTF16toUTF8(Cc).get(), NS_ConvertUTF16toUTF8(Bcc).get()));
  // set To, Cc, Bcc
  aCompFields->SetTo (To) ;
  aCompFields->SetCc (Cc) ;
  aCompFields->SetBcc (Bcc) ;

  // set subject
  if (aMessage->lpszSubject)
    aCompFields->SetSubject(NS_ConvertASCIItoUTF16(aMessage->lpszSubject));

  // handle attachments as File URL
  rv = HandleAttachments (aCompFields, aMessage->nFileCount, aMessage->lpFiles, true) ;
  if (NS_FAILED(rv)) return rv ;

  // set body
  if (aMessage->lpszNoteText)
  {
      nsString Body;
      CopyASCIItoUTF16(aMessage->lpszNoteText, Body);
      if (Body.Last() != '\n')
        Body.AppendLiteral(CRLF);

      if (Body.Find("<html>") == kNotFound)
        aCompFields->SetForcePlainText(true);

      rv = aCompFields->SetBody(Body) ;
  }
  return rv ;
}
nsresult JNICALL EmbedEventListener::takeActionOnNode(nsCOMPtr<nsIDOMNode> currentNode,
						      void *myObject)
{
    nsresult rv = NS_OK;
    nsString nodeInfo, nodeName, nodeValue; //, nodeDepth;
    jstring jNodeName, jNodeValue;
    PRUint32 depth = 0;
    EmbedEventListener *curThis = nsnull;
    //const PRUint32 depthStrLen = 20;
    //    char depthStr[depthStrLen];
    JNIEnv *env = (JNIEnv *) JNU_GetEnv(gVm, JNI_VERSION);

    PR_ASSERT(nsnull != myObject);
    curThis = (EmbedEventListener *) myObject;
    depth = curThis->mInverseDepth++; 

    if (!(curThis->mProperties)) {
        return rv;
    }
    // encode the depth of the node
    //    PR_snprintf(depthStr, depthStrLen, "depthFromLeaf:%d", depth);
    //    nodeDepth = (const char *) depthStr;

    // Store the name and the value of this node

    {
        // get the name and prepend the depth
        rv = currentNode->GetNodeName(nodeInfo);
        if (NS_FAILED(rv)) {
            return rv;
        }
        //        nodeName = nodeDepth;
        //        nodeName += nodeInfo;
        nodeName = nodeInfo;
        
        if (prLogModuleInfo) {
            char * nodeInfoCStr = ToNewCString(nodeName);
            PR_LOG(prLogModuleInfo, 4, ("%s", nodeInfoCStr));
            nsMemory::Free(nodeInfoCStr);
        }
        
        rv = currentNode->GetNodeValue(nodeInfo);
        if (NS_FAILED(rv)) {
            return rv;
        }
        //        nodeValue = nodeDepth;
        //        nodeValue += nodeInfo;
        nodeValue = nodeInfo;
        
        if (prLogModuleInfo) {
            char * nodeInfoCStr = ToNewCString(nodeName);
            PR_LOG(prLogModuleInfo, 4, ("%s", (const char *)nodeInfoCStr));
            nsMemory::Free(nodeInfoCStr);
        }
        
        jNodeName = ::util_NewString(env, nodeName.get(), 
                                     nodeName.Length());
        jNodeValue = ::util_NewString(env, nodeValue.get(), 
                                      nodeValue.Length());
        
        util_StoreIntoPropertiesObject(env, (jobject) curThis->mProperties,
                                       (jobject) jNodeName, 
                                       (jobject) jNodeValue, 
                                       (jobject) 
                                       &(curThis->mOwner->GetWrapperFactory()->shareContext));
        if (jNodeName) {
            ::util_DeleteString(env, jNodeName);
        }
        if (jNodeValue) {
            ::util_DeleteString(env, jNodeValue);
        }
    } // end of Storing the name and value of this node

    // store any attributes of this node
    {
        nsCOMPtr<nsIDOMNamedNodeMap> nodeMap;
        rv = currentNode->GetAttributes(getter_AddRefs(nodeMap));
        if (NS_FAILED(rv) || !nodeMap) {
            return rv;
        }
        PRUint32 length, i;
        rv = nodeMap->GetLength(&length);
        if (NS_FAILED(rv)) {
            return rv;
        }
        for (i = 0; i < length; i++) {
            rv = nodeMap->Item(i, getter_AddRefs(currentNode));
            
            if (nsnull == currentNode) {
                return rv;
            }
            
            rv = currentNode->GetNodeName(nodeInfo);
            if (NS_FAILED(rv)) {
                return rv;
            }
            //            nodeName = nodeDepth;
            //            nodeName += nodeInfo;
            nodeName = nodeInfo;

            if (prLogModuleInfo) {
                char * nodeInfoCStr = ToNewCString(nodeName);
                PR_LOG(prLogModuleInfo, 4, 
                       ("attribute[%d], %s", i, (const char *)nodeInfoCStr));
                nsMemory::Free(nodeInfoCStr);
            }
            
            rv = currentNode->GetNodeValue(nodeInfo);
            if (NS_FAILED(rv)) {
                return rv;
            }
            //            nodeValue = nodeDepth;
            //            nodeValue += nodeInfo;
            nodeValue = nodeInfo;
            
            if (prLogModuleInfo) {
                char * nodeInfoCStr = ToNewCString(nodeName);
                PR_LOG(prLogModuleInfo, 4, 
                       ("attribute[%d] %s", i,(const char *)nodeInfoCStr));
                nsMemory::Free(nodeInfoCStr);
            }
            jNodeName = ::util_NewString(env, nodeName.get(), 
                                         nodeName.Length());
            jNodeValue = ::util_NewString(env, nodeValue.get(), 
                                          nodeValue.Length());
            
            util_StoreIntoPropertiesObject(env, (jobject) curThis->mProperties,
                                           (jobject) jNodeName, 
                                           (jobject) jNodeValue, 
                                           (jobject) 
                                           &(curThis->mOwner->GetWrapperFactory()->shareContext));
            if (jNodeName) {
                ::util_DeleteString(env, jNodeName);
            }
            if (jNodeValue) {
                ::util_DeleteString(env, jNodeValue);
            }
        }
    } // end of storing the attributes
        
    return rv;
}
Пример #24
0
nsresult nsMapiHook::HandleAttachments (nsIMsgCompFields * aCompFields, int32_t aFileCount,
                                        lpnsMapiFileDesc aFiles, BOOL aIsUnicode)
{
    nsresult rv = NS_OK ;

    nsAutoCString Attachments ;
    nsAutoCString TempFiles ;

    nsCOMPtr <nsIFile> pFile = do_CreateInstance (NS_LOCAL_FILE_CONTRACTID, &rv) ;
    if (NS_FAILED(rv) || (!pFile) ) return rv ;
    nsCOMPtr <nsIFile> pTempDir = do_CreateInstance (NS_LOCAL_FILE_CONTRACTID, &rv) ;
    if (NS_FAILED(rv) || (!pTempDir) ) return rv ;

    for (int i=0 ; i < aFileCount ; i++)
    {
        bool bTempFile = false ;
        if (aFiles[i].lpszPathName)
        {
            // check if attachment exists
            if (aIsUnicode)
                pFile->InitWithPath (nsDependentString(aFiles[i].lpszPathName));
            else
                pFile->InitWithNativePath (nsDependentCString((const char*)aFiles[i].lpszPathName));

            bool bExist ;
            rv = pFile->Exists(&bExist) ;
            PR_LOG(MAPI, PR_LOG_DEBUG, ("nsMapiHook::HandleAttachments: filename: %s path: %s exists = %s \n", (const char*)aFiles[i].lpszFileName, (const char*)aFiles[i].lpszPathName, bExist ? "true" : "false"));
            if (NS_FAILED(rv) || (!bExist) ) return NS_ERROR_FILE_TARGET_DOES_NOT_EXIST ;

            //Temp Directory
            nsCOMPtr <nsIFile> pTempDir;
            NS_GetSpecialDirectory(NS_OS_TEMP_DIR, getter_AddRefs(pTempDir));

            // create a new sub directory called moz_mapi underneath the temp directory
            pTempDir->AppendRelativePath(NS_LITERAL_STRING("moz_mapi"));
            pTempDir->Exists (&bExist) ;
            if (!bExist)
            {
                rv = pTempDir->Create(nsIFile::DIRECTORY_TYPE, 777) ;
                if (NS_FAILED(rv)) return rv ;
            }

            // rename or copy the existing temp file with the real file name

            nsAutoString leafName ;
            // convert to Unicode using Platform charset
            // leafName already contains a unicode leafName from lpszPathName. If we were given
            // a value for lpszFileName, use it. Otherwise stick with leafName
            if (aFiles[i].lpszFileName)
            {
              nsAutoString wholeFileName;
                if (aIsUnicode)
                    wholeFileName.Assign(aFiles[i].lpszFileName);
                else
                    ConvertToUnicode(nsMsgI18NFileSystemCharset(), (char *) aFiles[i].lpszFileName, wholeFileName);
                // need to find the last '\' and find the leafname from that.
                int32_t lastSlash = wholeFileName.RFindChar(PRUnichar('\\'));
                if (lastSlash != kNotFound)
                  leafName.Assign(Substring(wholeFileName, lastSlash + 1));
                else
                  leafName.Assign(wholeFileName);
            }
            else
              pFile->GetLeafName (leafName);

            nsCOMPtr<nsIMsgAttachment> attachment = do_CreateInstance(NS_MSGATTACHMENT_CONTRACTID, &rv);
            NS_ENSURE_SUCCESS(rv, rv);
            attachment->SetName(leafName);

            nsCOMPtr<nsIFile> pTempFile;
            rv = pTempDir->Clone(getter_AddRefs(pTempFile));
            if (NS_FAILED(rv) || !pTempFile)
              return rv;

            pTempFile->Append(leafName);
            pTempFile->Exists(&bExist);
            if (bExist)
            {
              rv = pTempFile->CreateUnique(nsIFile::NORMAL_FILE_TYPE, 0777);
              NS_ENSURE_SUCCESS(rv, rv);
              pTempFile->Remove(false); // remove so we can copy over it.
              pTempFile->GetLeafName(leafName);
            }
            // copy the file to its new location and file name
            pFile->CopyTo(pTempDir, leafName);
            // point pFile to the new location of the attachment
            pFile->InitWithFile(pTempDir);
            pFile->Append(leafName);

            // create MsgCompose attachment object
            attachment->SetTemporary(true); // this one is a temp file so set the flag for MsgCompose

            // now set the attachment object
            nsAutoCString pURL ;
            NS_GetURLSpecFromFile(pFile, pURL);
            attachment->SetUrl(pURL);

            // set the file size
            int64_t fileSize;
            pFile->GetFileSize(&fileSize);
            attachment->SetSize(fileSize);

            // add the attachment
            rv = aCompFields->AddAttachment (attachment);
            if (NS_FAILED(rv))
              PR_LOG(MAPI, PR_LOG_DEBUG, ("nsMapiHook::HandleAttachments: AddAttachment rv =  %lx\n", rv));
        }
    }
    return rv ;
}
/* this should not be exposed in a header, but is here to keep the above
 * types/functions static
 */
NSS_IMPLEMENT PRStatus
nssTrustDomain_InitializeCache (
  NSSTrustDomain *td,
  PRUint32 cacheSize
)
{
    NSSArena *arena;
    nssTDCertificateCache *cache = td->cache;
#ifdef DEBUG_CACHE
    s_log = PR_NewLogModule("nss_cache");
    PR_ASSERT(s_log);
#endif
    PR_ASSERT(!cache);
    arena = nssArena_Create();
    if (!arena) {
	return PR_FAILURE;
    }
    cache = nss_ZNEW(arena, nssTDCertificateCache);
    if (!cache) {
	nssArena_Destroy(arena);
	return PR_FAILURE;
    }
    cache->lock = PZ_NewLock(nssILockCache);
    if (!cache->lock) {
	nssArena_Destroy(arena);
	return PR_FAILURE;
    }
    /* Create the issuer and serial DER --> certificate hash */
    cache->issuerAndSN = nssHash_CreateCertificate(arena, cacheSize);
    if (!cache->issuerAndSN) {
	goto loser;
    }
    /* Create the subject DER --> subject list hash */
    cache->subject = nssHash_CreateItem(arena, cacheSize);
    if (!cache->subject) {
	goto loser;
    }
    /* Create the nickname --> subject list hash */
    cache->nickname = nssHash_CreateString(arena, cacheSize);
    if (!cache->nickname) {
	goto loser;
    }
    /* Create the email --> list of subject lists hash */
    cache->email = nssHash_CreateString(arena, cacheSize);
    if (!cache->email) {
	goto loser;
    }
    cache->arena = arena;
    td->cache = cache;
#ifdef DEBUG_CACHE
    PR_LOG(s_log, PR_LOG_DEBUG, ("Cache initialized."));
#endif
    return PR_SUCCESS;
loser:
    PZ_DestroyLock(cache->lock);
    nssArena_Destroy(arena);
    td->cache = NULL;
#ifdef DEBUG_CACHE
    PR_LOG(s_log, PR_LOG_DEBUG, ("Cache initialization failed."));
#endif
    return PR_FAILURE;
}
Пример #26
0
// this is used to convert non Unicode data and then populate comp fields
nsresult nsMapiHook::PopulateCompFieldsWithConversion(lpnsMapiMessage aMessage,
                                    nsIMsgCompFields * aCompFields)
{
  nsresult rv = NS_OK;

  if (aMessage->lpOriginator)
  {
    nsAutoString From;
    From.Append(NS_ConvertASCIItoUTF16((char *) aMessage->lpOriginator->lpszAddress));
    aCompFields->SetFrom (From);
  }

  nsAutoString To;
  nsAutoString Cc;
  nsAutoString Bcc;
  NS_NAMED_LITERAL_STRING(Comma, ",");
  if (aMessage->lpRecips)
  {
    for (int i=0 ; i < (int) aMessage->nRecipCount ; i++)
    {
      if (aMessage->lpRecips[i].lpszAddress || aMessage->lpRecips[i].lpszName)
      {
        const char *addressWithoutType = (aMessage->lpRecips[i].lpszAddress)
          ? aMessage->lpRecips[i].lpszAddress : aMessage->lpRecips[i].lpszName;
        if (!PL_strncasecmp(addressWithoutType, "SMTP:", 5))
          addressWithoutType += 5;

        switch (aMessage->lpRecips[i].ulRecipClass)
        {
        case MAPI_TO :
          if (!To.IsEmpty())
            To += Comma ;
          To.Append(NS_ConvertASCIItoUTF16(addressWithoutType));
          break ;

        case MAPI_CC :
          if (!Cc.IsEmpty())
            Cc += Comma ;
          Cc.Append(NS_ConvertASCIItoUTF16(addressWithoutType));
          break ;

        case MAPI_BCC :
          if (!Bcc.IsEmpty())
              Bcc += Comma ;
          Bcc.Append(NS_ConvertASCIItoUTF16(addressWithoutType));
          break ;
        }
      }
    }
  }

  // set To, Cc, Bcc
  aCompFields->SetTo (To) ;
  aCompFields->SetCc (Cc) ;
  aCompFields->SetBcc (Bcc) ;

  PR_LOG(MAPI, PR_LOG_DEBUG, ("to: %s cc: %s bcc: %s \n", NS_ConvertUTF16toUTF8(To).get(), NS_ConvertUTF16toUTF8(Cc).get(), NS_ConvertUTF16toUTF8(Bcc).get()));

  nsAutoCString platformCharSet;
  // set subject
  if (aMessage->lpszSubject)
  {
    nsAutoString Subject ;
    if (platformCharSet.IsEmpty())
      platformCharSet.Assign(nsMsgI18NFileSystemCharset());
    rv = ConvertToUnicode(platformCharSet.get(), (char *) aMessage->lpszSubject, Subject);
    if (NS_FAILED(rv)) return rv;
    aCompFields->SetSubject(Subject);
  }

  // handle attachments as File URL
  rv = HandleAttachments (aCompFields, aMessage->nFileCount, aMessage->lpFiles, false) ;
  if (NS_FAILED(rv)) return rv ;

  // set body
  if (aMessage->lpszNoteText)
  {
    nsAutoString Body ;
    if (platformCharSet.IsEmpty())
      platformCharSet.Assign(nsMsgI18NFileSystemCharset());
    rv = ConvertToUnicode(platformCharSet.get(), (char *) aMessage->lpszNoteText, Body);
    if (NS_FAILED(rv)) return rv ;
    if (Body.Last() != '\n')
      Body.AppendLiteral(CRLF);

    if (Body.Find("<html>") == kNotFound)
      aCompFields->SetForcePlainText(true);

    rv = aCompFields->SetBody(Body) ;
  }

#ifdef RAJIV_DEBUG
  // testing what all was set in CompFields
  printf ("To : %S \n", To.get()) ;
  printf ("CC : %S \n", Cc.get() ) ;
  printf ("BCC : %S \n", Bcc.get() ) ;
#endif

  return rv ;
}
Пример #27
0
// nsIStreamListener implementation
NS_IMETHODIMP
nsFTPDirListingConv::OnDataAvailable(nsIRequest* request, nsISupports *ctxt,
                                  nsIInputStream *inStr, PRUint32 sourceOffset, PRUint32 count) {
    NS_ASSERTION(request, "FTP dir listing stream converter needs a request");
    
    nsresult rv;

    nsCOMPtr<nsIChannel> channel = do_QueryInterface(request, &rv);
    NS_ENSURE_SUCCESS(rv, rv);
    
    PRUint32 read, streamLen;

    rv = inStr->Available(&streamLen);
    NS_ENSURE_SUCCESS(rv, rv);

    nsAutoArrayPtr<char> buffer(new char[streamLen + 1]);
    NS_ENSURE_TRUE(buffer, NS_ERROR_OUT_OF_MEMORY);

    rv = inStr->Read(buffer, streamLen, &read);
    NS_ENSURE_SUCCESS(rv, rv);

    // the dir listings are ascii text, null terminate this sucker.
    buffer[streamLen] = '\0';

    PR_LOG(gFTPDirListConvLog, PR_LOG_DEBUG, ("nsFTPDirListingConv::OnData(request = %x, ctxt = %x, inStr = %x, sourceOffset = %d, count = %d)\n", request, ctxt, inStr, sourceOffset, count));

    if (!mBuffer.IsEmpty()) {
        // we have data left over from a previous OnDataAvailable() call.
        // combine the buffers so we don't lose any data.
        mBuffer.Append(buffer);

        buffer = new char[mBuffer.Length()+1];
        NS_ENSURE_TRUE(buffer, NS_ERROR_OUT_OF_MEMORY);

        strncpy(buffer, mBuffer.get(), mBuffer.Length()+1);
        mBuffer.Truncate();
    }

#ifndef DEBUG_dougt
    PR_LOG(gFTPDirListConvLog, PR_LOG_DEBUG, ("::OnData() received the following %d bytes...\n\n%s\n\n", streamLen, buffer.get()) );
#else
    printf("::OnData() received the following %d bytes...\n\n%s\n\n", streamLen, buffer);
#endif // DEBUG_dougt

    nsCAutoString indexFormat;
    if (!mSentHeading) {
        // build up the 300: line
        nsCOMPtr<nsIURI> uri;
        rv = channel->GetURI(getter_AddRefs(uri));
        NS_ENSURE_SUCCESS(rv, rv);

        rv = GetHeaders(indexFormat, uri);
        NS_ENSURE_SUCCESS(rv, rv);

        mSentHeading = PR_TRUE;
    }

    char *line = buffer;
    line = DigestBufferLines(line, indexFormat);

#ifndef DEBUG_dougt
    PR_LOG(gFTPDirListConvLog, PR_LOG_DEBUG, ("::OnData() sending the following %d bytes...\n\n%s\n\n", 
        indexFormat.Length(), indexFormat.get()) );
#else
    char *unescData = ToNewCString(indexFormat);
    NS_ENSURE_TRUE(unescData, NS_ERROR_OUT_OF_MEMORY);
    
    nsUnescape(unescData);
    printf("::OnData() sending the following %d bytes...\n\n%s\n\n", indexFormat.Length(), unescData);
    nsMemory::Free(unescData);
#endif // DEBUG_dougt

    // if there's any data left over, buffer it.
    if (line && *line) {
        mBuffer.Append(line);
        PR_LOG(gFTPDirListConvLog, PR_LOG_DEBUG, ("::OnData() buffering the following %d bytes...\n\n%s\n\n",
            PL_strlen(line), line) );
    }

    // send the converted data out.
    nsCOMPtr<nsIInputStream> inputData;

    rv = NS_NewCStringInputStream(getter_AddRefs(inputData), indexFormat);
    NS_ENSURE_SUCCESS(rv, rv);

    rv = mFinalListener->OnDataAvailable(request, ctxt, inputData, 0, indexFormat.Length());

    return rv;
}
Пример #28
0
// This is the function that looks for the first folder to purge. It also
// applies retention settings to any folder that hasn't had retention settings
// applied in mMinDelayBetweenPurges minutes (default, 8 hours).
// However, if we've spent more than .5 seconds in this loop, don't
// apply any more retention settings because it might lock up the UI.
// This might starve folders later on in the hierarchy, since we always
// start at the top, but since we also apply retention settings when you
// open a folder, or when you compact all folders, I think this will do
// for now, until we have a cleanup on shutdown architecture.
nsresult nsMsgPurgeService::PerformPurge()
{
    PR_LOG(MsgPurgeLogModule, PR_LOG_ALWAYS, ("performing purge"));

    nsresult rv;

    nsCOMPtr <nsIMsgAccountManager> accountManager = do_GetService(NS_MSGACCOUNTMANAGER_CONTRACTID, &rv);
    NS_ENSURE_SUCCESS(rv,rv);
    bool keepApplyingRetentionSettings = true;

    nsCOMPtr<nsISupportsArray> allServers;
    rv = accountManager->GetAllServers(getter_AddRefs(allServers));
    if (NS_SUCCEEDED(rv) && allServers)
    {
        PRUint32 numServers;
        rv = allServers->Count(&numServers);
        PR_LOG(MsgPurgeLogModule, PR_LOG_ALWAYS, ("%d servers", numServers));
        nsCOMPtr<nsIMsgFolder> folderToPurge;
        PRIntervalTime startTime = PR_IntervalNow();
        PRInt32 purgeIntervalToUse;
        PRTime oldestPurgeTime = 0; // we're going to pick the least-recently purged folder

        // apply retention settings to folders that haven't had retention settings
        // applied in mMinDelayBetweenPurges minutes (default 8 hours)
        // Because we get last purge time from the folder cache,
        // this code won't open db's for folders until it decides it needs
        // to apply retention settings, and since nsIMsgFolder::ApplyRetentionSettings
        // will close any db's it opens, this code won't leave db's open.
        for (PRUint32 serverIndex=0; serverIndex < numServers; serverIndex++)
        {
            nsCOMPtr <nsIMsgIncomingServer> server =
                do_QueryElementAt(allServers, serverIndex, &rv);
            if (NS_SUCCEEDED(rv) && server)
            {
                if (keepApplyingRetentionSettings)
                {
                    nsCOMPtr <nsIMsgFolder> rootFolder;
                    rv = server->GetRootFolder(getter_AddRefs(rootFolder));
                    NS_ENSURE_SUCCESS(rv, rv);

                    nsCOMPtr <nsISupportsArray> childFolders = do_CreateInstance(NS_SUPPORTSARRAY_CONTRACTID, &rv);
                    NS_ENSURE_SUCCESS(rv, rv);
                    rv = rootFolder->ListDescendents(childFolders);

                    PRUint32 cnt = 0;
                    childFolders->Count(&cnt);

                    nsCOMPtr<nsISupports> supports;
                    nsCOMPtr<nsIUrlListener> urlListener;
                    nsCOMPtr<nsIMsgFolder> childFolder;

                    for (PRUint32 index = 0; index < cnt; index++)
                    {
                        childFolder = do_QueryElementAt(childFolders, index);
                        if (childFolder)
                        {
                            PRUint32 folderFlags;
                            (void) childFolder->GetFlags(&folderFlags);
                            if (folderFlags & nsMsgFolderFlags::Virtual)
                                continue;
                            PRTime curFolderLastPurgeTime = 0;
                            nsCString curFolderLastPurgeTimeString, curFolderUri;
                            rv = childFolder->GetStringProperty("LastPurgeTime", curFolderLastPurgeTimeString);
                            if (NS_FAILED(rv))
                                continue; // it is ok to fail, go on to next folder

                            if (!curFolderLastPurgeTimeString.IsEmpty())
                            {
                                PRInt64 theTime;
                                PR_ParseTimeString(curFolderLastPurgeTimeString.get(), PR_FALSE, &theTime);
                                curFolderLastPurgeTime = theTime;
                            }

                            childFolder->GetURI(curFolderUri);
                            PR_LOG(MsgPurgeLogModule, PR_LOG_ALWAYS, ("%s curFolderLastPurgeTime=%s (if blank, then never)", curFolderUri.get(), curFolderLastPurgeTimeString.get()));

                            // check if this folder is due to purge
                            // has to have been purged at least mMinDelayBetweenPurges minutes ago
                            // we don't want to purge the folders all the time - once a day is good enough
                            PRInt64 minDelayBetweenPurges(mMinDelayBetweenPurges);
                            PRInt64 microSecondsPerMinute(60000000);
                            PRTime nextPurgeTime = curFolderLastPurgeTime + (minDelayBetweenPurges * microSecondsPerMinute);
                            if (nextPurgeTime < PR_Now())
                            {
                                PR_LOG(MsgPurgeLogModule, PR_LOG_ALWAYS, ("purging %s", curFolderUri.get()));
                                childFolder->ApplyRetentionSettings();
                            }
                            PRIntervalTime elapsedTime;
                            LL_SUB(elapsedTime, PR_IntervalNow(), startTime);
                            // check if more than 500 milliseconds have elapsed in this purge process
                            if (PR_IntervalToMilliseconds(elapsedTime) > 500)
                            {
                                keepApplyingRetentionSettings = PR_FALSE;
                                break;
                            }
                        }
                    }
                }
                nsCString type;
                nsresult rv = server->GetType(type);
                NS_ENSURE_SUCCESS(rv, rv);

                nsCAutoString contractid(NS_MSGPROTOCOLINFO_CONTRACTID_PREFIX);
                contractid.Append(type);

                nsCOMPtr<nsIMsgProtocolInfo> protocolInfo =
                    do_GetService(contractid.get(), &rv);
                NS_ENSURE_SUCCESS(rv, PR_FALSE);

                nsCString realHostName;
                server->GetRealHostName(realHostName);
                PR_LOG(MsgPurgeLogModule, PR_LOG_ALWAYS, ("[%d] %s (%s)", serverIndex, realHostName.get(), type.get()));

                nsCOMPtr <nsISpamSettings> spamSettings;
                rv = server->GetSpamSettings(getter_AddRefs(spamSettings));
                NS_ENSURE_SUCCESS(rv, rv);

                PRInt32 spamLevel;
                spamSettings->GetLevel(&spamLevel);
                PR_LOG(MsgPurgeLogModule, PR_LOG_ALWAYS, ("[%d] spamLevel=%d (if 0, don't purge)", serverIndex, spamLevel));
                if (!spamLevel)
                    continue;

                // check if we are set up to purge for this server
                // if not, skip it.
                bool purgeSpam;
                spamSettings->GetPurge(&purgeSpam);

                PR_LOG(MsgPurgeLogModule, PR_LOG_ALWAYS, ("[%d] purgeSpam=%s (if false, don't purge)", serverIndex, purgeSpam ? "true" : "false"));
                if (!purgeSpam)
                    continue;

                // check if the spam folder uri is set for this server
                // if not skip it.
                nsCString junkFolderURI;
                rv = spamSettings->GetSpamFolderURI(getter_Copies(junkFolderURI));
                NS_ENSURE_SUCCESS(rv,rv);

                PR_LOG(MsgPurgeLogModule, PR_LOG_ALWAYS, ("[%d] junkFolderURI=%s (if empty, don't purge)", serverIndex, junkFolderURI.get()));
                if (junkFolderURI.IsEmpty())
                    continue;

                // if the junk folder doesn't exist
                // because the folder pane isn't built yet, for example
                // skip this account
                nsCOMPtr<nsIMsgFolder> junkFolder;
                GetExistingFolder(junkFolderURI, getter_AddRefs(junkFolder));

                PR_LOG(MsgPurgeLogModule, PR_LOG_ALWAYS, ("[%d] %s exists? %s (if doesn't exist, don't purge)", serverIndex, junkFolderURI.get(), junkFolder ? "true" : "false"));
                if (!junkFolder)
                    continue;

                PRTime curJunkFolderLastPurgeTime = 0;
                nsCString curJunkFolderLastPurgeTimeString;
                rv = junkFolder->GetStringProperty("curJunkFolderLastPurgeTime", curJunkFolderLastPurgeTimeString);
                if (NS_FAILED(rv))
                    continue; // it is ok to fail, junk folder may not exist

                if (!curJunkFolderLastPurgeTimeString.IsEmpty())
                {
                    PRInt64 theTime;
                    PR_ParseTimeString(curJunkFolderLastPurgeTimeString.get(), PR_FALSE, &theTime);
                    curJunkFolderLastPurgeTime = theTime;
                }

                PR_LOG(MsgPurgeLogModule, PR_LOG_ALWAYS, ("[%d] %s curJunkFolderLastPurgeTime=%s (if blank, then never)", serverIndex, junkFolderURI.get(), curJunkFolderLastPurgeTimeString.get()));

                // check if this account is due to purge
                // has to have been purged at least mMinDelayBetweenPurges minutes ago
                // we don't want to purge the folders all the time
                PRTime nextPurgeTime = curJunkFolderLastPurgeTime + mMinDelayBetweenPurges * 60000000 /* convert mMinDelayBetweenPurges to into microseconds */;
                if (nextPurgeTime < PR_Now())
                {
                    PR_LOG(MsgPurgeLogModule, PR_LOG_ALWAYS, ("[%d] last purge greater than min delay", serverIndex));

                    nsCOMPtr <nsIMsgIncomingServer> junkFolderServer;
                    rv = junkFolder->GetServer(getter_AddRefs(junkFolderServer));
                    NS_ENSURE_SUCCESS(rv,rv);

                    bool serverBusy = false;
                    bool serverRequiresPassword = true;
                    bool passwordPromptRequired;
                    bool canSearchMessages = false;
                    junkFolderServer->GetPasswordPromptRequired(&passwordPromptRequired);
                    junkFolderServer->GetServerBusy(&serverBusy);
                    junkFolderServer->GetServerRequiresPasswordForBiff(&serverRequiresPassword);
                    junkFolderServer->GetCanSearchMessages(&canSearchMessages);
                    // Make sure we're logged on before doing the search (assuming we need to be)
                    // and make sure the server isn't already in the middle of downloading new messages
                    // and make sure a search isn't already going on
                    PR_LOG(MsgPurgeLogModule, PR_LOG_ALWAYS, ("[%d] (search in progress? %s)", serverIndex, mSearchSession ? "true" : "false"));
                    PR_LOG(MsgPurgeLogModule, PR_LOG_ALWAYS, ("[%d] (server busy? %s)", serverIndex, serverBusy ? "true" : "false"));
                    PR_LOG(MsgPurgeLogModule, PR_LOG_ALWAYS, ("[%d] (serverRequiresPassword? %s)", serverIndex, serverRequiresPassword ? "true" : "false"));
                    PR_LOG(MsgPurgeLogModule, PR_LOG_ALWAYS, ("[%d] (passwordPromptRequired? %s)", serverIndex, passwordPromptRequired ? "true" : "false"));
                    if (canSearchMessages && !mSearchSession && !serverBusy && (!serverRequiresPassword || !passwordPromptRequired))
                    {
                        PRInt32 purgeInterval;
                        spamSettings->GetPurgeInterval(&purgeInterval);

                        if ((oldestPurgeTime == 0) || (curJunkFolderLastPurgeTime < oldestPurgeTime))
                        {
                            PR_LOG(MsgPurgeLogModule, PR_LOG_ALWAYS, ("[%d] purging! searching for messages older than %d days", serverIndex, purgeInterval));
                            oldestPurgeTime = curJunkFolderLastPurgeTime;
                            purgeIntervalToUse = purgeInterval;
                            folderToPurge = junkFolder;
                            // if we've never purged this folder, do it...
                            if (curJunkFolderLastPurgeTime == 0)
                                break;
                        }
                    }
                    else {
                        NS_ASSERTION(canSearchMessages, "unexpected, you should be able to search");
                        PR_LOG(MsgPurgeLogModule, PR_LOG_ALWAYS, ("[%d] not a good time for this server, try again later", serverIndex));
                    }
                }
                else {
                    PR_LOG(MsgPurgeLogModule, PR_LOG_ALWAYS, ("[%d] last purge too recent", serverIndex));
                }
            }
        }
        if (folderToPurge)
            rv = SearchFolderToPurge(folderToPurge, purgeIntervalToUse);
    }

    // set up timer to check accounts again
    SetupNextPurge();
    return rv;
}
Пример #29
0
// wrapper for get_values_len
//
NS_IMETHODIMP 
nsLDAPMessage::GetBinaryValues(const char *aAttr, uint32_t *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) {
        int32_t 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
    //
    uint32_t 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
    //
    uint32_t 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<uint8_t *>(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;
}
Пример #30
0
Window
XRemoteClient::FindBestWindow(const char *aProgram, const char *aUsername,
                              const char *aProfile,
                              bool aSupportsCommandLine)
{
  Window root = RootWindowOfScreen(DefaultScreenOfDisplay(mDisplay));
  Window bestWindow = 0;
  Window root2, parent, *kids;
  unsigned int nkids;

  // Get a list of the children of the root window, walk the list
  // looking for the best window that fits the criteria.
  if (!XQueryTree(mDisplay, root, &root2, &parent, &kids, &nkids)) {
    PR_LOG(sRemoteLm, PR_LOG_DEBUG,
           ("XQueryTree failed in XRemoteClient::FindBestWindow"));
    return 0;
  }

  if (!(kids && nkids)) {
    PR_LOG(sRemoteLm, PR_LOG_DEBUG, ("root window has no children"));
    return 0;
  }

  // We'll walk the list of windows looking for a window that best
  // fits the criteria here.

  for (unsigned int i = 0; i < nkids; i++) {
    Atom type;
    int format;
    unsigned long nitems, bytesafter;
    unsigned char *data_return = 0;
    Window w;
    w = kids[i];
    // find the inner window with WM_STATE on it
    w = CheckWindow(w);

    int status = XGetWindowProperty(mDisplay, w, mMozVersionAtom,
                                    0, (65536 / sizeof (long)),
                                    False, XA_STRING,
                                    &type, &format, &nitems, &bytesafter,
                                    &data_return);

    if (!data_return)
      continue;

    double version = PR_strtod((char*) data_return, nullptr);
    XFree(data_return);

    if (aSupportsCommandLine && !(version >= 5.1 && version < 6))
      continue;

    data_return = 0;

    if (status != Success || type == None)
      continue;

    // If someone passed in a program name, check it against this one
    // unless it's "any" in which case, we don't care.  If someone did
    // pass in a program name and this window doesn't support that
    // protocol, we don't include it in our list.
    if (aProgram && strcmp(aProgram, "any")) {
        status = XGetWindowProperty(mDisplay, w, mMozProgramAtom,
                                    0, (65536 / sizeof(long)),
                                    False, XA_STRING,
                                    &type, &format, &nitems, &bytesafter,
                                    &data_return);
        
        // If the return name is not the same as what someone passed in,
        // we don't want this window.
        if (data_return) {
            if (strcmp(aProgram, (const char *)data_return)) {
                XFree(data_return);
                continue;
            }

            // This is actually the success condition.
            XFree(data_return);
        }
        else {
            // Doesn't support the protocol, even though the user
            // requested it.  So we're not going to use this window.
            continue;
        }
    }

    // Check to see if it has the user atom on that window.  If there
    // is then we need to make sure that it matches what we have.
    const char *username;
    if (aUsername) {
      username = aUsername;
    }
    else {
      username = PR_GetEnv("LOGNAME");
    }

    if (username) {
        status = XGetWindowProperty(mDisplay, w, mMozUserAtom,
                                    0, (65536 / sizeof(long)),
                                    False, XA_STRING,
                                    &type, &format, &nitems, &bytesafter,
                                    &data_return);

        // if there's a username compare it with what we have
        if (data_return) {
            // If the IDs aren't equal, we don't want this window.
            if (strcmp(username, (const char *)data_return)) {
                XFree(data_return);
                continue;
            }

            XFree(data_return);
        }
    }

    // Check to see if there's a profile name on this window.  If
    // there is, then we need to make sure it matches what someone
    // passed in.
    if (aProfile) {
        status = XGetWindowProperty(mDisplay, w, mMozProfileAtom,
                                    0, (65536 / sizeof(long)),
                                    False, XA_STRING,
                                    &type, &format, &nitems, &bytesafter,
                                    &data_return);

        // If there's a profile compare it with what we have
        if (data_return) {
            // If the profiles aren't equal, we don't want this window.
            if (strcmp(aProfile, (const char *)data_return)) {
                XFree(data_return);
                continue;
            }

            XFree(data_return);
        }
    }

    // Check to see if the window supports the new command-line passing
    // protocol, if that is requested.

    // If we got this far, this is the best window.  It passed
    // all the tests.
    bestWindow = w;
    break;
  }

  if (kids)
    XFree((char *) kids);

  return bestWindow;
}