/* static */ already_AddRefed<GetFileOrDirectoryTaskParent> GetFileOrDirectoryTaskParent::Create(FileSystemBase* aFileSystem, const FileSystemGetFileOrDirectoryParams& aParam, FileSystemRequestParent* aParent, ErrorResult& aRv) { MOZ_ASSERT(XRE_IsParentProcess(), "Only call from parent process!"); AssertIsOnBackgroundThread(); MOZ_ASSERT(aFileSystem); RefPtr<GetFileOrDirectoryTaskParent> task = new GetFileOrDirectoryTaskParent(aFileSystem, aParam, aParent); aRv = NS_NewLocalFile(aParam.realPath(), true, getter_AddRefs(task->mTargetPath)); if (NS_WARN_IF(aRv.Failed())) { return nullptr; } return task.forget(); }
NS_IMETHODIMP nsSound::PlaySystemSound(const nsAString &aSoundAlias) { if (NS_IsMozAliasSound(aSoundAlias)) { NS_WARNING("nsISound::playSystemSound is called with \"_moz_\" events, they are obsolete, use nsISound::playEventSound instead"); uint32_t eventId; if (aSoundAlias.Equals(NS_SYSSOUND_ALERT_DIALOG)) eventId = EVENT_ALERT_DIALOG_OPEN; else if (aSoundAlias.Equals(NS_SYSSOUND_CONFIRM_DIALOG)) eventId = EVENT_CONFIRM_DIALOG_OPEN; else if (aSoundAlias.Equals(NS_SYSSOUND_MAIL_BEEP)) eventId = EVENT_NEW_MAIL_RECEIVED; else if (aSoundAlias.Equals(NS_SYSSOUND_MENU_EXECUTE)) eventId = EVENT_MENU_EXECUTE; else if (aSoundAlias.Equals(NS_SYSSOUND_MENU_POPUP)) eventId = EVENT_MENU_POPUP; else return NS_OK; return PlayEventSound(eventId); } nsresult rv; nsCOMPtr <nsIURI> fileURI; // create a nsIFile and then a nsIFileURL from that nsCOMPtr <nsIFile> soundFile; rv = NS_NewLocalFile(aSoundAlias, true, getter_AddRefs(soundFile)); NS_ENSURE_SUCCESS(rv,rv); rv = NS_NewFileURI(getter_AddRefs(fileURI), soundFile); NS_ENSURE_SUCCESS(rv,rv); nsCOMPtr<nsIFileURL> fileURL = do_QueryInterface(fileURI,&rv); NS_ENSURE_SUCCESS(rv,rv); rv = Play(fileURL); return rv; }
//---------------------------------------------------------------------------------------- static nsresult GetWindowsFolder(int folder, nsILocalFile** aFile) //---------------------------------------------------------------------------------------- { #ifdef WINCE #define SHGetSpecialFolderPathW SHGetSpecialFolderPath #ifndef WINCE_WINDOWS_MOBILE if (folder == CSIDL_APPDATA || folder == CSIDL_LOCAL_APPDATA) folder = CSIDL_PROFILE; #endif #endif WCHAR path_orig[MAX_PATH + 3]; WCHAR *path = path_orig+1; HRESULT result = SHGetSpecialFolderPathW(NULL, path, folder, true); if (!SUCCEEDED(result)) return NS_ERROR_FAILURE; // Append the trailing slash int len = wcslen(path); if (len > 1 && path[len - 1] != L'\\') { path[len] = L'\\'; path[++len] = L'\0'; } #if defined(WINCE) && !defined(WINCE_WINDOWS_MOBILE) // sometimes CSIDL_PROFILE shows up without a root slash if (folder == CSIDL_PROFILE && path[0] != '\\') { path_orig[0] = '\\'; path = path_orig; len++; } #endif return NS_NewLocalFile(nsDependentString(path, len), PR_TRUE, aFile); }
bool FileSystemBase::GetRealPath(BlobImpl* aFile, nsIFile** aPath) const { AssertIsOnOwningThread(); MOZ_ASSERT(aFile, "aFile Should not be null."); MOZ_ASSERT(aPath); nsAutoString filePath; ErrorResult rv; aFile->GetMozFullPathInternal(filePath, rv); if (NS_WARN_IF(rv.Failed())) { rv.SuppressException(); return false; } rv = NS_NewLocalFile(filePath, true, aPath); if (NS_WARN_IF(rv.Failed())) { rv.SuppressException(); return false; } return true; }
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); }
nsresult MediaEngineDefaultVideoSource::Snapshot(uint32_t aDuration, nsIDOMFile** aFile) { *aFile = nullptr; #ifndef MOZ_WIDGET_ANDROID return NS_ERROR_NOT_IMPLEMENTED; #else if (!AndroidBridge::Bridge()) { return NS_ERROR_UNEXPECTED; } nsAutoString filePath; AndroidBridge::Bridge()->ShowFilePickerForMimeType(filePath, NS_LITERAL_STRING("image/*")); nsCOMPtr<nsIFile> file; nsresult rv = NS_NewLocalFile(filePath, false, getter_AddRefs(file)); NS_ENSURE_SUCCESS(rv, rv); NS_ADDREF(*aFile = new nsDOMFileFile(file)); return NS_OK; #endif }
static bool GetFileBase(const nsAString& aPluginPath, #if defined(XP_MACOSX) && defined(MOZ_GMP_SANDBOX) nsCOMPtr<nsIFile>& aLibDirectory, #endif nsCOMPtr<nsIFile>& aFileBase, nsAutoString& aBaseName) { nsresult rv = NS_NewLocalFile(aPluginPath, true, getter_AddRefs(aFileBase)); if (NS_FAILED(rv)) { return false; } #if defined(XP_MACOSX) && defined(MOZ_GMP_SANDBOX) if (NS_FAILED(aFileBase->Clone(getter_AddRefs(aLibDirectory)))) { return false; } #endif nsCOMPtr<nsIFile> parent; rv = aFileBase->GetParent(getter_AddRefs(parent)); if (NS_FAILED(rv)) { return false; } nsAutoString parentLeafName; rv = parent->GetLeafName(parentLeafName); if (NS_FAILED(rv)) { return false; } aBaseName = Substring(parentLeafName, 4, parentLeafName.Length() - 1); return true; }
void GetFileOrDirectoryTaskChild::SetSuccessRequestResult(const FileSystemResponseValue& aValue, ErrorResult& aRv) { MOZ_ASSERT(NS_IsMainThread(), "Only call on main thread!"); switch (aValue.type()) { case FileSystemResponseValue::TFileSystemFileResponse: { FileSystemFileResponse r = aValue; RefPtr<BlobImpl> blobImpl = static_cast<BlobChild*>(r.blobChild())->GetBlobImpl(); MOZ_ASSERT(blobImpl); mResultFile = File::Create(mFileSystem->GetParentObject(), blobImpl); MOZ_ASSERT(mResultFile); break; } case FileSystemResponseValue::TFileSystemDirectoryResponse: { FileSystemDirectoryResponse r = aValue; nsCOMPtr<nsIFile> file; aRv = NS_NewLocalFile(r.realPath(), true, getter_AddRefs(file)); if (NS_WARN_IF(aRv.Failed())) { return; } mResultDirectory = Directory::Create(mFileSystem->GetParentObject(), file, mFileSystem); MOZ_ASSERT(mResultDirectory); break; } default: { MOZ_CRASH("not reached"); break; } } }
NS_IMETHODIMP nsPluginDirServiceProvider::GetFile(const char *charProp, PRBool *persistant, nsIFile **_retval) { nsCOMPtr<nsILocalFile> localFile; nsresult rv = NS_ERROR_FAILURE; NS_ENSURE_ARG(charProp); *_retval = nsnull; *persistant = PR_FALSE; nsCOMPtr<nsIPrefBranch> prefs(do_GetService(NS_PREFSERVICE_CONTRACTID)); if (!prefs) return NS_ERROR_FAILURE; if (nsCRT::strcmp(charProp, NS_WIN_4DOTX_SCAN_KEY) == 0) { // Check our prefs to see if scanning the 4.x folder has been // explictly overriden failure to get the pref is okay, we'll do // what we've been doing -- a filtered scan PRBool bScan4x; if (NS_SUCCEEDED(prefs->GetBoolPref(NS_WIN_4DOTX_SCAN_KEY, &bScan4x)) && !bScan4x) { return NS_ERROR_FAILURE; } // Look for the plugin folder that the user has in their // Communicator 4x install HKEY keyloc; long result; DWORD type; WCHAR szKey[_MAX_PATH] = L"Software\\Netscape\\Netscape Navigator"; WCHAR path[_MAX_PATH]; result = ::RegOpenKeyExW(HKEY_LOCAL_MACHINE, szKey, 0, KEY_READ, &keyloc); if (result == ERROR_SUCCESS) { WCHAR current_version[80]; DWORD length = NS_ARRAY_LENGTH(current_version); result = ::RegQueryValueExW(keyloc, L"CurrentVersion", NULL, &type, (LPBYTE)¤t_version, &length); ::RegCloseKey(keyloc); wcscat(szKey, L"\\"); wcscat(szKey, current_version); wcscat(szKey, L"\\Main"); result = ::RegOpenKeyExW(HKEY_LOCAL_MACHINE, szKey, 0, KEY_READ, &keyloc); if (result == ERROR_SUCCESS) { DWORD pathlen = NS_ARRAY_LENGTH(path); result = ::RegQueryValueExW(keyloc, L"Plugins Directory", NULL, &type, (LPBYTE)&path, &pathlen); if (result == ERROR_SUCCESS) { rv = NS_NewLocalFile(nsDependentString(path), PR_TRUE, getter_AddRefs(localFile)); } ::RegCloseKey(keyloc); } } } else if (nsCRT::strcmp(charProp, NS_WIN_JRE_SCAN_KEY) == 0) { nsXPIDLCString strVer; if (NS_FAILED(prefs->GetCharPref(charProp, getter_Copies(strVer)))) return NS_ERROR_FAILURE; verBlock minVer; TranslateVersionStr(NS_ConvertASCIItoUTF16(strVer).get(), &minVer); // Look for the Java OJI plugin via the JRE install path HKEY baseloc; HKEY keyloc; HKEY entryloc; FILETIME modTime; DWORD type; DWORD index = 0; DWORD numChars = _MAX_PATH; DWORD pathlen; verBlock maxVer; ClearVersion(&maxVer); WCHAR curKey[_MAX_PATH] = L"Software\\JavaSoft\\Java Runtime Environment"; WCHAR path[_MAX_PATH]; // Add + 15 to prevent buffer overrun when adding \bin (+ optionally // \new_plugin) #define JAVA_PATH_SIZE _MAX_PATH + 15 WCHAR newestPath[JAVA_PATH_SIZE]; const WCHAR mozPath[_MAX_PATH] = L"Software\\mozilla.org\\Mozilla"; WCHAR browserJavaVersion[_MAX_PATH]; newestPath[0] = 0; LONG result = ::RegOpenKeyExW(HKEY_LOCAL_MACHINE, curKey, 0, KEY_READ, &baseloc); if (ERROR_SUCCESS != result) return NS_ERROR_FAILURE; // Look for "BrowserJavaVersion" if (ERROR_SUCCESS != ::RegQueryValueExW(baseloc, L"BrowserJavaVersion", NULL, NULL, (LPBYTE)&browserJavaVersion, &numChars)) browserJavaVersion[0] = 0; // We must enumerate through the keys because what if there is // more than one version? do { path[0] = 0; numChars = _MAX_PATH; pathlen = NS_ARRAY_LENGTH(path); result = ::RegEnumKeyExW(baseloc, index, curKey, &numChars, NULL, NULL, NULL, &modTime); index++; // Skip major.minor as it always points to latest in its family numChars = 0; for (WCHAR *p = curKey; *p; p++) { if (*p == '.') { numChars++; } } if (numChars < 2) continue; if (ERROR_SUCCESS == result) { if (ERROR_SUCCESS == ::RegOpenKeyExW(baseloc, curKey, 0, KEY_QUERY_VALUE, &keyloc)) { // We have a sub key if (ERROR_SUCCESS == ::RegQueryValueExW(keyloc, L"JavaHome", NULL, &type, (LPBYTE)&path, &pathlen)) { verBlock curVer; TranslateVersionStr(curKey, &curVer); if (CompareVersion(curVer, minVer) >= 0) { if (!wcsncmp(browserJavaVersion, curKey, _MAX_PATH)) { wcscpy(newestPath, path); ::RegCloseKey(keyloc); break; } if (CompareVersion(curVer, maxVer) >= 0) { wcscpy(newestPath, path); CopyVersion(&maxVer, &curVer); } } } ::RegCloseKey(keyloc); } } } while (ERROR_SUCCESS == result); ::RegCloseKey(baseloc); static const WCHAR kMozillaVersion[] = NS_L(MOZILLA_VERSION); // If nothing is found, then don't add \bin dir and don't set // CurrentVersion for Mozilla if (newestPath[0] != 0) { if (ERROR_SUCCESS == ::RegCreateKeyExW(HKEY_LOCAL_MACHINE, mozPath, 0, NULL, REG_OPTION_NON_VOLATILE, KEY_SET_VALUE|KEY_QUERY_VALUE, NULL, &entryloc, NULL)) { if (ERROR_SUCCESS != ::RegQueryValueExW(entryloc, L"CurrentVersion", 0, NULL, NULL, NULL)) { ::RegSetValueExW(entryloc, L"CurrentVersion", 0, REG_SZ, (const BYTE*) kMozillaVersion, NS_ARRAY_LENGTH(kMozillaVersion)); } ::RegCloseKey(entryloc); } wcscat(newestPath, L"\\bin"); // See whether the "new_plugin" directory exists WCHAR tmpPath[JAVA_PATH_SIZE]; nsCOMPtr<nsILocalFile> tmpFile; wcscpy(tmpPath, newestPath); wcscat(tmpPath, L"\\new_plugin"); rv = NS_NewLocalFile(nsDependentString(tmpPath), PR_TRUE, getter_AddRefs(tmpFile)); if (NS_SUCCEEDED(rv) && tmpFile) { PRBool exists = PR_FALSE; PRBool isDir = PR_FALSE; if (NS_SUCCEEDED(tmpFile->Exists(&exists)) && exists && NS_SUCCEEDED(tmpFile->IsDirectory(&isDir)) && isDir) { // Assume we're supposed to use this as the search // directory for the Java Plug-In instead of the normal // one wcscpy(newestPath, tmpPath); } } rv = NS_NewLocalFile(nsDependentString(newestPath), PR_TRUE, getter_AddRefs(localFile)); } } else if (nsCRT::strcmp(charProp, NS_WIN_QUICKTIME_SCAN_KEY) == 0) { nsXPIDLCString strVer; if (NS_FAILED(prefs->GetCharPref(charProp, getter_Copies(strVer)))) return NS_ERROR_FAILURE; verBlock minVer; TranslateVersionStr(NS_ConvertASCIItoUTF16(strVer).get(), &minVer); // Look for the Quicktime system installation plugins directory HKEY keyloc; long result; DWORD type; verBlock qtVer; ClearVersion(&qtVer); WCHAR path[_MAX_PATH]; DWORD pathlen = NS_ARRAY_LENGTH(path); // First we need to check the version of Quicktime via checking // the EXE's version table if (ERROR_SUCCESS == ::RegOpenKeyExW(HKEY_LOCAL_MACHINE, L"software\\Microsoft\\Windows\\CurrentVersion\\App Paths\\QuickTimePlayer.exe", 0, KEY_READ, &keyloc)) { if (ERROR_SUCCESS == ::RegQueryValueExW(keyloc, NULL, NULL, &type, (LPBYTE)&path, &pathlen)) { GetFileVersion(path, &qtVer); } ::RegCloseKey(keyloc); } if (CompareVersion(qtVer, minVer) < 0) return rv; if (ERROR_SUCCESS == ::RegOpenKeyExW(HKEY_LOCAL_MACHINE, L"software\\Apple Computer, Inc.\\QuickTime", 0, KEY_READ, &keyloc)) { DWORD pathlen = NS_ARRAY_LENGTH(path); result = ::RegQueryValueExW(keyloc, L"InstallDir", NULL, &type, (LPBYTE)&path, &pathlen); wcscat(path, L"\\Plugins"); if (result == ERROR_SUCCESS) rv = NS_NewLocalFile(nsDependentString(path), PR_TRUE, getter_AddRefs(localFile)); ::RegCloseKey(keyloc); } } else if (nsCRT::strcmp(charProp, NS_WIN_WMP_SCAN_KEY) == 0) { nsXPIDLCString strVer; if (NS_FAILED(prefs->GetCharPref(charProp, getter_Copies(strVer)))) return NS_ERROR_FAILURE; verBlock minVer; TranslateVersionStr(NS_ConvertASCIItoUTF16(strVer).get(), &minVer); // Look for Windows Media Player system installation plugins directory HKEY keyloc; DWORD type; verBlock wmpVer; ClearVersion(&wmpVer); WCHAR path[_MAX_PATH]; DWORD pathlen = NS_ARRAY_LENGTH(path); // First we need to check the version of WMP if (ERROR_SUCCESS == ::RegOpenKeyExW(HKEY_LOCAL_MACHINE, L"software\\Microsoft\\Windows\\CurrentVersion\\App Paths\\wmplayer.exe", 0, KEY_READ, &keyloc)) { if (ERROR_SUCCESS == ::RegQueryValueExW(keyloc, NULL, NULL, &type, (LPBYTE)&path, &pathlen)) { GetFileVersion(path, &wmpVer); } ::RegCloseKey(keyloc); } if (CompareVersion(wmpVer, minVer) < 0) return rv; if (ERROR_SUCCESS == ::RegOpenKeyExW(HKEY_LOCAL_MACHINE, L"software\\Microsoft\\MediaPlayer", 0, KEY_READ, &keyloc)) { if (ERROR_SUCCESS == ::RegQueryValueExW(keyloc, L"Installation Directory", NULL, &type, (LPBYTE)&path, &pathlen)) { rv = NS_NewLocalFile(nsDependentString(path), PR_TRUE, getter_AddRefs(localFile)); } ::RegCloseKey(keyloc); } } else if (nsCRT::strcmp(charProp, NS_WIN_ACROBAT_SCAN_KEY) == 0) { nsXPIDLCString strVer; if (NS_FAILED(prefs->GetCharPref(charProp, getter_Copies(strVer)))) { return NS_ERROR_FAILURE; } verBlock minVer; TranslateVersionStr(NS_ConvertASCIItoUTF16(strVer).get(), &minVer); // Look for Adobe Acrobat system installation plugins directory HKEY baseloc; HKEY keyloc; FILETIME modTime; DWORD type; DWORD index = 0; DWORD numChars = _MAX_PATH; DWORD pathlen; verBlock maxVer; ClearVersion(&maxVer); WCHAR curKey[_MAX_PATH] = L"software\\Adobe\\Acrobat Reader"; WCHAR path[_MAX_PATH]; // Add + 8 to prevent buffer overrun when adding \browser WCHAR newestPath[_MAX_PATH + 8]; newestPath[0] = 0; if (ERROR_SUCCESS != ::RegOpenKeyExW(HKEY_LOCAL_MACHINE, curKey, 0, KEY_READ, &baseloc)) { wcscpy(curKey, L"software\\Adobe\\Adobe Acrobat"); if (ERROR_SUCCESS != ::RegOpenKeyExW(HKEY_LOCAL_MACHINE, curKey, 0, KEY_READ, &baseloc)) { return NS_ERROR_FAILURE; } } // We must enumerate through the keys because what if there is // more than one version? LONG result = ERROR_SUCCESS; while (ERROR_SUCCESS == result) { path[0] = 0; numChars = _MAX_PATH; pathlen = NS_ARRAY_LENGTH(path); result = ::RegEnumKeyExW(baseloc, index, curKey, &numChars, NULL, NULL, NULL, &modTime); index++; if (ERROR_SUCCESS == result) { verBlock curVer; TranslateVersionStr(curKey, &curVer); wcscat(curKey, L"\\InstallPath"); if (ERROR_SUCCESS == ::RegOpenKeyExW(baseloc, curKey, 0, KEY_QUERY_VALUE, &keyloc)) { // We have a sub key if (ERROR_SUCCESS == ::RegQueryValueExW(keyloc, NULL, NULL, &type, (LPBYTE)&path, &pathlen)) { if (CompareVersion(curVer, maxVer) >= 0 && CompareVersion(curVer, minVer) >= 0) { wcscpy(newestPath, path); CopyVersion(&maxVer, &curVer); } } ::RegCloseKey(keyloc); } } } ::RegCloseKey(baseloc); if (newestPath[0] != 0) { wcscat(newestPath, L"\\browser"); rv = NS_NewLocalFile(nsDependentString(newestPath), PR_TRUE, getter_AddRefs(localFile)); } } if (localFile && NS_SUCCEEDED(rv)) return CallQueryInterface(localFile, _retval); return rv; }
void GeckoMediaPluginServiceParent::RemoveOnGMPThread(const nsAString& aDirectory, const bool aDeleteFromDisk, const bool aCanDefer) { MOZ_ASSERT(NS_GetCurrentThread() == mGMPThread); LOGD(("%s::%s: %s", __CLASS__, __FUNCTION__, NS_LossyConvertUTF16toASCII(aDirectory).get())); nsCOMPtr<nsIFile> directory; nsresult rv = NS_NewLocalFile(aDirectory, false, getter_AddRefs(directory)); if (NS_WARN_IF(NS_FAILED(rv))) { return; } // Plugin destruction can modify |mPlugins|. Put them aside for now and // destroy them once we're done with |mPlugins|. nsTArray<nsRefPtr<GMPParent>> deadPlugins; bool inUse = false; MutexAutoLock lock(mMutex); for (size_t i = mPlugins.Length() - 1; i < mPlugins.Length(); i--) { nsCOMPtr<nsIFile> pluginpath = mPlugins[i]->GetDirectory(); bool equals; if (NS_FAILED(directory->Equals(pluginpath, &equals)) || !equals) { continue; } nsRefPtr<GMPParent> gmp = mPlugins[i]; if (aDeleteFromDisk && gmp->State() != GMPStateNotLoaded) { // We have to wait for the child process to release its lib handle // before we can delete the GMP. inUse = true; gmp->MarkForDeletion(); if (!mPluginsWaitingForDeletion.Contains(aDirectory)) { mPluginsWaitingForDeletion.AppendElement(aDirectory); } } if (gmp->State() == GMPStateNotLoaded || !aCanDefer) { // GMP not in use or shutdown is being forced; can shut it down now. deadPlugins.AppendElement(gmp); mPlugins.RemoveElementAt(i); } } { MutexAutoUnlock unlock(mMutex); for (auto& gmp : deadPlugins) { gmp->AbortAsyncShutdown(); gmp->CloseActive(true); } } if (aDeleteFromDisk && !inUse) { if (NS_SUCCEEDED(directory->Remove(true))) { mPluginsWaitingForDeletion.RemoveElement(aDirectory); NS_DispatchToMainThread(new NotifyObserversTask("gmp-directory-deleted", nsString(aDirectory)), NS_DISPATCH_NORMAL); } } }
nsresult GetSpecialSystemDirectory(SystemDirectories aSystemSystemDirectory, nsIFile** aFile) { #if defined(XP_WIN) WCHAR path[MAX_PATH]; #else char path[MAXPATHLEN]; #endif switch (aSystemSystemDirectory) { case OS_CurrentWorkingDirectory: #if defined(XP_WIN) if (!_wgetcwd(path, MAX_PATH)) return NS_ERROR_FAILURE; return NS_NewLocalFile(nsDependentString(path), true, aFile); #elif defined(XP_OS2) if (DosQueryPathInfo( ".", FIL_QUERYFULLNAME, path, MAXPATHLEN)) return NS_ERROR_FAILURE; #else if(!getcwd(path, MAXPATHLEN)) return NS_ERROR_FAILURE; #endif #if !defined(XP_WIN) return NS_NewNativeLocalFile(nsDependentCString(path), true, aFile); #endif case OS_DriveDirectory: #if defined (XP_WIN) { PRInt32 len = ::GetWindowsDirectoryW(path, MAX_PATH); if (len == 0) break; if (path[1] == PRUnichar(':') && path[2] == PRUnichar('\\')) path[3] = 0; return NS_NewLocalFile(nsDependentString(path), true, aFile); } #elif defined(XP_OS2) { ULONG ulBootDrive = 0; char buffer[] = " :\\OS2\\"; DosQuerySysInfo( QSV_BOOT_DRIVE, QSV_BOOT_DRIVE, &ulBootDrive, sizeof ulBootDrive); buffer[0] = 'A' - 1 + ulBootDrive; // duh, 1-based index... return NS_NewNativeLocalFile(nsDependentCString(buffer), true, aFile); } #else return NS_NewNativeLocalFile(nsDependentCString("/"), true, aFile); #endif case OS_TemporaryDirectory: #if defined (XP_WIN) { DWORD len = ::GetTempPathW(MAX_PATH, path); if (len == 0) break; return NS_NewLocalFile(nsDependentString(path, len), true, aFile); } #elif defined(XP_OS2) { char *tPath = PR_GetEnv("TMP"); if (!tPath || !*tPath) { tPath = PR_GetEnv("TEMP"); if (!tPath || !*tPath) { // if an OS/2 system has neither TMP nor TEMP defined // then it is severely broken, so this will never happen. return NS_ERROR_UNEXPECTED; } } nsCString tString = nsDependentCString(tPath); if (tString.Find("/", false, 0, -1)) { tString.ReplaceChar('/','\\'); } return NS_NewNativeLocalFile(tString, true, aFile); } #elif defined(MOZ_WIDGET_COCOA) { return GetOSXFolderType(kUserDomain, kTemporaryFolderType, aFile); } #elif defined(XP_UNIX) { static const char *tPath = nullptr; if (!tPath) { tPath = PR_GetEnv("TMPDIR"); if (!tPath || !*tPath) { tPath = PR_GetEnv("TMP"); if (!tPath || !*tPath) { tPath = PR_GetEnv("TEMP"); if (!tPath || !*tPath) { tPath = "/tmp/"; } } } } return NS_NewNativeLocalFile(nsDependentCString(tPath), true, aFile); } #else break; #endif #if defined (XP_WIN) case Win_SystemDirectory: { PRInt32 len = ::GetSystemDirectoryW(path, MAX_PATH); // Need enough space to add the trailing backslash if (!len || len > MAX_PATH - 2) break; path[len] = L'\\'; path[++len] = L'\0'; return NS_NewLocalFile(nsDependentString(path, len), true, aFile); } case Win_WindowsDirectory: { PRInt32 len = ::GetWindowsDirectoryW(path, MAX_PATH); // Need enough space to add the trailing backslash if (!len || len > MAX_PATH - 2) break; path[len] = L'\\'; path[++len] = L'\0'; return NS_NewLocalFile(nsDependentString(path, len), true, aFile); } case Win_ProgramFiles: { return GetWindowsFolder(CSIDL_PROGRAM_FILES, aFile); } case Win_HomeDirectory: { nsresult rv = GetWindowsFolder(CSIDL_PROFILE, aFile); if (NS_SUCCEEDED(rv)) return rv; PRInt32 len; if ((len = ::GetEnvironmentVariableW(L"HOME", path, MAX_PATH)) > 0) { // Need enough space to add the trailing backslash if (len > MAX_PATH - 2) break; path[len] = L'\\'; path[++len] = L'\0'; rv = NS_NewLocalFile(nsDependentString(path, len), true, aFile); if (NS_SUCCEEDED(rv)) return rv; } len = ::GetEnvironmentVariableW(L"HOMEDRIVE", path, MAX_PATH); if (0 < len && len < MAX_PATH) { WCHAR temp[MAX_PATH]; DWORD len2 = ::GetEnvironmentVariableW(L"HOMEPATH", temp, MAX_PATH); if (0 < len2 && len + len2 < MAX_PATH) wcsncat(path, temp, len2); len = wcslen(path); // Need enough space to add the trailing backslash if (len > MAX_PATH - 2) break; path[len] = L'\\'; path[++len] = L'\0'; return NS_NewLocalFile(nsDependentString(path, len), true, aFile); } } case Win_Desktop: { return GetWindowsFolder(CSIDL_DESKTOP, aFile); } case Win_Programs: { return GetWindowsFolder(CSIDL_PROGRAMS, aFile); } case Win_Downloads: { // Defined in KnownFolders.h. GUID folderid_downloads = {0x374de290, 0x123f, 0x4565, {0x91, 0x64, 0x39, 0xc4, 0x92, 0x5e, 0x46, 0x7b}}; nsresult rv = GetKnownFolder(&folderid_downloads, aFile); // On WinXP, there is no downloads folder, default // to 'Desktop'. if(NS_ERROR_FAILURE == rv) { rv = GetWindowsFolder(CSIDL_DESKTOP, aFile); } return rv; } case Win_Controls: { return GetWindowsFolder(CSIDL_CONTROLS, aFile); } case Win_Printers: { return GetWindowsFolder(CSIDL_PRINTERS, aFile); } case Win_Personal: { return GetWindowsFolder(CSIDL_PERSONAL, aFile); } case Win_Favorites: { return GetWindowsFolder(CSIDL_FAVORITES, aFile); } case Win_Startup: { return GetWindowsFolder(CSIDL_STARTUP, aFile); } case Win_Recent: { return GetWindowsFolder(CSIDL_RECENT, aFile); } case Win_Sendto: { return GetWindowsFolder(CSIDL_SENDTO, aFile); } case Win_Bitbucket: { return GetWindowsFolder(CSIDL_BITBUCKET, aFile); } case Win_Startmenu: { return GetWindowsFolder(CSIDL_STARTMENU, aFile); } case Win_Desktopdirectory: { return GetWindowsFolder(CSIDL_DESKTOPDIRECTORY, aFile); } case Win_Drives: { return GetWindowsFolder(CSIDL_DRIVES, aFile); } case Win_Network: { return GetWindowsFolder(CSIDL_NETWORK, aFile); } case Win_Nethood: { return GetWindowsFolder(CSIDL_NETHOOD, aFile); } case Win_Fonts: { return GetWindowsFolder(CSIDL_FONTS, aFile); } case Win_Templates: { return GetWindowsFolder(CSIDL_TEMPLATES, aFile); } case Win_Common_Startmenu: { return GetWindowsFolder(CSIDL_COMMON_STARTMENU, aFile); } case Win_Common_Programs: { return GetWindowsFolder(CSIDL_COMMON_PROGRAMS, aFile); } case Win_Common_Startup: { return GetWindowsFolder(CSIDL_COMMON_STARTUP, aFile); } case Win_Common_Desktopdirectory: { return GetWindowsFolder(CSIDL_COMMON_DESKTOPDIRECTORY, aFile); } case Win_Common_AppData: { return GetWindowsFolder(CSIDL_COMMON_APPDATA, aFile); } case Win_Printhood: { return GetWindowsFolder(CSIDL_PRINTHOOD, aFile); } case Win_Cookies: { return GetWindowsFolder(CSIDL_COOKIES, aFile); } case Win_Appdata: { nsresult rv = GetWindowsFolder(CSIDL_APPDATA, aFile); if (NS_FAILED(rv)) rv = GetRegWindowsAppDataFolder(false, aFile); return rv; } case Win_LocalAppdata: { nsresult rv = GetWindowsFolder(CSIDL_LOCAL_APPDATA, aFile); if (NS_FAILED(rv)) rv = GetRegWindowsAppDataFolder(true, aFile); return rv; } #endif // XP_WIN #if defined(XP_UNIX) case Unix_LocalDirectory: return NS_NewNativeLocalFile(nsDependentCString("/usr/local/netscape/"), true, aFile); case Unix_LibDirectory: return NS_NewNativeLocalFile(nsDependentCString("/usr/local/lib/netscape/"), true, aFile); case Unix_HomeDirectory: return GetUnixHomeDir(aFile); case Unix_XDG_Desktop: case Unix_XDG_Documents: case Unix_XDG_Download: case Unix_XDG_Music: case Unix_XDG_Pictures: case Unix_XDG_PublicShare: case Unix_XDG_Templates: case Unix_XDG_Videos: return GetUnixXDGUserDirectory(aSystemSystemDirectory, aFile); #endif #ifdef XP_OS2 case OS2_SystemDirectory: { ULONG ulBootDrive = 0; char buffer[] = " :\\OS2\\System\\"; DosQuerySysInfo( QSV_BOOT_DRIVE, QSV_BOOT_DRIVE, &ulBootDrive, sizeof ulBootDrive); buffer[0] = 'A' - 1 + ulBootDrive; // duh, 1-based index... return NS_NewNativeLocalFile(nsDependentCString(buffer), true, aFile); } case OS2_OS2Directory: { ULONG ulBootDrive = 0; char buffer[] = " :\\OS2\\"; DosQuerySysInfo( QSV_BOOT_DRIVE, QSV_BOOT_DRIVE, &ulBootDrive, sizeof ulBootDrive); buffer[0] = 'A' - 1 + ulBootDrive; // duh, 1-based index... return NS_NewNativeLocalFile(nsDependentCString(buffer), true, aFile); } case OS2_HomeDirectory: { nsresult rv; char *tPath = PR_GetEnv("MOZILLA_HOME"); char buffer[CCHMAXPATH]; /* If MOZILLA_HOME is not set, use GetCurrentProcessDirectory */ /* To ensure we get a long filename system */ if (!tPath || !*tPath) { PPIB ppib; PTIB ptib; DosGetInfoBlocks( &ptib, &ppib); DosQueryModuleName( ppib->pib_hmte, CCHMAXPATH, buffer); *strrchr( buffer, '\\') = '\0'; // XXX DBCS misery tPath = buffer; } rv = NS_NewNativeLocalFile(nsDependentCString(tPath), true, aFile); PrfWriteProfileString(HINI_USERPROFILE, "Mozilla", "Home", tPath); return rv; } case OS2_DesktopDirectory: { char szPath[CCHMAXPATH + 1]; BOOL fSuccess; fSuccess = WinQueryActiveDesktopPathname (szPath, sizeof(szPath)); if (!fSuccess) { // this could happen if we are running without the WPS, return // the Home directory instead return GetSpecialSystemDirectory(OS2_HomeDirectory, aFile); } int len = strlen (szPath); if (len > CCHMAXPATH -1) break; szPath[len] = '\\'; szPath[len + 1] = '\0'; return NS_NewNativeLocalFile(nsDependentCString(szPath), true, aFile); } #endif default: break; } return NS_ERROR_NOT_AVAILABLE; }
bool DeviceStorageRequestChild::Recv__delete__(const DeviceStorageResponseValue& aValue) { switch (aValue.type()) { case DeviceStorageResponseValue::TErrorResponse: { ErrorResponse r = aValue; mRequest->FireError(r.error()); break; } case DeviceStorageResponseValue::TSuccessResponse: { jsval result = StringToJsval(mRequest->GetOwner(), mFile->mPath); mRequest->FireSuccess(result); break; } case DeviceStorageResponseValue::TBlobResponse: { BlobResponse r = aValue; BlobChild* actor = static_cast<BlobChild*>(r.blobChild()); nsCOMPtr<nsIDOMBlob> blob = actor->GetBlob(); jsval result = InterfaceToJsval(mRequest->GetOwner(), blob, &NS_GET_IID(nsIDOMBlob)); mRequest->FireSuccess(result); break; } case DeviceStorageResponseValue::TStatStorageResponse: { StatStorageResponse r = aValue; nsRefPtr<nsIDOMDeviceStorageStat> domstat = new nsDOMDeviceStorageStat(r.freeBytes(), r.totalBytes(), r.mountState()); jsval result = InterfaceToJsval(mRequest->GetOwner(), domstat, &NS_GET_IID(nsIDOMDeviceStorageStat)); mRequest->FireSuccess(result); break; } case DeviceStorageResponseValue::TEnumerationResponse: { EnumerationResponse r = aValue; nsDOMDeviceStorageCursor* cursor = static_cast<nsDOMDeviceStorageCursor*>(mRequest.get()); uint32_t count = r.paths().Length(); for (uint32_t i = 0; i < count; i++) { nsCOMPtr<nsIFile> f; nsresult rv = NS_NewLocalFile(r.paths()[i].fullpath(), false, getter_AddRefs(f)); if (NS_FAILED(rv)) { continue; } nsRefPtr<DeviceStorageFile> dsf = new DeviceStorageFile(r.paths()[i].type(), f); dsf->SetPath(r.paths()[i].name()); cursor->mFiles.AppendElement(dsf); } nsCOMPtr<ContinueCursorEvent> event = new ContinueCursorEvent(cursor); NS_DispatchToMainThread(event); break; } default: { NS_RUNTIMEABORT("not reached"); break; } } return true; }
nsresult nsPluginDirServiceProvider::GetPLIDDirectoriesWithHKEY(HKEY aKey, nsCOMArray<nsILocalFile> &aDirs) { WCHAR subkey[_MAX_PATH] = L"Software\\MozillaPlugins"; HKEY baseloc; if (ERROR_SUCCESS != ::RegOpenKeyExW(aKey, subkey, 0, KEY_READ, &baseloc)) return NS_ERROR_FAILURE; DWORD index = 0; DWORD subkeylen = _MAX_PATH; FILETIME modTime; while (ERROR_SUCCESS == ::RegEnumKeyExW(baseloc, index++, subkey, &subkeylen, NULL, NULL, NULL, &modTime)) { subkeylen = _MAX_PATH; HKEY keyloc; if (ERROR_SUCCESS == ::RegOpenKeyExW(baseloc, subkey, 0, KEY_QUERY_VALUE, &keyloc)) { DWORD type; WCHAR path[_MAX_PATH]; DWORD pathlen = NS_ARRAY_LENGTH(path); if (ERROR_SUCCESS == ::RegQueryValueExW(keyloc, L"Path", NULL, &type, (LPBYTE)&path, &pathlen)) { nsCOMPtr<nsILocalFile> localFile; if (NS_SUCCEEDED(NS_NewLocalFile(nsDependentString(path), PR_TRUE, getter_AddRefs(localFile))) && localFile) { // Some vendors use a path directly to the DLL so chop off // the filename PRBool isDir = PR_FALSE; if (NS_SUCCEEDED(localFile->IsDirectory(&isDir)) && !isDir) { nsCOMPtr<nsIFile> temp; localFile->GetParent(getter_AddRefs(temp)); if (temp) localFile = do_QueryInterface(temp); } // Now we check to make sure it's actually on disk and // To see if we already have this directory in the array PRBool isFileThere = PR_FALSE; PRBool isDupEntry = PR_FALSE; if (NS_SUCCEEDED(localFile->Exists(&isFileThere)) && isFileThere) { PRInt32 c = aDirs.Count(); for (PRInt32 i = 0; i < c; i++) { nsIFile *dup = static_cast<nsIFile*>(aDirs[i]); if (dup && NS_SUCCEEDED(dup->Equals(localFile, &isDupEntry)) && isDupEntry) { break; } } if (!isDupEntry) { aDirs.AppendObject(localFile); } } } } ::RegCloseKey(keyloc); } } ::RegCloseKey(baseloc); return NS_OK; }
nsresult TestPermissions() { nsresult rv; // Return value // File variables HANDLE tempFileHandle; nsCOMPtr<nsILocalFile> tempFile; nsCOMPtr<nsILocalFile> tempDirectory1; nsCOMPtr<nsILocalFile> tempDirectory2; WCHAR filePath[MAX_PATH]; WCHAR dir1Path[MAX_PATH]; WCHAR dir2Path[MAX_PATH]; // Security variables DWORD result; PSID everyoneSID = NULL, adminSID = NULL; PACL dirACL = NULL, fileACL = NULL; PSECURITY_DESCRIPTOR dirSD = NULL, fileSD = NULL; EXPLICIT_ACCESS ea[2]; SID_IDENTIFIER_AUTHORITY SIDAuthWorld = SECURITY_WORLD_SID_AUTHORITY; SID_IDENTIFIER_AUTHORITY SIDAuthNT = SECURITY_NT_AUTHORITY; SECURITY_ATTRIBUTES sa; TRUSTEE everyoneTrustee; ACCESS_MASK everyoneRights; // Create a well-known SID for the Everyone group. if(!AllocateAndInitializeSid(&SIDAuthWorld, 1, SECURITY_WORLD_RID, 0, 0, 0, 0, 0, 0, 0, &everyoneSID)) { fail("NTFS Permissions: AllocateAndInitializeSid Error"); return NS_ERROR_FAILURE; } // Create a SID for the Administrators group. if(! AllocateAndInitializeSid(&SIDAuthNT, 2, SECURITY_BUILTIN_DOMAIN_RID, DOMAIN_ALIAS_RID_ADMINS, 0, 0, 0, 0, 0, 0, &adminSID)) { fail("NTFS Permissions: AllocateAndInitializeSid Error"); return NS_ERROR_FAILURE; } // Initialize an EXPLICIT_ACCESS structure for an ACE. // The ACE will allow Everyone read access to the directory. ZeroMemory(&ea, 2 * sizeof(EXPLICIT_ACCESS)); ea[0].grfAccessPermissions = GENERIC_READ; ea[0].grfAccessMode = SET_ACCESS; ea[0].grfInheritance= SUB_CONTAINERS_AND_OBJECTS_INHERIT; ea[0].Trustee.TrusteeForm = TRUSTEE_IS_SID; ea[0].Trustee.TrusteeType = TRUSTEE_IS_WELL_KNOWN_GROUP; ea[0].Trustee.ptstrName = (LPTSTR) everyoneSID; // Initialize an EXPLICIT_ACCESS structure for an ACE. // The ACE will allow the Administrators group full access ea[1].grfAccessPermissions = GENERIC_ALL | STANDARD_RIGHTS_ALL; ea[1].grfAccessMode = SET_ACCESS; ea[1].grfInheritance= SUB_CONTAINERS_AND_OBJECTS_INHERIT; ea[1].Trustee.TrusteeForm = TRUSTEE_IS_SID; ea[1].Trustee.TrusteeType = TRUSTEE_IS_GROUP; ea[1].Trustee.ptstrName = (LPTSTR) adminSID; // Create a new ACL that contains the new ACEs. result = SetEntriesInAcl(2, ea, NULL, &dirACL); if (ERROR_SUCCESS != result) { fail("NTFS Permissions: SetEntriesInAcl Error"); return NS_ERROR_FAILURE; } // Initialize a security descriptor. dirSD = (PSECURITY_DESCRIPTOR) LocalAlloc(LPTR, SECURITY_DESCRIPTOR_MIN_LENGTH); if (NULL == dirSD) { fail("NTFS Permissions: LocalAlloc Error"); return NS_ERROR_FAILURE; } if (!InitializeSecurityDescriptor(dirSD, SECURITY_DESCRIPTOR_REVISION)) { fail("NTFS Permissions: InitializeSecurityDescriptor Error"); return NS_ERROR_FAILURE; } // Add the ACL to the security descriptor. if (!SetSecurityDescriptorDacl(dirSD, true, dirACL, false)) { fail("NTFS Permissions: SetSecurityDescriptorDacl Error"); return NS_ERROR_FAILURE; } // Initialize a security attributes structure. sa.nLength = sizeof (SECURITY_ATTRIBUTES); sa.lpSecurityDescriptor = dirSD; sa.bInheritHandle = false; // Create and open first temporary directory if(!CreateDirectoryW(L".\\NTFSPERMTEMP1", &sa)) { fail("NTFS Permissions: Creating Temporary Directory"); return NS_ERROR_FAILURE; } GetFullPathNameW((LPCWSTR)L".\\NTFSPERMTEMP1", MAX_PATH, dir1Path, NULL); rv = NS_NewLocalFile(nsEmbedString(dir1Path), false, getter_AddRefs(tempDirectory1)); if (NS_FAILED(rv)) { fail("NTFS Permissions: Opening Temporary Directory 1"); return rv; } // Create and open temporary file tempFileHandle = CreateFileW(L".\\NTFSPERMTEMP1\\NTFSPerm.tmp", GENERIC_READ | GENERIC_WRITE, 0, NULL, //default security CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL); if(tempFileHandle == INVALID_HANDLE_VALUE) { fail("NTFS Permissions: Creating Temporary File"); return NS_ERROR_FAILURE; } CloseHandle(tempFileHandle); GetFullPathNameW((LPCWSTR)L".\\NTFSPERMTEMP1\\NTFSPerm.tmp", MAX_PATH, filePath, NULL); rv = NS_NewLocalFile(nsEmbedString(filePath), false, getter_AddRefs(tempFile)); if (NS_FAILED(rv)) { fail("NTFS Permissions: Opening Temporary File"); return rv; } // Update Everyone Explict_Acess to full access. ea[0].grfAccessPermissions = GENERIC_ALL | STANDARD_RIGHTS_ALL; // Update the ACL to contain the new ACEs. result = SetEntriesInAcl(2, ea, NULL, &dirACL); if (ERROR_SUCCESS != result) { fail("NTFS Permissions: SetEntriesInAcl 2 Error"); return NS_ERROR_FAILURE; } // Add the new ACL to the security descriptor. if (!SetSecurityDescriptorDacl(dirSD, true, dirACL, false)) { fail("NTFS Permissions: SetSecurityDescriptorDacl 2 Error"); return NS_ERROR_FAILURE; } // Create and open second temporary directory if(!CreateDirectoryW(L".\\NTFSPERMTEMP2", &sa)) { fail("NTFS Permissions: Creating Temporary Directory 2"); return NS_ERROR_FAILURE; } GetFullPathNameW((LPCWSTR)L".\\NTFSPERMTEMP2", MAX_PATH, dir2Path, NULL); rv = NS_NewLocalFile(nsEmbedString(dir2Path), false, getter_AddRefs(tempDirectory2)); if (NS_FAILED(rv)) { fail("NTFS Permissions: Opening Temporary Directory 2"); return rv; } // Move the file. rv = tempFile->MoveTo(tempDirectory2, EmptyString()); if (NS_FAILED(rv)) { fail("NTFS Permissions: Moving"); return rv; } // Access the ACL of the file result = GetNamedSecurityInfoW(L".\\NTFSPERMTEMP2\\NTFSPerm.tmp", SE_FILE_OBJECT, DACL_SECURITY_INFORMATION | UNPROTECTED_DACL_SECURITY_INFORMATION, NULL, NULL, &fileACL, NULL, &fileSD); if (ERROR_SUCCESS != result) { fail("NTFS Permissions: GetNamedSecurityDescriptor Error"); return NS_ERROR_FAILURE; } // Build a trustee representing "Everyone" BuildTrusteeWithSid(&everyoneTrustee, everyoneSID); // Get Everyone's effective rights. result = GetEffectiveRightsFromAcl(fileACL, &everyoneTrustee, &everyoneRights); if (ERROR_SUCCESS != result) { fail("NTFS Permissions: GetEffectiveRightsFromAcl Error"); return NS_ERROR_FAILURE; } // Check for delete access, which we won't have unless permissions have // updated if((everyoneRights & DELETE) == (DELETE)) { passed("NTFS Permissions Test"); rv = NS_OK; } else { fail("NTFS Permissions: Access check."); rv = NS_ERROR_FAILURE; } // Cleanup if (everyoneSID) FreeSid(everyoneSID); if (adminSID) FreeSid(adminSID); if (dirACL) LocalFree(dirACL); if (dirSD) LocalFree(dirSD); if(fileACL) LocalFree(fileACL); tempDirectory1->Remove(true); tempDirectory2->Remove(true); return rv; }
DeviceStorageRequestParent::DeviceStorageRequestParent(const DeviceStorageParams& aParams) { MOZ_COUNT_CTOR(DeviceStorageRequestParent); switch (aParams.type()) { case DeviceStorageParams::TDeviceStorageAddParams: { DeviceStorageAddParams p = aParams; nsCOMPtr<nsIFile> f; NS_NewLocalFile(p.fullpath(), false, getter_AddRefs(f)); nsRefPtr<DeviceStorageFile> dsf = new DeviceStorageFile(f); BlobParent* bp = static_cast<BlobParent*>(p.blobParent()); nsCOMPtr<nsIDOMBlob> blob = bp->GetBlob(); nsCOMPtr<nsIInputStream> stream; blob->GetInternalStream(getter_AddRefs(stream)); nsRefPtr<CancelableRunnable> r = new WriteFileEvent(this, dsf, stream); nsCOMPtr<nsIEventTarget> target = do_GetService(NS_STREAMTRANSPORTSERVICE_CONTRACTID); NS_ASSERTION(target, "Must have stream transport service"); target->Dispatch(r, NS_DISPATCH_NORMAL); break; } case DeviceStorageParams::TDeviceStorageGetParams: { DeviceStorageGetParams p = aParams; nsCOMPtr<nsIFile> f; NS_NewLocalFile(p.fullpath(), false, getter_AddRefs(f)); nsRefPtr<DeviceStorageFile> dsf = new DeviceStorageFile(f); dsf->SetPath(p.name()); nsRefPtr<CancelableRunnable> r = new ReadFileEvent(this, dsf); nsCOMPtr<nsIEventTarget> target = do_GetService(NS_STREAMTRANSPORTSERVICE_CONTRACTID); NS_ASSERTION(target, "Must have stream transport service"); target->Dispatch(r, NS_DISPATCH_NORMAL); break; } case DeviceStorageParams::TDeviceStorageDeleteParams: { DeviceStorageDeleteParams p = aParams; nsCOMPtr<nsIFile> f; NS_NewLocalFile(p.fullpath(), false, getter_AddRefs(f)); nsRefPtr<DeviceStorageFile> dsf = new DeviceStorageFile(f); nsRefPtr<CancelableRunnable> r = new DeleteFileEvent(this, dsf); nsCOMPtr<nsIEventTarget> target = do_GetService(NS_STREAMTRANSPORTSERVICE_CONTRACTID); NS_ASSERTION(target, "Must have stream transport service"); target->Dispatch(r, NS_DISPATCH_NORMAL); break; } case DeviceStorageParams::TDeviceStorageStatParams: { DeviceStorageStatParams p = aParams; nsCOMPtr<nsIFile> f; NS_NewLocalFile(p.fullpath(), false, getter_AddRefs(f)); nsRefPtr<DeviceStorageFile> dsf = new DeviceStorageFile(f); nsRefPtr<StatFileEvent> r = new StatFileEvent(this, dsf); nsCOMPtr<nsIEventTarget> target = do_GetService(NS_STREAMTRANSPORTSERVICE_CONTRACTID); NS_ASSERTION(target, "Must have stream transport service"); target->Dispatch(r, NS_DISPATCH_NORMAL); break; } case DeviceStorageParams::TDeviceStorageEnumerationParams: { DeviceStorageEnumerationParams p = aParams; nsCOMPtr<nsIFile> f; NS_NewLocalFile(p.fullpath(), false, getter_AddRefs(f)); nsRefPtr<DeviceStorageFile> dsf = new DeviceStorageFile(f); nsRefPtr<CancelableRunnable> r = new EnumerateFileEvent(this, dsf, p.since()); nsCOMPtr<nsIEventTarget> target = do_GetService(NS_STREAMTRANSPORTSERVICE_CONTRACTID); NS_ASSERTION(target, "Must have stream transport service"); target->Dispatch(r, NS_DISPATCH_NORMAL); break; } default: { NS_RUNTIMEABORT("not reached"); break; } } }
//---------------------------------------------------------------------------------------- // GetProductDirectory - Gets the directory which contains the application data folder // // UNIX : ~/.mozilla/ // WIN : <Application Data folder on user's machine>\Mozilla // Mac : :Documents:Mozilla: //---------------------------------------------------------------------------------------- NS_METHOD nsAppFileLocationProvider::GetProductDirectory(nsIFile** aLocalFile, bool aLocal) { if (NS_WARN_IF(!aLocalFile)) { return NS_ERROR_INVALID_ARG; } nsresult rv; bool exists; nsCOMPtr<nsIFile> localDir; #if defined(MOZ_WIDGET_COCOA) FSRef fsRef; OSType folderType = aLocal ? (OSType)kCachedDataFolderType : (OSType)kDomainLibraryFolderType; OSErr err = ::FSFindFolder(kUserDomain, folderType, kCreateFolder, &fsRef); if (err) { return NS_ERROR_FAILURE; } NS_NewLocalFile(EmptyString(), true, getter_AddRefs(localDir)); if (!localDir) { return NS_ERROR_FAILURE; } nsCOMPtr<nsILocalFileMac> localDirMac(do_QueryInterface(localDir)); rv = localDirMac->InitWithFSRef(&fsRef); if (NS_FAILED(rv)) { return rv; } #elif defined(XP_WIN) nsCOMPtr<nsIProperties> directoryService = do_GetService(NS_DIRECTORY_SERVICE_CONTRACTID, &rv); if (NS_FAILED(rv)) { return rv; } const char* prop = aLocal ? NS_WIN_LOCAL_APPDATA_DIR : NS_WIN_APPDATA_DIR; rv = directoryService->Get(prop, NS_GET_IID(nsIFile), getter_AddRefs(localDir)); if (NS_FAILED(rv)) { return rv; } #elif defined(XP_UNIX) rv = NS_NewNativeLocalFile(nsDependentCString(PR_GetEnv("HOME")), true, getter_AddRefs(localDir)); if (NS_FAILED(rv)) { return rv; } #else #error dont_know_how_to_get_product_dir_on_your_platform #endif rv = localDir->AppendRelativeNativePath(DEFAULT_PRODUCT_DIR); if (NS_FAILED(rv)) { return rv; } rv = localDir->Exists(&exists); if (NS_SUCCEEDED(rv) && !exists) { rv = localDir->Create(nsIFile::DIRECTORY_TYPE, 0700); } if (NS_FAILED(rv)) { return rv; } localDir.forget(aLocalFile); return rv; }
nsresult GetSpecialSystemDirectory(SystemDirectories aSystemSystemDirectory, nsIFile** aFile) { #if defined(XP_WIN) WCHAR path[MAX_PATH]; #else char path[MAXPATHLEN]; #endif switch (aSystemSystemDirectory) { case OS_CurrentWorkingDirectory: #if defined(XP_WIN) if (!_wgetcwd(path, MAX_PATH)) return NS_ERROR_FAILURE; return NS_NewLocalFile(nsDependentString(path), true, aFile); #else if(!getcwd(path, MAXPATHLEN)) return NS_ERROR_FAILURE; #endif #if !defined(XP_WIN) return NS_NewNativeLocalFile(nsDependentCString(path), true, aFile); #endif case OS_DriveDirectory: #if defined (XP_WIN) { int32_t len = ::GetWindowsDirectoryW(path, MAX_PATH); if (len == 0) break; if (path[1] == PRUnichar(':') && path[2] == PRUnichar('\\')) path[3] = 0; return NS_NewLocalFile(nsDependentString(path), true, aFile); } #else return NS_NewNativeLocalFile(nsDependentCString("/"), true, aFile); #endif case OS_TemporaryDirectory: #if defined (XP_WIN) { DWORD len = ::GetTempPathW(MAX_PATH, path); if (len == 0) break; return NS_NewLocalFile(nsDependentString(path, len), true, aFile); } #elif defined(MOZ_WIDGET_COCOA) { return GetOSXFolderType(kUserDomain, kTemporaryFolderType, aFile); } #elif defined(XP_UNIX) { static const char *tPath = nullptr; if (!tPath) { tPath = PR_GetEnv("PANDORATMP"); if (!tPath) { tPath = PR_GetEnv("TMPDIR"); if (!tPath || !*tPath) { tPath = PR_GetEnv("TMP"); if (!tPath || !*tPath) { tPath = PR_GetEnv("TEMP"); if (!tPath || !*tPath) { tPath = "/tmp/"; } } } } } return NS_NewNativeLocalFile(nsDependentCString(tPath), true, aFile); } #else break; #endif #if defined (XP_WIN) case Win_SystemDirectory: { int32_t len = ::GetSystemDirectoryW(path, MAX_PATH); // Need enough space to add the trailing backslash if (!len || len > MAX_PATH - 2) break; path[len] = L'\\'; path[++len] = L'\0'; return NS_NewLocalFile(nsDependentString(path, len), true, aFile); } case Win_WindowsDirectory: { int32_t len = ::GetWindowsDirectoryW(path, MAX_PATH); // Need enough space to add the trailing backslash if (!len || len > MAX_PATH - 2) break; path[len] = L'\\'; path[++len] = L'\0'; return NS_NewLocalFile(nsDependentString(path, len), true, aFile); } case Win_ProgramFiles: { return GetWindowsFolder(CSIDL_PROGRAM_FILES, aFile); } case Win_HomeDirectory: { nsresult rv = GetWindowsFolder(CSIDL_PROFILE, aFile); if (NS_SUCCEEDED(rv)) return rv; int32_t len; if ((len = ::GetEnvironmentVariableW(L"HOME", path, MAX_PATH)) > 0) { // Need enough space to add the trailing backslash if (len > MAX_PATH - 2) break; path[len] = L'\\'; path[++len] = L'\0'; rv = NS_NewLocalFile(nsDependentString(path, len), true, aFile); if (NS_SUCCEEDED(rv)) return rv; } len = ::GetEnvironmentVariableW(L"HOMEDRIVE", path, MAX_PATH); if (0 < len && len < MAX_PATH) { WCHAR temp[MAX_PATH]; DWORD len2 = ::GetEnvironmentVariableW(L"HOMEPATH", temp, MAX_PATH); if (0 < len2 && len + len2 < MAX_PATH) wcsncat(path, temp, len2); len = wcslen(path); // Need enough space to add the trailing backslash if (len > MAX_PATH - 2) break; path[len] = L'\\'; path[++len] = L'\0'; return NS_NewLocalFile(nsDependentString(path, len), true, aFile); } } case Win_Desktop: { return GetWindowsFolder(CSIDL_DESKTOP, aFile); } case Win_Programs: { return GetWindowsFolder(CSIDL_PROGRAMS, aFile); } case Win_Downloads: { // Defined in KnownFolders.h. GUID folderid_downloads = {0x374de290, 0x123f, 0x4565, {0x91, 0x64, 0x39, 0xc4, 0x92, 0x5e, 0x46, 0x7b}}; nsresult rv = GetKnownFolder(&folderid_downloads, aFile); // On WinXP, there is no downloads folder, default // to 'Desktop'. if(NS_ERROR_FAILURE == rv) { rv = GetWindowsFolder(CSIDL_DESKTOP, aFile); } return rv; } case Win_Controls: { return GetWindowsFolder(CSIDL_CONTROLS, aFile); } case Win_Printers: { return GetWindowsFolder(CSIDL_PRINTERS, aFile); } case Win_Personal: { return GetWindowsFolder(CSIDL_PERSONAL, aFile); } case Win_Favorites: { return GetWindowsFolder(CSIDL_FAVORITES, aFile); } case Win_Startup: { return GetWindowsFolder(CSIDL_STARTUP, aFile); } case Win_Recent: { return GetWindowsFolder(CSIDL_RECENT, aFile); } case Win_Sendto: { return GetWindowsFolder(CSIDL_SENDTO, aFile); } case Win_Bitbucket: { return GetWindowsFolder(CSIDL_BITBUCKET, aFile); } case Win_Startmenu: { return GetWindowsFolder(CSIDL_STARTMENU, aFile); } case Win_Desktopdirectory: { return GetWindowsFolder(CSIDL_DESKTOPDIRECTORY, aFile); } case Win_Drives: { return GetWindowsFolder(CSIDL_DRIVES, aFile); } case Win_Network: { return GetWindowsFolder(CSIDL_NETWORK, aFile); } case Win_Nethood: { return GetWindowsFolder(CSIDL_NETHOOD, aFile); } case Win_Fonts: { return GetWindowsFolder(CSIDL_FONTS, aFile); } case Win_Templates: { return GetWindowsFolder(CSIDL_TEMPLATES, aFile); } case Win_Common_Startmenu: { return GetWindowsFolder(CSIDL_COMMON_STARTMENU, aFile); } case Win_Common_Programs: { return GetWindowsFolder(CSIDL_COMMON_PROGRAMS, aFile); } case Win_Common_Startup: { return GetWindowsFolder(CSIDL_COMMON_STARTUP, aFile); } case Win_Common_Desktopdirectory: { return GetWindowsFolder(CSIDL_COMMON_DESKTOPDIRECTORY, aFile); } case Win_Common_AppData: { return GetWindowsFolder(CSIDL_COMMON_APPDATA, aFile); } case Win_Printhood: { return GetWindowsFolder(CSIDL_PRINTHOOD, aFile); } case Win_Cookies: { return GetWindowsFolder(CSIDL_COOKIES, aFile); } case Win_Appdata: { nsresult rv = GetWindowsFolder(CSIDL_APPDATA, aFile); if (NS_FAILED(rv)) rv = GetRegWindowsAppDataFolder(false, aFile); return rv; } case Win_LocalAppdata: { nsresult rv = GetWindowsFolder(CSIDL_LOCAL_APPDATA, aFile); if (NS_FAILED(rv)) rv = GetRegWindowsAppDataFolder(true, aFile); return rv; } case Win_Documents: { return GetLibrarySaveToPath(CSIDL_MYDOCUMENTS, FOLDERID_DocumentsLibrary, aFile); } case Win_Pictures: { return GetLibrarySaveToPath(CSIDL_MYPICTURES, FOLDERID_PicturesLibrary, aFile); } case Win_Music: { return GetLibrarySaveToPath(CSIDL_MYMUSIC, FOLDERID_MusicLibrary, aFile); } case Win_Videos: { return GetLibrarySaveToPath(CSIDL_MYVIDEO, FOLDERID_VideosLibrary, aFile); } #endif // XP_WIN #if defined(XP_UNIX) case Unix_LocalDirectory: return NS_NewNativeLocalFile(nsDependentCString("/usr/local/netscape/"), true, aFile); case Unix_LibDirectory: return NS_NewNativeLocalFile(nsDependentCString("/usr/local/lib/netscape/"), true, aFile); case Unix_HomeDirectory: return GetUnixHomeDir(aFile); case Unix_XDG_Desktop: case Unix_XDG_Documents: case Unix_XDG_Download: case Unix_XDG_Music: case Unix_XDG_Pictures: case Unix_XDG_PublicShare: case Unix_XDG_Templates: case Unix_XDG_Videos: return GetUnixXDGUserDirectory(aSystemSystemDirectory, aFile); #endif // XP_UNIX default: break; } return NS_ERROR_NOT_AVAILABLE; }
//---------------------------------------------------------------------------------------- // GetProductDirectory - Gets the directory which contains the application data folder // // UNIX : ~/.mozilla/ // WIN : <Application Data folder on user's machine>\Mozilla // Mac : :Documents:Mozilla: //---------------------------------------------------------------------------------------- NS_METHOD nsAppFileLocationProvider::GetProductDirectory(nsILocalFile **aLocalFile, PRBool aLocal) { NS_ENSURE_ARG_POINTER(aLocalFile); nsresult rv; PRBool exists; nsCOMPtr<nsILocalFile> localDir; #if defined(XP_MACOSX) FSRef fsRef; OSType folderType = aLocal ? kCachedDataFolderType : kDomainLibraryFolderType; OSErr err = ::FSFindFolder(kUserDomain, folderType, kCreateFolder, &fsRef); if (err) return NS_ERROR_FAILURE; NS_NewLocalFile(EmptyString(), PR_TRUE, getter_AddRefs(localDir)); if (!localDir) return NS_ERROR_FAILURE; nsCOMPtr<nsILocalFileMac> localDirMac(do_QueryInterface(localDir)); rv = localDirMac->InitWithFSRef(&fsRef); if (NS_FAILED(rv)) return rv; #elif defined(XP_OS2) nsCOMPtr<nsIProperties> directoryService = do_GetService(NS_DIRECTORY_SERVICE_CONTRACTID, &rv); if (NS_FAILED(rv)) return rv; rv = directoryService->Get(NS_OS2_HOME_DIR, NS_GET_IID(nsILocalFile), getter_AddRefs(localDir)); if (NS_FAILED(rv)) return rv; #elif defined(XP_WIN) nsCOMPtr<nsIProperties> directoryService = do_GetService(NS_DIRECTORY_SERVICE_CONTRACTID, &rv); if (NS_FAILED(rv)) return rv; const char* prop = aLocal ? NS_WIN_LOCAL_APPDATA_DIR : NS_WIN_APPDATA_DIR; rv = directoryService->Get(prop, NS_GET_IID(nsILocalFile), getter_AddRefs(localDir)); if (NS_SUCCEEDED(rv)) rv = localDir->Exists(&exists); if (NS_FAILED(rv) || !exists) { // On some Win95 machines, NS_WIN_APPDATA_DIR does not exist - revert to NS_WIN_WINDOWS_DIR localDir = nsnull; rv = directoryService->Get(NS_WIN_WINDOWS_DIR, NS_GET_IID(nsILocalFile), getter_AddRefs(localDir)); } if (NS_FAILED(rv)) return rv; #elif defined(XP_UNIX) rv = NS_NewNativeLocalFile(nsDependentCString(PR_GetEnv("HOME")), PR_TRUE, getter_AddRefs(localDir)); if (NS_FAILED(rv)) return rv; #elif defined(XP_BEOS) char path[MAXPATHLEN]; find_directory(B_USER_SETTINGS_DIRECTORY, 0, 0, path, MAXPATHLEN); // Need enough space to add the trailing backslash int len = strlen(path); if (len > MAXPATHLEN-2) return NS_ERROR_FAILURE; path[len] = '/'; path[len+1] = '\0'; rv = NS_NewNativeLocalFile(nsDependentCString(path), PR_TRUE, getter_AddRefs(localDir)); if (NS_FAILED(rv)) return rv; #else #error dont_know_how_to_get_product_dir_on_your_platform #endif rv = localDir->AppendRelativeNativePath(DEFAULT_PRODUCT_DIR); if (NS_FAILED(rv)) return rv; rv = localDir->Exists(&exists); if (NS_SUCCEEDED(rv) && !exists) rv = localDir->Create(nsIFile::DIRECTORY_TYPE, 0700); if (NS_FAILED(rv)) return rv; *aLocalFile = localDir; NS_ADDREF(*aLocalFile); return rv; }
nsresult MediaEngineWebRTCVideoSource::Snapshot(PRUint32 aDuration, nsIDOMFile** aFile) { /** * To get a Snapshot we do the following: * - Set a condition variable (mInSnapshotMode) to true * - Attach the external renderer and start the camera * - Wait for the condition variable to change to false * * Starting the camera has the effect of invoking DeliverFrame() when * the first frame arrives from the camera. We only need one frame for * GetCaptureDeviceSnapshot to work, so we immediately set the condition * variable to false and notify this method. * * This causes the current thread to continue (PR_CondWaitVar will return), * at which point we can grab a snapshot, convert it to a file and * return from this function after cleaning up the temporary stream object * and caling Stop() on the media source. */ *aFile = nsnull; if (!mInitDone || mState != kAllocated) { return NS_ERROR_FAILURE; } mSnapshotLock = PR_NewLock(); mSnapshotCondVar = PR_NewCondVar(mSnapshotLock); PR_Lock(mSnapshotLock); mInSnapshotMode = true; // Start the rendering (equivalent to calling Start(), but without a track). int error = 0; if (!mInitDone || mState != kAllocated) { return NS_ERROR_FAILURE; } error = mViERender->AddRenderer(mCapIndex, webrtc::kVideoI420, (webrtc::ExternalRenderer*)this); if (error == -1) { return NS_ERROR_FAILURE; } error = mViERender->StartRender(mCapIndex); if (error == -1) { return NS_ERROR_FAILURE; } // Wait for the condition variable, will be set in DeliverFrame. // We use a while loop, because even if PR_WaitCondVar returns, it's not // guaranteed that the condition variable changed. while (mInSnapshotMode) { PR_WaitCondVar(mSnapshotCondVar, PR_INTERVAL_NO_TIMEOUT); } // If we get here, DeliverFrame received at least one frame. PR_Unlock(mSnapshotLock); PR_DestroyCondVar(mSnapshotCondVar); PR_DestroyLock(mSnapshotLock); webrtc::ViEFile* vieFile = webrtc::ViEFile::GetInterface(mVideoEngine); if (!vieFile) { return NS_ERROR_FAILURE; } // Create a temporary file on the main thread and put the snapshot in it. // See Run() in MediaEngineWebRTCVideo.h (sets mSnapshotPath). NS_DispatchToMainThread(this, NS_DISPATCH_SYNC); if (!mSnapshotPath) { return NS_ERROR_FAILURE; } const char* path = NS_ConvertUTF16toUTF8(*mSnapshotPath).get(); if (vieFile->GetCaptureDeviceSnapshot(mCapIndex, path) < 0) { delete mSnapshotPath; mSnapshotPath = NULL; return NS_ERROR_FAILURE; } // Stop the camera. mViERender->StopRender(mCapIndex); mViERender->RemoveRenderer(mCapIndex); nsCOMPtr<nsIFile> file; nsresult rv = NS_NewLocalFile(*mSnapshotPath, false, getter_AddRefs(file)); delete mSnapshotPath; mSnapshotPath = NULL; NS_ENSURE_SUCCESS(rv, rv); NS_ADDREF(*aFile = new nsDOMFileFile(file)); return NS_OK; }
nsresult nsXREDirProvider::GetUserDataDirectoryHome(nsIFile** aFile, bool aLocal) { // Copied from nsAppFileLocationProvider (more or less) nsresult rv; nsCOMPtr<nsIFile> localDir; #if defined(XP_MACOSX) FSRef fsRef; OSType folderType; if (aLocal) { folderType = kCachedDataFolderType; } else { #ifdef MOZ_THUNDERBIRD folderType = kDomainLibraryFolderType; #else folderType = kApplicationSupportFolderType; #endif } OSErr err = ::FSFindFolder(kUserDomain, folderType, kCreateFolder, &fsRef); NS_ENSURE_FALSE(err, NS_ERROR_FAILURE); rv = NS_NewNativeLocalFile(EmptyCString(), true, getter_AddRefs(localDir)); NS_ENSURE_SUCCESS(rv, rv); nsCOMPtr<nsILocalFileMac> dirFileMac = do_QueryInterface(localDir); NS_ENSURE_TRUE(dirFileMac, NS_ERROR_UNEXPECTED); rv = dirFileMac->InitWithFSRef(&fsRef); NS_ENSURE_SUCCESS(rv, rv); localDir = do_QueryInterface(dirFileMac, &rv); #elif defined(XP_WIN) nsString path; if (aLocal) { rv = GetShellFolderPath(CSIDL_LOCAL_APPDATA, path); if (NS_FAILED(rv)) rv = GetRegWindowsAppDataFolder(aLocal, path); } if (!aLocal || NS_FAILED(rv)) { rv = GetShellFolderPath(CSIDL_APPDATA, path); if (NS_FAILED(rv)) { if (!aLocal) rv = GetRegWindowsAppDataFolder(aLocal, path); } } NS_ENSURE_SUCCESS(rv, rv); rv = NS_NewLocalFile(path, true, getter_AddRefs(localDir)); #elif defined(XP_OS2) #if 0 /* For OS/2 we want to always use MOZILLA_HOME */ // we want an environment variable of the form // FIREFOX_HOME, etc if (!gAppData) return NS_ERROR_FAILURE; nsDependentCString envVar(nsDependentCString(gAppData->name)); envVar.Append("_HOME"); char *pHome = getenv(envVar.get()); #endif char *pHome = getenv("MOZILLA_HOME"); if (pHome && *pHome) { rv = NS_NewNativeLocalFile(nsDependentCString(pHome), true, getter_AddRefs(localDir)); } else { PPIB ppib; PTIB ptib; char appDir[CCHMAXPATH]; DosGetInfoBlocks(&ptib, &ppib); DosQueryModuleName(ppib->pib_hmte, CCHMAXPATH, appDir); *strrchr(appDir, '\\') = '\0'; rv = NS_NewNativeLocalFile(nsDependentCString(appDir), true, getter_AddRefs(localDir)); } #elif defined(MOZ_WIDGET_GONK) rv = NS_NewNativeLocalFile(NS_LITERAL_CSTRING("/data/b2g"), true, getter_AddRefs(localDir)); #elif defined(XP_UNIX) const char* homeDir = getenv("HOME"); if (!homeDir || !*homeDir) return NS_ERROR_FAILURE; #ifdef ANDROID /* We want (ProfD == ProfLD) on Android. */ aLocal = false; #endif if (aLocal) { // If $XDG_CACHE_HOME is defined use it, otherwise use $HOME/.cache. const char* cacheHome = getenv("XDG_CACHE_HOME"); if (cacheHome && *cacheHome) { rv = NS_NewNativeLocalFile(nsDependentCString(cacheHome), true, getter_AddRefs(localDir)); } else { rv = NS_NewNativeLocalFile(nsDependentCString(homeDir), true, getter_AddRefs(localDir)); if (NS_SUCCEEDED(rv)) rv = localDir->AppendNative(NS_LITERAL_CSTRING(".cache")); } } else { rv = NS_NewNativeLocalFile(nsDependentCString(homeDir), true, getter_AddRefs(localDir)); } #else #error "Don't know how to get product dir on your platform" #endif NS_IF_ADDREF(*aFile = localDir); return rv; }
// The "real" name of a given helper app (as specified by the path to the // executable file held in various registry keys) is stored n the VERSIONINFO // block in the file's resources. We need to find the path to the executable // and then retrieve the "FileDescription" field value from the file. nsresult nsOSHelperAppService::GetDefaultAppInfo(const nsAString& aAppInfo, nsAString& aDefaultDescription, nsIFile** aDefaultApplication) { nsAutoString handlerCommand; // If all else fails, use the file type key name, which will be // something like "pngfile" for .pngs, "WMVFile" for .wmvs, etc. aDefaultDescription = aAppInfo; *aDefaultApplication = nullptr; if (aAppInfo.IsEmpty()) return NS_ERROR_FAILURE; // aAppInfo may be a file, file path, program id, or // Applications reference - // c:\dir\app.exe // Applications\appfile.exe/dll (shell\open...) // ProgID.progid (shell\open...) nsAutoString handlerKeyName(aAppInfo); nsCOMPtr<nsIWindowsRegKey> chkKey = do_CreateInstance("@mozilla.org/windows-registry-key;1"); if (!chkKey) return NS_ERROR_FAILURE; nsresult rv = chkKey->Open(nsIWindowsRegKey::ROOT_KEY_CLASSES_ROOT, handlerKeyName, nsIWindowsRegKey::ACCESS_QUERY_VALUE); if (NS_FAILED(rv)) { // It's a file system path to a handler handlerCommand.Assign(aAppInfo); } else { handlerKeyName.AppendLiteral("\\shell\\open\\command"); nsCOMPtr<nsIWindowsRegKey> regKey = do_CreateInstance("@mozilla.org/windows-registry-key;1"); if (!regKey) return NS_ERROR_FAILURE; nsresult rv = regKey->Open(nsIWindowsRegKey::ROOT_KEY_CLASSES_ROOT, handlerKeyName, nsIWindowsRegKey::ACCESS_QUERY_VALUE); if (NS_FAILED(rv)) return NS_ERROR_FAILURE; // OK, the default value here is the description of the type. rv = regKey->ReadStringValue(EmptyString(), handlerCommand); if (NS_FAILED(rv)) { // Check if there is a DelegateExecute string nsAutoString delegateExecute; rv = regKey->ReadStringValue(NS_LITERAL_STRING("DelegateExecute"), delegateExecute); NS_ENSURE_SUCCESS(rv, rv); // Look for InProcServer32 nsAutoString delegateExecuteRegPath; delegateExecuteRegPath.AssignLiteral("CLSID\\"); delegateExecuteRegPath.Append(delegateExecute); delegateExecuteRegPath.AppendLiteral("\\InProcServer32"); rv = chkKey->Open(nsIWindowsRegKey::ROOT_KEY_CLASSES_ROOT, delegateExecuteRegPath, nsIWindowsRegKey::ACCESS_QUERY_VALUE); if (NS_SUCCEEDED(rv)) { rv = chkKey->ReadStringValue(EmptyString(), handlerCommand); } if (NS_FAILED(rv)) { // Look for LocalServer32 delegateExecuteRegPath.AssignLiteral("CLSID\\"); delegateExecuteRegPath.Append(delegateExecute); delegateExecuteRegPath.AppendLiteral("\\LocalServer32"); rv = chkKey->Open(nsIWindowsRegKey::ROOT_KEY_CLASSES_ROOT, delegateExecuteRegPath, nsIWindowsRegKey::ACCESS_QUERY_VALUE); NS_ENSURE_SUCCESS(rv, rv); rv = chkKey->ReadStringValue(EmptyString(), handlerCommand); NS_ENSURE_SUCCESS(rv, rv); } } } if (!CleanupCmdHandlerPath(handlerCommand)) return NS_ERROR_FAILURE; // XXX FIXME: If this fails, the UI will display the full command // string. // There are some rare cases this can happen - ["url.dll" -foo] // for example won't resolve correctly to the system dir. The // subsequent launch of the helper app will work though. nsCOMPtr<nsIFile> lf; NS_NewLocalFile(handlerCommand, true, getter_AddRefs(lf)); if (!lf) return NS_ERROR_FILE_NOT_FOUND; nsILocalFileWin* lfw = nullptr; CallQueryInterface(lf, &lfw); if (lfw) { // The "FileDescription" field contains the actual name of the application. lfw->GetVersionInfoField("FileDescription", aDefaultDescription); // QI addref'ed for us. *aDefaultApplication = lfw; } return NS_OK; }
nsresult nsProfileMigrator::GetDefaultBrowserMigratorKey(nsACString& aKey, nsCOMPtr<nsIBrowserProfileMigrator>& bpm) { #if XP_WIN nsCOMPtr<nsIWindowsRegKey> regKey = do_CreateInstance("@mozilla.org/windows-registry-key;1"); if (!regKey) return NS_ERROR_FAILURE; NS_NAMED_LITERAL_STRING(kCommandKey, "SOFTWARE\\Classes\\HTTP\\shell\\open\\command"); if (NS_FAILED(regKey->Open(nsIWindowsRegKey::ROOT_KEY_LOCAL_MACHINE, kCommandKey, nsIWindowsRegKey::ACCESS_READ))) return NS_ERROR_FAILURE; nsAutoString value; if (NS_FAILED(regKey->ReadStringValue(EmptyString(), value))) return NS_ERROR_FAILURE; PRInt32 len = value.Find(NS_LITERAL_STRING(".exe"), CaseInsensitiveCompare); if (len == -1) return NS_ERROR_FAILURE; // Move past ".exe" len += 4; PRUint32 start = 0; // skip an opening quotation mark if present if (value.get()[1] != ':') { start = 1; --len; } const nsDependentSubstring filePath(Substring(value, start, len)); // We want to find out what the default browser is but the path in and of itself // isn't enough. Why? Because sometimes on Windows paths get truncated like so: // C:\PROGRA~1\MOZILL~2\MOZILL~1.EXE // How do we know what product that is? Mozilla or Mozilla Firebird? etc. Mozilla's // file objects do nothing to 'normalize' the path so we need to attain an actual // product descriptor from the file somehow, and in this case it means getting // the "InternalName" field of the file's VERSIONINFO resource. // // In the file's resource segment there is a VERSIONINFO section that is laid // out like this: // // VERSIONINFO // StringFileInfo // <TranslationID> // InternalName "iexplore" // VarFileInfo // Translation <TranslationID> // // By Querying the VERSIONINFO section for its Tranlations, we can find out where // the InternalName lives. (A file can have more than one translation of its // VERSIONINFO segment, but we just assume the first one). nsCOMPtr<nsILocalFile> lf; NS_NewLocalFile(filePath, PR_TRUE, getter_AddRefs(lf)); if (!lf) return NS_ERROR_FAILURE; nsCOMPtr<nsILocalFileWin> lfw = do_QueryInterface(lf); if (!lfw) return NS_ERROR_FAILURE; nsAutoString internalName; if (NS_FAILED(lfw->GetVersionInfoField("InternalName", internalName))) return NS_ERROR_FAILURE; if (internalName.LowerCaseEqualsLiteral(INTERNAL_NAME_IEXPLORE)) { aKey = "ie"; return NS_OK; } if (internalName.LowerCaseEqualsLiteral(INTERNAL_NAME_MOZILLA_SUITE) || internalName.LowerCaseEqualsLiteral(INTERNAL_NAME_SEAMONKEY)) { aKey = "seamonkey"; return NS_OK; } if (internalName.LowerCaseEqualsLiteral(INTERNAL_NAME_DOGBERT)) { aKey = "dogbert"; return NS_OK; } if (internalName.LowerCaseEqualsLiteral(INTERNAL_NAME_OPERA)) { aKey = "opera"; return NS_OK; } // Migrate data from any existing Application Data\Phoenix\* installations. if (internalName.LowerCaseEqualsLiteral(INTERNAL_NAME_FIREBIRD) || internalName.LowerCaseEqualsLiteral(INTERNAL_NAME_FIREFOX) || internalName.LowerCaseEqualsLiteral(INTERNAL_NAME_PHOENIX)) { aKey = "phoenix"; return NS_OK; } #else PRBool exists = PR_FALSE; #define CHECK_MIGRATOR(browser) do {\ bpm = do_CreateInstance(NS_BROWSERPROFILEMIGRATOR_CONTRACTID_PREFIX browser);\ if (bpm)\ bpm->GetSourceExists(&exists);\ if (exists) {\ aKey = browser;\ return NS_OK;\ }} while(0) #if defined(XP_MACOSX) CHECK_MIGRATOR("safari"); CHECK_MIGRATOR("macie"); #endif CHECK_MIGRATOR("phoenix"); CHECK_MIGRATOR("seamonkey"); CHECK_MIGRATOR("opera"); #undef CHECK_MIGRATOR #endif return NS_ERROR_FAILURE; }
static BOOL load_gecko(void) { nsresult nsres; nsIObserver *pStartNotif; nsIComponentRegistrar *registrar = NULL; nsAString path; nsIFile *gre_dir; PRUnichar gre_path[MAX_PATH]; static BOOL tried_load = FALSE; TRACE("()\n"); if(tried_load) return pCompMgr != NULL; tried_load = TRUE; if(!load_wine_gecko(gre_path) && !load_mozctl(gre_path) && !load_mozilla(gre_path)) { install_wine_gecko(); if(!load_wine_gecko(gre_path)) { MESSAGE("Could not load Mozilla. HTML rendering will be disabled.\n"); return FALSE; } } NS_StringContainerInit(&path); NS_StringSetData(&path, gre_path, PR_UINT32_MAX); nsres = NS_NewLocalFile(&path, FALSE, &gre_dir); NS_StringContainerFinish(&path); if(NS_FAILED(nsres)) { ERR("NS_NewLocalFile failed: %08lx\n", nsres); FreeLibrary(hXPCOM); return FALSE; } nsres = NS_InitXPCOM2(&pServMgr, gre_dir, NULL); if(NS_FAILED(nsres)) { ERR("NS_InitXPCOM2 failed: %08lx\n", nsres); FreeLibrary(hXPCOM); return FALSE; } nsres = nsIServiceManager_QueryInterface(pServMgr, &IID_nsIComponentManager, (void**)&pCompMgr); if(NS_FAILED(nsres)) ERR("Could not get nsIComponentManager: %08lx\n", nsres); nsres = NS_GetComponentRegistrar(®istrar); if(NS_SUCCEEDED(nsres)) { nsres = nsIComponentRegistrar_AutoRegister(registrar, NULL); if(NS_FAILED(nsres)) ERR("AutoRegister(NULL) failed: %08lx\n", nsres); nsres = nsIComponentRegistrar_AutoRegister(registrar, gre_dir); if(NS_FAILED(nsres)) ERR("AutoRegister(gre_dir) failed: %08lx\n", nsres); init_nsio(pCompMgr, registrar); }else { ERR("NS_GetComponentRegistrar failed: %08lx\n", nsres); } nsres = nsIComponentManager_CreateInstanceByContractID(pCompMgr, NS_APPSTARTUPNOTIFIER_CONTRACTID, NULL, &IID_nsIObserver, (void**)&pStartNotif); if(NS_SUCCEEDED(nsres)) { nsres = nsIObserver_Observe(pStartNotif, NULL, APPSTARTUP_TOPIC, NULL); if(NS_FAILED(nsres)) ERR("Observe failed: %08lx\n", nsres); nsIObserver_Release(pStartNotif); }else { ERR("could not get appstartup-notifier: %08lx\n", nsres); } set_profile(); nsres = nsIComponentManager_CreateInstanceByContractID(pCompMgr, NS_MEMORY_CONTRACTID, NULL, &IID_nsIMemory, (void**)&nsmem); if(NS_FAILED(nsres)) ERR("Could not get nsIMemory: %08lx\n", nsres); if(registrar) { register_nsservice(registrar, pServMgr); nsIComponentRegistrar_Release(registrar); } return TRUE; }
void GetDirectoryListingTaskChild::HandlerCallback() { mFileSystem->AssertIsOnOwningThread(); if (mFileSystem->IsShutdown()) { mPromise = nullptr; return; } if (HasError()) { mPromise->MaybeReject(mErrorValue); mPromise = nullptr; return; } size_t count = mTargetData.Length(); nsAutoString directoryPath; ErrorResult error; mDirectory->GetPath(directoryPath, error); if (NS_WARN_IF(error.Failed())) { mPromise->MaybeReject(error.StealNSResult()); mPromise = nullptr; return; } Sequence<OwningFileOrDirectory> listing; if (!listing.SetLength(count, mozilla::fallible_t())) { mPromise->MaybeReject(NS_ERROR_OUT_OF_MEMORY); mPromise = nullptr; return; } for (unsigned i = 0; i < count; i++) { nsCOMPtr<nsIFile> path; NS_ConvertUTF16toUTF8 fullPath(mTargetData[i].mPath); nsresult rv = NS_NewNativeLocalFile(fullPath, true, getter_AddRefs(path)); if (NS_WARN_IF(NS_FAILED(rv))) { mPromise->MaybeReject(rv); mPromise = nullptr; return; } #ifdef DEBUG nsCOMPtr<nsIFile> rootPath; rv = NS_NewLocalFile(mFileSystem->LocalOrDeviceStorageRootPath(), false, getter_AddRefs(rootPath)); if (NS_WARN_IF(NS_FAILED(rv))) { mPromise->MaybeReject(rv); mPromise = nullptr; return; } MOZ_ASSERT(FileSystemUtils::IsDescendantPath(rootPath, path)); #endif if (mTargetData[i].mType == Directory::FileOrDirectoryPath::eDirectoryPath) { RefPtr<Directory> directory = Directory::Create(mFileSystem->GetParentObject(), path, mFileSystem); MOZ_ASSERT(directory); // Propogate mFilter onto sub-Directory object: directory->SetContentFilters(mFilters); listing[i].SetAsDirectory() = directory; } else { MOZ_ASSERT(mTargetData[i].mType == Directory::FileOrDirectoryPath::eFilePath); RefPtr<File> file = File::CreateFromFile(mFileSystem->GetParentObject(), path); MOZ_ASSERT(file); nsAutoString filePath; filePath.Assign(directoryPath); // This is specific for unix root filesystem. if (!directoryPath.EqualsLiteral(FILESYSTEM_DOM_PATH_SEPARATOR_LITERAL)) { filePath.AppendLiteral(FILESYSTEM_DOM_PATH_SEPARATOR_LITERAL); } nsAutoString name; file->GetName(name); filePath.Append(name); file->SetPath(filePath); listing[i].SetAsFile() = file; } } mPromise->MaybeResolve(listing); mPromise = nullptr; }
nsresult TestWinAttribs() { if (!IsXPOrGreater()) return NS_OK; printf("Is XP or greater, running tests...\n"); nsresult rv; // File variables HANDLE hIndexed; nsCOMPtr<nsIFile> localFile; WCHAR filePath[MAX_PATH]; // Create and open temporary file hIndexed = CreateFileW(L".\\indexbit.txt", GENERIC_READ | GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, //FILE_ATTRIBUTE_NOT_CONTENT_INDEXED, not supported by cf NULL); if(hIndexed == INVALID_HANDLE_VALUE) { fail("Test Win Attribs: Creating Test File"); return NS_ERROR_FAILURE; } CloseHandle(hIndexed); GetFullPathNameW((LPCWSTR)L".\\indexbit.txt", MAX_PATH, filePath, NULL); //wprintf(filePath); //wprintf(L"\n"); rv = NS_NewLocalFile(nsEmbedString(filePath), false, getter_AddRefs(localFile)); if (NS_FAILED(rv)) { fail("Test Win Attribs: Opening Test File"); DeleteFileW(filePath); return rv; } nsCOMPtr<nsILocalFileWin> localFileWin(do_QueryInterface(localFile)); DWORD dwAttrs = GetFileAttributesW(filePath); if (dwAttrs == INVALID_FILE_ATTRIBUTES) { fail("Test Win Attribs: GetFileAttributesW - couldn't find our temp file."); DeleteFileW(filePath); return NS_ERROR_FAILURE; } dwAttrs |= FILE_ATTRIBUTE_NOT_CONTENT_INDEXED; SetFileAttributesW(filePath, dwAttrs); uint32_t attribs = 0; rv = localFileWin->GetFileAttributesWin(&attribs); if (NS_FAILED(rv)) { fail("Test Win Attribs: GetFileAttributesWin failed to GET attributes. (1)"); DeleteFileW(filePath); return NS_ERROR_FAILURE; } if (attribs & nsILocalFileWin::WFA_SEARCH_INDEXED) { fail("Test Win Attribs: GetFileAttributesWin attributed did not match. (2)"); DeleteFileW(filePath); return NS_ERROR_FAILURE; } dwAttrs &= ~FILE_ATTRIBUTE_NOT_CONTENT_INDEXED; SetFileAttributesW(filePath, dwAttrs); rv = localFileWin->GetFileAttributesWin(&attribs); if (NS_FAILED(rv)) { fail("Test Win Attribs: GetFileAttributesWin failed to GET attributes. (3)"); DeleteFileW(filePath); return NS_ERROR_FAILURE; } if (!(attribs & nsILocalFileWin::WFA_SEARCH_INDEXED)) { fail("Test Win Attribs: GetFileAttributesWin attributed did not match. (4)"); DeleteFileW(filePath); return NS_ERROR_FAILURE; } dwAttrs &= ~FILE_ATTRIBUTE_NOT_CONTENT_INDEXED; SetFileAttributesW(filePath, dwAttrs); attribs = nsILocalFileWin::WFA_SEARCH_INDEXED; rv = localFileWin->SetFileAttributesWin(attribs); dwAttrs = GetFileAttributesW(filePath); if (NS_FAILED(rv)) { fail("Test Win Attribs: GetFileAttributesWin failed to SET attributes. (5)"); DeleteFileW(filePath); return NS_ERROR_FAILURE; } if (dwAttrs & FILE_ATTRIBUTE_NOT_CONTENT_INDEXED) { fail("Test Win Attribs: SetFileAttributesWin attributed did not match. (6)"); DeleteFileW(filePath); return NS_ERROR_FAILURE; } dwAttrs |= FILE_ATTRIBUTE_NOT_CONTENT_INDEXED; SetFileAttributesW(filePath, dwAttrs); attribs = 0; rv = localFileWin->SetFileAttributesWin(attribs); dwAttrs = GetFileAttributesW(filePath); if (NS_FAILED(rv)) { fail("Test Win Attribs: GetFileAttributesWin failed to SET attributes. (7)"); DeleteFileW(filePath); return NS_ERROR_FAILURE; } if (!(dwAttrs & FILE_ATTRIBUTE_NOT_CONTENT_INDEXED)) { fail("Test Win Attribs: SetFileAttributesWin attributed did not match. (8)"); DeleteFileW(filePath); return NS_ERROR_FAILURE; } DeleteFileW(filePath); passed("Test Win Attribs: passed tests."); return NS_OK; }
nsresult StartupCache::Init() { // workaround for bug 653936 nsCOMPtr<nsIProtocolHandler> jarInitializer(do_GetService(NS_NETWORK_PROTOCOL_CONTRACTID_PREFIX "jar")); nsresult rv; mTable.Init(); #ifdef DEBUG mWriteObjectMap.Init(); #endif // This allows to override the startup cache filename // which is useful from xpcshell, when there is no ProfLDS directory to keep cache in. char *env = PR_GetEnv("MOZ_STARTUP_CACHE"); if (env) { rv = NS_NewLocalFile(NS_ConvertUTF8toUTF16(env), false, getter_AddRefs(mFile)); } else { nsCOMPtr<nsIFile> file; rv = NS_GetSpecialDirectory("ProfLDS", getter_AddRefs(file)); if (NS_FAILED(rv)) { // return silently, this will fail in mochitests's xpcshell process. return rv; } nsCOMPtr<nsIFile> profDir; NS_GetSpecialDirectory("ProfDS", getter_AddRefs(profDir)); if (profDir) { bool same; if (NS_SUCCEEDED(profDir->Equals(file, &same)) && !same) { // We no longer store the startup cache in the main profile // directory, so we should cleanup the old one. if (NS_SUCCEEDED( profDir->AppendNative(NS_LITERAL_CSTRING("startupCache")))) { profDir->Remove(true); } } } rv = file->AppendNative(NS_LITERAL_CSTRING("startupCache")); NS_ENSURE_SUCCESS(rv, rv); // Try to create the directory if it's not there yet rv = file->Create(nsIFile::DIRECTORY_TYPE, 0777); if (NS_FAILED(rv) && rv != NS_ERROR_FILE_ALREADY_EXISTS) return rv; rv = file->AppendNative(NS_LITERAL_CSTRING(sStartupCacheName)); NS_ENSURE_SUCCESS(rv, rv); mFile = do_QueryInterface(file); } NS_ENSURE_TRUE(mFile, NS_ERROR_UNEXPECTED); mObserverService = do_GetService("@mozilla.org/observer-service;1"); if (!mObserverService) { NS_WARNING("Could not get observerService."); return NS_ERROR_UNEXPECTED; } mListener = new StartupCacheListener(); rv = mObserverService->AddObserver(mListener, NS_XPCOM_SHUTDOWN_OBSERVER_ID, false); NS_ENSURE_SUCCESS(rv, rv); rv = mObserverService->AddObserver(mListener, "startupcache-invalidate", false); NS_ENSURE_SUCCESS(rv, rv); rv = LoadArchive(RECORD_AGE); // Sometimes we don't have a cache yet, that's ok. // If it's corrupted, just remove it and start over. if (gIgnoreDiskCache || (NS_FAILED(rv) && rv != NS_ERROR_FILE_NOT_FOUND)) { NS_WARNING("Failed to load startupcache file correctly, removing!"); InvalidateCache(); } mMappingReporter = new StartupCacheMappingReporter(); mDataReporter = new StartupCacheDataReporter(); NS_RegisterMemoryReporter(mMappingReporter); NS_RegisterMemoryReporter(mDataReporter); return NS_OK; }
bool DeviceStorageRequestChild::Recv__delete__(const DeviceStorageResponseValue& aValue) { if (mCallback) { mCallback->RequestComplete(); mCallback = nullptr; } switch (aValue.type()) { case DeviceStorageResponseValue::TErrorResponse: { ErrorResponse r = aValue; mRequest->FireError(r.error()); break; } case DeviceStorageResponseValue::TSuccessResponse: { jsval result = StringToJsval(mRequest->GetOwner(), mFile->mPath); mRequest->FireSuccess(result); break; } case DeviceStorageResponseValue::TBlobResponse: { BlobResponse r = aValue; BlobChild* actor = static_cast<BlobChild*>(r.blobChild()); nsCOMPtr<nsIDOMBlob> blob = actor->GetBlob(); nsCOMPtr<nsIDOMFile> file = do_QueryInterface(blob); jsval result = InterfaceToJsval(mRequest->GetOwner(), file, &NS_GET_IID(nsIDOMFile)); mRequest->FireSuccess(result); break; } case DeviceStorageResponseValue::TFreeSpaceStorageResponse: { FreeSpaceStorageResponse r = aValue; jsval result = JS_NumberValue(double(r.freeBytes())); mRequest->FireSuccess(result); break; } case DeviceStorageResponseValue::TUsedSpaceStorageResponse: { UsedSpaceStorageResponse r = aValue; jsval result = JS_NumberValue(double(r.usedBytes())); mRequest->FireSuccess(result); break; } case DeviceStorageResponseValue::TAvailableStorageResponse: { AvailableStorageResponse r = aValue; jsval result = StringToJsval(mRequest->GetOwner(), r.mountState()); mRequest->FireSuccess(result); break; } case DeviceStorageResponseValue::TEnumerationResponse: { EnumerationResponse r = aValue; nsDOMDeviceStorageCursor* cursor = static_cast<nsDOMDeviceStorageCursor*>(mRequest.get()); uint32_t count = r.paths().Length(); for (uint32_t i = 0; i < count; i++) { nsCOMPtr<nsIFile> f; nsresult rv = NS_NewLocalFile(r.paths()[i].fullpath(), false, getter_AddRefs(f)); if (NS_FAILED(rv)) { continue; } nsRefPtr<DeviceStorageFile> dsf = new DeviceStorageFile(r.paths()[i].type(), f); dsf->SetPath(r.paths()[i].name()); cursor->mFiles.AppendElement(dsf); } nsCOMPtr<ContinueCursorEvent> event = new ContinueCursorEvent(cursor); event->Continue(); break; } default: { NS_RUNTIMEABORT("not reached"); break; } } return true; }
//------------------------------------------------------------------------- nsresult nsClipboard::GetDataFromDataObject(IDataObject * aDataObject, UINT anIndex, nsIWidget * aWindow, nsITransferable * aTransferable) { // make sure we have a good transferable if ( !aTransferable ) return NS_ERROR_INVALID_ARG; nsresult res = NS_ERROR_FAILURE; // get flavor list that includes all flavors that can be written (including ones // obtained through conversion) nsCOMPtr<nsISupportsArray> flavorList; res = aTransferable->FlavorsTransferableCanImport ( getter_AddRefs(flavorList) ); if ( NS_FAILED(res) ) return NS_ERROR_FAILURE; // Walk through flavors and see which flavor is on the clipboard them on the native clipboard, PRUint32 i; PRUint32 cnt; flavorList->Count(&cnt); for (i=0;i<cnt;i++) { nsCOMPtr<nsISupports> genericFlavor; flavorList->GetElementAt ( i, getter_AddRefs(genericFlavor) ); nsCOMPtr<nsISupportsCString> currentFlavor ( do_QueryInterface(genericFlavor) ); if ( currentFlavor ) { nsXPIDLCString flavorStr; currentFlavor->ToString(getter_Copies(flavorStr)); UINT format = GetFormat(flavorStr); // Try to get the data using the desired flavor. This might fail, but all is // not lost. void* data = nullptr; PRUint32 dataLen = 0; bool dataFound = false; if (nullptr != aDataObject) { if ( NS_SUCCEEDED(GetNativeDataOffClipboard(aDataObject, anIndex, format, flavorStr, &data, &dataLen)) ) dataFound = true; } else if (nullptr != aWindow) { if ( NS_SUCCEEDED(GetNativeDataOffClipboard(aWindow, anIndex, format, &data, &dataLen)) ) dataFound = true; } // This is our second chance to try to find some data, having not found it // when directly asking for the flavor. Let's try digging around in other // flavors to help satisfy our craving for data. if ( !dataFound ) { if ( strcmp(flavorStr, kUnicodeMime) == 0 ) dataFound = FindUnicodeFromPlainText ( aDataObject, anIndex, &data, &dataLen ); else if ( strcmp(flavorStr, kURLMime) == 0 ) { // drags from other windows apps expose the native // CFSTR_INETURL{A,W} flavor dataFound = FindURLFromNativeURL ( aDataObject, anIndex, &data, &dataLen ); if ( !dataFound ) dataFound = FindURLFromLocalFile ( aDataObject, anIndex, &data, &dataLen ); } } // if we try one last ditch effort to find our data // Hopefully by this point we've found it and can go about our business if ( dataFound ) { nsCOMPtr<nsISupports> genericDataWrapper; if ( strcmp(flavorStr, kFileMime) == 0 ) { // we have a file path in |data|. Create an nsLocalFile object. nsDependentString filepath(reinterpret_cast<PRUnichar*>(data)); nsCOMPtr<nsIFile> file; if ( NS_SUCCEEDED(NS_NewLocalFile(filepath, false, getter_AddRefs(file))) ) genericDataWrapper = do_QueryInterface(file); nsMemory::Free(data); } else if ( strcmp(flavorStr, kNativeHTMLMime) == 0) { // the editor folks want CF_HTML exactly as it's on the clipboard, no conversions, // no fancy stuff. Pull it off the clipboard, stuff it into a wrapper and hand // it back to them. if ( FindPlatformHTML(aDataObject, anIndex, &data, &dataLen) ) nsPrimitiveHelpers::CreatePrimitiveForData ( flavorStr, data, dataLen, getter_AddRefs(genericDataWrapper) ); else { nsMemory::Free(data); continue; // something wrong with this flavor, keep looking for other data } nsMemory::Free(data); } else if ( strcmp(flavorStr, kJPEGImageMime) == 0 || strcmp(flavorStr, kJPGImageMime) == 0 || strcmp(flavorStr, kPNGImageMime) == 0) { nsIInputStream * imageStream = reinterpret_cast<nsIInputStream*>(data); genericDataWrapper = do_QueryInterface(imageStream); NS_IF_RELEASE(imageStream); } else { // we probably have some form of text. The DOM only wants LF, so convert from Win32 line // endings to DOM line endings. PRInt32 signedLen = static_cast<PRInt32>(dataLen); nsLinebreakHelpers::ConvertPlatformToDOMLinebreaks ( flavorStr, &data, &signedLen ); dataLen = signedLen; nsPrimitiveHelpers::CreatePrimitiveForData ( flavorStr, data, dataLen, getter_AddRefs(genericDataWrapper) ); nsMemory::Free(data); } NS_ASSERTION ( genericDataWrapper, "About to put null data into the transferable" ); aTransferable->SetTransferData(flavorStr, genericDataWrapper, dataLen); res = NS_OK; // we found one, get out of the loop break; } } } // foreach flavor return res; }
nsresult nsXREDirProvider::GetUserDataDirectoryHome(nsIFile** aFile, bool aLocal) { // Copied from nsAppFileLocationProvider (more or less) nsresult rv; nsCOMPtr<nsIFile> localDir; #if defined(XP_MACOSX) FSRef fsRef; OSType folderType; if (aLocal) { folderType = kCachedDataFolderType; } else { #ifdef MOZ_THUNDERBIRD folderType = kDomainLibraryFolderType; #else folderType = kApplicationSupportFolderType; #endif } OSErr err = ::FSFindFolder(kUserDomain, folderType, kCreateFolder, &fsRef); NS_ENSURE_FALSE(err, NS_ERROR_FAILURE); rv = NS_NewNativeLocalFile(EmptyCString(), true, getter_AddRefs(localDir)); NS_ENSURE_SUCCESS(rv, rv); nsCOMPtr<nsILocalFileMac> dirFileMac = do_QueryInterface(localDir); NS_ENSURE_TRUE(dirFileMac, NS_ERROR_UNEXPECTED); rv = dirFileMac->InitWithFSRef(&fsRef); NS_ENSURE_SUCCESS(rv, rv); localDir = do_QueryInterface(dirFileMac, &rv); #elif defined(XP_IOS) nsAutoCString userDir; if (GetUIKitDirectory(aLocal, userDir)) { rv = NS_NewNativeLocalFile(userDir, true, getter_AddRefs(localDir)); } else { rv = NS_ERROR_FAILURE; } NS_ENSURE_SUCCESS(rv, rv); #elif defined(XP_WIN) nsString path; if (aLocal) { rv = GetShellFolderPath(CSIDL_LOCAL_APPDATA, path); if (NS_FAILED(rv)) rv = GetRegWindowsAppDataFolder(aLocal, path); } if (!aLocal || NS_FAILED(rv)) { rv = GetShellFolderPath(CSIDL_APPDATA, path); if (NS_FAILED(rv)) { if (!aLocal) rv = GetRegWindowsAppDataFolder(aLocal, path); } } NS_ENSURE_SUCCESS(rv, rv); rv = NS_NewLocalFile(path, true, getter_AddRefs(localDir)); #elif defined(MOZ_WIDGET_GONK) rv = NS_NewNativeLocalFile(NS_LITERAL_CSTRING("/data/b2g"), true, getter_AddRefs(localDir)); #elif defined(XP_UNIX) const char* homeDir = getenv("HOME"); if (!homeDir || !*homeDir) return NS_ERROR_FAILURE; #ifdef ANDROID /* We want (ProfD == ProfLD) on Android. */ aLocal = false; #endif if (aLocal) { // If $XDG_CACHE_HOME is defined use it, otherwise use $HOME/.cache. const char* cacheHome = getenv("XDG_CACHE_HOME"); if (cacheHome && *cacheHome) { rv = NS_NewNativeLocalFile(nsDependentCString(cacheHome), true, getter_AddRefs(localDir)); } else { rv = NS_NewNativeLocalFile(nsDependentCString(homeDir), true, getter_AddRefs(localDir)); if (NS_SUCCEEDED(rv)) rv = localDir->AppendNative(NS_LITERAL_CSTRING(".cache")); } } else { rv = NS_NewNativeLocalFile(nsDependentCString(homeDir), true, getter_AddRefs(localDir)); } #else #error "Don't know how to get product dir on your platform" #endif NS_IF_ADDREF(*aFile = localDir); return rv; }
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; }