Esempio n. 1
0
nsresult
LookupCache::Open()
{
  nsCOMPtr<nsIFile> storeFile;

  nsresult rv = mStoreDirectory->Clone(getter_AddRefs(storeFile));
  NS_ENSURE_SUCCESS(rv, rv);

  rv = storeFile->AppendNative(mTableName + NS_LITERAL_CSTRING(CACHE_SUFFIX));
  NS_ENSURE_SUCCESS(rv, rv);

  nsCOMPtr<nsIInputStream> inputStream;
  rv = NS_NewLocalFileInputStream(getter_AddRefs(inputStream), storeFile,
                                  PR_RDONLY | nsIFile::OS_READAHEAD);

  if (NS_FAILED(rv) && rv != NS_ERROR_FILE_NOT_FOUND) {
    Reset();
    return rv;
  }

  if (rv == NS_ERROR_FILE_NOT_FOUND) {
    // Simply lacking a .cache file is a recoverable error,
    // as unlike the .pset/.sbstore files it is a pure cache.
    // Just create a new empty one.
    ClearCompleteCache();
  } else {
    // Read in the .cache file
    rv = ReadHeader(inputStream);
    NS_ENSURE_SUCCESS(rv, rv);
    LOG(("ReadCompletions"));
    rv = ReadCompletions(inputStream);
    NS_ENSURE_SUCCESS(rv, rv);

    rv = inputStream->Close();
    NS_ENSURE_SUCCESS(rv, rv);
  }

  LOG(("Loading PrefixSet"));
  rv = LoadPrefixSet();
  NS_ENSURE_SUCCESS(rv, rv);

  return NS_OK;
}
Esempio n. 2
0
void
FileBlobImpl::GetInternalStream(nsIInputStream** aStream, ErrorResult& aRv)
{
  nsCOMPtr<nsIInputStream> stream;
  aRv = NS_NewLocalFileInputStream(getter_AddRefs(stream), mFile, -1, -1,
                                   sFileStreamFlags);
  if (NS_WARN_IF(aRv.Failed())) {
    return;
  }

  if (mWholeFile) {
    stream.forget(aStream);
    return;
  }

  RefPtr<SlicedInputStream> slicedInputStream =
    new SlicedInputStream(stream, mStart, mLength);
  slicedInputStream.forget(aStream);
}
Esempio n. 3
0
already_AddRefed<nsISupports>
DOMFileHandle::CreateStream(nsIFile* aFile, bool aReadOnly)
{
  nsresult rv;

  if (aReadOnly) {
    nsCOMPtr<nsIInputStream> stream;
    rv = NS_NewLocalFileInputStream(getter_AddRefs(stream), aFile, -1, -1,
                                    nsIFileInputStream::DEFER_OPEN);
    NS_ENSURE_SUCCESS(rv, nullptr);
    return stream.forget();
  }

  nsCOMPtr<nsIFileStream> stream;
  rv = NS_NewLocalFileStream(getter_AddRefs(stream), aFile, -1, -1,
                             nsIFileStream::DEFER_OPEN);
  NS_ENSURE_SUCCESS(rv, nullptr);
  return stream.forget();
}
NS_IMETHODIMP
nsMsgMaildirStore::GetMsgInputStream(nsIMsgFolder *aMsgFolder,
                                     const nsACString &aMsgToken,
                                     int64_t *aOffset,
                                     nsIMsgDBHdr *aMsgHdr,
                                     bool *aReusable,
                                     nsIInputStream **aResult)
{
  NS_ENSURE_ARG_POINTER(aMsgFolder);
  NS_ENSURE_ARG_POINTER(aOffset);
  NS_ENSURE_ARG_POINTER(aResult);

  *aReusable = false; // message per file
  *aOffset = 0;

  // construct path to file
  nsCOMPtr<nsIFile> path;
  nsresult rv = aMsgFolder->GetFilePath(getter_AddRefs(path));
  NS_ENSURE_SUCCESS(rv, rv);

  if (aMsgToken.IsEmpty())
  {
    PR_LOG(MailDirLog, PR_LOG_ALWAYS,
           ("GetMsgInputStream - empty storeToken!!\n"));
    return NS_ERROR_FAILURE;
  }

  path->Append(NS_LITERAL_STRING("cur"));
  path->AppendNative(aMsgToken);

  // let's check if the folder exists
  bool exists;
  path->Exists(&exists);
  if (!exists) {
    PR_LOG(MailDirLog, PR_LOG_ALWAYS,
           ("GetMsgInputStream - oops! cur subfolder does not exist!\n"));
    rv = path->Create(nsIFile::DIRECTORY_TYPE, 0755);
    NS_ENSURE_SUCCESS(rv, rv);
  }

  return NS_NewLocalFileInputStream(aResult, path);
}
/**
 * asynchronously copy file.
 */
static nsresult
RunTest(nsIFile *srcFile, nsIFile *destFile)
{
    nsresult rv;

    LOG(("RunTest\n"));

    nsCOMPtr<nsIStreamTransportService> sts =
        do_GetService(kStreamTransportServiceCID, &rv);
    if (NS_FAILED(rv)) return rv;

    nsCOMPtr<nsIInputStream> srcStr;
    rv = NS_NewLocalFileInputStream(getter_AddRefs(srcStr), srcFile);
    if (NS_FAILED(rv)) return rv;

    nsCOMPtr<nsIOutputStream> destStr;
    rv = NS_NewLocalFileOutputStream(getter_AddRefs(destStr), destFile);
    if (NS_FAILED(rv)) return rv;

    nsCOMPtr<nsITransport> srcTransport;
    rv = sts->CreateInputTransport(srcStr, PRInt64(-1), PRInt64(-1), PR_TRUE,
                                   getter_AddRefs(srcTransport));
    if (NS_FAILED(rv)) return rv;

    nsCOMPtr<nsITransport> destTransport;
    rv = sts->CreateOutputTransport(destStr, PRInt64(-1), PRInt64(-1), PR_TRUE,
                                    getter_AddRefs(destTransport));
    if (NS_FAILED(rv)) return rv;

    MyCopier *copier = new MyCopier();
    if (copier == nsnull)
        return NS_ERROR_OUT_OF_MEMORY;
    NS_ADDREF(copier);

    rv = copier->AsyncCopy(srcTransport, destTransport);
    if (NS_FAILED(rv)) return rv;

    PumpEvents();

    NS_RELEASE(copier);
    return NS_OK;
}
nsresult
VariableLengthPrefixSet::LoadFromFile(nsIFile* aFile)
{
  MutexAutoLock lock(mLock);

  NS_ENSURE_ARG_POINTER(aFile);

  Telemetry::AutoTimer<Telemetry::URLCLASSIFIER_VLPS_FILELOAD_TIME> timer;

  nsCOMPtr<nsIInputStream> localInFile;
  nsresult rv = NS_NewLocalFileInputStream(getter_AddRefs(localInFile), aFile,
                                           PR_RDONLY | nsIFile::OS_READAHEAD);
  NS_ENSURE_SUCCESS(rv, rv);

  // Calculate how big the file is, make sure our read buffer isn't bigger
  // than the file itself which is just wasting memory.
  int64_t fileSize;
  rv = aFile->GetFileSize(&fileSize);
  NS_ENSURE_SUCCESS(rv, rv);

  if (fileSize < 0 || fileSize > UINT32_MAX) {
    return NS_ERROR_FAILURE;
  }

  uint32_t bufferSize = std::min<uint32_t>(static_cast<uint32_t>(fileSize),
                                           MAX_BUFFER_SIZE);

  // Convert to buffered stream
  nsCOMPtr<nsIInputStream> in;
  rv = NS_NewBufferedInputStream(getter_AddRefs(in), localInFile.forget(),
                                 bufferSize);
  NS_ENSURE_SUCCESS(rv, rv);

  rv = mFixedPrefixSet->LoadPrefixes(in);
  NS_ENSURE_SUCCESS(rv, rv);

  rv = LoadPrefixes(in);
  NS_ENSURE_SUCCESS(rv, rv);

  return NS_OK;;
}
Esempio n. 7
0
/**
 * asynchronously copy file.
 */
