void UnregisterXULRunner(PRBool aRegisterGlobally, nsIFile* aLocation) { nsresult rv; char root[MAXPATHLEN] = "/etc/gre.d"; if (!aRegisterGlobally) { char *home = PR_GetEnv("HOME"); if (!home || !*home) return; PR_snprintf(root, MAXPATHLEN, "%s/.gre.d", home); } nsCOMPtr<nsIFile> savedInfoFile; aLocation->Clone(getter_AddRefs(savedInfoFile)); nsCOMPtr<nsILocalFile> localSaved (do_QueryInterface(savedInfoFile)); if (!localSaved) return; const char *infoname = aRegisterGlobally ? kRegFileGlobal : kRegFileUser; localSaved->AppendNative(nsDependentCString(infoname)); PRFileDesc* fd = nsnull; rv = localSaved->OpenNSPRFileDesc(PR_RDONLY, 0, &fd); if (NS_FAILED(rv)) { // XXX report error? return; } char keyName[MAXPATHLEN]; PRInt32 r = PR_Read(fd, keyName, MAXPATHLEN); PR_Close(fd); localSaved->Remove(PR_FALSE); if (r <= 0) return; keyName[r] = '\0'; char regFile[MAXPATHLEN]; PR_snprintf(regFile, MAXPATHLEN, "%s/%s.conf", root, keyName); nsCOMPtr<nsILocalFile> lf; rv = NS_NewNativeLocalFile(nsDependentCString(regFile), PR_FALSE, getter_AddRefs(lf)); if (NS_FAILED(rv)) return; nsINIParser p; rv = p.Init(lf); if (NS_FAILED(rv)) return; rv = p.GetString(kGREBuildID, "GRE_PATH", root, MAXPATHLEN); if (NS_FAILED(rv)) return; rv = NS_NewNativeLocalFile(nsDependentCString(root), PR_TRUE, getter_AddRefs(lf)); if (NS_FAILED(rv)) return; PRBool eq; if (NS_SUCCEEDED(aLocation->Equals(lf, &eq)) && eq) PR_Delete(regFile); }
bool nsProfileMigrator::ImportRegistryProfiles(const nsACString& aAppName) { nsresult rv; nsCOMPtr<nsIToolkitProfileService> profileSvc (do_GetService(NS_PROFILESERVICE_CONTRACTID)); NS_ENSURE_TRUE(profileSvc, PR_FALSE); nsCOMPtr<nsIProperties> dirService (do_GetService("@mozilla.org/file/directory_service;1")); NS_ENSURE_TRUE(dirService, PR_FALSE); nsCOMPtr<nsILocalFile> regFile; #ifdef XP_WIN rv = dirService->Get(NS_WIN_APPDATA_DIR, NS_GET_IID(nsILocalFile), getter_AddRefs(regFile)); NS_ENSURE_SUCCESS(rv, PR_FALSE); regFile->AppendNative(aAppName); regFile->AppendNative(NS_LITERAL_CSTRING("registry.dat")); #elif defined(XP_MACOSX) rv = dirService->Get(NS_MAC_USER_LIB_DIR, NS_GET_IID(nsILocalFile), getter_AddRefs(regFile)); NS_ENSURE_SUCCESS(rv, PR_FALSE); regFile->AppendNative(aAppName); regFile->AppendNative(NS_LITERAL_CSTRING("Application Registry")); #elif defined(XP_OS2) rv = dirService->Get(NS_OS2_HOME_DIR, NS_GET_IID(nsILocalFile), getter_AddRefs(regFile)); NS_ENSURE_SUCCESS(rv, PR_FALSE); regFile->AppendNative(aAppName); regFile->AppendNative(NS_LITERAL_CSTRING("registry.dat")); #else rv = dirService->Get(NS_UNIX_HOME_DIR, NS_GET_IID(nsILocalFile), getter_AddRefs(regFile)); NS_ENSURE_SUCCESS(rv, PR_FALSE); nsCAutoString dotAppName; ToLowerCase(aAppName, dotAppName); dotAppName.Insert('.', 0); regFile->AppendNative(dotAppName); regFile->AppendNative(NS_LITERAL_CSTRING("appreg")); #endif nsCAutoString path; rv = regFile->GetNativePath(path); NS_ENSURE_SUCCESS(rv, PR_FALSE); if (NR_StartupRegistry()) return PR_FALSE; bool migrated = false; HREG reg = nsnull; RKEY profiles = 0; REGENUM enumstate = 0; char profileName[MAXREGNAMELEN]; if (NR_RegOpen(path.get(), ®)) goto cleanup; if (NR_RegGetKey(reg, ROOTKEY_COMMON, "Profiles", &profiles)) goto cleanup; while (!NR_RegEnumSubkeys(reg, profiles, &enumstate, profileName, MAXREGNAMELEN, REGENUM_CHILDREN)) { #ifdef DEBUG_bsmedberg printf("Found profile %s.\n", profileName); #endif RKEY profile = 0; if (NR_RegGetKey(reg, profiles, profileName, &profile)) { NS_ERROR("Could not get the key that was enumerated."); continue; } char profilePath[MAXPATHLEN]; if (NR_RegGetEntryString(reg, profile, "directory", profilePath, MAXPATHLEN)) continue; nsCOMPtr<nsILocalFile> profileFile (do_CreateInstance("@mozilla.org/file/local;1")); if (!profileFile) continue; #if defined (XP_MACOSX) rv = profileFile->SetPersistentDescriptor(nsDependentCString(profilePath)); #else NS_ConvertUTF8toUTF16 widePath(profilePath); rv = profileFile->InitWithPath(widePath); #endif if (NS_FAILED(rv)) continue; nsCOMPtr<nsIToolkitProfile> tprofile; profileSvc->CreateProfile(profileFile, nsnull, nsDependentCString(profileName), getter_AddRefs(tprofile)); migrated = PR_TRUE; } cleanup: if (reg) NR_RegClose(reg); NR_ShutdownRegistry(); return migrated; }
void GfxInfo::GetData() { // to understand this function, see bug 639842. We retrieve the OpenGL driver information in a // separate process to protect against bad drivers. // if glxtest_pipe == 0, that means that we already read the information if (!glxtest_pipe) return; enum { buf_size = 1024 }; char buf[buf_size]; ssize_t bytesread = read(glxtest_pipe, &buf, buf_size-1); // -1 because we'll append a zero close(glxtest_pipe); glxtest_pipe = 0; // bytesread < 0 would mean that the above read() call failed. This should never happen. if (bytesread < 0) bytesread = 0; // let buf be a zero-terminated string buf[bytesread] = 0; // Wait for the glxtest process to finish. This serves 2 purposes: // * avoid having a zombie glxtest process laying around // * get the glxtest process status info. int glxtest_status = 0; bool wait_for_glxtest_process = true; bool waiting_for_glxtest_process_failed = false; while(wait_for_glxtest_process) { wait_for_glxtest_process = false; if (waitpid(glxtest_pid, &glxtest_status, 0) == -1) { if (errno == EINTR) wait_for_glxtest_process = true; else waiting_for_glxtest_process_failed = true; } } bool exited_with_error_code = !waiting_for_glxtest_process_failed && WIFEXITED(glxtest_status) && WEXITSTATUS(glxtest_status) != EXIT_SUCCESS; bool received_signal = !waiting_for_glxtest_process_failed && WIFSIGNALED(glxtest_status); bool error = waiting_for_glxtest_process_failed || exited_with_error_code || received_signal; nsCString *stringToFill = nsnull; char *bufptr = buf; if (!error) { while(true) { char *line = NS_strtok("\n", &bufptr); if (!line) break; if (stringToFill) { stringToFill->Assign(line); stringToFill = nsnull; } else if(!strcmp(line, "VENDOR")) stringToFill = &mVendor; else if(!strcmp(line, "RENDERER")) stringToFill = &mRenderer; else if(!strcmp(line, "VERSION")) stringToFill = &mVersion; } } const char *spoofedVendor = PR_GetEnv("MOZ_GFX_SPOOF_GL_VENDOR"); if (spoofedVendor) mVendor.Assign(spoofedVendor); const char *spoofedRenderer = PR_GetEnv("MOZ_GFX_SPOOF_GL_RENDERER"); if (spoofedRenderer) mRenderer.Assign(spoofedRenderer); const char *spoofedVersion = PR_GetEnv("MOZ_GFX_SPOOF_GL_VERSION"); if (spoofedVersion) mVersion.Assign(spoofedVersion); if (error || mVendor.IsEmpty() || mRenderer.IsEmpty() || mVersion.IsEmpty()) { mAdapterDescription.AppendLiteral("GLXtest process failed"); if (waiting_for_glxtest_process_failed) mAdapterDescription.AppendLiteral(" (waitpid failed)"); if (exited_with_error_code) mAdapterDescription.AppendPrintf(" (exited with status %d)", WEXITSTATUS(glxtest_status)); if (received_signal) mAdapterDescription.AppendPrintf(" (received signal %d)", WTERMSIG(glxtest_status)); if (bytesread) { mAdapterDescription.AppendLiteral(": "); mAdapterDescription.Append(nsDependentCString(buf)); mAdapterDescription.AppendLiteral("\n"); } #ifdef MOZ_CRASHREPORTER CrashReporter::AppendAppNotesToCrashReport(mAdapterDescription); #endif return; } mAdapterDescription.Append(mVendor); mAdapterDescription.AppendLiteral(" -- "); mAdapterDescription.Append(mRenderer); nsCAutoString note; note.Append("OpenGL: "); note.Append(mAdapterDescription); note.Append(" -- "); note.Append(mVersion); note.Append("\n"); #ifdef MOZ_CRASHREPORTER CrashReporter::AppendAppNotesToCrashReport(note); #endif // determine driver type (vendor) and where in the version string // the actual driver version numbers should be expected to be found (whereToReadVersionNumbers) const char *whereToReadVersionNumbers = nsnull; const char *Mesa_in_version_string = strstr(mVersion.get(), "Mesa"); if (Mesa_in_version_string) { mIsMesa = true; // with Mesa, the version string contains "Mesa major.minor" and that's all the version information we get: // there is no actual driver version info. whereToReadVersionNumbers = Mesa_in_version_string + strlen("Mesa"); } else if (strstr(mVendor.get(), "NVIDIA Corporation")) { mIsNVIDIA = true; // with the NVIDIA driver, the version string contains "NVIDIA major.minor" // note that here the vendor and version strings behave differently, that's why we don't put this above // alongside Mesa_in_version_string. const char *NVIDIA_in_version_string = strstr(mVersion.get(), "NVIDIA"); if (NVIDIA_in_version_string) whereToReadVersionNumbers = NVIDIA_in_version_string + strlen("NVIDIA"); } else if (strstr(mVendor.get(), "ATI Technologies Inc")) { mIsFGLRX = true; // with the FGLRX driver, the version string only gives a OpenGL version :/ so let's return that. // that can at least give a rough idea of how old the driver is. whereToReadVersionNumbers = mVersion.get(); } // read major.minor version numbers if (whereToReadVersionNumbers) { // copy into writable buffer, for tokenization strncpy(buf, whereToReadVersionNumbers, buf_size); bufptr = buf; // now try to read major.minor version numbers. In case of failure, gracefully exit: these numbers have // been initialized as 0 anyways char *token = NS_strtok(".", &bufptr); if (token) { mMajorVersion = strtol(token, 0, 10); token = NS_strtok(".", &bufptr); if (token) mMinorVersion = strtol(token, 0, 10); } } }
static int MimeObject_initialize (MimeObject *obj) { /* This is an abstract class; it shouldn't be directly instantiated. */ NS_ASSERTION(obj->clazz != &mimeObjectClass, "should directly instantiate abstract class"); /* Set up the content-type and encoding. */ if (!obj->content_type && obj->headers) obj->content_type = MimeHeaders_get (obj->headers, HEADER_CONTENT_TYPE, PR_TRUE, PR_FALSE); if (!obj->encoding && obj->headers) obj->encoding = MimeHeaders_get (obj->headers, HEADER_CONTENT_TRANSFER_ENCODING, PR_TRUE, PR_FALSE); /* Special case to normalize some types and encodings to a canonical form. (These are nonstandard types/encodings which have been seen to appear in multiple forms; we normalize them so that things like looking up icons and extensions has consistent behavior for the receiver, regardless of the "alias" type that the sender used.) */ if (!obj->content_type || !*(obj->content_type)) ; else if (!PL_strcasecmp(obj->content_type, APPLICATION_UUENCODE2) || !PL_strcasecmp(obj->content_type, APPLICATION_UUENCODE3) || !PL_strcasecmp(obj->content_type, APPLICATION_UUENCODE4)) { PR_Free(obj->content_type); obj->content_type = strdup(APPLICATION_UUENCODE); } else if (!PL_strcasecmp(obj->content_type, IMAGE_XBM2) || !PL_strcasecmp(obj->content_type, IMAGE_XBM3)) { PR_Free(obj->content_type); obj->content_type = strdup(IMAGE_XBM); } else { // MIME-types are case-insenitive, but let's make it lower case internally // to avoid some hassle later down the road. nsCAutoString lowerCaseContentType; ToLowerCase(nsDependentCString(obj->content_type), lowerCaseContentType); PR_Free(obj->content_type); obj->content_type = ToNewCString(lowerCaseContentType); } if (!obj->encoding) ; else if (!PL_strcasecmp(obj->encoding, ENCODING_UUENCODE2) || !PL_strcasecmp(obj->encoding, ENCODING_UUENCODE3) || !PL_strcasecmp(obj->encoding, ENCODING_UUENCODE4)) { PR_Free(obj->encoding); obj->encoding = strdup(ENCODING_UUENCODE); } else if (!PL_strcasecmp(obj->encoding, ENCODING_COMPRESS2)) { PR_Free(obj->encoding); obj->encoding = strdup(ENCODING_COMPRESS); } else if (!PL_strcasecmp(obj->encoding, ENCODING_GZIP2)) { PR_Free(obj->encoding); obj->encoding = strdup(ENCODING_GZIP); } return 0; }
NS_IMETHODIMP nsDeviceContextSpecQt::GetSurfaceForPrinter( gfxASurface** aSurface) { NS_ENSURE_ARG_POINTER(aSurface); *aSurface = nsnull; double width, height; mPrintSettings->GetEffectivePageSize(&width, &height); // If we're in landscape mode, we'll be rotating the output -- // need to swap width & height. PRInt32 orientation; mPrintSettings->GetOrientation(&orientation); if (nsIPrintSettings::kLandscapeOrientation == orientation) { double tmp = width; width = height; height = tmp; } // convert twips to points width /= TWIPS_PER_POINT_FLOAT; height /= TWIPS_PER_POINT_FLOAT; DO_PR_DEBUG_LOG(("\"%s\", %f, %f\n", mPath, width, height)); QTemporaryFile file; if(!file.open()) { return NS_ERROR_GFX_PRINTER_COULD_NOT_OPEN_FILE; } file.setAutoRemove(false); nsresult rv = NS_NewNativeLocalFile( nsDependentCString(file.fileName().toAscii().constData()), PR_FALSE, getter_AddRefs(mSpoolFile)); if (NS_FAILED(rv)) { file.remove(); return NS_ERROR_GFX_PRINTER_COULD_NOT_OPEN_FILE; } mSpoolName = file.fileName().toUtf8().constData(); mSpoolFile->SetPermissions(0600); nsCOMPtr<nsIFileOutputStream> stream = do_CreateInstance("@mozilla.org/network/file-output-stream;1"); rv = stream->Init(mSpoolFile, -1, -1, 0); if (NS_FAILED(rv)) return rv; PRInt16 format; mPrintSettings->GetOutputFormat(&format); nsRefPtr<gfxASurface> surface; gfxSize surfaceSize(width, height); if (format == nsIPrintSettings::kOutputFormatNative) { if (mIsPPreview) { // There is nothing to detect on Print Preview, use PS. // TODO: implement for Qt? //format = nsIPrintSettings::kOutputFormatPS; return NS_ERROR_NOT_IMPLEMENTED; } format = nsIPrintSettings::kOutputFormatPDF; } if (format == nsIPrintSettings::kOutputFormatPDF) { surface = new gfxPDFSurface(stream, surfaceSize); } else { return NS_ERROR_NOT_IMPLEMENTED; } NS_ABORT_IF_FALSE(surface, "valid address expected"); surface.swap(*aSurface); return NS_OK; }
//////////////////////////////////////////////////////////////////////////////////// // Utility Functions for MsgFolders //////////////////////////////////////////////////////////////////////////////////// nsresult LocateMessageFolder(nsIMsgIdentity *userIdentity, nsMsgDeliverMode aFolderType, const char *aFolderURI, nsIMsgFolder **msgFolder) { nsresult rv = NS_OK; if (!msgFolder) return NS_ERROR_NULL_POINTER; *msgFolder = nullptr; if (!aFolderURI || !*aFolderURI) return NS_ERROR_INVALID_ARG; // as long as it doesn't start with anyfolder:// if (PL_strncasecmp(ANY_SERVER, aFolderURI, strlen(aFolderURI)) != 0) { nsCOMPtr<nsIRDFService> rdf(do_GetService(kRDFServiceCID, &rv)); if (NS_FAILED(rv)) return rv; // get the corresponding RDF resource // RDF will create the folder resource if it doesn't already exist nsCOMPtr<nsIRDFResource> resource; rv = rdf->GetResource(nsDependentCString(aFolderURI), getter_AddRefs(resource)); if (NS_FAILED(rv)) return rv; nsCOMPtr <nsIMsgFolder> folderResource; folderResource = do_QueryInterface(resource, &rv); if (NS_SUCCEEDED(rv) && folderResource) { // don't check validity of folder - caller will handle creating it nsCOMPtr<nsIMsgIncomingServer> server; //make sure that folder hierarchy is built so that legitimate parent-child relationship is established rv = folderResource->GetServer(getter_AddRefs(server)); NS_ENSURE_SUCCESS(rv,rv); return server->GetMsgFolderFromURI(folderResource, nsDependentCString(aFolderURI), msgFolder); } else { return NS_ERROR_FAILURE; } } else { uint32_t cnt = 0; uint32_t i; if (!userIdentity) return NS_ERROR_INVALID_ARG; // get the account manager nsCOMPtr<nsIMsgAccountManager> accountManager = do_GetService(NS_MSGACCOUNTMANAGER_CONTRACTID, &rv); if (NS_FAILED(rv)) return rv; // If any folder will do, go look for one. nsCOMPtr<nsIArray> retval; accountManager->GetServersForIdentity(userIdentity, getter_AddRefs(retval)); if (!retval) return NS_ERROR_FAILURE; // Ok, we have to look through the servers and try to find the server that // has a valid folder of the type that interests us... rv = retval->GetLength(&cnt); if (NS_FAILED(rv)) return rv; for (i=0; i<cnt; i++) { // Now that we have the server...we need to get the named message folder nsCOMPtr<nsIMsgIncomingServer> inServer; inServer = do_QueryElementAt(retval, i, &rv); if(NS_FAILED(rv) || (!inServer)) continue; // // If aFolderURI is passed in, then the user has chosen a specific // mail folder to save the message, but if it is null, just find the // first one and make that work. The folder is specified as a URI, like // the following: // // mailbox://nobody@Local Folders/Sent // imap://rhp@nsmail-2/Drafts // newsgroup://news.mozilla.org/netscape.test // nsCString serverURI; rv = inServer->GetServerURI(serverURI); if (NS_FAILED(rv) || serverURI.IsEmpty()) continue; nsCOMPtr<nsIMsgFolder> rootFolder; rv = inServer->GetRootFolder(getter_AddRefs(rootFolder)); if(NS_FAILED(rv) || (!rootFolder)) continue; // use the defaults by getting the folder by flags if (aFolderType == nsIMsgSend::nsMsgQueueForLater || aFolderType == nsIMsgSend::nsMsgDeliverBackground) { // QueueForLater (Outbox) rootFolder->GetFolderWithFlags(nsMsgFolderFlags::Queue, msgFolder); } else if (aFolderType == nsIMsgSend::nsMsgSaveAsDraft) // SaveAsDraft (Drafts) { rootFolder->GetFolderWithFlags(nsMsgFolderFlags::Drafts, msgFolder); } else if (aFolderType == nsIMsgSend::nsMsgSaveAsTemplate) // SaveAsTemplate (Templates) { rootFolder->GetFolderWithFlags(nsMsgFolderFlags::Templates, msgFolder); } else // SaveInSentFolder (Sent) - nsMsgDeliverNow or nsMsgSendUnsent { rootFolder->GetFolderWithFlags(nsMsgFolderFlags::SentMail, msgFolder); } if (*msgFolder) { return NS_OK; } } } return NS_ERROR_FAILURE; }
static void ProxiedAuthCallback(gconstpointer in, gsize in_size, gpointer out, gsize out_size, gpointer callback_data) { GnomeVFSModuleCallbackAuthenticationIn *authIn = (GnomeVFSModuleCallbackAuthenticationIn *) in; GnomeVFSModuleCallbackAuthenticationOut *authOut = (GnomeVFSModuleCallbackAuthenticationOut *) out; LOG(("gnomevfs: ProxiedAuthCallback [uri=%s]\n", authIn->uri)); // Without a channel, we have no way of getting a prompter. nsIChannel *channel = (nsIChannel *) callback_data; if (!channel) return; nsCOMPtr<nsIAuthPrompt> prompt; NS_QueryNotificationCallbacks(channel, prompt); // If no auth prompt, then give up. We could failover to using the // WindowWatcher service, but that might defeat a consumer's purposeful // attempt to disable authentication (for whatever reason). if (!prompt) return; // Parse out the host and port... nsCOMPtr<nsIURI> uri; channel->GetURI(getter_AddRefs(uri)); if (!uri) return; #ifdef DEBUG { // // Make sure authIn->uri is consistent with the channel's URI. // // XXX This check is probably not IDN safe, and it might incorrectly // fire as a result of escaping differences. It's unclear what // kind of transforms GnomeVFS might have applied to the URI spec // that we originally gave to it. In spite of the likelihood of // false hits, this check is probably still valuable. // nsAutoCString spec; uri->GetSpec(spec); int uriLen = strlen(authIn->uri); if (!StringHead(spec, uriLen).Equals(nsDependentCString(authIn->uri, uriLen))) { LOG(("gnomevfs: [spec=%s authIn->uri=%s]\n", spec.get(), authIn->uri)); NS_ERROR("URI mismatch"); } } #endif nsAutoCString scheme, hostPort; uri->GetScheme(scheme); uri->GetHostPort(hostPort); // It doesn't make sense for either of these strings to be empty. What kind // of funky URI is this? if (scheme.IsEmpty() || hostPort.IsEmpty()) return; // Construct the single signon key. Altering the value of this key will // cause people's remembered passwords to be forgotten. Think carefully // before changing the way this key is constructed. nsAutoString key, realm; NS_ConvertUTF8toUTF16 dispHost(scheme); dispHost.Append(NS_LITERAL_STRING("://")); dispHost.Append(NS_ConvertUTF8toUTF16(hostPort)); key = dispHost; if (authIn->realm) { // We assume the realm string is ASCII. That might be a bogus assumption, // but we have no idea what encoding GnomeVFS is using, so for now we'll // limit ourselves to ISO-Latin-1. XXX What is a better solution? realm.Append('"'); realm.Append(NS_ConvertASCIItoUTF16(authIn->realm)); realm.Append('"'); key.Append(' '); key.Append(realm); } // Construct the message string... // // We use Necko's string bundle here. This code really should be encapsulated // behind some Necko API, after all this code is based closely on the code in // nsHttpChannel.cpp. nsCOMPtr<nsIStringBundleService> bundleSvc = do_GetService(NS_STRINGBUNDLE_CONTRACTID); if (!bundleSvc) return; nsCOMPtr<nsIStringBundle> bundle; bundleSvc->CreateBundle("chrome://global/locale/commonDialogs.properties", getter_AddRefs(bundle)); if (!bundle) return; nsString message; if (!realm.IsEmpty()) { const PRUnichar *strings[] = { realm.get(), dispHost.get() }; bundle->FormatStringFromName(NS_LITERAL_STRING("EnterUserPasswordForRealm").get(), strings, 2, getter_Copies(message)); } else { const PRUnichar *strings[] = { dispHost.get() }; bundle->FormatStringFromName(NS_LITERAL_STRING("EnterUserPasswordFor").get(), strings, 1, getter_Copies(message)); } if (message.IsEmpty()) return; // Prompt the user... nsresult rv; bool retval = false; PRUnichar *user = nullptr, *pass = nullptr; rv = prompt->PromptUsernameAndPassword(nullptr, message.get(), key.get(), nsIAuthPrompt::SAVE_PASSWORD_PERMANENTLY, &user, &pass, &retval); if (NS_FAILED(rv)) return; if (!retval || !user || !pass) return; // XXX We need to convert the UTF-16 username and password from our dialog to // strings that GnomeVFS can understand. It's unclear what encoding GnomeVFS // expects, so for now we assume 7-bit ASCII. Hopefully, we can get a better // solution at some point. // One copy is never enough... authOut->username = g_strdup(NS_LossyConvertUTF16toASCII(user).get()); authOut->password = g_strdup(NS_LossyConvertUTF16toASCII(pass).get()); nsMemory::Free(user); nsMemory::Free(pass); }
static void convertNameValue(VObject *vObj, nsIAbCard *aCard) { const char *cardPropName = NULL; // if the vCard property is not a root property then we need to determine its exact property. // a good example of this is VCTelephoneProp, this prop has four objects underneath it: // fax, work and home and cellular. if (PL_strcasecmp(VCCityProp, vObjectName(vObj)) == 0) cardPropName = kWorkCityProperty; else if (PL_strcasecmp(VCTelephoneProp, vObjectName(vObj)) == 0) { if (isAPropertyOf(vObj, VCFaxProp)) cardPropName = kFaxProperty; else if (isAPropertyOf(vObj, VCWorkProp)) cardPropName = kWorkPhoneProperty; else if (isAPropertyOf(vObj, VCHomeProp)) cardPropName = kHomePhoneProperty; else if (isAPropertyOf(vObj, VCCellularProp)) cardPropName = kCellularProperty; else if (isAPropertyOf(vObj, VCPagerProp)) cardPropName = kPagerProperty; else return; } else if (PL_strcasecmp(VCEmailAddressProp, vObjectName(vObj)) == 0) cardPropName = kPriEmailProperty; else if (PL_strcasecmp(VCFamilyNameProp, vObjectName(vObj)) == 0) cardPropName = kLastNameProperty; else if (PL_strcasecmp(VCFullNameProp, vObjectName(vObj)) == 0) cardPropName = kDisplayNameProperty; else if (PL_strcasecmp(VCGivenNameProp, vObjectName(vObj)) == 0) cardPropName = kFirstNameProperty; else if (PL_strcasecmp(VCOrgNameProp, vObjectName(vObj)) == 0) cardPropName = kCompanyProperty; else if (PL_strcasecmp(VCOrgUnitProp, vObjectName(vObj)) == 0) cardPropName = kDepartmentProperty; else if (PL_strcasecmp(VCPostalCodeProp, vObjectName(vObj)) == 0) cardPropName = kWorkZipCodeProperty; else if (PL_strcasecmp(VCRegionProp, vObjectName(vObj)) == 0) cardPropName = kWorkStateProperty; else if (PL_strcasecmp(VCStreetAddressProp, vObjectName(vObj)) == 0) cardPropName = kWorkAddressProperty; else if (PL_strcasecmp(VCPostalBoxProp, vObjectName(vObj)) == 0) cardPropName = kWorkAddress2Property; else if (PL_strcasecmp(VCCountryNameProp, vObjectName(vObj)) == 0) cardPropName = kWorkCountryProperty; else if (PL_strcasecmp(VCTitleProp, vObjectName(vObj)) == 0) cardPropName = kJobTitleProperty; else if (PL_strcasecmp(VCUseHTML, vObjectName(vObj)) == 0) cardPropName = kPreferMailFormatProperty; else if (PL_strcasecmp(VCNoteProp, vObjectName(vObj)) == 0) cardPropName = kNotesProperty; else if (PL_strcasecmp(VCURLProp, vObjectName(vObj)) == 0) cardPropName = kWorkWebPageProperty; else return; if (!VALUE_TYPE(vObj)) return; char *cardPropValue = getCString(vObj); aCard->SetPropertyAsAUTF8String(cardPropName, nsDependentCString(cardPropValue)); PR_FREEIF(cardPropValue); return; }
nsresult nsAbManager::ExportDirectoryToLDIF(nsIAbDirectory *aDirectory, nsILocalFile *aLocalFile) { nsCOMPtr <nsISimpleEnumerator> cardsEnumerator; nsCOMPtr <nsIAbCard> card; nsresult rv; nsCOMPtr <nsIOutputStream> outputStream; rv = MsgNewBufferedFileOutputStream(getter_AddRefs(outputStream), aLocalFile, PR_CREATE_FILE | PR_WRONLY | PR_TRUNCATE, 0664); // the desired file may be read only if (NS_FAILED(rv)) return rv; // Get the default attribute map for ldap. We use the default attribute // map rather than one for a specific server because if people want an // ldif export using a servers specific schema, then they can use ldapsearch nsCOMPtr<nsIAbLDAPAttributeMapService> mapSrv = do_GetService("@mozilla.org/addressbook/ldap-attribute-map-service;1", &rv); NS_ENSURE_SUCCESS(rv, rv); nsCOMPtr<nsIAbLDAPAttributeMap> attrMap; rv = mapSrv->GetMapForPrefBranch(NS_LITERAL_CSTRING("ldap_2.servers.default.attrmap"), getter_AddRefs(attrMap)); NS_ENSURE_SUCCESS(rv, rv); PRUint32 i; PRUint32 writeCount; PRUint32 length; rv = aDirectory->GetChildCards(getter_AddRefs(cardsEnumerator)); if (NS_SUCCEEDED(rv) && cardsEnumerator) { nsCOMPtr<nsISupports> item; bool more; while (NS_SUCCEEDED(cardsEnumerator->HasMoreElements(&more)) && more) { rv = cardsEnumerator->GetNext(getter_AddRefs(item)); if (NS_SUCCEEDED(rv)) { nsCOMPtr <nsIAbCard> card = do_QueryInterface(item, &rv); NS_ENSURE_SUCCESS(rv,rv); bool isMailList; rv = card->GetIsMailList(&isMailList); NS_ENSURE_SUCCESS(rv,rv); if (isMailList) { nsCString mailListCStr; rv = AppendLDIFForMailList(card, attrMap, mailListCStr); NS_ENSURE_SUCCESS(rv,rv); length = mailListCStr.Length(); rv = outputStream->Write(mailListCStr.get(), length, &writeCount); NS_ENSURE_SUCCESS(rv,rv); if (length != writeCount) return NS_ERROR_FAILURE; } else { nsString value; nsCString valueCStr; rv = AppendBasicLDIFForCard(card, attrMap, valueCStr); NS_ENSURE_SUCCESS(rv,rv); length = valueCStr.Length(); rv = outputStream->Write(valueCStr.get(), length, &writeCount); NS_ENSURE_SUCCESS(rv,rv); if (length != writeCount) return NS_ERROR_FAILURE; valueCStr.Truncate(); nsCAutoString ldapAttribute; for (i = 0; i < NS_ARRAY_LENGTH(EXPORT_ATTRIBUTES_TABLE); i++) { if (NS_SUCCEEDED(attrMap->GetFirstAttribute(nsDependentCString(EXPORT_ATTRIBUTES_TABLE[i].abPropertyName), ldapAttribute)) && !ldapAttribute.IsEmpty()) { rv = card->GetPropertyAsAString(EXPORT_ATTRIBUTES_TABLE[i].abPropertyName, value); if (NS_FAILED(rv)) value.Truncate(); if (!PL_strcmp(EXPORT_ATTRIBUTES_TABLE[i].abPropertyName, kPreferMailFormatProperty)) { if (value.EqualsLiteral("html")) value.AssignLiteral("true"); else if (value.EqualsLiteral("plaintext")) value.AssignLiteral("false"); else value.Truncate(); // unknown. } if (!value.IsEmpty()) { rv = AppendProperty(ldapAttribute.get(), value.get(), valueCStr); NS_ENSURE_SUCCESS(rv,rv); valueCStr += MSG_LINEBREAK; } else valueCStr.Truncate(); length = valueCStr.Length(); if (length) { rv = outputStream->Write(valueCStr.get(), length, &writeCount); NS_ENSURE_SUCCESS(rv,rv); if (length != writeCount) return NS_ERROR_FAILURE; } valueCStr.Truncate(); } else { // something we don't support yet // ldif doesn't export multiple addresses } } // write out the linebreak that separates the cards rv = outputStream->Write(MSG_LINEBREAK, MSG_LINEBREAK_LEN, &writeCount); NS_ENSURE_SUCCESS(rv,rv); if (MSG_LINEBREAK_LEN != writeCount) return NS_ERROR_FAILURE; } } } } rv = outputStream->Flush(); NS_ENSURE_SUCCESS(rv,rv); rv = outputStream->Close(); NS_ENSURE_SUCCESS(rv,rv); return NS_OK; }
// |decode_mime_part2_str| taken from comi18n.c // Decode RFC2047-encoded words in the input and convert the result to UTF-8. // If aOverrideCharset is true, charset in RFC2047-encoded words is // ignored and aDefaultCharset is assumed, instead. aDefaultCharset // is also used to convert raw octets (without RFC 2047 encoding) to UTF-8. //static nsresult DecodeRFC2047Str(const char *aHeader, const char *aDefaultCharset, bool aOverrideCharset, nsACString &aResult) { const char *p, *q, *r; char *decodedText; const char *begin; // tracking pointer for where we are in the input buffer PRInt32 isLastEncodedWord = 0; const char *charsetStart, *charsetEnd; char charset[80]; // initialize charset name to an empty string charset[0] = '\0'; begin = aHeader; // To avoid buffer realloc, if possible, set capacity in advance. No // matter what, more than 3x expansion can never happen for all charsets // supported by Mozilla. SCSU/BCSU with the sliding window set to a // non-BMP block may be exceptions, but Mozilla does not support them. // Neither any known mail/news program use them. Even if there's, we're // safe because we don't use a raw *char any more. aResult.SetCapacity(3 * strlen(aHeader)); while ((p = PL_strstr(begin, "=?")) != 0) { if (isLastEncodedWord) { // See if it's all whitespace. for (q = begin; q < p; ++q) { if (!PL_strchr(" \t\r\n", *q)) break; } } if (!isLastEncodedWord || q < p) { // copy the part before the encoded-word CopyRawHeader(begin, p - begin, aDefaultCharset, aResult); begin = p; } p += 2; // Get charset info charsetStart = p; charsetEnd = 0; for (q = p; *q != '?'; q++) { if (*q <= ' ' || PL_strchr(especials, *q)) { goto badsyntax; } // RFC 2231 section 5 if (!charsetEnd && *q == '*') { charsetEnd = q; } } if (!charsetEnd) { charsetEnd = q; } // Check for too-long charset name if (PRUint32(charsetEnd - charsetStart) >= sizeof(charset)) goto badsyntax; memcpy(charset, charsetStart, charsetEnd - charsetStart); charset[charsetEnd - charsetStart] = 0; q++; if (*q != 'Q' && *q != 'q' && *q != 'B' && *q != 'b') goto badsyntax; if (q[1] != '?') goto badsyntax; r = q; for (r = q + 2; *r != '?'; r++) { if (*r < ' ') goto badsyntax; } if (r[1] != '=') goto badsyntax; else if (r == q + 2) { // it's empty, skip begin = r + 2; isLastEncodedWord = 1; continue; } if(*q == 'Q' || *q == 'q') decodedText = DecodeQ(q + 2, r - (q + 2)); else { // bug 227290. ignore an extraneous '=' at the end. // (# of characters in B-encoded part has to be a multiple of 4) PRInt32 n = r - (q + 2); n -= (n % 4 == 1 && !PL_strncmp(r - 3, "===", 3)) ? 1 : 0; decodedText = PL_Base64Decode(q + 2, n, nsnull); } if (decodedText == nsnull) goto badsyntax; // Override charset if requested. Never override labeled UTF-8. // Use default charset instead of UNKNOWN-8BIT if ((aOverrideCharset && 0 != nsCRT::strcasecmp(charset, "UTF-8")) || (aDefaultCharset && 0 == nsCRT::strcasecmp(charset, "UNKNOWN-8BIT"))) { PL_strncpy(charset, aDefaultCharset, sizeof(charset) - 1); charset[sizeof(charset) - 1] = '\0'; } { nsCOMPtr<nsIUTF8ConverterService> cvtUTF8(do_GetService(NS_UTF8CONVERTERSERVICE_CONTRACTID)); nsCAutoString utf8Text; // skip ASCIIness/UTF8ness test if aCharset is 7bit non-ascii charset. if (cvtUTF8 && NS_SUCCEEDED( cvtUTF8->ConvertStringToUTF8(nsDependentCString(decodedText), charset, IS_7BIT_NON_ASCII_CHARSET(charset), utf8Text))) { aResult.Append(utf8Text); } else { aResult.Append(REPLACEMENT_CHAR); } } PR_Free(decodedText); begin = r + 2; isLastEncodedWord = 1; continue; badsyntax: // copy the part before the encoded-word aResult.Append(begin, p - begin); begin = p; isLastEncodedWord = 0; } // put the tail back CopyRawHeader(begin, strlen(begin), aDefaultCharset, aResult); nsCAutoString tempStr(aResult); tempStr.ReplaceChar('\t', ' '); aResult = tempStr; return NS_OK; }
nsresult nsEudoraWin32::GetAttachmentInfo( const char *pFileName, nsIFile *pFile, nsCString& mimeType, nsCString& aAttachmentName) { nsresult rv; mimeType.Truncate(); nsCOMPtr <nsILocalFile> pLocalFile = do_QueryInterface(pFile, &rv); NS_ENSURE_SUCCESS(rv, rv); pLocalFile->InitWithNativePath(nsDependentCString(pFileName)); bool isFile = false; bool exists = false; if (NS_FAILED( rv = pFile->Exists( &exists))) return( rv); if ( exists && NS_FAILED( rv = pFile->IsFile(&isFile) ) ) return( rv); if (!exists || !isFile) { // Windows Eudora writes the full path to the attachment when the message // is received, but doesn't update that path if the attachment directory // changes (e.g. if email directory is moved). When operating on an // attachment (opening, etc.) Eudora will first check the full path // and then if the file doesn't exist there Eudora will check the // current attachment directory for a file with the same name. // // Check to see if we have any better luck looking for the attachment // in the current attachment directory. nsCAutoString name; pFile->GetNativeLeafName(name); if (name.IsEmpty()) return( NS_ERROR_FAILURE); nsCOMPtr <nsIFile> altFile; rv = m_mailImportLocation->Clone(getter_AddRefs(altFile)); NS_ENSURE_SUCCESS(rv, rv); // For now, we'll do that using a hard coded name and location for the // attachment directory on Windows (the default location) "attach" inside // of the Eudora mail directory. Once settings from Eudora are imported // better, we'll want to check where the settings say attachments are stored. altFile->AppendNative(NS_LITERAL_CSTRING("attach")); altFile->AppendNative(name); // Did we come up with a different path or was the original path already // in the current attachment directory? bool isSamePath = true; rv = altFile->Equals(pFile, &isSamePath); if (NS_SUCCEEDED(rv) && !isSamePath) { // We came up with a different path - check the new path. if (NS_FAILED( rv = altFile->Exists( &exists))) return( rv); if ( exists && NS_FAILED( rv = altFile->IsFile( &isFile) ) ) return( rv); // Keep the new path if it helped us. if (exists && isFile) { nsCString nativePath; altFile->GetNativePath(nativePath); pLocalFile->InitWithNativePath(nativePath); } } } if (exists && isFile) { nsCAutoString name; pFile->GetNativeLeafName(name); if (name.IsEmpty()) return( NS_ERROR_FAILURE); if (name.Length() > 4) { nsCString ext; PRInt32 idx = name.RFindChar( '.'); if (idx != -1) { ext = Substring(name, idx); GetMimeTypeFromExtension(ext, mimeType); } } if (mimeType.IsEmpty()) mimeType = "application/octet-stream"; nsAutoString description; rv = NS_CopyNativeToUnicode(name, description); if (NS_SUCCEEDED(rv)) aAttachmentName = NS_ConvertUTF16toUTF8(description); else aAttachmentName = name; return( NS_OK); } return( NS_ERROR_FAILURE); }
nsresult GetDefaultAdapterPathInternal(nsCString& aAdapterPath) { DBusMessage *msg = NULL, *reply = NULL; DBusError err; const char *device_path = NULL; int attempt = 0; for (attempt = 0; attempt < 1000 && reply == NULL; attempt ++) { msg = dbus_message_new_method_call("org.bluez", "/", "org.bluez.Manager", "DefaultAdapter"); if (!msg) { LOG("%s: Can't allocate new method call for get_adapter_path!", __FUNCTION__); return NS_ERROR_FAILURE; } dbus_message_append_args(msg, DBUS_TYPE_INVALID); dbus_error_init(&err); reply = dbus_connection_send_with_reply_and_block( sDBusConnection->mConnection, msg, -1, &err); if (!reply) { if (dbus_error_is_set(&err)) { if (dbus_error_has_name(&err, "org.freedesktop.DBus.Error.ServiceUnknown")) { // bluetoothd is still down, retry LOG("Service unknown\n"); dbus_error_free(&err); //usleep(10000); // 10 ms continue; } else if (dbus_error_has_name(&err, "org.bluez.Error.NoSuchAdapter")) { LOG("No adapter found\n"); dbus_error_free(&err); goto failed; } else { // Some other error we weren't expecting LOG("other error\n"); dbus_error_free(&err); } } } } if (attempt == 1000) { LOG("timeout\n"); //printfE("Time out while trying to get Adapter path, is bluetoothd up ?"); goto failed; } if (!dbus_message_get_args(reply, &err, DBUS_TYPE_OBJECT_PATH, &device_path, DBUS_TYPE_INVALID) || !device_path) { if (dbus_error_is_set(&err)) { dbus_error_free(&err); } goto failed; } dbus_message_unref(msg); aAdapterPath = nsDependentCString(device_path); return NS_OK; failed: dbus_message_unref(msg); return NS_ERROR_FAILURE; }
nsresult nsAbBSDirectory::EnsureInitialized() { if (mInitialized) return NS_OK; nsresult rv; nsCOMPtr<nsIAbDirFactoryService> dirFactoryService = do_GetService(NS_ABDIRFACTORYSERVICE_CONTRACTID,&rv); NS_ENSURE_SUCCESS (rv, rv); nsTArray<DIR_Server*> *directories = DIR_GetDirectories(); if (!directories) return NS_ERROR_FAILURE; int32_t count = directories->Length(); for (int32_t i = 0; i < count; i++) { DIR_Server *server = directories->ElementAt(i); // if this is a 4.x, local .na2 addressbook (PABDirectory) // we must skip it. // mozilla can't handle 4.x .na2 addressbooks // note, the filename might be na2 for 4.x LDAP directories // (we used the .na2 file for replication), and we don't want to skip // those. see bug #127007 uint32_t fileNameLen = strlen(server->fileName); if (((fileNameLen > kABFileName_PreviousSuffixLen) && strcmp(server->fileName + fileNameLen - kABFileName_PreviousSuffixLen, kABFileName_PreviousSuffix) == 0) && (server->dirType == PABDirectory)) continue; // Set the uri property nsAutoCString URI (server->uri); // This is in case the uri is never set // in the nsDirPref.cpp code. if (!server->uri) { URI = NS_LITERAL_CSTRING(kMDBDirectoryRoot); URI += nsDependentCString(server->fileName); } /* * Check that we are not converting from a * a 4.x address book file e.g. pab.na2 * check if the URI ends with ".na2" */ if (StringEndsWith(URI, NS_LITERAL_CSTRING(kABFileName_PreviousSuffix))) URI.Replace(kMDBDirectoryRootLen, URI.Length() - kMDBDirectoryRootLen, server->fileName); // Create the directories rv = CreateDirectoriesFromFactory(URI, server, false /* notify */); // If we failed, this could be because something has set a pref for us // which is now broke (e.g. no factory present). So just ignore this one // and move on. if (NS_FAILED(rv)) NS_WARNING("CreateDirectoriesFromFactory failed - Invalid factory?"); } mInitialized = true; // sort directories by position... return NS_OK; }
nsresult writeoutto(const char* i_pURL, char** o_Result, PRInt32 urlFactory = URL_FACTORY_DEFAULT) { if (!o_Result || !i_pURL) return NS_ERROR_FAILURE; *o_Result = 0; nsCOMPtr<nsIURI> pURL; nsresult result = NS_OK; switch (urlFactory) { case URL_FACTORY_STDURL: { nsIURI* url; result = CallCreateInstance(kStdURLCID, &url); if (NS_FAILED(result)) { printf("CreateInstance failed\n"); return NS_ERROR_FAILURE; } pURL = url; pURL->SetSpec(nsDependentCString(i_pURL)); break; } case URL_FACTORY_DEFAULT: { nsCOMPtr<nsIIOService> pService = do_GetService(kIOServiceCID, &result); if (NS_FAILED(result)) { printf("Service failed!\n"); return NS_ERROR_FAILURE; } result = pService->NewURI(nsDependentCString(i_pURL), nullptr, nullptr, getter_AddRefs(pURL)); } } nsCString output; if (NS_SUCCEEDED(result)) { nsCOMPtr<nsIURL> tURL = do_QueryInterface(pURL); nsCAutoString temp; PRInt32 port; nsresult rv; #define RESULT() NS_SUCCEEDED(rv) ? temp.get() : "" rv = tURL->GetScheme(temp); output += RESULT(); output += ','; rv = tURL->GetUsername(temp); output += RESULT(); output += ','; rv = tURL->GetPassword(temp); output += RESULT(); output += ','; rv = tURL->GetHost(temp); output += RESULT(); output += ','; rv = tURL->GetPort(&port); char portbuffer[40]; PR_snprintf(portbuffer, sizeof(portbuffer), "%d", port); output.Append(portbuffer); output += ','; rv = tURL->GetDirectory(temp); output += RESULT(); output += ','; rv = tURL->GetFileBaseName(temp); output += RESULT(); output += ','; rv = tURL->GetFileExtension(temp); output += RESULT(); output += ','; // removed with https://bugzilla.mozilla.org/show_bug.cgi?id=665706 // rv = tURL->GetParam(temp); // output += RESULT(); output += ','; rv = tURL->GetQuery(temp); output += RESULT(); output += ','; rv = tURL->GetRef(temp); output += RESULT(); output += ','; rv = tURL->GetSpec(temp); output += RESULT(); *o_Result = ToNewCString(output); } else { output = "Can not create URL"; *o_Result = ToNewCString(output); } return NS_OK; }
nsresult nsXREDirProvider::GetUpdateRootDir(nsIFile* *aResult) { nsCOMPtr<nsIFile> updRoot; #if defined(MOZ_WIDGET_GONK) nsresult rv = NS_NewNativeLocalFile(nsDependentCString("/data/local"), true, getter_AddRefs(updRoot)); NS_ENSURE_SUCCESS(rv, rv); #else nsCOMPtr<nsIFile> appFile; bool per = false; nsresult rv = GetFile(XRE_EXECUTABLE_FILE, &per, getter_AddRefs(appFile)); NS_ENSURE_SUCCESS(rv, rv); rv = appFile->GetParent(getter_AddRefs(updRoot)); NS_ENSURE_SUCCESS(rv, rv); #ifdef XP_WIN nsAutoString pathHash; bool pathHashResult = false; bool hasVendor = gAppData->vendor && strlen(gAppData->vendor) != 0; nsAutoString appDirPath; if (SUCCEEDED(updRoot->GetPath(appDirPath))) { // Figure out where we should check for a cached hash value. If the // application doesn't have the nsXREAppData vendor value defined check // under SOFTWARE\Mozilla. wchar_t regPath[1024] = { L'\0' }; swprintf_s(regPath, mozilla::ArrayLength(regPath), L"SOFTWARE\\%S\\%S\\TaskBarIDs", (hasVendor ? gAppData->vendor : "Mozilla"), MOZ_APP_BASENAME); // If we pre-computed the hash, grab it from the registry. pathHashResult = GetCachedHash(HKEY_LOCAL_MACHINE, nsDependentString(regPath), appDirPath, pathHash); if (!pathHashResult) { pathHashResult = GetCachedHash(HKEY_CURRENT_USER, nsDependentString(regPath), appDirPath, pathHash); } } // Get the local app data directory and if a vendor name exists append it. // If only a product name exists, append it. If neither exist fallback to // old handling. We don't use the product name on purpose because we want a // shared update directory for different apps run from the same path (like // Metro & Desktop). nsCOMPtr<nsIFile> localDir; if (pathHashResult && (hasVendor || gAppData->name) && NS_SUCCEEDED(GetUserDataDirectoryHome(getter_AddRefs(localDir), true)) && NS_SUCCEEDED(localDir->AppendNative(nsDependentCString(hasVendor ? gAppData->vendor : gAppData->name))) && NS_SUCCEEDED(localDir->Append(NS_LITERAL_STRING("updates"))) && NS_SUCCEEDED(localDir->Append(pathHash))) { NS_ADDREF(*aResult = localDir); return NS_OK; } nsAutoString appPath; rv = updRoot->GetPath(appPath); NS_ENSURE_SUCCESS(rv, rv); // AppDir may be a short path. Convert to long path to make sure // the consistency of the update folder location nsString longPath; wchar_t* buf; uint32_t bufLength = longPath.GetMutableData(&buf, MAXPATHLEN); NS_ENSURE_TRUE(bufLength >= MAXPATHLEN, NS_ERROR_OUT_OF_MEMORY); DWORD len = GetLongPathNameW(appPath.get(), buf, bufLength); // Failing GetLongPathName() is not fatal. if (len <= 0 || len >= bufLength) longPath.Assign(appPath); else longPath.SetLength(len); // Use <UserLocalDataDir>\updates\<relative path to app dir from // Program Files> if app dir is under Program Files to avoid the // folder virtualization mess on Windows Vista nsAutoString programFiles; rv = GetShellFolderPath(CSIDL_PROGRAM_FILES, programFiles); NS_ENSURE_SUCCESS(rv, rv); programFiles.AppendLiteral("\\"); uint32_t programFilesLen = programFiles.Length(); nsAutoString programName; if (_wcsnicmp(programFiles.get(), longPath.get(), programFilesLen) == 0) { programName = Substring(longPath, programFilesLen); } else { // We need the update root directory to live outside of the installation // directory, because otherwise the updater writing the log file can cause // the directory to be locked, which prevents it from being replaced after // background updates. programName.AssignASCII(MOZ_APP_NAME); } rv = GetUserLocalDataDirectory(getter_AddRefs(updRoot)); NS_ENSURE_SUCCESS(rv, rv); rv = updRoot->AppendRelativePath(programName); NS_ENSURE_SUCCESS(rv, rv); #endif #endif NS_ADDREF(*aResult = updRoot); return NS_OK; }
NS_IMETHODIMP nsCRLManager::ComputeNextAutoUpdateTime(nsICRLInfo *info, uint32_t autoUpdateType, double dayCnt, PRUnichar **nextAutoUpdate) { if (!info) return NS_ERROR_FAILURE; NS_ENSURE_ARG_POINTER(nextAutoUpdate); PRTime microsecInDayCnt; PRTime now = PR_Now(); PRTime tempTime; int64_t diff = 0; int64_t secsInDay = 86400UL; int64_t temp; int64_t cycleCnt = 0; double tmpData = double(secsInDay); tmpData *= dayCnt; microsecInDayCnt = int64_t(tmpData) * PR_USEC_PER_SEC; PRTime lastUpdate; PRTime nextUpdate; nsresult rv; rv = info->GetLastUpdate(&lastUpdate); if (NS_FAILED(rv)) return rv; rv = info->GetNextUpdate(&nextUpdate); if (NS_FAILED(rv)) return rv; switch (autoUpdateType) { case TYPE_AUTOUPDATE_FREQ_BASED: diff = now - lastUpdate; //diff is the no of micro sec between now and last update cycleCnt = diff / microsecInDayCnt; //temp is the number of full cycles from lst update temp = diff % microsecInDayCnt; if(temp != 0) { ++cycleCnt; //no of complete cycles till next autoupdate instant } temp = cycleCnt * microsecInDayCnt; //micro secs from last update tempTime = lastUpdate + temp; break; case TYPE_AUTOUPDATE_TIME_BASED: tempTime = nextUpdate - microsecInDayCnt; break; default: return NS_ERROR_NOT_IMPLEMENTED; } //Now, a basic constraing is that the next auto update date can never be after //next update, if one is defined if(nextUpdate > 0) { if(tempTime > nextUpdate) { tempTime = nextUpdate; } } // Return value as string; no pref type for Int64/PRTime char *tempTimeStr = PR_smprintf("%lli", tempTime); *nextAutoUpdate = ToNewUnicode(nsDependentCString(tempTimeStr)); PR_smprintf_free(tempTimeStr); return NS_OK; }
NS_IMETHODIMP nsGNOMEShellService::SetDesktopBackground(nsIDOMElement* aElement, int32_t aPosition) { nsCString brandName; nsresult rv = GetBrandName(brandName); NS_ENSURE_SUCCESS(rv, rv); // build the file name nsCString filePath(PR_GetEnv("HOME")); filePath.Append('/'); filePath.Append(brandName); filePath.AppendLiteral("_wallpaper.png"); // get the image container nsCOMPtr<nsIImageLoadingContent> imageContent(do_QueryInterface(aElement, &rv)); NS_ENSURE_SUCCESS(rv, rv); nsCOMPtr<imgIRequest> request; rv = imageContent->GetRequest(nsIImageLoadingContent::CURRENT_REQUEST, getter_AddRefs(request)); NS_ENSURE_TRUE(request, rv); nsCOMPtr<imgIContainer> container; rv = request->GetImage(getter_AddRefs(container)); NS_ENSURE_TRUE(request, rv); nsCOMPtr<nsIImageToPixbuf> imgToPixbuf(do_GetService("@mozilla.org/widget/image-to-gdk-pixbuf;1")); if (!imgToPixbuf) return NS_ERROR_NOT_AVAILABLE; GdkPixbuf* pixbuf = imgToPixbuf->ConvertImageToPixbuf(container); if (!pixbuf) return NS_ERROR_NOT_AVAILABLE; // write the image to a file in the home dir gboolean res = gdk_pixbuf_save(pixbuf, filePath.get(), "png", NULL, NULL); g_object_unref(pixbuf); if (!res) return NS_ERROR_FAILURE; // set desktop wallpaper filling style const char* options; switch (aPosition) { case BACKGROUND_TILE: options = "wallpaper"; break; case BACKGROUND_STRETCH: options = "stretched"; break; case BACKGROUND_FILL: options = "zoom"; break; case BACKGROUND_FIT: options = "scaled"; break; default: options = "centered"; break; } // Try GSettings first. If we don't have GSettings or the right schema, fall back // to using GConf instead. Note that if GSettings works ok, the changes get // mirrored to GConf by the gsettings->gconf bridge in gnome-settings-daemon nsCOMPtr<nsIGSettingsService> gsettings(do_GetService(NS_GSETTINGSSERVICE_CONTRACTID)); if (gsettings) { nsCOMPtr<nsIGSettingsCollection> background_settings; gsettings->GetCollectionForSchema(NS_LITERAL_CSTRING(OGDB_SCHEMA), getter_AddRefs(background_settings)); if (background_settings) { gchar *file_uri = g_filename_to_uri(filePath.get(), NULL, NULL); if (!file_uri) return NS_ERROR_FAILURE; background_settings->SetString(NS_LITERAL_CSTRING(OGDB_OPTIONS), nsDependentCString(options)); background_settings->SetString(NS_LITERAL_CSTRING(OGDB_IMAGE), nsDependentCString(file_uri)); g_free(file_uri); background_settings->SetBoolean(NS_LITERAL_CSTRING(OGDB_DRAWBG), true); return NS_OK; } } // if the file was written successfully, set it as the system wallpaper nsCOMPtr<nsIGConfService> gconf(do_GetService(NS_GCONFSERVICE_CONTRACTID)); if (gconf) { gconf->SetString(NS_LITERAL_CSTRING(DGB_OPTIONS), nsDependentCString(options)); // Set the image to an empty string first to force a refresh (since we could // be writing a new image on top of an existing SeaMonkey_wallpaper.png // and nautilus doesn't monitor the file for changes). gconf->SetString(NS_LITERAL_CSTRING(DGB_IMAGE), EmptyCString()); gconf->SetString(NS_LITERAL_CSTRING(DGB_IMAGE), filePath); gconf->SetBool(NS_LITERAL_CSTRING(DGB_DRAWBG), true); } return NS_OK; }
nsresult nsReadConfig::openAndEvaluateJSFile(const char *aFileName, PRBool isEncoded, PRInt32 obscureValue, PRBool isBinDir) { nsresult rv; nsCOMPtr<nsIFile> jsFile; if (isBinDir) { rv = NS_GetSpecialDirectory(NS_XPCOM_CURRENT_PROCESS_DIR, getter_AddRefs(jsFile)); if (NS_FAILED(rv)) return rv; #ifdef XP_MAC jsFile->AppendNative(NS_LITERAL_CSTRING("Essential Files")); #endif } else { rv = NS_GetSpecialDirectory(NS_APP_DEFAULTS_50_DIR, getter_AddRefs(jsFile)); if (NS_FAILED(rv)) return rv; rv = jsFile->AppendNative(NS_LITERAL_CSTRING("autoconfig")); if (NS_FAILED(rv)) return rv; } rv = jsFile->AppendNative(nsDependentCString(aFileName)); if (NS_FAILED(rv)) return rv; nsCOMPtr<nsIInputStream> inStr; rv = NS_NewLocalFileInputStream(getter_AddRefs(inStr), jsFile); if (NS_FAILED(rv)) return rv; PRInt64 fileSize; PRUint32 fs, amt = 0; jsFile->GetFileSize(&fileSize); LL_L2UI(fs, fileSize); // Converting 64 bit structure to unsigned int char *buf = (char *)PR_Malloc(fs * sizeof(char)); if (!buf) return NS_ERROR_OUT_OF_MEMORY; rv = inStr->Read(buf, fs, &amt); NS_ASSERTION((amt == fs), "failed to read the entire configuration file!!"); if (NS_SUCCEEDED(rv)) { if (obscureValue > 0) { // Unobscure file by subtracting some value from every char. for (PRUint32 i = 0; i < amt; i++) buf[i] -= obscureValue; } nsCAutoString path; jsFile->GetNativePath(path); nsCAutoString fileURL; fileURL = NS_LITERAL_CSTRING("file:///") + path; rv = EvaluateAdminConfigScript(buf, amt, fileURL.get(), PR_FALSE, PR_TRUE, isEncoded ? PR_TRUE:PR_FALSE); } inStr->Close(); PR_Free(buf); return rv; }
/* static */ CanPlayStatus DecoderTraits::CanHandleMediaType(const char* aMIMEType, bool aHaveRequestedCodecs, const nsAString& aRequestedCodecs) { char const* const* codecList = nullptr; CanPlayStatus result = CANPLAY_NO; #ifdef MOZ_RAW if (IsRawType(nsDependentCString(aMIMEType))) { codecList = gRawCodecs; result = CANPLAY_MAYBE; } #endif if (IsOggType(nsDependentCString(aMIMEType))) { codecList = MediaDecoder::IsOpusEnabled() ? gOggCodecsWithOpus : gOggCodecs; result = CANPLAY_MAYBE; } #ifdef MOZ_WAVE if (IsWaveType(nsDependentCString(aMIMEType))) { codecList = gWaveCodecs; result = CANPLAY_MAYBE; } #endif #if defined(MOZ_WEBM) && !defined(MOZ_OMX_WEBM_DECODER) if (IsWebMType(nsDependentCString(aMIMEType))) { codecList = gWebMCodecs; result = CANPLAY_MAYBE; } #endif #ifdef MOZ_FMP4 if (IsMP4SupportedType(nsDependentCString(aMIMEType), aRequestedCodecs)) { return aHaveRequestedCodecs ? CANPLAY_YES : CANPLAY_MAYBE; } #endif #ifdef MOZ_GSTREAMER if (GStreamerDecoder::CanHandleMediaType(nsDependentCString(aMIMEType), aHaveRequestedCodecs ? &aRequestedCodecs : nullptr)) { if (aHaveRequestedCodecs) return CANPLAY_YES; return CANPLAY_MAYBE; } #endif #ifdef MOZ_OMX_DECODER if (IsOmxSupportedType(nsDependentCString(aMIMEType))) { result = CANPLAY_MAYBE; if (nsDependentCString(aMIMEType).EqualsASCII("audio/mpeg")) { codecList = gMpegAudioCodecs; #ifdef MOZ_OMX_WEBM_DECODER } else if (nsDependentCString(aMIMEType).EqualsASCII("audio/webm") || nsDependentCString(aMIMEType).EqualsASCII("video/webm")) { codecList = gOMXWebMCodecs; #endif } else { codecList = gH264Codecs; } } #endif #ifdef MOZ_DIRECTSHOW // Note: DirectShow should come before WMF, so that we prefer DirectShow's // MP3 support over WMF's. if (DirectShowDecoder::GetSupportedCodecs(nsDependentCString(aMIMEType), &codecList)) { result = CANPLAY_MAYBE; } #endif #ifdef MOZ_FMP4 if (MP4Decoder::GetSupportedCodecs(nsDependentCString(aMIMEType), &codecList)) { result = CANPLAY_MAYBE; } #endif #ifdef MOZ_WMF if (!Preferences::GetBool("media.fragmented-mp4.exposed", false) && IsWMFSupportedType(nsDependentCString(aMIMEType))) { if (!aHaveRequestedCodecs) { return CANPLAY_MAYBE; } return WMFDecoder::CanPlayType(nsDependentCString(aMIMEType), aRequestedCodecs) ? CANPLAY_YES : CANPLAY_NO; } #endif #ifdef MOZ_APPLEMEDIA if (IsAppleMediaSupportedType(nsDependentCString(aMIMEType), &codecList)) { result = CANPLAY_MAYBE; } #endif #ifdef MOZ_ANDROID_OMX if (MediaDecoder::IsAndroidMediaEnabled() && GetAndroidMediaPluginHost()->FindDecoder(nsDependentCString(aMIMEType), &codecList)) result = CANPLAY_MAYBE; #endif #ifdef NECKO_PROTOCOL_rtsp if (IsRtspSupportedType(nsDependentCString(aMIMEType))) { result = CANPLAY_MAYBE; } #endif if (result == CANPLAY_NO || !aHaveRequestedCodecs || !codecList) { return result; } // See http://www.rfc-editor.org/rfc/rfc4281.txt for the description // of the 'codecs' parameter nsCharSeparatedTokenizer tokenizer(aRequestedCodecs, ','); bool expectMoreTokens = false; while (tokenizer.hasMoreTokens()) { const nsSubstring& token = tokenizer.nextToken(); if (!CodecListContains(codecList, token)) { // Totally unsupported codec return CANPLAY_NO; } expectMoreTokens = tokenizer.separatorAfterCurrentToken(); } if (expectMoreTokens) { // Last codec name was empty return CANPLAY_NO; } return CANPLAY_YES; }
nsresult nsMsgMdnGenerator::CreateSecondPart() { DEBUG_MDN("nsMsgMdnGenerator::CreateSecondPart"); char *tmpBuffer = nsnull; char *convbuf = nsnull; nsresult rv = NS_OK; nsCOMPtr <nsIMsgCompUtils> compUtils; bool conformToStandard = false; tmpBuffer = PR_smprintf("--%s" CRLF, m_mimeSeparator.get()); PUSH_N_FREE_STRING(tmpBuffer); tmpBuffer = PR_smprintf("%s" CRLF, "Content-Type: message/disposition-notification; name=\042MDNPart2.txt\042"); PUSH_N_FREE_STRING(tmpBuffer); tmpBuffer = PR_smprintf("%s" CRLF, "Content-Disposition: inline"); PUSH_N_FREE_STRING(tmpBuffer); tmpBuffer = PR_smprintf("Content-Transfer-Encoding: %s" CRLF CRLF, ENCODING_7BIT); PUSH_N_FREE_STRING(tmpBuffer); nsCOMPtr<nsIHttpProtocolHandler> pHTTPHandler = do_GetService(NS_NETWORK_PROTOCOL_CONTRACTID_PREFIX "http", &rv); if (NS_SUCCEEDED(rv) && pHTTPHandler) { nsCAutoString userAgentString; pHTTPHandler->GetUserAgent(userAgentString); if (!userAgentString.IsEmpty()) { // Prepend the product name with the dns name according to RFC 3798. char hostName[256]; PR_GetSystemInfo(PR_SI_HOSTNAME_UNTRUNCATED, hostName, sizeof hostName); if ((hostName[0] != '\0') && (strchr(hostName, '.') != NULL)) { userAgentString.Insert("; ", 0); userAgentString.Insert(nsDependentCString(hostName), 0); } tmpBuffer = PR_smprintf("Reporting-UA: %s" CRLF, userAgentString.get()); PUSH_N_FREE_STRING(tmpBuffer); } } nsCString originalRecipient; m_headers->ExtractHeader(HEADER_ORIGINAL_RECIPIENT, false, getter_Copies(originalRecipient)); if (!originalRecipient.IsEmpty()) { tmpBuffer = PR_smprintf("Original-Recipient: %s" CRLF, originalRecipient.get()); PUSH_N_FREE_STRING(tmpBuffer); } compUtils = do_GetService(NS_MSGCOMPUTILS_CONTRACTID, &rv); if (compUtils) compUtils->GetMsgMimeConformToStandard(&conformToStandard); convbuf = nsMsgI18NEncodeMimePartIIStr( m_email.get(), true, m_charset.get(), 0, conformToStandard); tmpBuffer = PR_smprintf("Final-Recipient: rfc822;%s" CRLF, convbuf ? convbuf : m_email.get()); PUSH_N_FREE_STRING(tmpBuffer); PR_Free (convbuf); if (*m_messageId.get() == '<') tmpBuffer = PR_smprintf("Original-Message-ID: %s" CRLF, m_messageId.get()); else tmpBuffer = PR_smprintf("Original-Message-ID: <%s>" CRLF, m_messageId.get()); PUSH_N_FREE_STRING(tmpBuffer); tmpBuffer = PR_smprintf("Disposition: %s/%s; %s" CRLF CRLF, (m_autoAction ? "automatic-action" : "manual-action"), (m_autoSend ? "MDN-sent-automatically" : "MDN-sent-manually"), DispositionTypes[(int) m_disposeType]); PUSH_N_FREE_STRING(tmpBuffer); return rv; }
static int MimeObject_parse_begin (MimeObject *obj) { NS_ASSERTION (!obj->closed_p, "object shouldn't be already closed"); /* If we haven't set up the state object yet, then this should be the outermost object... */ if (obj->options && !obj->options->state) { NS_ASSERTION(!obj->headers, "headers should be null"); /* should be the outermost object. */ obj->options->state = new MimeParseStateObject; if (!obj->options->state) return MIME_OUT_OF_MEMORY; obj->options->state->root = obj; obj->options->state->separator_suppressed_p = PR_TRUE; /* no first sep */ const char *delParts = PL_strcasestr(obj->options->url, "&del="); const char *detachLocations = PL_strcasestr(obj->options->url, "&detachTo="); if (delParts) { const char *delEnd = PL_strcasestr(delParts + 1, "&"); if (!delEnd) delEnd = delParts + strlen(delParts); ParseString(Substring(delParts + 5, delEnd), ',', obj->options->state->partsToStrip); } if (detachLocations) { detachLocations += 10; // advance past "&detachTo=" ParseString(nsDependentCString(detachLocations), ',', obj->options->state->detachToFiles); } } /* Decide whether this object should be output or not... */ if (!obj->options || !obj->options->output_fn /* if we are decomposing the message in files and processing a multipart object, we must not output it without parsing it first */ || (obj->options->decompose_file_p && obj->options->decompose_file_output_fn && mime_typep(obj, (MimeObjectClass*) &mimeMultipartClass)) ) obj->output_p = PR_FALSE; else if (!obj->options->part_to_load) obj->output_p = PR_TRUE; else { char *id = mime_part_address(obj); if (!id) return MIME_OUT_OF_MEMORY; // We need to check if a part is the subpart of the part to load. // If so and this is a raw or body display output operation, then // we should mark the part for subsequent output. // // First, check for an exact match obj->output_p = !strcmp(id, obj->options->part_to_load); if (!obj->output_p && (obj->options->format_out == nsMimeOutput::nsMimeMessageRaw || obj->options->format_out == nsMimeOutput::nsMimeMessageBodyDisplay || obj->options->format_out == nsMimeOutput::nsMimeMessageAttach)) { // Then, check for subpart unsigned int partlen = strlen(obj->options->part_to_load); obj->output_p = (strlen(id) >= partlen + 2) && (id[partlen] == '.') && !strncmp(id, obj->options->part_to_load, partlen); } PR_Free(id); } return 0; }
nsresult GetSlotWithMechanism(uint32_t aMechanism, nsIInterfaceRequestor* m_ctx, PK11SlotInfo** aSlot, nsNSSShutDownPreventionLock& /*proofOfLock*/) { PK11SlotList * slotList = nullptr; char16_t** tokenNameList = nullptr; nsCOMPtr<nsITokenDialogs> dialogs; char16_t *unicodeTokenChosen; PK11SlotListElement *slotElement, *tmpSlot; uint32_t numSlots = 0, i = 0; bool canceled; nsresult rv = NS_OK; *aSlot = nullptr; // Get the slot slotList = PK11_GetAllTokens(MapGenMechToAlgoMech(aMechanism), true, true, m_ctx); if (!slotList || !slotList->head) { rv = NS_ERROR_FAILURE; goto loser; } if (!slotList->head->next) { /* only one slot available, just return it */ *aSlot = slotList->head->slot; } else { // Gerenate a list of slots and ask the user to choose // tmpSlot = slotList->head; while (tmpSlot) { numSlots++; tmpSlot = tmpSlot->next; } // Allocate the slot name buffer // tokenNameList = static_cast<char16_t**>(moz_xmalloc(sizeof(char16_t *) * numSlots)); if (!tokenNameList) { rv = NS_ERROR_OUT_OF_MEMORY; goto loser; } i = 0; slotElement = PK11_GetFirstSafe(slotList); while (slotElement) { tokenNameList[i] = UTF8ToNewUnicode(nsDependentCString(PK11_GetTokenName(slotElement->slot))); slotElement = PK11_GetNextSafe(slotList, slotElement, false); if (tokenNameList[i]) i++; else { // OOM. adjust numSlots so we don't free unallocated memory. numSlots = i; PK11_FreeSlotListElement(slotList, slotElement); rv = NS_ERROR_OUT_OF_MEMORY; goto loser; } } // Throw up the token list dialog and get back the token. rv = getNSSDialogs(getter_AddRefs(dialogs), NS_GET_IID(nsITokenDialogs), NS_TOKENDIALOGS_CONTRACTID); if (NS_FAILED(rv)) { goto loser; } if (!tokenNameList || !*tokenNameList) { rv = NS_ERROR_OUT_OF_MEMORY; } else { rv = dialogs->ChooseToken(m_ctx, (const char16_t**)tokenNameList, numSlots, &unicodeTokenChosen, &canceled); } if (NS_FAILED(rv)) goto loser; if (canceled) { rv = NS_ERROR_NOT_AVAILABLE; goto loser; } // Get the slot // slotElement = PK11_GetFirstSafe(slotList); nsAutoString tokenStr(unicodeTokenChosen); while (slotElement) { if (tokenStr.Equals(NS_ConvertUTF8toUTF16(PK11_GetTokenName(slotElement->slot)))) { *aSlot = slotElement->slot; PK11_FreeSlotListElement(slotList, slotElement); break; } slotElement = PK11_GetNextSafe(slotList, slotElement, false); } if(!(*aSlot)) { rv = NS_ERROR_FAILURE; goto loser; } } // Get a reference to the slot // PK11_ReferenceSlot(*aSlot); loser: if (slotList) { PK11_FreeSlotList(slotList); } if (tokenNameList) { NS_FREE_XPCOM_ALLOCATED_POINTER_ARRAY(numSlots, tokenNameList); } return rv; }
nsresult nsHttpConnection::CreateTransport(PRUint8 caps) { nsresult rv; NS_PRECONDITION(!mSocketTransport, "unexpected"); nsCOMPtr<nsISocketTransportService> sts = do_GetService(NS_SOCKETTRANSPORTSERVICE_CONTRACTID, &rv); if (NS_FAILED(rv)) return rv; // configure the socket type based on the connection type requested. const char* types[1]; if (mConnInfo->UsingSSL()) types[0] = "ssl"; else types[0] = gHttpHandler->DefaultSocketType(); nsCOMPtr<nsISocketTransport> strans; PRUint32 typeCount = (types[0] != nsnull); rv = sts->CreateTransport(types, typeCount, nsDependentCString(mConnInfo->Host()), mConnInfo->Port(), mConnInfo->ProxyInfo(), getter_AddRefs(strans)); if (NS_FAILED(rv)) return rv; PRUint32 tmpFlags = 0; if (caps & NS_HTTP_REFRESH_DNS) tmpFlags = nsISocketTransport::BYPASS_CACHE; if (caps & NS_HTTP_LOAD_ANONYMOUS) tmpFlags |= nsISocketTransport::ANONYMOUS_CONNECT; strans->SetConnectionFlags(tmpFlags); strans->SetQoSBits(gHttpHandler->GetQoSBits()); // NOTE: these create cyclical references, which we break inside // nsHttpConnection::Close rv = strans->SetEventSink(this, nsnull); if (NS_FAILED(rv)) return rv; rv = strans->SetSecurityCallbacks(this); if (NS_FAILED(rv)) return rv; // next open the socket streams nsCOMPtr<nsIOutputStream> sout; rv = strans->OpenOutputStream(nsITransport::OPEN_UNBUFFERED, 0, 0, getter_AddRefs(sout)); if (NS_FAILED(rv)) return rv; nsCOMPtr<nsIInputStream> sin; rv = strans->OpenInputStream(nsITransport::OPEN_UNBUFFERED, 0, 0, getter_AddRefs(sin)); if (NS_FAILED(rv)) return rv; mSocketTransport = strans; mSocketIn = do_QueryInterface(sin); mSocketOut = do_QueryInterface(sout); 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(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; }
static int MimeInlineTextPlainFlowed_parse_line(const char *aLine, int32_t length, MimeObject *obj) { int status; bool quoting = (obj->options && (obj->options->format_out == nsMimeOutput::nsMimeMessageQuoting || obj->options->format_out == nsMimeOutput::nsMimeMessageBodyQuoting)); // see above bool plainHTML = quoting || (obj->options && obj->options->format_out == nsMimeOutput::nsMimeMessageSaveAs); // see above struct MimeInlineTextPlainFlowedExData *exdata; exdata = MimeInlineTextPlainFlowedExDataList; while (exdata && (exdata->ownerobj != obj)) { exdata = exdata->next; } NS_ASSERTION(exdata, "The extra data has disappeared!"); NS_ASSERTION(length > 0, "zero length"); if (length <= 0) return 0; uint32_t linequotelevel = 0; nsAutoCString real_line(aLine, length); char *line = real_line.BeginWriting(); const char *linep = real_line.BeginReading(); // Space stuffed? if (' ' == *linep) { linep++; } else { // count '>':s before the first non-'>' while ('>' == *linep) { linep++; linequotelevel++; } // Space stuffed? if (' ' == *linep) { linep++; } } // Look if the last character (after stripping ending end // of lines and quoting stuff) is a SPACE. If it is, we are looking at a // flowed line. Normally we assume that the last two chars // are CR and LF as said in RFC822, but that doesn't seem to // be the case always. bool flowed = false; bool sigSeparator = false; int32_t index = length - 1; while (index >= 0 && ('\r' == line[index] || '\n' == line[index])) { index--; } if (index > linep - line && ' ' == line[index]) /* Ignore space stuffing, i.e. lines with just (quote marks and) a space count as empty */ { flowed = true; sigSeparator = (index - (linep - line) + 1 == 3) && !strncmp(linep, "-- ", 3); if (((MimeInlineTextPlainFlowed *)obj)->delSp && !sigSeparator) /* If line is flowed and DelSp=yes, logically delete trailing space. Line consisting of dash dash space ("-- "), commonly used as signature separator, gets special handling (RFC 3676) */ { length = index; line[index] = '\0'; } } if (obj->options && obj->options->decompose_file_p && obj->options->decompose_file_output_fn) { return obj->options->decompose_file_output_fn(line, length, obj->options->stream_closure); } mozITXTToHTMLConv *conv = GetTextConverter(obj->options); bool skipConversion = !conv || (obj->options && obj->options->force_user_charset); nsAutoString lineSource; nsString lineResult; char *mailCharset = NULL; nsresult rv; if (!skipConversion) { // Convert only if the source string is not empty if (length - (linep - line) > 0) { uint32_t whattodo = obj->options->whattodo; if (plainHTML) { if (quoting) whattodo = 0; else whattodo = whattodo & ~mozITXTToHTMLConv::kGlyphSubstitution; /* Do recognition for the case, the result is viewed in Mozilla, but not GlyphSubstitution, because other UAs might not be able to display the glyphs. */ } const nsDependentCSubstring &inputStr = Substring(linep, linep + (length - (linep - line))); // For 'SaveAs', |line| is in |mailCharset|. // convert |line| to UTF-16 before 'html'izing (calling ScanTXT()) if (obj->options->format_out == nsMimeOutput::nsMimeMessageSaveAs) { // Get the mail charset of this message. MimeInlineText *inlinetext = (MimeInlineText *)obj; if (!inlinetext->initializeCharset) ((MimeInlineTextClass *)&mimeInlineTextClass) ->initialize_charset(obj); mailCharset = inlinetext->charset; if (mailCharset && *mailCharset) { rv = nsMsgI18NConvertToUnicode(nsDependentCString(mailCharset), PromiseFlatCString(inputStr), lineSource); NS_ENSURE_SUCCESS(rv, -1); } else // this probably never happens... CopyUTF8toUTF16(inputStr, lineSource); } else // line is in UTF-8 CopyUTF8toUTF16(inputStr, lineSource); // This is the main TXT to HTML conversion: // escaping (very important), eventually recognizing etc. rv = conv->ScanTXT(lineSource, whattodo, lineResult); NS_ENSURE_SUCCESS(rv, -1); } } else { CopyUTF8toUTF16(nsDependentCString(line, length), lineResult); status = 0; } nsAutoCString preface; /* Correct number of blockquotes */ int32_t quoteleveldiff = linequotelevel - exdata->quotelevel; if ((quoteleveldiff != 0) && flowed && exdata->inflow) { // From RFC 2646 4.5 // The receiver SHOULD handle this error by using the 'quote-depth-wins' // rule, which is to ignore the flowed indicator and treat the line as // fixed. That is, the change in quote depth ends the paragraph. // We get that behaviour by just going on. } // Cast so we have access to the prefs we need. MimeInlineTextPlainFlowed *tObj = (MimeInlineTextPlainFlowed *)obj; while (quoteleveldiff > 0) { quoteleveldiff--; preface += "<blockquote type=cite"; nsAutoCString style; MimeTextBuildPrefixCSS(tObj->mQuotedSizeSetting, tObj->mQuotedStyleSetting, tObj->mCitationColor, style); if (!plainHTML && !style.IsEmpty()) { preface += " style=\""; preface += style; preface += '"'; } preface += '>'; } while (quoteleveldiff < 0) { quoteleveldiff++; preface += "</blockquote>"; } exdata->quotelevel = linequotelevel; nsAutoString lineResult2; if (flowed) { // Check RFC 2646 "4.3. Usenet Signature Convention": "-- "+CRLF is // not a flowed line if (sigSeparator) { if (linequotelevel > 0 || exdata->isSig) { preface += "-- <br>"; } else { exdata->isSig = true; preface += "<div class=\"moz-txt-sig\"><span class=\"moz-txt-tag\">" "-- <br></span>"; } } else { Line_convert_whitespace(lineResult, false /* Allow wraps */, lineResult2); } exdata->inflow = true; } else { // Fixed paragraph. Line_convert_whitespace(lineResult, !plainHTML && !obj->options->wrap_long_lines_p /* If wrap, convert all spaces but the last in a row into nbsp, otherwise all. */ , lineResult2); lineResult2.AppendLiteral("<br>"); exdata->inflow = false; } // End Fixed line if (!(exdata->isSig && quoting && tObj->mStripSig)) { status = MimeObject_write(obj, preface.get(), preface.Length(), true); if (status < 0) return status; nsAutoCString outString; if (obj->options->format_out != nsMimeOutput::nsMimeMessageSaveAs || !mailCharset || !*mailCharset) CopyUTF16toUTF8(lineResult2, outString); else { // convert back to mailCharset before writing. rv = nsMsgI18NConvertFromUnicode(nsDependentCString(mailCharset), lineResult2, outString); NS_ENSURE_SUCCESS(rv, -1); } status = MimeObject_write(obj, outString.get(), outString.Length(), true); return status; } return 0; }
nsresult nsXREDirProvider::AppendProfilePath(nsIFile* aFile, const nsACString* aProfileName, const nsACString* aAppName, const nsACString* aVendorName, bool aLocal) { NS_ASSERTION(aFile, "Null pointer!"); if (!gAppData) { return NS_ERROR_FAILURE; } nsAutoCString profile; nsAutoCString appName; nsAutoCString vendor; if (aProfileName && !aProfileName->IsEmpty()) { profile = *aProfileName; } else if (aAppName) { appName = *aAppName; if (aVendorName) { vendor = *aVendorName; } } else if (gAppData->profile) { profile = gAppData->profile; } else { appName = gAppData->name; vendor = gAppData->vendor; } nsresult rv; #if defined (XP_MACOSX) if (!profile.IsEmpty()) { rv = AppendProfileString(aFile, profile.get()); } else { // Note that MacOS ignores the vendor when creating the profile hierarchy - // all application preferences directories live alongside one another in // ~/Library/Application Support/ rv = aFile->AppendNative(appName); } NS_ENSURE_SUCCESS(rv, rv); #elif defined(XP_WIN) if (!profile.IsEmpty()) { rv = AppendProfileString(aFile, profile.get()); } else { if (!vendor.IsEmpty()) { rv = aFile->AppendNative(vendor); NS_ENSURE_SUCCESS(rv, rv); } rv = aFile->AppendNative(appName); } NS_ENSURE_SUCCESS(rv, rv); #elif defined(ANDROID) // The directory used for storing profiles // The parent of this directory is set in GetUserDataDirectoryHome // XXX: handle gAppData->profile properly // XXXsmaug ...and the rest of the profile creation! MOZ_ASSERT(!aAppName, "Profile creation for external applications is not implemented!"); rv = aFile->AppendNative(nsDependentCString("mozilla")); NS_ENSURE_SUCCESS(rv, rv); #elif defined(XP_UNIX) nsAutoCString folder; // Make it hidden (by starting with "."), except when local (the // profile is already under ~/.cache or XDG_CACHE_HOME). if (!aLocal) folder.Assign('.'); if (!profile.IsEmpty()) { // Skip any leading path characters const char* profileStart = profile.get(); while (*profileStart == '/' || *profileStart == '\\') profileStart++; // On the off chance that someone wanted their folder to be hidden don't // let it become ".." if (*profileStart == '.' && !aLocal) profileStart++; folder.Append(profileStart); ToLowerCase(folder); rv = AppendProfileString(aFile, folder.BeginReading()); } else { if (!vendor.IsEmpty()) { folder.Append(vendor); ToLowerCase(folder); rv = aFile->AppendNative(folder); NS_ENSURE_SUCCESS(rv, rv); folder.Truncate(); } folder.Append(appName); ToLowerCase(folder); rv = aFile->AppendNative(folder); } NS_ENSURE_SUCCESS(rv, rv); #else #error "Don't know how to get profile path on your platform" #endif return NS_OK; }
NS_IMETHODIMP nsAppFileLocationProvider::GetFile(const char *prop, bool *persistent, nsIFile **_retval) { if (NS_WARN_IF(!prop)) return NS_ERROR_INVALID_ARG; nsCOMPtr<nsIFile> localFile; nsresult rv = NS_ERROR_FAILURE; *_retval = nullptr; *persistent = true; #ifdef MOZ_WIDGET_COCOA FSRef fileRef; nsCOMPtr<nsILocalFileMac> macFile; #endif if (nsCRT::strcmp(prop, NS_APP_APPLICATION_REGISTRY_DIR) == 0) { rv = GetProductDirectory(getter_AddRefs(localFile)); } else if (nsCRT::strcmp(prop, NS_APP_APPLICATION_REGISTRY_FILE) == 0) { rv = GetProductDirectory(getter_AddRefs(localFile)); if (NS_SUCCEEDED(rv)) rv = localFile->AppendNative(APP_REGISTRY_NAME); } else if (nsCRT::strcmp(prop, NS_APP_DEFAULTS_50_DIR) == 0) { rv = CloneMozBinDirectory(getter_AddRefs(localFile)); if (NS_SUCCEEDED(rv)) rv = localFile->AppendRelativeNativePath(DEFAULTS_DIR_NAME); } else if (nsCRT::strcmp(prop, NS_APP_PREF_DEFAULTS_50_DIR) == 0) { rv = CloneMozBinDirectory(getter_AddRefs(localFile)); if (NS_SUCCEEDED(rv)) { rv = localFile->AppendRelativeNativePath(DEFAULTS_DIR_NAME); if (NS_SUCCEEDED(rv)) rv = localFile->AppendRelativeNativePath(DEFAULTS_PREF_DIR_NAME); } } else if (nsCRT::strcmp(prop, NS_APP_PROFILE_DEFAULTS_50_DIR) == 0 || nsCRT::strcmp(prop, NS_APP_PROFILE_DEFAULTS_NLOC_50_DIR) == 0) { rv = CloneMozBinDirectory(getter_AddRefs(localFile)); if (NS_SUCCEEDED(rv)) { rv = localFile->AppendRelativeNativePath(DEFAULTS_DIR_NAME); if (NS_SUCCEEDED(rv)) rv = localFile->AppendRelativeNativePath(DEFAULTS_PROFILE_DIR_NAME); } } else if (nsCRT::strcmp(prop, NS_APP_USER_PROFILES_ROOT_DIR) == 0) { rv = GetDefaultUserProfileRoot(getter_AddRefs(localFile)); } else if (nsCRT::strcmp(prop, NS_APP_USER_PROFILES_LOCAL_ROOT_DIR) == 0) { rv = GetDefaultUserProfileRoot(getter_AddRefs(localFile), true); } else if (nsCRT::strcmp(prop, NS_APP_RES_DIR) == 0) { rv = CloneMozBinDirectory(getter_AddRefs(localFile)); if (NS_SUCCEEDED(rv)) rv = localFile->AppendRelativeNativePath(RES_DIR_NAME); } else if (nsCRT::strcmp(prop, NS_APP_CHROME_DIR) == 0) { rv = CloneMozBinDirectory(getter_AddRefs(localFile)); if (NS_SUCCEEDED(rv)) rv = localFile->AppendRelativeNativePath(CHROME_DIR_NAME); } else if (nsCRT::strcmp(prop, NS_APP_PLUGINS_DIR) == 0) { rv = CloneMozBinDirectory(getter_AddRefs(localFile)); if (NS_SUCCEEDED(rv)) rv = localFile->AppendRelativeNativePath(PLUGINS_DIR_NAME); } #ifdef MOZ_WIDGET_COCOA else if (nsCRT::strcmp(prop, NS_MACOSX_USER_PLUGIN_DIR) == 0) { if (::FSFindFolder(kUserDomain, kInternetPlugInFolderType, false, &fileRef) == noErr) { rv = NS_NewLocalFileWithFSRef(&fileRef, true, getter_AddRefs(macFile)); if (NS_SUCCEEDED(rv)) localFile = macFile; } } else if (nsCRT::strcmp(prop, NS_MACOSX_LOCAL_PLUGIN_DIR) == 0) { if (::FSFindFolder(kLocalDomain, kInternetPlugInFolderType, false, &fileRef) == noErr) { rv = NS_NewLocalFileWithFSRef(&fileRef, true, getter_AddRefs(macFile)); if (NS_SUCCEEDED(rv)) localFile = macFile; } } else if (nsCRT::strcmp(prop, NS_MACOSX_JAVA2_PLUGIN_DIR) == 0) { static const char *const java2PluginDirPath = "/System/Library/Java/Support/Deploy.bundle/Contents/Resources/"; rv = NS_NewNativeLocalFile(nsDependentCString(java2PluginDirPath), true, getter_AddRefs(localFile)); } #else else if (nsCRT::strcmp(prop, NS_ENV_PLUGINS_DIR) == 0) { NS_ERROR("Don't use nsAppFileLocationProvider::GetFile(NS_ENV_PLUGINS_DIR, ...). " "Use nsAppFileLocationProvider::GetFiles(...)."); const char *pathVar = PR_GetEnv("MOZ_PLUGIN_PATH"); if (pathVar && *pathVar) rv = NS_NewNativeLocalFile(nsDependentCString(pathVar), true, getter_AddRefs(localFile)); } else if (nsCRT::strcmp(prop, NS_USER_PLUGINS_DIR) == 0) { #ifdef ENABLE_SYSTEM_EXTENSION_DIRS rv = GetProductDirectory(getter_AddRefs(localFile)); if (NS_SUCCEEDED(rv)) rv = localFile->AppendRelativeNativePath(PLUGINS_DIR_NAME); #else rv = NS_ERROR_FAILURE; #endif } #ifdef XP_UNIX else if (nsCRT::strcmp(prop, NS_SYSTEM_PLUGINS_DIR) == 0) { #ifdef ENABLE_SYSTEM_EXTENSION_DIRS static const char *const sysLPlgDir = #if defined(HAVE_USR_LIB64_DIR) && defined(__LP64__) "/usr/lib64/mozilla/plugins"; #elif defined(__OpenBSD__) || defined (__FreeBSD__) "/usr/local/lib/mozilla/plugins"; #else "/usr/lib/mozilla/plugins"; #endif rv = NS_NewNativeLocalFile(nsDependentCString(sysLPlgDir), false, getter_AddRefs(localFile)); #else rv = NS_ERROR_FAILURE; #endif } #endif #endif else if (nsCRT::strcmp(prop, NS_APP_SEARCH_DIR) == 0) { rv = CloneMozBinDirectory(getter_AddRefs(localFile)); if (NS_SUCCEEDED(rv)) rv = localFile->AppendRelativeNativePath(SEARCH_DIR_NAME); } else if (nsCRT::strcmp(prop, NS_APP_USER_SEARCH_DIR) == 0) { rv = NS_GetSpecialDirectory(NS_APP_USER_PROFILE_50_DIR, _retval); if (NS_SUCCEEDED(rv)) rv = (*_retval)->AppendNative(SEARCH_DIR_NAME); } else if (nsCRT::strcmp(prop, NS_APP_INSTALL_CLEANUP_DIR) == 0) { // This is cloned so that embeddors will have a hook to override // with their own cleanup dir. See bugzilla bug #105087 rv = CloneMozBinDirectory(getter_AddRefs(localFile)); } if (localFile && NS_SUCCEEDED(rv)) return localFile->QueryInterface(NS_GET_IID(nsIFile), (void**)_retval); return rv; }
NS_IMETHODIMP nsXREDirProvider::GetFile(const char* aProperty, bool* aPersistent, nsIFile** aFile) { nsresult rv; bool gettingProfile = false; if (!strcmp(aProperty, NS_APP_USER_PROFILE_LOCAL_50_DIR)) { // If XRE_NotifyProfile hasn't been called, don't fall through to // mAppProvider on the profile keys. if (!mProfileNotified) return NS_ERROR_FAILURE; if (mProfileLocalDir) return mProfileLocalDir->Clone(aFile); if (mAppProvider) return mAppProvider->GetFile(aProperty, aPersistent, aFile); // This falls through to the case below gettingProfile = true; } if (!strcmp(aProperty, NS_APP_USER_PROFILE_50_DIR) || gettingProfile) { if (!mProfileNotified) return NS_ERROR_FAILURE; if (mProfileDir) return mProfileDir->Clone(aFile); if (mAppProvider) return mAppProvider->GetFile(aProperty, aPersistent, aFile); // If we don't succeed here, bail early so that we aren't reentrant // through the "GetProfileDir" call below. return NS_ERROR_FAILURE; } if (mAppProvider) { rv = mAppProvider->GetFile(aProperty, aPersistent, aFile); if (NS_SUCCEEDED(rv) && *aFile) return rv; } *aPersistent = true; if (!strcmp(aProperty, NS_GRE_DIR)) { return mGREDir->Clone(aFile); } else if (!strcmp(aProperty, NS_OS_CURRENT_PROCESS_DIR) || !strcmp(aProperty, NS_APP_INSTALL_CLEANUP_DIR)) { return GetAppDir()->Clone(aFile); } rv = NS_ERROR_FAILURE; nsCOMPtr<nsIFile> file; if (!strcmp(aProperty, NS_APP_PROFILE_DEFAULTS_50_DIR) || !strcmp(aProperty, NS_APP_PROFILE_DEFAULTS_NLOC_50_DIR)) { return GetProfileDefaultsDir(aFile); } else if (!strcmp(aProperty, NS_APP_PREF_DEFAULTS_50_DIR)) { // return the GRE default prefs directory here, and the app default prefs // directory (if applicable) in NS_APP_PREFS_DEFAULTS_DIR_LIST. rv = mGREDir->Clone(getter_AddRefs(file)); if (NS_SUCCEEDED(rv)) { rv = file->AppendNative(NS_LITERAL_CSTRING("defaults")); if (NS_SUCCEEDED(rv)) rv = file->AppendNative(NS_LITERAL_CSTRING("pref")); } } else if (!strcmp(aProperty, NS_APP_APPLICATION_REGISTRY_DIR) || !strcmp(aProperty, XRE_USER_APP_DATA_DIR)) { rv = GetUserAppDataDirectory(getter_AddRefs(file)); } else if (!strcmp(aProperty, XRE_UPDATE_ROOT_DIR)) { rv = GetUpdateRootDir(getter_AddRefs(file)); } else if (!strcmp(aProperty, NS_APP_APPLICATION_REGISTRY_FILE)) { rv = GetUserAppDataDirectory(getter_AddRefs(file)); if (NS_SUCCEEDED(rv)) rv = file->AppendNative(NS_LITERAL_CSTRING(APP_REGISTRY_NAME)); } else if (!strcmp(aProperty, NS_APP_USER_PROFILES_ROOT_DIR)) { rv = GetUserProfilesRootDir(getter_AddRefs(file), nullptr, nullptr, nullptr); } else if (!strcmp(aProperty, NS_APP_USER_PROFILES_LOCAL_ROOT_DIR)) { rv = GetUserProfilesLocalDir(getter_AddRefs(file), nullptr, nullptr, nullptr); } else if (!strcmp(aProperty, XRE_EXECUTABLE_FILE) && gArgv[0]) { nsCOMPtr<nsIFile> lf; rv = XRE_GetBinaryPath(gArgv[0], getter_AddRefs(lf)); if (NS_SUCCEEDED(rv)) file = lf; } else if (!strcmp(aProperty, NS_APP_PROFILE_DIR_STARTUP) && mProfileDir) { return mProfileDir->Clone(aFile); } else if (!strcmp(aProperty, NS_APP_PROFILE_LOCAL_DIR_STARTUP)) { if (mProfileLocalDir) return mProfileLocalDir->Clone(aFile); if (mProfileDir) return mProfileDir->Clone(aFile); if (mAppProvider) return mAppProvider->GetFile(NS_APP_PROFILE_DIR_STARTUP, aPersistent, aFile); } #if defined(XP_UNIX) || defined(XP_MACOSX) else if (!strcmp(aProperty, XRE_SYS_LOCAL_EXTENSION_PARENT_DIR)) { #ifdef ENABLE_SYSTEM_EXTENSION_DIRS return GetSystemExtensionsDirectory(aFile); #else return NS_ERROR_FAILURE; #endif } #endif #if defined(XP_UNIX) && !defined(XP_MACOSX) else if (!strcmp(aProperty, XRE_SYS_SHARE_EXTENSION_PARENT_DIR)) { #ifdef ENABLE_SYSTEM_EXTENSION_DIRS #if defined(__OpenBSD__) || defined(__FreeBSD__) static const char *const sysLExtDir = "/usr/local/share/mozilla/extensions"; #else static const char *const sysLExtDir = "/usr/share/mozilla/extensions"; #endif return NS_NewNativeLocalFile(nsDependentCString(sysLExtDir), false, aFile); #else return NS_ERROR_FAILURE; #endif } #endif else if (!strcmp(aProperty, XRE_USER_SYS_EXTENSION_DIR)) { #ifdef ENABLE_SYSTEM_EXTENSION_DIRS return GetSysUserExtensionsDirectory(aFile); #else return NS_ERROR_FAILURE; #endif } else if (!strcmp(aProperty, XRE_APP_DISTRIBUTION_DIR)) { bool persistent = false; rv = GetFile(XRE_EXECUTABLE_FILE, &persistent, getter_AddRefs(file)); if (NS_SUCCEEDED(rv)) rv = file->SetNativeLeafName(NS_LITERAL_CSTRING("distribution")); } else if (NS_SUCCEEDED(GetProfileStartupDir(getter_AddRefs(file)))) { // We need to allow component, xpt, and chrome registration to // occur prior to the profile-after-change notification. if (!strcmp(aProperty, NS_APP_USER_CHROME_DIR)) { rv = file->AppendNative(NS_LITERAL_CSTRING("chrome")); } } if (NS_SUCCEEDED(rv) && file) { NS_ADDREF(*aFile = file); return NS_OK; } bool ensureFilePermissions = false; if (NS_SUCCEEDED(GetProfileDir(getter_AddRefs(file)))) { if (!strcmp(aProperty, NS_APP_PREFS_50_DIR)) { rv = NS_OK; } else if (!strcmp(aProperty, NS_APP_PREFS_50_FILE)) { rv = file->AppendNative(NS_LITERAL_CSTRING("prefs.js")); } else if (!strcmp(aProperty, NS_METRO_APP_PREFS_50_FILE)) { rv = file->AppendNative(NS_LITERAL_CSTRING("metro-prefs.js")); } else if (!strcmp(aProperty, NS_LOCALSTORE_UNSAFE_FILE)) { rv = file->AppendNative(NS_LITERAL_CSTRING("localstore.rdf")); } else if (!strcmp(aProperty, NS_APP_LOCALSTORE_50_FILE)) { if (gSafeMode) { rv = file->AppendNative(NS_LITERAL_CSTRING("localstore-safe.rdf")); file->Remove(false); } else { rv = file->AppendNative(NS_LITERAL_CSTRING("localstore.rdf")); EnsureProfileFileExists(file); ensureFilePermissions = true; } } else if (!strcmp(aProperty, NS_APP_USER_MIMETYPES_50_FILE)) { rv = file->AppendNative(NS_LITERAL_CSTRING("mimeTypes.rdf")); EnsureProfileFileExists(file); ensureFilePermissions = true; } else if (!strcmp(aProperty, NS_APP_DOWNLOADS_50_FILE)) { rv = file->AppendNative(NS_LITERAL_CSTRING("downloads.rdf")); } else if (!strcmp(aProperty, NS_APP_PREFS_OVERRIDE_DIR)) { rv = mProfileDir->Clone(getter_AddRefs(file)); nsresult tmp = file->AppendNative(NS_LITERAL_CSTRING(PREF_OVERRIDE_DIRNAME)); if (NS_FAILED(tmp)) { rv = tmp; } tmp = EnsureDirectoryExists(file); if (NS_FAILED(tmp)) { rv = tmp; } } } if (NS_FAILED(rv) || !file) return NS_ERROR_FAILURE; if (ensureFilePermissions) { bool fileToEnsureExists; bool isWritable; if (NS_SUCCEEDED(file->Exists(&fileToEnsureExists)) && fileToEnsureExists && NS_SUCCEEDED(file->IsWritable(&isWritable)) && !isWritable) { uint32_t permissions; if (NS_SUCCEEDED(file->GetPermissions(&permissions))) { rv = file->SetPermissions(permissions | 0600); NS_ASSERTION(NS_SUCCEEDED(rv), "failed to ensure file permissions"); } } } NS_ADDREF(*aFile = file); return NS_OK; }
nsresult HttpBaseChannel::SetupReplacementChannel(nsIURI *newURI, nsIChannel *newChannel, bool preserveMethod) { LOG(("HttpBaseChannel::SetupReplacementChannel " "[this=%p newChannel=%p preserveMethod=%d]", this, newChannel, preserveMethod)); PRUint32 newLoadFlags = mLoadFlags | LOAD_REPLACE; // if the original channel was using SSL and this channel is not using // SSL, then no need to inhibit persistent caching. however, if the // original channel was not using SSL and has INHIBIT_PERSISTENT_CACHING // set, then allow the flag to apply to the redirected channel as well. // since we force set INHIBIT_PERSISTENT_CACHING on all HTTPS channels, // we only need to check if the original channel was using SSL. if (mConnectionInfo->UsingSSL()) newLoadFlags &= ~INHIBIT_PERSISTENT_CACHING; // Do not pass along LOAD_CHECK_OFFLINE_CACHE newLoadFlags &= ~nsICachingChannel::LOAD_CHECK_OFFLINE_CACHE; newChannel->SetLoadGroup(mLoadGroup); newChannel->SetNotificationCallbacks(mCallbacks); newChannel->SetLoadFlags(newLoadFlags); nsCOMPtr<nsIHttpChannel> httpChannel = do_QueryInterface(newChannel); if (!httpChannel) return NS_OK; // no other options to set if (preserveMethod) { nsCOMPtr<nsIUploadChannel> uploadChannel = do_QueryInterface(httpChannel); nsCOMPtr<nsIUploadChannel2> uploadChannel2 = do_QueryInterface(httpChannel); if (mUploadStream && (uploadChannel2 || uploadChannel)) { // rewind upload stream nsCOMPtr<nsISeekableStream> seekable = do_QueryInterface(mUploadStream); if (seekable) seekable->Seek(nsISeekableStream::NS_SEEK_SET, 0); // replicate original call to SetUploadStream... if (uploadChannel2) { const char *ctype = mRequestHead.PeekHeader(nsHttp::Content_Type); if (!ctype) ctype = ""; const char *clen = mRequestHead.PeekHeader(nsHttp::Content_Length); PRInt64 len = clen ? nsCRT::atoll(clen) : -1; uploadChannel2->ExplicitSetUploadStream( mUploadStream, nsDependentCString(ctype), len, nsDependentCString(mRequestHead.Method()), mUploadStreamHasHeaders); } else { if (mUploadStreamHasHeaders) { uploadChannel->SetUploadStream(mUploadStream, EmptyCString(), -1); } else { const char *ctype = mRequestHead.PeekHeader(nsHttp::Content_Type); const char *clen = mRequestHead.PeekHeader(nsHttp::Content_Length); if (!ctype) { ctype = "application/octet-stream"; } if (clen) { uploadChannel->SetUploadStream(mUploadStream, nsDependentCString(ctype), atoi(clen)); } } } } // since preserveMethod is true, we need to ensure that the appropriate // request method gets set on the channel, regardless of whether or not // we set the upload stream above. This means SetRequestMethod() will // be called twice if ExplicitSetUploadStream() gets called above. httpChannel->SetRequestMethod(nsDependentCString(mRequestHead.Method())); } // convey the referrer if one was used for this channel to the next one if (mReferrer) httpChannel->SetReferrer(mReferrer); // convey the mAllowPipelining flag httpChannel->SetAllowPipelining(mAllowPipelining); // convey the new redirection limit httpChannel->SetRedirectionLimit(mRedirectionLimit - 1); nsCOMPtr<nsIHttpChannelInternal> httpInternal = do_QueryInterface(newChannel); if (httpInternal) { // convey the mForceAllowThirdPartyCookie flag httpInternal->SetForceAllowThirdPartyCookie(mForceAllowThirdPartyCookie); // convey the spdy flag httpInternal->SetAllowSpdy(mAllowSpdy); // update the DocumentURI indicator since we are being redirected. // if this was a top-level document channel, then the new channel // should have its mDocumentURI point to newURI; otherwise, we // just need to pass along our mDocumentURI to the new channel. if (newURI && (mURI == mDocumentURI)) httpInternal->SetDocumentURI(newURI); else httpInternal->SetDocumentURI(mDocumentURI); // if there is a chain of keys for redirect-responses we transfer it to // the new channel (see bug #561276) if (mRedirectedCachekeys) { LOG(("HttpBaseChannel::SetupReplacementChannel " "[this=%p] transferring chain of redirect cache-keys", this)); httpInternal->SetCacheKeysRedirectChain(mRedirectedCachekeys.forget()); } } // transfer application cache information nsCOMPtr<nsIApplicationCacheChannel> appCacheChannel = do_QueryInterface(newChannel); if (appCacheChannel) { appCacheChannel->SetApplicationCache(mApplicationCache); appCacheChannel->SetInheritApplicationCache(mInheritApplicationCache); // We purposely avoid transfering mChooseApplicationCache. } // transfer any properties nsCOMPtr<nsIWritablePropertyBag> bag(do_QueryInterface(newChannel)); if (bag) mPropertyHash.EnumerateRead(CopyProperties, bag.get()); // transfer timed channel enabled status nsCOMPtr<nsITimedChannel> timed(do_QueryInterface(newChannel)); if (timed) timed->SetTimingEnabled(mTimingEnabled); return NS_OK; }
PRBool RegisterXULRunner(PRBool aRegisterGlobally, nsIFile* aLocation, const GREProperty *aProperties, PRUint32 aPropertiesLen) { // Register ourself in /etc/gre.d or ~/.gre.d/ and record what key we created // for future unregistration. nsresult rv; char root[MAXPATHLEN] = "/etc/gre.d"; if (!aRegisterGlobally) { char *home = PR_GetEnv("HOME"); if (!home || !*home) return PR_FALSE; PR_snprintf(root, MAXPATHLEN, "%s/.gre.d", home); } nsCAutoString greHome; rv = aLocation->GetNativePath(greHome); if (NS_FAILED(rv)) return rv; nsCOMPtr<nsIFile> savedInfoFile; aLocation->Clone(getter_AddRefs(savedInfoFile)); nsCOMPtr<nsILocalFile> localSaved(do_QueryInterface(savedInfoFile)); if (!localSaved) return PR_FALSE; const char *infoname = aRegisterGlobally ? kRegFileGlobal : kRegFileUser; localSaved->AppendNative(nsDependentCString(infoname)); AutoFDClose fd; rv = localSaved->OpenNSPRFileDesc(PR_CREATE_FILE | PR_RDWR, 0664, &fd); // XXX report error? if (NS_FAILED(rv)) return PR_FALSE; char keyName[MAXPATHLEN]; PRInt32 r = PR_Read(fd, keyName, MAXPATHLEN); if (r < 0) return PR_FALSE; char regfile[MAXPATHLEN]; if (r > 0) { keyName[r] = '\0'; PR_snprintf(regfile, MAXPATHLEN, "%s/%s.conf", root, keyName); // There was already a .reginfo file, let's see if we are already // registered. if (access(regfile, R_OK) == 0) { fprintf(stderr, "Warning: Configuration file '%s' already exists.\n" "No action was performed.\n", regfile); return PR_FALSE; } rv = localSaved->OpenNSPRFileDesc(PR_CREATE_FILE | PR_WRONLY | PR_TRUNCATE, 0664, &fd); if (NS_FAILED(rv)) return PR_FALSE; } if (access(root, R_OK | X_OK) && mkdir(root, 0775)) { fprintf(stderr, "Error: could not create '%s'.\n", root); return PR_FALSE; } PR_snprintf(regfile, MAXPATHLEN, "%s/%s.conf", root, kGREBuildID); if (MakeConfFile(regfile, greHome, aProperties, aPropertiesLen)) { PR_Write(fd, kGREBuildID, sizeof(kGREBuildID) - 1); return PR_TRUE; } for (int i = 0; i < UNIQ_LOOP_LIMIT; ++i) { static char buildID[30]; sprintf(buildID, "%s_%i", kGREBuildID, i); PR_snprintf(regfile, MAXPATHLEN, "%s/%s.conf", root, buildID); if (MakeConfFile(regfile, greHome, aProperties, aPropertiesLen)) { PR_Write(fd, buildID, strlen(buildID)); return PR_TRUE; } } return PR_FALSE; }