void ChromiumCDMProxy::Init(PromiseId aPromiseId, const nsAString& aOrigin, const nsAString& aTopLevelOrigin, const nsAString& aGMPName) { MOZ_ASSERT(NS_IsMainThread()); NS_ENSURE_TRUE_VOID(!mKeys.IsNull()); EME_LOG( "ChromiumCDMProxy::Init (pid=%u, origin=%s, topLevelOrigin=%s, gmp=%s)", aPromiseId, NS_ConvertUTF16toUTF8(aOrigin).get(), NS_ConvertUTF16toUTF8(aTopLevelOrigin).get(), NS_ConvertUTF16toUTF8(aGMPName).get()); if (!mGMPThread) { RejectPromise( aPromiseId, NS_ERROR_DOM_INVALID_STATE_ERR, NS_LITERAL_CSTRING("Couldn't get GMP thread ChromiumCDMProxy::Init")); return; } if (aGMPName.IsEmpty()) { RejectPromise(aPromiseId, NS_ERROR_DOM_INVALID_STATE_ERR, nsPrintfCString("Unknown GMP for keysystem '%s'", NS_ConvertUTF16toUTF8(mKeySystem).get())); return; } gmp::NodeId nodeId(aOrigin, aTopLevelOrigin, aGMPName); RefPtr<AbstractThread> thread = mGMPThread; RefPtr<GMPCrashHelper> helper(mCrashHelper); RefPtr<ChromiumCDMProxy> self(this); nsCString keySystem = NS_ConvertUTF16toUTF8(mKeySystem); RefPtr<Runnable> task(NS_NewRunnableFunction( [self, nodeId, helper, aPromiseId, thread, keySystem]() -> void { MOZ_ASSERT(self->IsOnOwnerThread()); RefPtr<gmp::GeckoMediaPluginService> service = gmp::GeckoMediaPluginService::GetGeckoMediaPluginService(); if (!service) { self->RejectPromise( aPromiseId, NS_ERROR_DOM_INVALID_STATE_ERR, NS_LITERAL_CSTRING( "Couldn't get GeckoMediaPluginService in ChromiumCDMProxy::Init")); return; } RefPtr<gmp::GetCDMParentPromise> promise = service->GetCDM(nodeId, { keySystem }, helper); promise->Then( thread, __func__, [self, aPromiseId](RefPtr<gmp::ChromiumCDMParent> cdm) { if (!cdm->Init(self, self->mDistinctiveIdentifierRequired, self->mPersistentStateRequired)) { self->RejectPromise(aPromiseId, NS_ERROR_FAILURE, NS_LITERAL_CSTRING("GetCDM failed.")); return; } { MutexAutoLock lock(self->mCDMMutex); self->mCDM = cdm; } self->OnCDMCreated(aPromiseId); }, [self, aPromiseId](nsresult rv) { self->RejectPromise( aPromiseId, NS_ERROR_FAILURE, NS_LITERAL_CSTRING("GetCDM failed.")); }); })); mGMPThread->Dispatch(task.forget()); }
void nsXFormsXPathParser::OutputSubExpression(PRInt32 aOffset, PRInt32 aEndOffset) { const nsDependentSubstring expr = Substring(mScanner.Expression(), aOffset, aEndOffset - aOffset); printf("%s\n", NS_ConvertUTF16toUTF8(expr).get()); }
nsresult UDPSocket::InitLocal(const nsAString& aLocalAddress, const uint16_t& aLocalPort) { nsresult rv; nsCOMPtr<nsIUDPSocket> sock = do_CreateInstance("@mozilla.org/network/udp-socket;1", &rv); if (NS_FAILED(rv)) { return rv; } if (aLocalAddress.IsEmpty()) { rv = sock->Init(aLocalPort, /* loopback = */ false, mAddressReuse, /* optionalArgc = */ 1); } else { PRNetAddr prAddr; PR_InitializeNetAddr(PR_IpAddrAny, aLocalPort, &prAddr); PR_StringToNetAddr(NS_ConvertUTF16toUTF8(aLocalAddress).BeginReading(), &prAddr); mozilla::net::NetAddr addr; PRNetAddrToNetAddr(&prAddr, &addr); rv = sock->InitWithAddress(&addr, mAddressReuse, /* optionalArgc = */ 1); } if (NS_FAILED(rv)) { return rv; } rv = sock->SetMulticastLoopback(mLoopback); if (NS_FAILED(rv)) { return rv; } mSocket = sock; // Get real local address and local port nsCOMPtr<nsINetAddr> localAddr; rv = mSocket->GetLocalAddr(getter_AddRefs(localAddr)); if (NS_FAILED(rv)) { return rv; } nsCString localAddress; rv = localAddr->GetAddress(localAddress); if (NS_FAILED(rv)) { return rv; } mLocalAddress = NS_ConvertUTF8toUTF16(localAddress); uint16_t localPort; rv = localAddr->GetPort(&localPort); if (NS_FAILED(rv)) { return rv; } mLocalPort.SetValue(localPort); mListenerProxy = new ListenerProxy(this); rv = mSocket->AsyncListen(mListenerProxy); if (NS_FAILED(rv)) { return rv; } mReadyState = SocketReadyState::Open; rv = DoPendingMcastCommand(); if (NS_FAILED(rv)) { return rv; } mOpened->MaybeResolve(JS::UndefinedHandleValue); return NS_OK; }
NS_IMETHODIMP WebBrowserChrome::HandleEvent(nsIDOMEvent* aEvent) { NS_ENSURE_TRUE(mListener, NS_ERROR_FAILURE); nsString type; if (aEvent) { aEvent->GetType(type); } LOGT("Event:'%s'", NS_ConvertUTF16toUTF8(type).get()); nsCOMPtr<nsIDOMWindow> docWin = do_GetInterface(mWebBrowser); nsCOMPtr<nsPIDOMWindow> window = do_GetInterface(mWebBrowser); nsCOMPtr<nsIDOMWindowUtils> utils = do_GetInterface(window); if (type.EqualsLiteral(MOZ_MozScrolledAreaChanged)) { nsCOMPtr<nsIDOMEventTarget> origTarget; aEvent->GetOriginalTarget(getter_AddRefs(origTarget)); nsCOMPtr<nsIDOMDocument> ctDoc = do_QueryInterface(origTarget); nsCOMPtr<nsIDOMWindow> targetWin; ctDoc->GetDefaultView(getter_AddRefs(targetWin)); nsCOMPtr<nsIDOMWindow> docWin = do_GetInterface(mWebBrowser); if (targetWin != docWin) { return NS_OK; // We are only interested in root scroll pane changes } // Adjust width and height from the incoming event properties so that we // ignore changes to width and height contributed by growth in page // quadrants other than x > 0 && y > 0. nsIntPoint scrollOffset = GetScrollOffset(docWin); nsCOMPtr<nsIDOMScrollAreaEvent> scrollEvent = do_QueryInterface(aEvent); float evX, evY, evW, evH; scrollEvent->GetX(&evX); scrollEvent->GetY(&evY); scrollEvent->GetWidth(&evW); scrollEvent->GetHeight(&evH); float x = evX + scrollOffset.x; float y = evY + scrollOffset.y; uint32_t width = evW + (x < 0 ? x : 0); uint32_t height = evH + (y < 0 ? y : 0); mListener->OnScrolledAreaChanged(width, height); nsCOMPtr<nsIDOMEventTarget> target = do_QueryInterface(window->GetChromeEventHandler()); target->AddEventListener(NS_LITERAL_STRING(MOZ_AFTER_PAINT_LITERAL), this, PR_FALSE); } else if (type.EqualsLiteral("pagehide")) { mScrollOffset = nsIntPoint(); } else if (type.EqualsLiteral(MOZ_AFTER_PAINT_LITERAL)) { nsCOMPtr<nsPIDOMWindow> pidomWindow = do_QueryInterface(docWin); nsCOMPtr<nsIDOMEventTarget> target = do_QueryInterface(pidomWindow->GetChromeEventHandler()); target->RemoveEventListener(NS_LITERAL_STRING(MOZ_AFTER_PAINT_LITERAL), this, PR_FALSE); if (mFirstPaint) { mListener->OnUpdateDisplayPort(); return NS_OK; } mFirstPaint = true; nsIntPoint offset = GetScrollOffset(docWin); mListener->OnFirstPaint(offset.x, offset.y); } else if (type.EqualsLiteral(MOZ_scroll)) { nsCOMPtr<nsIDOMEventTarget> target; aEvent->GetTarget(getter_AddRefs(target)); nsCOMPtr<nsIDOMDocument> eventDoc = do_QueryInterface(target); nsCOMPtr<nsIDOMWindow> docWin = do_GetInterface(mWebBrowser); nsCOMPtr<nsIDOMDocument> ctDoc; docWin->GetDocument(getter_AddRefs(ctDoc)); if (eventDoc != ctDoc) { return NS_OK; } SendScroll(); } return NS_OK; }
already_AddRefed<nsMIMEInfoWin> nsOSHelperAppService::GetByExtension(const nsAFlatString& aFileExt, const char *aTypeHint) { if (aFileExt.IsEmpty()) return nsnull; // windows registry assumes your file extension is going to include the '.'. // so make sure it's there... nsAutoString fileExtToUse; if (aFileExt.First() != PRUnichar('.')) fileExtToUse = PRUnichar('.'); fileExtToUse.Append(aFileExt); // Try to get an entry from the windows registry. nsCOMPtr<nsIWindowsRegKey> regKey = do_CreateInstance("@mozilla.org/windows-registry-key;1"); if (!regKey) return nsnull; nsresult rv = regKey->Open(nsIWindowsRegKey::ROOT_KEY_CLASSES_ROOT, fileExtToUse, nsIWindowsRegKey::ACCESS_QUERY_VALUE); if (NS_FAILED(rv)) return nsnull; nsCAutoString typeToUse; if (aTypeHint && *aTypeHint) { typeToUse.Assign(aTypeHint); } else { nsAutoString temp; if (NS_FAILED(regKey->ReadStringValue(NS_LITERAL_STRING("Content Type"), temp)) || temp.IsEmpty()) { return nsnull; } // Content-Type is always in ASCII LossyAppendUTF16toASCII(temp, typeToUse); } nsMIMEInfoWin* mimeInfo = new nsMIMEInfoWin(typeToUse); if (!mimeInfo) return nsnull; // out of memory NS_ADDREF(mimeInfo); // don't append the '.' mimeInfo->AppendExtension(NS_ConvertUTF16toUTF8(Substring(fileExtToUse, 1))); mimeInfo->SetPreferredAction(nsIMIMEInfo::useSystemDefault); nsAutoString appInfo; bool found; // Retrieve the default application for this extension if (mAppAssoc) { // Vista: use the new application association COM interfaces // for resolving helpers. nsString assocType(fileExtToUse); PRUnichar * pResult = nsnull; HRESULT hr = mAppAssoc->QueryCurrentDefault(assocType.get(), AT_FILEEXTENSION, AL_EFFECTIVE, &pResult); if (SUCCEEDED(hr)) { found = true; appInfo.Assign(pResult); CoTaskMemFree(pResult); } else { found = false; } } else { found = NS_SUCCEEDED(regKey->ReadStringValue(EmptyString(), appInfo)); } // Bug 358297 - ignore the default handler, force the user to choose app if (appInfo.EqualsLiteral("XPSViewer.Document")) found = false; if (!found) { NS_IF_RELEASE(mimeInfo); // we failed to really find an entry in the registry return nsnull; } // Get other nsIMIMEInfo fields from registry, if possible. nsAutoString defaultDescription; nsCOMPtr<nsIFile> defaultApplication; if (NS_FAILED(GetDefaultAppInfo(appInfo, defaultDescription, getter_AddRefs(defaultApplication)))) { NS_IF_RELEASE(mimeInfo); return nsnull; } mimeInfo->SetDefaultDescription(defaultDescription); mimeInfo->SetDefaultApplicationHandler(defaultApplication); // Grab the general description GetMIMEInfoFromRegistry(appInfo, mimeInfo); return mimeInfo; }
nsresult FetchDriver::BasicFetch() { nsAutoCString url; mRequest->GetURL(url); nsCOMPtr<nsIURI> uri; nsresult rv = NS_NewURI(getter_AddRefs(uri), url, nullptr, nullptr); if (NS_WARN_IF(NS_FAILED(rv))) { FailWithNetworkError(); return rv; } nsAutoCString scheme; rv = uri->GetScheme(scheme); if (NS_WARN_IF(NS_FAILED(rv))) { FailWithNetworkError(); return rv; } if (scheme.LowerCaseEqualsLiteral("about")) { if (url.EqualsLiteral("about:blank")) { nsRefPtr<InternalResponse> response = new InternalResponse(200, NS_LITERAL_CSTRING("OK")); ErrorResult result; response->Headers()->Append(NS_LITERAL_CSTRING("content-type"), NS_LITERAL_CSTRING("text/html;charset=utf-8"), result); MOZ_ASSERT(!result.Failed()); nsCOMPtr<nsIInputStream> body; rv = NS_NewCStringInputStream(getter_AddRefs(body), EmptyCString()); if (NS_WARN_IF(NS_FAILED(rv))) { FailWithNetworkError(); return rv; } response->SetBody(body); BeginResponse(response); return SucceedWithResponse(); } return FailWithNetworkError(); } if (scheme.LowerCaseEqualsLiteral("blob")) { nsRefPtr<BlobImpl> blobImpl; rv = NS_GetBlobForBlobURI(uri, getter_AddRefs(blobImpl)); BlobImpl* blob = static_cast<BlobImpl*>(blobImpl.get()); if (NS_WARN_IF(NS_FAILED(rv))) { FailWithNetworkError(); return rv; } nsRefPtr<InternalResponse> response = new InternalResponse(200, NS_LITERAL_CSTRING("OK")); ErrorResult result; uint64_t size = blob->GetSize(result); if (NS_WARN_IF(result.Failed())) { FailWithNetworkError(); return result.StealNSResult(); } nsAutoString sizeStr; sizeStr.AppendInt(size); response->Headers()->Append(NS_LITERAL_CSTRING("Content-Length"), NS_ConvertUTF16toUTF8(sizeStr), result); if (NS_WARN_IF(result.Failed())) { FailWithNetworkError(); return result.StealNSResult(); } nsAutoString type; blob->GetType(type); response->Headers()->Append(NS_LITERAL_CSTRING("Content-Type"), NS_ConvertUTF16toUTF8(type), result); if (NS_WARN_IF(result.Failed())) { FailWithNetworkError(); return result.StealNSResult(); } nsCOMPtr<nsIInputStream> stream; blob->GetInternalStream(getter_AddRefs(stream), result); if (NS_WARN_IF(result.Failed())) { FailWithNetworkError(); return result.StealNSResult(); } response->SetBody(stream); BeginResponse(response); return SucceedWithResponse(); } if (scheme.LowerCaseEqualsLiteral("data")) { nsAutoCString method; mRequest->GetMethod(method); if (method.LowerCaseEqualsASCII("get")) { nsresult rv; nsCOMPtr<nsIProtocolHandler> dataHandler = do_GetService(NS_NETWORK_PROTOCOL_CONTRACTID_PREFIX "data", &rv); if (NS_WARN_IF(NS_FAILED(rv))) { return FailWithNetworkError(); } nsCOMPtr<nsIChannel> channel; rv = dataHandler->NewChannel(uri, getter_AddRefs(channel)); if (NS_WARN_IF(NS_FAILED(rv))) { return FailWithNetworkError(); } nsCOMPtr<nsIInputStream> stream; rv = channel->Open(getter_AddRefs(stream)); if (NS_WARN_IF(NS_FAILED(rv))) { return FailWithNetworkError(); } // nsDataChannel will parse the data URI when it is Open()ed and set the // correct content type and charset. nsAutoCString contentType; if (NS_SUCCEEDED(channel->GetContentType(contentType))) { nsAutoCString charset; if (NS_SUCCEEDED(channel->GetContentCharset(charset)) && !charset.IsEmpty()) { contentType.AppendLiteral(";charset="); contentType.Append(charset); } } else { NS_WARNING("Could not get content type from data channel"); } nsRefPtr<InternalResponse> response = new InternalResponse(200, NS_LITERAL_CSTRING("OK")); ErrorResult result; response->Headers()->Append(NS_LITERAL_CSTRING("Content-Type"), contentType, result); if (NS_WARN_IF(result.Failed())) { FailWithNetworkError(); return result.StealNSResult(); } response->SetBody(stream); BeginResponse(response); return SucceedWithResponse(); } return FailWithNetworkError(); } if (scheme.LowerCaseEqualsLiteral("http") || scheme.LowerCaseEqualsLiteral("https") || scheme.LowerCaseEqualsLiteral("app")) { return HttpFetch(); } return FailWithNetworkError(); }
/** Parses e.g. "a(href,title)" (but not several tags at once). */ nsresult mozSanitizingHTMLSerializer::ParseTagPref(const nsCAutoString& tagpref) { nsIParserService* parserService = nsContentUtils::GetParserService(); if (!parserService) return NS_ERROR_OUT_OF_MEMORY; // Parsing tag PRInt32 bracket = tagpref.FindChar('('); if (bracket == 0) { printf(" malformed pref: %s\n", tagpref.get()); return NS_ERROR_CANNOT_CONVERT_DATA; } nsAutoString tag; CopyUTF8toUTF16(StringHead(tagpref, bracket), tag); // Create key PRInt32 tag_id = parserService->HTMLStringTagToId(tag); if (tag_id == eHTMLTag_userdefined) { printf(" unknown tag <%s>, won't add.\n", NS_ConvertUTF16toUTF8(tag).get()); return NS_ERROR_CANNOT_CONVERT_DATA; } nsPRUint32Key tag_key(tag_id); if (mAllowedTags.Exists(&tag_key)) { printf(" duplicate tag: %s\n", NS_ConvertUTF16toUTF8(tag).get()); return NS_ERROR_CANNOT_CONVERT_DATA; } if (bracket == kNotFound) /* There are no attributes in the pref. So, allow none; only the tag itself */ { mAllowedTags.Put(&tag_key, 0); } else { // Attributes // where is the macro for non-fatal errors in opt builds? if(tagpref[tagpref.Length() - 1] != ')' || tagpref.Length() < PRUint32(bracket) + 3) { printf(" malformed pref: %s\n", tagpref.get()); return NS_ERROR_CANNOT_CONVERT_DATA; } nsCOMPtr<nsIProperties> attr_bag = do_CreateInstance(NS_PROPERTIES_CONTRACTID); NS_ENSURE_TRUE(attr_bag, NS_ERROR_INVALID_POINTER); nsCAutoString attrList; attrList.Append(Substring(tagpref, bracket + 1, tagpref.Length() - 2 - bracket)); char* attrs_lasts; for (char* iAttr = PL_strtok_r(attrList.BeginWriting(), ",", &attrs_lasts); iAttr; iAttr = PL_strtok_r(NULL, ",", &attrs_lasts)) { attr_bag->Set(iAttr, 0); } nsIProperties* attr_bag_raw = attr_bag; NS_ADDREF(attr_bag_raw); mAllowedTags.Put(&tag_key, attr_bag_raw); } return NS_OK; }
NS_IMETHODIMP DOMStorageObserver::Observe(nsISupports* aSubject, const char* aTopic, const char16_t* aData) { nsresult rv; // Start the thread that opens the database. if (!strcmp(aTopic, kStartupTopic)) { nsCOMPtr<nsIObserverService> obs = mozilla::services::GetObserverService(); obs->RemoveObserver(this, kStartupTopic); mDBThreadStartDelayTimer = do_CreateInstance(NS_TIMER_CONTRACTID); if (!mDBThreadStartDelayTimer) { return NS_ERROR_UNEXPECTED; } mDBThreadStartDelayTimer->Init(this, nsITimer::TYPE_ONE_SHOT, kStartupDelay); return NS_OK; } // Timer callback used to start the database a short timer after startup if (!strcmp(aTopic, NS_TIMER_CALLBACK_TOPIC)) { nsCOMPtr<nsITimer> timer = do_QueryInterface(aSubject); if (!timer) { return NS_ERROR_UNEXPECTED; } if (timer == mDBThreadStartDelayTimer) { mDBThreadStartDelayTimer = nullptr; DOMStorageDBBridge* db = DOMStorageCache::StartDatabase(); NS_ENSURE_TRUE(db, NS_ERROR_FAILURE); } return NS_OK; } // Clear everything, caches + database if (!strcmp(aTopic, "cookie-changed")) { if (!NS_LITERAL_STRING("cleared").Equals(aData)) { return NS_OK; } DOMStorageDBBridge* db = DOMStorageCache::StartDatabase(); NS_ENSURE_TRUE(db, NS_ERROR_FAILURE); db->AsyncClearAll(); Notify("cookie-cleared"); return NS_OK; } // Clear from caches everything that has been stored // while in session-only mode if (!strcmp(aTopic, "perm-changed")) { // Check for cookie permission change nsCOMPtr<nsIPermission> perm(do_QueryInterface(aSubject)); if (!perm) { return NS_OK; } nsAutoCString type; perm->GetType(type); if (type != NS_LITERAL_CSTRING("cookie")) { return NS_OK; } uint32_t cap = 0; perm->GetCapability(&cap); if (!(cap & nsICookiePermission::ACCESS_SESSION) || !NS_LITERAL_STRING("deleted").Equals(nsDependentString(aData))) { return NS_OK; } nsCOMPtr<nsIPrincipal> principal; perm->GetPrincipal(getter_AddRefs(principal)); if (!principal) { return NS_OK; } nsAutoCString originSuffix; BasePrincipal::Cast(principal)->OriginAttributesRef().CreateSuffix(originSuffix); nsCOMPtr<nsIURI> origin; principal->GetURI(getter_AddRefs(origin)); if (!origin) { return NS_OK; } nsAutoCString host; origin->GetHost(host); if (host.IsEmpty()) { return NS_OK; } nsAutoCString originScope; rv = CreateReversedDomain(host, originScope); NS_ENSURE_SUCCESS(rv, rv); Notify("session-only-cleared", NS_ConvertUTF8toUTF16(originSuffix), originScope); return NS_OK; } // Clear everything (including so and pb data) from caches and database // for the gived domain and subdomains. if (!strcmp(aTopic, "browser:purge-domain-data")) { // Convert the domain name to the ACE format nsAutoCString aceDomain; nsCOMPtr<nsIIDNService> converter = do_GetService(NS_IDNSERVICE_CONTRACTID); if (converter) { rv = converter->ConvertUTF8toACE(NS_ConvertUTF16toUTF8(aData), aceDomain); NS_ENSURE_SUCCESS(rv, rv); } else { // In case the IDN service is not available, this is the best we can come up with! rv = NS_EscapeURL(NS_ConvertUTF16toUTF8(aData), esc_OnlyNonASCII | esc_AlwaysCopy, aceDomain, fallible); NS_ENSURE_SUCCESS(rv, rv); } nsAutoCString originScope; rv = CreateReversedDomain(aceDomain, originScope); NS_ENSURE_SUCCESS(rv, rv); DOMStorageDBBridge* db = DOMStorageCache::StartDatabase(); NS_ENSURE_TRUE(db, NS_ERROR_FAILURE); db->AsyncClearMatchingOrigin(originScope); Notify("domain-data-cleared", EmptyString(), originScope); return NS_OK; } // Clear all private-browsing caches if (!strcmp(aTopic, "last-pb-context-exited")) { Notify("private-browsing-data-cleared"); return NS_OK; } // Clear data of the origins whose prefixes will match the suffix. if (!strcmp(aTopic, "clear-origin-attributes-data")) { OriginAttributesPattern pattern; if (!pattern.Init(nsDependentString(aData))) { NS_ERROR("Cannot parse origin attributes pattern"); return NS_ERROR_FAILURE; } DOMStorageDBBridge* db = DOMStorageCache::StartDatabase(); NS_ENSURE_TRUE(db, NS_ERROR_FAILURE); db->AsyncClearMatchingOriginAttributes(pattern); Notify("origin-attr-pattern-cleared", nsDependentString(aData)); return NS_OK; } if (!strcmp(aTopic, "profile-after-change")) { Notify("profile-change"); return NS_OK; } if (!strcmp(aTopic, "profile-before-change") || !strcmp(aTopic, "xpcom-shutdown")) { rv = DOMStorageCache::StopDatabase(); if (NS_FAILED(rv)) { NS_WARNING("Error while stopping DOMStorage DB background thread"); } return NS_OK; } if (!strcmp(aTopic, "disk-space-watcher")) { if (NS_LITERAL_STRING("full").Equals(aData)) { Notify("low-disk-space"); } else if (NS_LITERAL_STRING("free").Equals(aData)) { Notify("no-low-disk-space"); } return NS_OK; } #ifdef DOM_STORAGE_TESTS if (!strcmp(aTopic, "domstorage-test-flush-force")) { DOMStorageDBBridge* db = DOMStorageCache::GetDatabase(); if (db) { db->AsyncFlush(); } return NS_OK; } if (!strcmp(aTopic, "domstorage-test-flushed")) { // Only used to propagate to IPC children Notify("test-flushed"); return NS_OK; } if (!strcmp(aTopic, "domstorage-test-reload")) { Notify("test-reload"); return NS_OK; } #endif NS_ERROR("Unexpected topic"); return NS_ERROR_UNEXPECTED; }
NS_IMETHODIMP nsHostObjectProtocolHandler::NewChannel(nsIURI* uri, nsIChannel* *result) { *result = nullptr; nsCString spec; uri->GetSpec(spec); DataInfo* info = GetDataInfo(spec); if (!info) { return NS_ERROR_DOM_BAD_URI; } nsCOMPtr<nsIDOMBlob> blob = do_QueryInterface(info->mObject); nsCOMPtr<mozilla::dom::MediaSource> mediasource = do_QueryInterface(info->mObject); if (!blob && !mediasource) { return NS_ERROR_DOM_BAD_URI; } #ifdef DEBUG { nsCOMPtr<nsIURIWithPrincipal> uriPrinc = do_QueryInterface(uri); nsCOMPtr<nsIPrincipal> principal; uriPrinc->GetPrincipal(getter_AddRefs(principal)); NS_ASSERTION(info->mPrincipal == principal, "Wrong principal!"); } #endif nsCOMPtr<nsIInputStream> stream; nsresult rv = NS_OK; if (blob) { rv = blob->GetInternalStream(getter_AddRefs(stream)); } else { stream = mediasource->CreateInternalStream(); } NS_ENSURE_SUCCESS(rv, rv); nsCOMPtr<nsIChannel> channel; rv = NS_NewInputStreamChannel(getter_AddRefs(channel), uri, stream); NS_ENSURE_SUCCESS(rv, rv); nsCOMPtr<nsISupports> owner = do_QueryInterface(info->mPrincipal); nsString type; if (blob) { rv = blob->GetType(type); NS_ENSURE_SUCCESS(rv, rv); uint64_t size; rv = blob->GetSize(&size); NS_ENSURE_SUCCESS(rv, rv); nsCOMPtr<nsIDOMFile> file = do_QueryInterface(info->mObject); if (file) { nsString filename; rv = file->GetName(filename); NS_ENSURE_SUCCESS(rv, rv); channel->SetContentDispositionFilename(filename); } channel->SetContentLength(size); } else { type = mediasource->GetType(); } channel->SetOwner(owner); channel->SetOriginalURI(uri); channel->SetContentType(NS_ConvertUTF16toUTF8(type)); channel.forget(result); return NS_OK; }
NS_IMETHODIMP nsXULTemplateQueryProcessorStorage::CompileQuery(nsIXULTemplateBuilder* aBuilder, nsIDOMNode* aQueryNode, nsIAtom* aRefVariable, nsIAtom* aMemberVariable, nsISupports** aReturn) { nsCOMPtr<nsIDOMNodeList> childNodes; aQueryNode->GetChildNodes(getter_AddRefs(childNodes)); uint32_t length; childNodes->GetLength(&length); nsCOMPtr<mozIStorageStatement> statement; nsCOMPtr<nsIContent> queryContent = do_QueryInterface(aQueryNode); nsAutoString sqlQuery; // Let's get all text nodes (which should be the query) if (!nsContentUtils::GetNodeTextContent(queryContent, false, sqlQuery, fallible)) { return NS_ERROR_OUT_OF_MEMORY; } nsresult rv = mStorageConnection->CreateStatement(NS_ConvertUTF16toUTF8(sqlQuery), getter_AddRefs(statement)); if (NS_FAILED(rv)) { nsXULContentUtils::LogTemplateError(ERROR_TEMPLATE_STORAGE_BAD_QUERY); return rv; } uint32_t parameterCount = 0; for (nsIContent* child = queryContent->GetFirstChild(); child; child = child->GetNextSibling()) { if (child->NodeInfo()->Equals(nsGkAtoms::param, kNameSpaceID_XUL)) { nsAutoString value; if (!nsContentUtils::GetNodeTextContent(child, false, value, fallible)) { return NS_ERROR_OUT_OF_MEMORY; } uint32_t index = parameterCount; nsAutoString name, indexValue; if (child->GetAttr(kNameSpaceID_None, nsGkAtoms::name, name)) { rv = statement->GetParameterIndex(NS_ConvertUTF16toUTF8(name), &index); if (NS_FAILED(rv)) { nsXULContentUtils::LogTemplateError(ERROR_TEMPLATE_STORAGE_UNKNOWN_QUERY_PARAMETER); return rv; } parameterCount++; } else if (child->GetAttr(kNameSpaceID_None, nsGkAtoms::index, indexValue)) { PR_sscanf(NS_ConvertUTF16toUTF8(indexValue).get(),"%d",&index); if (index > 0) index--; } else { parameterCount++; } static nsIContent::AttrValuesArray sTypeValues[] = { &nsGkAtoms::int32, &nsGkAtoms::integer, &nsGkAtoms::int64, &nsGkAtoms::null, &nsGkAtoms::double_, &nsGkAtoms::string, nullptr }; int32_t typeError = 1; int32_t typeValue = child->FindAttrValueIn(kNameSpaceID_None, nsGkAtoms::type, sTypeValues, eCaseMatters); rv = NS_ERROR_ILLEGAL_VALUE; int32_t valInt32 = 0; int64_t valInt64 = 0; double valFloat = 0; switch (typeValue) { case 0: case 1: typeError = PR_sscanf(NS_ConvertUTF16toUTF8(value).get(),"%d",&valInt32); if (typeError > 0) rv = statement->BindInt32ByIndex(index, valInt32); break; case 2: typeError = PR_sscanf(NS_ConvertUTF16toUTF8(value).get(),"%lld",&valInt64); if (typeError > 0) rv = statement->BindInt64ByIndex(index, valInt64); break; case 3: rv = statement->BindNullByIndex(index); break; case 4: typeError = PR_sscanf(NS_ConvertUTF16toUTF8(value).get(),"%lf",&valFloat); if (typeError > 0) rv = statement->BindDoubleByIndex(index, valFloat); break; case 5: case nsIContent::ATTR_MISSING: rv = statement->BindStringByIndex(index, value); break; default: typeError = 0; } if (typeError <= 0) { nsXULContentUtils::LogTemplateError(ERROR_TEMPLATE_STORAGE_WRONG_TYPE_QUERY_PARAMETER); return rv; } if (NS_FAILED(rv)) { nsXULContentUtils::LogTemplateError(ERROR_TEMPLATE_STORAGE_QUERY_PARAMETER_NOT_BOUND); return rv; } } } *aReturn = statement; NS_IF_ADDREF(*aReturn); return NS_OK; }
nsresult sbDeviceXMLInfo::Read(nsIDOMDocument* aDeviceXMLInfoDocument) { // Validate arguments. NS_ENSURE_ARG_POINTER(aDeviceXMLInfoDocument); // Function variables. nsresult rv; // Get the list of all device info elements. nsCOMPtr<nsIDOMNodeList> nodeList; rv = aDeviceXMLInfoDocument->GetElementsByTagNameNS (NS_LITERAL_STRING(SB_DEVICE_INFO_NS), NS_LITERAL_STRING("deviceinfo"), getter_AddRefs(nodeList)); NS_ENSURE_SUCCESS(rv, rv); // Search all device info elements for one that matches target device. PRUint32 nodeCount; rv = nodeList->GetLength(&nodeCount); NS_ENSURE_SUCCESS(rv, rv); for (PRUint32 i = 0; i < nodeCount; i++) { // Get the next device info element. nsCOMPtr<nsIDOMNode> node; rv = nodeList->Item(i, getter_AddRefs(node)); NS_ENSURE_SUCCESS(rv, rv); // Use device info node if it matches target device and is // newer than any previous match nsString foundVersion; nsCOMPtr<nsIDOMNode> deviceNode; rv = DeviceMatchesDeviceInfoNode(node, foundVersion, getter_AddRefs(deviceNode)); NS_ENSURE_SUCCESS(rv, rv); if (foundVersion.IsEmpty()) { // Not a match continue; } if (mDeviceInfoVersion.IsEmpty() || NS_CompareVersions( NS_LossyConvertUTF16toASCII(foundVersion).get(), NS_LossyConvertUTF16toASCII(mDeviceInfoVersion).get()) > 0) { // Found version is greater than current version, if any. Keep this // node and replace any previously found node // Log the found device info if logging enabled if (mLogDeviceInfo) { nsCOMPtr<nsIDOMSerializer> serializer = do_CreateInstance("@mozilla.org/xmlextras/xmlserializer;1"); // Translate the found deviceinfo element to XML nsString fullXml(NS_LITERAL_STRING("<ERROR PRINTING deviceinfo NODE>")); if (serializer) { serializer->SerializeToString(node, fullXml); } // Translate the device element matching this device to XML, if any nsString deviceXml(NS_LITERAL_STRING("<ERROR PRINTING device NODE>")); if (deviceNode && serializer) { serializer->SerializeToString(deviceNode, deviceXml); } nsCAutoString curVersUtf8 = NS_ConvertUTF16toUTF8(mDeviceInfoVersion); nsCAutoString foundVersUtf8 = NS_ConvertUTF16toUTF8(foundVersion); // Log the device info and version. The first line has two // alternate forms, depending on whether the existing device // info is being replaced: // // FOUND deviceinfo version <found version>: // - OR - // REPLACED deviceinfo version <current version> with <found version>: Log("%s deviceinfo version %s%s%s:\n%s%s%s", mDeviceInfoElement ? "REPLACED" : "FOUND", curVersUtf8.get(), // current version OR blank mDeviceInfoElement ? " with " : "", foundVersUtf8.get(), // found version OR found version NS_ConvertUTF16toUTF8(fullXml).get(), deviceNode ? "\n\nMATCHING device element:\n" : "", deviceNode ? NS_ConvertUTF16toUTF8(deviceXml).get() : ""); } mDeviceInfoVersion.Assign(foundVersion); mDeviceInfoElement = do_QueryInterface(node, &rv); NS_ENSURE_SUCCESS(rv, rv); if (deviceNode) { mDeviceElement = do_QueryInterface(deviceNode, &rv); NS_ENSURE_SUCCESS(rv, rv); } else { mDeviceElement = nsnull; } } } return NS_OK; }
void BluetoothMapFolder::DumpFolderInfo() { BT_LOGR("Folder name: %s, subfolder counts: %d", NS_ConvertUTF16toUTF8(mName).get(), mSubFolders.Count()); }
nsresult BackgroundFileSaver::ExtractSignatureInfo(const nsAString& filePath) { MOZ_ASSERT(!NS_IsMainThread(), "Cannot extract signature on main thread"); nsNSSShutDownPreventionLock nssLock; if (isAlreadyShutDown()) { return NS_ERROR_NOT_AVAILABLE; } { MutexAutoLock lock(mLock); if (!mSignatureInfoEnabled) { return NS_OK; } } nsresult rv; nsCOMPtr<nsIX509CertDB> certDB = do_GetService(NS_X509CERTDB_CONTRACTID, &rv); NS_ENSURE_SUCCESS(rv, rv); #ifdef XP_WIN // Setup the file to check. WINTRUST_FILE_INFO fileToCheck = {0}; fileToCheck.cbStruct = sizeof(WINTRUST_FILE_INFO); fileToCheck.pcwszFilePath = filePath.Data(); fileToCheck.hFile = nullptr; fileToCheck.pgKnownSubject = nullptr; // We want to check it is signed and trusted. WINTRUST_DATA trustData = {0}; trustData.cbStruct = sizeof(trustData); trustData.pPolicyCallbackData = nullptr; trustData.pSIPClientData = nullptr; trustData.dwUIChoice = WTD_UI_NONE; trustData.fdwRevocationChecks = WTD_REVOKE_NONE; trustData.dwUnionChoice = WTD_CHOICE_FILE; trustData.dwStateAction = WTD_STATEACTION_VERIFY; trustData.hWVTStateData = nullptr; trustData.pwszURLReference = nullptr; // Disallow revocation checks over the network trustData.dwProvFlags = WTD_CACHE_ONLY_URL_RETRIEVAL; // no UI trustData.dwUIContext = 0; trustData.pFile = &fileToCheck; // The WINTRUST_ACTION_GENERIC_VERIFY_V2 policy verifies that the certificate // chains up to a trusted root CA and has appropriate permissions to sign // code. GUID policyGUID = WINTRUST_ACTION_GENERIC_VERIFY_V2; // Check if the file is signed by something that is trusted. If the file is // not signed, this is a no-op. LONG ret = WinVerifyTrust(nullptr, &policyGUID, &trustData); CRYPT_PROVIDER_DATA* cryptoProviderData = nullptr; // According to the Windows documentation, we should check against 0 instead // of ERROR_SUCCESS, which is an HRESULT. if (ret == 0) { cryptoProviderData = WTHelperProvDataFromStateData(trustData.hWVTStateData); } if (cryptoProviderData) { // Lock because signature information is read on the main thread. MutexAutoLock lock(mLock); LOG(("Downloaded trusted and signed file [this = %p].", this)); // A binary may have multiple signers. Each signer may have multiple certs // in the chain. for (DWORD i = 0; i < cryptoProviderData->csSigners; ++i) { const CERT_CHAIN_CONTEXT* certChainContext = cryptoProviderData->pasSigners[i].pChainContext; if (!certChainContext) { break; } for (DWORD j = 0; j < certChainContext->cChain; ++j) { const CERT_SIMPLE_CHAIN* certSimpleChain = certChainContext->rgpChain[j]; if (!certSimpleChain) { break; } nsCOMPtr<nsIX509CertList> nssCertList = do_CreateInstance(NS_X509CERTLIST_CONTRACTID); if (!nssCertList) { break; } bool extractionSuccess = true; for (DWORD k = 0; k < certSimpleChain->cElement; ++k) { CERT_CHAIN_ELEMENT* certChainElement = certSimpleChain->rgpElement[k]; if (certChainElement->pCertContext->dwCertEncodingType != X509_ASN_ENCODING) { continue; } nsCOMPtr<nsIX509Cert> nssCert = nullptr; rv = certDB->ConstructX509( reinterpret_cast<char *>( certChainElement->pCertContext->pbCertEncoded), certChainElement->pCertContext->cbCertEncoded, getter_AddRefs(nssCert)); if (!nssCert) { extractionSuccess = false; LOG(("Couldn't create NSS cert [this = %p]", this)); break; } nssCertList->AddCert(nssCert); nsString subjectName; nssCert->GetSubjectName(subjectName); LOG(("Adding cert %s [this = %p]", NS_ConvertUTF16toUTF8(subjectName).get(), this)); } if (extractionSuccess) { mSignatureInfo.AppendObject(nssCertList); } } } // Free the provider data if cryptoProviderData is not null. trustData.dwStateAction = WTD_STATEACTION_CLOSE; WinVerifyTrust(nullptr, &policyGUID, &trustData); } else { LOG(("Downloaded unsigned or untrusted file [this = %p].", this)); } #endif return NS_OK; }
NS_IMETHODIMP nsDeviceContextSpecOS2::Init(nsIWidget *aWidget, nsIPrintSettings* aPS, PRBool aIsPrintPreview) { nsresult rv = NS_ERROR_FAILURE; mPrintSettings = aPS; NS_ASSERTION(aPS, "Must have a PrintSettings!"); rv = GlobalPrinters::GetInstance()->InitializeGlobalPrinters(); if (NS_FAILED(rv)) { return rv; } if (aPS) { PRBool tofile = PR_FALSE; PRInt32 copies = 1; PRUnichar *printer = nsnull; PRUnichar *printfile = nsnull; mPrintSettings->GetPrinterName(&printer); mPrintSettings->GetToFileName(&printfile); mPrintSettings->GetPrintToFile(&tofile); mPrintSettings->GetNumCopies(&copies); if ((copies == 0) || (copies > 999)) { GlobalPrinters::GetInstance()->FreeGlobalPrinters(); return NS_ERROR_FAILURE; } if (printfile != nsnull) { // ToDo: Use LocalEncoding instead of UTF-8 (see bug 73446) strcpy(mPrData.path, NS_ConvertUTF16toUTF8(printfile).get()); } if (printer != nsnull) strcpy(mPrData.printer, NS_ConvertUTF16toUTF8(printer).get()); if (aIsPrintPreview) mPrData.destination = printPreview; else if (tofile) mPrData.destination = printToFile; else mPrData.destination = printToPrinter; mPrData.copies = copies; rv = GlobalPrinters::GetInstance()->InitializeGlobalPrinters(); if (NS_FAILED(rv)) return rv; const nsAFlatString& printerUCS2 = NS_ConvertUTF8toUTF16(mPrData.printer); ULONG numPrinters = GlobalPrinters::GetInstance()->GetNumPrinters(); if (numPrinters) { for(ULONG i = 0; (i < numPrinters) && !mQueue; i++) { if ((GlobalPrinters::GetInstance()->GetStringAt(i)->Equals(printerUCS2, nsCaseInsensitiveStringComparator()))) { SetupDevModeFromSettings(i, aPS); mQueue = PrnDlg.SetPrinterQueue(i); } } } if (printfile != nsnull) nsMemory::Free(printfile); if (printer != nsnull) nsMemory::Free(printer); } GlobalPrinters::GetInstance()->FreeGlobalPrinters(); return rv; }
nsresult nsXHTMLContentSerializer::EscapeURI(nsIContent* aContent, const nsAString& aURI, nsAString& aEscapedURI) { // URL escape %xx cannot be used in JS. // No escaping if the scheme is 'javascript'. if (IsJavaScript(aContent, nsGkAtoms::href, kNameSpaceID_None, aURI)) { aEscapedURI = aURI; return NS_OK; } // nsITextToSubURI does charset convert plus uri escape // This is needed to convert to a document charset which is needed to support existing browsers. // But we eventually want to use UTF-8 instead of a document charset, then the code would be much simpler. // See HTML 4.01 spec, "Appendix B.2.1 Non-ASCII characters in URI attribute values" nsCOMPtr<nsITextToSubURI> textToSubURI; nsAutoString uri(aURI); // in order to use FindCharInSet() nsresult rv = NS_OK; if (!mCharset.IsEmpty() && !IsASCII(uri)) { textToSubURI = do_GetService(NS_ITEXTTOSUBURI_CONTRACTID, &rv); NS_ENSURE_SUCCESS(rv, rv); } int32_t start = 0; int32_t end; nsAutoString part; nsXPIDLCString escapedURI; aEscapedURI.Truncate(0); // Loop and escape parts by avoiding escaping reserved characters // (and '%', '#', as well as '[' and ']' for IPv6 address literals). while ((end = uri.FindCharInSet("%#;/?:@&=+$,[]", start)) != -1) { part = Substring(aURI, start, (end-start)); if (textToSubURI && !IsASCII(part)) { rv = textToSubURI->ConvertAndEscape(mCharset.get(), part.get(), getter_Copies(escapedURI)); NS_ENSURE_SUCCESS(rv, rv); } else { escapedURI.Adopt(nsEscape(NS_ConvertUTF16toUTF8(part).get(), url_Path)); } AppendASCIItoUTF16(escapedURI, aEscapedURI); // Append a reserved character without escaping. part = Substring(aURI, end, 1); aEscapedURI.Append(part); start = end + 1; } if (start < (int32_t) aURI.Length()) { // Escape the remaining part. part = Substring(aURI, start, aURI.Length()-start); if (textToSubURI) { rv = textToSubURI->ConvertAndEscape(mCharset.get(), part.get(), getter_Copies(escapedURI)); NS_ENSURE_SUCCESS(rv, rv); } else { escapedURI.Adopt(nsEscape(NS_ConvertUTF16toUTF8(part).get(), url_Path)); } AppendASCIItoUTF16(escapedURI, aEscapedURI); } return rv; }
nsresult nsRDFPropertyTestNode::FilterInstantiations(InstantiationSet& aInstantiations, bool* aCantHandleYet) const { nsresult rv; if (aCantHandleYet) *aCantHandleYet = PR_FALSE; nsIRDFDataSource* ds = mProcessor->GetDataSource(); InstantiationSet::Iterator last = aInstantiations.Last(); for (InstantiationSet::Iterator inst = aInstantiations.First(); inst != last; ++inst) { bool hasSourceBinding; nsCOMPtr<nsIRDFResource> sourceRes; if (mSource) { hasSourceBinding = PR_TRUE; sourceRes = mSource; } else { nsCOMPtr<nsIRDFNode> sourceValue; hasSourceBinding = inst->mAssignments.GetAssignmentFor(mSourceVariable, getter_AddRefs(sourceValue)); sourceRes = do_QueryInterface(sourceValue); } bool hasTargetBinding; nsCOMPtr<nsIRDFNode> targetValue; if (mTarget) { hasTargetBinding = PR_TRUE; targetValue = mTarget; } else { hasTargetBinding = inst->mAssignments.GetAssignmentFor(mTargetVariable, getter_AddRefs(targetValue)); } #ifdef PR_LOGGING if (PR_LOG_TEST(gXULTemplateLog, PR_LOG_DEBUG)) { const char* source = "(unbound)"; if (hasSourceBinding) sourceRes->GetValueConst(&source); nsAutoString target(NS_LITERAL_STRING("(unbound)")); if (hasTargetBinding) nsXULContentUtils::GetTextForNode(targetValue, target); PR_LOG(gXULTemplateLog, PR_LOG_DEBUG, ("nsRDFPropertyTestNode[%p]: FilterInstantiations() source=[%s] target=[%s]", this, source, NS_ConvertUTF16toUTF8(target).get())); } #endif if (hasSourceBinding && hasTargetBinding) { // it's a consistency check. see if we have a assignment that is consistent bool hasAssertion; rv = ds->HasAssertion(sourceRes, mProperty, targetValue, PR_TRUE, &hasAssertion); if (NS_FAILED(rv)) return rv; #ifdef PR_LOGGING PR_LOG(gXULTemplateLog, PR_LOG_DEBUG, (" consistency check => %s", hasAssertion ? "passed" : "failed")); #endif if (hasAssertion) { // it's consistent. Element* element = nsRDFPropertyTestNode::Element::Create(sourceRes, mProperty, targetValue); if (! element) return NS_ERROR_OUT_OF_MEMORY; inst->AddSupportingElement(element); } else { // it's inconsistent. remove it. aInstantiations.Erase(inst--); } } else if ((hasSourceBinding && ! hasTargetBinding) || (! hasSourceBinding && hasTargetBinding)) { // it's an open ended query on the source or // target. figure out what matches and add as a // cross-product. nsCOMPtr<nsISimpleEnumerator> results; if (hasSourceBinding) { rv = ds->GetTargets(sourceRes, mProperty, PR_TRUE, getter_AddRefs(results)); } else { rv = ds->GetSources(mProperty, targetValue, PR_TRUE, getter_AddRefs(results)); if (NS_FAILED(rv)) return rv; } while (1) { bool hasMore; rv = results->HasMoreElements(&hasMore); if (NS_FAILED(rv)) return rv; if (! hasMore) break; nsCOMPtr<nsISupports> isupports; rv = results->GetNext(getter_AddRefs(isupports)); if (NS_FAILED(rv)) return rv; nsIAtom* variable; nsCOMPtr<nsIRDFNode> value; if (hasSourceBinding) { variable = mTargetVariable; value = do_QueryInterface(isupports); NS_ASSERTION(value != nsnull, "target is not an nsIRDFNode"); #ifdef PR_LOGGING if (PR_LOG_TEST(gXULTemplateLog, PR_LOG_DEBUG)) { nsAutoString s(NS_LITERAL_STRING("(none found)")); if (value) nsXULContentUtils::GetTextForNode(value, s); PR_LOG(gXULTemplateLog, PR_LOG_DEBUG, (" target => %s", NS_ConvertUTF16toUTF8(s).get())); } #endif if (! value) continue; targetValue = value; } else { variable = mSourceVariable; nsCOMPtr<nsIRDFResource> source = do_QueryInterface(isupports); NS_ASSERTION(source != nsnull, "source is not an nsIRDFResource"); #ifdef PR_LOGGING if (PR_LOG_TEST(gXULTemplateLog, PR_LOG_DEBUG)) { const char* s = "(none found)"; if (source) source->GetValueConst(&s); PR_LOG(gXULTemplateLog, PR_LOG_DEBUG, (" source => %s", s)); } #endif if (! source) continue; value = sourceRes = source; } // Copy the original instantiation, and add it to the // instantiation set with the new assignment that we've // introduced. Ownership will be transferred to the Instantiation newinst = *inst; newinst.AddAssignment(variable, value); Element* element = nsRDFPropertyTestNode::Element::Create(sourceRes, mProperty, targetValue); if (! element) return NS_ERROR_OUT_OF_MEMORY; newinst.AddSupportingElement(element); aInstantiations.Insert(inst, newinst); } // finally, remove the "under specified" instantiation. aInstantiations.Erase(inst--); } else { if (!aCantHandleYet) { nsXULContentUtils::LogTemplateError(ERROR_TEMPLATE_TRIPLE_UNBOUND); // Neither source nor target assignment! return NS_ERROR_UNEXPECTED; } *aCantHandleYet = PR_TRUE; return NS_OK; } } return NS_OK; }
void IDBDatabase::DeleteObjectStore(const nsAString& aName, ErrorResult& aRv) { AssertIsOnOwningThread(); IDBTransaction* transaction = IDBTransaction::GetCurrent(); if (!transaction || transaction->Database() != this || transaction->GetMode() != IDBTransaction::VERSION_CHANGE) { aRv.Throw(NS_ERROR_DOM_INDEXEDDB_NOT_ALLOWED_ERR); return; } if (!transaction->IsOpen()) { aRv.Throw(NS_ERROR_DOM_INDEXEDDB_TRANSACTION_INACTIVE_ERR); return; } nsTArray<ObjectStoreSpec>& specArray = mSpec->objectStores(); int64_t objectStoreId = 0; for (uint32_t specCount = specArray.Length(), specIndex = 0; specIndex < specCount; specIndex++) { const ObjectStoreMetadata& metadata = specArray[specIndex].metadata(); MOZ_ASSERT(metadata.id()); if (aName == metadata.name()) { objectStoreId = metadata.id(); // Must do this before altering the metadata array! transaction->DeleteObjectStore(objectStoreId); specArray.RemoveElementAt(specIndex); RefreshSpec(/* aMayDelete */ false); break; } } if (!objectStoreId) { aRv.Throw(NS_ERROR_DOM_INDEXEDDB_NOT_FOUND_ERR); return; } // Don't do this in the macro because we always need to increment the serial // number to keep in sync with the parent. const uint64_t requestSerialNumber = IDBRequest::NextSerialNumber(); IDB_LOG_MARK("IndexedDB %s: Child Transaction[%lld] Request[%llu]: " "database(%s).transaction(%s).deleteObjectStore(\"%s\")", "IndexedDB %s: C T[%lld] R[%llu]: " "IDBDatabase.deleteObjectStore()", IDB_LOG_ID_STRING(), transaction->LoggingSerialNumber(), requestSerialNumber, IDB_LOG_STRINGIFY(this), IDB_LOG_STRINGIFY(transaction), NS_ConvertUTF16toUTF8(aName).get()); }
nsresult XULContentSinkImpl::OpenTag(const PRUnichar** aAttributes, const uint32_t aAttrLen, const uint32_t aLineNumber, nsINodeInfo *aNodeInfo) { nsresult rv; // Create the element nsXULPrototypeElement* element; rv = CreateElement(aNodeInfo, &element); if (NS_FAILED(rv)) { #ifdef PR_LOGGING if (PR_LOG_TEST(gLog, PR_LOG_ERROR)) { nsAutoString anodeC; aNodeInfo->GetName(anodeC); PR_LOG(gLog, PR_LOG_ERROR, ("xul: unable to create element '%s' at line %d", NS_ConvertUTF16toUTF8(anodeC).get(), aLineNumber)); } #endif return rv; } // Link this element to its parent. nsPrototypeArray* children = nullptr; rv = mContextStack.GetTopChildren(&children); if (NS_FAILED(rv)) { delete element; return rv; } // Add the attributes rv = AddAttributes(aAttributes, aAttrLen, element); if (NS_FAILED(rv)) return rv; children->AppendElement(element); if (aNodeInfo->Equals(nsGkAtoms::script, kNameSpaceID_XHTML) || aNodeInfo->Equals(nsGkAtoms::script, kNameSpaceID_XUL)) { // Do scripty things now rv = OpenScript(aAttributes, aLineNumber); NS_ENSURE_SUCCESS(rv, rv); NS_ASSERTION(mState == eInScript || mState == eInDocumentElement, "Unexpected state"); if (mState == eInScript) { // OpenScript has pushed the nsPrototypeScriptElement onto the // stack, so we're done. return NS_OK; } } // Push the element onto the context stack, so that child // containers will hook up to us as their parent. rv = mContextStack.Push(element, mState); if (NS_FAILED(rv)) return rv; mState = eInDocumentElement; return NS_OK; }
// This function implements the "HTTP Fetch" algorithm from the Fetch spec. // Functionality is often split between here, the CORS listener proxy and the // Necko HTTP implementation. nsresult FetchDriver::HttpFetch(bool aCORSFlag, bool aCORSPreflightFlag, bool aAuthenticationFlag) { // Step 1. "Let response be null." mResponse = nullptr; nsresult rv; nsCOMPtr<nsIIOService> ios = do_GetIOService(&rv); if (NS_WARN_IF(NS_FAILED(rv))) { FailWithNetworkError(); return rv; } nsAutoCString url; mRequest->GetURL(url); nsCOMPtr<nsIURI> uri; rv = NS_NewURI(getter_AddRefs(uri), url, nullptr, nullptr, ios); if (NS_WARN_IF(NS_FAILED(rv))) { FailWithNetworkError(); return rv; } // Step 2 deals with letting ServiceWorkers intercept requests. This is // handled by Necko after the channel is opened. // FIXME(nsm): Bug 1119026: The channel's skip service worker flag should be // set based on the Request's flag. // Step 3.1 "If the CORS preflight flag is set and one of these conditions is // true..." is handled by the CORS proxy. // // Step 3.2 "Set request's skip service worker flag." This isn't required // since Necko will fall back to the network if the ServiceWorker does not // respond with a valid Response. // // NS_StartCORSPreflight() will automatically kick off the original request // if it succeeds, so we need to have everything setup for the original // request too. // Step 3.3 "Let credentials flag be set if either request's credentials mode // is include, or request's credentials mode is same-origin and the CORS flag // is unset, and unset otherwise." bool useCredentials = false; if (mRequest->GetCredentialsMode() == RequestCredentials::Include || (mRequest->GetCredentialsMode() == RequestCredentials::Same_origin && !aCORSFlag)) { useCredentials = true; } // This is effectivetly the opposite of the use credentials flag in "HTTP // network or cache fetch" in the spec and decides whether to transmit // cookies and other identifying information. LOAD_ANONYMOUS also prevents // new cookies sent by the server from being stored. const nsLoadFlags credentialsFlag = useCredentials ? 0 : nsIRequest::LOAD_ANONYMOUS; // From here on we create a channel and set its properties with the // information from the InternalRequest. This is an implementation detail. MOZ_ASSERT(mLoadGroup); nsCOMPtr<nsIChannel> chan; rv = NS_NewChannel(getter_AddRefs(chan), uri, mPrincipal, nsILoadInfo::SEC_NORMAL, mRequest->ContentPolicyType(), mLoadGroup, nullptr, /* aCallbacks */ nsIRequest::LOAD_NORMAL | credentialsFlag, ios); mLoadGroup = nullptr; if (NS_WARN_IF(NS_FAILED(rv))) { FailWithNetworkError(); return rv; } // Insert ourselves into the notification callbacks chain so we can handle // cross-origin redirects. chan->GetNotificationCallbacks(getter_AddRefs(mNotificationCallbacks)); chan->SetNotificationCallbacks(this); // FIXME(nsm): Bug 1120715. // Step 3.4 "If request's cache mode is default and request's header list // contains a header named `If-Modified-Since`, `If-None-Match`, // `If-Unmodified-Since`, `If-Match`, or `If-Range`, set request's cache mode // to no-store." // Step 3.5 begins "HTTP network or cache fetch". // HTTP network or cache fetch // --------------------------- // Step 1 "Let HTTPRequest..." The channel is the HTTPRequest. nsCOMPtr<nsIHttpChannel> httpChan = do_QueryInterface(chan); if (httpChan) { // Copy the method. nsAutoCString method; mRequest->GetMethod(method); rv = httpChan->SetRequestMethod(method); if (NS_WARN_IF(NS_FAILED(rv))) { FailWithNetworkError(); return rv; } // Set the same headers. nsAutoTArray<InternalHeaders::Entry, 5> headers; mRequest->Headers()->GetEntries(headers); for (uint32_t i = 0; i < headers.Length(); ++i) { httpChan->SetRequestHeader(headers[i].mName, headers[i].mValue, false /* merge */); } // Step 2. Set the referrer. nsAutoString referrer; mRequest->GetReferrer(referrer); if (referrer.EqualsLiteral(kFETCH_CLIENT_REFERRER_STR)) { rv = nsContentUtils::SetFetchReferrerURIWithPolicy(mPrincipal, mDocument, httpChan); if (NS_WARN_IF(NS_FAILED(rv))) { return FailWithNetworkError(); } } else if (referrer.IsEmpty()) { rv = httpChan->SetReferrerWithPolicy(nullptr, net::RP_No_Referrer); if (NS_WARN_IF(NS_FAILED(rv))) { return FailWithNetworkError(); } } else { // From "Determine request's Referrer" step 3 // "If request's referrer is a URL, let referrerSource be request's // referrer." // // XXXnsm - We never actually hit this from a fetch() call since both // fetch and Request() create a new internal request whose referrer is // always set to about:client. Should we just crash here instead until // someone tries to use FetchDriver for non-fetch() APIs? nsCOMPtr<nsIURI> referrerURI; rv = NS_NewURI(getter_AddRefs(referrerURI), referrer, nullptr, nullptr); if (NS_WARN_IF(NS_FAILED(rv))) { return FailWithNetworkError(); } rv = httpChan->SetReferrerWithPolicy(referrerURI, mDocument ? mDocument->GetReferrerPolicy() : net::RP_Default); if (NS_WARN_IF(NS_FAILED(rv))) { return FailWithNetworkError(); } } // Step 3 "If HTTPRequest's force Origin header flag is set..." if (mRequest->ForceOriginHeader()) { nsAutoString origin; rv = nsContentUtils::GetUTFOrigin(mPrincipal, origin); if (NS_WARN_IF(NS_FAILED(rv))) { return FailWithNetworkError(); } httpChan->SetRequestHeader(NS_LITERAL_CSTRING("origin"), NS_ConvertUTF16toUTF8(origin), false /* merge */); } // Bug 1120722 - Authorization will be handled later. // Auth may require prompting, we don't support it yet. // The next patch in this same bug prevents this from aborting the request. // Credentials checks for CORS are handled by nsCORSListenerProxy, } // Step 5. Proxy authentication will be handled by Necko. // FIXME(nsm): Bug 1120715. // Step 7-10. "If request's cache mode is neither no-store nor reload..." // Continue setting up 'HTTPRequest'. Content-Type and body data. nsCOMPtr<nsIUploadChannel2> uploadChan = do_QueryInterface(chan); if (uploadChan) { nsAutoCString contentType; ErrorResult result; mRequest->Headers()->Get(NS_LITERAL_CSTRING("content-type"), contentType, result); // This is an error because the Request constructor explicitly extracts and // sets a content-type per spec. if (result.Failed()) { return FailWithNetworkError(); } nsCOMPtr<nsIInputStream> bodyStream; mRequest->GetBody(getter_AddRefs(bodyStream)); if (bodyStream) { nsAutoCString method; mRequest->GetMethod(method); rv = uploadChan->ExplicitSetUploadStream(bodyStream, contentType, -1, method, false /* aStreamHasHeaders */); if (NS_WARN_IF(NS_FAILED(rv))) { return FailWithNetworkError(); } } } // Set skip serviceworker flag. // While the spec also gates on the client being a ServiceWorker, we can't // infer that here. Instead we rely on callers to set the flag correctly. if (mRequest->SkipServiceWorker()) { if (httpChan) { nsCOMPtr<nsIHttpChannelInternal> internalChan = do_QueryInterface(httpChan); internalChan->ForceNoIntercept(); } else { nsCOMPtr<nsIJARChannel> jarChannel = do_QueryInterface(chan); // If it is not an http channel, it has to be a jar one. MOZ_ASSERT(jarChannel); jarChannel->ForceNoIntercept(); } } nsCOMPtr<nsIStreamListener> listener = this; // Unless the cors mode is explicitly no-cors, we set up a cors proxy even in // the same-origin case, since the proxy does not enforce cors header checks // in the same-origin case. if (mRequest->Mode() != RequestMode::No_cors) { // Set up a CORS proxy that will handle the various requirements of the CORS // protocol. It handles the preflight cache and CORS response headers. // If the request is allowed, it will start our original request // and our observer will be notified. On failure, our observer is notified // directly. nsRefPtr<nsCORSListenerProxy> corsListener = new nsCORSListenerProxy(this, mPrincipal, useCredentials); rv = corsListener->Init(chan, DataURIHandling::Allow); if (NS_WARN_IF(NS_FAILED(rv))) { return FailWithNetworkError(); } listener = corsListener.forget(); } // If preflight is required, start a "CORS preflight fetch" // https://fetch.spec.whatwg.org/#cors-preflight-fetch-0. All the // implementation is handled by NS_StartCORSPreflight, we just set up the // unsafeHeaders so they can be verified against the response's // "Access-Control-Allow-Headers" header. if (aCORSPreflightFlag) { MOZ_ASSERT(mRequest->Mode() != RequestMode::No_cors, "FetchDriver::ContinueFetch() should ensure that the request is not no-cors"); nsCOMPtr<nsIChannel> preflightChannel; nsAutoTArray<nsCString, 5> unsafeHeaders; mRequest->Headers()->GetUnsafeHeaders(unsafeHeaders); rv = NS_StartCORSPreflight(chan, listener, mPrincipal, useCredentials, unsafeHeaders, getter_AddRefs(preflightChannel)); } else { rv = chan->AsyncOpen(listener, nullptr); } if (NS_WARN_IF(NS_FAILED(rv))) { return FailWithNetworkError(); } // Step 4 onwards of "HTTP Fetch" is handled internally by Necko. return NS_OK; }
/* void parentChanged (in nsIDOMElement newParent); */ NS_IMETHODIMP xgGtkElement::ParentChanged (nsIDOMElement *newParent) { /* no need for this rigamarole... */ if (GTK_IS_WINDOW (mObject)) { return NS_OK; } /* just as a sanity check */ nsCOMPtr<xgIGObjectHolder> wrappedParent (do_QueryInterface (newParent)); GObject *parent = NULL; if (!wrappedParent || NS_FAILED (wrappedParent->GetGObject (&parent)) || !GTK_IS_CONTAINER (parent)) { g_warning (GOM_LOC ("Could not get parent widget for node: <%s>"), G_OBJECT_TYPE_NAME (mObject)); return NS_ERROR_FAILURE; } g_assert (GTK_WIDGET (parent) == gtk_widget_get_parent (GTK_WIDGET (mObject))); nsresult rv; nsCOMPtr<nsIDOMElement> elem; rv = mWrapper->GetElementNode (getter_AddRefs (elem)); NS_ENSURE_SUCCESS (rv, rv); nsCOMPtr<nsIDOMNamedNodeMap> attrs; rv = elem->GetAttributes (getter_AddRefs (attrs)); NS_ENSURE_SUCCESS (rv, rv); PRUint32 len; rv = attrs->GetLength (&len); NS_ENSURE_SUCCESS (rv, rv); nsCOMPtr<nsIDOMNode> attr; nsAutoString attrName; nsAutoString attrValue; const char *camel_prop; GValue gval = { 0 }; for (PRUint32 i = 0; i < len; i++) { rv = attrs->Item (i, getter_AddRefs (attr)); NS_ENSURE_SUCCESS (rv, rv); rv = attr->GetNodeName (attrName); NS_ENSURE_SUCCESS (rv, rv); NS_ConvertUTF16toUTF8 attrCName (attrName); camel_prop = gom_camel_uncase (attrCName.get ()); rv = attr->GetNodeValue (attrValue); NS_ENSURE_SUCCESS (rv, rv); g_value_init (&gval, G_TYPE_STRING); g_value_set_string (&gval, NS_ConvertUTF16toUTF8 (attrValue).get ()); append_child_attrs_foreach ((gpointer)camel_prop, (gpointer)&gval, (gpointer)mObject); GOM_CAMEL_FREE (camel_prop, attrCName.get ()); g_value_unset (&gval); } return NS_OK; }
static int MimeInlineTextPlain_parse_line (const char *line, PRInt32 length, MimeObject *obj) { int status; PRBool quoting = ( obj->options && ( obj->options->format_out == nsMimeOutput::nsMimeMessageQuoting || obj->options->format_out == nsMimeOutput::nsMimeMessageBodyQuoting ) ); // see above PRBool plainHTML = quoting || (obj->options && obj->options->format_out == nsMimeOutput::nsMimeMessageSaveAs); // see above PRBool rawPlainText = obj->options && (obj->options->format_out == nsMimeOutput::nsMimeMessageFilterSniffer || obj->options->format_out == nsMimeOutput::nsMimeMessageAttach); // this routine gets called for every line of data that comes through the // mime converter. It's important to make sure we are efficient with // how we allocate memory in this routine. be careful if you go to add // more to this routine. NS_ASSERTION(length > 0, "zero length"); if (length <= 0) return 0; mozITXTToHTMLConv *conv = GetTextConverter(obj->options); MimeInlineTextPlain *text = (MimeInlineTextPlain *) obj; PRBool skipConversion = !conv || rawPlainText || (obj->options && obj->options->force_user_charset); char *mailCharset = NULL; nsresult rv; if (!skipConversion) { nsDependentCString inputStr(line, length); nsAutoString lineSourceStr; // For 'SaveAs', |line| is in |mailCharset|. // convert |line| to UTF-16 before 'html'izing (calling ScanTXT()) if (obj->options->format_out == nsMimeOutput::nsMimeMessageSaveAs) { // Get the mail charset of this message. MimeInlineText *inlinetext = (MimeInlineText *) obj; if (!inlinetext->initializeCharset) ((MimeInlineTextClass*)&mimeInlineTextClass)->initialize_charset(obj); mailCharset = inlinetext->charset; if (mailCharset && *mailCharset) { rv = nsMsgI18NConvertToUnicode(mailCharset, inputStr, lineSourceStr); NS_ENSURE_SUCCESS(rv, -1); } else // this probably never happens ... CopyUTF8toUTF16(inputStr, lineSourceStr); } else // line is in UTF-8 CopyUTF8toUTF16(inputStr, lineSourceStr); nsCAutoString prefaceResultStr; // Quoting stuff before the real text // Recognize quotes PRUint32 oldCiteLevel = text->mCiteLevel; PRUint32 logicalLineStart = 0; rv = conv->CiteLevelTXT(lineSourceStr.get(), &logicalLineStart, &(text->mCiteLevel)); NS_ENSURE_SUCCESS(rv, -1); // Find out, which recognitions to do PRBool whattodo = obj->options->whattodo; if (plainHTML) { if (quoting) whattodo = 0; // This is done on Send. Don't do it twice. else whattodo = whattodo & ~mozITXTToHTMLConv::kGlyphSubstitution; /* Do recognition for the case, the result is viewed in Mozilla, but not GlyphSubstitution, because other UAs might not be able to display the glyphs. */ if (!text->mBlockquoting) text->mCiteLevel = 0; } // Write blockquote if (text->mCiteLevel > oldCiteLevel) { prefaceResultStr += "</pre>"; for (PRUint32 i = 0; i < text->mCiteLevel - oldCiteLevel; i++) { nsCAutoString style; MimeTextBuildPrefixCSS(text->mQuotedSizeSetting, text->mQuotedStyleSetting, text->mCitationColor, style); if (!plainHTML && !style.IsEmpty()) { prefaceResultStr += "<blockquote type=cite style=\""; prefaceResultStr += style; prefaceResultStr += "\">"; } else prefaceResultStr += "<blockquote type=cite>"; } prefaceResultStr += "<pre wrap>\n"; } else if (text->mCiteLevel < oldCiteLevel) { prefaceResultStr += "</pre>"; for (PRUint32 i = 0; i < oldCiteLevel - text->mCiteLevel; i++) prefaceResultStr += "</blockquote>"; prefaceResultStr += "<pre wrap>\n"; } // Write plain text quoting tags if (logicalLineStart != 0 && !(plainHTML && text->mBlockquoting)) { if (!plainHTML) prefaceResultStr += "<span class=\"moz-txt-citetags\">"; nsString citeTagsSource(StringHead(lineSourceStr, logicalLineStart)); // Convert to HTML nsString citeTagsResultUnichar; rv = conv->ScanTXT(citeTagsSource.get(), 0 /* no recognition */, getter_Copies(citeTagsResultUnichar)); if (NS_FAILED(rv)) return -1; prefaceResultStr.Append(NS_ConvertUTF16toUTF8(citeTagsResultUnichar)); if (!plainHTML) prefaceResultStr += "</span>"; } // recognize signature if ((lineSourceStr.Length() >= 4) && lineSourceStr.First() == '-' && Substring(lineSourceStr, 0, 3).EqualsLiteral("-- ") && (lineSourceStr[3] == '\r' || lineSourceStr[3] == '\n') ) { text->mIsSig = PR_TRUE; if (!quoting) prefaceResultStr += "<div class=\"moz-txt-sig\">"; } /* This is the main TXT to HTML conversion: escaping (very important), eventually recognizing etc. */ nsString lineResultUnichar; rv = conv->ScanTXT(lineSourceStr.get() + logicalLineStart, whattodo, getter_Copies(lineResultUnichar)); NS_ENSURE_SUCCESS(rv, -1); if (!(text->mIsSig && quoting)) { status = MimeObject_write(obj, prefaceResultStr.get(), prefaceResultStr.Length(), PR_TRUE); if (status < 0) return status; nsCAutoString outString; if (obj->options->format_out != nsMimeOutput::nsMimeMessageSaveAs || !mailCharset || !*mailCharset) CopyUTF16toUTF8(lineResultUnichar, outString); else { // convert back to mailCharset before writing. rv = nsMsgI18NConvertFromUnicode(mailCharset, lineResultUnichar, outString); NS_ENSURE_SUCCESS(rv, -1); } status = MimeObject_write(obj, outString.get(), outString.Length(), PR_TRUE); } else { status = NS_OK; } } else { status = MimeObject_write(obj, line, length, PR_TRUE); } return status; }
void URL::SetUsername(const nsAString& aUsername, ErrorResult& aRv) { mURI->SetUsername(NS_ConvertUTF16toUTF8(aUsername)); }
nsresult nsAlertsIconListener::InitAlertAsync(const nsAString & aImageUrl, const nsAString & aAlertTitle, const nsAString & aAlertText, bool aAlertTextClickable, const nsAString & aAlertCookie, nsIObserver * aAlertListener) { if (!libNotifyHandle) return NS_ERROR_FAILURE; if (!notify_is_initted()) { // Give the name of this application to libnotify nsCOMPtr<nsIStringBundleService> bundleService = do_GetService(NS_STRINGBUNDLE_CONTRACTID); nsAutoCString appShortName; if (bundleService) { nsCOMPtr<nsIStringBundle> bundle; bundleService->CreateBundle("chrome://branding/locale/brand.properties", getter_AddRefs(bundle)); nsAutoString appName; if (bundle) { bundle->GetStringFromName(MOZ_UTF16("brandShortName"), getter_Copies(appName)); appShortName = NS_ConvertUTF16toUTF8(appName); } else { NS_WARNING("brand.properties not present, using default application name"); appShortName.AssignLiteral("Mozilla"); } } else { appShortName.AssignLiteral("Mozilla"); } if (!notify_init(appShortName.get())) return NS_ERROR_FAILURE; GList *server_caps = notify_get_server_caps(); if (server_caps) { gHasCaps = true; for (GList* cap = server_caps; cap != nullptr; cap = cap->next) { if (!strcmp((char*) cap->data, "actions")) { gHasActions = true; break; } } g_list_foreach(server_caps, (GFunc)g_free, nullptr); g_list_free(server_caps); } } if (!gHasCaps) { // if notify_get_server_caps() failed above we need to assume // there is no notification-server to display anything return NS_ERROR_FAILURE; } if (!gHasActions && aAlertTextClickable) return NS_ERROR_FAILURE; // No good, fallback to XUL nsCOMPtr<nsIObserverService> obsServ = do_GetService("@mozilla.org/observer-service;1"); if (obsServ) obsServ->AddObserver(this, "quit-application", true); // Workaround for a libnotify bug - blank titles aren't dealt with // properly so we use a space if (aAlertTitle.IsEmpty()) { mAlertTitle = NS_LITERAL_CSTRING(" "); } else { mAlertTitle = NS_ConvertUTF16toUTF8(aAlertTitle); } mAlertText = NS_ConvertUTF16toUTF8(aAlertText); mAlertHasAction = aAlertTextClickable; mAlertListener = aAlertListener; mAlertCookie = aAlertCookie; return StartRequest(aImageUrl); }
void URL::SetPassword(const nsAString& aPassword, ErrorResult& aRv) { mURI->SetPassword(NS_ConvertUTF16toUTF8(aPassword)); }
NS_IMETHODIMP nsBinaryOutputStream::WriteUtf8Z(const PRUnichar* aString) { return WriteStringZ(NS_ConvertUTF16toUTF8(aString).get()); }
void URL::SetHost(const nsAString& aHost, ErrorResult& aRv) { mURI->SetHostPort(NS_ConvertUTF16toUTF8(aHost)); }
bool UDPSocket::Send(const StringOrBlobOrArrayBufferOrArrayBufferView& aData, const Optional<nsAString>& aRemoteAddress, const Optional<Nullable<uint16_t>>& aRemotePort, ErrorResult& aRv) { if (mReadyState != SocketReadyState::Open) { aRv.Throw(NS_ERROR_DOM_INVALID_STATE_ERR); return false; } MOZ_ASSERT(mSocket || mSocketChild); // If the remote address and port were not specified in the constructor or as arguments, // throw InvalidAccessError. nsCString remoteAddress; if (aRemoteAddress.WasPassed()) { remoteAddress = NS_ConvertUTF16toUTF8(aRemoteAddress.Value()); } else if (!mRemoteAddress.IsVoid()) { remoteAddress = mRemoteAddress; } else { aRv.Throw(NS_ERROR_DOM_INVALID_ACCESS_ERR); return false; } uint16_t remotePort; if (aRemotePort.WasPassed() && !aRemotePort.Value().IsNull()) { remotePort = aRemotePort.Value().Value(); } else if (!mRemotePort.IsNull()) { remotePort = mRemotePort.Value(); } else { aRv.Throw(NS_ERROR_DOM_INVALID_ACCESS_ERR); return false; } nsCOMPtr<nsIInputStream> stream; if (aData.IsBlob()) { File& blob = aData.GetAsBlob(); aRv = blob.GetInternalStream(getter_AddRefs(stream)); if (NS_WARN_IF(aRv.Failed())) { return false; } } else { nsresult rv; nsCOMPtr<nsIStringInputStream> strStream = do_CreateInstance(NS_STRINGINPUTSTREAM_CONTRACTID, &rv); if (NS_WARN_IF(NS_FAILED(rv))) { aRv.Throw(rv); return false; } if (aData.IsString()) { NS_ConvertUTF16toUTF8 data(aData.GetAsString()); aRv = strStream->SetData(data.BeginReading(), data.Length()); } else if (aData.IsArrayBuffer()) { const ArrayBuffer& data = aData.GetAsArrayBuffer(); data.ComputeLengthAndData(); aRv = strStream->SetData(reinterpret_cast<const char*>(data.Data()), data.Length()); } else { const ArrayBufferView& data = aData.GetAsArrayBufferView(); data.ComputeLengthAndData(); aRv = strStream->SetData(reinterpret_cast<const char*>(data.Data()), data.Length()); } if (NS_WARN_IF(aRv.Failed())) { return false; } stream = strStream; } if (mSocket) { aRv = mSocket->SendBinaryStream(remoteAddress, remotePort, stream); } else if (mSocketChild) { aRv = mSocketChild->SendBinaryStream(remoteAddress, remotePort, stream); } if (NS_WARN_IF(aRv.Failed())) { return false; } return true; }
void URL::SetHash(const nsAString& aHash, ErrorResult& aRv) { mURI->SetRef(NS_ConvertUTF16toUTF8(aHash)); }
void HTMLTrackElement::LoadResource() { // Find our 'src' url nsAutoString src; if (!GetAttr(kNameSpaceID_None, nsGkAtoms::src, src)) { return; } nsCOMPtr<nsIURI> uri; nsresult rv = NewURIFromString(src, getter_AddRefs(uri)); NS_ENSURE_TRUE_VOID(NS_SUCCEEDED(rv)); LOG(PR_LOG_ALWAYS, ("%p Trying to load from src=%s", this, NS_ConvertUTF16toUTF8(src).get())); if (mChannel) { mChannel->Cancel(NS_BINDING_ABORTED); mChannel = nullptr; } rv = nsContentUtils::GetSecurityManager()-> CheckLoadURIWithPrincipal(NodePrincipal(), uri, nsIScriptSecurityManager::STANDARD); NS_ENSURE_TRUE_VOID(NS_SUCCEEDED(rv)); int16_t shouldLoad = nsIContentPolicy::ACCEPT; rv = NS_CheckContentLoadPolicy(nsIContentPolicy::TYPE_MEDIA, uri, NodePrincipal(), static_cast<Element*>(this), NS_LITERAL_CSTRING("text/vtt"), // mime type nullptr, // extra &shouldLoad, nsContentUtils::GetContentPolicy(), nsContentUtils::GetSecurityManager()); NS_ENSURE_TRUE_VOID(NS_SUCCEEDED(rv)); if (NS_CP_REJECTED(shouldLoad)) { return; } CreateTextTrack(); // Check for a Content Security Policy to pass down to the channel // created to load the media content. nsCOMPtr<nsIChannelPolicy> channelPolicy; nsCOMPtr<nsIContentSecurityPolicy> csp; rv = NodePrincipal()->GetCsp(getter_AddRefs(csp)); NS_ENSURE_TRUE_VOID(NS_SUCCEEDED(rv)); if (csp) { channelPolicy = do_CreateInstance("@mozilla.org/nschannelpolicy;1"); if (!channelPolicy) { return; } channelPolicy->SetContentSecurityPolicy(csp); channelPolicy->SetLoadType(nsIContentPolicy::TYPE_MEDIA); } nsCOMPtr<nsIChannel> channel; nsCOMPtr<nsILoadGroup> loadGroup = OwnerDoc()->GetDocumentLoadGroup(); rv = NS_NewChannel(getter_AddRefs(channel), uri, nullptr, loadGroup, nullptr, nsIRequest::LOAD_NORMAL, channelPolicy); NS_ENSURE_TRUE_VOID(NS_SUCCEEDED(rv)); mListener = new WebVTTListener(this); rv = mListener->LoadResource(); NS_ENSURE_TRUE_VOID(NS_SUCCEEDED(rv)); channel->SetNotificationCallbacks(mListener); LOG(PR_LOG_DEBUG, ("opening webvtt channel")); rv = channel->AsyncOpen(mListener, nullptr); NS_ENSURE_TRUE_VOID(NS_SUCCEEDED(rv)); mChannel = channel; }
nsresult sbProcess::Run() { PRStatus status; nsresult rv; // Set up to auto-kill process. sbAutoKillProcess autoSelf(this); // Operate under the process lock. { NS_ENSURE_TRUE(mProcessLock, NS_ERROR_NOT_INITIALIZED); nsAutoLock autoProcessLock(mProcessLock); // Get the number of arguments. PRUint32 argCount = mArgList.Length(); NS_ENSURE_TRUE(argCount > 0, NS_ERROR_ILLEGAL_VALUE); // Convert the UTF-16 argument list to a UTF-8 argument list. nsTArray<nsCString> argListUTF8; for (PRUint32 i = 0; i < argCount; i++) { NS_ENSURE_TRUE(argListUTF8.AppendElement (NS_ConvertUTF16toUTF8(mArgList[i])), NS_ERROR_OUT_OF_MEMORY); } // Allocate a null-terminated char* argument list and set it up for // auto-disposal. char** argList = reinterpret_cast<char**> (NS_Alloc((argCount + 1) * sizeof(char*))); NS_ENSURE_TRUE(argList, NS_ERROR_OUT_OF_MEMORY); sbAutoNSTypePtr<char*> autoArgList(argList); // Convert the argument list to a null-terminated char* argument list. for (PRUint32 i = 0; i < argCount; i++) { argList[i] = const_cast<char*>(argListUTF8[i].get()); } argList[argCount] = NULL; // Set up the process attributes and set them up for auto-disposal. PRProcessAttr* processAttr = PR_NewProcessAttr(); NS_ENSURE_TRUE(processAttr, NS_ERROR_FAILURE); sbAutoPRProcessAttr autoProcessAttr(processAttr); // Set up process stdin. if (mPipeStdinString) { // Create a process stdin pipe and set it up for auto-disposal. PRFileDesc* stdinReadFD; PRFileDesc* stdinWriteFD; status = PR_CreatePipe(&stdinReadFD, &stdinWriteFD); NS_ENSURE_TRUE(status == PR_SUCCESS, NS_ERROR_FAILURE); sbAutoPRFileDesc autoStdinReadFD(stdinReadFD); sbAutoPRFileDesc autoStdinWriteFD(stdinWriteFD); // Set up stdin pipe file descriptors. status = PR_SetFDInheritable(stdinReadFD, PR_TRUE); NS_ENSURE_TRUE(status == PR_SUCCESS, NS_ERROR_FAILURE); status = PR_SetFDInheritable(stdinWriteFD, PR_FALSE); NS_ENSURE_TRUE(status == PR_SUCCESS, NS_ERROR_FAILURE); // Fill pipe. nsCAutoString writeData = NS_ConvertUTF16toUTF8(mStdinString); PRInt32 bytesWritten; bytesWritten = PR_Write(stdinWriteFD, writeData.get(), writeData.Length()); NS_ENSURE_TRUE(bytesWritten == writeData.Length(), NS_ERROR_FAILURE); // Redirect process stdin. PR_ProcessAttrSetStdioRedirect(processAttr, PR_StandardInput, stdinReadFD); // Keep stdin read descriptor open for the process to read. Close the // stdin write descriptor so that the process gets EOF when all of the // data is read. mStdinReadFD = autoStdinReadFD.forget(); PR_Close(autoStdinWriteFD.forget()); } // Set up process stdout. if (mPipeStdoutString) { // Create a process stdout pipe and set it up for auto-disposal. PRFileDesc* stdoutReadFD; PRFileDesc* stdoutWriteFD; status = PR_CreatePipe(&stdoutReadFD, &stdoutWriteFD); NS_ENSURE_TRUE(status == PR_SUCCESS, NS_ERROR_FAILURE); sbAutoPRFileDesc autoStdoutReadFD(stdoutReadFD); sbAutoPRFileDesc autoStdoutWriteFD(stdoutWriteFD); // Set up stdout pipe file descriptors. status = PR_SetFDInheritable(stdoutReadFD, PR_FALSE); NS_ENSURE_TRUE(status == PR_SUCCESS, NS_ERROR_FAILURE); status = PR_SetFDInheritable(stdoutWriteFD, PR_TRUE); NS_ENSURE_TRUE(status == PR_SUCCESS, NS_ERROR_FAILURE); // Redirect process stdout. PR_ProcessAttrSetStdioRedirect(processAttr, PR_StandardOutput, stdoutWriteFD); // Keep descriptors. mStdoutReadFD = autoStdoutReadFD.forget(); mStdoutWriteFD = autoStdoutWriteFD.forget(); } // Create and start running the process. mBaseProcess = PR_CreateProcess(argList[0], argList, NULL, processAttr); NS_ENSURE_TRUE(mBaseProcess, NS_ERROR_FAILURE); // Wait for process done on another thread. nsCOMPtr<nsIRunnable> runnable = NS_NEW_RUNNABLE_METHOD(sbProcess, this, WaitForDone); NS_ENSURE_TRUE(runnable, NS_ERROR_OUT_OF_MEMORY); rv = NS_NewThread(getter_AddRefs(mWaitForDoneThread), runnable); NS_ENSURE_SUCCESS(rv, rv); } // Clear process auto-kill. autoSelf.forget(); return NS_OK; }