static nsresult
RunTest(nsIFile *file, int64_t offset, int64_t length)
{
    nsresult rv;

    LOG(("RunTest\n"));

    nsCOMPtr<nsIInputStream> stream;
    rv = NS_NewLocalFileInputStream(getter_AddRefs(stream), file);
    if (NS_FAILED(rv)) return rv;

    nsCOMPtr<nsIInputStreamPump> pump;
    rv = NS_NewInputStreamPump(getter_AddRefs(pump), stream, offset, length);
    if (NS_FAILED(rv)) return rv;

    rv = pump->AsyncRead(new MyListener(), nullptr);
    if (NS_FAILED(rv)) return rv;

    PumpEvents();
    return NS_OK;
}
Esempio n. 8
0
nsresult
nsFileChannel::MakeFileInputStream(nsIFile *file,
                                   nsCOMPtr<nsIInputStream> &stream,
                                   nsCString &contentType,
                                   bool async)
{
  // we accept that this might result in a disk hit to stat the file
  bool isDir;
  nsresult rv = file->IsDirectory(&isDir);
  if (NS_FAILED(rv)) {
    // canonicalize error message
    if (rv == NS_ERROR_FILE_TARGET_DOES_NOT_EXIST)
      rv = NS_ERROR_FILE_NOT_FOUND;

    if (async && (NS_ERROR_FILE_NOT_FOUND == rv)) {
      // We don't return "Not Found" errors here. Since we could not find
      // the file, it's not a directory anyway.
      isDir = false;
    } else {
      return rv;
    }
  }

  if (isDir) {
    rv = nsDirectoryIndexStream::Create(file, getter_AddRefs(stream));
    if (NS_SUCCEEDED(rv) && !HasContentTypeHint())
      contentType.AssignLiteral(APPLICATION_HTTP_INDEX_FORMAT);
  } else {
    rv = NS_NewLocalFileInputStream(getter_AddRefs(stream), file, -1, -1,
                                    async? nsIFileInputStream::DEFER_OPEN : 0);
    if (NS_SUCCEEDED(rv) && !HasContentTypeHint()) {
      // Use file extension to infer content type
      nsCOMPtr<nsIMIMEService> mime = do_GetService("@mozilla.org/mime;1", &rv);
      if (NS_SUCCEEDED(rv)) {
        mime->GetTypeFromFile(file, contentType);
      }
    }
  }
  return rv;
}
Esempio n. 9
0
nsresult nsTextAddress::ReadRecordNumber(nsIFile *aSrc, nsCString &aLine, PRInt32 rNum)
{
  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;
  }

  PRInt32 rIndex = 0;
  PRUint32 bytesLeft = 0;

  rv = inputStream->Available(&bytesLeft);
  if (NS_FAILED(rv)) {
    IMPORT_LOG0( "*** Error checking address file for eof\n");
    inputStream->Close();
    return rv;
  }

  nsCOMPtr<nsILineInputStream> lineStream(do_QueryInterface(inputStream, &rv));
  NS_ENSURE_SUCCESS(rv, rv);

  bool more = true;

  while (more && (rIndex <= rNum)) {
    rv = ReadRecord(lineStream, aLine, &more);
    if (NS_FAILED(rv)) {
      inputStream->Close();
      return rv;
    }
    if (rIndex == rNum) {
      inputStream->Close();
      return NS_OK;
    }

    rIndex++;
  }

  return NS_ERROR_FAILURE;
}
static nsresult
RunBlockingTest(nsIFile *srcFile, nsIFile *destFile)
{
    nsresult rv;

    LOG(("RunBlockingTest\n"));

    nsCOMPtr<nsIStreamTransportService> sts =
        do_GetService(kStreamTransportServiceCID, &rv);
    if (NS_FAILED(rv)) return rv;

    nsCOMPtr<nsIInputStream> srcIn;
    rv = NS_NewLocalFileInputStream(getter_AddRefs(srcIn), srcFile);
    if (NS_FAILED(rv)) return rv;

    nsCOMPtr<nsIOutputStream> fileOut;
    rv = NS_NewLocalFileOutputStream(getter_AddRefs(fileOut), destFile);
    if (NS_FAILED(rv)) return rv;
    
    nsCOMPtr<nsITransport> destTransport;
    rv = sts->CreateOutputTransport(fileOut, PRInt64(-1), PRInt64(-1),
                                    PR_TRUE, getter_AddRefs(destTransport));
    if (NS_FAILED(rv)) return rv;

    nsCOMPtr<nsIOutputStream> destOut;
    rv = destTransport->OpenOutputStream(nsITransport::OPEN_BLOCKING, 100, 10, getter_AddRefs(destOut));
    if (NS_FAILED(rv)) return rv;

    char buf[120];
    PRUint32 n;
    for (;;) {
        rv = srcIn->Read(buf, sizeof(buf), &n);
        if (NS_FAILED(rv) || (n == 0)) return rv;

        rv = destOut->Write(buf, n, &n);
        if (NS_FAILED(rv)) return rv;
    }

    return NS_OK;
}
Esempio n. 11
0
void nsBrowserListener::GetProperty(nsIPersistentProperties **prop,nsACString &fileName)
{
  nsresult rv;
  nsCOMPtr<nsIPersistentProperties> tmpprop=do_CreateInstance("@mozilla.org/persistent-properties;1", &rv);
  if (NS_FAILED(rv)) 
    {
      LOG<<"Get properties Error:"<<rv<<"\n";
    }
  nsCOMPtr<nsILocalFile> file;
  rv = NS_NewLocalFile(NS_ConvertUTF8toUTF16(fileName), PR_FALSE,
				   getter_AddRefs(file));
  if (NS_FAILED(rv))
    return ;
  nsCOMPtr<nsIInputStream> fistream;
  rv=NS_NewLocalFileInputStream(getter_AddRefs(fistream), file);
  if (NS_FAILED(rv)) 
    {
      return ; 
    }
  tmpprop->Load(fistream);
  *prop=tmpprop;
  NS_ADDREF(*prop);
}
Esempio n. 12
0
// virtual
already_AddRefed<nsISupports>
FileHandle::CreateStream(nsIFile* aFile, bool aReadOnly)
{
  nsresult rv;

  if (aReadOnly) {
    nsCOMPtr<nsIInputStream> stream;
    rv = NS_NewLocalFileInputStream(getter_AddRefs(stream), aFile, -1, -1,
                                    nsIFileInputStream::DEFER_OPEN);
    if (NS_WARN_IF(NS_FAILED(rv))) {
      return nullptr;
    }
    return stream.forget();
  }

  nsCOMPtr<nsIFileStream> stream;
  rv = NS_NewLocalFileStream(getter_AddRefs(stream), aFile, -1, -1,
                             nsIFileStream::DEFER_OPEN);
  if (NS_WARN_IF(NS_FAILED(rv))) {
    return nullptr;
  }
  return stream.forget();
}
Esempio n. 13
0
nsresult
FileMediaResource::Open(nsIStreamListener** aStreamListener)
{
  NS_ASSERTION(NS_IsMainThread(), "Only call on main thread");
  MOZ_ASSERT(aStreamListener);

  *aStreamListener = nullptr;
  nsresult rv = NS_OK;

  // The channel is already open. We need a synchronous stream that
  // implements nsISeekableStream, so we have to find the underlying
  // file and reopen it
  nsCOMPtr<nsIFileChannel> fc(do_QueryInterface(mChannel));
  if (fc) {
    nsCOMPtr<nsIFile> file;
    rv = fc->GetFile(getter_AddRefs(file));
    NS_ENSURE_SUCCESS(rv, rv);

    rv = NS_NewLocalFileInputStream(
      getter_AddRefs(mInput), file, -1, -1, nsIFileInputStream::SHARE_DELETE);
  } else if (IsBlobURI(mURI)) {
    rv = NS_GetStreamForBlobURI(mURI, getter_AddRefs(mInput));
  }

  NS_ENSURE_SUCCESS(rv, rv);

  mSeekable = do_QueryInterface(mInput);
  if (!mSeekable) {
    // XXX The file may just be a .url or similar
    // shortcut that points to a Web site. We need to fix this by
    // doing an async open and waiting until we locate the real resource,
    // then using that (if it's still a file!).
    return NS_ERROR_FAILURE;
  }

  return NS_OK;
}
Esempio n. 14
0
    NS_IMETHOD Run() {
        nsresult rv;

        PRIntervalTime startTime = PR_IntervalNow();
        PRIntervalTime endTime;
        nsCOMPtr<nsIInputStream> inStr;
        nsCOMPtr<nsIOutputStream> outStr;
        PRUint32 copyCount = 0;

        // Open the input stream:
        nsCOMPtr<nsIInputStream> fileIn;
        rv = NS_NewLocalFileInputStream(getter_AddRefs(fileIn), mInPath);
        if (NS_FAILED(rv)) return rv;

        rv = NS_NewBufferedInputStream(getter_AddRefs(inStr), fileIn, 65535);
        if (NS_FAILED(rv)) return rv;

        // Open the output stream:
        nsCOMPtr<nsIOutputStream> fileOut;
        rv = NS_NewLocalFileOutputStream(getter_AddRefs(fileOut),
                                         mOutPath, 
                                         PR_CREATE_FILE | PR_WRONLY | PR_TRUNCATE,
                                         0664);
        if (NS_FAILED(rv)) return rv;

        rv = NS_NewBufferedOutputStream(getter_AddRefs(outStr), fileOut, 65535);
        if (NS_FAILED(rv)) return rv;

        // Copy from one to the other
        rv = Copy(inStr, outStr, mBuffer, mBufferSize, &copyCount);
        if (NS_FAILED(rv)) return rv;

        endTime = PR_IntervalNow();
        gTimeSampler.AddTime(endTime - startTime);

        return rv;
    }
