Esempio n. 1
0
nsresult WriteProperties(const char* properties_file)
{
    FILE* props;
    printf("writing to %s\n", properties_file);
    if (!(props = fopen(properties_file, "w"))) {
        printf("Could not write to %s\n", properties_file);
        return NS_ERROR_FAILURE;
    }

    nsCOMPtr<nsIFile> chromeFile;
    nsresult rv = NS_GetSpecialDirectory(NS_APP_CHROME_DIR, getter_AddRefs(chromeFile));
    if(NS_FAILED(rv)) {
        fclose(props);
        return rv;
    }

    chromeFile->AppendNative(NS_LITERAL_CSTRING("chrome.rdf"));
    
    nsCAutoString pathURL;
    NS_GetURLSpecFromFile(chromeFile, pathURL);

    nsCOMPtr<nsIRDFService> rdf = 
        do_GetService("@mozilla.org/rdf/rdf-service;1");

    nsCOMPtr<nsIRDFDataSource> chromeDS;
    rdf->GetDataSource(pathURL.get(), getter_AddRefs(chromeDS));

    WritePropertiesTo(chromeDS, "package", props);
    WritePropertiesTo(chromeDS, "skin", props);
    WritePropertiesTo(chromeDS, "locale", props);

    fclose(props);
    return NS_OK;
}
nsPluginStreamToFile::nsPluginStreamToFile(const char* target,
                                           nsIPluginInstanceOwner* owner)
