NS_IMETHODIMP nsJavaXPTCStub::QueryInterface(const nsID &aIID, void **aInstancePtr) { nsresult rv; LOG(("JavaStub::QueryInterface()\n")); *aInstancePtr = nsnull; nsJavaXPTCStub *master = mMaster ? mMaster : this; // This helps us differentiate between the help classes. if (aIID.Equals(NS_GET_IID(nsJavaXPTCStub))) { *aInstancePtr = master; NS_ADDREF(this); return NS_OK; } // always return the master stub for nsISupports if (aIID.Equals(NS_GET_IID(nsISupports))) { *aInstancePtr = master->mXPTCStub; NS_ADDREF(master); return NS_OK; } // All Java objects support weak references if (aIID.Equals(NS_GET_IID(nsISupportsWeakReference))) { *aInstancePtr = static_cast<nsISupportsWeakReference*>(master); NS_ADDREF(master); return NS_OK; } // does any existing stub support the requested IID? nsJavaXPTCStub *stub = master->FindStubSupportingIID(aIID); if (stub) { *aInstancePtr = stub->mXPTCStub; NS_ADDREF(stub); return NS_OK; } JNIEnv* env = GetJNIEnv(); // Query Java object LOG(("\tCalling Java object queryInterface\n")); jobject javaObject = env->CallObjectMethod(mJavaWeakRef, getReferentMID); jmethodID qiMID = 0; jclass clazz = env->GetObjectClass(javaObject); if (clazz) { char* sig = "(Ljava/lang/String;)Lorg/mozilla/interfaces/nsISupports;"; qiMID = env->GetMethodID(clazz, "queryInterface", sig); NS_ASSERTION(qiMID, "Failed to get queryInterface method ID"); } if (qiMID == 0) { env->ExceptionClear(); return NS_NOINTERFACE; } // construct IID string jstring iid_jstr = nsnull; char* iid_str = aIID.ToString(); if (iid_str) { iid_jstr = env->NewStringUTF(iid_str); } if (!iid_str || !iid_jstr) { env->ExceptionClear(); return NS_ERROR_OUT_OF_MEMORY; } PR_Free(iid_str); // call queryInterface method jobject obj = env->CallObjectMethod(javaObject, qiMID, iid_jstr); if (env->ExceptionCheck()) { env->ExceptionClear(); return NS_ERROR_FAILURE; } if (!obj) return NS_NOINTERFACE; // Get interface info for new java object nsCOMPtr<nsIInterfaceInfoManager> iim(do_GetService(NS_INTERFACEINFOMANAGER_SERVICE_CONTRACTID, &rv)); NS_ENSURE_SUCCESS(rv, rv); nsCOMPtr<nsIInterfaceInfo> iinfo; rv = iim->GetInfoForIID(&aIID, getter_AddRefs(iinfo)); if (NS_FAILED(rv)) return rv; stub = new nsJavaXPTCStub(obj, iinfo, &rv); if (!stub) return NS_ERROR_OUT_OF_MEMORY; if (NS_FAILED(rv)) { delete stub; return rv; } // add stub to the master's list of children, so we can preserve // symmetry in future QI calls. the master will delete each child // when it is destroyed. the refcount of each child is bound to // the refcount of the master. this is done to deal with code // like this: // // nsCOMPtr<nsIBar> bar = ...; // nsIFoo *foo; // { // nsCOMPtr<nsIFoo> temp = do_QueryInterface(bar); // foo = temp; // } // foo->DoStuff(); // // while this code is not valid XPCOM (since it is using |foo| // after having called Release on it), such code is unfortunately // very common in the mozilla codebase. the assumption this code // is making is that so long as |bar| is alive, it should be valid // to access |foo| even if the code doesn't own a strong reference // to |foo|! clearly wrong, but we need to support it anyways. stub->mMaster = master; master->mChildren.AppendElement(stub); *aInstancePtr = stub->mXPTCStub; NS_ADDREF(stub); return NS_OK; }
nsresult nsMsgTagService::MigrateLabelsToTags() { nsCString prefString; int32_t prefVersion = 0; nsresult rv = m_tagPrefBranch->GetIntPref(TAG_PREF_VERSION, &prefVersion); if (NS_SUCCEEDED(rv) && prefVersion > 1) return rv; else if (prefVersion == 1) { gMigratingKeys = true; // need to convert the keys to lower case nsIMsgTag **tagArray; uint32_t numTags; GetAllTags(&numTags, &tagArray); for (uint32_t tagIndex = 0; tagIndex < numTags; tagIndex++) { nsAutoCString key, color, ordinal; nsAutoString tagStr; nsIMsgTag *tag = tagArray[tagIndex]; tag->GetKey(key); tag->GetTag(tagStr); tag->GetOrdinal(ordinal); tag->GetColor(color); DeleteKey(key); ToLowerCase(key); AddTagForKey(key, tagStr, color, ordinal); } NS_FREE_XPCOM_ISUPPORTS_POINTER_ARRAY(numTags, tagArray); gMigratingKeys = false; } else { nsCOMPtr<nsIPrefBranch> prefRoot(do_GetService(NS_PREFSERVICE_CONTRACTID)); nsCOMPtr<nsIPrefLocalizedString> pls; nsString ucsval; nsAutoCString labelKey("$label1"); for(int32_t i = 0; i < PREF_LABELS_MAX; ) { prefString.Assign(PREF_LABELS_DESCRIPTION); prefString.AppendInt(i + 1); rv = prefRoot->GetComplexValue(prefString.get(), NS_GET_IID(nsIPrefLocalizedString), getter_AddRefs(pls)); NS_ENSURE_SUCCESS(rv, rv); pls->ToString(getter_Copies(ucsval)); prefString.Assign(PREF_LABELS_COLOR); prefString.AppendInt(i + 1); nsCString csval; rv = prefRoot->GetCharPref(prefString.get(), getter_Copies(csval)); NS_ENSURE_SUCCESS(rv, rv); rv = AddTagForKey(labelKey, ucsval, csval, EmptyCString()); NS_ENSURE_SUCCESS(rv, rv); labelKey.SetCharAt(++i + '1', 6); } } m_tagPrefBranch->SetIntPref(TAG_PREF_VERSION, 2); return rv; }
JSObject * WrapperFactory::PrepareForWrapping(JSContext *cx, HandleObject scope, HandleObject objArg, HandleObject objectPassedToWrap) { bool waive = ShouldWaiveXray(cx, objectPassedToWrap); RootedObject obj(cx, objArg); // Outerize any raw inner objects at the entry point here, so that we don't // have to worry about them for the rest of the wrapping code. if (js::IsInnerObject(obj)) { JSAutoCompartment ac(cx, obj); obj = JS_ObjectToOuterObject(cx, obj); NS_ENSURE_TRUE(obj, nullptr); // The outerization hook wraps, which means that we can end up with a // CCW here if |obj| was a navigated-away-from inner. Strip any CCWs. obj = js::UncheckedUnwrap(obj); MOZ_ASSERT(js::IsOuterObject(obj)); } // If we've got an outer window, there's nothing special that needs to be // done here, and we can move on to the next phase of wrapping. We handle // this case first to allow us to assert against wrappers below. if (js::IsOuterObject(obj)) return waive ? WaiveXray(cx, obj) : obj; // Here are the rules for wrapping: // We should never get a proxy here (the JS engine unwraps those for us). MOZ_ASSERT(!IsWrapper(obj)); // If the object being wrapped is a prototype for a standard class and the // wrapper does not subsumes the wrappee, use the one from the content // compartment. This is generally safer all-around, and in the COW case this // lets us safely take advantage of things like .forEach() via the // ChromeObjectWrapper machinery. // // If the prototype chain of chrome object |obj| looks like this: // // obj => foo => bar => chromeWin.StandardClass.prototype // // The prototype chain of COW(obj) looks lke this: // // COW(obj) => COW(foo) => COW(bar) => contentWin.StandardClass.prototype // // NB: We now remap all non-subsuming access of standard prototypes. // // NB: We need to ignore domain here so that the security relationship we // compute here can't change over time. See the comment above the other // subsumes call below. bool subsumes = AccessCheck::subsumes(js::GetContextCompartment(cx), js::GetObjectCompartment(obj)); XrayType xrayType = GetXrayType(obj); if (!subsumes && (xrayType == NotXray || ForceCOWBehavior(obj))) { JSProtoKey key = JSProto_Null; { JSAutoCompartment ac(cx, obj); key = IdentifyStandardPrototype(obj); } if (key != JSProto_Null) { RootedObject homeProto(cx); if (!JS_GetClassPrototype(cx, key, &homeProto)) return nullptr; MOZ_ASSERT(homeProto); // No need to double-wrap here. We should never have waivers to // COWs. return homeProto; } } // Now, our object is ready to be wrapped, but several objects (notably // nsJSIIDs) have a wrapper per scope. If we are about to wrap one of // those objects in a security wrapper, then we need to hand back the // wrapper for the new scope instead. Also, global objects don't move // between scopes so for those we also want to return the wrapper. So... if (!IS_WN_REFLECTOR(obj) || !js::GetObjectParent(obj)) return waive ? WaiveXray(cx, obj) : obj; XPCWrappedNative *wn = XPCWrappedNative::Get(obj); JSAutoCompartment ac(cx, obj); XPCCallContext ccx(JS_CALLER, cx, obj); RootedObject wrapScope(cx, scope); { if (NATIVE_HAS_FLAG(&ccx, WantPreCreate)) { // We have a precreate hook. This object might enforce that we only // ever create JS object for it. // Note: this penalizes objects that only have one wrapper, but are // being accessed across compartments. We would really prefer to // replace the above code with a test that says "do you only have one // wrapper?" nsresult rv = wn->GetScriptableInfo()->GetCallback()-> PreCreate(wn->Native(), cx, scope, wrapScope.address()); NS_ENSURE_SUCCESS(rv, waive ? WaiveXray(cx, obj) : obj); // If the handed back scope differs from the passed-in scope and is in // a separate compartment, then this object is explicitly requesting // that we don't create a second JS object for it: create a security // wrapper. if (js::GetObjectCompartment(scope) != js::GetObjectCompartment(wrapScope)) return waive ? WaiveXray(cx, obj) : obj; RootedObject currentScope(cx, JS_GetGlobalForObject(cx, obj)); if (MOZ_UNLIKELY(wrapScope != currentScope)) { // The wrapper claims it wants to be in the new scope, but // currently has a reflection that lives in the old scope. This // can mean one of two things, both of which are rare: // // 1 - The object has a PreCreate hook (we checked for it above), // but is deciding to request one-wrapper-per-scope (rather than // one-wrapper-per-native) for some reason. Usually, a PreCreate // hook indicates one-wrapper-per-native. In this case we want to // make a new wrapper in the new scope. // // 2 - We're midway through wrapper reparenting. The document has // moved to a new scope, but |wn| hasn't been moved yet, and // we ended up calling JS_WrapObject() on its JS object. In this // case, we want to return the existing wrapper. // // So we do a trick: call PreCreate _again_, but say that we're // wrapping for the old scope, rather than the new one. If (1) is // the case, then PreCreate will return the scope we pass to it // (the old scope). If (2) is the case, PreCreate will return the // scope of the document (the new scope). RootedObject probe(cx); rv = wn->GetScriptableInfo()->GetCallback()-> PreCreate(wn->Native(), cx, currentScope, probe.address()); // Check for case (2). if (probe != currentScope) { MOZ_ASSERT(probe == wrapScope); return waive ? WaiveXray(cx, obj) : obj; } // Ok, must be case (1). Fall through and create a new wrapper. } // Nasty hack for late-breaking bug 781476. This will confuse identity checks, // but it's probably better than any of our alternatives. // // Note: We have to ignore domain here. The JS engine assumes that, given a // compartment c, if c->wrap(x) returns a cross-compartment wrapper at time t0, // it will also return a cross-compartment wrapper for any time t1 > t0 unless // an explicit transplant is performed. In particular, wrapper recomputation // assumes that recomputing a wrapper will always result in a wrapper. // // This doesn't actually pose a security issue, because we'll still compute // the correct (opaque) wrapper for the object below given the security // characteristics of the two compartments. if (!AccessCheck::isChrome(js::GetObjectCompartment(wrapScope)) && AccessCheck::subsumes(js::GetObjectCompartment(wrapScope), js::GetObjectCompartment(obj))) { return waive ? WaiveXray(cx, obj) : obj; } } } // This public WrapNativeToJSVal API enters the compartment of 'wrapScope' // so we don't have to. RootedValue v(cx); nsresult rv = nsXPConnect::XPConnect()->WrapNativeToJSVal(cx, wrapScope, wn->Native(), nullptr, &NS_GET_IID(nsISupports), false, &v); NS_ENSURE_SUCCESS(rv, nullptr); obj.set(&v.toObject()); MOZ_ASSERT(IS_WN_REFLECTOR(obj), "bad object"); // Because the underlying native didn't have a PreCreate hook, we had // to a new (or possibly pre-existing) XPCWN in our compartment. // This could be a problem for chrome code that passes XPCOM objects // across compartments, because the effects of QI would disappear across // compartments. // // So whenever we pull an XPCWN across compartments in this manner, we // give the destination object the union of the two native sets. We try // to do this cleverly in the common case to avoid too much overhead. XPCWrappedNative *newwn = XPCWrappedNative::Get(obj); XPCNativeSet *unionSet = XPCNativeSet::GetNewOrUsed(newwn->GetSet(), wn->GetSet(), false); if (!unionSet) return nullptr; newwn->SetSet(unionSet); return waive ? WaiveXray(cx, obj) : obj; }
nsresult nsWifiMonitor::DoScan() { void* iwlib_handle = dlopen("libiw.so", RTLD_NOW); if (!iwlib_handle) { iwlib_handle = dlopen("libiw.so.29", RTLD_NOW); if (!iwlib_handle) { iwlib_handle = dlopen("libiw.so.30", RTLD_NOW); if (!iwlib_handle) { LOG(("Could not load libiw\n")); return NS_ERROR_NOT_AVAILABLE; } } } else { LOG(("Loaded libiw\n")); } iw_open_t iw_open = (iw_open_t) dlsym(iwlib_handle, "iw_sockets_open"); iw_enum_t iw_enum = (iw_enum_t) dlsym(iwlib_handle, "iw_enum_devices"); iw_stats_t iw_stats = (iw_stats_t)dlsym(iwlib_handle, "iw_get_stats"); if (!iw_open || !iw_enum || !iw_stats) { dlclose(iwlib_handle); LOG(("Could not load a symbol from iwlib.so\n")); return NS_ERROR_FAILURE; } int skfd = (*iw_open)(); if (skfd < 0) { dlclose(iwlib_handle); return NS_ERROR_FAILURE; } nsCOMArray<nsWifiAccessPoint> lastAccessPoints; nsCOMArray<nsWifiAccessPoint> accessPoints; char* args[] = {(char*) &accessPoints, (char*) iw_stats, nsnull }; while (mKeepGoing) { accessPoints.Clear(); (*iw_enum)(skfd, &scan_wifi, args, 1); PRBool accessPointsChanged = !AccessPointsEqual(accessPoints, lastAccessPoints); nsCOMArray<nsIWifiListener> currentListeners; { nsAutoMonitor mon(mMonitor); for (PRUint32 i = 0; i < mListeners.Length(); i++) { if (!mListeners[i].mHasSentData || accessPointsChanged) { mListeners[i].mHasSentData = PR_TRUE; currentListeners.AppendObject(mListeners[i].mListener); } } } ReplaceArray(lastAccessPoints, accessPoints); if (currentListeners.Count() > 0) { PRUint32 resultCount = lastAccessPoints.Count(); nsIWifiAccessPoint** result = static_cast<nsIWifiAccessPoint**> (nsMemory::Alloc(sizeof(nsIWifiAccessPoint*) * resultCount)); if (!result) { dlclose(iwlib_handle); return NS_ERROR_OUT_OF_MEMORY; } for (PRUint32 i = 0; i < resultCount; i++) result[i] = lastAccessPoints[i]; for (PRInt32 i = 0; i < currentListeners.Count(); i++) { LOG(("About to send data to the wifi listeners\n")); nsCOMPtr<nsIWifiListener> proxy; nsCOMPtr<nsIProxyObjectManager> proxyObjMgr = do_GetService("@mozilla.org/xpcomproxy;1"); proxyObjMgr->GetProxyForObject(NS_PROXY_TO_MAIN_THREAD, NS_GET_IID(nsIWifiListener), currentListeners[i], NS_PROXY_SYNC | NS_PROXY_ALWAYS, getter_AddRefs(proxy)); if (!proxy) { LOG(("There is no proxy available. this should never happen\n")); } else { nsresult rv = proxy->OnChange(result, resultCount); LOG( ("... sent %d\n", rv)); } } nsMemory::Free(result); } LOG(("waiting on monitor\n")); nsAutoMonitor mon(mMonitor); mon.Wait(PR_SecondsToInterval(60)); } iw_sockets_close(skfd); return NS_OK; }
int main(int argc, char *argv[]) { /* * Check that PRUnichar is equal in size to what compiler composes L"" * strings from; otherwise NS_LITERAL_STRING macros won't work correctly * and we will get a meaningless SIGSEGV. This, of course, must be checked * at compile time in xpcom/string/nsTDependentString.h, but XPCOM lacks * compile-time assert macros and I'm not going to add them now. */ if (sizeof(PRUnichar) != sizeof(wchar_t)) { printf("Error: sizeof(PRUnichar) {%lu} != sizeof(wchar_t) {%lu}!\n" "Probably, you forgot the -fshort-wchar compiler option.\n", (unsigned long) sizeof(PRUnichar), (unsigned long) sizeof(wchar_t)); return -1; } nsresult rc; /* * This is the standard XPCOM init procedure. * What we do is just follow the required steps to get an instance * of our main interface, which is IVirtualBox. */ #if defined(XPCOM_GLUE) XPCOMGlueStartup(nsnull); #endif /* * Note that we scope all nsCOMPtr variables in order to have all XPCOM * objects automatically released before we call NS_ShutdownXPCOM at the * end. This is an XPCOM requirement. */ { nsCOMPtr<nsIServiceManager> serviceManager; rc = NS_InitXPCOM2(getter_AddRefs(serviceManager), nsnull, nsnull); if (NS_FAILED(rc)) { printf("Error: XPCOM could not be initialized! rc=0x%x\n", rc); return -1; } #if 0 /* * Register our components. This step is only necessary if this executable * implements XPCOM components itself which is not the case for this * simple example. */ nsCOMPtr<nsIComponentRegistrar> registrar = do_QueryInterface(serviceManager); if (!registrar) { printf("Error: could not query nsIComponentRegistrar interface!\n"); return -1; } registrar->AutoRegister(nsnull); #endif /* * Make sure the main event queue is created. This event queue is * responsible for dispatching incoming XPCOM IPC messages. The main * thread should run this event queue's loop during lengthy non-XPCOM * operations to ensure messages from the VirtualBox server and other * XPCOM IPC clients are processed. This use case doesn't perform such * operations so it doesn't run the event loop. */ nsCOMPtr<nsIEventQueue> eventQ; rc = NS_GetMainEventQ(getter_AddRefs (eventQ)); if (NS_FAILED(rc)) { printf("Error: could not get main event queue! rc=%08X\n", rc); return -1; } /* * Now XPCOM is ready and we can start to do real work. * IVirtualBox is the root interface of VirtualBox and will be * retrieved from the XPCOM component manager. We use the * XPCOM provided smart pointer nsCOMPtr for all objects because * that's very convenient and removes the need deal with reference * counting and freeing. */ nsCOMPtr<nsIComponentManager> manager; rc = NS_GetComponentManager (getter_AddRefs (manager)); if (NS_FAILED(rc)) { printf("Error: could not get component manager! rc=%08X\n", rc); return -1; } nsCOMPtr<IVirtualBox> virtualBox; rc = manager->CreateInstanceByContractID (NS_VIRTUALBOX_CONTRACTID, nsnull, NS_GET_IID(IVirtualBox), getter_AddRefs(virtualBox)); if (NS_FAILED(rc)) { printf("Error, could not instantiate VirtualBox object! rc=0x%x\n", rc); return -1; } printf("VirtualBox object created\n"); //////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// listVMs(virtualBox); createVM(virtualBox); //////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// /* this is enough to free the IVirtualBox instance -- smart pointers rule! */ virtualBox = nsnull; /* * Process events that might have queued up in the XPCOM event * queue. If we don't process them, the server might hang. */ eventQ->ProcessPendingEvents(); } /* * Perform the standard XPCOM shutdown procedure. */ NS_ShutdownXPCOM(nsnull); #if defined(XPCOM_GLUE) XPCOMGlueShutdown(); #endif printf("Done!\n"); return 0; }
NS_IMPL_CYCLE_COLLECTION_UNLINK(mParent) NS_IMPL_CYCLE_COLLECTION_UNLINK_PRESERVED_WRAPPER NS_IMPL_CYCLE_COLLECTION_UNLINK_END NS_IMPL_CYCLE_COLLECTION_TRAVERSE_BEGIN(Blob) NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mParent) NS_IMPL_CYCLE_COLLECTION_TRAVERSE_SCRIPT_OBJECTS NS_IMPL_CYCLE_COLLECTION_TRAVERSE_END NS_IMPL_CYCLE_COLLECTION_TRACE_BEGIN(Blob) NS_IMPL_CYCLE_COLLECTION_TRACE_PRESERVED_WRAPPER NS_IMPL_CYCLE_COLLECTION_TRACE_END NS_INTERFACE_MAP_BEGIN_CYCLE_COLLECTION(Blob) // This class should not receive any nsIRemoteBlob QI! MOZ_ASSERT(!aIID.Equals(NS_GET_IID(nsIRemoteBlob))); NS_WRAPPERCACHE_INTERFACE_MAP_ENTRY NS_INTERFACE_MAP_ENTRY_AMBIGUOUS(nsISupports, nsIDOMBlob) NS_INTERFACE_MAP_ENTRY(nsIDOMBlob) NS_INTERFACE_MAP_ENTRY(nsIXHRSendable) NS_INTERFACE_MAP_ENTRY(nsIMutable) NS_INTERFACE_MAP_ENTRY(nsISupportsWeakReference) NS_INTERFACE_MAP_END NS_IMPL_CYCLE_COLLECTING_ADDREF(Blob) NS_IMPL_CYCLE_COLLECTING_RELEASE(Blob) /* static */ Blob* Blob::Create(nsISupports* aParent, BlobImpl* aImpl) {
NS_IMETHODIMP nsCRLManager::ImportCrl (PRUint8 *aData, PRUint32 aLength, nsIURI * aURI, PRUint32 aType, PRBool doSilentDonwload, const PRUnichar* crlKey) { nsNSSShutDownPreventionLock locker; nsresult rv; PRArenaPool *arena = NULL; CERTCertificate *caCert; SECItem derName = { siBuffer, NULL, 0 }; SECItem derCrl; CERTSignedData sd; SECStatus sec_rv; CERTSignedCrl *crl; nsCAutoString url; nsCOMPtr<nsICRLInfo> crlData; PRBool importSuccessful; PRInt32 errorCode; nsString errorMessage; nsCOMPtr<nsINSSComponent> nssComponent(do_GetService(kNSSComponentCID, &rv)); if (NS_FAILED(rv)) return rv; aURI->GetSpec(url); arena = PORT_NewArena(DER_DEFAULT_CHUNKSIZE); if (!arena) { goto loser; } memset(&sd, 0, sizeof(sd)); derCrl.data = (unsigned char*)aData; derCrl.len = aLength; sec_rv = CERT_KeyFromDERCrl(arena, &derCrl, &derName); if (sec_rv != SECSuccess) { goto loser; } caCert = CERT_FindCertByName(CERT_GetDefaultCertDB(), &derName); if (!caCert) { if (aType == SEC_KRL_TYPE) { goto loser; } } else { sec_rv = SEC_ASN1DecodeItem(arena, &sd, SEC_ASN1_GET(CERT_SignedDataTemplate), &derCrl); if (sec_rv != SECSuccess) { goto loser; } sec_rv = CERT_VerifySignedData(&sd, caCert, PR_Now(), nsnull); if (sec_rv != SECSuccess) { goto loser; } } crl = SEC_NewCrl(CERT_GetDefaultCertDB(), const_cast<char*>(url.get()), &derCrl, aType); if (!crl) { goto loser; } crlData = new nsCRLInfo(crl); SSL_ClearSessionCache(); SEC_DestroyCrl(crl); importSuccessful = PR_TRUE; goto done; loser: importSuccessful = PR_FALSE; errorCode = PR_GetError(); switch (errorCode) { case SEC_ERROR_CRL_EXPIRED: nssComponent->GetPIPNSSBundleString("CrlImportFailureExpired", errorMessage); break; case SEC_ERROR_CRL_BAD_SIGNATURE: nssComponent->GetPIPNSSBundleString("CrlImportFailureBadSignature", errorMessage); break; case SEC_ERROR_CRL_INVALID: nssComponent->GetPIPNSSBundleString("CrlImportFailureInvalid", errorMessage); break; case SEC_ERROR_OLD_CRL: nssComponent->GetPIPNSSBundleString("CrlImportFailureOld", errorMessage); break; case SEC_ERROR_CRL_NOT_YET_VALID: nssComponent->GetPIPNSSBundleString("CrlImportFailureNotYetValid", errorMessage); break; default: nssComponent->GetPIPNSSBundleString("CrlImportFailureReasonUnknown", errorMessage); errorMessage.AppendInt(errorCode,16); break; } done: if(!doSilentDonwload) { if (!importSuccessful) { nsString message; nsString temp; nsCOMPtr<nsIWindowWatcher> wwatch(do_GetService(NS_WINDOWWATCHER_CONTRACTID)); nsCOMPtr<nsIPrompt> prompter; if (wwatch) { wwatch->GetNewPrompter(0, getter_AddRefs(prompter)); nssComponent->GetPIPNSSBundleString("CrlImportFailure1x", message); message.Append(NS_LITERAL_STRING("\n").get()); message.Append(errorMessage); nssComponent->GetPIPNSSBundleString("CrlImportFailure2", temp); message.Append(NS_LITERAL_STRING("\n").get()); message.Append(temp); if(prompter) { nsPSMUITracker tracker; if (!tracker.isUIForbidden()) { prompter->Alert(0, message.get()); } } } } else { nsCOMPtr<nsICertificateDialogs> certDialogs; // Not being able to display the success dialog should not // be a fatal error, so don't return a failure code. { nsPSMUITracker tracker; if (tracker.isUIForbidden()) { rv = NS_ERROR_NOT_AVAILABLE; } else { rv = ::getNSSDialogs(getter_AddRefs(certDialogs), NS_GET_IID(nsICertificateDialogs), NS_CERTIFICATEDIALOGS_CONTRACTID); } } if (NS_SUCCEEDED(rv)) { nsCOMPtr<nsIInterfaceRequestor> cxt = new PipUIContext(); certDialogs->CrlImportStatusDialog(cxt, crlData); } } } else { if(crlKey == nsnull) { return NS_ERROR_FAILURE; } nsCOMPtr<nsIPrefService> prefSvc = do_GetService(NS_PREFSERVICE_CONTRACTID,&rv); nsCOMPtr<nsIPrefBranch> pref = do_GetService(NS_PREFSERVICE_CONTRACTID,&rv); if (NS_FAILED(rv)) { return rv; } nsCAutoString updateErrCntPrefStr(CRL_AUTOUPDATE_ERRCNT_PREF); updateErrCntPrefStr.AppendWithConversion(crlKey); if(importSuccessful) { PRUnichar *updateTime; nsCAutoString updateTimeStr; nsCString updateURL; PRInt32 timingTypePref; double dayCnt; char *dayCntStr; nsCAutoString updateTypePrefStr(CRL_AUTOUPDATE_TIMIINGTYPE_PREF); nsCAutoString updateTimePrefStr(CRL_AUTOUPDATE_TIME_PREF); nsCAutoString updateUrlPrefStr(CRL_AUTOUPDATE_URL_PREF); nsCAutoString updateDayCntPrefStr(CRL_AUTOUPDATE_DAYCNT_PREF); nsCAutoString updateFreqCntPrefStr(CRL_AUTOUPDATE_FREQCNT_PREF); updateTypePrefStr.AppendWithConversion(crlKey); updateTimePrefStr.AppendWithConversion(crlKey); updateUrlPrefStr.AppendWithConversion(crlKey); updateDayCntPrefStr.AppendWithConversion(crlKey); updateFreqCntPrefStr.AppendWithConversion(crlKey); pref->GetIntPref(updateTypePrefStr.get(),&timingTypePref); //Compute and update the next download instant if(timingTypePref == TYPE_AUTOUPDATE_TIME_BASED) { pref->GetCharPref(updateDayCntPrefStr.get(),&dayCntStr); } else { pref->GetCharPref(updateFreqCntPrefStr.get(),&dayCntStr); } dayCnt = atof(dayCntStr); nsMemory::Free(dayCntStr); PRBool toBeRescheduled = PR_FALSE; if(NS_SUCCEEDED(ComputeNextAutoUpdateTime(crlData, timingTypePref, dayCnt, &updateTime))) { updateTimeStr.AssignWithConversion(updateTime); nsMemory::Free(updateTime); pref->SetCharPref(updateTimePrefStr.get(),updateTimeStr.get()); //Now, check if this update time is already in the past. This would //imply we have downloaded the same crl, or there is something wrong //with the next update date. We will not reschedule this crl in this //session anymore - or else, we land into a loop. It would anyway be //imported once the browser is restarted. PRTime nextTime; PR_ParseTimeString(updateTimeStr.get(),PR_TRUE, &nextTime); if(LL_CMP(nextTime, > , PR_Now())) { toBeRescheduled = PR_TRUE; } } //Update the url to download from, next time crlData->GetLastFetchURL(updateURL); pref->SetCharPref(updateUrlPrefStr.get(),updateURL.get()); pref->SetIntPref(updateErrCntPrefStr.get(),0); if(toBeRescheduled == PR_TRUE) { nsAutoString hashKey(crlKey); nssComponent->RemoveCrlFromList(hashKey); nssComponent->DefineNextTimer(); } } else {
NS_METHOD NS_InitEmbedding(nsILocalFile *mozBinDirectory, nsIDirectoryServiceProvider *appFileLocProvider, nsStaticModuleInfo const *aStaticComponents, PRUint32 aStaticComponentCount) { nsresult rv; // Reentrant calls to this method do nothing except increment a counter sInitCounter++; if (sInitCounter > 1) return NS_OK; // Initialise XPCOM #ifdef HACK_AROUND_NONREENTRANT_INITXPCOM // Can't call NS_InitXPCom more than once or things go boom! if (!sXPCOMInitializedFlag) #endif { // Initialise XPCOM rv = NS_InitXPCOM3(&sServiceManager, mozBinDirectory, appFileLocProvider, aStaticComponents, aStaticComponentCount); NS_ENSURE_SUCCESS(rv, rv); #ifdef HACK_AROUND_NONREENTRANT_INITXPCOM sXPCOMInitializedFlag = PR_TRUE; sXPCOMCleanupHack.mCleanOnExit = PR_TRUE; #endif } // Register components if (!sRegistryInitializedFlag) { #ifdef DEBUG nsIComponentRegistrar *registrar; rv = sServiceManager->QueryInterface(NS_GET_IID(nsIComponentRegistrar), (void **) ®istrar); if (NS_FAILED(rv)) { NS_WARNING("Could not QI to registrar"); return rv; } rv = registrar->AutoRegister(nsnull); if (NS_FAILED(rv)) { NS_WARNING("Could not AutoRegister"); } else { // If the application is using an GRE, then, auto register components // in the GRE directory as well. // // The application indicates that it's using an GRE by returning a // valid nsIFile when queried (via appFileLocProvider) for the // NS_GRE_DIR atom as shown below if (appFileLocProvider) { nsIFile *greDir = nsnull; PRBool persistent = PR_TRUE; appFileLocProvider->GetFile(NS_GRE_DIR, &persistent, &greDir); if (greDir) { rv = registrar->AutoRegister(greDir); if (NS_FAILED(rv)) NS_WARNING("Could not AutoRegister GRE components"); NS_RELEASE(greDir); } } } NS_RELEASE(registrar); if (NS_FAILED(rv)) return rv; #endif sRegistryInitializedFlag = PR_TRUE; } nsIComponentManager *compMgr; rv = sServiceManager->QueryInterface(NS_GET_IID(nsIComponentManager), (void **) &compMgr); if (NS_FAILED(rv)) return rv; nsIObserver *startupNotifier; rv = compMgr->CreateInstanceByContractID(NS_APPSTARTUPNOTIFIER_CONTRACTID, NULL, NS_GET_IID(nsIObserver), (void **) &startupNotifier); NS_RELEASE(compMgr); if (NS_FAILED(rv)) return rv; startupNotifier->Observe(nsnull, APPSTARTUP_TOPIC, nsnull); NS_RELEASE(startupNotifier); #ifdef HACK_AROUND_THREADING_ISSUES // XXX force certain objects to be created on the main thread nsIStringBundleService *bundleService; rv = sServiceManager->GetServiceByContractID(NS_STRINGBUNDLE_CONTRACTID, NS_GET_IID(nsIStringBundleService), (void **) &bundleService); if (NS_SUCCEEDED(rv)) { nsIStringBundle *stringBundle; const char propertyURL[] = "chrome://necko/locale/necko.properties"; rv = bundleService->CreateBundle(propertyURL, &stringBundle); NS_RELEASE(stringBundle); NS_RELEASE(bundleService); } #endif return NS_OK; }
// static nsresult nsXPCWrappedJS::GetNewOrUsed(XPCCallContext& ccx, JSObject* aJSObj, REFNSIID aIID, nsISupports* aOuter, nsXPCWrappedJS** wrapperResult) { JSObject2WrappedJSMap* map; JSObject* rootJSObj; nsXPCWrappedJS* root = nsnull; nsXPCWrappedJS* wrapper = nsnull; nsXPCWrappedJSClass* clazz = nsnull; XPCJSRuntime* rt = ccx.GetRuntime(); JSBool release_root = false; map = rt->GetWrappedJSMap(); if (!map) { NS_ASSERTION(map,"bad map"); return NS_ERROR_FAILURE; } nsXPCWrappedJSClass::GetNewOrUsed(ccx, aIID, &clazz); if (!clazz) return NS_ERROR_FAILURE; // from here on we need to return through 'return_wrapper' // always find the root JSObject rootJSObj = clazz->GetRootJSObject(ccx, aJSObj); if (!rootJSObj) goto return_wrapper; // look for the root wrapper, and if found, hold the map lock until // we've added our ref to prevent another thread from destroying it // under us { // scoped lock XPCAutoLock lock(rt->GetMapLock()); root = map->Find(rootJSObj); if (root) { if ((nsnull != (wrapper = root->Find(aIID))) || (nsnull != (wrapper = root->FindInherited(aIID)))) { NS_ADDREF(wrapper); goto return_wrapper; } } } if (!root) { // build the root wrapper if (rootJSObj == aJSObj) { // the root will do double duty as the interface wrapper wrapper = root = new nsXPCWrappedJS(ccx, aJSObj, clazz, nsnull, aOuter); if (!root) goto return_wrapper; { // scoped lock #if DEBUG_xpc_leaks printf("Created nsXPCWrappedJS %p, JSObject is %p\n", (void*)wrapper, (void*)aJSObj); #endif XPCAutoLock lock(rt->GetMapLock()); map->Add(root); } if (!CheckMainThreadOnly(root)) { XPCAutoLock lock(rt->GetMapLock()); map->Remove(root); wrapper = NULL; } goto return_wrapper; } else { // just a root wrapper nsXPCWrappedJSClass* rootClazz = nsnull; nsXPCWrappedJSClass::GetNewOrUsed(ccx, NS_GET_IID(nsISupports), &rootClazz); if (!rootClazz) goto return_wrapper; root = new nsXPCWrappedJS(ccx, rootJSObj, rootClazz, nsnull, aOuter); NS_RELEASE(rootClazz); if (!root) goto return_wrapper; release_root = true; { // scoped lock #if DEBUG_xpc_leaks printf("Created nsXPCWrappedJS %p, JSObject is %p\n", (void*)root, (void*)rootJSObj); #endif XPCAutoLock lock(rt->GetMapLock()); map->Add(root); } if (!CheckMainThreadOnly(root)) { XPCAutoLock lock(rt->GetMapLock()); map->Remove(root); goto return_wrapper; } } } // at this point we have a root and may need to build the specific wrapper NS_ASSERTION(root,"bad root"); NS_ASSERTION(clazz,"bad clazz"); if (!wrapper) { wrapper = new nsXPCWrappedJS(ccx, aJSObj, clazz, root, aOuter); if (!wrapper) goto return_wrapper; #if DEBUG_xpc_leaks printf("Created nsXPCWrappedJS %p, JSObject is %p\n", (void*)wrapper, (void*)aJSObj); #endif } wrapper->mNext = root->mNext; root->mNext = wrapper; return_wrapper: if (clazz) NS_RELEASE(clazz); if (release_root) NS_RELEASE(root); if (!wrapper) return NS_ERROR_FAILURE; *wrapperResult = wrapper; return NS_OK; }
NS_IMETHODIMP TransportSecurityInfo::Write(nsIObjectOutputStream* stream) { nsresult rv = stream->WriteID(kTransportSecurityInfoMagic); if (NS_FAILED(rv)) { return rv; } MutexAutoLock lock(mMutex); rv = stream->Write32(mSecurityState); if (NS_FAILED(rv)) { return rv; } rv = stream->Write32(mSubRequestsBrokenSecurity); if (NS_FAILED(rv)) { return rv; } rv = stream->Write32(mSubRequestsNoSecurity); if (NS_FAILED(rv)) { return rv; } rv = stream->Write32(static_cast<uint32_t>(mErrorCode)); if (NS_FAILED(rv)) { return rv; } if (mErrorMessageCached.IsEmpty()) { // XXX: uses nsNSSComponent string bundles off the main thread rv = formatErrorMessage(lock, mErrorCode, mErrorMessageType, true, true, mErrorMessageCached); if (NS_FAILED(rv)) { return rv; } } rv = stream->WriteWStringZ(mErrorMessageCached.get()); if (NS_FAILED(rv)) { return rv; } // For successful connections and for connections with overridable errors, // mSSLStatus will be non-null. However, for connections with non-overridable // errors, it will be null. nsCOMPtr<nsISerializable> serializable(mSSLStatus); rv = NS_WriteOptionalCompoundObject(stream, serializable, NS_GET_IID(nsISSLStatus), true); if (NS_FAILED(rv)) { return rv; } rv = NS_WriteOptionalCompoundObject(stream, mFailedCertChain, NS_GET_IID(nsIX509CertList), true); if (NS_FAILED(rv)) { return rv; } return NS_OK; }
//------------------------------------------------------------------------ // XPI_Init() //------------------------------------------------------------------------ PR_PUBLIC_API(nsresult) XPI_Init( const char* aProgramDir, const char* aLogName, pfnXPIProgress progressCB ) { nsresult rv; //-------------------------------------------------------------------- // Initialize XPCOM and AutoRegister() its components //-------------------------------------------------------------------- #if defined(XP_WIN) || defined(XP_OS2) #ifdef XP_OS2_EMX char componentPath[MAX_PATH]; _getcwd2(componentPath, MAX_PATH); int len = strlen(componentPath); for (int i = 0; i < len; i++) { if (componentPath[i] == '/') { componentPath[i] = '\\'; } } #else char componentPath[MAX_PATH]; getcwd(componentPath, MAX_PATH); #endif nsCOMPtr<nsILocalFile> file; rv = NS_NewNativeLocalFile(nsDependentCString(componentPath), PR_TRUE, getter_AddRefs(file)); if (NS_FAILED(rv)) return rv; rv = NS_InitXPCOM2(&gServiceMgr, file, nsnull); #elif defined(XP_UNIX) rv = NS_InitXPCOM2(&gServiceMgr, nsnull, nsnull); char cwd[1024]; char compDirPath[1024]; memset(cwd, 0, 1024); memset(compDirPath, 0, 1024); getcwd(cwd, 1024); sprintf(compDirPath, "%s/components", cwd); nsCOMPtr<nsILocalFile> compDir; NS_NewNativeLocalFile(nsDependentCString(compDirPath), PR_TRUE, getter_AddRefs(compDir)); #else rv = NS_InitXPCOM2(&gServiceMgr, NULL, NULL); #endif if (NS_FAILED(rv)) return rv; nsCOMPtr<nsIComponentRegistrar> registrar = do_QueryInterface(gServiceMgr); NS_ASSERTION(registrar, "Null nsIComponentRegistrar"); #if defined(XP_UNIX) rv = registrar->AutoRegister(compDir); #else rv = registrar->AutoRegister(nsnull); #endif if (NS_FAILED(rv)) return rv; //-------------------------------------------------------------------- // Get the SoftwareUpdate (XPInstall) service. // // Since AppShell is not started by XPIStub the XPI service is never // registered with the service manager. We keep a local pointer to it // so it stays alive througout. //-------------------------------------------------------------------- rv = CallCreateInstance(kSoftwareUpdateCID, &gXPI); if (NS_FAILED(rv)) return rv; //-------------------------------------------------------------------- // Override XPInstall's natural assumption that the current executable // is Mozilla. Use the given directory as the "Program" folder. //-------------------------------------------------------------------- nsCOMPtr<nsPIXPIStubHook> hook = do_QueryInterface(gXPI); nsCOMPtr<nsILocalFile> iDirSpec; if (aProgramDir) { NS_NewNativeLocalFile(nsDependentCString(aProgramDir), PR_TRUE, getter_AddRefs(iDirSpec)); } else { nsCOMPtr<nsIProperties> directoryService = do_GetService(NS_DIRECTORY_SERVICE_CONTRACTID, &rv); directoryService->Get(NS_XPCOM_CURRENT_PROCESS_DIR, NS_GET_IID(nsILocalFile), getter_AddRefs(iDirSpec)); } if (hook && iDirSpec) { rv = hook->StubInitialize( iDirSpec, aLogName ); if (NS_FAILED(rv)) return rv; } else return NS_ERROR_NULL_POINTER; //-------------------------------------------------------------------- // Save the install wizard's callbacks as a nsIXPINotifer for later //-------------------------------------------------------------------- nsStubListener* stub = new nsStubListener( progressCB ); if (!stub) { gXPI->Release(); rv = NS_ERROR_OUT_OF_MEMORY; } else { rv = stub->QueryInterface(NS_GET_IID(nsIXPIListener), (void**)&gListener); } return rv; }
nsresult NS_GetMemoryManager(nsIMemory* *result) { return sGlobalMemory.QueryInterface(NS_GET_IID(nsIMemory), (void**) result); }
NS_IMETHODIMP nsImportService::CreateNewABDescriptor(nsIImportABDescriptor **_retval) { return nsImportABDescriptor::Create(nsnull, NS_GET_IID(nsIImportABDescriptor), (void**)_retval); }
NS_IMETHODIMP nsImportService::CreateNewFieldMap(nsIImportFieldMap **_retval) { return nsImportFieldMap::Create(m_stringBundle, nsnull, NS_GET_IID(nsIImportFieldMap), (void**)_retval); }
NS_IMETHODIMP nsXPInstallManager::OpenProgressDialog(const PRUnichar **aPackageList, PRUint32 aCount, nsIObserver *aObserver) { // --- convert parameters into nsISupportArray members nsCOMPtr<nsIDialogParamBlock> list; nsresult rv = LoadParams( aCount, aPackageList, getter_AddRefs(list) ); if (NS_FAILED(rv)) return rv; nsCOMPtr<nsISupportsInterfacePointer> listwrap(do_CreateInstance(NS_SUPPORTS_INTERFACE_POINTER_CONTRACTID)); if (listwrap) { listwrap->SetData(list); listwrap->SetDataIID(&NS_GET_IID(nsIDialogParamBlock)); } nsCOMPtr<nsISupportsInterfacePointer> callbackwrap(do_CreateInstance(NS_SUPPORTS_INTERFACE_POINTER_CONTRACTID)); if (callbackwrap) { callbackwrap->SetData(aObserver); callbackwrap->SetDataIID(&NS_GET_IID(nsIObserver)); } nsCOMPtr<nsISupportsArray> params(do_CreateInstance(NS_SUPPORTSARRAY_CONTRACTID)); if ( !params || !listwrap || !callbackwrap ) return NS_ERROR_FAILURE; params->AppendElement(listwrap); params->AppendElement(callbackwrap); // --- open the window nsCOMPtr<nsIWindowWatcher> wwatch(do_GetService(NS_WINDOWWATCHER_CONTRACTID, &rv)); if (!wwatch) return rv; char *statusDialogURL, *statusDialogType; nsCOMPtr<nsIPrefBranch> pref(do_GetService(NS_PREFSERVICE_CONTRACTID, &rv)); if (!pref) return rv; const char* statusDlg = mChromeType == CHROME_SKIN ? PREF_XPINSTALL_STATUS_DLG_SKIN : PREF_XPINSTALL_STATUS_DLG_CHROME; rv = pref->GetCharPref(statusDlg, &statusDialogURL); NS_ASSERTION(NS_SUCCEEDED(rv), "Can't invoke XPInstall FE without a FE URL! Set xpinstall.dialog.status"); if (NS_FAILED(rv)) return rv; const char* statusType = mChromeType == CHROME_SKIN ? PREF_XPINSTALL_STATUS_DLG_TYPE_SKIN : PREF_XPINSTALL_STATUS_DLG_TYPE_CHROME; rv = pref->GetCharPref(statusType, &statusDialogType); nsAutoString type; type.AssignWithConversion(statusDialogType); if (NS_SUCCEEDED(rv) && !type.IsEmpty()) { nsCOMPtr<nsIWindowMediator> wm = do_GetService(NS_WINDOWMEDIATOR_CONTRACTID); nsCOMPtr<nsIDOMWindowInternal> recentWindow; wm->GetMostRecentWindow(type.get(), getter_AddRefs(recentWindow)); if (recentWindow) { nsCOMPtr<nsIObserverService> os(do_GetService("@mozilla.org/observer-service;1")); os->NotifyObservers(params, "xpinstall-download-started", nsnull); recentWindow->Focus(); return NS_OK; } } nsCOMPtr<nsIDOMWindow> newWindow; rv = wwatch->OpenWindow(0, statusDialogURL, "_blank", "chrome,centerscreen,titlebar,dialog=no,resizable", params, getter_AddRefs(newWindow)); return rv; }
nsresult nsAbPalmHotSync::Done(PRBool aSuccess, PRInt32 aPalmCatIndex, PRUint32 aPalmRecIDListCount, unsigned long * aPalmRecordIDList) { if(!mInitialized) return NS_ERROR_NOT_INITIALIZED; nsresult rv=NS_ERROR_UNEXPECTED; if(aPalmRecIDListCount == mNewCardCount) { for(PRUint32 i=0; i<aPalmRecIDListCount; i++) { nsCOMPtr<nsIAbMDBCard> dbCard; rv = mNewCardsArray->QueryElementAt(i, NS_GET_IID(nsIAbMDBCard), getter_AddRefs(dbCard)); if(NS_SUCCEEDED(rv) && dbCard) { ConvertAssignPalmIDAttrib(aPalmRecordIDList[i], dbCard); nsCOMPtr<nsIAbCard> newCard; newCard = do_QueryInterface(dbCard, &rv); if(NS_SUCCEEDED(rv)) mABDB->EditCard(newCard, PR_FALSE, nsnull); } } } if(mABDB && mDBOpen) { if(aSuccess) { rv = mABDB->Close(PR_TRUE); if(NS_SUCCEEDED(rv)) { mDBOpen = PR_FALSE; PRUint32 modTimeInSec; PRTime2Seconds(PR_Now(), &modTimeInSec); rv = UpdateABInfo(modTimeInSec, aPalmCatIndex); } } if(NS_FAILED(rv) || !aSuccess) { // get back the previous file rv = mABDB->ForceClosed(); if(NS_SUCCEEDED(rv)) { nsCAutoString leafName; mABFile->GetNativeLeafName(leafName); PRBool bExists=PR_FALSE; mPreviousABFile->Exists(&bExists); if(bExists) { nsCOMPtr<nsIFile> parent; rv = mABFile->GetParent(getter_AddRefs(parent)); if (NS_SUCCEEDED(rv)) { mABFile->Remove(PR_FALSE); mPreviousABFile->CopyToNative(parent, leafName); } } mDBOpen = PR_FALSE; } } } return rv; }
NS_IMETHODIMP nsDefaultURIFixup::KeywordToURI(const nsACString& aKeyword, nsIURI **aURI) { *aURI = nsnull; NS_ENSURE_STATE(mPrefBranch); nsXPIDLCString url; nsCOMPtr<nsIPrefLocalizedString> keywordURL; mPrefBranch->GetComplexValue("keyword.URL", NS_GET_IID(nsIPrefLocalizedString), getter_AddRefs(keywordURL)); if (keywordURL) { nsXPIDLString wurl; keywordURL->GetData(getter_Copies(wurl)); CopyUTF16toUTF8(wurl, url); } else { // Fall back to a non-localized pref, for backwards compat mPrefBranch->GetCharPref("keyword.URL", getter_Copies(url)); } // If the pref is set and non-empty, use it. if (!url.IsEmpty()) { nsCAutoString spec; nsresult rv = MangleKeywordIntoURI(PromiseFlatCString(aKeyword).get(), url.get(), spec); if (NS_FAILED(rv)) return rv; return NS_NewURI(aURI, spec); } // Try falling back to the search service's default search engine nsCOMPtr<nsIBrowserSearchService> searchSvc = do_GetService("@mozilla.org/browser/search-service;1"); if (searchSvc) { nsCOMPtr<nsISearchEngine> defaultEngine; searchSvc->GetOriginalDefaultEngine(getter_AddRefs(defaultEngine)); if (defaultEngine) { nsCOMPtr<nsISearchSubmission> submission; // We want to allow default search plugins to specify alternate // parameters that are specific to keyword searches. For the moment, // do this by first looking for a magic // "application/x-moz-keywordsearch" submission type. In the future, // we should instead use a solution that relies on bug 587780. defaultEngine->GetSubmission(NS_ConvertUTF8toUTF16(aKeyword), NS_LITERAL_STRING("application/x-moz-keywordsearch"), getter_AddRefs(submission)); // If getting the special x-moz-keywordsearch submission type failed, // fall back to the default response type. if (!submission) { defaultEngine->GetSubmission(NS_ConvertUTF8toUTF16(aKeyword), EmptyString(), getter_AddRefs(submission)); } if (submission) { // The submission depends on POST data (i.e. the search engine's // "method" is POST), we can't use this engine for keyword // searches nsCOMPtr<nsIInputStream> postData; submission->GetPostData(getter_AddRefs(postData)); if (postData) { return NS_ERROR_NOT_AVAILABLE; } return submission->GetUri(aURI); } } } // out of options return NS_ERROR_NOT_AVAILABLE; }
static int MimeInlineText_initializeCharset(MimeObject *obj) { MimeInlineText *text = (MimeInlineText *) obj; text->inputAutodetect = PR_FALSE; text->charsetOverridable = PR_FALSE; /* Figure out an appropriate charset for this object. */ if (!text->charset && obj->headers) { if (obj->options && obj->options->override_charset) { text->charset = strdup(obj->options->default_charset); } else { char *ct = MimeHeaders_get (obj->headers, HEADER_CONTENT_TYPE, PR_FALSE, PR_FALSE); if (ct) { text->charset = MimeHeaders_get_parameter (ct, "charset", NULL, NULL); PR_Free(ct); } if (!text->charset) { /* If we didn't find "Content-Type: ...; charset=XX" then look for "X-Sun-Charset: XX" instead. (Maybe this should be done in MimeSunAttachmentClass, but it's harder there than here.) */ text->charset = MimeHeaders_get (obj->headers, HEADER_X_SUN_CHARSET, PR_FALSE, PR_FALSE); } /* iMIP entities without an explicit charset parameter default to US-ASCII (RFC 2447, section 2.4). However, Microsoft Outlook generates UTF-8 but omits the charset parameter. When no charset is defined by the container (e.g. iMIP), iCalendar files default to UTF-8 (RFC 2445, section 4.1.4). */ if (!text->charset && obj->content_type && !PL_strcasecmp(obj->content_type, TEXT_CALENDAR)) text->charset = strdup("UTF-8"); if (!text->charset) { nsresult res; text->charsetOverridable = PR_TRUE; nsCOMPtr<nsIPrefBranch> prefBranch(do_GetService(NS_PREFSERVICE_CONTRACTID, &res)); if (NS_SUCCEEDED(res)) { nsCOMPtr<nsIPrefLocalizedString> str; if (NS_SUCCEEDED(prefBranch->GetComplexValue("intl.charset.detector", NS_GET_IID(nsIPrefLocalizedString), getter_AddRefs(str)))) { //only if we can get autodetector name correctly, do we set this to true text->inputAutodetect = PR_TRUE; } } if (obj->options && obj->options->default_charset) text->charset = strdup(obj->options->default_charset); else { if (NS_SUCCEEDED(res)) { nsString value; NS_GetLocalizedUnicharPreferenceWithDefault(prefBranch, "mailnews.view_default_charset", EmptyString(), value); text->charset = ToNewUTF8String(value); } else text->charset = strdup(""); } } } } if (text->inputAutodetect) { //we need to prepare lineDam for charset detection text->lineDamBuffer = (char*)PR_Malloc(DAM_MAX_BUFFER_SIZE); text->lineDamPtrs = (char**)PR_Malloc(DAM_MAX_LINES*sizeof(char*)); text->curDamOffset = 0; text->lastLineInDam = 0; if (!text->lineDamBuffer || !text->lineDamPtrs) { text->inputAutodetect = PR_FALSE; PR_FREEIF(text->lineDamBuffer); PR_FREEIF(text->lineDamPtrs); } } text->initializeCharset = PR_TRUE; return 0; }
nsresult nsMsgMdnGenerator::InitAndProcess() { DEBUG_MDN("nsMsgMdnGenerator::InitAndProcess"); nsresult rv = m_folder->GetServer(getter_AddRefs(m_server)); nsCOMPtr<nsIMsgAccountManager> accountManager = do_GetService(NS_MSGACCOUNTMANAGER_CONTRACTID, &rv); if (accountManager && m_server) { if (!m_identity) { // check if this is a message delivered to the global inbox, // in which case we find the originating account's identity. nsCString accountKey; m_headers->ExtractHeader(HEADER_X_MOZILLA_ACCOUNT_KEY, PR_FALSE, getter_Copies(accountKey)); nsCOMPtr <nsIMsgAccount> account; if (!accountKey.IsEmpty()) accountManager->GetAccount(accountKey, getter_AddRefs(account)); if (account) account->GetIncomingServer(getter_AddRefs(m_server)); if (m_server) { // Find the correct identity based on the "To:" and "Cc:" header nsCString mailTo; nsCString mailCC; m_headers->ExtractHeader(HEADER_TO, PR_TRUE, getter_Copies(mailTo)); m_headers->ExtractHeader(HEADER_CC, PR_TRUE, getter_Copies(mailCC)); nsCOMPtr<nsISupportsArray> servIdentities; accountManager->GetIdentitiesForServer(m_server, getter_AddRefs(servIdentities)); if (servIdentities) { nsCOMPtr<nsIMsgIdentity> ident; nsCString identEmail; PRUint32 count = 0; servIdentities->Count(&count); // First check in the "To:" header for (PRUint32 i = 0; i < count; i++) { rv = servIdentities->QueryElementAt(i, NS_GET_IID(nsIMsgIdentity),getter_AddRefs(ident)); if (NS_FAILED(rv)) continue; ident->GetEmail(identEmail); if (!mailTo.IsEmpty() && !identEmail.IsEmpty() && mailTo.Find(identEmail, PR_TRUE) != -1) { m_identity = ident; break; } } // If no match, check the "Cc:" header if (!m_identity) { for (PRUint32 i = 0; i < count; i++) { rv = servIdentities->QueryElementAt(i, NS_GET_IID(nsIMsgIdentity),getter_AddRefs(ident)); if (NS_FAILED(rv)) continue; ident->GetEmail(identEmail); if (!mailCC.IsEmpty() && !identEmail.IsEmpty() && mailCC.Find(identEmail, PR_TRUE) != -1) { m_identity = ident; break; } } } } // If no match again, use the first identity if (!m_identity) rv = accountManager->GetFirstIdentityForServer(m_server, getter_AddRefs(m_identity)); } } NS_ENSURE_SUCCESS(rv,rv); if (m_identity) { PRBool useCustomPrefs = PR_FALSE; m_identity->GetBoolAttribute("use_custom_prefs", &useCustomPrefs); if (useCustomPrefs) { PRBool bVal = PR_FALSE; m_server->GetBoolValue("mdn_report_enabled", &bVal); m_mdnEnabled = bVal; m_server->GetIntValue("mdn_not_in_to_cc", &m_notInToCcOp); m_server->GetIntValue("mdn_outside_domain", &m_outsideDomainOp); m_server->GetIntValue("mdn_other", &m_otherOp); } else { PRBool bVal = PR_FALSE; nsCOMPtr<nsIPrefBranch> prefBranch(do_GetService(NS_PREFSERVICE_CONTRACTID, &rv)); if (NS_FAILED(rv)) return rv; if(prefBranch) { prefBranch->GetBoolPref("mail.mdn.report.enabled", &bVal); m_mdnEnabled = bVal; prefBranch->GetIntPref("mail.mdn.report.not_in_to_cc", &m_notInToCcOp); prefBranch->GetIntPref("mail.mdn.report.outside_domain", &m_outsideDomainOp); prefBranch->GetIntPref("mail.mdn.report.other", &m_otherOp); } } } } rv = m_folder->GetCharset(m_charset); if (m_mdnEnabled) { m_headers->ExtractHeader(HEADER_DISPOSITION_NOTIFICATION_TO, PR_FALSE, getter_Copies(m_dntRrt)); if (m_dntRrt.IsEmpty()) m_headers->ExtractHeader(HEADER_RETURN_RECEIPT_TO, PR_FALSE, getter_Copies(m_dntRrt)); if (!m_dntRrt.IsEmpty() && ProcessSendMode() && ValidateReturnPath()) rv = CreateMdnMsg(); } return NS_OK; }
void mozHunspell::LoadDictionaryList() { mDictionaries.Clear(); nsresult rv; nsCOMPtr<nsIProperties> dirSvc = do_GetService(NS_DIRECTORY_SERVICE_CONTRACTID); if (!dirSvc) return; // find built in dictionaries nsCOMPtr<nsIFile> dictDir; rv = dirSvc->Get(DICTIONARY_SEARCH_DIRECTORY, NS_GET_IID(nsIFile), getter_AddRefs(dictDir)); if (NS_SUCCEEDED(rv)) { LoadDictionariesFromDir(dictDir); } else { // try to load gredir/dictionaries nsCOMPtr<nsIFile> greDir; rv = dirSvc->Get(NS_GRE_DIR, NS_GET_IID(nsIFile), getter_AddRefs(greDir)); if (NS_SUCCEEDED(rv)) { greDir->AppendNative(NS_LITERAL_CSTRING("dictionaries")); LoadDictionariesFromDir(greDir); } // try to load appdir/dictionaries only if different than gredir nsCOMPtr<nsIFile> appDir; rv = dirSvc->Get(NS_XPCOM_CURRENT_PROCESS_DIR, NS_GET_IID(nsIFile), getter_AddRefs(appDir)); bool equals; if (NS_SUCCEEDED(rv) && NS_SUCCEEDED(appDir->Equals(greDir, &equals)) && !equals) { appDir->AppendNative(NS_LITERAL_CSTRING("dictionaries")); LoadDictionariesFromDir(appDir); } } // find dictionaries from extensions requiring restart nsCOMPtr<nsISimpleEnumerator> dictDirs; rv = dirSvc->Get(DICTIONARY_SEARCH_DIRECTORY_LIST, NS_GET_IID(nsISimpleEnumerator), getter_AddRefs(dictDirs)); if (NS_FAILED(rv)) return; bool hasMore; while (NS_SUCCEEDED(dictDirs->HasMoreElements(&hasMore)) && hasMore) { nsCOMPtr<nsISupports> elem; dictDirs->GetNext(getter_AddRefs(elem)); dictDir = do_QueryInterface(elem); if (dictDir) LoadDictionariesFromDir(dictDir); } // find dictionaries from restartless extensions for (int32_t i = 0; i < mDynamicDirectories.Count(); i++) { LoadDictionariesFromDir(mDynamicDirectories[i]); } // Now we have finished updating the list of dictionaries, update the current // dictionary and any editors which may use it. mozInlineSpellChecker::UpdateCanEnableInlineSpellChecking(); // Check if the current dictionary is still available. // If not, try to replace it with another dictionary of the same language. if (!mDictionary.IsEmpty()) { rv = SetDictionary(mDictionary.get()); if (NS_SUCCEEDED(rv)) return; } // If the current dictionary has gone, and we don't have a good replacement, // set no current dictionary. if (!mDictionary.IsEmpty()) { SetDictionary(EmptyString().get()); } }
NS_IMETHODIMP nsPrintProgress::OpenProgressDialog(mozIDOMWindowProxy *parent, const char *dialogURL, nsISupports *parameters, nsIObserver *openDialogObserver, bool *notifyOnOpen) { *notifyOnOpen = true; m_observer = openDialogObserver; nsresult rv = NS_ERROR_FAILURE; if (m_dialog) return NS_ERROR_ALREADY_INITIALIZED; if (!dialogURL || !*dialogURL) return NS_ERROR_INVALID_ARG; if (parent) { // Set up window.arguments[0]... nsCOMPtr<nsISupportsArray> array; rv = NS_NewISupportsArray(getter_AddRefs(array)); NS_ENSURE_SUCCESS(rv, rv); nsCOMPtr<nsISupportsInterfacePointer> ifptr = do_CreateInstance(NS_SUPPORTS_INTERFACE_POINTER_CONTRACTID, &rv); NS_ENSURE_SUCCESS(rv, rv); ifptr->SetData(static_cast<nsIPrintProgress*>(this)); ifptr->SetDataIID(&NS_GET_IID(nsIPrintProgress)); array->AppendElement(ifptr); array->AppendElement(parameters); // We will set the opener of the dialog to be the nsIDOMWindow for the // browser XUL window itself, as opposed to the content. That way, the // progress window has access to the opener. nsCOMPtr<nsPIDOMWindowOuter> pParentWindow = nsPIDOMWindowOuter::From(parent); NS_ENSURE_STATE(pParentWindow); nsCOMPtr<nsIDocShell> docShell = pParentWindow->GetDocShell(); NS_ENSURE_STATE(docShell); nsCOMPtr<nsIDocShellTreeOwner> owner; docShell->GetTreeOwner(getter_AddRefs(owner)); nsCOMPtr<nsIXULWindow> ownerXULWindow = do_GetInterface(owner); nsCOMPtr<mozIDOMWindowProxy> ownerWindow = do_GetInterface(ownerXULWindow); NS_ENSURE_STATE(ownerWindow); nsCOMPtr<nsPIDOMWindowOuter> piOwnerWindow = nsPIDOMWindowOuter::From(ownerWindow); // Open the dialog. nsCOMPtr<nsPIDOMWindowOuter> newWindow; rv = piOwnerWindow->OpenDialog(NS_ConvertASCIItoUTF16(dialogURL), NS_LITERAL_STRING("_blank"), NS_LITERAL_STRING("chrome,titlebar,dependent,centerscreen"), array, getter_AddRefs(newWindow)); } return rv; }
NS_IMETHODIMP nsAppFileLocationProvider::GetFile(const char *prop, PRBool *persistent, nsIFile **_retval) { nsCOMPtr<nsILocalFile> localFile; nsresult rv = NS_ERROR_FAILURE; NS_ENSURE_ARG(prop); *_retval = nsnull; *persistent = PR_TRUE; #ifdef XP_MACOSX 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), PR_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 XP_MACOSX else if (nsCRT::strcmp(prop, NS_MACOSX_USER_PLUGIN_DIR) == 0) { if (::FSFindFolder(kUserDomain, kInternetPlugInFolderType, false, &fileRef) == noErr) { rv = NS_NewLocalFileWithFSRef(&fileRef, PR_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, PR_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/Frameworks/JavaVM.framework/Versions/Current/Resources/"; NS_NewNativeLocalFile(nsDependentCString(java2PluginDirPath), PR_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), PR_TRUE, getter_AddRefs(localFile)); } else if (nsCRT::strcmp(prop, NS_USER_PLUGINS_DIR) == 0) { rv = GetProductDirectory(getter_AddRefs(localFile)); if (NS_SUCCEEDED(rv)) rv = localFile->AppendRelativeNativePath(PLUGINS_DIR_NAME); } #ifdef XP_UNIX else if (nsCRT::strcmp(prop, NS_SYSTEM_PLUGINS_DIR) == 0) { static const char *const sysLPlgDir = #if defined(HAVE_USR_LIB64_DIR) && defined(__LP64__) "/usr/lib64/mozilla/plugins"; #else "/usr/lib/mozilla/plugins"; #endif rv = NS_NewNativeLocalFile(nsDependentCString(sysLPlgDir), PR_FALSE, getter_AddRefs(localFile)); } #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; }
/** * Create a sample VM * * @param virtualBox VirtualBox instance object. */ void createVM(IVirtualBox *virtualBox) { nsresult rc; /* * First create a unnamed new VM. It will be unconfigured and not be saved * in the configuration until we explicitely choose to do so. */ nsCOMPtr<IMachine> machine; rc = virtualBox->CreateMachine(NULL, /* settings file */ NS_LITERAL_STRING("A brand new name").get(), 0, nsnull, /* groups (safearray)*/ nsnull, /* ostype */ nsnull, /* create flags */ getter_AddRefs(machine)); if (NS_FAILED(rc)) { printf("Error: could not create machine! rc=%08X\n", rc); return; } /* * Set some properties */ /* alternative to illustrate the use of string classes */ rc = machine->SetName(NS_ConvertUTF8toUTF16("A new name").get()); rc = machine->SetMemorySize(128); /* * Now a more advanced property -- the guest OS type. This is * an object by itself which has to be found first. Note that we * use the ID of the guest OS type here which is an internal * representation (you can find that by configuring the OS type of * a machine in the GUI and then looking at the <Guest ostype=""/> * setting in the XML file. It is also possible to get the OS type from * its description (win2k would be "Windows 2000") by getting the * guest OS type collection and enumerating it. */ nsCOMPtr<IGuestOSType> osType; rc = virtualBox->GetGuestOSType(NS_LITERAL_STRING("win2k").get(), getter_AddRefs(osType)); if (NS_FAILED(rc)) { printf("Error: could not find guest OS type! rc=%08X\n", rc); } else { machine->SetOSTypeId (NS_LITERAL_STRING("win2k").get()); } /* * Register the VM. Note that this call also saves the VM config * to disk. It is also possible to save the VM settings but not * register the VM. * * Also note that due to current VirtualBox limitations, the machine * must be registered *before* we can attach hard disks to it. */ rc = virtualBox->RegisterMachine(machine); if (NS_FAILED(rc)) { printf("Error: could not register machine! rc=%08X\n", rc); printErrorInfo(); return; } /* * In order to manipulate the registered machine, we must open a session * for that machine. Do it now. */ nsCOMPtr<ISession> session; { nsCOMPtr<nsIComponentManager> manager; rc = NS_GetComponentManager (getter_AddRefs (manager)); if (NS_FAILED(rc)) { printf("Error: could not get component manager! rc=%08X\n", rc); return; } rc = manager->CreateInstanceByContractID (NS_SESSION_CONTRACTID, nsnull, NS_GET_IID(ISession), getter_AddRefs(session)); if (NS_FAILED(rc)) { printf("Error, could not instantiate session object! rc=0x%x\n", rc); return; } rc = machine->LockMachine(session, LockType_Write); if (NS_FAILED(rc)) { printf("Error, could not lock the machine for the session! rc=0x%x\n", rc); return; } /* * After the machine is registered, the initial machine object becomes * immutable. In order to get a mutable machine object, we must query * it from the opened session object. */ rc = session->GetMachine(getter_AddRefs(machine)); if (NS_FAILED(rc)) { printf("Error, could not get machine session! rc=0x%x\n", rc); return; } } /* * Create a virtual harddisk */ nsCOMPtr<IMedium> hardDisk = 0; rc = virtualBox->CreateHardDisk(NS_LITERAL_STRING("VDI").get(), NS_LITERAL_STRING("TestHardDisk.vdi").get(), getter_AddRefs(hardDisk)); if (NS_FAILED(rc)) { printf("Failed creating a hard disk object! rc=%08X\n", rc); } else { /* * We have only created an object so far. No on disk representation exists * because none of its properties has been set so far. Let's continue creating * a dynamically expanding image. */ nsCOMPtr <IProgress> progress; com::SafeArray<MediumVariant_T> mediumVariant(sizeof(MediumVariant_T)*8); mediumVariant.push_back(MediumVariant_Standard); rc = hardDisk->CreateBaseStorage(100, // size in megabytes ComSafeArrayAsInParam(mediumVariant), getter_AddRefs(progress)); // optional progress object if (NS_FAILED(rc)) { printf("Failed creating hard disk image! rc=%08X\n", rc); } else { /* * Creating the image is done in the background because it can take quite * some time (at least fixed size images). We have to wait for its completion. * Here we wait forever (timeout -1) which is potentially dangerous. */ rc = progress->WaitForCompletion(-1); PRInt32 resultCode; progress->GetResultCode(&resultCode); if (NS_FAILED(rc) || NS_FAILED(resultCode)) { printf("Error: could not create hard disk! rc=%08X\n", NS_FAILED(rc) ? rc : resultCode); } else { /* * Now that it's created, we can assign it to the VM. */ rc = machine->AttachDevice(NS_LITERAL_STRING("IDE Controller").get(), // controller identifier 0, // channel number on the controller 0, // device number on the controller DeviceType_HardDisk, hardDisk); if (NS_FAILED(rc)) { printf("Error: could not attach hard disk! rc=%08X\n", rc); } } } } /* * It's got a hard disk but that one is new and thus not bootable. Make it * boot from an ISO file. This requires some processing. First the ISO file * has to be registered and then mounted to the VM's DVD drive and selected * as the boot device. */ nsCOMPtr<IMedium> dvdImage; rc = virtualBox->OpenMedium(NS_LITERAL_STRING("/home/vbox/isos/winnt4ger.iso").get(), DeviceType_DVD, AccessMode_ReadOnly, false /* fForceNewUuid */, getter_AddRefs(dvdImage)); if (NS_FAILED(rc)) printf("Error: could not open CD image! rc=%08X\n", rc); else { /* * Now assign it to our VM */ rc = machine->MountMedium(NS_LITERAL_STRING("IDE Controller").get(), // controller identifier 2, // channel number on the controller 0, // device number on the controller dvdImage, PR_FALSE); // aForce if (NS_FAILED(rc)) { printf("Error: could not mount ISO image! rc=%08X\n", rc); } else { /* * Last step: tell the VM to boot from the CD. */ rc = machine->SetBootOrder (1, DeviceType::DVD); if (NS_FAILED(rc)) { printf("Could not set boot device! rc=%08X\n", rc); } } } /* * Save all changes we've just made. */ rc = machine->SaveSettings(); if (NS_FAILED(rc)) { printf("Could not save machine settings! rc=%08X\n", rc); } /* * It is always important to close the open session when it becomes not * necessary any more. */ session->UnlockMachine(); }
//---------------------------------------------------------------------------------------- // 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; }
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(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; }
NS_IMETHODIMP ImportAddressImpl::FindAddressBooks(nsIFileSpec *pLoc, nsISupportsArray **ppArray) { NS_PRECONDITION(pLoc != nsnull, "null ptr"); NS_PRECONDITION(ppArray != nsnull, "null ptr"); if (!pLoc || !ppArray) return NS_ERROR_NULL_POINTER; ClearSampleFile(); *ppArray = nsnull; PRBool exists = PR_FALSE; nsresult rv = pLoc->Exists( &exists); if (NS_FAILED( rv) || !exists) return( NS_ERROR_FAILURE); PRBool isFile = PR_FALSE; rv = pLoc->IsFile( &isFile); if (NS_FAILED( rv) || !isFile) return( NS_ERROR_FAILURE); rv = m_text.DetermineDelim( pLoc); if (NS_FAILED( rv)) { IMPORT_LOG0( "*** Error determining delimitter\n"); return( rv); } m_haveDelim = PR_TRUE; m_delim = m_text.GetDelim(); m_fileLoc = pLoc; NS_ADDREF( m_fileLoc); /* Build an address book descriptor based on the file passed in! */ nsCOMPtr<nsISupportsArray> array; rv = NS_NewISupportsArray( getter_AddRefs( array)); if (NS_FAILED( rv)) { IMPORT_LOG0( "FAILED to allocate the nsISupportsArray\n"); return( rv); } nsCOMPtr<nsIImportService> impSvc(do_GetService(NS_IMPORTSERVICE_CONTRACTID, &rv)); if (NS_FAILED( rv)) { IMPORT_LOG0( "*** Failed to obtain the import service\n"); return( rv); } nsXPIDLCString pName; rv = pLoc->GetLeafName(getter_Copies(pName)); if (NS_FAILED( rv)) { IMPORT_LOG0( "*** Failed getting leaf name of file\n"); return( rv); } // for get unicode leafname. If it uses nsILocalFile interface, // these codes do not need due to nsILocalFile->GetUnicodeLeafName() nsString name; rv = impSvc->SystemStringToUnicode((const char*) pName, name); if (NS_FAILED(rv)) name.AssignWithConversion((const char*) pName); PRInt32 idx = name.RFindChar( '.'); if ((idx != -1) && (idx > 0) && ((name.Length() - idx - 1) < 5)) { nsString t; name.Left( t, idx); name = t; } nsCOMPtr<nsIImportABDescriptor> desc; nsISupports * pInterface; rv = impSvc->CreateNewABDescriptor( getter_AddRefs( desc)); if (NS_SUCCEEDED( rv)) { PRUint32 sz = 0; pLoc->GetFileSize( &sz); desc->SetPreferredName( name.get()); desc->SetSize( sz); nsIFileSpec *pSpec = nsnull; desc->GetFileSpec( &pSpec); if (pSpec) { pSpec->FromFileSpec( pLoc); NS_RELEASE( pSpec); } rv = desc->QueryInterface( kISupportsIID, (void **) &pInterface); array->AppendElement( pInterface); pInterface->Release(); } if (NS_FAILED( rv)) { IMPORT_LOG0( "*** Error creating address book descriptor for text import\n"); } else { rv = array->QueryInterface( NS_GET_IID(nsISupportsArray), (void **) ppArray); } return( rv); }
static void DIR_SetLocalizedStringPref (const char *prefRoot, const char *prefLeaf, const char *value) { nsresult rv; nsCOMPtr<nsIPrefService> prefSvc(do_GetService(NS_PREFSERVICE_CONTRACTID, &rv)); if (NS_FAILED(rv)) return; nsCAutoString prefLocation(prefRoot); prefLocation.Append('.'); nsCOMPtr<nsIPrefBranch> prefBranch; rv = prefSvc->GetBranch(prefLocation.get(), getter_AddRefs(prefBranch)); if (NS_FAILED(rv)) return; nsString wvalue; nsCOMPtr<nsIPrefLocalizedString> newStr( do_CreateInstance(NS_PREFLOCALIZEDSTRING_CONTRACTID, &rv)); if (NS_FAILED(rv)) { NS_ASSERTION(NS_SUCCEEDED(rv), "Could not createInstance in DIR_SetLocalizedStringPref"); return; } NS_ConvertUTF8toUTF16 newValue(value); rv = newStr->SetData(newValue.get()); if (NS_FAILED(rv)) { NS_ASSERTION(NS_SUCCEEDED(rv), "Could not set pref data in DIR_SetLocalizedStringPref"); return; } nsCOMPtr<nsIPrefLocalizedString> locStr; if (NS_SUCCEEDED(prefBranch->GetComplexValue(prefLeaf, NS_GET_IID(nsIPrefLocalizedString), getter_AddRefs(locStr)))) { nsString data; locStr->GetData(getter_Copies(data)); // Only set the pref if the data values aren't the same (i.e. don't change // unnecessarily, but also, don't change in the case that its a chrome // string pointing to the value we want to set the pref to). if (newValue != data) rv = prefBranch->SetComplexValue(prefLeaf, NS_GET_IID(nsIPrefLocalizedString), newStr); } else { // No value set, but check the default pref branch (i.e. user may have // cleared the pref) nsCOMPtr<nsIPrefBranch> dPB; rv = prefSvc->GetDefaultBranch(prefLocation.get(), getter_AddRefs(dPB)); if (NS_SUCCEEDED(dPB->GetComplexValue(prefLeaf, NS_GET_IID(nsIPrefLocalizedString), getter_AddRefs(locStr)))) { // Default branch has a value nsString data; locStr->GetData(getter_Copies(data)); if (newValue != data) // If the vales aren't the same, set the data on the main pref branch rv = prefBranch->SetComplexValue(prefLeaf, NS_GET_IID(nsIPrefLocalizedString), newStr); else // Else if they are, kill the user pref rv = prefBranch->ClearUserPref(prefLeaf); } else // No values set anywhere, so just set the pref rv = prefBranch->SetComplexValue(prefLeaf, NS_GET_IID(nsIPrefLocalizedString), newStr); } NS_ASSERTION(NS_SUCCEEDED(rv), "Could not set pref in DIR_SetLocalizedStringPref"); }
// Test a message send???? nsresult nsEudoraCompose::SendTheMessage(nsIFile *pMailImportLocation, nsIFile **pMsg) { nsresult rv = CreateComponents(); if (NS_SUCCEEDED( rv)) rv = CreateIdentity(); if (NS_FAILED( rv)) return( rv); // IMPORT_LOG0( "Outlook Compose created necessary components\n"); nsString bodyType; nsString charSet; nsString headerVal; GetHeaderValue( m_pHeaders, m_headerLen, "From:", headerVal); if (!headerVal.IsEmpty()) m_pMsgFields->SetFrom( headerVal); GetHeaderValue( m_pHeaders, m_headerLen, "To:", headerVal); if (!headerVal.IsEmpty()) m_pMsgFields->SetTo( headerVal); GetHeaderValue( m_pHeaders, m_headerLen, "Subject:", headerVal); if (!headerVal.IsEmpty()) m_pMsgFields->SetSubject( headerVal); GetHeaderValue( m_pHeaders, m_headerLen, "Content-type:", headerVal); bodyType = headerVal; ExtractType( bodyType); ExtractCharset( headerVal); // Use platform charset as default if the msg doesn't specify one // (ie, no 'charset' param in the Content-Type: header). As the last // resort we'll use the mail default charset. // (ie, no 'charset' param in the Content-Type: header) or if the // charset parameter fails a length sanity check. // As the last resort we'll use the mail default charset. if ( headerVal.IsEmpty() || (headerVal.Length() > kContentTypeLengthSanityCheck) ) { CopyASCIItoUTF16(nsMsgI18NFileSystemCharset(), headerVal); if (headerVal.IsEmpty()) { // last resort if (m_defCharset.IsEmpty()) { nsString defaultCharset; NS_GetLocalizedUnicharPreferenceWithDefault(nsnull, "mailnews.view_default_charset", NS_LITERAL_STRING("ISO-8859-1"), defaultCharset); m_defCharset = defaultCharset; } headerVal = m_defCharset; } } m_pMsgFields->SetCharacterSet( NS_LossyConvertUTF16toASCII(headerVal).get() ); charSet = headerVal; GetHeaderValue( m_pHeaders, m_headerLen, "CC:", headerVal); if (!headerVal.IsEmpty()) m_pMsgFields->SetCc( headerVal); GetHeaderValue( m_pHeaders, m_headerLen, "Message-ID:", headerVal); if (!headerVal.IsEmpty()) m_pMsgFields->SetMessageId( NS_LossyConvertUTF16toASCII(headerVal).get() ); GetHeaderValue( m_pHeaders, m_headerLen, "Reply-To:", headerVal); if (!headerVal.IsEmpty()) m_pMsgFields->SetReplyTo( headerVal); // what about all of the other headers?!?!?!?!?!?! char *pMimeType; if (!bodyType.IsEmpty()) pMimeType = ToNewCString(bodyType); else pMimeType = ToNewCString(m_bodyType); // IMPORT_LOG0( "Outlook compose calling CreateAndSendMessage\n"); nsMsgAttachedFile *pAttach = GetLocalAttachments(); /* l10n - I have the body of the message in the system charset, I need to "encode" it to be the charset for the message *UNLESS* of course, I don't know what the charset of the message should be? How do I determine what the charset should be if it doesn't exist? */ nsString uniBody; NS_CopyNativeToUnicode( nsDependentCString(m_pBody), uniBody); nsCString body; rv = nsMsgI18NConvertFromUnicode( NS_LossyConvertUTF16toASCII(charSet).get(), uniBody, body); if (NS_FAILED( rv)) { // in this case, if we did not use the default compose // charset, then try that. if (!charSet.Equals( m_defCharset)) { body.Truncate(); rv = nsMsgI18NConvertFromUnicode( NS_LossyConvertUTF16toASCII(charSet).get(), uniBody, body); } } uniBody.Truncate(); // See if it's a draft msg (ie, no From: or no To: AND no Cc: AND no Bcc:). // Eudora saves sent and draft msgs in Out folder (ie, mixed) and it does // store Bcc: header in the msg itself. nsMsgDeliverMode mode = nsIMsgSend::nsMsgDeliverNow; nsAutoString from, to, cc, bcc; rv = m_pMsgFields->GetFrom(from); rv = m_pMsgFields->GetTo(to); rv = m_pMsgFields->GetCc(cc); rv = m_pMsgFields->GetBcc(bcc); if ( from.IsEmpty() || to.IsEmpty() && cc.IsEmpty() && bcc.IsEmpty() ) mode = nsIMsgSend::nsMsgSaveAsDraft; // We only get the editor interface when there's embedded content. // Otherwise pEditor remains NULL. That way we only import with the pseudo // editor when it helps. nsRefPtr<nsEudoraEditor> pEudoraEditor = new nsEudoraEditor(m_pBody, pMailImportLocation); nsCOMPtr<nsIEditor> pEditor; if (pEudoraEditor->HasEmbeddedContent()) // There's embedded content that we need to import, so query for the editor interface pEudoraEditor->QueryInterface( NS_GET_IID(nsIEditor), getter_AddRefs(pEditor) ); if (NS_FAILED( rv)) { rv = m_pSendProxy->CreateAndSendMessage( pEditor.get(), // pseudo editor shell when there's embedded content s_pIdentity, // dummy identity nsnull, // account key m_pMsgFields, // message fields PR_FALSE, // digest = NO PR_TRUE, // dont_deliver = YES, make a file mode, // mode nsnull, // no message to replace pMimeType, // body type m_pBody, // body pointer m_bodyLen, // body length nsnull, // remote attachment data pAttach, // local attachments nsnull, // related part nsnull, // parent window nsnull, // progress listener m_pListener, // listener nsnull, // password EmptyCString(), // originalMsgURI nsnull); // message compose type } else { rv = m_pSendProxy->CreateAndSendMessage( pEditor.get(), // pseudo editor shell when there's embedded content s_pIdentity, // dummy identity nsnull, // account key m_pMsgFields, // message fields PR_FALSE, // digest = NO PR_TRUE, // dont_deliver = YES, make a file mode, // mode nsnull, // no message to replace pMimeType, // body type body.get(), // body pointer body.Length(), // body length nsnull, // remote attachment data pAttach, // local attachments nsnull, // related part nsnull, // parent window nsnull, // progress listener m_pListener, // listener nsnull, // password EmptyCString(), // originalMsgURI nsnull); // message compose type } // IMPORT_LOG0( "Returned from CreateAndSendMessage\n"); if (pAttach) delete [] pAttach; EudoraSendListener *pListen = (EudoraSendListener *)m_pListener; if (NS_FAILED( rv)) { IMPORT_LOG1( "*** Error, CreateAndSendMessage FAILED: 0x%lx\n", rv); // IMPORT_LOG1( "Headers: %80s\n", m_pHeaders); } else { // wait for the listener to get done! PRInt32 abortCnt = 0; PRInt32 cnt = 0; PRInt32 sleepCnt = 1; while (!pListen->m_done && (abortCnt < kHungAbortCount)) { PR_Sleep( sleepCnt); cnt++; if (cnt > kHungCount) { abortCnt++; sleepCnt *= 2; cnt = 0; } } if (abortCnt >= kHungAbortCount) { IMPORT_LOG0( "**** Create and send message hung\n"); IMPORT_LOG1( "Headers: %s\n", m_pHeaders); IMPORT_LOG1( "Body: %s\n", m_pBody); rv = NS_ERROR_FAILURE; } } if (pMimeType) NS_Free( pMimeType); if (pListen->m_location) { pListen->m_location->Clone(pMsg); rv = NS_OK; } else { rv = NS_ERROR_FAILURE; IMPORT_LOG0( "*** Error, Outlook compose unsuccessful\n"); } pListen->Reset(); return( rv); }
void nsPKCS12Blob::handleError(int myerr) { nsPSMUITracker tracker; if (tracker.isUIForbidden()) { return; } nsresult rv; int prerr = PORT_GetError(); PR_LOG(gPIPNSSLog, PR_LOG_DEBUG, ("PKCS12: NSS/NSPR error(%d)", prerr)); PR_LOG(gPIPNSSLog, PR_LOG_DEBUG, ("PKCS12: I called(%d)", myerr)); nsCOMPtr<nsINSSComponent> nssComponent(do_GetService(kNSSComponentCID, &rv)); if (NS_FAILED(rv)) return; nsCOMPtr<nsIPrompt> errPrompt; nsCOMPtr<nsIWindowWatcher> wwatch(do_GetService(NS_WINDOWWATCHER_CONTRACTID)); if (wwatch) { wwatch->GetNewPrompter(0, getter_AddRefs(errPrompt)); if (errPrompt) { nsCOMPtr<nsIPrompt> proxyPrompt; NS_GetProxyForObject(NS_PROXY_TO_MAIN_THREAD, NS_GET_IID(nsIPrompt), errPrompt, NS_PROXY_SYNC, getter_AddRefs(proxyPrompt)); if (!proxyPrompt) return; } else { return; } } else { return; } nsAutoString errorMsg; switch (myerr) { case PIP_PKCS12_RESTORE_OK: rv = nssComponent->GetPIPNSSBundleString("SuccessfulP12Restore", errorMsg); if (NS_FAILED(rv)) return; errPrompt->Alert(nsnull, errorMsg.get()); return; case PIP_PKCS12_BACKUP_OK: rv = nssComponent->GetPIPNSSBundleString("SuccessfulP12Backup", errorMsg); if (NS_FAILED(rv)) return; errPrompt->Alert(nsnull, errorMsg.get()); return; case PIP_PKCS12_USER_CANCELED: return; /* Just ignore it for now */ case PIP_PKCS12_NOSMARTCARD_EXPORT: rv = nssComponent->GetPIPNSSBundleString("PKCS12InfoNoSmartcardBackup", errorMsg); if (NS_FAILED(rv)) return; errPrompt->Alert(nsnull, errorMsg.get()); return; case PIP_PKCS12_RESTORE_FAILED: rv = nssComponent->GetPIPNSSBundleString("PKCS12UnknownErrRestore", errorMsg); if (NS_FAILED(rv)) return; errPrompt->Alert(nsnull, errorMsg.get()); return; case PIP_PKCS12_BACKUP_FAILED: rv = nssComponent->GetPIPNSSBundleString("PKCS12UnknownErrBackup", errorMsg); if (NS_FAILED(rv)) return; errPrompt->Alert(nsnull, errorMsg.get()); return; case PIP_PKCS12_NSS_ERROR: switch (prerr) { // The following errors have the potential to be "handled", by asking // the user (via a dialog) whether s/he wishes to continue case 0: break; case SEC_ERROR_PKCS12_CERT_COLLISION: /* pop a dialog saying the cert is already in the database */ /* ask to keep going? what happens if one collision but others ok? */ // The following errors cannot be "handled", notify the user (via an alert) // that the operation failed. #if 0 // XXX a boy can dream... // but the PKCS12 lib never throws this error // but then again, how would it? anyway, convey the info below case SEC_ERROR_PKCS12_PRIVACY_PASSWORD_INCORRECT: rv = nssComponent->GetPIPNSSBundleString("PKCS12PasswordInvalid", errorMsg); if (NS_FAILED(rv)) return; errPrompt->Alert(nsnull, errorMsg.get()); break; #endif case SEC_ERROR_BAD_PASSWORD: rv = nssComponent->GetPIPNSSBundleString("PK11BadPassword", errorMsg); if (NS_FAILED(rv)) return; errPrompt->Alert(nsnull, errorMsg.get()); break; case SEC_ERROR_BAD_DER: case SEC_ERROR_PKCS12_CORRUPT_PFX_STRUCTURE: case SEC_ERROR_PKCS12_INVALID_MAC: rv = nssComponent->GetPIPNSSBundleString("PKCS12DecodeErr", errorMsg); if (NS_FAILED(rv)) return; errPrompt->Alert(nsnull, errorMsg.get()); break; case SEC_ERROR_PKCS12_DUPLICATE_DATA: rv = nssComponent->GetPIPNSSBundleString("PKCS12DupData", errorMsg); if (NS_FAILED(rv)) return; errPrompt->Alert(nsnull, errorMsg.get()); break; default: rv = nssComponent->GetPIPNSSBundleString("PKCS12UnknownErr", errorMsg); if (NS_FAILED(rv)) return; errPrompt->Alert(nsnull, errorMsg.get()); } break; case 0: default: rv = nssComponent->GetPIPNSSBundleString("PKCS12UnknownErr", errorMsg); if (NS_FAILED(rv)) return; errPrompt->Alert(nsnull, errorMsg.get()); break; } }
/** * Handle 'inout', 'out', and 'retval' params */ nsresult nsJavaXPTCStub::FinalizeJavaParams(const nsXPTParamInfo &aParamInfo, const XPTMethodDescriptor *aMethodInfo, PRUint16 aMethodIndex, nsXPTCMiniVariant* aDispatchParams, nsXPTCMiniVariant &aVariant, jvalue &aJValue) { nsresult rv = NS_OK; JNIEnv* env = GetJNIEnv(); const nsXPTType &type = aParamInfo.GetType(); PRUint8 tag = type.TagPart(); switch (tag) { case nsXPTType::T_I8: { jbyte value; if (aParamInfo.IsRetval()) { // 'retval' value = aJValue.b; } else if (aJValue.l) { // 'inout' & 'out' env->GetByteArrayRegion((jbyteArray) aJValue.l, 0, 1, &value); } if (aVariant.val.p) *((PRInt8 *) aVariant.val.p) = value; } break; case nsXPTType::T_U8: case nsXPTType::T_I16: { jshort value = 0; if (aParamInfo.IsRetval()) { // 'retval' value = aJValue.s; } else if (aJValue.l) { // 'inout' & 'out' env->GetShortArrayRegion((jshortArray) aJValue.l, 0, 1, &value); } if (aVariant.val.p) { if (tag == nsXPTType::T_U8) *((PRUint8 *) aVariant.val.p) = value; else *((PRInt16 *) aVariant.val.p) = value; } } break; case nsXPTType::T_U16: case nsXPTType::T_I32: { jint value = 0; if (aParamInfo.IsRetval()) { // 'retval' value = aJValue.i; } else if (aJValue.l) { // 'inout' & 'out' env->GetIntArrayRegion((jintArray) aJValue.l, 0, 1, &value); } if (aVariant.val.p) { if (tag == nsXPTType::T_U16) *((PRUint16 *) aVariant.val.p) = value; else *((PRInt32 *) aVariant.val.p) = value; } } break; case nsXPTType::T_U32: case nsXPTType::T_I64: { jlong value = 0; if (aParamInfo.IsRetval()) { // 'retval' value = aJValue.j; } else if (aJValue.l) { // 'inout' & 'out' env->GetLongArrayRegion((jlongArray) aJValue.l, 0, 1, &value); } if (aVariant.val.p) { if (tag == nsXPTType::T_U32) *((PRUint32 *) aVariant.val.p) = value; else *((PRInt64 *) aVariant.val.p) = value; } } break; case nsXPTType::T_FLOAT: { if (aParamInfo.IsRetval()) { // 'retval' *((float *) aVariant.val.p) = aJValue.f; } else if (aJValue.l) { // 'inout' & 'out' env->GetFloatArrayRegion((jfloatArray) aJValue.l, 0, 1, (jfloat*) aVariant.val.p); } } break; // XXX how do we handle 64-bit values? case nsXPTType::T_U64: case nsXPTType::T_DOUBLE: { jdouble value = 0; if (aParamInfo.IsRetval()) { // 'retval' value = aJValue.d; } else if (aJValue.l) { // 'inout' & 'out' env->GetDoubleArrayRegion((jdoubleArray) aJValue.l, 0, 1, &value); } if (aVariant.val.p) { if (tag == nsXPTType::T_DOUBLE) *((double *) aVariant.val.p) = value; else *((PRUint64 *) aVariant.val.p) = static_cast<PRUint64>(value); } } break; case nsXPTType::T_BOOL: { if (aParamInfo.IsRetval()) { // 'retval' *((PRBool *) aVariant.val.p) = aJValue.z; } else if (aJValue.l) { // 'inout' & 'out' env->GetBooleanArrayRegion((jbooleanArray) aJValue.l, 0, 1, (jboolean*) aVariant.val.p); } } break; case nsXPTType::T_CHAR: case nsXPTType::T_WCHAR: { if (aParamInfo.IsRetval()) { // 'retval' if (type.TagPart() == nsXPTType::T_CHAR) *((char *) aVariant.val.p) = aJValue.c; else *((PRUnichar *) aVariant.val.p) = aJValue.c; } else if (aJValue.l) { // 'inout' & 'out' jchar* array = env->GetCharArrayElements((jcharArray) aJValue.l, nsnull); if (!array) { rv = NS_ERROR_OUT_OF_MEMORY; break; } if (type.TagPart() == nsXPTType::T_CHAR) *((char *) aVariant.val.p) = array[0]; else *((PRUnichar *) aVariant.val.p) = array[0]; env->ReleaseCharArrayElements((jcharArray) aJValue.l, array, JNI_ABORT); } } break; case nsXPTType::T_CHAR_STR: { jstring str = nsnull; if (aParamInfo.IsRetval()) { // 'retval' str = (jstring) aJValue.l; } else { // 'inout' & 'out' str = (jstring) env->GetObjectArrayElement((jobjectArray) aJValue.l, 0); } char** variant = static_cast<char**>(aVariant.val.p); if (str) { // Get string buffer const char* char_ptr = env->GetStringUTFChars(str, nsnull); if (!char_ptr) { rv = NS_ERROR_OUT_OF_MEMORY; break; } // If new string is different from one passed in, free old string // and replace with new string. if (aParamInfo.IsRetval() || *variant == nsnull || strcmp(*variant, char_ptr) != 0) { if (!aParamInfo.IsRetval() && *variant) PR_Free(*variant); *variant = strdup(char_ptr); if (*variant == nsnull) { rv = NS_ERROR_OUT_OF_MEMORY; // don't 'break'; fall through to release chars } } // Release string buffer env->ReleaseStringUTFChars(str, char_ptr); } else { // If we were passed in a string, delete it now, and set to null. // (Only for 'inout' & 'out' params) if (*variant && !aParamInfo.IsRetval()) { PR_Free(*variant); } *variant = nsnull; } } break; case nsXPTType::T_WCHAR_STR: { jstring str = nsnull; if (aParamInfo.IsRetval()) { // 'retval' str = (jstring) aJValue.l; } else { // 'inout' & 'out' str = (jstring) env->GetObjectArrayElement((jobjectArray) aJValue.l, 0); } PRUnichar** variant = static_cast<PRUnichar**>(aVariant.val.p); if (str) { // Get string buffer const jchar* wchar_ptr = env->GetStringChars(str, nsnull); if (!wchar_ptr) { rv = NS_ERROR_OUT_OF_MEMORY; break; } // If new string is different from one passed in, free old string // and replace with new string. We if (aParamInfo.IsRetval() || *variant == nsnull || nsCRT::strcmp(*variant, wchar_ptr) != 0) { if (!aParamInfo.IsRetval() && *variant) PR_Free(*variant); PRUint32 length = nsCRT::strlen(wchar_ptr); *variant = (PRUnichar*) PR_Malloc((length + 1) * sizeof(PRUnichar)); if (*variant) { memcpy(*variant, wchar_ptr, length * sizeof(PRUnichar)); (*variant)[length] = 0; } else { rv = NS_ERROR_OUT_OF_MEMORY; // don't 'break'; fall through to release chars } } // Release string buffer env->ReleaseStringChars(str, wchar_ptr); } else { // If we were passed in a string, delete it now, and set to null. // (Only for 'inout' & 'out' params) if (*variant && !aParamInfo.IsRetval()) { PR_Free(*variant); } *variant = nsnull; } } break; case nsXPTType::T_IID: { jstring str = nsnull; if (aParamInfo.IsRetval()) { // 'retval' str = (jstring) aJValue.l; } else { // 'inout' & 'out' str = (jstring) env->GetObjectArrayElement((jobjectArray) aJValue.l, 0); } nsID** variant = static_cast<nsID**>(aVariant.val.p); if (str) { // Get string buffer const char* char_ptr = env->GetStringUTFChars(str, nsnull); if (!char_ptr) { rv = NS_ERROR_OUT_OF_MEMORY; break; } if (!aParamInfo.IsRetval() && *variant) { // If we were given an nsID, set it to the new string nsID* oldIID = *variant; oldIID->Parse(char_ptr); } else { // If the argument that was passed in was null, then we need to // create a new nsID. nsID* newIID = new nsID; if (newIID) { newIID->Parse(char_ptr); *variant = newIID; } else { rv = NS_ERROR_OUT_OF_MEMORY; // don't 'break'; fall through to release chars } } // Release string buffer env->ReleaseStringUTFChars(str, char_ptr); } else { // If we were passed in an nsID, delete it now, and set to null. // (Free only 'inout' & 'out' params) if (*variant && !aParamInfo.IsRetval()) { delete *variant; } *variant = nsnull; } } break; case nsXPTType::T_INTERFACE: case nsXPTType::T_INTERFACE_IS: { jobject java_obj = nsnull; if (aParamInfo.IsRetval()) { // 'retval' java_obj = aJValue.l; } else if (aJValue.l) { // 'inout' & 'out' java_obj = env->GetObjectArrayElement((jobjectArray) aJValue.l, 0); } void* xpcom_obj = nsnull; if (java_obj) { // Get IID for this param nsID iid; rv = GetIIDForMethodParam(mIInfo, aMethodInfo, aParamInfo, aParamInfo.GetType().TagPart(), aMethodIndex, aDispatchParams, PR_FALSE, iid); if (NS_FAILED(rv)) break; // If the requested interface is nsIWeakReference, then we look for or // create a stub for the nsISupports interface. Then we create a weak // reference from that stub. PRBool isWeakRef; if (iid.Equals(NS_GET_IID(nsIWeakReference))) { isWeakRef = PR_TRUE; iid = NS_GET_IID(nsISupports); } else { isWeakRef = PR_FALSE; } rv = JavaObjectToNativeInterface(env, java_obj, iid, &xpcom_obj); if (NS_FAILED(rv)) break; rv = ((nsISupports*) xpcom_obj)->QueryInterface(iid, &xpcom_obj); if (NS_FAILED(rv)) break; // If the function expects a weak reference, then we need to // create it here. if (isWeakRef) { nsISupports* isupports = (nsISupports*) xpcom_obj; nsCOMPtr<nsISupportsWeakReference> supportsweak = do_QueryInterface(isupports); if (supportsweak) { nsWeakPtr weakref; supportsweak->GetWeakReference(getter_AddRefs(weakref)); NS_RELEASE(isupports); xpcom_obj = weakref; NS_ADDREF((nsISupports*) xpcom_obj); } else { xpcom_obj = nsnull; } } } // For 'inout' params, if the resulting xpcom value is different than the // one passed in, then we must release the incoming xpcom value. nsISupports** variant = static_cast<nsISupports**>(aVariant.val.p); if (aParamInfo.IsIn() && *variant) { nsCOMPtr<nsISupports> in = do_QueryInterface(*variant); nsCOMPtr<nsISupports> out = do_QueryInterface((nsISupports*) xpcom_obj); if (in != out) { NS_RELEASE(*variant); } } *(static_cast<void**>(aVariant.val.p)) = xpcom_obj; } break; case nsXPTType::T_ASTRING: case nsXPTType::T_DOMSTRING: { NS_PRECONDITION(aParamInfo.IsDipper(), "string argument is not dipper"); if (!aParamInfo.IsDipper()) { rv = NS_ERROR_UNEXPECTED; break; } jstring jstr = (jstring) aJValue.l; nsString* variant = static_cast<nsString*>(aVariant.val.p); if (jstr) { // Get string buffer const jchar* wchar_ptr = env->GetStringChars(jstr, nsnull); if (!wchar_ptr) { rv = NS_ERROR_OUT_OF_MEMORY; break; } variant->Assign(wchar_ptr); // release String buffer env->ReleaseStringChars(jstr, wchar_ptr); } else { variant->SetIsVoid(PR_TRUE); } } break; case nsXPTType::T_UTF8STRING: case nsXPTType::T_CSTRING: { NS_PRECONDITION(aParamInfo.IsDipper(), "string argument is not dipper"); if (!aParamInfo.IsDipper()) { rv = NS_ERROR_UNEXPECTED; break; } jstring jstr = (jstring) aJValue.l; nsCString* variant = static_cast<nsCString*>(aVariant.val.p); if (jstr) { // Get string buffer const char* char_ptr = env->GetStringUTFChars(jstr, nsnull); if (!char_ptr) { rv = NS_ERROR_OUT_OF_MEMORY; break; } variant->Assign(char_ptr); // release String buffer env->ReleaseStringUTFChars(jstr, char_ptr); } else { variant->SetIsVoid(PR_TRUE); } } break; case nsXPTType::T_VOID: { if (aParamInfo.IsRetval()) { // 'retval' aVariant.val.p = reinterpret_cast<void*>(aJValue.j); } else if (aJValue.l) { // 'inout' & 'out' env->GetLongArrayRegion((jlongArray) aJValue.l, 0, 1, (jlong*) aVariant.val.p); } } break; default: NS_WARNING("unexpected parameter type"); return NS_ERROR_UNEXPECTED; } return rv; }