Esempio n. 15
0
// inputToDecoder
//
// Given a decoder, read bytes from file and input them to the decoder.
nsresult
nsPKCS12Blob::inputToDecoder(SEC_PKCS12DecoderContext *dcx, nsILocalFile *file)
{
  nsNSSShutDownPreventionLock locker;
  nsresult rv;
  SECStatus srv;
  PRUint32 amount;
  char buf[PIP_PKCS12_BUFFER_SIZE];

  nsCOMPtr<nsIInputStream> fileStream;
  rv = NS_NewLocalFileInputStream(getter_AddRefs(fileStream), file);
  
  if (NS_FAILED(rv)) {
    return rv;
  }

  while (true) {
    rv = fileStream->Read(buf, PIP_PKCS12_BUFFER_SIZE, &amount);
    if (NS_FAILED(rv)) {
      return rv;
    }
    // feed the file data into the decoder
    srv = SEC_PKCS12DecoderUpdate(dcx, 
				  (unsigned char*) buf, 
				  amount);
    if (srv) {
      // don't allow the close call to overwrite our precious error code
      int pr_err = PORT_GetError();
      PORT_SetError(pr_err);
      return NS_ERROR_ABORT;
    }
    if (amount < PIP_PKCS12_BUFFER_SIZE)
      break;
  }
  return NS_OK;
}
nsresult
nsMsgAttachmentHandler::LoadDataFromFile(nsILocalFile *file, nsString &sigData, bool charsetConversion)
{
  PRInt32       readSize;
  char          *readBuf;

  nsCOMPtr <nsIInputStream> inputFile;
  nsresult rv = NS_NewLocalFileInputStream(getter_AddRefs(inputFile), file);
  if (NS_FAILED(rv))
    return NS_MSG_ERROR_WRITING_FILE;

  PRInt64 fileSize;
  file->GetFileSize(&fileSize);
  readSize = (PRUint32) fileSize;

  readBuf = (char *)PR_Malloc(readSize + 1);
  if (!readBuf)
    return NS_ERROR_OUT_OF_MEMORY;
  memset(readBuf, 0, readSize + 1);

  PRUint32 bytesRead;
  inputFile->Read(readBuf, readSize, &bytesRead);
  inputFile->Close();

  nsDependentCString cstringReadBuf(readBuf, bytesRead);
  if (charsetConversion)
  {
    if (NS_FAILED(ConvertToUnicode(m_charset.get(), cstringReadBuf, sigData)))
      CopyASCIItoUTF16(cstringReadBuf, sigData);
  }
  else
    CopyASCIItoUTF16(cstringReadBuf, sigData);

  PR_FREEIF(readBuf);
  return NS_OK;
}
Esempio n. 17
0
nsresult nsReadConfig::openAndEvaluateJSFile(const char *aFileName, PRInt32 obscureValue,
                                             bool isEncoded,
                                             bool isBinDir)
{
    nsresult rv;

    nsCOMPtr<nsIInputStream> inStr;
    if (isBinDir) {
        nsCOMPtr<nsIFile> jsFile;
        rv = NS_GetSpecialDirectory(NS_XPCOM_CURRENT_PROCESS_DIR, 
                                    getter_AddRefs(jsFile));
        if (NS_FAILED(rv)) 
            return rv;

        rv = jsFile->AppendNative(nsDependentCString(aFileName));
        if (NS_FAILED(rv)) 
            return rv;

        rv = NS_NewLocalFileInputStream(getter_AddRefs(inStr), jsFile);
        if (NS_FAILED(rv)) 
            return rv;

    } else {
        nsCOMPtr<nsIIOService> ioService = do_GetIOService(&rv);
        if (NS_FAILED(rv)) 
            return rv;

        nsCAutoString location("resource://gre/defaults/autoconfig/");
        location += aFileName;

        nsCOMPtr<nsIURI> uri;
        rv = ioService->NewURI(location, nsnull, nsnull, getter_AddRefs(uri));
        if (NS_FAILED(rv))
            return rv;

        nsCOMPtr<nsIChannel> channel;
        rv = ioService->NewChannelFromURI(uri, getter_AddRefs(channel));
        if (NS_FAILED(rv))
            return rv;

        rv = channel->Open(getter_AddRefs(inStr));
        if (NS_FAILED(rv)) 
            return rv;
    }

    PRUint32 fs, amt = 0;
    inStr->Available(&fs);

    char *buf = (char *)PR_Malloc(fs * sizeof(char));
    if (!buf) 
        return NS_ERROR_OUT_OF_MEMORY;

    rv = inStr->Read(buf, fs, &amt);
    NS_ASSERTION((amt == fs), "failed to read the entire configuration file!!");
    if (NS_SUCCEEDED(rv)) {
        if (obscureValue > 0) {

            // Unobscure file by subtracting some value from every char. 
            for (PRUint32 i = 0; i < amt; i++)
                buf[i] -= obscureValue;
        }
        rv = EvaluateAdminConfigScript(buf, amt, aFileName,
                                       false, true,
                                       isEncoded ? true:false);
    }
    inStr->Close();
    PR_Free(buf);
    
    return rv;
}
Esempio n. 18
0
nsresult nsTextAddress::ImportAddresses(bool *pAbort, const PRUnichar *pName, nsIFile *pSrc, nsIAddrDatabase *pDb, nsIImportFieldMap *fieldMap, nsString& errors, PRUint32 *pProgress)
{
  // Open the source file for reading, read each line and process it!
  NS_IF_RELEASE(m_database);
  NS_IF_RELEASE(m_fieldMap);
  m_database = pDb;
  m_fieldMap = fieldMap;
  NS_ADDREF(m_fieldMap);
  NS_ADDREF(m_database);

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

  // Here we use this to work out the size of the file, so we can update
  // an integer as we go through the file which will update a progress
  // bar if required by the caller.
  PRUint32 bytesLeft = 0;
  rv = inputStream->Available(&bytesLeft);
  if (NS_FAILED(rv)) {
    IMPORT_LOG0( "*** Error checking address file for size\n");
    inputStream->Close();
    return rv;
  }

  PRUint32 totalBytes = bytesLeft;
  bool skipRecord = false;

  rv = m_fieldMap->GetSkipFirstRecord(&skipRecord);
  if (NS_FAILED(rv)) {
    IMPORT_LOG0("*** Error checking to see if we should skip the first record\n");
    return rv;
  }

  nsCOMPtr<nsILineInputStream> lineStream(do_QueryInterface(inputStream, &rv));
  NS_ENSURE_SUCCESS(rv, rv);

  bool more = true;
  nsCString line;

  // Skip the first record if the user has requested it.
  if (skipRecord)
    rv = ReadRecord(lineStream, line, &more);

  while (!(*pAbort) && more && NS_SUCCEEDED( rv)) {
    // Read the line in
    rv = ReadRecord(lineStream, line, &more);
    if (NS_SUCCEEDED(rv)) {
      // Now proces it to add it to the database
      rv = ProcessLine(line.get(), line.Length(), errors);

      if (NS_FAILED(rv)) {
        IMPORT_LOG0( "*** Error processing text record.\n");
      }
    }
    if (NS_SUCCEEDED(rv) && pProgress) {
      // This won't be totally accurate, but its the best we can do
      // considering that lineStream won't give us how many bytes
      // are actually left.
      bytesLeft -= line.Length();
      *pProgress = totalBytes - bytesLeft;
    }
  }

  inputStream->Close();

  if (NS_FAILED(rv)) {
    IMPORT_LOG0( "*** Error reading the address book - probably incorrect ending\n");
    return NS_ERROR_FAILURE;
  }

  return pDb->Commit(nsAddrDBCommitType::kLargeCommit);
}
Esempio n. 19
0
nsresult
AppTrustDomain::SetTrustedRoot(AppTrustedRoot trustedRoot)
{
  SECItem trustedDER;

  // Load the trusted certificate into the in-memory NSS database so that
  // CERT_CreateSubjectCertList can find it.

  switch (trustedRoot)
  {
    case nsIX509CertDB::AppMarketplaceProdPublicRoot:
      trustedDER.data = const_cast<uint8_t*>(marketplaceProdPublicRoot);
      trustedDER.len = mozilla::ArrayLength(marketplaceProdPublicRoot);
      break;

    case nsIX509CertDB::AppMarketplaceProdReviewersRoot:
      trustedDER.data = const_cast<uint8_t*>(marketplaceProdReviewersRoot);
      trustedDER.len = mozilla::ArrayLength(marketplaceProdReviewersRoot);
      break;

    case nsIX509CertDB::AppMarketplaceDevPublicRoot:
      trustedDER.data = const_cast<uint8_t*>(marketplaceDevPublicRoot);
      trustedDER.len = mozilla::ArrayLength(marketplaceDevPublicRoot);
      break;

    case nsIX509CertDB::AppMarketplaceDevReviewersRoot:
      trustedDER.data = const_cast<uint8_t*>(marketplaceDevReviewersRoot);
      trustedDER.len = mozilla::ArrayLength(marketplaceDevReviewersRoot);
      break;

    case nsIX509CertDB::AppMarketplaceStageRoot:
      trustedDER.data = const_cast<uint8_t*>(marketplaceStageRoot);
      trustedDER.len = mozilla::ArrayLength(marketplaceStageRoot);
      // The staging root was generated with a 1024-bit key.
      mMinRSABits = 1024u;
      break;

    case nsIX509CertDB::AppXPCShellRoot:
      trustedDER.data = const_cast<uint8_t*>(xpcshellRoot);
      trustedDER.len = mozilla::ArrayLength(xpcshellRoot);
      break;

    case nsIX509CertDB::AddonsPublicRoot:
      trustedDER.data = const_cast<uint8_t*>(addonsPublicRoot);
      trustedDER.len = mozilla::ArrayLength(addonsPublicRoot);
      break;

    case nsIX509CertDB::AddonsStageRoot:
      trustedDER.data = const_cast<uint8_t*>(addonsStageRoot);
      trustedDER.len = mozilla::ArrayLength(addonsStageRoot);
      break;

    case nsIX509CertDB::PrivilegedPackageRoot:
      trustedDER.data = const_cast<uint8_t*>(privilegedPackageRoot);
      trustedDER.len = mozilla::ArrayLength(privilegedPackageRoot);
      break;

    case nsIX509CertDB::DeveloperImportedRoot: {
      StaticMutexAutoLock lock(sMutex);
      if (!sDevImportedDERData) {
        MOZ_ASSERT(!NS_IsMainThread());
        nsCOMPtr<nsIFile> file(do_CreateInstance("@mozilla.org/file/local;1"));
        if (!file) {
          return NS_ERROR_FAILURE;
        }
        nsresult rv = file->InitWithNativePath(
          Preferences::GetCString(kDevImportedDER));
        if (NS_FAILED(rv)) {
          return rv;
        }

        nsCOMPtr<nsIInputStream> inputStream;
        rv = NS_NewLocalFileInputStream(getter_AddRefs(inputStream), file, -1,
                                        -1, nsIFileInputStream::CLOSE_ON_EOF);
        if (NS_FAILED(rv)) {
          return rv;
        }

        uint64_t length;
        rv = inputStream->Available(&length);
        if (NS_FAILED(rv)) {
          return rv;
        }

        auto data = MakeUnique<char[]>(length);
        rv = inputStream->Read(data.get(), length, &sDevImportedDERLen);
        if (NS_FAILED(rv)) {
          return rv;
        }

        MOZ_ASSERT(length == sDevImportedDERLen);
        sDevImportedDERData.reset(
          BitwiseCast<unsigned char*, char*>(data.release()));
      }

      trustedDER.data = sDevImportedDERData.get();
      trustedDER.len = sDevImportedDERLen;
      break;
    }

    default:
      return NS_ERROR_INVALID_ARG;
  }

  mTrustedRoot.reset(CERT_NewTempCertificate(CERT_GetDefaultCertDB(),
                                             &trustedDER, nullptr, false, true));
  if (!mTrustedRoot) {
    return mozilla::psm::GetXPCOMFromNSSError(PR_GetError());
  }

  return NS_OK;
}
static void
loadTestEVInfos()
{
  if (!testEVInfos)
    return;

  testEVInfos->Clear();

  char *env_val = getenv("ENABLE_TEST_EV_ROOTS_FILE");
  if (!env_val)
    return;
    
  int enabled_val = atoi(env_val);
  if (!enabled_val)
    return;

  nsCOMPtr<nsIFile> aFile;
  NS_GetSpecialDirectory(NS_APP_USER_PROFILE_50_DIR, getter_AddRefs(aFile));
  if (!aFile)
    return;

  aFile->AppendNative(NS_LITERAL_CSTRING(kTestEVRootsFileName));

  nsresult rv;
  nsCOMPtr<nsIInputStream> fileInputStream;
  rv = NS_NewLocalFileInputStream(getter_AddRefs(fileInputStream), aFile);
  if (NS_FAILED(rv))
    return;

  nsCOMPtr<nsILineInputStream> lineInputStream = do_QueryInterface(fileInputStream, &rv);
  if (NS_FAILED(rv))
    return;

  nsCAutoString buffer;
  PRBool isMore = PR_TRUE;

  /* file format
   *
   * file format must be strictly followed
   * strings in file must be UTF-8
   * each record consists of multiple lines
   * each line consists of a descriptor, a single space, and the data
   * the descriptors are:
   *   1_fingerprint (in format XX:XX:XX:...)
   *   2_readable_oid (treated as a comment)
   * the input file must strictly follow this order
   * the input file may contain 0, 1 or many records
   * completely empty lines are ignored
   * lines that start with the # char are ignored
   */

  int line_counter = 0;
  PRBool found_error = PR_FALSE;

  enum { 
    pos_fingerprint, pos_readable_oid, pos_issuer, pos_serial
  } reader_position = pos_fingerprint;

  nsCString fingerprint, readable_oid, issuer, serial;

  while (isMore && NS_SUCCEEDED(lineInputStream->ReadLine(buffer, &isMore))) {
    ++line_counter;
    if (buffer.IsEmpty() || buffer.First() == '#') {
      continue;
    }

    PRInt32 seperatorIndex = buffer.FindChar(' ', 0);
    if (seperatorIndex == 0) {
      found_error = PR_TRUE;
      break;
    }

    const nsASingleFragmentCString &descriptor = Substring(buffer, 0, seperatorIndex);
    const nsASingleFragmentCString &data = 
            Substring(buffer, seperatorIndex + 1, 
                      buffer.Length() - seperatorIndex + 1);

    if (reader_position == pos_fingerprint &&
        descriptor.EqualsLiteral(("1_fingerprint"))) {
      fingerprint = data;
      reader_position = pos_readable_oid;
      continue;
    }
    else if (reader_position == pos_readable_oid &&
        descriptor.EqualsLiteral(("2_readable_oid"))) {
      readable_oid = data;
      reader_position = pos_issuer;
      continue;
    }
    else if (reader_position == pos_issuer &&
        descriptor.EqualsLiteral(("3_issuer"))) {
      issuer = data;
      reader_position = pos_serial;
      continue;
    }
    else if (reader_position == pos_serial &&
        descriptor.EqualsLiteral(("4_serial"))) {
      serial = data;
      reader_position = pos_fingerprint;
    }
    else {
      found_error = PR_TRUE;
      break;
    }

    nsMyTrustedEVInfoClass *temp_ev = new nsMyTrustedEVInfoClass;
    if (!temp_ev)
      return;

    temp_ev->ev_root_sha1_fingerprint = strdup(fingerprint.get());
    temp_ev->oid_name = strdup(readable_oid.get());
    temp_ev->dotted_oid = strdup(readable_oid.get());
    temp_ev->issuer_base64 = strdup(issuer.get());
    temp_ev->serial_base64 = strdup(serial.get());

    SECStatus rv;
    CERTIssuerAndSN ias;

    rv = ATOB_ConvertAsciiToItem(&ias.derIssuer, const_cast<char*>(temp_ev->issuer_base64));
    NS_ASSERTION(rv==SECSuccess, "error converting ascii to binary.");
    rv = ATOB_ConvertAsciiToItem(&ias.serialNumber, const_cast<char*>(temp_ev->serial_base64));
    NS_ASSERTION(rv==SECSuccess, "error converting ascii to binary.");

    temp_ev->cert = CERT_FindCertByIssuerAndSN(nsnull, &ias);
    NS_ASSERTION(temp_ev->cert, "Could not find EV root in NSS storage");

    if (!temp_ev->cert)
      return;

    nsNSSCertificate c(temp_ev->cert);
    nsAutoString fingerprint;
    c.GetSha1Fingerprint(fingerprint);

    NS_ConvertASCIItoUTF16 sha1(temp_ev->ev_root_sha1_fingerprint);

    if (sha1 != fingerprint) {
      NS_ASSERTION(sha1 == fingerprint, "found EV root with unexpected SHA1 mismatch");
      CERT_DestroyCertificate(temp_ev->cert);
      temp_ev->cert = nsnull;
      return;
    }

    SECItem ev_oid_item;
    ev_oid_item.data = nsnull;
    ev_oid_item.len = 0;
    SECStatus srv = SEC_StringToOID(nsnull, &ev_oid_item,
                                    readable_oid.get(), readable_oid.Length());
    if (srv != SECSuccess) {
      delete temp_ev;
      found_error = PR_TRUE;
      break;
    }

    temp_ev->oid_tag = register_oid(&ev_oid_item, temp_ev->oid_name);
    SECITEM_FreeItem(&ev_oid_item, PR_FALSE);

    testEVInfos->AppendElement(temp_ev);
  }

  if (found_error) {
    fprintf(stderr, "invalid line %d in test_ev_roots file\n", line_counter);
  }
}
Esempio n. 21
0
NS_IMETHODIMP
nsAboutBloat::NewChannel(nsIURI *aURI, nsIChannel **result)
{
    NS_ENSURE_ARG_POINTER(aURI);
    nsresult rv;
    nsAutoCString path;
    rv = aURI->GetPath(path);
    if (NS_FAILED(rv)) return rv;

    nsTraceRefcntImpl::StatisticsType statType = nsTraceRefcntImpl::ALL_STATS;
    bool clear = false;
    bool leaks = false;

    int32_t pos = path.Find("?");
    if (pos > 0) {
        nsAutoCString param;
        (void)path.Right(param, path.Length() - (pos+1));
        if (param.EqualsLiteral("new"))
            statType = nsTraceRefcntImpl::NEW_STATS;
        else if (param.EqualsLiteral("clear"))
            clear = true;
        else if (param.EqualsLiteral("leaks"))
            leaks = true;
    }

    nsCOMPtr<nsIInputStream> inStr;
    if (clear) {
        nsTraceRefcntImpl::ResetStatistics();

        rv = NS_NewCStringInputStream(getter_AddRefs(inStr),
            NS_LITERAL_CSTRING("Bloat statistics cleared."));
        if (NS_FAILED(rv)) return rv;
    }
    else if (leaks) {
        // dump the current set of leaks.
        GC_gcollect();
    	
        rv = NS_NewCStringInputStream(getter_AddRefs(inStr),
            NS_LITERAL_CSTRING("Memory leaks dumped."));
        if (NS_FAILED(rv)) return rv;
    }
    else {
        nsCOMPtr<nsIFile> file;
        rv = NS_GetSpecialDirectory(NS_OS_CURRENT_PROCESS_DIR, 
                                    getter_AddRefs(file));       
        if (NS_FAILED(rv)) return rv;

        rv = file->AppendNative(NS_LITERAL_CSTRING("bloatlogs"));
        if (NS_FAILED(rv)) return rv;

        bool exists;
        rv = file->Exists(&exists);
        if (NS_FAILED(rv)) return rv;

        if (!exists) {
            // On all the platforms that I know use permissions,
            // directories need to have the executable flag set
            // if you want to do anything inside the directory.
            rv = file->Create(nsIFile::DIRECTORY_TYPE, 0755);
            if (NS_FAILED(rv)) return rv;
        }

        nsAutoCString dumpFileName;
        if (statType == nsTraceRefcntImpl::ALL_STATS)
            dumpFileName.AssignLiteral("all-");
        else
            dumpFileName.AssignLiteral("new-");
        PRExplodedTime expTime;
        PR_ExplodeTime(PR_Now(), PR_LocalTimeParameters, &expTime);
        char time[128];
        PR_FormatTimeUSEnglish(time, 128, "%Y-%m-%d-%H%M%S.txt", &expTime);
        dumpFileName += time;
        rv = file->AppendNative(dumpFileName);
        if (NS_FAILED(rv)) return rv;

        FILE* out;
        rv = file->OpenANSIFileDesc("w", &out);
        if (NS_FAILED(rv)) return rv;

        rv = nsTraceRefcntImpl::DumpStatistics(statType, out);
        ::fclose(out);
        if (NS_FAILED(rv)) return rv;

        rv = NS_NewLocalFileInputStream(getter_AddRefs(inStr), file);
        if (NS_FAILED(rv)) return rv;
    }

    nsIChannel* channel;
    rv = NS_NewInputStreamChannel(&channel, aURI, inStr,
                                  NS_LITERAL_CSTRING("text/plain"),
                                  NS_LITERAL_CSTRING("utf-8"));
    if (NS_FAILED(rv)) return rv;

    *result = channel;
    return rv;
}
Esempio n. 22
0
// Called on the worker thread.
nsresult
BackgroundFileSaver::ProcessStateChange()
{
  nsresult rv;

  // We might have been notified because the operation is complete, verify.
  if (CheckCompletion()) {
    return NS_OK;
  }

  // Get a copy of the current shared state for the worker thread.
  nsCOMPtr<nsIFile> initialTarget;
  bool initialTargetKeepPartial;
  nsCOMPtr<nsIFile> renamedTarget;
  bool renamedTargetKeepPartial;
  bool sha256Enabled;
  bool append;
  {
    MutexAutoLock lock(mLock);

    initialTarget = mInitialTarget;
    initialTargetKeepPartial = mInitialTargetKeepPartial;
    renamedTarget = mRenamedTarget;
    renamedTargetKeepPartial = mRenamedTargetKeepPartial;
    sha256Enabled = mSha256Enabled;
    append = mAppend;

    // From now on, another attention event needs to be posted if state changes.
    mWorkerThreadAttentionRequested = false;
  }

  // The initial target can only be null if it has never been assigned.  In this
  // case, there is nothing to do since we never created any output file.
  if (!initialTarget) {
    return NS_OK;
  }

  // Determine if we are processing the attention request for the first time.
  bool isContinuation = !!mActualTarget;
  if (!isContinuation) {
    // Assign the target file for the first time.
    mActualTarget = initialTarget;
    mActualTargetKeepPartial = initialTargetKeepPartial;
  }

  // Verify whether we have actually been instructed to use a different file.
  // This may happen the first time this function is executed, if SetTarget was
  // called two times before the worker thread processed the attention request.
  bool equalToCurrent = false;
  if (renamedTarget) {
    rv = mActualTarget->Equals(renamedTarget, &equalToCurrent);
    NS_ENSURE_SUCCESS(rv, rv);
    if (!equalToCurrent)
    {
      // If we were asked to rename the file but the initial file did not exist,
      // we simply create the file in the renamed location.  We avoid this check
      // if we have already started writing the output file ourselves.
      bool exists = true;
      if (!isContinuation) {
        rv = mActualTarget->Exists(&exists);
        NS_ENSURE_SUCCESS(rv, rv);
      }
      if (exists) {
        // We are moving the previous target file to a different location.
        nsCOMPtr<nsIFile> renamedTargetParentDir;
        rv = renamedTarget->GetParent(getter_AddRefs(renamedTargetParentDir));
        NS_ENSURE_SUCCESS(rv, rv);

        nsAutoString renamedTargetName;
        rv = renamedTarget->GetLeafName(renamedTargetName);
        NS_ENSURE_SUCCESS(rv, rv);

        // We must delete any existing target file before moving the current
        // one.
        rv = renamedTarget->Exists(&exists);
        NS_ENSURE_SUCCESS(rv, rv);
        if (exists) {
          rv = renamedTarget->Remove(false);
          NS_ENSURE_SUCCESS(rv, rv);
        }

        // Move the file.  If this fails, we still reference the original file
        // in mActualTarget, so that it is deleted if requested.  If this
        // succeeds, the nsIFile instance referenced by mActualTarget mutates
        // and starts pointing to the new file, but we'll discard the reference.
        rv = mActualTarget->MoveTo(renamedTargetParentDir, renamedTargetName);
        NS_ENSURE_SUCCESS(rv, rv);
      }

      // Now we can update the actual target file name.
      mActualTarget = renamedTarget;
      mActualTargetKeepPartial = renamedTargetKeepPartial;
    }
  }

  // Notify if the target file name actually changed.
  if (!equalToCurrent) {
    // We must clone the nsIFile instance because mActualTarget is not
    // immutable, it may change if the target is renamed later.
    nsCOMPtr<nsIFile> actualTargetToNotify;
    rv = mActualTarget->Clone(getter_AddRefs(actualTargetToNotify));
    NS_ENSURE_SUCCESS(rv, rv);

    RefPtr<NotifyTargetChangeRunnable> event =
      new NotifyTargetChangeRunnable(this, actualTargetToNotify);
    NS_ENSURE_TRUE(event, NS_ERROR_FAILURE);

    rv = mControlThread->Dispatch(event, NS_DISPATCH_NORMAL);
    NS_ENSURE_SUCCESS(rv, rv);
  }

  if (isContinuation) {
    // The pending rename operation might be the last task before finishing. We
    // may return here only if we have already created the target file.
    if (CheckCompletion()) {
      return NS_OK;
    }

    // Even if the operation did not complete, the pipe input stream may be
    // empty and may have been closed already.  We detect this case using the
    // Available property, because it never returns an error if there is more
    // data to be consumed.  If the pipe input stream is closed, we just exit
    // and wait for more calls like SetTarget or Finish to be invoked on the
    // control thread.  However, we still truncate the file or create the
    // initial digest context if we are expected to do that.
    uint64_t available;
    rv = mPipeInputStream->Available(&available);
    if (NS_FAILED(rv)) {
      return NS_OK;
    }
  }

  // Create the digest context if requested and NSS hasn't been shut down.
  if (sha256Enabled && !mDigestContext) {
    nsNSSShutDownPreventionLock lock;
    if (!isAlreadyShutDown()) {
      mDigestContext = UniquePK11Context(
        PK11_CreateDigestContext(SEC_OID_SHA256));
      NS_ENSURE_TRUE(mDigestContext, NS_ERROR_OUT_OF_MEMORY);
    }
  }

  // When we are requested to append to an existing file, we should read the
  // existing data and ensure we include it as part of the final hash.
  if (mDigestContext && append && !isContinuation) {
    nsCOMPtr<nsIInputStream> inputStream;
    rv = NS_NewLocalFileInputStream(getter_AddRefs(inputStream),
                                    mActualTarget,
                                    PR_RDONLY | nsIFile::OS_READAHEAD);
    if (rv != NS_ERROR_FILE_NOT_FOUND) {
      NS_ENSURE_SUCCESS(rv, rv);

      char buffer[BUFFERED_IO_SIZE];
      while (true) {
        uint32_t count;
        rv = inputStream->Read(buffer, BUFFERED_IO_SIZE, &count);
        NS_ENSURE_SUCCESS(rv, rv);

        if (count == 0) {
          // We reached the end of the file.
          break;
        }

        nsNSSShutDownPreventionLock lock;
        if (isAlreadyShutDown()) {
          return NS_ERROR_NOT_AVAILABLE;
        }

        nsresult rv = MapSECStatus(PK11_DigestOp(mDigestContext.get(),
                                                 uint8_t_ptr_cast(buffer),
                                                 count));
        NS_ENSURE_SUCCESS(rv, rv);
      }

      rv = inputStream->Close();
      NS_ENSURE_SUCCESS(rv, rv);
    }
  }

  // We will append to the initial target file only if it was requested by the
  // caller, but we'll always append on subsequent accesses to the target file.
  int32_t creationIoFlags;
  if (isContinuation) {
    creationIoFlags = PR_APPEND;
  } else {
    creationIoFlags = (append ? PR_APPEND : PR_TRUNCATE) | PR_CREATE_FILE;
  }

  // Create the target file, or append to it if we already started writing it.
  // The 0600 permissions are used while the file is being downloaded, and for
  // interrupted downloads. Those may be located in the system temporary
  // directory, as well as the target directory, and generally have a ".part"
  // extension. Those part files should never be group or world-writable even
  // if the umask allows it.
  nsCOMPtr<nsIOutputStream> outputStream;
  rv = NS_NewLocalFileOutputStream(getter_AddRefs(outputStream),
                                   mActualTarget,
                                   PR_WRONLY | creationIoFlags, 0600);
  NS_ENSURE_SUCCESS(rv, rv);

  outputStream = NS_BufferOutputStream(outputStream, BUFFERED_IO_SIZE);
  if (!outputStream) {
    return NS_ERROR_FAILURE;
  }

  // Wrap the output stream so that it feeds the digest context if needed.
  if (mDigestContext) {
    // No need to acquire the NSS lock here, DigestOutputStream must acquire it
    // in any case before each asynchronous write. Constructing the
    // DigestOutputStream cannot fail. Passing mDigestContext to
    // DigestOutputStream is safe, because BackgroundFileSaver always outlives
    // the outputStream. BackgroundFileSaver is reference-counted before the
    // call to AsyncCopy, and mDigestContext is never destroyed before
    // AsyncCopyCallback.
    outputStream = new DigestOutputStream(outputStream, mDigestContext.get());
  }

  // Start copying our input to the target file.  No errors can be raised past
  // this point if the copy starts, since they should be handled by the thread.
  {
    MutexAutoLock lock(mLock);

    rv = NS_AsyncCopy(mPipeInputStream, outputStream, mWorkerThread,
                      NS_ASYNCCOPY_VIA_READSEGMENTS, 4096, AsyncCopyCallback,
                      this, false, true, getter_AddRefs(mAsyncCopyContext),
                      GetProgressCallback());
    if (NS_FAILED(rv)) {
      NS_WARNING("NS_AsyncCopy failed.");
      mAsyncCopyContext = nullptr;
      return rv;
    }
  }

  // If the operation succeeded, we must ensure that we keep this object alive
  // for the entire duration of the copy, since only the raw pointer will be
  // provided as the argument of the AsyncCopyCallback function.  We can add the
  // reference now, after NS_AsyncCopy returned, because it always starts
  // processing asynchronously, and there is no risk that the callback is
  // invoked before we reach this point.  If the operation failed instead, then
  // AsyncCopyCallback will never be called.
  NS_ADDREF_THIS();

  return NS_OK;
}
Esempio n. 23
0
nsresult
nsOperaProfileMigrator::CopyBookmarksBatched(PRBool aReplace)
{
    // Find Opera Bookmarks
    nsCOMPtr<nsIFile> operaBookmarks;
    mOperaProfile->Clone(getter_AddRefs(operaBookmarks));
    operaBookmarks->Append(OPERA_BOOKMARKS_FILE_NAME);

    nsCOMPtr<nsIInputStream> fileInputStream;
    NS_NewLocalFileInputStream(getter_AddRefs(fileInputStream), operaBookmarks);
    NS_ENSURE_TRUE(fileInputStream, NS_ERROR_OUT_OF_MEMORY);

    nsCOMPtr<nsILineInputStream> lineInputStream(do_QueryInterface(fileInputStream));

    nsresult rv;
    nsCOMPtr<nsINavBookmarksService> bms =
        do_GetService(NS_NAVBOOKMARKSSERVICE_CONTRACTID, &rv);
    NS_ENSURE_SUCCESS(rv, rv);
    PRInt64 bookmarksMenuFolderId;
    rv = bms->GetBookmarksMenuFolder(&bookmarksMenuFolderId);
    NS_ENSURE_SUCCESS(rv, rv);
    PRInt64 parentFolder = bookmarksMenuFolderId;

    nsCOMPtr<nsIStringBundleService> bundleService =
        do_GetService(NS_STRINGBUNDLE_CONTRACTID, &rv);
    NS_ENSURE_SUCCESS(rv, rv);
    nsCOMPtr<nsIStringBundle> bundle;
    rv = bundleService->CreateBundle(MIGRATION_BUNDLE, getter_AddRefs(bundle));
    NS_ENSURE_SUCCESS(rv, rv);

    if (!aReplace) {
        nsString sourceNameOpera;
        rv = bundle->GetStringFromName(NS_LITERAL_STRING("sourceNameOpera").get(),
                                       getter_Copies(sourceNameOpera));
        NS_ENSURE_SUCCESS(rv, rv);

        const PRUnichar* sourceNameStrings[] = { sourceNameOpera.get() };
        nsString importedOperaHotlistTitle;
        rv = bundle->FormatStringFromName(NS_LITERAL_STRING("importedBookmarksFolder").get(),
                                          sourceNameStrings, 1,
                                          getter_Copies(importedOperaHotlistTitle));
        NS_ENSURE_SUCCESS(rv, rv);

        rv = bms->CreateFolder(parentFolder,
                               NS_ConvertUTF16toUTF8(importedOperaHotlistTitle),
                               nsINavBookmarksService::DEFAULT_INDEX,
                               &parentFolder);
        NS_ENSURE_SUCCESS(rv, rv);
    }
    else {
        nsCOMPtr<nsIFile> profile;
        GetProfilePath(nsnull, profile);
        rv = InitializeBookmarks(profile);
        NS_ENSURE_SUCCESS(rv, rv);
    }

#if defined(XP_WIN) || (defined(XP_UNIX) && !defined(XP_MACOSX))
    CopySmartKeywords(bms, bundle, parentFolder);
#endif

    PRInt64 bookmarksToolbarFolderId;
    rv = bms->GetToolbarFolder(&bookmarksToolbarFolderId);
    NS_ENSURE_SUCCESS(rv, rv);

    rv = ParseBookmarksFolder(lineInputStream, parentFolder,
                              bookmarksToolbarFolderId, bms);
    NS_ENSURE_SUCCESS(rv, rv);

    return NS_OK;
}
Esempio n. 24
0
nsresult
nsOperaProfileMigrator::CopyHistoryBatched(PRBool aReplace)
{
    nsCOMPtr<nsIBrowserHistory> hist(do_GetService(NS_GLOBALHISTORY2_CONTRACTID));

    nsCOMPtr<nsIFile> temp;
    mOperaProfile->Clone(getter_AddRefs(temp));
    nsCOMPtr<nsILocalFile> historyFile(do_QueryInterface(temp));
    historyFile->Append(OPERA_HISTORY_FILE_NAME);

    nsCOMPtr<nsIInputStream> fileStream;
    NS_NewLocalFileInputStream(getter_AddRefs(fileStream), historyFile);
    if (!fileStream) return NS_ERROR_OUT_OF_MEMORY;

    nsCOMPtr<nsILineInputStream> lineStream = do_QueryInterface(fileStream);

    nsCAutoString buffer, url;
    nsAutoString title;
    PRTime lastVisitDate;
    PRBool moreData = PR_FALSE;

    enum { TITLE, URL, LASTVISIT } state = TITLE;

    // Format is "title\nurl\nlastvisitdate"
    do {
        nsresult rv = lineStream->ReadLine(buffer, &moreData);
        if (NS_FAILED(rv))
            return rv;

        switch (state) {
        case TITLE:
            CopyUTF8toUTF16(buffer, title);
            state = URL;
            break;
        case URL:
            url = buffer;
            state = LASTVISIT;
            break;
        case LASTVISIT:
            // Opera time format is a second offset, PRTime is a microsecond offset
            nsresult err;
            lastVisitDate = buffer.ToInteger(&err);

            PRInt64 temp, million;
            LL_I2L(temp, lastVisitDate);
            LL_I2L(million, PR_USEC_PER_SEC);
            LL_MUL(lastVisitDate, temp, million);

            nsCOMPtr<nsIURI> uri;
            NS_NewURI(getter_AddRefs(uri), url);
            if (uri)
                hist->AddPageWithDetails(uri, title.get(), lastVisitDate);

            state = TITLE;
            break;
        }
    }
    while (moreData);

    return NS_OK;
}
nsresult
nsPermissionManager::Import()
{
  nsresult rv;

  nsCOMPtr<nsIFile> permissionsFile;
  rv = NS_GetSpecialDirectory(NS_APP_USER_PROFILE_50_DIR, getter_AddRefs(permissionsFile));
  if (NS_FAILED(rv)) return rv;

  rv = permissionsFile->AppendNative(NS_LITERAL_CSTRING(kHostpermFileName));
  NS_ENSURE_SUCCESS(rv, rv);

  nsCOMPtr<nsIInputStream> fileInputStream;
  rv = NS_NewLocalFileInputStream(getter_AddRefs(fileInputStream),
                                  permissionsFile);
  if (NS_FAILED(rv)) return rv;

  nsCOMPtr<nsILineInputStream> lineInputStream = do_QueryInterface(fileInputStream, &rv);
  NS_ENSURE_SUCCESS(rv, rv);

  // start a transaction on the storage db, to optimize insertions.
  // transaction will automically commit on completion
  mozStorageTransaction transaction(mDBConn, PR_TRUE);

  /* format is:
   * matchtype \t type \t permission \t host
   * Only "host" is supported for matchtype
   * type is a string that identifies the type of permission (e.g. "cookie")
   * permission is an integer between 1 and 15
   */

  nsCAutoString buffer;
  PRBool isMore = PR_TRUE;
  while (isMore && NS_SUCCEEDED(lineInputStream->ReadLine(buffer, &isMore))) {
    if (buffer.IsEmpty() || buffer.First() == '#') {
      continue;
    }

    nsTArray<nsCString> lineArray;

    // Split the line at tabs
    ParseString(buffer, '\t', lineArray);
    
    if (lineArray[0].EqualsLiteral(kMatchTypeHost) &&
        lineArray.Length() == 4) {
      
      PRInt32 error;
      PRUint32 permission = lineArray[2].ToInteger(&error);
      if (error)
        continue;

      // hosts might be encoded in UTF8; switch them to ACE to be consistent
      if (!IsASCII(lineArray[3])) {
        rv = NormalizeToACE(lineArray[3]);
        if (NS_FAILED(rv))
          continue;
      }

      rv = AddInternal(lineArray[3], lineArray[1], permission, 0, 
                       nsIPermissionManager::EXPIRE_NEVER, 0, eDontNotify, eWriteToDB);
      NS_ENSURE_SUCCESS(rv, rv);
    }
  }

  // we're done importing - delete the old file
  permissionsFile->Remove(PR_FALSE);

  return NS_OK;
}
Esempio n. 26
0
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);
}
Esempio n. 27
0
int
MimePartBufferRead (MimePartBufferData *data,
          nsresult (*read_fn) (const char *buf, PRInt32 size, void *closure),
          void *closure)
{
  int status = 0;
  NS_ASSERTION(data, "no data");
  if (!data) return -1;

  if (data->part_buffer)
  {
    // Read it out of memory.
    status = read_fn(data->part_buffer, data->part_buffer_fp, closure);
  }
  else if (data->file_buffer)
  {
    /* Read it off disk.
     */
    char *buf;
    PRInt32 buf_size = DISK_BUFFER_SIZE;

    NS_ASSERTION(data->part_buffer_size == 0 && data->part_buffer_fp == 0, "buffer size is not null");
    NS_ASSERTION(data->file_buffer, "no file buffer name");
    if (!data->file_buffer)
      return -1;

    buf = (char *) PR_MALLOC(buf_size);
    if (!buf)
      return MIME_OUT_OF_MEMORY;

    // First, close the output file to open the input file!
    if (data->output_file_stream)
      data->output_file_stream->Close();

    nsresult rv = NS_NewLocalFileInputStream(getter_AddRefs(data->input_file_stream), data->file_buffer);
    if (NS_FAILED(rv))
    {
      PR_Free(buf);
      return MIME_UNABLE_TO_OPEN_TMP_FILE;
    }
    while(1)
    {
      PRUint32 bytesRead = 0;
      rv = data->input_file_stream->Read(buf, buf_size - 1, &bytesRead);
      if (NS_FAILED(rv) || !bytesRead)
      {
        break;
      }
      else
      {
        /* It would be really nice to be able to yield here, and let
        some user events and other input sources get processed.
        Oh well. */

        status = read_fn (buf, bytesRead, closure);
        if (status < 0) break;
      }
    }
    PR_Free(buf);
  }

  return 0;
}
Esempio n. 28
0
NS_IMETHODIMP nsAbLDIFService::ImportLDIFFile(nsIAddrDatabase *aDb, nsIFile *aSrc, bool aStoreLocAsHome, PRUint32 *aProgress)
{
  NS_ENSURE_ARG_POINTER(aSrc);
  NS_ENSURE_ARG_POINTER(aDb);

  mStoreLocAsHome = aStoreLocAsHome;

  char buf[1024];
  char* pBuf = &buf[0];
  PRInt32 startPos = 0;
  PRUint32 len = 0;
  nsVoidArray listPosArray;   // where each list/group starts in ldif file
  nsVoidArray listSizeArray;  // size of the list/group info
  PRInt32 savedStartPos = 0;
  PRInt32 filePos = 0;
  PRUint32 bytesLeft = 0;

  nsCOMPtr<nsIInputStream> inputStream;
  nsresult rv = NS_NewLocalFileInputStream(getter_AddRefs(inputStream), aSrc);
  NS_ENSURE_SUCCESS(rv, rv);

  // Initialize the parser for a run...
  mLdifLine.Truncate();

  while (NS_SUCCEEDED(inputStream->Available(&bytesLeft)) && bytesLeft > 0)
  {
    if (NS_SUCCEEDED(inputStream->Read(pBuf, sizeof(buf), &len)) && len > 0)
    {
      startPos = 0;

      while (NS_SUCCEEDED(GetLdifStringRecord(buf, len, startPos)))
      {
        if (mLdifLine.Find("groupOfNames") == -1)
          AddLdifRowToDatabase(aDb, false);
        else
        {
          //keep file position for mailing list
          listPosArray.AppendElement((void*)savedStartPos);
          listSizeArray.AppendElement((void*)(filePos + startPos-savedStartPos));
          ClearLdifRecordBuffer();
        }
        savedStartPos = filePos + startPos;
      }
      filePos += len;
      if (aProgress)
        *aProgress = (PRUint32)filePos;
    }
  }
  //last row
  if (!mLdifLine.IsEmpty() && mLdifLine.Find("groupOfNames") == -1)
    AddLdifRowToDatabase(aDb, false); 

  // mail Lists
  PRInt32 i, pos;
  PRUint32 size;
  PRInt32 listTotal = listPosArray.Count();
  char *listBuf;
  ClearLdifRecordBuffer();  // make sure the buffer is clean

  nsCOMPtr<nsISeekableStream> seekableStream = do_QueryInterface(inputStream, &rv);
  NS_ENSURE_SUCCESS(rv, rv);

  for (i = 0; i < listTotal; i++)
  {
    pos  = NS_PTR_TO_INT32(listPosArray.ElementAt(i));
    size = NS_PTR_TO_INT32(listSizeArray.ElementAt(i));
    if (NS_SUCCEEDED(seekableStream->Seek(nsISeekableStream::NS_SEEK_SET, pos)))
    {
      // Allocate enough space for the lists/groups as the size varies.
      listBuf = (char *) PR_Malloc(size);
      if (!listBuf)
        continue;
      if (NS_SUCCEEDED(inputStream->Read(listBuf, size, &len)) && len > 0)
      {
        startPos = 0;

        while (NS_SUCCEEDED(GetLdifStringRecord(listBuf, len, startPos)))
        {
          if (mLdifLine.Find("groupOfNames") != -1)
          {
            AddLdifRowToDatabase(aDb, true);
            if (NS_SUCCEEDED(seekableStream->Seek(nsISeekableStream::NS_SEEK_SET, 0)))
              break;
          }
        }
      }
    PR_FREEIF(listBuf);
    }
  }

  rv = inputStream->Close();
  NS_ENSURE_SUCCESS(rv, rv);

  // Finally commit everything to the database and return.
  return aDb->Commit(nsAddrDBCommitType::kLargeCommit);
}
bool nsEudoraFilters::RealImport()
{
  nsresult rv;

  rv = Init();
  if (NS_FAILED(rv))
  {
    IMPORT_LOG0("*** Error initializing filter import process\n");
    return false;
  }

  nsCOMPtr <nsIInputStream> inputStream;
  rv = NS_NewLocalFileInputStream(getter_AddRefs(inputStream), m_pLocation);

  if (NS_FAILED(rv))
  {
    IMPORT_LOG0("*** Error opening filters file for reading\n");
    return false;
  }

  rv = LoadServers();
  if (NS_FAILED(rv))
  {
    IMPORT_LOG0("*** Error loading servers with filters\n");
    return false;
  }

  nsCOMPtr<nsILineInputStream> lineStream(do_QueryInterface(inputStream, &rv));
  NS_ENSURE_SUCCESS(rv, false);

  nsCString     line;
  bool          more = true;
  nsAutoCString header;
  nsAutoCString verb;
  nsAutoString  name;

  // Windows Eudora filters files have a version header as a first line - just skip it
#if defined(XP_WIN)
  rv = lineStream->ReadLine(line, &more);
#endif

  while (more && NS_SUCCEEDED(rv))
  {
    rv = lineStream->ReadLine(line, &more);
    const char* pLine = line.get();
    if (NS_SUCCEEDED(rv))
    {
      // New filters start with a "rule <name>" line
      if (!strncmp(pLine, "rule ", 5))
      {
        rv = FinalizeFilter();
        if (NS_SUCCEEDED(rv))
        {
          const char* pName = pLine + 5;
          NS_CopyNativeToUnicode(nsCString(pName), name);
          rv = CreateNewFilter(pName);
        }
      }
#ifdef XP_MACOSX
      else if (!strncmp(pLine, "id ", 3))
        ;// ids have no value to us, but we don't want them to produce a warning either
#endif
      else if (!strncmp(pLine, "conjunction ", 12))
      {
        const char* cj = pLine + 12;
        if (!strcmp(cj, "and"))
          m_isAnd = true;
        else if (!strcmp(cj, "unless"))
          m_isUnless = true;
        else if (!strcmp(cj, "ignore"))
          m_ignoreTerm = true;
      }
      else if (!strncmp(pLine, "header ", 7))
        header = (pLine + 7);
      else if (!strncmp(pLine, "verb ", 5))
        verb = (pLine + 5);
      else if (!strncmp(pLine, "value ", 6))
      {
        if (!m_ignoreTerm)
        {
          rv = AddTerm(header.get(), verb.get(), pLine + 6, (m_isAnd || m_isUnless), m_isUnless);
          // For now, ignoring terms that can't be represented in TB filters
          if (rv == NS_ERROR_INVALID_ARG)
          {
            rv = NS_OK;
            m_termNotGroked = true;
          }
        }
      }
      else if (!strcmp(pLine, "incoming"))
        m_isIncoming = true;
      else if (!strncmp(pLine, "transfer ", 9) ||
               !strncmp(pLine, "copy ", 5))
      {
        const char* pMailboxPath = strchr(pLine, ' ') + 1;
        bool isTransfer = (*pLine == 't');
        rv = AddMailboxAction(pMailboxPath, isTransfer);
        if (rv == NS_ERROR_INVALID_ARG)
        {
          nsAutoString unicodeMailboxPath;
          NS_CopyNativeToUnicode(nsCString(pMailboxPath), unicodeMailboxPath);
          m_errorLog += NS_LITERAL_STRING("- ");
          m_errorLog += name;
          m_errorLog += NS_LITERAL_STRING(": ");
          m_errorLog += nsEudoraStringBundle::FormatString(EUDORAIMPORT_FILTERS_WARN_MAILBOX_MISSING, unicodeMailboxPath.get());
          m_errorLog += NS_LITERAL_STRING("\n");
          rv = NS_OK;
        }
      }
      // Doing strncmp() here because Win Eudora puts a space after "stop" but Mac Eudora doesn't
      else if (!strncmp(pLine, "stop", 4))
        m_hasStop = true;
      else if (!strncmp(pLine, "forward ", 8))
        rv = AddStringAction(nsMsgFilterAction::Forward, pLine + 8);
      else if (!strncmp(pLine, "reply ", 6))
        rv = AddStringAction(nsMsgFilterAction::Reply, pLine + 6);
      else if (!strncmp(pLine, "priority ", 9))
      {
        // Win Eudora's  priority values are 0 (highest) to 4 (lowest)
        // Mac Eudora's  priority values are 1 (highest) to 5 (lowest)
        // Thunderbird's priority values are 6 (highest) to 2 (lowest)
        int32_t TBPriority = 6 - atoi(pLine + 9);
#ifdef XP_MACOSX
        TBPriority++;
#endif
        rv = AddPriorityAction(TBPriority);
      }
      else if (!strncmp(pLine, "label ", 6))
      {
        nsAutoCString tagName("$label");
        tagName += pLine + 6;
        rv = AddStringAction(nsMsgFilterAction::AddTag, tagName.get());
      }
      // Doing strncmp() here because Win Eudora puts a space after "junk" but Mac Eudora doesn't
      else if (!strncmp(pLine, "junk", 4))
        rv = AddJunkAction(100);
      else if (!strncmp(pLine, "status ", 7))
      {
        // Win Eudora's read status is 1, whereas Mac Eudora's read status is 2
        uint32_t status = atoi(pLine + 7);
#ifdef XP_MACOSX
        status--;
#endif
        if (status == 1)
          rv = AddAction(nsMsgFilterAction::MarkRead);
      }
      else if (!strncmp(pLine, "serverOpt ", 10))
      {
        // Win and Mac Eudora have the two bits swapped in the file
        uint32_t bits = atoi(pLine + 10);
#if defined(XP_WIN)
        bool bFetch  = (bits & 1);
        bool bDelete = (bits & 2);
#endif
#ifdef XP_MACOSX
        bool bFetch  = (bits & 2);
        bool bDelete = (bits & 1);
#endif
        rv = AddAction(bDelete? (nsMsgRuleActionType)nsMsgFilterAction::DeleteFromPop3Server : (nsMsgRuleActionType)nsMsgFilterAction::LeaveOnPop3Server);
        if (NS_SUCCEEDED(rv) && bFetch)
          rv = AddAction(nsMsgFilterAction::FetchBodyFromPop3Server);
      }
      else if (strcmp(pLine, "manual") == 0)
        ;// Just ignore manual as TB handles manual in a different way
      else if (strcmp(pLine, "outgoing") == 0)
      {
        m_errorLog += NS_LITERAL_STRING("- ");
        m_errorLog += name;
        m_errorLog += NS_LITERAL_STRING(": ");
        m_errorLog += nsEudoraStringBundle::FormatString(EUDORAIMPORT_FILTERS_WARN_OUTGOING);
        m_errorLog += NS_LITERAL_STRING("\n");
      }
      else
      {
        nsAutoString unicodeLine;
        NS_CopyNativeToUnicode(nsCString(pLine), unicodeLine);
        m_errorLog += NS_LITERAL_STRING("- ");
        m_errorLog += name;
        m_errorLog += NS_LITERAL_STRING(": ");
        m_errorLog += nsEudoraStringBundle::FormatString(EUDORAIMPORT_FILTERS_WARN_ACTION, unicodeLine.get());
        m_errorLog += NS_LITERAL_STRING("\n");
      }
    }
  }

  // Process the last filter
  if (!more && NS_SUCCEEDED(rv))
    rv = FinalizeFilter();

  inputStream->Close();

  if (more)
  {
    IMPORT_LOG0("*** Error reading the filters, didn't reach the end\n");
    return false;
  }

  rv = SaveFilters();

  return NS_SUCCEEDED(rv);
}
Esempio n. 30
0
nsresult
GMPParent::ReadGMPMetaData()
{
  MOZ_ASSERT(mDirectory, "Plugin directory cannot be NULL!");
  MOZ_ASSERT(!mName.IsEmpty(), "Plugin mName cannot be empty!");

  nsCOMPtr<nsIFile> infoFile;
  nsresult rv = mDirectory->Clone(getter_AddRefs(infoFile));
  if (NS_FAILED(rv)) {
    return rv;
  }
  infoFile->AppendRelativePath(mName + NS_LITERAL_STRING(".info"));

  nsCOMPtr<nsIInputStream> inputStream;
  rv = NS_NewLocalFileInputStream(getter_AddRefs(inputStream), infoFile);
  if (NS_FAILED(rv)) {
    return rv;
  }

  nsCOMPtr<nsILineInputStream> lineInputStream = do_QueryInterface(inputStream, &rv);
  if (NS_FAILED(rv)) {
    return rv;
  }

  nsCString value;
  bool moreLines = false;

  // 'Name:' record
  nsCString prefix = NS_LITERAL_CSTRING("Name:");
  rv = ParseNextRecord(lineInputStream, prefix, value, moreLines);
  if (NS_FAILED(rv)) {
    return rv;
  }
  if (value.IsEmpty()) {
    // Not OK for name to be empty. Must have one non-whitespace character.
    return NS_ERROR_FAILURE;
  }
  mDisplayName = value;

  // 'Description:' record
  if (!moreLines) {
    return NS_ERROR_FAILURE;
  }
  prefix = NS_LITERAL_CSTRING("Description:");
  rv = ParseNextRecord(lineInputStream, prefix, value, moreLines);
  if (NS_FAILED(rv)) {
    return rv;
  }
  mDescription = value;

  // 'Version:' record
  if (!moreLines) {
    return NS_ERROR_FAILURE;
  }
  prefix = NS_LITERAL_CSTRING("Version:");
  rv = ParseNextRecord(lineInputStream, prefix, value, moreLines);
  if (NS_FAILED(rv)) {
    return rv;
  }
  mVersion = value;

  // 'Capability:' record
  if (!moreLines) {
    return NS_ERROR_FAILURE;
  }
  prefix = NS_LITERAL_CSTRING("APIs:");
  rv = ParseNextRecord(lineInputStream, prefix, value, moreLines);
  if (NS_FAILED(rv)) {
    return rv;
  }
  nsCCharSeparatedTokenizer apiTokens(value, ',');
  while (apiTokens.hasMoreTokens()) {
    nsAutoCString api(apiTokens.nextToken());
    api.StripWhitespace();
    if (api.IsEmpty()) {
      continue;
    }

    int32_t tagsStart = api.FindChar('[');
    if (tagsStart == 0) {
      // Not allowed to be the first character.
      // API name must be at least one character.
      continue;
    }

    auto cap = new GMPCapability();
    if (tagsStart == -1) {
      // No tags.
      cap->mAPIName.Assign(api);
    } else {
      auto tagsEnd = api.FindChar(']');
      if (tagsEnd == -1 || tagsEnd < tagsStart) {
        // Invalid syntax, skip whole capability.
        delete cap;
        continue;
      }

      cap->mAPIName.Assign(Substring(api, 0, tagsStart));

      if ((tagsEnd - tagsStart) > 1) {
        const nsDependentCSubstring ts(Substring(api, tagsStart + 1, tagsEnd - tagsStart - 1));
        nsCCharSeparatedTokenizer tagTokens(ts, ':');
        while (tagTokens.hasMoreTokens()) {
          const nsDependentCSubstring tag(tagTokens.nextToken());
          cap->mAPITags.AppendElement(tag);
        }
      }
    }

    mCapabilities.AppendElement(cap);
  }

  if (mCapabilities.IsEmpty()) {
    return NS_ERROR_FAILURE;
  }

  return NS_OK;
}