NS_IMETHODIMP nsMsgThread::GetRootHdr(int32_t *resultIndex, nsIMsgDBHdr **result) { NS_ENSURE_ARG_POINTER(result); *result = nullptr; nsresult rv = NS_OK; if (m_threadRootKey != nsMsgKey_None) { rv = GetChildHdrForKey(m_threadRootKey, result, resultIndex); if (NS_SUCCEEDED(rv) && *result) { // check that we're really the root key. nsMsgKey parentKey; (*result)->GetThreadParent(&parentKey); if (parentKey == nsMsgKey_None) return rv; NS_RELEASE(*result); } #ifdef DEBUG_David_Bienvenu printf("need to reset thread root key\n"); #endif uint32_t numChildren; nsMsgKey threadParentKey = nsMsgKey_None; GetNumChildren(&numChildren); for (uint32_t childIndex = 0; childIndex < numChildren; childIndex++) { nsCOMPtr <nsIMsgDBHdr> curChild; rv = GetChildHdrAt(childIndex, getter_AddRefs(curChild)); if (NS_SUCCEEDED(rv) && curChild) { nsMsgKey parentKey; curChild->GetThreadParent(&parentKey); if (parentKey == nsMsgKey_None) { curChild->GetMessageKey(&threadParentKey); if (*result) { NS_WARNING("two top level msgs, not good"); continue; } SetThreadRootKey(threadParentKey); if (resultIndex) *resultIndex = childIndex; NS_ADDREF(*result = curChild); ReparentMsgsWithInvalidParent(numChildren, threadParentKey); // return NS_OK; } } } } if (!*result) { // if we can't get the thread root key, we'll just get the first hdr. // there's a bug where sometimes we weren't resetting the thread root key // when removing the thread root key. if (resultIndex) *resultIndex = 0; rv = GetChildHdrAt(0, result); } if (!*result) return rv; // Check that the thread id of the message is this thread. nsMsgKey threadId = nsMsgKey_None; (void)(*result)->GetThreadId(&threadId); if (threadId != m_threadKey) (*result)->SetThreadId(m_threadKey); return rv; }
// // Always set *identityInvalid == FALSE here. This // will prevent the browser from popping up the authentication // prompt window. Because GSSAPI does not have an API // for fetching initial credentials (ex: A Kerberos TGT), // there is no correct way to get the users credentials. // NS_IMETHODIMP nsHttpNegotiateAuth::ChallengeReceived(nsIHttpAuthenticableChannel *authChannel, const char *challenge, bool isProxyAuth, nsISupports **sessionState, nsISupports **continuationState, bool *identityInvalid) { nsIAuthModule *module = (nsIAuthModule *) *continuationState; *identityInvalid = false; if (module) return NS_OK; nsresult rv; nsCOMPtr<nsIURI> uri; rv = authChannel->GetURI(getter_AddRefs(uri)); if (NS_FAILED(rv)) return rv; uint32_t req_flags = nsIAuthModule::REQ_DEFAULT; nsAutoCString service; if (isProxyAuth) { if (!TestBoolPref(kNegotiateAuthAllowProxies)) { LOG(("nsHttpNegotiateAuth::ChallengeReceived proxy auth blocked\n")); return NS_ERROR_ABORT; } nsCOMPtr<nsIProxyInfo> proxyInfo; authChannel->GetProxyInfo(getter_AddRefs(proxyInfo)); NS_ENSURE_STATE(proxyInfo); proxyInfo->GetHost(service); } else { bool allowed = TestNonFqdn(uri) || TestPref(uri, kNegotiateAuthTrustedURIs); if (!allowed) { LOG(("nsHttpNegotiateAuth::ChallengeReceived URI blocked\n")); return NS_ERROR_ABORT; } bool delegation = TestPref(uri, kNegotiateAuthDelegationURIs); if (delegation) { LOG((" using REQ_DELEGATE\n")); req_flags |= nsIAuthModule::REQ_DELEGATE; } rv = uri->GetAsciiHost(service); if (NS_FAILED(rv)) return rv; } LOG((" service = %s\n", service.get())); // // The correct service name for IIS servers is "HTTP/f.q.d.n", so // construct the proper service name for passing to "gss_import_name". // // TODO: Possibly make this a configurable service name for use // with non-standard servers that use stuff like "khttp/f.q.d.n" // instead. // service.Insert("HTTP@", 0); const char *contractID; if (TestBoolPref(kNegotiateAuthSSPI)) { LOG((" using negotiate-sspi\n")); contractID = NS_AUTH_MODULE_CONTRACTID_PREFIX "negotiate-sspi"; } else { LOG((" using negotiate-gss\n")); contractID = NS_AUTH_MODULE_CONTRACTID_PREFIX "negotiate-gss"; } rv = CallCreateInstance(contractID, &module); if (NS_FAILED(rv)) { LOG((" Failed to load Negotiate Module \n")); return rv; } rv = module->Init(service.get(), req_flags, nullptr, nullptr, nullptr); if (NS_FAILED(rv)) { NS_RELEASE(module); return rv; } *continuationState = module; return NS_OK; }
nsresult ThirdPartyUtil::GetFirstPartyURIInternal(nsIChannel *aChannel, nsIDocument *aDoc, bool aLogErrors, nsIURI **aOutput) { nsresult rv = NS_ERROR_NULL_POINTER; nsCOMPtr<nsIURI> srcURI; if (!aOutput) return rv; *aOutput = nullptr; if (!aChannel && aDoc) { aChannel = aDoc->GetChannel(); } // If aChannel is specified or available, use the official route // for sure if (aChannel) { rv = GetOriginatingURI(aChannel, aOutput); aChannel->GetURI(getter_AddRefs(srcURI)); if (NS_SUCCEEDED(rv) && *aOutput) { // At this point, about: and chrome: URLs have been mapped to file: or // jar: URLs. Try to recover the original URL. nsAutoCString scheme; nsresult rv2 = (*aOutput)->GetScheme(scheme); NS_ENSURE_SUCCESS(rv2, rv2); if (scheme.Equals("file") || scheme.Equals("jar")) { nsCOMPtr<nsIURI> originalURI; rv2 = aChannel->GetOriginalURI(getter_AddRefs(originalURI)); if (NS_SUCCEEDED(rv2) && originalURI) { NS_RELEASE(*aOutput); NS_ADDREF(*aOutput = originalURI); } } } } // If the channel was missing, closed or broken, try the // window hierarchy directly. // // This might fail to work for first-party loads themselves, but // we don't need this codepath for that case. if (NS_FAILED(rv) && aDoc) { nsCOMPtr<nsIDOMWindow> top; nsCOMPtr<nsIDOMDocument> topDDoc; nsIURI *docURI = nullptr; srcURI = aDoc->GetDocumentURI(); if (aDoc->GetWindow()) { aDoc->GetWindow()->GetTop(getter_AddRefs(top)); top->GetDocument(getter_AddRefs(topDDoc)); nsCOMPtr<nsIDocument> topDoc(do_QueryInterface(topDDoc)); docURI = topDoc->GetOriginalURI(); if (docURI) { // Give us a mutable URI and also addref rv = NS_EnsureSafeToReturn(docURI, aOutput); } } else { // XXX: Chrome callers (such as NoScript) can end up here // through getImageData/canvas usage with no document state // (no Window and a document URI of about:blank). Propogate // rv fail (by doing nothing), and hope caller recovers. } if (*aOutput) rv = NS_OK; } if (*aOutput && !SchemeIsWhiteListed(*aOutput)) { // If URI scheme is not whitelisted and the URI lacks a hostname, force a // failure. nsAutoCString host; rv = (*aOutput)->GetHost(host); if (NS_SUCCEEDED(rv) && (host.Length() == 0)) { rv = NS_ERROR_FAILURE; } } // Log failure to error console. if (aLogErrors && NS_FAILED(rv)) { nsCOMPtr<nsIConsoleService> console (do_GetService(NS_CONSOLESERVICE_CONTRACTID)); if (console) { nsCString spec; nsCString srcSpec("unknown"); if (srcURI) srcURI->GetSpec(srcSpec); if (*aOutput) (*aOutput)->GetSpec(spec); if (spec.Length() > 0) { nsPrintfCString msg("getFirstPartyURI failed for %s: no host in first party URI %s", srcSpec.get(), spec.get()); // TODO: L10N console->LogStringMessage(NS_ConvertUTF8toUTF16(msg).get()); } else { nsPrintfCString msg("getFirstPartyURI failed for %s: 0x%x", srcSpec.get(), rv); console->LogStringMessage(NS_ConvertUTF8toUTF16(msg).get()); } } if (*aOutput) { // discard return object. (*aOutput)->Release(); *aOutput = nullptr; } } // TODO: We could provide a route through the loadgroup + notification // callbacks too, but either channel or document was always available // in the cases where this function was originally needed (the image cache). // The notification callbacks also appear to suffers from the same limitation // as the document path. See nsICookiePermissions.GetOriginatingURI() for // details. return rv; }
// 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 nsMsgBrkMBoxStore::GetNewMsgOutputStream(nsIMsgFolder *aFolder, nsIMsgDBHdr **aNewMsgHdr, bool *aReusable, nsIOutputStream **aResult) { NS_ENSURE_ARG_POINTER(aFolder); NS_ENSURE_ARG_POINTER(aNewMsgHdr); NS_ENSURE_ARG_POINTER(aReusable); NS_ENSURE_ARG_POINTER(aResult); #ifdef _DEBUG NS_ASSERTION(m_streamOutstandingFolder != aFolder, "didn't finish prev msg"); m_streamOutstandingFolder = aFolder; #endif *aReusable = true; nsCOMPtr<nsIFile> mboxFile; aFolder->GetFilePath(getter_AddRefs(mboxFile)); nsCOMPtr<nsIMsgDatabase> db; aFolder->GetMsgDatabase(getter_AddRefs(db)); if (!db && !*aNewMsgHdr) NS_WARNING("no db, and no message header"); bool exists; mboxFile->Exists(&exists); if (!exists) mboxFile->Create(nsIFile::NORMAL_FILE_TYPE, 0600); nsCString URI; aFolder->GetURI(URI); nsresult rv; nsCOMPtr<nsISeekableStream> seekable; if (m_outputStreams.Get(URI, aResult)) { seekable = do_QueryInterface(*aResult, &rv); NS_ENSURE_SUCCESS(rv, rv); rv = seekable->Seek(nsISeekableStream::NS_SEEK_END, 0); if (NS_FAILED(rv)) { m_outputStreams.Remove(URI); NS_RELEASE(*aResult); } } if (!*aResult) { rv = MsgGetFileStream(mboxFile, aResult); NS_ASSERTION(NS_SUCCEEDED(rv), "failed opening offline store for output"); if (NS_FAILED(rv)) printf("failed opening offline store for %s\n", URI.get()); NS_ENSURE_SUCCESS(rv, rv); seekable = do_QueryInterface(*aResult, &rv); NS_ENSURE_SUCCESS(rv, rv); rv = seekable->Seek(nsISeekableStream::NS_SEEK_END, 0); NS_ENSURE_SUCCESS(rv, rv); m_outputStreams.Put(URI, *aResult); } int64_t filePos; seekable->Tell(&filePos); if (db && !*aNewMsgHdr) { // if mbox is close to 4GB, auto-assign the msg key. nsMsgKey key = filePos > 0xFFFFFF00 ? nsMsgKey_None : (nsMsgKey) filePos; db->CreateNewHdr(key, aNewMsgHdr); } if (*aNewMsgHdr) { char storeToken[100]; PR_snprintf(storeToken, sizeof(storeToken), "%lld", filePos); (*aNewMsgHdr)->SetMessageOffset(filePos); (*aNewMsgHdr)->SetStringProperty("storeToken", storeToken); } return rv; }
/** * 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; }
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 void TestSecurityManager(JSContext* jscontext, JSObject* glob, nsIXPConnect* xpc) { const char* t; jsval rval; JSBool success = JS_TRUE; MySecMan* sm = new MySecMan(); nsTestXPCFoo* foo = new nsTestXPCFoo(); if(!sm || ! foo) { success = JS_FALSE; printf("FAILED to create object!\n"); goto sm_test_done; } rval = JSVAL_FALSE; JS_SetProperty(jscontext, glob, "failed", &rval); printf("Individual SecurityManager tests...\n"); if(NS_FAILED(xpc->SetSecurityManagerForJSContext(jscontext, sm, nsIXPCSecurityManager::HOOK_ALL))) { success = JS_FALSE; printf("SetSecurityManagerForJSContext FAILED!\n"); goto sm_test_done; } printf(" build wrapper with veto: TEST NOT RUN\n"); /* // This test is broken because xpconnect now detects that this is a // call from native code and lets it succeed without calling the security manager sm->SetMode(MySecMan::VETO_ALL); printf(" build wrapper with veto: "); if(NS_SUCCEEDED(xpc->WrapNative(jscontext, glob, foo, NS_GET_IID(nsITestXPCFoo2), &wrapper))) { success = JS_FALSE; printf("FAILED\n"); NS_RELEASE(wrapper); } else { printf("passed\n"); } */ sm->SetMode(MySecMan::OK_ALL); printf(" build wrapper no veto: "); nsIXPConnectJSObjectHolder* holder; if(NS_SUCCEEDED(xpc->WrapNative(jscontext, glob, foo, NS_GET_IID(nsITestXPCFoo2), &holder))) { printf("passed\n"); JSObject* obj; if(NS_SUCCEEDED(holder->GetJSObject(&obj))) { rval = OBJECT_TO_JSVAL(obj); JS_SetProperty(jscontext, glob, "foo", &rval); } NS_RELEASE(holder); } else { success = JS_FALSE; printf("FAILED\n"); } sm->SetMode(MySecMan::OK_ALL); printf(" getService no veto: "); t = "try{Components.classes['@mozilla.org/js/xpc/XPConnect;1'].getService(); print('passed');}catch(e){failed = true; print('FAILED');}"; JS_EvaluateScript(jscontext, glob, t, strlen(t), "builtin", 1, &rval); sm->SetMode(MySecMan::VETO_ALL); printf(" getService with veto: "); t = "try{Components.classes['@mozilla.org/js/xpc/XPConnect;1'].getService(); failed = true; print('FAILED');}catch(e){print('passed');}"; JS_EvaluateScript(jscontext, glob, t, strlen(t), "builtin", 1, &rval); sm->SetMode(MySecMan::OK_ALL); printf(" createInstance no veto: "); t = "try{Components.classes['@mozilla.org/js/xpc/ID;1'].createInstance(Components.interfaces.nsIJSID); print('passed');}catch(e){failed = true; print('FAILED');}"; JS_EvaluateScript(jscontext, glob, t, strlen(t), "builtin", 1, &rval); sm->SetMode(MySecMan::VETO_ALL); printf(" getService with veto: "); t = "try{Components.classes['@mozilla.org/js/xpc/ID;1'].createInstance(Components.interfaces.nsIJSID); failed = true; print('FAILED');}catch(e){print('passed');}"; JS_EvaluateScript(jscontext, glob, t, strlen(t), "builtin", 1, &rval); sm->SetMode(MySecMan::OK_ALL); printf(" call method no veto: "); t = "try{foo.Test2(); print(' : passed');}catch(e){failed = true; print(' : FAILED');}"; JS_EvaluateScript(jscontext, glob, t, strlen(t), "builtin", 1, &rval); sm->SetMode(MySecMan::VETO_ALL); printf(" call method with veto: "); t = "try{foo.Test2(); failed = true; print(' : FAILED');}catch(e){print(' : passed');}"; JS_EvaluateScript(jscontext, glob, t, strlen(t), "builtin", 1, &rval); sm->SetMode(MySecMan::OK_ALL); printf(" get attribute no veto: "); t = "try{foo.Foo; print(' : passed');}catch(e){failed = true; print(' : FAILED');}"; JS_EvaluateScript(jscontext, glob, t, strlen(t), "builtin", 1, &rval); sm->SetMode(MySecMan::VETO_ALL); printf(" get attribute with veto: "); t = "try{foo.Foo; failed = true; print(' : FAILED');}catch(e){print(' : passed');}"; JS_EvaluateScript(jscontext, glob, t, strlen(t), "builtin", 1, &rval); sm->SetMode(MySecMan::OK_ALL); printf(" set attribute no veto: "); t = "try{foo.Foo = 0; print(' : passed');}catch(e){failed = true; print(' : FAILED');}"; JS_EvaluateScript(jscontext, glob, t, strlen(t), "builtin", 1, &rval); sm->SetMode(MySecMan::VETO_ALL); printf(" set attribute with veto: "); t = "try{foo.Foo = 0; failed = true; print(' : FAILED');}catch(e){print(' : passed');}"; JS_EvaluateScript(jscontext, glob, t, strlen(t), "builtin", 1, &rval); sm_test_done: success = success && JS_GetProperty(jscontext, glob, "failed", &rval) && JSVAL_TRUE != rval; printf("SecurityManager tests : %s\n", success ? "passed" : "FAILED"); NS_IF_RELEASE(foo); xpc->SetSecurityManagerForJSContext(jscontext, nsnull, 0); }
NS_IMETHODIMP nsInternetCiter::Rewrap(const nsAString& aInString, PRUint32 aWrapCol, PRUint32 aFirstLineOffset, PRBool aRespectNewlines, nsAString& aOutString) { // There shouldn't be returns in this string, only dom newlines. // Check to make sure: #ifdef DEBUG PRInt32 cr = aInString.FindChar(PRUnichar('\r')); NS_ASSERTION((cr < 0), "Rewrap: CR in string gotten from DOM!\n"); #endif /* DEBUG */ aOutString.Truncate(); nsCOMPtr<nsILineBreaker> lineBreaker; nsILineBreakerFactory *lf; nsresult rv; rv = CallGetService(NS_LWBRK_CONTRACTID, &lf); if (NS_SUCCEEDED(rv)) { nsAutoString lbarg; lf->GetBreaker(lbarg, getter_AddRefs(lineBreaker)); NS_RELEASE(lf); } // Loop over lines in the input string, rewrapping each one. PRUint32 length; PRUint32 posInString = 0; PRUint32 outStringCol = 0; PRUint32 citeLevel = 0; const nsPromiseFlatString &tString = PromiseFlatString(aInString); length = tString.Length(); #ifdef DEBUG_wrapping int loopcount = 0; #endif while (posInString < length) { #ifdef DEBUG_wrapping printf("Outer loop: '%s'\n", NS_LossyConvertUCS2toASCII(Substring(tString, posInString, length-posInString)).get()); printf("out string is now: '%s'\n", NS_LossyConvertUCS2toASCII(aOutString).get()); #endif // Get the new cite level here since we're at the beginning of a line PRUint32 newCiteLevel = 0; while (posInString < length && tString[posInString] == gt) { ++newCiteLevel; ++posInString; while (posInString < length && tString[posInString] == space) ++posInString; } if (posInString >= length) break; // Special case: if this is a blank line, maintain a blank line // (retain the original paragraph breaks) if (tString[posInString] == nl && !aOutString.IsEmpty()) { if (aOutString.Last() != nl) aOutString.Append(nl); AddCite(aOutString, newCiteLevel); aOutString.Append(nl); ++posInString; outStringCol = 0; continue; } // If the cite level has changed, then start a new line with the // new cite level (but if we're at the beginning of the string, // don't bother). if (newCiteLevel != citeLevel && posInString > newCiteLevel+1 && outStringCol != 0) { BreakLine(aOutString, outStringCol, 0); } citeLevel = newCiteLevel; // Prepend the quote level to the out string if appropriate if (outStringCol == 0) { AddCite(aOutString, citeLevel); outStringCol = citeLevel + (citeLevel ? 1 : 0); } // If it's not a cite, and we're not at the beginning of a line in // the output string, add a space to separate new text from the // previous text. else if (outStringCol > citeLevel) { aOutString.Append(space); ++outStringCol; } // find the next newline -- don't want to go farther than that PRInt32 nextNewline = tString.FindChar(nl, posInString); if (nextNewline < 0) nextNewline = length; // For now, don't wrap unquoted lines at all. // This is because the plaintext edit window has already wrapped them // by the time we get them for rewrap, yet when we call the line // breaker, it will refuse to break backwards, and we'll end up // with a line that's too long and gets displayed as a lone word // on a line by itself. Need special logic to detect this case // and break it ourselves without resorting to the line breaker. if (citeLevel == 0) { aOutString.Append(Substring(tString, posInString, nextNewline-posInString)); outStringCol += nextNewline - posInString; if (nextNewline != (PRInt32)length) { aOutString.Append(nl); outStringCol = 0; } posInString = nextNewline+1; continue; } // Otherwise we have to use the line breaker and loop // over this line of the input string to get all of it: while ((PRInt32)posInString < nextNewline) { #ifdef DEBUG_wrapping if (++loopcount > 1000) NS_ASSERTION(PR_FALSE, "possible infinite loop in nsInternetCiter\n"); printf("Inner loop: '%s'\n", NS_LossyConvertUCS2toASCII(Substring(tString, posInString, nextNewline-posInString)).get()); #endif // Skip over initial spaces: while ((PRInt32)posInString < nextNewline && nsCRT::IsAsciiSpace(tString[posInString])) ++posInString; // If this is a short line, just append it and continue: if (outStringCol + nextNewline - posInString <= aWrapCol-citeLevel-1) { // If this short line is the final one in the in string, // then we need to include the final newline, if any: if (nextNewline+1 == (PRInt32)length && tString[nextNewline-1] == nl) ++nextNewline; // Trim trailing spaces: PRInt32 lastRealChar = nextNewline; while ((PRUint32)lastRealChar > posInString && nsCRT::IsAsciiSpace(tString[lastRealChar-1])) --lastRealChar; aOutString += Substring(tString, posInString, lastRealChar - posInString); outStringCol += lastRealChar - posInString; posInString = nextNewline + 1; continue; } PRInt32 eol = posInString + aWrapCol - citeLevel - outStringCol; // eol is the prospective end of line. // We'll first look backwards from there for a place to break. // If it's already less than our current position, // then our line is already too long, so break now. if (eol <= (PRInt32)posInString) { BreakLine(aOutString, outStringCol, citeLevel); continue; // continue inner loop, with outStringCol now at bol } PRUint32 breakPt; rv = NS_ERROR_BASE; if (lineBreaker) { PRBool needMore; rv = lineBreaker->Prev(tString.get() + posInString, length - posInString, eol + 1 - posInString, &breakPt, &needMore); if (NS_FAILED(rv) || needMore) { // if we couldn't find a breakpoint looking backwards, // and we're not starting a new line, then end this line // and loop around again: if (outStringCol > citeLevel + 1) { BreakLine(aOutString, outStringCol, citeLevel); continue; // continue inner loop, with outStringCol now at bol } // Else try looking forwards: rv = lineBreaker->Next(tString.get() + posInString, length - posInString, eol - posInString, &breakPt, &needMore); if (needMore) rv = NS_ERROR_BASE; } } // If rv is okay, then breakPt is the place to break. // If we get out here and rv is set, something went wrong with line // breaker. Just break the line, hard. if (NS_FAILED(rv)) { #ifdef DEBUG_akkana printf("nsInternetCiter: LineBreaker not working -- breaking hard\n"); #endif breakPt = eol; } // Special case: maybe we should have wrapped last time. // If the first breakpoint here makes the current line too long, // then if we already have text on the current line, // break and loop around again. // If we're at the beginning of the current line, though, // don't force a break since the long word might be a url // and breaking it would make it unclickable on the other end. const int SLOP = 6; if (outStringCol + breakPt > aWrapCol + SLOP && outStringCol > citeLevel+1) { BreakLine(aOutString, outStringCol, citeLevel); continue; } nsAutoString sub (Substring(tString, posInString, breakPt)); // skip newlines or whitespace at the end of the string PRInt32 subend = sub.Length(); while (subend > 0 && IsSpace(sub[subend-1])) --subend; sub.Left(sub, subend); aOutString += sub; outStringCol += sub.Length(); // Advance past the whitespace which caused the wrap: posInString += breakPt; while (posInString < length && IsSpace(tString[posInString])) ++posInString; // Add a newline and the quote level to the out string if (posInString < length) // not for the last line, though BreakLine(aOutString, outStringCol, citeLevel); } // end inner loop within one line of aInString #ifdef DEBUG_wrapping printf("---------\nEnd inner loop: out string is now '%s'\n-----------\n", NS_LossyConvertUCS2toASCII(aOutString).get()); #endif } // end outer loop over lines of aInString #ifdef DEBUG_wrapping printf("Final out string is now: '%s'\n", NS_LossyConvertUCS2toASCII(aOutString).get()); #endif return NS_OK; }
BOOL CPlugin::init(HWND hWndParent) { dbgOut1("CPlugin::init()"); nsISupports * sm = NULL; nsIPrefBranch * prefBranch = NULL; PRBool bSendUrls = PR_FALSE; // default to false if problem getting pref // note that Mozilla will add reference, so do not forget to release NPN_GetValue(NULL, NPNVserviceManager, &sm); // do a QI on the service manager we get back to ensure it's the one we are expecting if(sm) { sm->QueryInterface(NS_GET_IID(nsIServiceManager), (void**)&gServiceManager); NS_RELEASE(sm); } if (gServiceManager) { // get service using its contract id and use it to allocate the memory gServiceManager->GetServiceByContractID(NS_PREFSERVICE_CONTRACTID, NS_GET_IID(nsIPrefBranch), (void **)&prefBranch); if(prefBranch) { prefBranch->GetBoolPref("application.use_ns_plugin_finder", &bSendUrls); NS_RELEASE(prefBranch); } } m_bSmartUpdate = bSendUrls; if(!m_bHidden) { assert(IsWindow(hWndParent)); if(IsWindow(hWndParent)) m_hWndParent = hWndParent; RECT rcParent; GetClientRect(m_hWndParent, &rcParent); CreateWindow(szNullPluginWindowClassName, "NULL Plugin", WS_CHILD, 0,0, rcParent.right, rcParent.bottom, m_hWndParent, (HMENU)NULL, m_hInst, (LPVOID)this); assert(m_hWnd != NULL); if((m_hWnd == NULL) || (!IsWindow(m_hWnd))) return FALSE; UpdateWindow(m_hWnd); ShowWindow(m_hWnd, SW_SHOW); } if(IsNewMimeType((LPSTR)m_pNPMIMEType) || m_bHidden) showGetPluginDialog(); return TRUE; }
nsresult nsMsgFolderCache::OpenMDB(const nsACString& dbName, PRBool exists) { nsresult ret=NS_OK; nsCOMPtr<nsIMdbFactory> mdbFactory; GetMDBFactory(getter_AddRefs(mdbFactory)); if (mdbFactory) { ret = mdbFactory->MakeEnv(nsnull, &m_mdbEnv); if (NS_SUCCEEDED(ret)) { nsIMdbThumb *thumb = nsnull; nsIMdbHeap* dbHeap = 0; mdb_bool dbFrozen = mdbBool_kFalse; // not readonly, we want modifiable if (m_mdbEnv) m_mdbEnv->SetAutoClear(PR_TRUE); if (exists) { mdbOpenPolicy inOpenPolicy; mdb_bool canOpen; mdbYarn outFormatVersion; nsIMdbFile* oldFile = 0; ret = mdbFactory->OpenOldFile(m_mdbEnv, dbHeap, nsCString(dbName).get(), dbFrozen, &oldFile); if ( oldFile ) { if (NS_SUCCEEDED(ret)) { ret = mdbFactory->CanOpenFilePort(m_mdbEnv, oldFile, // file to investigate &canOpen, &outFormatVersion); if (NS_SUCCEEDED(ret) && canOpen) { inOpenPolicy.mOpenPolicy_ScopePlan.mScopeStringSet_Count = 0; inOpenPolicy.mOpenPolicy_MinMemory = 0; inOpenPolicy.mOpenPolicy_MaxLazy = 0; ret = mdbFactory->OpenFileStore(m_mdbEnv, NULL, oldFile, &inOpenPolicy, &thumb); } else ret = NS_MSG_ERROR_FOLDER_SUMMARY_OUT_OF_DATE; } NS_RELEASE(oldFile); // always release our file ref, store has own } } if (NS_SUCCEEDED(ret) && thumb) { mdb_count outTotal; // total somethings to do in operation mdb_count outCurrent; // subportion of total completed so far mdb_bool outDone = PR_FALSE; // is operation finished? mdb_bool outBroken; // is operation irreparably dead and broken? do { ret = thumb->DoMore(m_mdbEnv, &outTotal, &outCurrent, &outDone, &outBroken); if (ret != 0) {// mork isn't really doing NS errors yet. outDone = PR_TRUE; break; } } while (NS_SUCCEEDED(ret) && !outBroken && !outDone); // m_mdbEnv->ClearErrors(); // ### temporary... if (NS_SUCCEEDED(ret) && outDone) { ret = mdbFactory->ThumbToOpenStore(m_mdbEnv, thumb, &m_mdbStore); if (NS_SUCCEEDED(ret) && m_mdbStore) ret = InitExistingDB(); } #ifdef DEBUG_bienvenu1 DumpContents(); #endif } else // ### need error code saying why open file store failed { nsIMdbFile* newFile = 0; ret = mdbFactory->CreateNewFile(m_mdbEnv, dbHeap, nsCString(dbName).get(), &newFile); if ( newFile ) { if (NS_SUCCEEDED(ret)) { mdbOpenPolicy inOpenPolicy; inOpenPolicy.mOpenPolicy_ScopePlan.mScopeStringSet_Count = 0; inOpenPolicy.mOpenPolicy_MinMemory = 0; inOpenPolicy.mOpenPolicy_MaxLazy = 0; ret = mdbFactory->CreateNewFileStore(m_mdbEnv, dbHeap, newFile, &inOpenPolicy, &m_mdbStore); if (NS_SUCCEEDED(ret)) ret = InitNewDB(); } NS_RELEASE(newFile); // always release our file ref, store has own } } NS_IF_RELEASE(thumb); } } return ret; }
XPCCallContext::~XPCCallContext() { // do cleanup... bool shouldReleaseXPC = false; if (mXPCContext) { mXPCContext->SetCallingLangType(mPrevCallerLanguage); #ifdef DEBUG XPCCallContext* old = mThreadData->SetCallContext(mPrevCallContext); NS_ASSERTION(old == this, "bad pop from per thread data"); #else (void) mThreadData->SetCallContext(mPrevCallContext); #endif shouldReleaseXPC = mPrevCallContext == nsnull; } // NB: Needs to happen before the context stack pop. if (mJSContext && mCallerLanguage == NATIVE_CALLER) JS_EndRequest(mJSContext); if (mContextPopRequired) { XPCJSContextStack* stack = mThreadData->GetJSContextStack(); NS_ASSERTION(stack, "bad!"); if (stack) { #ifdef DEBUG JSContext* poppedCX; nsresult rv = stack->Pop(&poppedCX); NS_ASSERTION(NS_SUCCEEDED(rv) && poppedCX == mJSContext, "bad pop"); #else (void) stack->Pop(nsnull); #endif } } if (mJSContext) { if (mDestroyJSContextInDestructor) { #ifdef DEBUG_xpc_hacker printf("!xpc - doing deferred destruction of JSContext @ %p\n", mJSContext); #endif NS_ASSERTION(!mThreadData->GetJSContextStack() || !mThreadData->GetJSContextStack()-> DEBUG_StackHasJSContext(mJSContext), "JSContext still in threadjscontextstack!"); JS_DestroyContext(mJSContext); } } #ifdef DEBUG for (PRUint32 i = 0; i < XPCCCX_STRING_CACHE_SIZE; ++i) { NS_ASSERTION(!mScratchStrings[i].mInUse, "Uh, string wrapper still in use!"); } #endif if (shouldReleaseXPC && mXPC) NS_RELEASE(mXPC); }
nsresult nsKeygenFormProcessor::GetPublicKey(const nsAString& aValue, const nsAString& aChallenge, const nsAFlatString& aKeyType, nsAString& aOutPublicKey, const nsAString& aKeyParams) { nsNSSShutDownPreventionLock locker; if (isAlreadyShutDown()) { return NS_ERROR_NOT_AVAILABLE; } nsresult rv = NS_ERROR_FAILURE; UniquePORTString keystring; char *keyparamsString = nullptr; uint32_t keyGenMechanism; PK11SlotInfo *slot = nullptr; PK11RSAGenParams rsaParams; SECOidTag algTag; int keysize = 0; void *params = nullptr; SECKEYPrivateKey *privateKey = nullptr; SECKEYPublicKey *publicKey = nullptr; CERTSubjectPublicKeyInfo *spkInfo = nullptr; SECStatus srv = SECFailure; SECItem spkiItem; SECItem pkacItem; SECItem signedItem; CERTPublicKeyAndChallenge pkac; pkac.challenge.data = nullptr; nsCOMPtr<nsIGeneratingKeypairInfoDialogs> dialogs; nsKeygenThread *KeygenRunnable = 0; nsCOMPtr<nsIKeygenThread> runnable; // permanent and sensitive flags for keygen PK11AttrFlags attrFlags = PK11_ATTR_TOKEN | PK11_ATTR_SENSITIVE | PK11_ATTR_PRIVATE; UniquePLArenaPool arena(PORT_NewArena(DER_DEFAULT_CHUNKSIZE)); if (!arena) { goto loser; } // Get the key size // for (size_t i = 0; i < number_of_key_size_choices; ++i) { if (aValue.Equals(mSECKeySizeChoiceList[i].name)) { keysize = mSECKeySizeChoiceList[i].size; break; } } if (!keysize) { goto loser; } // Set the keygen mechanism if (aKeyType.IsEmpty() || aKeyType.LowerCaseEqualsLiteral("rsa")) { keyGenMechanism = CKM_RSA_PKCS_KEY_PAIR_GEN; } else if (aKeyType.LowerCaseEqualsLiteral("ec")) { keyparamsString = ToNewCString(aKeyParams); if (!keyparamsString) { rv = NS_ERROR_OUT_OF_MEMORY; goto loser; } keyGenMechanism = CKM_EC_KEY_PAIR_GEN; /* ecParams are initialized later */ } else { goto loser; } // Get the slot rv = GetSlot(keyGenMechanism, &slot); if (NS_FAILED(rv)) { goto loser; } switch (keyGenMechanism) { case CKM_RSA_PKCS_KEY_PAIR_GEN: rsaParams.keySizeInBits = keysize; rsaParams.pe = DEFAULT_RSA_KEYGEN_PE; algTag = DEFAULT_RSA_KEYGEN_ALG; params = &rsaParams; break; case CKM_EC_KEY_PAIR_GEN: /* XXX We ought to rethink how the KEYGEN tag is * displayed. The pulldown selections presented * to the user must depend on the keytype. * The displayed selection could be picked * from the keyparams attribute (this is currently called * the pqg attribute). * For now, we pick ecparams from the keyparams field * if it specifies a valid supported curve, or else * we pick one of secp384r1, secp256r1 or secp192r1 * respectively depending on the user's selection * (High, Medium, Low). * (RSA uses RSA-2048, RSA-1024 and RSA-512 for historical * reasons, while ECC choices represent a stronger mapping) * NOTE: The user's selection * is silently ignored when a valid curve is presented * in keyparams. */ if ((params = decode_ec_params(keyparamsString)) == nullptr) { /* The keyparams attribute did not specify a valid * curve name so use a curve based on the keysize. * NOTE: Here keysize is used only as an indication of * High/Medium/Low strength; elliptic curve * cryptography uses smaller keys than RSA to provide * equivalent security. */ switch (keysize) { case 2048: params = decode_ec_params("secp384r1"); break; case 1024: case 512: params = decode_ec_params("secp256r1"); break; } } /* XXX The signature algorithm ought to choose the hashing * algorithm based on key size once ECDSA variations based * on SHA256 SHA384 and SHA512 are standardized. */ algTag = SEC_OID_ANSIX962_ECDSA_SIGNATURE_WITH_SHA1_DIGEST; break; default: goto loser; } /* Make sure token is initialized. */ rv = setPassword(slot, m_ctx, locker); if (NS_FAILED(rv)) goto loser; srv = PK11_Authenticate(slot, true, m_ctx); if (srv != SECSuccess) { goto loser; } rv = getNSSDialogs(getter_AddRefs(dialogs), NS_GET_IID(nsIGeneratingKeypairInfoDialogs), NS_GENERATINGKEYPAIRINFODIALOGS_CONTRACTID); if (NS_SUCCEEDED(rv)) { KeygenRunnable = new nsKeygenThread(); NS_IF_ADDREF(KeygenRunnable); } if (NS_FAILED(rv) || !KeygenRunnable) { rv = NS_OK; privateKey = PK11_GenerateKeyPairWithFlags(slot, keyGenMechanism, params, &publicKey, attrFlags, m_ctx); } else { KeygenRunnable->SetParams( slot, attrFlags, nullptr, 0, keyGenMechanism, params, m_ctx ); runnable = do_QueryInterface(KeygenRunnable); if (runnable) { rv = dialogs->DisplayGeneratingKeypairInfo(m_ctx, runnable); // We call join on the thread so we can be sure that no // simultaneous access to the passed parameters will happen. KeygenRunnable->Join(); if (NS_SUCCEEDED(rv)) { PK11SlotInfo *used_slot = nullptr; rv = KeygenRunnable->ConsumeResult(&used_slot, &privateKey, &publicKey); if (NS_SUCCEEDED(rv) && used_slot) { PK11_FreeSlot(used_slot); } } } } if (NS_FAILED(rv) || !privateKey) { goto loser; } // just in case we'll need to authenticate to the db -jp // privateKey->wincx = m_ctx; /* * Create a subject public key info from the public key. */ spkInfo = SECKEY_CreateSubjectPublicKeyInfo(publicKey); if ( !spkInfo ) { goto loser; } /* * Now DER encode the whole subjectPublicKeyInfo. */ srv = DER_Encode(arena.get(), &spkiItem, CERTSubjectPublicKeyInfoTemplate, spkInfo); if (srv != SECSuccess) { goto loser; } /* * set up the PublicKeyAndChallenge data structure, then DER encode it */ pkac.spki = spkiItem; pkac.challenge.len = aChallenge.Length(); pkac.challenge.data = (unsigned char *)ToNewCString(aChallenge); if (!pkac.challenge.data) { rv = NS_ERROR_OUT_OF_MEMORY; goto loser; } srv = DER_Encode(arena.get(), &pkacItem, CERTPublicKeyAndChallengeTemplate, &pkac); if (srv != SECSuccess) { goto loser; } /* * now sign the DER encoded PublicKeyAndChallenge */ srv = SEC_DerSignData(arena.get(), &signedItem, pkacItem.data, pkacItem.len, privateKey, algTag); if (srv != SECSuccess) { goto loser; } /* * Convert the signed public key and challenge into base64/ascii. */ keystring = UniquePORTString( BTOA_DataToAscii(signedItem.data, signedItem.len)); if (!keystring) { rv = NS_ERROR_OUT_OF_MEMORY; goto loser; } CopyASCIItoUTF16(keystring.get(), aOutPublicKey); rv = NS_OK; GatherKeygenTelemetry(keyGenMechanism, keysize, keyparamsString); loser: if (srv != SECSuccess) { if ( privateKey ) { PK11_DestroyTokenObject(privateKey->pkcs11Slot,privateKey->pkcs11ID); } if ( publicKey ) { PK11_DestroyTokenObject(publicKey->pkcs11Slot,publicKey->pkcs11ID); } } if ( spkInfo ) { SECKEY_DestroySubjectPublicKeyInfo(spkInfo); } if ( publicKey ) { SECKEY_DestroyPublicKey(publicKey); } if ( privateKey ) { SECKEY_DestroyPrivateKey(privateKey); } if (slot) { PK11_FreeSlot(slot); } if (KeygenRunnable) { NS_RELEASE(KeygenRunnable); } if (keyparamsString) { free(keyparamsString); } if (pkac.challenge.data) { free(pkac.challenge.data); } // If params is non-null and doesn't point to rsaParams, it was allocated // in decode_ec_params. We have to free this memory. if (params && params != &rsaParams) { SECITEM_FreeItem(static_cast<SECItem*>(params), true); params = nullptr; } return rv; }
bool OutlookSettings::DoImport(nsIMsgAccount **aAccount) { nsCOMPtr<nsIWindowsRegKey> key; nsresult rv = OutlookSettings::FindAccountsKey(getter_AddRefs(key)); if (NS_FAILED(rv)) { IMPORT_LOG0("*** Error finding Outlook registry account keys\n"); return false; } nsCOMPtr<nsIMsgAccountManager> accMgr = do_GetService(NS_MSGACCOUNTMANAGER_CONTRACTID, &rv); if (NS_FAILED(rv)) { IMPORT_LOG0("*** Failed to create a account manager!\n"); return false; } nsAutoString defMailName; rv = GetDefaultMailAccountName(defMailName); uint32_t childCount; key->GetChildCount(&childCount); uint32_t accounts = 0; uint32_t popCount = 0; for (uint32_t i = 0; i < childCount; i++) { nsAutoString keyName; key->GetChildName(i, keyName); nsCOMPtr<nsIWindowsRegKey> subKey; rv = key->OpenChild(keyName, nsIWindowsRegKey::ACCESS_QUERY_VALUE, getter_AddRefs(subKey)); if (NS_FAILED(rv)) continue; // Get the values for this account. nsAutoCString nativeKeyName; NS_CopyUnicodeToNative(keyName, nativeKeyName); IMPORT_LOG1("Opened Outlook account: %s\n", nativeKeyName.get()); nsCOMPtr<nsIMsgAccount> account; nsAutoString value; rv = subKey->ReadStringValue(NS_LITERAL_STRING("IMAP Server"), value); if (NS_SUCCEEDED(rv) && DoIMAPServer(accMgr, subKey, value, getter_AddRefs(account))) accounts++; rv = subKey->ReadStringValue(NS_LITERAL_STRING("POP3 Server"), value); if (NS_SUCCEEDED(rv) && DoPOP3Server(accMgr, subKey, value, getter_AddRefs(account))) { popCount++; accounts++; if (aAccount && account) { // If we created a mail account, get rid of it since // we have 2 POP accounts! if (popCount > 1) NS_RELEASE(*aAccount); else NS_ADDREF(*aAccount = account); } } // Is this the default account? if (account && keyName.Equals(defMailName)) accMgr->SetDefaultAccount(account); } // Now save the new acct info to pref file. rv = accMgr->SaveAccountInfo(); NS_ASSERTION(NS_SUCCEEDED(rv), "Can't save account info to pref file"); return accounts != 0; }
nsAppShellWindowEnumerator::~nsAppShellWindowEnumerator() { mWindowMediator->RemoveEnumerator(this); NS_RELEASE(mWindowMediator); }
void nsHttpTransaction::Close(nsresult reason) { LOG(("nsHttpTransaction::Close [this=%x reason=%x]\n", this, reason)); NS_ASSERTION(PR_GetCurrentThread() == gSocketThread, "wrong thread"); if (mClosed) { LOG((" already closed\n")); return; } mTimings.responseEnd = mozilla::TimeStamp::Now(); if (mActivityDistributor) { // report the reponse is complete if not already reported if (!mResponseIsComplete) mActivityDistributor->ObserveActivity( mChannel, NS_HTTP_ACTIVITY_TYPE_HTTP_TRANSACTION, NS_HTTP_ACTIVITY_SUBTYPE_RESPONSE_COMPLETE, PR_Now(), static_cast<PRUint64>(mContentRead), EmptyCString()); // report that this transaction is closing mActivityDistributor->ObserveActivity( mChannel, NS_HTTP_ACTIVITY_TYPE_HTTP_TRANSACTION, NS_HTTP_ACTIVITY_SUBTYPE_TRANSACTION_CLOSE, PR_Now(), LL_ZERO, EmptyCString()); } // we must no longer reference the connection! find out if the // connection was being reused before letting it go. PRBool connReused = PR_FALSE; if (mConnection) connReused = mConnection->IsReused(); mConnected = PR_FALSE; // // if the connection was reset or closed before we wrote any part of the // request or if we wrote the request but didn't receive any part of the // response and the connection was being reused, then we can (and really // should) assume that we wrote to a stale connection and we must therefore // repeat the request over a new connection. // // NOTE: the conditions under which we will automatically retry the HTTP // request have to be carefully selected to avoid duplication of the // request from the point-of-view of the server. such duplication could // have dire consequences including repeated purchases, etc. // // NOTE: because of the way SSL proxy CONNECT is implemented, it is // possible that the transaction may have received data without having // sent any data. for this reason, mSendData == FALSE does not imply // mReceivedData == FALSE. (see bug 203057 for more info.) // if (reason == NS_ERROR_NET_RESET || reason == NS_OK) { if (!mReceivedData && (!mSentData || connReused)) { // if restarting fails, then we must proceed to close the pipe, // which will notify the channel that the transaction failed. if (NS_SUCCEEDED(Restart())) return; } } PRBool relConn = PR_TRUE; if (NS_SUCCEEDED(reason)) { // the server has not sent the final \r\n terminating the header // section, and there may still be a header line unparsed. let's make // sure we parse the remaining header line, and then hopefully, the // response will be usable (see bug 88792). related to that, we may // also have an empty response containing no headers. we should treat // that as an empty HTTP/0.9 response (see bug 300613). if (!mHaveAllHeaders) { char data = '\n'; PRUint32 unused; ParseHead(&data, 1, &unused); } // honor the sticky connection flag... if (mCaps & NS_HTTP_STICKY_CONNECTION) relConn = PR_FALSE; } if (relConn && mConnection) NS_RELEASE(mConnection); mStatus = reason; mTransactionDone = PR_TRUE; // forcibly flag the transaction as complete mClosed = PR_TRUE; // release some resources that we no longer need mRequestStream = nsnull; mReqHeaderBuf.Truncate(); mLineBuf.Truncate(); if (mChunkedDecoder) { delete mChunkedDecoder; mChunkedDecoder = nsnull; } // closing this pipe triggers the channel's OnStopRequest method. mPipeOut->CloseWithStatus(reason); }
PRBool nsEudoraWin32::ImportSettings( nsIFile *pIniFile, nsIMsgAccount **localMailAccount) { PRBool result = PR_FALSE; nsresult rv; nsCOMPtr<nsIMsgAccountManager> accMgr = do_GetService(NS_MSGACCOUNTMANAGER_CONTRACTID, &rv); if (NS_FAILED(rv)) { IMPORT_LOG0( "*** Failed to create a account manager!\n"); return( PR_FALSE); } // Eudora info is arranged by key, 1 for the default, then persona's for additional // accounts. // Start with the first one, then do each persona nsCString iniPath; pIniFile->GetNativePath(iniPath); if (iniPath.IsEmpty()) return( PR_FALSE); UINT valInt; SimpleBufferTonyRCopiedOnce section; DWORD sSize; DWORD sOffset = 0; DWORD start; nsCString sectionName("Settings"); int popCount = 0; int accounts = 0; DWORD allocSize = 0; do { allocSize += 2048; section.Allocate( allocSize); sSize = ::GetPrivateProfileSection( "Personalities", section.m_pBuffer, allocSize, iniPath.get()); } while (sSize == (allocSize - 2)); nsIMsgAccount * pAccount; do { if (!sectionName.IsEmpty()) { pAccount = nsnull; valInt = ::GetPrivateProfileInt( sectionName.get(), "UsesPOP", 1, iniPath.get()); if (valInt) { // This is a POP account if (BuildPOPAccount( accMgr, sectionName.get(), iniPath.get(), &pAccount)) { accounts++; popCount++; if (popCount > 1) { if (localMailAccount && *localMailAccount) { NS_RELEASE( *localMailAccount); *localMailAccount = nsnull; } } else { if (localMailAccount) { *localMailAccount = pAccount; NS_IF_ADDREF( pAccount); } } } } else { valInt = ::GetPrivateProfileInt( sectionName.get(), "UsesIMAP", 0, iniPath.get()); if (valInt) { // This is an IMAP account if (BuildIMAPAccount( accMgr, sectionName.get(), iniPath.get(), &pAccount)) accounts++; } } if (pAccount && (sOffset == 0)) accMgr->SetDefaultAccount( pAccount); NS_IF_RELEASE( pAccount); } sectionName.Truncate(); while ((sOffset < sSize) && (section.m_pBuffer[sOffset] != '=')) sOffset++; sOffset++; start = sOffset; while ((sOffset < sSize) && (section.m_pBuffer[sOffset] != 0)) sOffset++; if (sOffset > start) { sectionName.Append( section.m_pBuffer + start, sOffset - start); sectionName.Trim( kWhitespace); } } while (sOffset < sSize); // Now save the new acct info to pref file. rv = accMgr->SaveAccountInfo(); NS_ASSERTION(NS_SUCCEEDED(rv), "Can't save account info to pref file"); return( accounts != 0); }
nsXPIDLPlugin::~nsXPIDLPlugin() { NS_RELEASE( plugin ); }
nsresult done() { NS_RELEASE(ccMan); return NS_OK; }
NS_IMETHODIMP nsCertPicker::PickByUsage(nsIInterfaceRequestor *ctx, const PRUnichar *selectedNickname, PRInt32 certUsage, bool allowInvalid, bool allowDuplicateNicknames, bool *canceled, nsIX509Cert **_retval) { nsNSSShutDownPreventionLock locker; PRInt32 selectedIndex = -1; bool selectionFound = false; PRUnichar **certNicknameList = nsnull; PRUnichar **certDetailsList = nsnull; CERTCertListNode* node = nsnull; nsresult rv = NS_OK; { // Iterate over all certs. This assures that user is logged in to all hardware tokens. CERTCertList *allcerts = nsnull; nsCOMPtr<nsIInterfaceRequestor> ctx = new PipUIContext(); allcerts = PK11_ListCerts(PK11CertListUnique, ctx); CERT_DestroyCertList(allcerts); } /* find all user certs that are valid and for SSL */ /* note that we are allowing expired certs in this list */ CERTCertList *certList = CERT_FindUserCertsByUsage(CERT_GetDefaultCertDB(), (SECCertUsage)certUsage, !allowDuplicateNicknames, !allowInvalid, ctx); CERTCertListCleaner clc(certList); if (!certList) { return NS_ERROR_NOT_AVAILABLE; } CERTCertNicknames *nicknames = getNSSCertNicknamesFromCertList(certList); CERTCertNicknamesCleaner cnc(nicknames); if (!nicknames) { return NS_ERROR_NOT_AVAILABLE; } certNicknameList = (PRUnichar **)nsMemory::Alloc(sizeof(PRUnichar *) * nicknames->numnicknames); certDetailsList = (PRUnichar **)nsMemory::Alloc(sizeof(PRUnichar *) * nicknames->numnicknames); if (!certNicknameList || !certDetailsList) { nsMemory::Free(certNicknameList); nsMemory::Free(certDetailsList); return NS_ERROR_OUT_OF_MEMORY; } PRInt32 CertsToUse; for (CertsToUse = 0, node = CERT_LIST_HEAD(certList); !CERT_LIST_END(node, certList) && CertsToUse < nicknames->numnicknames; node = CERT_LIST_NEXT(node) ) { nsNSSCertificate *tempCert = nsNSSCertificate::Create(node->cert); if (tempCert) { // XXX we really should be using an nsCOMPtr instead of manually add-refing, // but nsNSSCertificate does not have a default constructor. NS_ADDREF(tempCert); nsAutoString i_nickname(NS_ConvertUTF8toUTF16(nicknames->nicknames[CertsToUse])); nsAutoString nickWithSerial; nsAutoString details; if (!selectionFound) { if (i_nickname == nsDependentString(selectedNickname)) { selectedIndex = CertsToUse; selectionFound = true; } } if (NS_SUCCEEDED(tempCert->FormatUIStrings(i_nickname, nickWithSerial, details))) { certNicknameList[CertsToUse] = ToNewUnicode(nickWithSerial); certDetailsList[CertsToUse] = ToNewUnicode(details); } else { certNicknameList[CertsToUse] = nsnull; certDetailsList[CertsToUse] = nsnull; } NS_RELEASE(tempCert); ++CertsToUse; } } if (CertsToUse) { nsICertPickDialogs *dialogs = nsnull; rv = getNSSDialogs((void**)&dialogs, NS_GET_IID(nsICertPickDialogs), NS_CERTPICKDIALOGS_CONTRACTID); if (NS_SUCCEEDED(rv)) { nsPSMUITracker tracker; if (tracker.isUIForbidden()) { rv = NS_ERROR_NOT_AVAILABLE; } else { /* Throw up the cert picker dialog and get back the index of the selected cert */ rv = dialogs->PickCertificate(ctx, (const PRUnichar**)certNicknameList, (const PRUnichar**)certDetailsList, CertsToUse, &selectedIndex, canceled); } NS_RELEASE(dialogs); } } PRInt32 i; for (i = 0; i < CertsToUse; ++i) { nsMemory::Free(certNicknameList[i]); nsMemory::Free(certDetailsList[i]); } nsMemory::Free(certNicknameList); nsMemory::Free(certDetailsList); if (!CertsToUse) { return NS_ERROR_NOT_AVAILABLE; } if (NS_SUCCEEDED(rv) && !*canceled) { for (i = 0, node = CERT_LIST_HEAD(certList); !CERT_LIST_END(node, certList); ++i, node = CERT_LIST_NEXT(node)) { if (i == selectedIndex) { nsNSSCertificate *cert = nsNSSCertificate::Create(node->cert); if (!cert) { rv = NS_ERROR_OUT_OF_MEMORY; break; } nsIX509Cert *x509 = 0; nsresult rv = cert->QueryInterface(NS_GET_IID(nsIX509Cert), (void**)&x509); if (NS_FAILED(rv)) { break; } NS_ADDREF(x509); *_retval = x509; NS_RELEASE(cert); break; } } } return rv; }
nsresult txExecutionState::getVariable(PRInt32 aNamespace, nsIAtom* aLName, txAExprResult*& aResult) { nsresult rv = NS_OK; txExpandedName name(aNamespace, aLName); // look for a local variable if (mLocalVariables) { mLocalVariables->getVariable(name, &aResult); if (aResult) { return NS_OK; } } // look for an evaluated global variable mGlobalVariableValues.getVariable(name, &aResult); if (aResult) { if (aResult == mGlobalVarPlaceholderValue) { // XXX ErrorReport: cyclic variable-value NS_RELEASE(aResult); return NS_ERROR_XSLT_BAD_RECURSION; } return NS_OK; } // Is there perchance a global variable not evaluated yet? txStylesheet::GlobalVariable* var = mStylesheet->getGlobalVariable(name); if (!var) { // XXX ErrorReport: variable doesn't exist in this scope return NS_ERROR_FAILURE; } NS_ASSERTION(var->mExpr && !var->mFirstInstruction || !var->mExpr && var->mFirstInstruction, "global variable should have either instruction or expression"); // Is this a stylesheet parameter that has a value? if (var->mIsParam && mGlobalParams) { txIGlobalParameter* param = mGlobalParams->get(name); if (param) { rv = param->getValue(&aResult); NS_ENSURE_SUCCESS(rv, rv); rv = mGlobalVariableValues.bindVariable(name, aResult); if (NS_FAILED(rv)) { NS_RELEASE(aResult); return rv; } return NS_OK; } } // Insert a placeholdervalue to protect against recursion rv = mGlobalVariableValues.bindVariable(name, mGlobalVarPlaceholderValue); NS_ENSURE_SUCCESS(rv, rv); // evaluate the global variable pushEvalContext(mInitialEvalContext); if (var->mExpr) { txVariableMap* oldVars = mLocalVariables; mLocalVariables = nsnull; rv = var->mExpr->evaluate(getEvalContext(), &aResult); mLocalVariables = oldVars; NS_ENSURE_SUCCESS(rv, rv); } else { nsAutoPtr<txRtfHandler> rtfHandler(new txRtfHandler); NS_ENSURE_TRUE(rtfHandler, NS_ERROR_OUT_OF_MEMORY); rv = pushResultHandler(rtfHandler); NS_ENSURE_SUCCESS(rv, rv); rtfHandler.forget(); txInstruction* prevInstr = mNextInstruction; // set return to nsnull to stop execution mNextInstruction = nsnull; rv = runTemplate(var->mFirstInstruction); NS_ENSURE_SUCCESS(rv, rv); pushTemplateRule(nsnull, txExpandedName(), nsnull); rv = txXSLTProcessor::execute(*this); NS_ENSURE_SUCCESS(rv, rv); popTemplateRule(); mNextInstruction = prevInstr; rtfHandler = (txRtfHandler*)popResultHandler(); rv = rtfHandler->getAsRTF(&aResult); NS_ENSURE_SUCCESS(rv, rv); } popEvalContext(); // Remove the placeholder and insert the calculated value mGlobalVariableValues.removeVariable(name); rv = mGlobalVariableValues.bindVariable(name, aResult); if (NS_FAILED(rv)) { NS_RELEASE(aResult); return rv; } return NS_OK; }
PrepareAndDispatch(uint32 methodIndex, nsXPTCStubBase* self, PRUint32* args) { #define PARAM_BUFFER_COUNT 16 nsXPTCMiniVariant paramBuffer[PARAM_BUFFER_COUNT]; nsXPTCMiniVariant* dispatchParams = NULL; nsIInterfaceInfo* iface_info = NULL; const nsXPTMethodInfo* info = NULL; PRUint8 paramCount; PRUint8 i; nsresult result = NS_ERROR_FAILURE; NS_ASSERTION(self,"no self"); self->GetInterfaceInfo(&iface_info); NS_ASSERTION(iface_info,"no interface info"); iface_info->GetMethodInfo(PRUint16(methodIndex), &info); NS_ASSERTION(info,"no interface info"); #ifdef VBOX if (!info) return result; #endif paramCount = info->GetParamCount(); // setup variant array pointer if(paramCount > PARAM_BUFFER_COUNT) dispatchParams = new nsXPTCMiniVariant[paramCount]; else dispatchParams = paramBuffer; NS_ASSERTION(dispatchParams,"no place for params"); PRUint32* ap = args; for(i = 0; i < paramCount; i++, ap++) { const nsXPTParamInfo& param = info->GetParam(i); const nsXPTType& type = param.GetType(); nsXPTCMiniVariant* dp = &dispatchParams[i]; if(param.IsOut() || !type.IsArithmetic()) { dp->val.p = (void*) *ap; continue; } // else dp->val.p = (void*) *ap; switch(type) { case nsXPTType::T_I64 : dp->val.i64 = *((PRInt64*) ap); ap++; break; case nsXPTType::T_U64 : dp->val.u64 = *((PRUint64*)ap); ap++; break; case nsXPTType::T_DOUBLE : dp->val.d = *((double*) ap); ap++; break; } } result = self->CallMethod((PRUint16)methodIndex, info, dispatchParams); NS_RELEASE(iface_info); if(dispatchParams != paramBuffer) delete [] dispatchParams; return result; }
void nsIOThreadPool::ThreadFunc(void *arg) { nsIOThreadPool *pool = (nsIOThreadPool *) arg; LOG(("entering ThreadFunc\n")); { nsAutoLock lock(pool->mLock); for (;;) { PRIntervalTime start = PR_IntervalNow(), timeout = IDLE_TIMEOUT; // // wait for one or more of the following to occur: // (1) the event queue has an event to process // (2) the shutdown flag has been set // (3) the thread has been idle for too long // // PR_WaitCondVar will return when any of these conditions is true. // while (PR_CLIST_IS_EMPTY(&pool->mEventQ) && !pool->mShutdown) { pool->mNumIdleThreads++; PR_WaitCondVar(pool->mIdleThreadCV, timeout); pool->mNumIdleThreads--; PRIntervalTime delta = PR_IntervalNow() - start; if (delta >= timeout) break; timeout -= delta; start += delta; } // if the queue is still empty, then kill this thread (either we // are shutting down or the thread exceeded the idle timeout)... if (PR_CLIST_IS_EMPTY(&pool->mEventQ)) break; // handle one event at a time: we don't want this one thread to hog // all the events while other threads may be able to help out ;-) do { PLEvent *event = PLEVENT_FROM_LINK(PR_LIST_HEAD(&pool->mEventQ)); PR_REMOVE_AND_INIT_LINK(&event->link); LOG(("event:%p\n", event)); // release lock! lock.unlock(); PL_HandleEvent(event); lock.lock(); } while (!PR_CLIST_IS_EMPTY(&pool->mEventQ)); } // thread is going away... pool->mNumThreads--; PR_NotifyCondVar(pool->mExitThreadCV); } // release our reference to the pool NS_RELEASE(pool); LOG(("leaving ThreadFunc\n")); }
static nsresult PrepareAndDispatch(nsXPTCStubBase* self, uint32 methodIndex, PRUint64* args) { const PRUint8 PARAM_BUFFER_COUNT = 16; const PRUint8 NUM_ARG_REGS = 6-1; // -1 for "this" pointer nsXPTCMiniVariant paramBuffer[PARAM_BUFFER_COUNT]; nsXPTCMiniVariant* dispatchParams = NULL; nsIInterfaceInfo* iface_info = NULL; const nsXPTMethodInfo* info; PRUint8 paramCount; PRUint8 i; nsresult result = NS_ERROR_FAILURE; NS_ASSERTION(self,"no self"); self->GetInterfaceInfo(&iface_info); NS_ASSERTION(iface_info,"no interface info"); iface_info->GetMethodInfo(PRUint16(methodIndex), &info); NS_ASSERTION(info,"no interface info"); paramCount = info->GetParamCount(); // setup variant array pointer if(paramCount > PARAM_BUFFER_COUNT) dispatchParams = new nsXPTCMiniVariant[paramCount]; else dispatchParams = paramBuffer; NS_ASSERTION(dispatchParams,"no place for params"); // args[0] to args[NUM_ARG_REGS] hold floating point register values PRUint64* ap = args + NUM_ARG_REGS; for(i = 0; i < paramCount; i++, ap++) { const nsXPTParamInfo& param = info->GetParam(i); const nsXPTType& type = param.GetType(); nsXPTCMiniVariant* dp = &dispatchParams[i]; if(param.IsOut() || !type.IsArithmetic()) { dp->val.p = (void*) *ap; continue; } // else switch(type) { case nsXPTType::T_I8 : dp->val.i8 = (PRInt8) *ap; break; case nsXPTType::T_I16 : dp->val.i16 = (PRInt16) *ap; break; case nsXPTType::T_I32 : dp->val.i32 = (PRInt32) *ap; break; case nsXPTType::T_I64 : dp->val.i64 = (PRInt64) *ap; break; case nsXPTType::T_U8 : dp->val.u8 = (PRUint8) *ap; break; case nsXPTType::T_U16 : dp->val.u16 = (PRUint16) *ap; break; case nsXPTType::T_U32 : dp->val.u32 = (PRUint32) *ap; break; case nsXPTType::T_U64 : dp->val.u64 = (PRUint64) *ap; break; case nsXPTType::T_FLOAT : if(i < NUM_ARG_REGS) { // floats passed via registers are stored as doubles // in the first NUM_ARG_REGS entries in args dp->val.u64 = (PRUint64) args[i]; dp->val.f = (float) dp->val.d; // convert double to float } else dp->val.u32 = (PRUint32) *ap; break; case nsXPTType::T_DOUBLE : // doubles passed via registers are also stored // in the first NUM_ARG_REGS entries in args dp->val.u64 = (i < NUM_ARG_REGS) ? args[i] : *ap; break; case nsXPTType::T_BOOL : dp->val.b = (PRBool) *ap; break; case nsXPTType::T_CHAR : dp->val.c = (char) *ap; break; case nsXPTType::T_WCHAR : dp->val.wc = (PRUnichar) *ap; break; default: NS_ASSERTION(0, "bad type"); break; } } result = self->CallMethod((PRUint16)methodIndex, info, dispatchParams); NS_RELEASE(iface_info); if(dispatchParams != paramBuffer) delete [] dispatchParams; return result; }
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); }
// add SOCKS IO layer to an existing socket nsresult nsSOCKSIOLayerAddToSocket(PRInt32 family, const char *host, PRInt32 port, const char *proxyHost, PRInt32 proxyPort, PRInt32 socksVersion, PRUint32 flags, PRFileDesc *fd, nsISupports** info) { NS_ENSURE_TRUE((socksVersion == 4) || (socksVersion == 5), NS_ERROR_NOT_INITIALIZED); if (firstTime) { //XXX hack until NSPR provides an official way to detect system IPv6 // support (bug 388519) PRFileDesc *tmpfd = PR_OpenTCPSocket(PR_AF_INET6); if (!tmpfd) { ipv6Supported = false; } else { // If the system does not support IPv6, NSPR will push // IPv6-to-IPv4 emulation layer onto the native layer ipv6Supported = PR_GetIdentitiesLayer(tmpfd, PR_NSPR_IO_LAYER) == tmpfd; PR_Close(tmpfd); } nsSOCKSIOLayerIdentity = PR_GetUniqueIdentity("SOCKS layer"); nsSOCKSIOLayerMethods = *PR_GetDefaultIOMethods(); nsSOCKSIOLayerMethods.connect = nsSOCKSIOLayerConnect; nsSOCKSIOLayerMethods.connectcontinue = nsSOCKSIOLayerConnectContinue; nsSOCKSIOLayerMethods.poll = nsSOCKSIOLayerPoll; nsSOCKSIOLayerMethods.bind = nsSOCKSIOLayerBind; nsSOCKSIOLayerMethods.acceptread = nsSOCKSIOLayerAcceptRead; nsSOCKSIOLayerMethods.getsockname = nsSOCKSIOLayerGetName; nsSOCKSIOLayerMethods.getpeername = nsSOCKSIOLayerGetPeerName; nsSOCKSIOLayerMethods.accept = nsSOCKSIOLayerAccept; nsSOCKSIOLayerMethods.listen = nsSOCKSIOLayerListen; nsSOCKSIOLayerMethods.close = nsSOCKSIOLayerClose; firstTime = false; #if defined(PR_LOGGING) gSOCKSLog = PR_NewLogModule("SOCKS"); #endif } LOGDEBUG(("Entering nsSOCKSIOLayerAddToSocket().")); PRFileDesc * layer; PRStatus rv; layer = PR_CreateIOLayerStub(nsSOCKSIOLayerIdentity, &nsSOCKSIOLayerMethods); if (! layer) { LOGERROR(("PR_CreateIOLayerStub() failed.")); return NS_ERROR_FAILURE; } nsSOCKSSocketInfo * infoObject = new nsSOCKSSocketInfo(); if (!infoObject) { // clean up IOLayerStub LOGERROR(("Failed to create nsSOCKSSocketInfo().")); PR_DELETE(layer); return NS_ERROR_FAILURE; } NS_ADDREF(infoObject); infoObject->Init(socksVersion, family, proxyHost, proxyPort, host, flags); layer->secret = (PRFilePrivate*) infoObject; rv = PR_PushIOLayer(fd, PR_GetLayersIdentity(fd), layer); if (NS_FAILED(rv)) { LOGERROR(("PR_PushIOLayer() failed. rv = %x.", rv)); NS_RELEASE(infoObject); PR_DELETE(layer); return NS_ERROR_FAILURE; } *info = static_cast<nsISOCKSSocketInfo*>(infoObject); NS_ADDREF(*info); return NS_OK; }
nsWFSecureEnv::~nsWFSecureEnv(void) { OJI_LOG("nsWFSecureEnv::~nsWFSecureEnv"); NS_RELEASE(m_jvm); }
extern "C" nsresult PrepareAndDispatch(nsXPTCStubBase* self, PRUint32 methodIndex, PRUint32* args, PRUint32 *gprData, double *fprData) { nsXPTCMiniVariant paramBuffer[PARAM_BUFFER_COUNT]; nsXPTCMiniVariant* dispatchParams = NULL; nsIInterfaceInfo* iface_info = NULL; const nsXPTMethodInfo* info; PRUint32 paramCount; PRUint32 i; nsresult result = NS_ERROR_FAILURE; NS_ASSERTION(self,"no self"); self->GetInterfaceInfo(&iface_info); NS_ASSERTION(iface_info,"no interface info"); if (! iface_info) return NS_ERROR_UNEXPECTED; iface_info->GetMethodInfo(PRUint16(methodIndex), &info); NS_ASSERTION(info,"no method info"); if (! info) return NS_ERROR_UNEXPECTED; paramCount = info->GetParamCount(); // setup variant array pointer if(paramCount > PARAM_BUFFER_COUNT) dispatchParams = new nsXPTCMiniVariant[paramCount]; else dispatchParams = paramBuffer; NS_ASSERTION(dispatchParams,"no place for params"); if (! dispatchParams) return NS_ERROR_OUT_OF_MEMORY; PRUint32* ap = args; PRUint32 gpr = 1; // skip one GPR register PRUint32 fpr = 0; PRUint32 tempu32; PRUint64 tempu64; for(i = 0; i < paramCount; i++) { const nsXPTParamInfo& param = info->GetParam(i); const nsXPTType& type = param.GetType(); nsXPTCMiniVariant* dp = &dispatchParams[i]; if (!param.IsOut() && type == nsXPTType::T_DOUBLE) { if (fpr < FPR_COUNT) dp->val.d = fprData[fpr++]; else { if ((PRUint32) ap & 4) ap++; // doubles are 8-byte aligned on stack dp->val.d = *(double*) ap; ap += 2; if (gpr < GPR_COUNT) gpr += 2; } continue; } else if (!param.IsOut() && type == nsXPTType::T_FLOAT) { if (fpr < FPR_COUNT) dp->val.f = (float) fprData[fpr++]; // in registers floats are passed as doubles else { dp->val.f = *(float*) ap; ap += 1; if (gpr < GPR_COUNT) gpr += 1; } continue; } else if (!param.IsOut() && (type == nsXPTType::T_I64 || type == nsXPTType::T_U64)) { if (gpr & 1) gpr++; // longlongs are aligned in odd/even register pairs, eg. r5/r6 if ((gpr + 1) < GPR_COUNT) { tempu64 = *(PRUint64*) &gprData[gpr]; gpr += 2; } else { if ((PRUint32) ap & 4) ap++; // longlongs are 8-byte aligned on stack tempu64 = *(PRUint64*) ap; ap += 2; } } else { if (gpr < GPR_COUNT) tempu32 = gprData[gpr++]; else tempu32 = *ap++; } if(param.IsOut() || !type.IsArithmetic()) { dp->val.p = (void*) tempu32; continue; } switch(type) { case nsXPTType::T_I8: dp->val.i8 = (PRInt8) tempu32; break; case nsXPTType::T_I16: dp->val.i16 = (PRInt16) tempu32; break; case nsXPTType::T_I32: dp->val.i32 = (PRInt32) tempu32; break; case nsXPTType::T_I64: dp->val.i64 = (PRInt64) tempu64; break; case nsXPTType::T_U8: dp->val.u8 = (PRUint8) tempu32; break; case nsXPTType::T_U16: dp->val.u16 = (PRUint16) tempu32; break; case nsXPTType::T_U32: dp->val.u32 = (PRUint32) tempu32; break; case nsXPTType::T_U64: dp->val.u64 = (PRUint64) tempu64; break; case nsXPTType::T_BOOL: dp->val.b = (bool) tempu32; break; case nsXPTType::T_CHAR: dp->val.c = (char) tempu32; break; case nsXPTType::T_WCHAR: dp->val.wc = (wchar_t) tempu32; break; default: NS_ERROR("bad type"); break; } } result = self->CallMethod((PRUint16) methodIndex, info, dispatchParams); NS_RELEASE(iface_info); if (dispatchParams != paramBuffer) delete [] dispatchParams; return result; }
nsresult nsRDFXMLSerializer::SerializeContainer(nsIOutputStream* aStream, nsIRDFResource* aContainer) { nsresult rv; nsCAutoString tag; // Decide if it's a sequence, bag, or alternation, and print the // appropriate tag-open sequence if (IsA(mDataSource, aContainer, kRDF_Bag)) { tag.AssignLiteral("RDF:Bag"); } else if (IsA(mDataSource, aContainer, kRDF_Seq)) { tag.AssignLiteral("RDF:Seq"); } else if (IsA(mDataSource, aContainer, kRDF_Alt)) { tag.AssignLiteral("RDF:Alt"); } else { NS_ASSERTION(PR_FALSE, "huh? this is _not_ a container."); return NS_ERROR_UNEXPECTED; } rv = rdf_BlockingWrite(aStream, " <", 3); if (NS_FAILED(rv)) return rv; rv = rdf_BlockingWrite(aStream, tag); if (NS_FAILED(rv)) return rv; // Unfortunately, we always need to print out the identity of the // resource, even if was constructed "anonymously". We need to do // this because we never really know who else might be referring // to it... nsCAutoString uri; if (NS_SUCCEEDED(aContainer->GetValueUTF8(uri))) { rdf_MakeRelativeRef(mBaseURLSpec, uri); rdf_EscapeAttributeValue(uri); if (uri.First() == '#') { // Okay, it's actually identified as an element in the // current document, not trying to decorate some absolute // URI. We can use the 'ID=' attribute... uri.Cut(0, 1); // chop the '#' rv = rdf_BlockingWrite(aStream, kIDAttr, sizeof(kIDAttr) - 1); if (NS_FAILED(rv)) return rv; } else { // We need to cheat and spit out an illegal 'about=' on // the sequence. rv = rdf_BlockingWrite(aStream, kAboutAttr, sizeof(kAboutAttr) - 1); if (NS_FAILED(rv)) return rv; } rv = rdf_BlockingWrite(aStream, uri); if (NS_FAILED(rv)) return rv; rv = rdf_BlockingWrite(aStream, "\"", 1); if (NS_FAILED(rv)) return rv; } rv = rdf_BlockingWrite(aStream, ">\n", 2); if (NS_FAILED(rv)) return rv; // First iterate through each of the ordinal elements (the RDF/XML // syntax doesn't allow us to place properties on RDF container // elements). nsCOMPtr<nsISimpleEnumerator> elements; rv = NS_NewContainerEnumerator(mDataSource, aContainer, getter_AddRefs(elements)); if (NS_SUCCEEDED(rv)) { while (1) { PRBool hasMore; rv = elements->HasMoreElements(&hasMore); if (NS_FAILED(rv)) break; if (! hasMore) break; nsCOMPtr<nsISupports> isupports; elements->GetNext(getter_AddRefs(isupports)); nsCOMPtr<nsIRDFNode> element = do_QueryInterface(isupports); NS_ASSERTION(element != nsnull, "not an nsIRDFNode"); if (! element) continue; SerializeMember(aStream, aContainer, element); } } // close the container tag rv = rdf_BlockingWrite(aStream, " </", 4); if (NS_FAILED(rv)) return rv; tag.Append(">\n", 2); rv = rdf_BlockingWrite(aStream, tag); if (NS_FAILED(rv)) return rv; // Now, we iterate through _all_ of the arcs, in case someone has // applied properties to the bag itself. These'll be placed in a // separate RDF:Description element. nsCOMPtr<nsISimpleEnumerator> arcs; mDataSource->ArcLabelsOut(aContainer, getter_AddRefs(arcs)); PRBool wroteDescription = PR_FALSE; while (! wroteDescription) { PRBool hasMore = PR_FALSE; rv = arcs->HasMoreElements(&hasMore); if (NS_FAILED(rv)) break; if (! hasMore) break; nsIRDFResource* property; rv = arcs->GetNext((nsISupports**) &property); if (NS_FAILED(rv)) break; // If it's a membership property, then output a "LI" // tag. Otherwise, output a property. if (! IsContainerProperty(property)) { rv = SerializeDescription(aStream, aContainer); wroteDescription = PR_TRUE; } NS_RELEASE(property); if (NS_FAILED(rv)) break; } return NS_OK; }
nsMsgThreadEnumerator::~nsMsgThreadEnumerator() { NS_RELEASE(mThread); }