: mTarget(PL_strdup(target)),
mOwner(owner)
{
  nsresult rv;
  nsCOMPtr<nsIFile> pluginTmp;
  rv = NS_GetSpecialDirectory(NS_OS_TEMP_DIR, getter_AddRefs(pluginTmp));
  if (NS_FAILED(rv)) return;
  
  mTempFile = do_QueryInterface(pluginTmp, &rv);
  if (NS_FAILED(rv)) return;
  
  // need to create a file with a unique name - use target as the basis
  rv = mTempFile->AppendNative(nsDependentCString(target));
  if (NS_FAILED(rv)) return;
  
  // Yes, make it unique.
  rv = mTempFile->CreateUnique(nsIFile::NORMAL_FILE_TYPE, 0700); 
  if (NS_FAILED(rv)) return;
  
  // create the file
  rv = NS_NewLocalFileOutputStream(getter_AddRefs(mOutputStream), mTempFile, -1, 00600);
  if (NS_FAILED(rv))
    return;
	
  // construct the URL we'll use later in calls to GetURL()
  NS_GetURLSpecFromFile(mTempFile, mFileURL);
  
#ifdef DEBUG
  printf("File URL = %s\n", mFileURL.get());
#endif
}
NS_IMETHODIMP
nsPrintSettingsGTK::SetToFileName(const char16_t * aToFileName)
{
    if (aToFileName[0] == 0) {
        mToFileName.SetLength(0);
        gtk_print_settings_set(mPrintSettings, GTK_PRINT_SETTINGS_OUTPUT_URI,
                               nullptr);
        return NS_OK;
    }

    if (StringEndsWith(nsDependentString(aToFileName), NS_LITERAL_STRING(".ps"))) {
        gtk_print_settings_set(mPrintSettings, GTK_PRINT_SETTINGS_OUTPUT_FILE_FORMAT, "ps");
    } else {
        gtk_print_settings_set(mPrintSettings, GTK_PRINT_SETTINGS_OUTPUT_FILE_FORMAT, "pdf");
    }

    nsCOMPtr<nsIFile> file;
    nsresult rv = NS_NewLocalFile(nsDependentString(aToFileName), true,
                                  getter_AddRefs(file));
    NS_ENSURE_SUCCESS(rv, rv);

    // Convert the nsIFile to a URL
    nsAutoCString url;
    rv = NS_GetURLSpecFromFile(file, url);
    NS_ENSURE_SUCCESS(rv, rv);

    gtk_print_settings_set(mPrintSettings, GTK_PRINT_SETTINGS_OUTPUT_URI, url.get());
    mToFileName = aToFileName;

    return NS_OK;
}
nsresult
nsDownloadManager::GetProfileDownloadsFileURL(nsCString& aDownloadsFileURL)
{
    nsCOMPtr<nsIFile> downloadsFile;
    nsresult rv = NS_GetSpecialDirectory(NS_APP_DOWNLOADS_50_FILE, getter_AddRefs(downloadsFile));
    if (NS_FAILED(rv))
        return rv;

    return NS_GetURLSpecFromFile(downloadsFile, aDownloadsFileURL);
}
Esempio n. 5
0
NS_IMETHODIMP
nsMsgFilterList::GetLogURL(nsACString &aLogURL)
{
  nsCOMPtr <nsIFile> file;
  nsresult rv = GetLogFile(getter_AddRefs(file));
  NS_ENSURE_SUCCESS(rv,rv);

  rv = NS_GetURLSpecFromFile(file, aLogURL);
  NS_ENSURE_SUCCESS(rv,rv);

  return !aLogURL.IsEmpty() ? NS_OK : NS_ERROR_OUT_OF_MEMORY;
}
Esempio n. 6
0
//
// FindURLFromLocalFile
//
// we are looking for a URL and couldn't find it, try again with looking for 
// a local file. If we have one, it may either be a normal file or an internet shortcut.
// In both cases, however, we can get a URL (it will be a file:// url in the
// local file case).
//
bool
nsClipboard :: FindURLFromLocalFile ( IDataObject* inDataObject, UINT inIndex, void** outData, PRUint32* outDataLen )
{
  bool dataFound = false;

  nsresult loadResult = GetNativeDataOffClipboard(inDataObject, inIndex, GetFormat(kFileMime), nullptr, outData, outDataLen);
  if ( NS_SUCCEEDED(loadResult) && *outData ) {
    // we have a file path in |data|. Is it an internet shortcut or a normal file?
    const nsDependentString filepath(static_cast<PRUnichar*>(*outData));
    nsCOMPtr<nsIFile> file;
    nsresult rv = NS_NewLocalFile(filepath, true, getter_AddRefs(file));
    if (NS_FAILED(rv)) {
      nsMemory::Free(*outData);
      return dataFound;
    }

    if ( IsInternetShortcut(filepath) ) {
      nsMemory::Free(*outData);
      nsCAutoString url;
      ResolveShortcut( file, url );
      if ( !url.IsEmpty() ) {
        // convert it to unicode and pass it out
        nsDependentString urlString(UTF8ToNewUnicode(url));
        // the internal mozilla URL format, text/x-moz-url, contains
        // URL\ntitle.  We can guess the title from the file's name.
        nsAutoString title;
        file->GetLeafName(title);
        // We rely on IsInternetShortcut check that file has a .url extension.
        title.SetLength(title.Length() - 4);
        if (title.IsEmpty())
          title = urlString;
        *outData = ToNewUnicode(urlString + NS_LITERAL_STRING("\n") + title);
        *outDataLen = NS_strlen(static_cast<PRUnichar*>(*outData)) * sizeof(PRUnichar);

        dataFound = true;
      }
    }
    else {
      // we have a normal file, use some Necko objects to get our file path
      nsCAutoString urlSpec;
      NS_GetURLSpecFromFile(file, urlSpec);

      // convert it to unicode and pass it out
      nsMemory::Free(*outData);
      *outData = UTF8ToNewUnicode(urlSpec);
      *outDataLen = NS_strlen(static_cast<PRUnichar*>(*outData)) * sizeof(PRUnichar);
      dataFound = true;
    } // else regular file
  }

  return dataFound;
} // FindURLFromLocalFile
Esempio n. 7
0
static nsresult GetIconURLVariant(nsIFile* aApplication, nsIVariant* *_retval)
{
  nsresult rv = CallCreateInstance("@mozilla.org/variant;1", _retval);
  if (NS_FAILED(rv))
    return rv;
  nsCAutoString fileURLSpec;
  NS_GetURLSpecFromFile(aApplication, fileURLSpec);
  nsCAutoString iconURLSpec; iconURLSpec.AssignLiteral("moz-icon://");
  iconURLSpec += fileURLSpec;
  nsCOMPtr<nsIWritableVariant> writable(do_QueryInterface(*_retval));
  writable->SetAsAUTF8String(iconURLSpec);
  return NS_OK;
}
//----------------------------------------------------------------------------------------
nsresult nsMacCommandLine::AddToCommandLine(const char* inOptionString, const FSSpec& inFileSpec)
//----------------------------------------------------------------------------------------
{
  // Convert the filespec to a URL
  FSSpec nonConstSpec = inFileSpec;
  nsCOMPtr<nsILocalFileMac> inFile;
  nsresult rv = NS_NewLocalFileWithFSSpec(&nonConstSpec, PR_TRUE, getter_AddRefs(inFile));
  if (NS_FAILED(rv))
    return rv;
  nsCAutoString specBuf;
  rv = NS_GetURLSpecFromFile(inFile, specBuf);
  if (NS_FAILED(rv))
    return rv;
  AddToCommandLine(inOptionString);  
  AddToCommandLine(specBuf.get());
  return NS_OK;
}
Esempio n. 9
0
nsHyphenator::nsHyphenator(nsIFile *aFile)
  : mDict(nsnull)
{
  nsCString urlSpec;
  nsresult rv = NS_GetURLSpecFromFile(aFile, urlSpec);
  if (NS_FAILED(rv)) {
    return;
  }
  mDict = hnj_hyphen_load(urlSpec.get());
#ifdef DEBUG
  if (mDict) {
    printf("loaded hyphenation patterns from %s\n", urlSpec.get());
  }
#endif
  mCategories = do_GetService(NS_UNICHARCATEGORY_CONTRACTID, &rv);
  NS_ASSERTION(NS_SUCCEEDED(rv), "failed to get category service");
}
nsresult
nsNetscapeProfileMigratorBase::SetFile(PrefTransform* aTransform,
                                       nsIPrefBranch* aBranch)
{
  // In this case targetPrefName is just an additional preference
  // that needs to be modified and not what the sourcePrefName is
  // going to be saved to once it is modified.
  nsresult rv = NS_OK;
  if (aTransform->prefHasValue) {
    nsCString fileURL(aTransform->stringValue);
    nsCOMPtr<nsIFile> aFile;
    // Start off by assuming fileURL is a URL spec and
    // try and get a File from it.
    rv = NS_GetFileFromURLSpec(fileURL, getter_AddRefs(aFile));
    if (NS_FAILED(rv)) {
      // Okay it wasn't a URL spec so assume it is a localfile,
      // if this fails then just don't set anything.
      nsCOMPtr<nsIFile> localFile;
      rv = NS_NewNativeLocalFile(fileURL, false, getter_AddRefs(localFile));
      if (NS_FAILED(rv))
        return NS_OK;  
      aFile = localFile;
    }
    // Now test to see if File exists and is an actual file.
    bool exists = false;
    rv = aFile->Exists(&exists);
    if (NS_SUCCEEDED(rv) && exists)
      rv = aFile->IsFile(&exists);

    if (NS_SUCCEEDED(rv) && exists) {
      // After all that let's just get the URL spec and set the pref to it.
      rv = NS_GetURLSpecFromFile(aFile, fileURL);
      if (NS_FAILED(rv))
        return NS_OK;
      rv = aBranch->SetCharPref(aTransform->sourcePrefName, fileURL.get());
      if (NS_SUCCEEDED(rv) && aTransform->targetPrefName)
        rv = aBranch->SetIntPref(aTransform->targetPrefName, 1);
    }
  }
  return rv;
}
Esempio n. 11
0
//
// FindURLFromLocalFile
//
// we are looking for a URL and couldn't find it, try again with looking for 
// a local file. If we have one, it may either be a normal file or an internet shortcut.
// In both cases, however, we can get a URL (it will be a file:// url in the
// local file case).
//
PRBool
nsClipboard :: FindURLFromLocalFile ( IDataObject* inDataObject, UINT inIndex, void** outData, PRUint32* outDataLen )
{
  PRBool dataFound = PR_FALSE;

  nsresult loadResult = GetNativeDataOffClipboard(inDataObject, inIndex, GetFormat(kFileMime), outData, outDataLen);
  if ( NS_SUCCEEDED(loadResult) && *outData ) {
    // we have a file path in |data|. Is it an internet shortcut or a normal file?
    const nsDependentString filepath(static_cast<PRUnichar*>(*outData));
    nsCOMPtr<nsILocalFile> file;
    nsresult rv = NS_NewLocalFile(filepath, PR_TRUE, getter_AddRefs(file));
    if (NS_FAILED(rv))
      return dataFound;

    if ( IsInternetShortcut(filepath) ) {
      nsCAutoString url;
      ResolveShortcut( file, url );
      if ( !url.IsEmpty() ) {
        // convert it to unicode and pass it out
        nsMemory::Free(*outData);
        *outData = UTF8ToNewUnicode(url);
        *outDataLen = nsCRT::strlen(static_cast<PRUnichar*>(*outData)) * sizeof(PRUnichar);

        dataFound = PR_TRUE;
      }
    }
    else {
      // we have a normal file, use some Necko objects to get our file path
      nsCAutoString urlSpec;
      NS_GetURLSpecFromFile(file, urlSpec);

      // convert it to unicode and pass it out
      nsMemory::Free(*outData);
      *outData = UTF8ToNewUnicode(urlSpec);
      *outDataLen = nsCRT::strlen(static_cast<PRUnichar*>(*outData)) * sizeof(PRUnichar);
      dataFound = PR_TRUE;
    } // else regular file
  }

  return dataFound;
} // FindURLFromLocalFile
void nsMsgServiceProviderService::LoadISPFilesFromDir(nsIFile* aDir)
{
  nsresult rv;

  bool check = false;
  rv = aDir->Exists(&check);
  if (NS_FAILED(rv) || !check)
    return;

  rv = aDir->IsDirectory(&check);
  if (NS_FAILED(rv) || !check)
    return;

  nsCOMPtr<nsISimpleEnumerator> e;
  rv = aDir->GetDirectoryEntries(getter_AddRefs(e));
  if (NS_FAILED(rv))
    return;

  nsCOMPtr<nsIDirectoryEnumerator> files(do_QueryInterface(e));
  if (!files)
    return;

  // we only care about the .rdf files in this directory
  nsCOMPtr<nsIFile> file;
  while (NS_SUCCEEDED(files->GetNextFile(getter_AddRefs(file))) && file) {
    nsAutoString leafName;
    file->GetLeafName(leafName);
    if (!StringEndsWith(leafName, NS_LITERAL_STRING(".rdf")))
      continue;

    nsAutoCString urlSpec;
    rv = NS_GetURLSpecFromFile(file, urlSpec);
    if (NS_SUCCEEDED(rv))
      LoadDataSource(urlSpec.get());
  }
}
Esempio n. 13
0
// this is used to populate the docs as attachments in the Comp fields for Send Documents
nsresult nsMapiHook::PopulateCompFieldsForSendDocs(nsIMsgCompFields * aCompFields, ULONG aFlags,
                            PRUnichar * aDelimChar, PRUnichar * aFilePaths)
{
  nsAutoString strDelimChars ;
  nsString strFilePaths;
  nsresult rv = NS_OK ;
  PRBool bExist ;

  if (aFlags & MAPI_UNICODE)
  {
    if (aDelimChar)
      strDelimChars.Assign (aDelimChar);
    if (aFilePaths)
      strFilePaths.Assign (aFilePaths);
  }
  else
  {
    if (aDelimChar)
      strDelimChars.Assign(aDelimChar);
    if (aFilePaths)
      strFilePaths.Assign ( aFilePaths);
  }

  // check for comma in filename
  if (strDelimChars.Find (",") == kNotFound)  // if comma is not in the delimiter specified by user
  {
    if (strFilePaths.Find(",") != kNotFound) // if comma found in filenames return error
      return NS_ERROR_FILE_INVALID_PATH;
  }

  nsCString Attachments ;

  // only 1 file is to be sent, no delim specified
  if (strDelimChars.IsEmpty())
      strDelimChars.AssignLiteral(";");

  PRInt32 offset = 0 ;
  PRInt32 FilePathsLen = strFilePaths.Length() ;
  if (FilePathsLen)
  {
    nsAutoString Subject ;

    // multiple files to be sent, delim specified
    nsCOMPtr <nsILocalFile> pFile = do_CreateInstance (NS_LOCAL_FILE_CONTRACTID, &rv) ;
    if (NS_FAILED(rv) || (!pFile) ) return rv ;

    PRUnichar * newFilePaths = (PRUnichar *) strFilePaths.get() ;
    while (offset != kNotFound)
    {
      //Temp Directory
      nsCOMPtr <nsIFile> pTempFileDir;
      NS_GetSpecialDirectory(NS_OS_TEMP_DIR, getter_AddRefs(pTempFileDir));
      nsCOMPtr <nsILocalFile> pTempDir = do_QueryInterface(pTempFileDir);

      // if not already existing, create another temp dir for mapi within Win temp dir
      // this is windows only so we can do "\\"
      pTempDir->AppendRelativePath (NS_LITERAL_STRING("moz_mapi"));
      pTempDir->Exists(&bExist) ;
      if (!bExist)
      {
        rv = pTempDir->Create(nsIFile::DIRECTORY_TYPE, 777) ;
        if (NS_FAILED(rv)) return rv ;
      }

      nsString RemainingPaths ;
      RemainingPaths.Assign(newFilePaths) ;
      offset = RemainingPaths.Find (strDelimChars) ;
      if (offset != kNotFound)
      {
        RemainingPaths.SetLength (offset) ;
        if ((offset + strDelimChars.Length()) < FilePathsLen)
          newFilePaths += offset + strDelimChars.Length() ;
        else
          offset = kNotFound;
        FilePathsLen -= offset + strDelimChars.Length();
      }

      if (RemainingPaths[1] != ':' && RemainingPaths[1] != '\\')
      {
        char cwd[MAX_PATH];
        if (_getdcwd(_getdrive(), cwd, MAX_PATH))
        {
          nsAutoString cwdStr;
          CopyASCIItoUTF16(cwd, cwdStr);
          cwdStr.Append('\\');
          RemainingPaths.Insert(cwdStr, 0);
        }
      }

      pFile->InitWithPath (RemainingPaths) ;

      rv = pFile->Exists(&bExist) ;
      if (NS_FAILED(rv) || (!bExist) ) return NS_ERROR_FILE_TARGET_DOES_NOT_EXIST ;

      // filename of the file attachment
      nsAutoString leafName ;
      pFile->GetLeafName (leafName) ;
      if(NS_FAILED(rv) || leafName.IsEmpty()) return rv ;

      if (!Subject.IsEmpty())
          Subject.AppendLiteral(", ");
      Subject += leafName;

      // create MsgCompose attachment object
      nsCOMPtr<nsIMsgAttachment> attachment = do_CreateInstance(NS_MSGATTACHMENT_CONTRACTID, &rv);
      NS_ENSURE_SUCCESS(rv, rv);

      nsDependentString fileNameNative(leafName.get());
      rv = pFile->CopyTo(pTempDir, fileNameNative);
      if (NS_FAILED(rv)) return rv ;

      // now turn pTempDir into a full file path to the temp file
      pTempDir->Append(fileNameNative);

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

      // now set the attachment object
      nsCAutoString pURL ;
      NS_GetURLSpecFromFile(pTempDir, pURL);
      attachment->SetUrl(pURL.get()) ;

      // add the attachment
      rv = aCompFields->AddAttachment (attachment);
      if (NS_FAILED(rv)) return rv ;
    }

    rv = aCompFields->SetBody(Subject) ;
  }

  return rv ;
}
Esempio n. 14
0
nsresult nsMapiHook::HandleAttachments (nsIMsgCompFields * aCompFields, PRInt32 aFileCount,
                                        lpnsMapiFileDesc aFiles, BOOL aIsUnicode)
{
    nsresult rv = NS_OK ;

    nsCAutoString Attachments ;
    nsCAutoString TempFiles ;

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

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

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

            //Temp Directory
            nsCOMPtr <nsIFile> pTempFileDir;
            NS_GetSpecialDirectory(NS_OS_TEMP_DIR, getter_AddRefs(pTempFileDir));
            nsCOMPtr <nsILocalFile> pTempDir = do_QueryInterface(pTempFileDir);

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

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

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

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

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

            // create MsgCompose attachment object
            nsCOMPtr<nsIMsgAttachment> attachment = do_CreateInstance(NS_MSGATTACHMENT_CONTRACTID, &rv);
            NS_ENSURE_SUCCESS(rv, rv);
            attachment->SetTemporary(PR_TRUE); // this one is a temp file so set the flag for MsgCompose

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

            // add the attachment
            rv = aCompFields->AddAttachment (attachment);
            if (NS_FAILED(rv))
              PR_LOG(MAPI, PR_LOG_DEBUG, ("nsMapiHook::HandleAttachments: AddAttachment rv =  %lx\n", rv));
        }
    }
    return rv ;
}
Esempio n. 15
0
nsresult nsDefaultURIFixup::ConvertFileToStringURI(const nsACString& aIn,
                                                   nsCString& aOut)
{
    PRBool attemptFixup = PR_FALSE;

#if defined(XP_WIN) || defined(XP_OS2)
    // Check for \ in the url-string or just a drive (PC)
    if(kNotFound != aIn.FindChar('\\') ||
       (aIn.Length() == 2 && (aIn.Last() == ':' || aIn.Last() == '|')))
    {
        attemptFixup = PR_TRUE;
    }
#elif defined(XP_UNIX) || defined(XP_BEOS)
    // Check if it starts with / (UNIX)
    if(aIn.First() == '/')
    {
        attemptFixup = PR_TRUE;
    }
#else
    // Do nothing (All others for now) 
#endif

    if (attemptFixup)
    {
        // Test if this is a valid path by trying to create a local file
        // object. The URL of that is returned if successful.

        // NOTE: Please be sure to check that the call to NS_NewLocalFile
        //       rejects bad file paths when using this code on a new
        //       platform.

        nsCOMPtr<nsILocalFile> filePath;
        nsresult rv;

        // this is not the real fix but a temporary fix
        // in order to really fix the problem, we need to change the 
        // nsICmdLineService interface to use wstring to pass paramenters 
        // instead of string since path name and other argument could be
        // in non ascii.(see bug 87127) Since it is too risky to make interface change right
        // now, we decide not to do so now.
        // Therefore, the aIn we receive here maybe already in damage form
        // (e.g. treat every bytes as ISO-8859-1 and cast up to PRUnichar
        //  while the real data could be in file system charset )
        // we choice the following logic which will work for most of the case.
        // Case will still failed only if it meet ALL the following condiction:
        //    1. running on CJK, Russian, or Greek system, and 
        //    2. user type it from URL bar
        //    3. the file name contains character in the range of 
        //       U+00A1-U+00FF but encode as different code point in file
        //       system charset (e.g. ACP on window)- this is very rare case
        // We should remove this logic and convert to File system charset here
        // once we change nsICmdLineService to use wstring and ensure
        // all the Unicode data come in is correctly converted.
        // XXXbz nsICmdLineService doesn't hand back unicode, so in some cases
        // what we have is actually a "utf8" version of a "utf16" string that's
        // actually byte-expanded native-encoding data.  Someone upstream needs
        // to stop using AssignWithConversion and do things correctly.  See bug
        // 58866 for what happens if we remove this
        // PossiblyByteExpandedFileName check.
        NS_ConvertUTF8toUTF16 in(aIn);
        if (PossiblyByteExpandedFileName(in)) {
          // removes high byte
          rv = NS_NewNativeLocalFile(NS_LossyConvertUTF16toASCII(in), PR_FALSE, getter_AddRefs(filePath));
        }
        else {
          // input is unicode
          rv = NS_NewLocalFile(in, PR_FALSE, getter_AddRefs(filePath));
        }

        if (NS_SUCCEEDED(rv))
        {
            NS_GetURLSpecFromFile(filePath, aOut);
            return NS_OK;
        }
    }

    return NS_ERROR_FAILURE;
}
Esempio n. 16
0
nsresult nsEudoraEditor::GetEmbeddedObjects(nsISupportsArray ** aNodeList)
{
    NS_ENSURE_ARG_POINTER(aNodeList);

    // Check to see if we were already called
    if (m_EmbeddedObjectList != nsnull)
    {
        *aNodeList = m_EmbeddedObjectList;
        return NS_OK;
    }

    // Create array in m_EmbeddedObjectList
    nsresult rv = NS_NewISupportsArray( getter_AddRefs(m_EmbeddedObjectList) );
    NS_ENSURE_SUCCESS(rv, rv);

    // Return m_EmbeddedObjectList in aNodeList and increment ref count - caller
    // assumes that we incremented the ref count.
    NS_IF_ADDREF(*aNodeList = m_EmbeddedObjectList);

    // Create the embedded folder spec
    nsCOMPtr<nsIFile>   embeddedFolderSpec;
    // Create the embedded image spec
    nsCOMPtr<nsIFile>   embeddedImageSpec;

    // Fill in the details for the embedded folder spec - "Embedded" folder
    // inside of the mail folder. We don't bother to check to see if the embedded
    // folder exists, because it seems to me that would only save time in the
    // unexpected case where it doesn't exist. Keep in mind that we will be checking
    // for the existence of any embedded images anyway - if the folder doesn't
    // exist that check will fail.
    rv = m_pMailImportLocation->Clone(getter_AddRefs(embeddedFolderSpec));
    NS_ENSURE_SUCCESS(rv, rv);
    embeddedFolderSpec->AppendNative(NS_LITERAL_CSTRING("Embedded"));

    // Look for the start of the last closing tag so that we only search for
    // valid "Embedded Content" lines. (In practice this is not super important,
    // but there were some proof of concept exploits at one point where "Embedded
    // Content" lines were faked in the body of messages).
    PRInt32     startLastClosingTag = m_body.RFind("</");
    if (startLastClosingTag == kNotFound)
        startLastClosingTag = 0;
    bool        foundEmbeddedContentLines = false;

    // Search for various translations of "Embedded Content" - as of this writing only
    // one that I know of, but then again I didn't realize that Eudora translators had
    // ever translated "Attachment Converted" as suggested by other Eudora importing code.
    for (PRInt32 i = 0; *sEudoraEmbeddedContentLines[i] != '\0'; i++)
    {
        // Search for "Embedded Content: " lines starting after last closing tag (if any)
        PRInt32   startEmbeddedContentLine = startLastClosingTag;
        PRInt32   lenEmbeddedContentTag = strlen(sEudoraEmbeddedContentLines[i]);

        while ( (startEmbeddedContentLine = m_body.Find(sEudoraEmbeddedContentLines[i], true, startEmbeddedContentLine+1)) != kNotFound )
        {
            // Found this translation of "Embedded Content" - remember that so that we don't
            // bother looking for any other translations.
            foundEmbeddedContentLines = true;

            // Extract the file name from the embedded content line
            PRInt32   startFileName = startEmbeddedContentLine + lenEmbeddedContentTag;
            PRInt32   endFileName = m_body.Find(":", false, startFileName);

            // Create the file spec for the embedded image
            embeddedFolderSpec->Clone(getter_AddRefs(embeddedImageSpec));
            embeddedImageSpec->Append(Substring(m_body, startFileName, endFileName - startFileName));

            // Verify that the embedded image spec exists and is a file
            bool      isFile = false;
            bool      exists = false;
            if ( NS_FAILED(embeddedImageSpec->Exists( &exists)) || NS_FAILED(embeddedImageSpec->IsFile(&isFile)) )
                continue;
            if (!exists || !isFile)
                continue;

            // Extract CID hash from the embedded content line
            PRInt32     cidHashValue;
            PRInt32     startCIDHash = m_body.Find(",", false, endFileName);
            if (startCIDHash != kNotFound)
            {
                startCIDHash++;
                PRInt32   endCIDHash = m_body.Find(",", false, startCIDHash);

                if (endCIDHash != kNotFound)
                {
                    nsString    cidHash;
                    cidHash.Assign(Substring(m_body, startCIDHash, endCIDHash - startCIDHash));

                    if ( !cidHash.IsEmpty() )
                    {
                        // Convert CID hash string to numeric value
                        nsresult aErrorCode;
                        cidHashValue = cidHash.ToInteger(&aErrorCode, 16);
                    }
                }
            }

            // Get the URL for the embedded image
            nsCString     embeddedImageURL;
            rv = NS_GetURLSpecFromFile(embeddedImageSpec, embeddedImageURL);
            NS_ENSURE_SUCCESS(rv, rv);

            NS_ConvertASCIItoUTF16 srcUrl(embeddedImageURL);
            nsString cid;
            // We're going to remember the original cid in the image element,
            // which the send code will retrieve as the kMozCIDAttrName property.
            GetEmbeddedImageCID(cidHashValue, srcUrl, cid);
            // Create the embedded image node
            nsEudoraHTMLImageElement *image =
                new nsEudoraHTMLImageElement(srcUrl, cid);

            nsCOMPtr<nsIDOMHTMLImageElement>   imageNode;
            image->QueryInterface( NS_GET_IID(nsIDOMHTMLImageElement), getter_AddRefs(imageNode) );

            // Append the embedded image node to the list
            (*aNodeList)->AppendElement(imageNode);

            PRInt32   endEmbeddedContentLine = m_body.Find("\r\n", true, startEmbeddedContentLine+1);
            if (endEmbeddedContentLine != kNotFound)
            {
                // We recognized the "Embedded Content" line correctly and found the associated image.
                // Remove the Eudora specific line about it now.
                m_body.Cut(startEmbeddedContentLine, endEmbeddedContentLine - startEmbeddedContentLine + 2);

                // Backup by one to correct where we start looking for the next line
                startEmbeddedContentLine--;
            }
        }

        // Assume at most one translation for "Embedded Content: " in a given message
        if (foundEmbeddedContentLines)
            break;
    }

    return NS_OK;
}
nsresult
mozJSComponentLoader::GlobalForLocation(nsILocalFile *aComponent,
                                        JSObject **aGlobal,
                                        char **aLocation)
{
    nsresult rv;

    JSPrincipals* jsPrincipals = nsnull;
    JSCLContextHelper cx(mContext);

#ifndef XPCONNECT_STANDALONE
    rv = mSystemPrincipal->GetJSPrincipals(cx, &jsPrincipals);
    NS_ENSURE_SUCCESS(rv, rv);

    JSPrincipalsHolder princHolder(mContext, jsPrincipals);
#endif

    nsCOMPtr<nsIXPCScriptable> backstagePass;
    rv = mRuntimeService->GetBackstagePass(getter_AddRefs(backstagePass));
    NS_ENSURE_SUCCESS(rv, rv);

    JSCLAutoErrorReporterSetter aers(cx, mozJSLoaderErrorReporter);

    nsCOMPtr<nsIXPConnect> xpc =
        do_GetService(kXPConnectServiceContractID, &rv);
    NS_ENSURE_SUCCESS(rv, rv);

    // Make sure InitClassesWithNewWrappedGlobal() installs the
    // backstage pass as the global in our compilation context.
    JS_SetGlobalObject(cx, nsnull);

    nsCOMPtr<nsIXPConnectJSObjectHolder> holder;
    rv = xpc->InitClassesWithNewWrappedGlobal(cx, backstagePass,
                                              NS_GET_IID(nsISupports),
                                              nsIXPConnect::
                                                  FLAG_SYSTEM_GLOBAL_OBJECT,
                                              getter_AddRefs(holder));
    NS_ENSURE_SUCCESS(rv, rv);

    JSObject *global;
    rv = holder->GetJSObject(&global);
    NS_ENSURE_SUCCESS(rv, rv);

    if (!JS_DefineFunctions(cx, global, gGlobalFun)) {
        return NS_ERROR_FAILURE;
    }

    nsCOMPtr<nsIXPConnectJSObjectHolder> locationHolder;
    rv = xpc->WrapNative(cx, global, aComponent,
                         NS_GET_IID(nsILocalFile),
                         getter_AddRefs(locationHolder));
    NS_ENSURE_SUCCESS(rv, rv);

    JSObject *locationObj;
    rv = locationHolder->GetJSObject(&locationObj);
    NS_ENSURE_SUCCESS(rv, rv);

    if (!JS_DefineProperty(cx, global, "__LOCATION__",
                           OBJECT_TO_JSVAL(locationObj), nsnull, nsnull, 0)) {
        return NS_ERROR_FAILURE;
    }

    nsCAutoString nativePath;
    // Quick hack to unbust XPCONNECT_STANDALONE.
    // This leaves the jsdebugger with a non-URL pathname in the 
    // XPCONNECT_STANDALONE case - but at least it builds and runs otherwise.
    // See: http://bugzilla.mozilla.org/show_bug.cgi?id=121438
#ifdef XPCONNECT_STANDALONE
    localFile->GetNativePath(nativePath);
#else
    NS_GetURLSpecFromFile(aComponent, nativePath);
#endif

    // Before compiling the script, first check to see if we have it in
    // the fastload file.  Note: as a rule, fastload errors are not fatal
    // to loading the script, since we can always slow-load.
    nsCOMPtr<nsIFastLoadService> flSvc = do_GetFastLoadService(&rv);

    // Save the old state and restore it upon return
    FastLoadStateHolder flState(flSvc);
    PRBool fastLoading = PR_FALSE;

    if (NS_SUCCEEDED(rv)) {
        rv = StartFastLoad(flSvc);
        if (NS_SUCCEEDED(rv)) {
            fastLoading = PR_TRUE;
        }
    }

    nsCOMPtr<nsIURI> uri;
    rv = NS_NewURI(getter_AddRefs(uri), nativePath);
    NS_ENSURE_SUCCESS(rv, rv);

    JSScript *script = nsnull;

    if (fastLoading) {
        rv = ReadScript(flSvc, nativePath.get(), uri, cx, &script);
        if (NS_SUCCEEDED(rv)) {
            LOG(("Successfully loaded %s from fastload\n", nativePath.get()));
            fastLoading = PR_FALSE; // no need to write out the script
        } else if (rv == NS_ERROR_NOT_AVAILABLE) {
            // This is ok, it just means the script is not yet in the
            // fastload file.
            rv = NS_OK;
        } else {
            LOG(("Failed to deserialize %s\n", nativePath.get()));

            // Remove the fastload file, it may be corrupted.
            LOG(("Invalid fastload file detected, removing it\n"));
            nsCOMPtr<nsIObjectOutputStream> objectOutput;
            flSvc->GetOutputStream(getter_AddRefs(objectOutput));
            if (objectOutput) {
                flSvc->SetOutputStream(nsnull);
                objectOutput->Close();
            }
            nsCOMPtr<nsIObjectInputStream> objectInput;
            flSvc->GetInputStream(getter_AddRefs(objectInput));
            if (objectInput) {
                flSvc->SetInputStream(nsnull);
                objectInput->Close();
            }
            if (mFastLoadFile) {
                mFastLoadFile->Remove(PR_FALSE);
            }
            fastLoading = PR_FALSE;
        }
    }


    if (!script || NS_FAILED(rv)) {
        // The script wasn't in the fastload cache, so compile it now.
        LOG(("Slow loading %s\n", nativePath.get()));

#ifdef HAVE_PR_MEMMAP
        PRInt64 fileSize;
        rv = aComponent->GetFileSize(&fileSize);
        if (NS_FAILED(rv))
            return rv;

        PRInt64 maxSize;
        LL_UI2L(maxSize, PR_UINT32_MAX);
        if (LL_CMP(fileSize, >, maxSize)) {
            NS_ERROR("file too large");
            return NS_ERROR_FAILURE;
        }

        PRFileDesc *fileHandle;
        rv = aComponent->OpenNSPRFileDesc(PR_RDONLY, 0, &fileHandle);
        NS_ENSURE_SUCCESS(rv, rv);

        // Make sure the file is closed, no matter how we return.
        FileAutoCloser fileCloser(fileHandle);

        PRFileMap *map = PR_CreateFileMap(fileHandle, fileSize,
                                          PR_PROT_READONLY);
        if (!map) {
            NS_ERROR("Failed to create file map");
            return NS_ERROR_FAILURE;
        }

        // Make sure the file map is closed, no matter how we return.
        FileMapAutoCloser mapCloser(map);

        PRUint32 fileSize32;
        LL_L2UI(fileSize32, fileSize);

        char *buf = static_cast<char*>(PR_MemMap(map, 0, fileSize32));
        if (!buf) {
            NS_WARNING("Failed to map file");
            return NS_ERROR_FAILURE;
        }

        script = JS_CompileScriptForPrincipals(cx, global,
                                               jsPrincipals,
                                               buf, fileSize32,
                                               nativePath.get(), 1);
        PR_MemUnmap(buf, fileSize32);

#else  /* HAVE_PR_MEMMAP */

        /**
         * No memmap implementation, so fall back to using
         * JS_CompileFileHandleForPrincipals().
         */

        FILE *fileHandle;
        rv = aComponent->OpenANSIFileDesc("r", &fileHandle);
        NS_ENSURE_SUCCESS(rv, rv);

        script = JS_CompileFileHandleForPrincipals(cx, global,
                                                   nativePath.get(),
                                                   fileHandle, jsPrincipals);

        /* JS will close the filehandle after compilation is complete. */

#endif /* HAVE_PR_MEMMAP */
    }
Esempio n. 18
0
//----------------------------------------------------------------------------------------
OSErr nsMacCommandLine::HandleOpenOneDoc(const FSSpec& inFileSpec, OSType inFileType)
//----------------------------------------------------------------------------------------
{
  nsCOMPtr<nsILocalFileMac> inFile;
  nsresult rv = NS_NewLocalFileWithFSSpec(&inFileSpec, PR_TRUE, getter_AddRefs(inFile));
  if (NS_FAILED(rv))
    return errAEEventNotHandled;

  if (!mStartedUp)
  {
    // Is it the right type to be a command-line file?
    if (inFileType == 'TEXT' || inFileType == 'CMDL')
    {
      // Can we open the file?
      FILE *fp = 0;
      rv = inFile->OpenANSIFileDesc("r", &fp);
      if (NS_SUCCEEDED(rv))
      {
        Boolean foundArgs = false;
        Boolean foundEnv = false;
        char chars[1024];
        static const char kCommandLinePrefix[] = "ARGS:";
        static const char kEnvVarLinePrefix[] = "ENV:";

        while (ReadLine(fp, chars, sizeof(chars)) != -1)
        {       // See if there are any command line or environment var settings
          if (PL_strstr(chars, kCommandLinePrefix) == chars)
          {
            (void)AddToCommandLine(chars + sizeof(kCommandLinePrefix) - 1);
            foundArgs = true;
          }
          else if (PL_strstr(chars, kEnvVarLinePrefix) == chars)
          {
            (void)AddToEnvironmentVars(chars + sizeof(kEnvVarLinePrefix) - 1);
            foundEnv = true;
          }
        }

        fclose(fp);
#ifndef XP_MACOSX
        // If we found any environment vars we need to re-init NSPR's logging
        // so that it knows what the new vars are
        if (foundEnv)
          PR_Init_Log();
#endif
        // If we found a command line or environment vars we want to return now
        // raather than trying to open the file as a URL
        if (foundArgs || foundEnv)
          return noErr;
      }
    }
    // If it's not a command-line argument, and we are starting up the application,
    // add a command-line "-url" argument to the global list. This means that if
    // the app is opened with documents on the mac, they'll be handled the same
    // way as if they had been typed on the command line in Unix or DOS.
    return AddToCommandLine("-url", inFileSpec);
  }

  // Final case: we're not just starting up. How do we handle this?
  nsCAutoString specBuf;
  rv = NS_GetURLSpecFromFile(inFile, specBuf);
  if (NS_FAILED(rv))
    return errAEEventNotHandled;
  
  return OpenURL(specBuf.get());
}