nsresult nsComm4xMail::FoundMailbox(nsIFile *mailFile, nsAutoString *pName, nsISupportsArray *pArray, nsIImportService *pImport)
{
    nsCOMPtr<nsIImportMailboxDescriptor>    desc;

    nsCString pPath;
    mailFile->GetNativePath(pPath);
    if (!pPath.IsEmpty())
      IMPORT_LOG2("Found comm4x mailbox: %s, m_depth = %d\n", pPath.get(), m_depth);
    else
      IMPORT_LOG2("Can't get native path but found comm4x mailbox: %s, m_depth = %d\n", NS_ConvertUTF16toUTF8(*pName).get(), m_depth);

    nsresult rv = pImport->CreateNewMailboxDescriptor(getter_AddRefs(desc));
    if (NS_SUCCEEDED(rv)) {
        PRInt64        sz = 0;
        mailFile->GetFileSize(&sz);
        desc->SetDisplayName(pName->get());
        desc->SetDepth(m_depth);
        desc->SetSize((PRUint32) sz);
        nsCOMPtr <nsILocalFile> pFile;
        desc->GetFile(getter_AddRefs(pFile));
        if (pFile) {
          nsCOMPtr <nsILocalFile> localMailFile = do_QueryInterface(mailFile);
          pFile->InitWithFile(localMailFile);
        }
        nsCOMPtr <nsISupports> pInterface = do_QueryInterface(desc);
        if (pInterface)
            pArray->AppendElement(pInterface);
    }
    return NS_OK;
}
Exemple #2
0
bool OutlookSettings::DoIMAPServer(nsIMsgAccountManager *aMgr,
                                   nsIWindowsRegKey *aKey,
                                   const nsString &aServerName,
                                   nsIMsgAccount **aAccount)
{
  nsAutoString userName;
  nsresult rv;
  rv = aKey->ReadStringValue(NS_LITERAL_STRING("IMAP User Name"), userName);
  if (NS_FAILED(rv))
    return false;

  bool result = false;

  // I now have a user name/server name pair, find out if it already exists?
  nsCAutoString nativeUserName;
  NS_CopyUnicodeToNative(userName, nativeUserName);
  nsCAutoString nativeServerName;
  NS_CopyUnicodeToNative(aServerName, nativeServerName);
  nsCOMPtr<nsIMsgIncomingServer> in;
  rv = aMgr->FindServer(nativeUserName,
                        nativeServerName,
                        NS_LITERAL_CSTRING("imap"),
                        getter_AddRefs(in));
  if (NS_FAILED(rv) || (in == nsnull)) {
    // Create the incoming server and an account for it?
    rv = aMgr->CreateIncomingServer(nativeUserName,
                                    nativeServerName,
                                    NS_LITERAL_CSTRING("imap"),
                                    getter_AddRefs(in));
    if (NS_SUCCEEDED(rv) && in) {
      rv = in->SetType(NS_LITERAL_CSTRING("imap"));
      // TODO SSL, auth method

      IMPORT_LOG2("Created IMAP server named: %s, userName: %s\n",
                  nativeServerName.get(), nativeUserName.get());

      nsAutoString prettyName;
      if (NS_SUCCEEDED(GetAccountName(aKey, aServerName, prettyName)))
        rv = in->SetPrettyName(prettyName);
      // We have a server, create an account.
      nsCOMPtr<nsIMsgAccount>  account;
      rv = aMgr->CreateAccount(getter_AddRefs(account));
      if (NS_SUCCEEDED(rv) && account) {
        rv = account->SetIncomingServer(in);

        IMPORT_LOG0("Created an account and set the IMAP server as the incoming server\n");

        // Fiddle with the identities
        SetIdentities(aMgr, account, aKey);
        result = true;
        if (aAccount)
          account.forget(aAccount);
      }
    }
  }
  else
    result = true;

  return result;
}
Exemple #3
0
PRBool CIndexScanner::GetMailItem( PRUint32 *pFlags, PRUint32 *pOffset, PRUint32 *pSize)
{
    PRUint32	values[kNumIdxLongsToRead];
    PRInt32		cnt = kNumIdxLongsToRead * sizeof( PRUint32);
    PRInt8 *	pReadTo = (PRInt8 *) values;
    PRInt32		cntRead;
    nsresult	rv;

    rv = m_idxFile->Seek( m_idxOffset);
    if (NS_FAILED( rv))
        return( PR_FALSE);

    rv = m_idxFile->Read( (char **) &pReadTo, cnt, &cntRead);
    if (NS_FAILED( rv) || (cntRead != cnt))
        return( PR_FALSE);

    if (values[3] != m_idxOffset) {
        IMPORT_LOG2( "Self pointer invalid: m_idxOffset=0x%lx, self=0x%lx\n", m_idxOffset, values[3]);
        return( PR_FALSE);
    }

    // So... what do we have here???
#ifdef DEBUG_SUBJECT_AND_FLAGS
    IMPORT_LOG2( "Number: %ld, msg offset: 0x%lx, ", values[2], values[5]);
    IMPORT_LOG2( "msg length: %ld, Flags: 0x%lx\n", values[6], values[0]);
    m_idxFile->seek( m_idxOffset + 212);
    PRUint32	subSz = 0;
    cnt = 4;
    pReadTo = (PRInt8 *) &subSz;
    m_idxFile->Read( (char **) &pReadTo, cnt, &cntRead);
    if ((subSz >= 0) && (subSz < 1024)) {
        char *pSub = new char[subSz + 1];
        m_idxFile->Read( &pSub, subSz, &cntRead);
        pSub[subSz] = 0;
        IMPORT_LOG1( "    Subject: %s\n", pSub);
        delete [] pSub;
    }
#endif

    m_idxOffset += values[4];
    m_didBytes += values[4];

    *pFlags = values[0];
    *pOffset = values[5];
    *pSize = values[6];
    return( PR_TRUE);
}
PRBool nsEudoraWin32::BuildIMAPAccount( nsIMsgAccountManager *accMgr, const char *pSection, const char *pIni, nsIMsgAccount **ppAccount)
{
  char valBuff[kIniValueSize];
  nsCString serverName;
  nsCString userName;

  GetServerAndUserName( pSection, pIni, serverName, userName, valBuff);

  if (serverName.IsEmpty() || userName.IsEmpty())
    return( PR_FALSE);

  PRBool result = PR_FALSE;

  nsCOMPtr<nsIMsgIncomingServer> in;
  nsresult rv = accMgr->FindServer( userName, serverName, NS_LITERAL_CSTRING("imap"), getter_AddRefs(in));
  if (NS_FAILED( rv) || (in == nsnull))
  {
    // Create the incoming server and an account for it?
    rv = accMgr->CreateIncomingServer( userName, serverName, NS_LITERAL_CSTRING("imap"), getter_AddRefs(in));
    if (NS_SUCCEEDED( rv) && in)
    {
      rv = in->SetType(NS_LITERAL_CSTRING("imap"));
      // rv = in->SetHostName( serverName);
      // rv = in->SetUsername( userName);

      IMPORT_LOG2( "Created IMAP server named: %s, userName: %s\n", serverName.get(), userName.get());

      nsString prettyName;
      GetAccountName( pSection, prettyName);
      IMPORT_LOG1( "\tSet pretty name to: %S\n", prettyName.get());
      rv = in->SetPrettyName(prettyName);

      // We have a server, create an account.
      nsCOMPtr<nsIMsgAccount> account;
      rv = accMgr->CreateAccount( getter_AddRefs( account));
      if (NS_SUCCEEDED( rv) && account)
      {
        rv = account->SetIncomingServer(in);

        IMPORT_LOG0( "Created an account and set the IMAP server as the incoming server\n");

        // Fiddle with the identities
        SetIdentities(accMgr, account, pSection, pIni, userName.get(), serverName.get(), valBuff);
        result = PR_TRUE;
        if (ppAccount)
          account->QueryInterface( NS_GET_IID(nsIMsgAccount), (void **)ppAccount);
      }
    }
  }
  else
    result = PR_TRUE;

  return( result);
}
Exemple #5
0
bool OutlookSettings::DoIMAPServer(nsIMsgAccountManager *pMgr, HKEY hKey, char *pServerName, nsIMsgAccount **ppAccount)
{
  if (ppAccount)
    *ppAccount = nsnull;

  BYTE *pBytes;
  pBytes = nsOutlookRegUtil::GetValueBytes(hKey, "IMAP User Name");
  if (!pBytes)
    return false;

  bool    result = false;

  // I now have a user name/server name pair, find out if it already exists?
  nsCOMPtr<nsIMsgIncomingServer> in;
  nsresult rv = pMgr->FindServer(nsDependentCString((const char *)pBytes), nsDependentCString(pServerName), NS_LITERAL_CSTRING("imap"), getter_AddRefs(in));
  if (NS_FAILED(rv) || (in == nsnull)) {
    // Create the incoming server and an account for it?
    rv = pMgr->CreateIncomingServer(nsDependentCString((const char *)pBytes), nsDependentCString(pServerName), NS_LITERAL_CSTRING("imap"), getter_AddRefs(in));
    if (NS_SUCCEEDED(rv) && in) {
      rv = in->SetType(NS_LITERAL_CSTRING("imap"));
      // TODO SSL, auth method

      IMPORT_LOG2("Created IMAP server named: %s, userName: %s\n", pServerName, (char *)pBytes);

      nsString prettyName;
      if (NS_SUCCEEDED(GetAccountName(hKey, pServerName, prettyName)))
        rv = in->SetPrettyName(prettyName);
      // We have a server, create an account.
      nsCOMPtr<nsIMsgAccount>  account;
      rv = pMgr->CreateAccount(getter_AddRefs(account));
      if (NS_SUCCEEDED(rv) && account) {
        rv = account->SetIncomingServer(in);

        IMPORT_LOG0("Created an account and set the IMAP server as the incoming server\n");

        // Fiddle with the identities
        SetIdentities(pMgr, account, hKey);
        result = true;
        if (ppAccount)
          account->QueryInterface(NS_GET_IID(nsIMsgAccount), (void **)ppAccount);
      }
    }
  }
  else
    result = true;

  nsOutlookRegUtil::FreeValueBytes(pBytes);

  return result;
}
nsresult nsTextAddress::DetermineDelim(nsIFile *aSrc) {
  nsCOMPtr<nsIInputStream> inputStream;
  nsresult rv = NS_NewLocalFileInputStream(getter_AddRefs(inputStream), aSrc);
  if (NS_FAILED(rv)) {
    IMPORT_LOG0("*** Error opening address file for reading\n");
    return rv;
  }

  int32_t lineCount = 0;
  int32_t tabCount = 0;
  int32_t commaCount = 0;
  int32_t tabLines = 0;
  int32_t commaLines = 0;
  nsAutoString line;
  bool more = true;

  nsCOMPtr<nsIUnicharLineInputStream> lineStream;
  rv = GetUnicharLineStreamForFile(aSrc, inputStream,
                                   getter_AddRefs(lineStream));
  if (NS_FAILED(rv)) {
    IMPORT_LOG0("*** Error opening converter stream for importer\n");
    return rv;
  }

  while (more && NS_SUCCEEDED(rv) && (lineCount < 100)) {
    rv = lineStream->ReadLine(line, &more);
    if (NS_SUCCEEDED(rv)) {
      tabCount = CountFields(line, char16_t('\t'));
      commaCount = CountFields(line, char16_t(','));
      if (tabCount > commaCount)
        tabLines++;
      else if (commaCount)
        commaLines++;
    }
    lineCount++;
  }

  rv = inputStream->Close();

  if (tabLines > commaLines)
    m_delim = char16_t('\t');
  else
    m_delim = char16_t(',');

  IMPORT_LOG2("Tab count = %d, Comma count = %d\n", tabLines, commaLines);

  return rv;
}
nsresult nsEudoraWin32::FoundMailbox( nsIFile *mailFile, const char *pName, nsISupportsArray *pArray, nsIImportService *pImport)
{
  nsString displayName;
  nsCOMPtr<nsIImportMailboxDescriptor> desc;
  nsISupports * pInterface;

  NS_CopyNativeToUnicode(nsDependentCString(pName), displayName);

#ifdef IMPORT_DEBUG
  nsCAutoString path;
  mailFile->GetNativePath(path);
  if (!path.IsEmpty())
    IMPORT_LOG2( "Found eudora mailbox, %s: %s\n", path.get(), pName);
  else
    IMPORT_LOG1( "Found eudora mailbox, %s\n", pName);
  IMPORT_LOG1( "\tm_depth = %d\n", (int)m_depth);
#endif

  nsresult rv = pImport->CreateNewMailboxDescriptor( getter_AddRefs( desc));
  if (NS_SUCCEEDED( rv))
  {
    PRInt64 sz = 0;
    mailFile->GetFileSize( &sz);
    desc->SetDisplayName( displayName.get());
    desc->SetDepth( m_depth);
    desc->SetSize( sz);
    nsCOMPtr <nsILocalFile> pFile = nsnull;
    desc->GetFile(getter_AddRefs(pFile));
    if (pFile)
    {
      nsCOMPtr <nsILocalFile> localMailFile = do_QueryInterface(mailFile);
      pFile->InitWithFile( localMailFile);
    }
    rv = desc->QueryInterface( kISupportsIID, (void **) &pInterface);
    pArray->AppendElement( pInterface);
    pInterface->Release();
  }

  return( NS_OK);
}
Exemple #8
0
PRBool CMbxScanner::WriteMailItem( PRUint32 flags, PRUint32 offset, PRUint32 size, PRUint32 *pTotalMsgSize)
{
    PRUint32	values[kNumMbxLongsToRead];
    PRInt32		cnt = kNumMbxLongsToRead * sizeof( PRUint32);
    nsresult	rv;
    PRBool		failed = PR_FALSE;
    PRInt32		cntRead;
    PRInt8 *	pChar = (PRInt8 *) values;

    rv = m_mbxFile->Seek( offset);
    m_mbxFile->Failed( &failed);

    if (NS_FAILED( rv) || failed) {
        IMPORT_LOG1( "Mbx seek error: 0x%lx\n", offset);
        return( PR_FALSE);
    }
    rv = m_mbxFile->Read( (char **) &pChar, cnt, &cntRead);
    if (NS_FAILED( rv) || (cntRead != cnt)) {
        IMPORT_LOG1( "Mbx read error at: 0x%lx\n", offset);
        return( PR_FALSE);
    }
    if (values[0] != 0x7F007F00) {
        IMPORT_LOG2( "Mbx tag field doesn't match: 0x%lx, at offset: 0x%lx\n", values[0], offset);
        return( PR_FALSE);
    }
    if (size && (values[2] != size)) {
        IMPORT_LOG3( "Mbx size doesn't match idx, mbx: %ld, idx: %ld, at offset: 0x%lx\n", values[2], size, offset);
        return( PR_FALSE);
    }

    if (pTotalMsgSize != nsnull)
        *pTotalMsgSize = values[2];

    // everything looks kosher...
    // the actual message text follows and is values[3] bytes long...
    return( CopyMbxFileBytes(flags,  values[3]));
}
nsresult nsEudoraWin32::ScanDescmap( nsIFile *pFolder, nsISupportsArray *pArray, nsIImportService *pImport, const char *pData, PRInt32 len)
{
  // use this to find stuff in the directory.

  nsCOMPtr<nsIFile>  entry;
  nsresult        rv;

  if (NS_FAILED( rv = pFolder->Clone(getter_AddRefs(entry))))
    return( rv);
  entry->AppendNative(NS_LITERAL_CSTRING("dummy"));
  // format is Name,FileName,Type,Flag?
  //  Type = M or S for mailbox
  //       = F for folder

  PRInt32      fieldLen;
  PRInt32      pos = 0;
  const char * pStart;
  nsCString    name;
  nsCString    fName;
  nsCString    type;
  nsCString    flag;
  PRBool       isFile;
  PRBool       isFolder;
  while (pos < len)
  {
    pStart = pData;
    fieldLen = 0;
    while ((pos < len) && (*pData != ','))
    {
      pos++;
      pData++;
      fieldLen++;
    }
    name.Truncate();
    if (fieldLen)
      name.Append( pStart, fieldLen);
    name.Trim( kWhitespace);
    pos++;
    pData++;
    pStart = pData;
    fieldLen = 0;
    while ((pos < len) && (*pData != ','))
    {
      pos++;
      pData++;
      fieldLen++;
    }
    fName.Truncate();
    if (fieldLen)
      fName.Append( pStart, fieldLen);
    // Descmap file name is written without any extraneous white space - i.e.
    // if there's whitespace present it's intentional and important. Don't
    // strip whitespace from the fName.
    pos++;
    pData++;
    pStart = pData;
    fieldLen = 0;
    while ((pos < len) && (*pData != ','))
    {
      pos++;
      pData++;
      fieldLen++;
    }
    type.Truncate();
    if (fieldLen)
      type.Append( pStart, fieldLen);
    type.Trim( kWhitespace);
    pos++;
    pData++;
    pStart = pData;
    fieldLen = 0;
    while ((pos < len) && (*pData != 0x0D) && (*pData != 0x0A) && (*pData != ','))
    {
      pos++;
      pData++;
      fieldLen++;
    }
    flag.Truncate();
    if (fieldLen)
      flag.Append( pStart, fieldLen);
    flag.Trim( kWhitespace);
    while ((pos < len) && ((*pData == 0x0D) || (*pData == 0x0A)))
    {
      pos++;
      pData++;
    }

    IMPORT_LOG2( "name: %s, fName: %s\n", name.get(), fName.get());

    if (!fName.IsEmpty() && !name.IsEmpty() && (type.Length() == 1))
    {
      rv = entry->SetNativeLeafName(fName);
      if (NS_SUCCEEDED( rv))
      {
        if (type.CharAt( 0) == 'F')
        {
          isFolder = PR_FALSE;
          entry->IsDirectory( &isFolder);
          if (isFolder)
          {
            rv = FoundMailFolder( entry, name.get(), pArray, pImport);
            if (NS_SUCCEEDED( rv))
            {
              rv = ScanMailDir( entry, pArray, pImport);
              if (NS_FAILED( rv))
                IMPORT_LOG0( "*** Error scanning mail directory\n");
            }
          }
        }
        else if ((type.CharAt( 0) == 'M') || (type.CharAt( 0) == 'S'))
        {
          isFile = PR_FALSE;
          entry->IsFile( &isFile);
          if (isFile)
            FoundMailbox( entry, name.get(), pArray, pImport);
        }
      }
    }
  }

  return( NS_OK);
}
Exemple #10
0
bool OESettings::DoNNTPServer(nsIMsgAccountManager *pMgr, HKEY hKey,
                                char *pServerName, nsIMsgAccount **ppAccount)
{
  if (ppAccount)
    *ppAccount = nsnull;

  char * pUserName;
  // this only exists if NNTP server requires it or not anon login
  pUserName = (char *)nsOERegUtil::GetValueBytes(hKey, "NNTP User Name");

  bool result = false;

  // I now have a user name/server name pair, find out if it already exists?
  // NNTP can have empty user name.  This is wild card in findserver
  nsCOMPtr<nsIMsgIncomingServer> in;
  nsresult rv = pMgr->FindServer(EmptyCString(),
                                 nsDependentCString(pServerName),
                                 NS_LITERAL_CSTRING("nntp"),
                                 getter_AddRefs(in));
  if (NS_FAILED(rv) || (in == nsnull)) {
    // Create the incoming server and an account for it?
    rv = pMgr->CreateIncomingServer(EmptyCString(),
                                    nsDependentCString(pServerName),
                                    NS_LITERAL_CSTRING("nntp"),
                                    getter_AddRefs(in));
    if (NS_SUCCEEDED(rv) && in) {
      BYTE * pBytesTemp = nsOERegUtil::GetValueBytes(hKey, "NNTP Port");
      if (pBytesTemp && *(PRInt32 *)pBytesTemp != 119)
        in->SetPort(*(PRInt32 *) pBytesTemp);
      nsOERegUtil::FreeValueBytes(pBytesTemp);

      // do nntpincomingserver stuff
      nsCOMPtr<nsINntpIncomingServer> nntpServer = do_QueryInterface(in);
      if (nntpServer && pUserName && *pUserName) {
        nntpServer->SetPushAuth(true);
        in->SetUsername(nsDependentCString(pUserName));
      }

      IMPORT_LOG2("Created NNTP server named: %s, userName: %s\n",
                   pServerName, pUserName? pUserName : "");

      nsString prettyName;
      if (NS_SUCCEEDED(GetAccountName(hKey, pServerName, prettyName)))
        rv = in->SetPrettyName(prettyName);

      // We have a server, create an account.
      nsCOMPtr<nsIMsgAccount> account;
      rv = pMgr->CreateAccount(getter_AddRefs(account));
      if (NS_SUCCEEDED(rv) && account) {
        rv = account->SetIncomingServer(in);

        IMPORT_LOG0("Created an account and set the NNTP server as the incoming server\n");

        // Fiddle with the identities
        SetIdentities(pMgr, account, hKey, pUserName, 0, true);
        result = true;
        if (ppAccount)
          account->QueryInterface(NS_GET_IID(nsIMsgAccount), (void **)ppAccount);
      }
    }
  }
  else if (NS_SUCCEEDED(rv) && in) {
    // for the existing server...
    nsCOMPtr<nsIMsgAccount> account;
    rv = pMgr->FindAccountForServer(in, getter_AddRefs(account));
    if (NS_SUCCEEDED(rv) && account) {
      IMPORT_LOG0("Using existing account and set the NNTP server as the incoming server\n");
      // Fiddle with the identities
      SetIdentities(pMgr, account, hKey, pUserName, 0, true);
      result = true;
      if (ppAccount)
        account->QueryInterface(NS_GET_IID(nsIMsgAccount),
                                 (void **)ppAccount);
    }
  }
  else
    result = true;
  nsOERegUtil::FreeValueBytes((BYTE *) pUserName);
  return result;
}
Exemple #11
0
bool OESettings::DoPOP3Server(nsIMsgAccountManager *pMgr, HKEY hKey, char *pServerName, nsIMsgAccount **ppAccount)
{
  PRInt32 authMethod;    // Secure Password Authentication
  if (ppAccount)
    *ppAccount = nsnull;

  char * pUserName;
  pUserName = (char *)nsOERegUtil::GetValueBytes(hKey, "POP3 User Name");
  if (!pUserName)
    return false;

  bool result = false;

  // I now have a user name/server name pair, find out if it already exists?
  nsCOMPtr<nsIMsgIncomingServer> in;
  nsresult rv = pMgr->FindServer(nsDependentCString(pUserName),
                                 nsDependentCString(pServerName),
                                 NS_LITERAL_CSTRING("pop3"),
                                 getter_AddRefs(in));
  if (NS_FAILED(rv) || (in == nsnull)) {
    // Create the incoming server and an account for it?
    rv = pMgr->CreateIncomingServer(nsDependentCString(pUserName),
                                    nsDependentCString(pServerName),
                                    NS_LITERAL_CSTRING("pop3"),
                                    getter_AddRefs(in));
    if (NS_SUCCEEDED(rv) && in) {
      BYTE * pSecureConnection = nsOERegUtil::GetValueBytes(hKey, "POP3 Secure Connection");
      if (pSecureConnection)
      {
        if (*pSecureConnection)
          in->SetSocketType(nsMsgSocketType::SSL);
        nsOERegUtil::FreeValueBytes(pSecureConnection);
      }

      BYTE * pPort = nsOERegUtil::GetValueBytes(hKey, "POP3 Port");
      if (pPort)
      {
        in->SetPort(*(PRInt32 *) pPort);
        nsOERegUtil::FreeValueBytes(pPort);
      }

      BYTE * pBytesTemp = nsOERegUtil::GetValueBytes(hKey, "POP3 Use Sicily");
      if (pBytesTemp)
      {
        bool secAuth = *(bool *)pBytesTemp;
        nsOERegUtil::FreeValueBytes(pBytesTemp);
        authMethod = secAuth ? nsMsgAuthMethod::secure
            : nsMsgAuthMethod::passwordCleartext;
      }
      else {
        authMethod = nsMsgAuthMethod::passwordCleartext;
      }
      in->SetAuthMethod(authMethod);

      in->SetDoBiff(checkNewMail);
      in->SetBiffMinutes(checkNewMailTime);
      nsCOMPtr<nsIPop3IncomingServer> pop3Server = do_QueryInterface(in);
      if (pop3Server) {
        // set local folders as the Inbox to use for this POP3 server
        nsCOMPtr<nsIMsgIncomingServer> localFoldersServer;
        pMgr->GetLocalFoldersServer(getter_AddRefs(localFoldersServer));

        if (!localFoldersServer)
        {
          // If Local Folders does not exist already, create it

          if (NS_FAILED(pMgr->CreateLocalMailAccount())) {
            IMPORT_LOG0("*** Failed to create Local Folders!\n");
            return false;
          }

          pMgr->GetLocalFoldersServer(getter_AddRefs(localFoldersServer));
        }

        // now get the account for this server
        nsCOMPtr<nsIMsgAccount> localFoldersAccount;
        pMgr->FindAccountForServer(localFoldersServer, getter_AddRefs(localFoldersAccount));
        if (localFoldersAccount)
        {
          nsCString localFoldersAcctKey;
          localFoldersAccount->GetKey(localFoldersAcctKey);
          pop3Server->SetDeferredToAccount(localFoldersAcctKey);
        }

        pBytesTemp = nsOERegUtil::GetValueBytes(hKey, "POP3 Skip Account");
        if (pBytesTemp)
        {
        // OE:0=='Include this account when receiving mail or synchronizing'==
        // TB:1==AM:Server:advanced:Include this server when getting new mail
          pop3Server->SetDeferGetNewMail(*pBytesTemp == 0);
          nsOERegUtil::FreeValueBytes(pBytesTemp);
        }
        else
          pop3Server->SetDeferGetNewMail(false);
        pBytesTemp = nsOERegUtil::GetValueBytes(hKey, "Leave Mail On Server");
        if (pBytesTemp)
        {
          pop3Server->SetLeaveMessagesOnServer(*pBytesTemp == 1);
          nsOERegUtil::FreeValueBytes(pBytesTemp);
        }
        pBytesTemp = nsOERegUtil::GetValueBytes(hKey, "Remove When Deleted");
        if (pBytesTemp)
        {
          pop3Server->SetDeleteMailLeftOnServer(*pBytesTemp == 1);
          nsOERegUtil::FreeValueBytes(pBytesTemp);
        }
        pBytesTemp = nsOERegUtil::GetValueBytes(hKey, "Remove When Expired");
        if (pBytesTemp)
        {
          pop3Server->SetDeleteByAgeFromServer(*pBytesTemp == 1);
          nsOERegUtil::FreeValueBytes(pBytesTemp);
        }
        pBytesTemp = nsOERegUtil::GetValueBytes(hKey, "Expire Days");
        if (pBytesTemp)
        {
          pop3Server->SetNumDaysToLeaveOnServer(*(PRInt32*)pBytesTemp);
          nsOERegUtil::FreeValueBytes(pBytesTemp);
        }
      }
      IMPORT_LOG2("Created POP3 server named: %s, userName: %s\n",
                   pServerName, pUserName);
      nsString prettyName;
      if (NS_SUCCEEDED(GetAccountName(hKey, pServerName, prettyName)))
        rv = in->SetPrettyName(prettyName);

      // We have a server, create an account.
      nsCOMPtr<nsIMsgAccount>  account;
      rv = pMgr->CreateAccount(getter_AddRefs(account));
      if (NS_SUCCEEDED(rv) && account) {
        rv = account->SetIncomingServer(in);
        IMPORT_LOG0("Created a new account and set the incoming server to the POP3 server.\n");

        // Fiddle with the identities
        SetIdentities(pMgr, account, hKey, pUserName, authMethod, false);
        result = true;
        if (ppAccount)
          account->QueryInterface(NS_GET_IID(nsIMsgAccount),
                                   (void **)ppAccount);
      }
    }
  } 
  else if (NS_SUCCEEDED(rv) && in) {
    IMPORT_LOG2("Existing POP3 server named: %s, userName: %s\n",
                pServerName, pUserName);
    // for an existing server we create another identity,
    // TB listed under 'manage identities'
    nsCOMPtr<nsIMsgAccount>  account;
    rv = pMgr->FindAccountForServer(in, getter_AddRefs(account));
    if (NS_SUCCEEDED(rv) && account) {
      IMPORT_LOG0("Created identity and added to existing POP3 incoming server.\n");
      // Fiddle with the identities
      in->GetAuthMethod(&authMethod);
      SetIdentities(pMgr, account, hKey, pUserName, authMethod, false);
      result = true;
      if (ppAccount)
        account->QueryInterface(NS_GET_IID(nsIMsgAccount), (void **)ppAccount);
    }
  }
  else
    result = true;
  nsOERegUtil::FreeValueBytes((BYTE *) pUserName);
  return result;
}
Exemple #12
0
bool OESettings::DoIMAPServer(nsIMsgAccountManager *pMgr, HKEY hKey, char *pServerName, nsIMsgAccount **ppAccount)
{
  PRInt32 authMethod;
  if (ppAccount)
    *ppAccount = nsnull;

  char * pUserName;
  pUserName = (char *)nsOERegUtil::GetValueBytes(hKey, "IMAP User Name");
  if (!pUserName)
    return false;

  bool result = false;

  // I now have a user name/server name pair, find out if it already exists?
  nsCOMPtr<nsIMsgIncomingServer> in;
  nsresult rv = pMgr->FindServer(nsDependentCString(pUserName),
                                 nsDependentCString(pServerName),
                                 NS_LITERAL_CSTRING("imap"),
                                 getter_AddRefs(in));
  if (NS_FAILED(rv) || (in == nsnull)) {
    // Create the incoming server and an account for it?
    rv = pMgr->CreateIncomingServer(nsDependentCString(pUserName),
                                    nsDependentCString(pServerName),
                                    NS_LITERAL_CSTRING("imap"),
                                    getter_AddRefs(in));
    if (NS_SUCCEEDED(rv) && in) {
      BYTE * pRootFolder = nsOERegUtil::GetValueBytes(hKey, "IMAP Root Folder");
      if (pRootFolder)
      {
        nsCOMPtr<nsIImapIncomingServer> imapServer = do_QueryInterface(in);
        imapServer->SetServerDirectory(nsDependentCString((const char *) pRootFolder));
        nsOERegUtil::FreeValueBytes(pRootFolder);
      }

      BYTE * pSecureConnection = nsOERegUtil::GetValueBytes(hKey, "IMAP Secure Connection");
      if (pSecureConnection)
      {
        if (*pSecureConnection)
          in->SetSocketType(nsMsgSocketType::SSL);
        nsOERegUtil::FreeValueBytes(pSecureConnection);
      }

      BYTE * pPort = nsOERegUtil::GetValueBytes(hKey, "IMAP Port");
      if (pPort)
      {
        in->SetPort(*(PRInt32 *) pPort);
        nsOERegUtil::FreeValueBytes(pPort);
      }

      BYTE * pBytesTemp = nsOERegUtil::GetValueBytes(hKey, "IMAP Use Sicily");
      if (pBytesTemp)
      {
        bool secAuth = *(bool *)pBytesTemp;
        nsOERegUtil::FreeValueBytes(pBytesTemp);
        authMethod = secAuth ? nsMsgAuthMethod::secure
            : nsMsgAuthMethod::passwordCleartext;
      }
      else {
        authMethod = nsMsgAuthMethod::passwordCleartext;
      }
      in->SetAuthMethod(authMethod);

      in->SetDoBiff(checkNewMail);
      in->SetBiffMinutes(checkNewMailTime);

      IMPORT_LOG2("Created IMAP server named: %s, userName: %s\n",
                   pServerName, pUserName);

      nsString prettyName;
      if (NS_SUCCEEDED(GetAccountName(hKey, pServerName, prettyName)))
        rv = in->SetPrettyName(prettyName);

      // We have a server, create an account.
      nsCOMPtr<nsIMsgAccount> account;
      rv = pMgr->CreateAccount(getter_AddRefs(account));
      if (NS_SUCCEEDED(rv) && account) {
        rv = account->SetIncomingServer(in);

        IMPORT_LOG0("Created an account and set the IMAP server as the incoming server\n");

        // Fiddle with the identities
        SetIdentities(pMgr, account, hKey, pUserName, authMethod, false);
        result = true;
        if (ppAccount)
          account->QueryInterface(NS_GET_IID(nsIMsgAccount), (void **)ppAccount);
      }
    }
  }
  else if (NS_SUCCEEDED(rv) && in) {
    // for an existing server we create another identity,
    //  TB lists under 'manage identities'
    nsCOMPtr<nsIMsgAccount> account;
    rv = pMgr->FindAccountForServer(in, getter_AddRefs(account));
    if (NS_SUCCEEDED(rv) && account) {
      IMPORT_LOG0("Created an identity and added to existing IMAP incoming server\n");
      // Fiddle with the identities
      in->GetAuthMethod(&authMethod);
      SetIdentities(pMgr, account, hKey, pUserName, authMethod, false);
      result = true;
      if (ppAccount)
        account->QueryInterface(NS_GET_IID(nsIMsgAccount),
                                 (void **)ppAccount);
    }
  }
  else
    result = true;
  nsOERegUtil::FreeValueBytes((BYTE *) pUserName);
  return result;
}
Exemple #13
0
bool OutlookSettings::DoPOP3Server(nsIMsgAccountManager *pMgr, HKEY hKey, char *pServerName, nsIMsgAccount **ppAccount)
{
  if (ppAccount)
    *ppAccount = nsnull;

  BYTE *pBytes;
  pBytes = nsOutlookRegUtil::GetValueBytes(hKey, "POP3 User Name");
  if (!pBytes)
    return false;

  bool result = false;

  // I now have a user name/server name pair, find out if it already exists?
  nsCOMPtr<nsIMsgIncomingServer> in;
  nsresult rv = pMgr->FindServer(nsDependentCString((const char *)pBytes), nsDependentCString(pServerName), NS_LITERAL_CSTRING("pop3"), getter_AddRefs(in));
  if (NS_FAILED(rv) || (in == nsnull)) {
    // Create the incoming server and an account for it?
    rv = pMgr->CreateIncomingServer(nsDependentCString((const char *)pBytes), nsDependentCString(pServerName), NS_LITERAL_CSTRING("pop3"), getter_AddRefs(in));
    if (NS_SUCCEEDED(rv) && in) {
      rv = in->SetType(NS_LITERAL_CSTRING("pop3"));

      // TODO SSL, auth method

        nsCOMPtr<nsIPop3IncomingServer> pop3Server = do_QueryInterface(in);
        if (pop3Server) {
            // set local folders as the Inbox to use for this POP3 server
            nsCOMPtr<nsIMsgIncomingServer> localFoldersServer;
            pMgr->GetLocalFoldersServer(getter_AddRefs(localFoldersServer));

            if (!localFoldersServer)
            {
                // XXX: We may need to move this local folder creation code to the generic nsImportSettings code
                // if the other import modules end up needing to do this too.
                // if Local Folders does not exist already, create it
                rv = pMgr->CreateLocalMailAccount();
                if (NS_FAILED(rv)) {
                    IMPORT_LOG0("*** Failed to create Local Folders!\n");
                    return false;
                }
                pMgr->GetLocalFoldersServer(getter_AddRefs(localFoldersServer));
            }

            // now get the account for this server
            nsCOMPtr<nsIMsgAccount> localFoldersAccount;
            pMgr->FindAccountForServer(localFoldersServer, getter_AddRefs(localFoldersAccount));
            if (localFoldersAccount)
            {
              nsCString localFoldersAcctKey;
              localFoldersAccount->GetKey(localFoldersAcctKey);
              pop3Server->SetDeferredToAccount(localFoldersAcctKey);
              pop3Server->SetDeferGetNewMail(true);
            }
        }

        IMPORT_LOG2("Created POP3 server named: %s, userName: %s\n", pServerName, (char *)pBytes);

        nsString prettyName;
        if (NS_SUCCEEDED(GetAccountName(hKey, pServerName, prettyName)))
          rv = in->SetPrettyName(prettyName);
      // We have a server, create an account.
      nsCOMPtr<nsIMsgAccount>  account;
      rv = pMgr->CreateAccount(getter_AddRefs(account));
      if (NS_SUCCEEDED(rv) && account) {
        rv = account->SetIncomingServer(in);

      IMPORT_LOG0("Created a new account and set the incoming server to the POP3 server.\n");

        nsCOMPtr<nsIPop3IncomingServer> pop3Server = do_QueryInterface(in, &rv);
        NS_ENSURE_SUCCESS(rv,rv);
        BYTE *pLeaveOnServer = nsOutlookRegUtil::GetValueBytes(hKey, "Leave Mail On Server");
        if (pLeaveOnServer)
        {
          pop3Server->SetLeaveMessagesOnServer(*pLeaveOnServer == 1 ? true : false);
          nsOutlookRegUtil::FreeValueBytes(pLeaveOnServer);
        }

        // Fiddle with the identities
        SetIdentities(pMgr, account, hKey);
        result = true;
        if (ppAccount)
          account->QueryInterface(NS_GET_IID(nsIMsgAccount), (void **)ppAccount);
      }
    }
  }
  else
    result = true;

  nsOutlookRegUtil::FreeValueBytes(pBytes);

  return result;
}
bool OESettings::DoNNTPServer(nsIMsgAccountManager *aMgr,
                              nsIWindowsRegKey *aKey,
                              const nsString &aServerName,
                              nsIMsgAccount **ppAccount)
{
  if (ppAccount)
    *ppAccount = nullptr;

  nsAutoString userName;
  nsresult rv;
  // this only exists if NNTP server requires it or not anon login
  rv = aKey->ReadStringValue(NS_LITERAL_STRING("NNTP User Name"), userName);

  bool result = false;

  nsAutoCString nativeServerName;
  NS_CopyUnicodeToNative(aServerName, nativeServerName);
  // I now have a user name/server name pair, find out if it already exists?
  // NNTP can have empty user name.  This is wild card in findserver
  nsCOMPtr<nsIMsgIncomingServer> in;
  rv = aMgr->FindServer(EmptyCString(),
                        nativeServerName,
                        NS_LITERAL_CSTRING("nntp"),
                        getter_AddRefs(in));
  if (NS_FAILED(rv) || (in == nullptr)) {
    // Create the incoming server and an account for it?
    rv = aMgr->CreateIncomingServer(EmptyCString(),
                                    nativeServerName,
                                    NS_LITERAL_CSTRING("nntp"),
                                    getter_AddRefs(in));
    if (NS_SUCCEEDED(rv) && in) {
      uint32_t port = 0;
      rv = aKey->ReadIntValue(NS_LITERAL_STRING("NNTP Port"),
                              &port);
      if (NS_SUCCEEDED(rv) && port && port != 119)
        in->SetPort(static_cast<int32_t>(port));

      nsAutoCString nativeUserName;
      NS_CopyUnicodeToNative(userName, nativeUserName);
      // do nntpincomingserver stuff
      nsCOMPtr<nsINntpIncomingServer> nntpServer = do_QueryInterface(in);
      if (nntpServer && !userName.IsEmpty()) {
        nntpServer->SetPushAuth(true);
        in->SetUsername(nativeUserName);
      }

      IMPORT_LOG2("Created NNTP server named: %s, userName: %s\n",
                  nativeServerName.get(), nativeUserName.get());

      nsString prettyName;
      if (NS_SUCCEEDED(GetAccountName(aKey, aServerName, prettyName)))
        rv = in->SetPrettyName(prettyName);

      // We have a server, create an account.
      nsCOMPtr<nsIMsgAccount> account;
      rv = aMgr->CreateAccount(getter_AddRefs(account));
      if (NS_SUCCEEDED(rv) && account) {
        rv = account->SetIncomingServer(in);

        IMPORT_LOG0("Created an account and set the NNTP server as the incoming server\n");

        // Fiddle with the identities
        SetIdentities(aMgr, account, aKey, userName, 0, true);
        result = true;
        if (ppAccount)
          account->QueryInterface(NS_GET_IID(nsIMsgAccount), (void **)ppAccount);
      }
    }
  }
  else if (NS_SUCCEEDED(rv) && in) {
    // for the existing server...
    nsCOMPtr<nsIMsgAccount> account;
    rv = aMgr->FindAccountForServer(in, getter_AddRefs(account));
    if (NS_SUCCEEDED(rv) && account) {
      IMPORT_LOG0("Using existing account and set the NNTP server as the incoming server\n");
      // Fiddle with the identities
      SetIdentities(aMgr, account, aKey, userName, 0, true);
      if (ppAccount)
        account->QueryInterface(NS_GET_IID(nsIMsgAccount),
                                 (void **)ppAccount);
      return true;
    }
  }
  else
    result = true;

  return result;
}
PRBool nsOEScanBoxes::FindMailBoxes( nsIFile* descFile)
{
  Reset();

  nsresult  rv;
  PRBool    isFile = PR_FALSE;

  rv = descFile->IsFile( &isFile);
  if (NS_FAILED( rv) || !isFile)
    return( PR_FALSE);

        nsCOMPtr <nsIInputStream> descInputStream;

        rv = NS_NewLocalFileInputStream(getter_AddRefs(descInputStream), descFile);
  if (NS_FAILED( rv))
    return( PR_FALSE);

  IMPORT_LOG0( "Reading the folders.nch file\n");

  PRUint32    curRec;
  if (!ReadLong( descInputStream, curRec, 20)) {
    return( PR_FALSE);
  }

  // Now for each record
  PRBool      done = PR_FALSE;
  PRUint32    equal;
  PRUint32    size;
  PRUint32    previous;
  PRUint32    next;
  MailboxEntry *  pEntry;
  PRBool      failed;
  nsCString    ext;
  nsCString    mbxExt( ".mbx");

  while (!done) {

    if (!ReadLong( descInputStream, equal, curRec)) return( PR_FALSE);
    if (curRec != equal) {
      IMPORT_LOG1( "Record start invalid: %ld\n", curRec);
      break;
    }
    if (!ReadLong( descInputStream, size, curRec + 4)) return( PR_FALSE);
    if (!ReadLong( descInputStream, previous, curRec + 8)) return( PR_FALSE);
    if (!ReadLong( descInputStream, next, curRec + 12)) return( PR_FALSE);
    failed = PR_FALSE;
    pEntry = new MailboxEntry;
    if (!ReadLong( descInputStream, pEntry->index, curRec + 16)) failed = PR_TRUE;
    if (!ReadString( descInputStream, pEntry->mailName, curRec + 20)) failed = PR_TRUE;
    if (!ReadString( descInputStream, pEntry->fileName, curRec + 279)) failed = PR_TRUE;
    if (!ReadLong( descInputStream, pEntry->parent, curRec + 539)) failed = PR_TRUE;
    if (!ReadLong( descInputStream, pEntry->child, curRec + 543)) failed = PR_TRUE;
    if (!ReadLong( descInputStream, pEntry->sibling, curRec + 547)) failed = PR_TRUE;
    if (!ReadLong( descInputStream, pEntry->type, curRec + 551)) failed = PR_TRUE;
    if (failed) {
      delete pEntry;
      return( PR_FALSE);
    }

    #ifdef _TRACE_MAILBOX_ENTRIES
    IMPORT_LOG0( "------------\n");
    IMPORT_LOG2( "    Offset: %lx, index: %ld\n", curRec, pEntry->index);
    IMPORT_LOG2( "      previous: %lx, next: %lx\n", previous, next);
    IMPORT_LOG2( "      Name: %S, File: %s\n", (PRUnichar *) pEntry->mailName, (const char *) pEntry->fileName);
    IMPORT_LOG3( "      Parent: %ld, Child: %ld, Sibling: %ld\n", pEntry->parent, pEntry->child, pEntry->sibling);
    #endif

    pEntry->fileName.Right( ext, 4);
    if (!ext.Equals(mbxExt))
      pEntry->fileName.Append( ".mbx");

    m_entryArray.AppendElement( pEntry);

    curRec = next;
    if (!next)
      done = PR_TRUE;
  }

  MailboxEntry *pZero = GetIndexEntry( 0);
  if (pZero)
    m_pFirst = GetIndexEntry( pZero->child);

  IMPORT_LOG1( "Read the folders.nch file, found %ld mailboxes\n", (long) m_entryArray.Count());

  return( PR_TRUE);
}
bool OESettings::DoPOP3Server(nsIMsgAccountManager *aMgr,
                              nsIWindowsRegKey *aKey,
                              const nsString &aServerName,
                              nsIMsgAccount **ppAccount)
{
  if (ppAccount)
    *ppAccount = nullptr;

  nsAutoString userName;
  nsresult rv;
  rv = aKey->ReadStringValue(NS_LITERAL_STRING("POP3 User Name"), userName);
  if (NS_FAILED(rv))
    return false;

  nsAutoCString nativeUserName;
  NS_CopyUnicodeToNative(userName, nativeUserName);
  nsAutoCString nativeServerName;
  NS_CopyUnicodeToNative(aServerName, nativeServerName);

  // I now have a user name/server name pair, find out if it already exists?
  nsCOMPtr<nsIMsgIncomingServer> in;
  rv = aMgr->FindServer(nativeUserName,
                        nativeServerName,
                        NS_LITERAL_CSTRING("pop3"),
                        getter_AddRefs(in));
  if (NS_SUCCEEDED(rv)) {
    IMPORT_LOG2("Existing POP3 server named: %s, userName: %s\n",
                nativeUserName.get(), nativeServerName.get());
    // for an existing server we create another identity,
    // TB listed under 'manage identities'
    nsCOMPtr<nsIMsgAccount>  account;
    rv = aMgr->FindAccountForServer(in, getter_AddRefs(account));
    if (NS_SUCCEEDED(rv) && account) {
      IMPORT_LOG0("Created identity and added to existing POP3 incoming server.\n");
      // Fiddle with the identities
      int32_t authMethod;
      in->GetAuthMethod(&authMethod);
      SetIdentities(aMgr, account, aKey, userName, authMethod, false);
      if (ppAccount)
        account->QueryInterface(NS_GET_IID(nsIMsgAccount), (void **)ppAccount);
      return true;
    }
    return false;
  }

  // Create the incoming server and an account for it?
  rv = aMgr->CreateIncomingServer(nativeUserName,
                                  nativeServerName,
                                  NS_LITERAL_CSTRING("pop3"),
                                  getter_AddRefs( in));
  if (NS_FAILED(rv))
    return false;

  SetIncomingServerProperties(in, aKey, NS_LITERAL_STRING("POP3 "));

  nsCOMPtr<nsIPop3IncomingServer> pop3Server = do_QueryInterface(in);
  if (pop3Server) {
    // set local folders as the Inbox to use for this POP3 server
    nsCOMPtr<nsIMsgIncomingServer> localFoldersServer;
    aMgr->GetLocalFoldersServer(getter_AddRefs(localFoldersServer));

    if (!localFoldersServer)
    {
      // If Local Folders does not exist already, create it

      if (NS_FAILED(aMgr->CreateLocalMailAccount())) {
        IMPORT_LOG0("*** Failed to create Local Folders!\n");
        return false;
      }

      aMgr->GetLocalFoldersServer(getter_AddRefs(localFoldersServer));
    }

    // now get the account for this server
    nsCOMPtr<nsIMsgAccount> localFoldersAccount;
    aMgr->FindAccountForServer(localFoldersServer, getter_AddRefs(localFoldersAccount));
    if (localFoldersAccount)
    {
      nsCString localFoldersAcctKey;
      localFoldersAccount->GetKey(localFoldersAcctKey);
      pop3Server->SetDeferredToAccount(localFoldersAcctKey);
    }

    uint32_t intValue;
    rv = aKey->ReadIntValue(NS_LITERAL_STRING("POP3 Skip Account"), &intValue);
    // OE:0=='Include this account when receiving mail or synchronizing'==
    // TB:1==AM:Server:advanced:Include this server when getting new mail
    pop3Server->SetDeferGetNewMail(NS_SUCCEEDED(rv) && intValue == 0);

    rv = aKey->ReadIntValue(NS_LITERAL_STRING("Leave Mail On Server"),
                            &intValue);
    pop3Server->SetLeaveMessagesOnServer(NS_SUCCEEDED(rv) && intValue == 1);

    rv = aKey->ReadIntValue(NS_LITERAL_STRING("Remove When Deleted"),
                            &intValue);
    pop3Server->SetDeleteMailLeftOnServer(NS_SUCCEEDED(rv) && intValue == 1);

    rv = aKey->ReadIntValue(NS_LITERAL_STRING("Remove When Expired"),
                            &intValue);
    pop3Server->SetDeleteByAgeFromServer(NS_SUCCEEDED(rv) && intValue == 1);

    rv = aKey->ReadIntValue(NS_LITERAL_STRING("Expire Days"),
                            &intValue);
    if (NS_SUCCEEDED(rv))
      pop3Server->SetNumDaysToLeaveOnServer(static_cast<int32_t>(intValue));
  }
  IMPORT_LOG2("Created POP3 server named: %s, userName: %s\n",
              nativeServerName.get(), nativeUserName.get());
  nsString prettyName;
  if (NS_SUCCEEDED(GetAccountName(aKey, aServerName, prettyName)))
    rv = in->SetPrettyName(prettyName);

  // We have a server, create an account.
  nsCOMPtr<nsIMsgAccount>  account;
  rv = aMgr->CreateAccount(getter_AddRefs( account));
  if (NS_SUCCEEDED( rv) && account) {
    rv = account->SetIncomingServer(in);
    IMPORT_LOG0("Created a new account and set the incoming server to the POP3 server.\n");

    int32_t authMethod;
    in->GetAuthMethod(&authMethod);
    // Fiddle with the identities
    SetIdentities(aMgr, account, aKey, userName, authMethod, false);
    if (ppAccount)
      account->QueryInterface(NS_GET_IID(nsIMsgAccount),
                               (void **)ppAccount);
    return true;
  }

  return false;
}
PRBool nsEudoraWin32::BuildPOPAccount( nsIMsgAccountManager *accMgr, const char *pSection, const char *pIni, nsIMsgAccount **ppAccount)
{
  if (ppAccount)
    *ppAccount = nsnull;

  char valBuff[kIniValueSize];
  nsCString serverName;
  nsCString userName;

  GetServerAndUserName( pSection, pIni, serverName, userName, valBuff);

  if (serverName.IsEmpty() || userName.IsEmpty())
    return( PR_FALSE);

  PRBool result = PR_FALSE;

  // I now have a user name/server name pair, find out if it already exists?
  nsCOMPtr<nsIMsgIncomingServer> in;
  nsresult rv = accMgr->FindServer( userName, serverName, NS_LITERAL_CSTRING("pop3"), getter_AddRefs(in));
  if (NS_FAILED(rv) || !in)
  {
    // Create the incoming server and an account for it?
    rv = accMgr->CreateIncomingServer( userName, serverName, NS_LITERAL_CSTRING("pop3"), getter_AddRefs(in));
    if (NS_SUCCEEDED( rv) && in)
    {
      rv = in->SetType(NS_LITERAL_CSTRING("pop3"));
      // rv = in->SetHostName( serverName);
      // rv = in->SetUsername( userName);

      IMPORT_LOG2( "Created POP3 server named: %s, userName: %s\n", serverName.get(), userName.get());

      nsString prettyName;
      GetAccountName( pSection, prettyName);
      IMPORT_LOG1( "\tSet pretty name to: %S\n", prettyName.get());
      rv = in->SetPrettyName( prettyName);

      // We have a server, create an account.
      nsCOMPtr<nsIMsgAccount>  account;
      rv = accMgr->CreateAccount( getter_AddRefs( account));
      if (NS_SUCCEEDED( rv) && account)
      {
        rv = account->SetIncomingServer( in);

        IMPORT_LOG0( "Created a new account and set the incoming server to the POP3 server.\n");

        nsCOMPtr<nsIPop3IncomingServer> pop3Server = do_QueryInterface(in, &rv);
        NS_ENSURE_SUCCESS(rv,rv);
        UINT valInt = ::GetPrivateProfileInt(pSection, "LeaveMailOnServer", 0, pIni);
        pop3Server->SetLeaveMessagesOnServer(valInt ? PR_TRUE : PR_FALSE);

        // Fiddle with the identities
        SetIdentities(accMgr, account, pSection, pIni, userName.get(), serverName.get(), valBuff);
        result = PR_TRUE;
        if (ppAccount)
          account->QueryInterface( NS_GET_IID(nsIMsgAccount), (void **)ppAccount);
      }
    }
  }
  else
    result = PR_TRUE;

  return( result);
}
Exemple #18
0
bool OutlookSettings::DoPOP3Server(nsIMsgAccountManager *aMgr,
                                   nsIWindowsRegKey *aKey,
                                   const nsString &aServerName,
                                   nsIMsgAccount **aAccount)
{
  nsAutoString userName;
  nsresult rv;
  rv = aKey->ReadStringValue(NS_LITERAL_STRING("POP3 User Name"), userName);
  if (NS_FAILED(rv))
    return false;

  // I now have a user name/server name pair, find out if it already exists?
  nsCAutoString nativeUserName;
  NS_CopyUnicodeToNative(userName, nativeUserName);
  nsCAutoString nativeServerName;
  NS_CopyUnicodeToNative(aServerName, nativeServerName);
  nsCOMPtr<nsIMsgIncomingServer> in;
  rv = aMgr->FindServer(nativeUserName,
                        nativeServerName,
                        NS_LITERAL_CSTRING("pop3"),
                        getter_AddRefs(in));
  if (NS_SUCCEEDED(rv))
    return true;

  // Create the incoming server and an account for it?
  rv = aMgr->CreateIncomingServer(nativeUserName,
                                  nativeServerName,
                                  NS_LITERAL_CSTRING("pop3"),
                                  getter_AddRefs(in));
  rv = in->SetType(NS_LITERAL_CSTRING("pop3"));

  // TODO SSL, auth method

  nsCOMPtr<nsIPop3IncomingServer> pop3Server = do_QueryInterface(in);
  NS_ENSURE_SUCCESS(rv, false);

  // set local folders as the Inbox to use for this POP3 server
  nsCOMPtr<nsIMsgIncomingServer> localFoldersServer;
  aMgr->GetLocalFoldersServer(getter_AddRefs(localFoldersServer));

  if (!localFoldersServer) {
    // XXX: We may need to move this local folder creation code to the generic nsImportSettings code
    // if the other import modules end up needing to do this too.
    // if Local Folders does not exist already, create it
    rv = aMgr->CreateLocalMailAccount();
    if (NS_FAILED(rv)) {
      IMPORT_LOG0("*** Failed to create Local Folders!\n");
      return false;
    }
    aMgr->GetLocalFoldersServer(getter_AddRefs(localFoldersServer));
  }

  // now get the account for this server
  nsCOMPtr<nsIMsgAccount> localFoldersAccount;
  aMgr->FindAccountForServer(localFoldersServer, getter_AddRefs(localFoldersAccount));
  if (localFoldersAccount) {
    nsCString localFoldersAcctKey;
    localFoldersAccount->GetKey(localFoldersAcctKey);
    pop3Server->SetDeferredToAccount(localFoldersAcctKey);
    pop3Server->SetDeferGetNewMail(true);
  }

  IMPORT_LOG2("Created POP3 server named: %s, userName: %s\n",
              nativeServerName.get(),
              nativeUserName.get());

  nsString prettyName;
  rv = GetAccountName(aKey, aServerName, prettyName);
  if (NS_FAILED(rv))
    return false;

  rv = in->SetPrettyName(prettyName);
  // We have a server, create an account.
  nsCOMPtr<nsIMsgAccount>  account;
  rv = aMgr->CreateAccount(getter_AddRefs(account));
  if (NS_FAILED(rv))
    return false;

  rv = account->SetIncomingServer(in);

  IMPORT_LOG0("Created a new account and set the incoming server to the POP3 server.\n");

  PRUint32 leaveOnServer;
  rv = aKey->ReadIntValue(NS_LITERAL_STRING("Leave Mail On Server"), &leaveOnServer);
  if (NS_SUCCEEDED(rv))
    pop3Server->SetLeaveMessagesOnServer(leaveOnServer == 1 ? true : false);

  // Fiddle with the identities
  SetIdentities(aMgr, account, aKey);

  if (aAccount)
    account.forget(aAccount);

  return true;
}
nsresult nsEudoraMailbox::ReadNextMessage(ReadFileState *pState, SimpleBufferTonyRCopiedOnce& copy,
                                          SimpleBufferTonyRCopiedOnce& header, SimpleBufferTonyRCopiedOnce& body,
                                          nsCString& defaultDate, nsCString& bodyType, EudoraTOCEntry *pTocEntry)
{
  header.m_writeOffset = 0;
  body.m_writeOffset = 0;

  nsresult    rv;
  int32_t      lineLen;
  char      endBuffer = 0;

  lineLen = -1;
  // Find the from separator - we should actually be positioned at the
  // from separator, but for now, we'll verify this.
  while (lineLen == -1) {
    if (NS_FAILED(rv = FillMailBuffer(pState, copy))) {
      IMPORT_LOG0("*** Error, FillMailBuffer FAILED in ReadNextMessage\n");
      return rv;
    }
    lineLen = IsEudoraFromSeparator(copy.m_pBuffer + copy.m_writeOffset, copy.m_bytesInBuf - copy.m_writeOffset, defaultDate);

    if (lineLen == -1) {
      while ((lineLen = FindStartLine(copy)) == -1) {
        copy.m_writeOffset = copy.m_bytesInBuf;
        if (NS_FAILED(rv = FillMailBuffer(pState, copy))) {
          IMPORT_LOG0("*** Error, FillMailBuffer FAILED in ReadNextMessage, looking for next start line\n");
          return rv;
        }
        if (!copy.m_bytesInBuf) {
          IMPORT_LOG0("*** Error, ReadNextMessage, looking for start of next line, got end of file.\n");
          return NS_ERROR_FAILURE;
        }
      }
      copy.m_writeOffset += lineLen;
      lineLen = -1;
    }
  }

  // Skip past the from line separator
  while ((lineLen = FindStartLine(copy)) == -1) {
    copy.m_writeOffset = copy.m_bytesInBuf;
    if (NS_FAILED(rv = FillMailBuffer(pState, copy))) {
      IMPORT_LOG0("*** Error, ReadNextMessage, FillMailBuffer failed looking for from sep\n");
      return rv;
    }
    if (!copy.m_bytesInBuf) {
      IMPORT_LOG0("*** Error, ReadNextMessage, end of file looking for from sep\n");
      return NS_ERROR_FAILURE;
    }
  }
  copy.m_writeOffset += lineLen;
  if (NS_FAILED(rv = FillMailBuffer(pState, copy))) {
    IMPORT_LOG0("*** Error, Unable to fill mail buffer after from sep.\n");
    return rv;
  }

  // This should be the headers...
  int32_t endLen = -1;
  while ((endLen = IsEndHeaders(copy)) == -1) {
    while ((lineLen = FindNextEndLine(copy)) == -1) {
      copy.m_writeOffset = copy.m_bytesInBuf;
      if (!header.Write(copy.m_pBuffer, copy.m_writeOffset)) {
        IMPORT_LOG0("*** ERROR, writing headers\n");
        return NS_ERROR_FAILURE;
      }
      if (NS_FAILED(rv = FillMailBuffer(pState, copy))) {
        IMPORT_LOG0("*** Error reading message headers\n");
        return rv;
      }
      if (!copy.m_bytesInBuf) {
        IMPORT_LOG0("*** Error, end of file while reading headers\n");
        return NS_ERROR_FAILURE;
      }
    }
    copy.m_writeOffset += lineLen;
    if ((copy.m_writeOffset + 4) >= copy.m_bytesInBuf) {
      if (!header.Write(copy.m_pBuffer, copy.m_writeOffset)) {
        IMPORT_LOG0("*** ERROR, writing headers 2\n");
        return NS_ERROR_FAILURE;
      }
      if (NS_FAILED(rv = FillMailBuffer(pState, copy))) {
        IMPORT_LOG0("*** Error reading message headers 2\n");
        return rv;
      }
    }
  }

  if (!header.Write(copy.m_pBuffer, copy.m_writeOffset)) {
    IMPORT_LOG0("*** Error writing final headers\n");
    return NS_ERROR_FAILURE;
  }

  if (pTocEntry) {
    // This is not the prettiest spot to stick this code, but it works and it was convenient.
    char    header_str[128];

    // Write X-Mozilla-Status header
    PR_snprintf(header_str, 128, MSG_LINEBREAK X_MOZILLA_STATUS_FORMAT MSG_LINEBREAK, pTocEntry->GetMozillaStatusFlags());
    header.Write(header_str, strlen(header_str));

    // Write X-Mozilla-Status2 header
    PR_snprintf(header_str, 128, X_MOZILLA_STATUS2_FORMAT MSG_LINEBREAK, pTocEntry->GetMozillaStatus2Flags());
    header.Write(header_str, strlen(header_str));

    // Format and write X-Mozilla-Keys header
    nsCString  keywordHdr(X_MOZILLA_KEYWORDS);
    if (pTocEntry->HasEudoraLabel()) {
      PR_snprintf(header_str, 128, "eudoralabel%d", pTocEntry->GetLabelNumber());
      keywordHdr.Replace(sizeof(HEADER_X_MOZILLA_KEYWORDS) + 1, strlen(header_str), header_str);
    }
    header.Write(keywordHdr.get(), keywordHdr.Length());
  }

  if (!header.Write(&endBuffer, 1)) {
    IMPORT_LOG0("*** Error writing header trailing null\n");
    return NS_ERROR_FAILURE;
  }

  copy.m_writeOffset += endLen;
  if (NS_FAILED(rv = FillMailBuffer(pState, copy))) {
    IMPORT_LOG0("*** Error reading beginning of message body\n");
    return rv;
  }

  EmptyAttachments();

  // Get the body!
  // Read one line at a time here and look for the next separator
  nsCString tmp;
  bool insideEudoraTags = false;
  // by default we consider the body text to be plain text
  bodyType = "text/plain";

  while ((lineLen = IsEudoraFromSeparator(copy.m_pBuffer + copy.m_writeOffset, copy.m_bytesInBuf - copy.m_writeOffset, tmp)) == -1) {
    int32_t tagLength = 0;
    if (IsEudoraTag (copy.m_pBuffer + copy.m_writeOffset, copy.m_bytesInBuf - copy.m_writeOffset, insideEudoraTags, bodyType, tagLength)) {
      // We don't want to keep eudora tags so skip over them.

      // let's write the previous text
      if (!body.Write(copy.m_pBuffer, copy.m_writeOffset)) {
        IMPORT_LOG0("*** Error writing to message body\n");
        return NS_ERROR_FAILURE;
      }

      // we want to skip over the tag...for now we are assuming the tag is always at the start of line.
      copy.m_writeOffset += tagLength;
        if (NS_FAILED(rv = FillMailBuffer(pState, copy))) {
          IMPORT_LOG0("*** Error reading message body\n");
          return rv;
        }

      if (!copy.m_bytesInBuf)
        break;

      continue;
    }

    // Eudora Attachment lines are always outside Eudora Tags
    // so we shouldn't try to find one here
    if (!insideEudoraTags) {
    // Debatable is whether or not to exclude these lines from the
    // text of the message, I prefer not to in case the original
    // attachment is actually missing.
    rv = ExamineAttachment(copy);
    if (NS_FAILED(rv)) {
      IMPORT_LOG0("*** Error examining attachment line\n");
      return rv;
    }
    }

    while (((lineLen = FindStartLine(copy)) == -1) && copy.m_bytesInBuf) {
      copy.m_writeOffset = copy.m_bytesInBuf;
      if (!body.Write(copy.m_pBuffer, copy.m_writeOffset)) {
        IMPORT_LOG0("*** Error writing to message body\n");
        return NS_ERROR_FAILURE;
      }
      if (NS_FAILED(rv = FillMailBuffer(pState, copy))) {
        IMPORT_LOG0("*** Error reading message body\n");
        return rv;
      }
    }
    if (!copy.m_bytesInBuf)
      break;

    copy.m_writeOffset += lineLen;

    // found the start of the next line
    // make sure it's long enough to check for the from line
    if ((copy.m_writeOffset + 2048) >= copy.m_bytesInBuf) {
      if (!body.Write(copy.m_pBuffer, copy.m_writeOffset)) {
        IMPORT_LOG0("*** Error writing to message body 2\n");
        return NS_ERROR_FAILURE;
      }
      if (NS_FAILED(rv = FillMailBuffer(pState, copy))) {
        IMPORT_LOG0("*** Error reading message body 2\n");
        return rv;
      }
    }
  }

  // the start of the current line is a from, we-re done
  if (!body.Write(copy.m_pBuffer, copy.m_writeOffset)) {
    IMPORT_LOG0("*** Error writing final message body\n");
    return NS_ERROR_FAILURE;
  }
  if (!body.Write(&endBuffer, 1)) {
    IMPORT_LOG0("*** Error writing body trailing null\n");
    IMPORT_LOG2("\tbody.m_size: %ld, body.m_writeOffset: %ld\n", body.m_size, body.m_writeOffset);
    return NS_ERROR_FAILURE;
  }
  if (NS_FAILED(rv = FillMailBuffer(pState, copy))) {
    IMPORT_LOG0("*** Error filling mail buffer for next read message\n");
    return rv;
  }

  return NS_OK;
}
bool WMSettings::DoNNTPServer(nsIMsgAccountManager *pMgr,
                                nsIDOMDocument *xmlDoc,
                                const nsString& serverName,
                                nsIMsgAccount **ppAccount)
{
  PRInt32 authMethod;
  PRInt32 errorCode;
  if (ppAccount)
    *ppAccount = nsnull;

  nsAutoString userName, value;
  // this only exists if NNTP server requires it or not, anonymous login
  GetValueForTag(xmlDoc, NS_LITERAL_STRING("NNTP_User_Name"), userName);
  bool result = false;

  // I now have a user name/server name pair, find out if it already exists?
  // NNTP can have empty user name.  This is wild card in findserver
  nsCOMPtr<nsIMsgIncomingServer> in;
  nsresult rv = pMgr->FindServer(EmptyCString(),
                         NS_ConvertUTF16toUTF8(serverName),
                         NS_LITERAL_CSTRING("nntp"),
                         getter_AddRefs(in));
  if (NS_FAILED(rv) || (in == nsnull)) {
    // Create the incoming server and an account for it?
    rv = pMgr->CreateIncomingServer(nsDependentCString(""),
                                    NS_ConvertUTF16toUTF8(serverName),
                                    NS_LITERAL_CSTRING("nntp"),
                                    getter_AddRefs(in));
    if (NS_SUCCEEDED(rv) && in) {

      nsCOMPtr<nsINntpIncomingServer> nntpServer = do_QueryInterface(in);
      if (!nntpServer) {
        IMPORT_LOG1("*** Failed to create nsINnntpIncomingServer for %S!\n",
          serverName.get());
        return PR_FALSE;
      }
      if (!userName.IsEmpty()) {  // if username req'd then auth req'd
        nntpServer->SetPushAuth(PR_TRUE);
        in->SetUsername(NS_ConvertUTF16toUTF8(userName));
      }

      nsAutoString value;
      GetValueForTag(xmlDoc, NS_LITERAL_STRING("NNTP_Port"), value);
      if (!value.IsEmpty()) {
        in->SetPort(value.ToInteger(&errorCode, 16));
      }

      GetValueForTag(xmlDoc, NS_LITERAL_STRING("Account_Name"), value);
      if (!value.IsEmpty()) {
        in->SetPrettyName(value);
      }

      GetValueForTag(xmlDoc, NS_LITERAL_STRING("NNTP_Use_Sicily"), value);
      bool secAuth = (bool)value.ToInteger(&errorCode, 16);
      authMethod = secAuth ? nsMsgAuthMethod::secure :
                             nsMsgAuthMethod::passwordCleartext;
      in->SetAuthMethod(authMethod);

      IMPORT_LOG2("Created NNTP server named: %S, userName: %S\n",
                  serverName.get(), userName.get());

      // We have a server, create an account.
      nsCOMPtr<nsIMsgAccount> account;
      rv = pMgr->CreateAccount(getter_AddRefs(account));
      if (NS_SUCCEEDED(rv) && account) {
        rv = account->SetIncomingServer(in);

        IMPORT_LOG0("Created an account and set the NNTP server "
                    "as the incoming server\n");

        // Fiddle with the identities
        SetIdentities(pMgr, account, xmlDoc, userName, authMethod, PR_TRUE);
        result = PR_TRUE;
        if (ppAccount)
          account.forget(ppAccount);
      }
    }
  }
  else if (NS_SUCCEEDED(rv) && in) {
    // for the existing server...
    nsCOMPtr<nsIMsgAccount> account;
    rv = pMgr->FindAccountForServer(in, getter_AddRefs(account));
    if (NS_SUCCEEDED(rv) && account) {
      IMPORT_LOG0("Using existing account and set the "
                  "NNTP server as the incoming server\n");
      // Fiddle with the identities
      in->GetAuthMethod(&authMethod);
      SetIdentities(pMgr, account, xmlDoc, userName, authMethod, PR_TRUE);
      result = PR_TRUE;
      if (ppAccount)
        account.forget(ppAccount);
    }
  }
  else
    result = PR_TRUE;
  return result;
}
bool WMSettings::DoPOP3Server(nsIMsgAccountManager *pMgr,
                                nsIDOMDocument *xmlDoc,
                                const nsString& serverName,
                                nsIMsgAccount **ppAccount)
{
  PRInt32 authMethod;   // Secure Password Authentication (SPA)
  PRInt32 errorCode;
  if (ppAccount)
    *ppAccount = nsnull;

  nsAutoString userName, value;
  if (NS_FAILED(GetValueForTag(xmlDoc, NS_LITERAL_STRING("POP3_User_Name"),
                               userName)))
    return PR_FALSE;
  bool result = false;
  // I now have a user name/server name pair, find out if it already exists?
  nsCOMPtr<nsIMsgIncomingServer> in;
  nsresult rv = pMgr->FindServer(NS_ConvertUTF16toUTF8(userName),
                                 NS_ConvertUTF16toUTF8(serverName),
                                 NS_LITERAL_CSTRING("pop3"),
                                 getter_AddRefs(in));
  if (NS_FAILED(rv) || (in == nsnull)) {
    // Create the incoming server and an account for it?
    rv = pMgr->CreateIncomingServer(NS_ConvertUTF16toUTF8(userName),
                                    NS_ConvertUTF16toUTF8(serverName),
                                    NS_LITERAL_CSTRING("pop3"),
                                    getter_AddRefs(in));
    if (NS_SUCCEEDED(rv) && in) {
      nsCOMPtr<nsIPop3IncomingServer> pop3Server = do_QueryInterface(in);
      if (!pop3Server){
        IMPORT_LOG1("*** Failed to create nsIPop3IncomingServer for %S!\n",
          serverName.get());
        return PR_FALSE;
      }

      GetValueForTag(xmlDoc, NS_LITERAL_STRING("POP3_Secure_Connection"), value);
      if (value.ToInteger(&errorCode, 16))
        in->SetSocketType(nsMsgSocketType::SSL);

      GetValueForTag(xmlDoc, NS_LITERAL_STRING("POP3_Use_Sicily"), value);
      bool secAuth = (bool)value.ToInteger(&errorCode, 16);
      authMethod = secAuth ? nsMsgAuthMethod::secure :
                             nsMsgAuthMethod::passwordCleartext;
      in->SetAuthMethod(authMethod);

      GetValueForTag(xmlDoc, NS_LITERAL_STRING("POP3_Port"), value);
      if (!value.IsEmpty())
        in->SetPort(value.ToInteger(&errorCode, 16));

      GetValueForTag(xmlDoc, NS_LITERAL_STRING("POP3_Skip_Account"), value);
      if (!value.IsEmpty())
        // OE:0=='Include this account when receiving mail or synchronizing'==
        // TB:1==ActMgr:Server:advanced:Include this server when getting new mail
        pop3Server->SetDeferGetNewMail(value.ToInteger(&errorCode, 16) == 0);
      else
        pop3Server->SetDeferGetNewMail(PR_FALSE);
      GetValueForTag(xmlDoc, NS_LITERAL_STRING("Leave_Mail_On_Server"), value);
      if (!value.IsEmpty())
        pop3Server->SetLeaveMessagesOnServer((bool)value.ToInteger(&errorCode, 16));
      GetValueForTag(xmlDoc, NS_LITERAL_STRING("Remove_When_Deleted"), value);
      if (!value.IsEmpty())
        pop3Server->SetDeleteMailLeftOnServer((bool)value.ToInteger(&errorCode, 16));
      GetValueForTag(xmlDoc, NS_LITERAL_STRING("Remove_When_Expired"), value);
      if (!value.IsEmpty())
        pop3Server->SetDeleteByAgeFromServer((bool)value.ToInteger(&errorCode, 16));
      GetValueForTag(xmlDoc, NS_LITERAL_STRING("Expire_Days"), value);
      if (!value.IsEmpty())
        pop3Server->SetNumDaysToLeaveOnServer(value.ToInteger(&errorCode, 16));
      GetValueForTag(xmlDoc, NS_LITERAL_STRING("Account_Name"), value);
      if (!value.IsEmpty())
        rv = in->SetPrettyName(value);

      in->SetDoBiff(checkNewMail);
      in->SetBiffMinutes(checkNewMailTime);

      // set local folders as the Inbox to use for this POP3 server
      nsCOMPtr<nsIMsgIncomingServer> localFoldersServer;
      pMgr->GetLocalFoldersServer(getter_AddRefs(localFoldersServer));
      if (!localFoldersServer) {
        // XXX: We may need to move this local folder creation
        // code to the generic nsImportSettings code
        // if the other import modules end up needing to do this too.
        // if Local Folders does not exist already, create it
        rv = pMgr->CreateLocalMailAccount();
        if (NS_FAILED(rv)) {
          IMPORT_LOG0("*** Failed to create Local Folders!\n");
          return PR_FALSE;
        }
        pMgr->GetLocalFoldersServer(getter_AddRefs(localFoldersServer));
      }

      // now get the account for this server
      nsCOMPtr<nsIMsgAccount> localFoldersAccount;
      pMgr->FindAccountForServer(localFoldersServer,
                                 getter_AddRefs(localFoldersAccount));
      if (localFoldersAccount) {
        nsCString localFoldersAcctKey;
        localFoldersAccount->GetKey(localFoldersAcctKey);
        pop3Server->SetDeferredToAccount(localFoldersAcctKey);
      }

      IMPORT_LOG2("Created POP3 server named: %S, userName: %S\n",
                  serverName.get(), userName.get());

      // We have a server, create an account.
      nsCOMPtr<nsIMsgAccount> account;
      rv = pMgr->CreateAccount(getter_AddRefs(account));
      if (NS_SUCCEEDED(rv) && account) {
        rv = account->SetIncomingServer(in);
        IMPORT_LOG0("Created a new account and set the incoming "
                    "server to the POP3 server.\n");

        // Fiddle with the identities
        SetIdentities(pMgr, account, xmlDoc, userName, authMethod, PR_FALSE);
        result = PR_TRUE;
        if (ppAccount)
          account.forget(ppAccount);
      }
    }
  }
  else if (NS_SUCCEEDED(rv) && in) {
    IMPORT_LOG2("Existing POP3 server named: %S, userName: %S\n",
                serverName.get(), userName.get());
    // for an existing server we create another identity,
    // TB listed under 'manage identities'
    nsCOMPtr<nsIMsgAccount>  account;
    rv = pMgr->FindAccountForServer(in, getter_AddRefs(account));
    if (NS_SUCCEEDED(rv) && account) {
      IMPORT_LOG0("Created identity and added to existing POP3 incoming server.\n");
      // Fiddle with the identities
      in->GetAuthMethod(&authMethod);
      SetIdentities(pMgr, account, xmlDoc, userName, authMethod, PR_FALSE);
      result = PR_TRUE;
      if (ppAccount)
        account.forget(ppAccount);
    }
  }
  else
    result = PR_TRUE;
  return result;
}
bool WMSettings::DoIMAPServer(nsIMsgAccountManager *pMgr,
                                nsIDOMDocument *xmlDoc,
                                const nsString& serverName,
                                nsIMsgAccount **ppAccount)
{
  PRInt32 authMethod;   // Secure Password Authentication (SPA)
  PRInt32 errorCode;
  if (ppAccount)
    *ppAccount = nsnull;

  nsAutoString userName, value;
  if (NS_FAILED(GetValueForTag(xmlDoc, NS_LITERAL_STRING("IMAP_User_Name"),
                               userName)))
    return PR_FALSE;
  bool result = false;
  // I now have a user name/server name pair, find out if it already exists?
  nsCOMPtr<nsIMsgIncomingServer> in;
  nsresult rv = pMgr->FindServer(NS_ConvertUTF16toUTF8(userName),
                                 NS_ConvertUTF16toUTF8(serverName),
                                 NS_LITERAL_CSTRING("imap"),
                                 getter_AddRefs(in));
  if (NS_FAILED(rv) || (in == nsnull)) {
    // Create the incoming server and an account for it?
    rv = pMgr->CreateIncomingServer(NS_ConvertUTF16toUTF8(userName),
                                    NS_ConvertUTF16toUTF8(serverName),
                                    NS_LITERAL_CSTRING("imap"),
                                    getter_AddRefs(in));
    if (NS_SUCCEEDED(rv) && in) {
      nsCOMPtr<nsIImapIncomingServer> imapServer = do_QueryInterface(in);
      if (!imapServer){
        IMPORT_LOG1("*** Failed to create nsIImapIncomingServer for %S!\n",
                    serverName.get());
        return PR_FALSE;
      }
      GetValueForTag(xmlDoc, NS_LITERAL_STRING("IMAP_Root_Folder"), value);
      if (!value.IsEmpty())
        imapServer->SetServerDirectory(NS_ConvertUTF16toUTF8(value));

      GetValueForTag(xmlDoc, NS_LITERAL_STRING("IMAP_Secure_Connection"), value);
      if (value.ToInteger(&errorCode, 16))
        in->SetSocketType(nsMsgSocketType::SSL);

      GetValueForTag(xmlDoc, NS_LITERAL_STRING("IMAP_Use_Sicily"), value);
      bool secAuth = (bool)value.ToInteger(&errorCode, 16);
      authMethod = secAuth ? nsMsgAuthMethod::secure :
                             nsMsgAuthMethod::passwordCleartext;
      in->SetAuthMethod(authMethod);

      GetValueForTag(xmlDoc, NS_LITERAL_STRING("IMAP_Port"), value);
      if (!value.IsEmpty())
        in->SetPort(value.ToInteger(&errorCode, 16));

      GetValueForTag(xmlDoc, NS_LITERAL_STRING("Account_Name"), value);
      if (!value.IsEmpty())
        rv = in->SetPrettyName(value);
      in->SetDoBiff(checkNewMail);
      in->SetBiffMinutes(checkNewMailTime);

      IMPORT_LOG2("Created IMAP server named: %S, userName: %S\n",
                  serverName.get(), userName.get());

      // We have a server, create an account.
      nsCOMPtr<nsIMsgAccount> account;
      rv = pMgr->CreateAccount(getter_AddRefs(account));
      if (NS_SUCCEEDED(rv) && account) {
        rv = account->SetIncomingServer(in);

        IMPORT_LOG0("Created an account and set the IMAP server "
                    "as the incoming server\n");

        // Fiddle with the identities
        SetIdentities(pMgr, account, xmlDoc, userName, authMethod, PR_FALSE);
        result = PR_TRUE;
        if (ppAccount)
          account.forget(ppAccount);
      }
    }
  }
  else if (NS_SUCCEEDED(rv) && in) {
    // for an existing server we create another identity,
    //  TB lists under 'manage identities'
    nsCOMPtr<nsIMsgAccount> account;
    rv = pMgr->FindAccountForServer(in, getter_AddRefs(account));
    if (NS_SUCCEEDED(rv) && account) {
      IMPORT_LOG0("Created an identity and added to existing "
                  "IMAP incoming server\n");
      // Fiddle with the identities
      in->GetAuthMethod(&authMethod);
      SetIdentities(pMgr, account, xmlDoc, userName, authMethod, PR_FALSE);
      result = PR_TRUE;
      if (ppAccount)
        account.forget(ppAccount);
    }
  }
  else
    result = PR_TRUE;
  return result;
}
nsresult nsOE5File::ImportMailbox( PRUint32 *pBytesDone, PRBool *pAbort, nsString& name, nsIFile *inFile, nsIFile *pDestination, PRUint32 *pCount)
{
  nsresult  rv;
  PRInt32    msgCount = 0;
  if (pCount)
    *pCount = 0;

  nsCOMPtr <nsIInputStream> inputStream;
  rv = NS_NewLocalFileInputStream(getter_AddRefs(inputStream), inFile);
  if (NS_FAILED( rv)) return( rv);
  nsCOMPtr <nsIOutputStream> outputStream;
  rv = NS_NewLocalFileOutputStream(getter_AddRefs(outputStream), pDestination, -1, 0600);
  if (NS_FAILED( rv))
    return( rv);

  PRUint32 *  pIndex;
  PRUint32  indexSize;

  if (!ReadIndex( inputStream, &pIndex, &indexSize)) {
    IMPORT_LOG1( "No messages found in mailbox: %S\n", name.get());
    return( NS_OK);
  }

  char *  pBuffer = new char[kMailboxBufferSize];
  if (!(*pAbort))
    ConvertIndex( inputStream, pBuffer, pIndex, indexSize);

  PRUint32  block[4];
  PRInt32   sepLen = (PRInt32) strlen( m_pFromLineSep);
  PRUint32   written;

  /*
      Each block is:
      marker - matches file offset
      block length
      text length in block
      pointer to next block. (0 if end)

      Each message is made up of a linked list of block data.
      So what we do for each message is:
      1. Read the first block data.
      2. Write out the From message separator if the message doesn't already
      start with one.
      3. If the block of data doesn't end with CRLF then a line is broken into two blocks,
      so save the incomplete line for later process when we read the next block. Then
      write out the block excluding the partial line at the end of the block (if exists).
      4. If there's next block of data then read next data block. Otherwise we're done.
      If we found a partial line in step #3 then find the rest of the line from the
      current block and write out this line separately.
      5. Reset some of the control variables and repeat step #3.
  */

  PRUint32  didBytes = 0;
  PRUint32  next, size;
  char *pStart, *pEnd, *partialLineStart;
  nsCAutoString partialLine, tempLine;
  rv = NS_OK;

  for (PRUint32 i = 0; (i < indexSize) && !(*pAbort); i++)
  {
    if (! pIndex[i])
      continue;

    if (ReadBytes( inputStream, block, pIndex[i], 16) && (block[0] == pIndex[i]) &&
      (block[2] < kMailboxBufferSize) && (ReadBytes( inputStream, pBuffer, kDontSeek, block[2])))
    {
      // block[2] contains the chars in the buffer (ie, buf content size).
      // block[3] contains offset to the next block of data (0 means no more data).
      size = block[2];
      pStart = pBuffer;
      pEnd = pStart + size;

      // write out the from separator.
      if (IsFromLine( pBuffer, size))
      {
        char *pChar = pStart;
        while ((pChar < pEnd) && (*pChar != '\r') && (*(pChar+1) != '\n'))
          pChar++;

        if (pChar < pEnd)
        {
          // Get the "From " line so write it out.
          rv = outputStream->Write(pStart, pChar-pStart+2, &written);
          NS_ENSURE_SUCCESS(rv,rv);
          // Now buffer starts from the 2nd line.
          pStart = pChar + 2;
        }
      }
      else
      {
        // Write out the default from line since there is none in the msg.
        rv = outputStream->Write( m_pFromLineSep, sepLen, &written);
        // FIXME: Do I need to check the return value of written???
        if (NS_FAILED( rv))
          break;
      }

      char statusLine[50];
      PRUint32 msgFlags = 0; // need to convert from OE flags to mozilla flags
      PR_snprintf(statusLine, sizeof(statusLine), X_MOZILLA_STATUS_FORMAT MSG_LINEBREAK, msgFlags & 0xFFFF);
      rv = outputStream->Write(statusLine, strlen(statusLine), &written);
      NS_ENSURE_SUCCESS(rv,rv);
      PR_snprintf(statusLine, sizeof(statusLine), X_MOZILLA_STATUS2_FORMAT MSG_LINEBREAK, msgFlags & 0xFFFF0000);
      rv = outputStream->Write(statusLine, strlen(statusLine), &written);
      NS_ENSURE_SUCCESS(rv,rv);

      do
      {
        partialLine.Truncate();
        partialLineStart = pEnd;

        // If the buffer doesn't end with CRLF then a line is broken into two blocks,
        // so save the incomplete line for later process when we read the next block.
        if ( (size > 1) && !(*(pEnd - 2) == '\r' && *(pEnd - 1) == '\n') )
        {
          partialLineStart -= 2;
          while ((partialLineStart >= pStart) && (*partialLineStart != '\r') && (*(partialLineStart+1) != '\n'))
            partialLineStart--;
          if (partialLineStart != (pEnd - 2))
            partialLineStart += 2; // skip over CRLF if we find them.
          partialLine.Assign(partialLineStart, pEnd - partialLineStart);
        }

        // Now process the block of data which ends with CRLF.
        rv = EscapeFromSpaceLine(outputStream, pStart, partialLineStart);
        if (NS_FAILED(rv))
          break;

        didBytes += block[2];

        next = block[3];
        if (! next)
        {
          // OK, we're done so flush out the partial line if it's not empty.
          if (partialLine.Length())
            rv = EscapeFromSpaceLine(outputStream, (char *)partialLine.get(), (partialLine.get()+partialLine.Length()));
        }
        else
          if (ReadBytes(inputStream, block, next, 16) && (block[0] == next) &&
            (block[2] < kMailboxBufferSize) && (ReadBytes(inputStream, pBuffer, kDontSeek, block[2])))
          {
            // See if we have a partial line from previous block. If so then build a complete
            // line (ie, take the remaining chars from this block) and process this line. Need
            // to adjust where data start and size in this case.
            size = block[2];
            pStart = pBuffer;
            pEnd = pStart + size;
            if (partialLine.Length())
            {
              while ((pStart < pEnd) && (*pStart != '\r') && (*(pStart+1) != '\n'))
                pStart++;
              if (pStart < pEnd)  // if we found a CRLF ..
                pStart += 2;      // .. then copy that too.
              tempLine.Assign(pBuffer, pStart - pBuffer);
              partialLine.Append(tempLine);
              rv = EscapeFromSpaceLine(outputStream, (char *)partialLine.get(), (partialLine.get()+partialLine.Length()));
              if (NS_FAILED(rv))
                break;

              // Adjust where data start and size (since some of the data has been processed).
              size -= (pStart - pBuffer);
            }
          }
          else
          {
            IMPORT_LOG2( "Error reading message from %S at 0x%lx\n", name.get(), pIndex[i]);
            rv = outputStream->Write( "\x0D\x0A", 2, &written);
            next = 0;
          }
      } while (next);

      // Always end a msg with CRLF. This will make sure that OE msgs without body is
      // correctly recognized as msgs. Otherwise, we'll end up with the following in
      // the msg folder where the 2nd msg starts right after the headers of the 1st msg:
      //
      // From - Jan 1965 00:00:00     <<<--- 1st msg starts here
      // Subject: Test msg
      // . . . (more headers)
      // To: <*****@*****.**>
      // From - Jan 1965 00:00:00     <<<--- 2nd msg starts here
      // Subject: How are you
      // . . .(more headers)
      //
      // In this case, the 1st msg is not recognized as a msg (it's skipped)
      // when you open the folder.
      rv = outputStream->Write( "\x0D\x0A", 2, &written);

      if (NS_FAILED(rv))
        break;

      msgCount++;
      if (pCount)
        *pCount = msgCount;
      if (pBytesDone)
        *pBytesDone = didBytes;
    }
    else {
      // Error reading message, should this be logged???
      IMPORT_LOG2( "Error reading message from %S at 0x%lx\n", name.get(), pIndex[i]);
      *pAbort = PR_TRUE;
    }
  }

  delete [] pBuffer;

  if (NS_FAILED(rv))
    *pAbort = PR_TRUE;

  return( rv);
}
bool OESettings::DoIMAPServer(nsIMsgAccountManager *aMgr,
                              nsIWindowsRegKey *aKey,
                              const nsString &aServerName,
                              nsIMsgAccount **ppAccount)
{
  if (ppAccount)
    *ppAccount = nullptr;

  nsAutoString userName;
  nsresult rv;
  rv = aKey->ReadStringValue(NS_LITERAL_STRING("IMAP User Name"), userName);
  if (NS_FAILED(rv))
    return false;

  nsAutoCString nativeUserName;
  NS_CopyUnicodeToNative(userName, nativeUserName);
  nsAutoCString nativeServerName;
  NS_CopyUnicodeToNative(aServerName, nativeServerName);
  // I now have a user name/server name pair, find out if it already exists?
  nsCOMPtr<nsIMsgIncomingServer> in;
  rv = aMgr->FindServer(nativeUserName,
                        nativeServerName,
                        NS_LITERAL_CSTRING("imap"),
                        getter_AddRefs(in));
  if (NS_SUCCEEDED(rv)) {
    // for an existing server we create another identity,
    //  TB lists under 'manage identities'
    nsCOMPtr<nsIMsgAccount> account;
    rv = aMgr->FindAccountForServer(in, getter_AddRefs(account));
    if (NS_FAILED(rv))
      return false;

    IMPORT_LOG0("Created an identity and added to existing IMAP incoming server\n");
    // Fiddle with the identities
    int32_t authMethod;
    in->GetAuthMethod(&authMethod);
    SetIdentities(aMgr, account, aKey, userName, authMethod, false);
    if (ppAccount)
      account->QueryInterface(NS_GET_IID(nsIMsgAccount),
                              (void **)ppAccount);
    return true;
  }

  // Create the incoming server and an account for it?
  rv = aMgr->CreateIncomingServer(nativeUserName,
                                  nativeServerName,
                                  NS_LITERAL_CSTRING("imap"),
                                  getter_AddRefs(in));
  NS_ENSURE_SUCCESS(rv, false);

  nsAutoString rootFolder;
  rv = aKey->ReadStringValue(NS_LITERAL_STRING("IMAP Root Folder"), rootFolder);
  if (NS_SUCCEEDED(rv) && !rootFolder.IsEmpty()) {
    nsCOMPtr<nsIImapIncomingServer> imapServer = do_QueryInterface(in);
    nsAutoCString nativeRootFolder;
    NS_CopyUnicodeToNative(rootFolder, nativeRootFolder);
    imapServer->SetServerDirectory(nativeRootFolder);
  }

  SetIncomingServerProperties(in, aKey, NS_LITERAL_STRING("IMAP "));

  IMPORT_LOG2("Created IMAP server named: %s, userName: %s\n",
              nativeServerName.get(), nativeUserName.get());

  nsAutoString prettyName;
  if (NS_SUCCEEDED(GetAccountName(aKey, aServerName, prettyName)))
    rv = in->SetPrettyName(prettyName);

  // We have a server, create an account.
  nsCOMPtr<nsIMsgAccount> account;
  rv = aMgr->CreateAccount(getter_AddRefs(account));
  if (NS_SUCCEEDED(rv) && account) {
    rv = account->SetIncomingServer(in);

    IMPORT_LOG0("Created an account and set the IMAP server as the incoming server\n");

    // Fiddle with the identities
    int32_t authMethod;
    in->GetAuthMethod(&authMethod);
    SetIdentities(aMgr, account, aKey, userName, authMethod, false);
    if (ppAccount)
      account->QueryInterface(NS_GET_IID(nsIMsgAccount), (void **)ppAccount);
    return true;
  }

  return false;
}