TEST(CloneInputStream, NonCloneableInput_NoFallback) { nsTArray<char> inputData; testing::CreateData(4 * 1024, inputData); nsDependentCSubstring inputString(inputData.Elements(), inputData.Length()); nsCOMPtr<nsIInputStream> base; nsresult rv = NS_NewCStringInputStream(getter_AddRefs(base), inputString); ASSERT_TRUE(NS_SUCCEEDED(rv)); // Take advantage of nsBufferedInputStream being non-cloneable right // now. If this changes in the future, then we need a different stream // type in this test. nsCOMPtr<nsIInputStream> stream; rv = NS_NewBufferedInputStream(getter_AddRefs(stream), base, 4096); ASSERT_TRUE(NS_SUCCEEDED(rv)); nsCOMPtr<nsICloneableInputStream> cloneable = do_QueryInterface(stream); ASSERT_TRUE(cloneable == nullptr); nsCOMPtr<nsIInputStream> clone; rv = NS_CloneInputStream(stream, getter_AddRefs(clone)); ASSERT_TRUE(NS_FAILED(rv)); ASSERT_TRUE(clone == nullptr); testing::ConsumeAndValidateStream(stream, inputString); }
// Convert aFromStream (of type aFromType), to _retval (nsIInputStream of type aToType). // This Convert method simply converts the stream byte-by-byte, to the first character // in the aToType "string". NS_IMETHODIMP TestConverter::Convert(nsIInputStream *aFromStream, const char *aFromType, const char *aToType, nsISupports *ctxt, nsIInputStream **_retval) { char buf[1024+1]; PRUint32 read; nsresult rv = aFromStream->Read(buf, 1024, &read); if (NS_FAILED(rv) || read == 0) return rv; // verify that the data we're converting matches the from type // if it doesn't then we're being handed the wrong data. char fromChar = *aFromType; if (fromChar != buf[0]) { printf("We're receiving %c, but are supposed to have %c.\n", buf[0], fromChar); return NS_ERROR_FAILURE; } // Get the first character char toChar = *aToType; for (PRUint32 i = 0; i < read; i++) buf[i] = toChar; buf[read] = '\0'; return NS_NewCStringInputStream(_retval, nsDependentCString(buf)); }
void DataTransfer::FillInExternalCustomTypes(nsIVariant* aData, uint32_t aIndex, nsIPrincipal* aPrincipal) { char* chrs; uint32_t len = 0; nsresult rv = aData->GetAsStringWithSize(&len, &chrs); if (NS_FAILED(rv)) { return; } nsAutoCString str; str.Adopt(chrs, len); nsCOMPtr<nsIInputStream> stringStream; NS_NewCStringInputStream(getter_AddRefs(stringStream), str); nsCOMPtr<nsIBinaryInputStream> stream = do_CreateInstance("@mozilla.org/binaryinputstream;1"); if (!stream) { return; } rv = stream->SetInputStream(stringStream); NS_ENSURE_SUCCESS_VOID(rv); uint32_t type; do { rv = stream->Read32(&type); NS_ENSURE_SUCCESS_VOID(rv); if (type == eCustomClipboardTypeId_String) { uint32_t formatLength; rv = stream->Read32(&formatLength); NS_ENSURE_SUCCESS_VOID(rv); char* formatBytes; rv = stream->ReadBytes(formatLength, &formatBytes); NS_ENSURE_SUCCESS_VOID(rv); nsAutoString format; format.Adopt(reinterpret_cast<char16_t*>(formatBytes), formatLength / sizeof(char16_t)); uint32_t dataLength; rv = stream->Read32(&dataLength); NS_ENSURE_SUCCESS_VOID(rv); char* dataBytes; rv = stream->ReadBytes(dataLength, &dataBytes); NS_ENSURE_SUCCESS_VOID(rv); nsAutoString data; data.Adopt(reinterpret_cast<char16_t*>(dataBytes), dataLength / sizeof(char16_t)); RefPtr<nsVariantCC> variant = new nsVariantCC(); rv = variant->SetAsAString(data); NS_ENSURE_SUCCESS_VOID(rv); SetDataWithPrincipal(format, variant, aIndex, aPrincipal); } } while (type != eCustomClipboardTypeId_None); }
NS_IMETHODIMP nsRDFXMLParser::ParseString(nsIRDFDataSource* aSink, nsIURI* aBaseURI, const nsACString& aString) { nsresult rv; nsCOMPtr<nsIRDFContentSink> sink = do_CreateInstance("@mozilla.org/rdf/content-sink;1", &rv); if (NS_FAILED(rv)) return rv; rv = sink->Init(aBaseURI); if (NS_FAILED(rv)) return rv; // We set the content sink's data source directly to our in-memory // store. This allows the initial content to be generated "directly". rv = sink->SetDataSource(aSink); if (NS_FAILED(rv)) return rv; nsCOMPtr<nsIParser> parser = do_CreateInstance(kParserCID, &rv); if (NS_FAILED(rv)) return rv; parser->SetDocumentCharset(NS_LITERAL_CSTRING("UTF-8"), kCharsetFromOtherComponent); parser->SetContentSink(sink); rv = parser->Parse(aBaseURI); if (NS_FAILED(rv)) return rv; nsCOMPtr<nsIStreamListener> listener = do_QueryInterface(parser); if (! listener) return NS_ERROR_FAILURE; nsCOMPtr<nsIInputStream> stream; rv = NS_NewCStringInputStream(getter_AddRefs(stream), aString); if (NS_FAILED(rv)) return rv; nsCOMPtr<nsIPrincipal> nullPrincipal = nsNullPrincipal::Create(); NS_ENSURE_TRUE(nullPrincipal, NS_ERROR_FAILURE); // The following channel is never openend, so it does not matter what // securityFlags we pass; let's follow the principle of least privilege. nsCOMPtr<nsIChannel> channel; rv = NS_NewInputStreamChannel(getter_AddRefs(channel), aBaseURI, stream, nullPrincipal, nsILoadInfo::SEC_REQUIRE_SAME_ORIGIN_DATA_IS_BLOCKED, nsIContentPolicy::TYPE_OTHER, NS_LITERAL_CSTRING("text/xml")); if (NS_FAILED(rv)) return rv; listener->OnStartRequest(channel, nullptr); listener->OnDataAvailable(channel, nullptr, stream, 0, aString.Length()); listener->OnStopRequest(channel, nullptr, NS_OK); return NS_OK; }
nsresult nsIndexedToHTML::SendToListener(nsIRequest* aRequest, nsISupports *aContext, const nsACString &aBuffer) { nsCOMPtr<nsIInputStream> inputData; nsresult rv = NS_NewCStringInputStream(getter_AddRefs(inputData), aBuffer); NS_ENSURE_SUCCESS(rv, rv); return mListener->OnDataAvailable(aRequest, aContext, inputData, 0, aBuffer.Length()); }
NS_IMETHODIMP URLSearchParams::GetSendInfo(nsIInputStream** aBody, uint64_t* aContentLength, nsACString& aContentType, nsACString& aCharset) { aContentType.AssignLiteral("application/x-www-form-urlencoded"); aCharset.AssignLiteral("UTF-8"); nsAutoString serialized; Serialize(serialized); NS_ConvertUTF16toUTF8 converted(serialized); *aContentLength = converted.Length(); return NS_NewCStringInputStream(aBody, converted); }
// Helper function for creating a seekable nsIInputStream + a SlicedInputStream. SlicedInputStream* CreateSeekableStreams(uint32_t aSize, uint64_t aStart, uint64_t aLength, nsCString& aBuffer) { aBuffer.SetLength(aSize); for (uint32_t i = 0; i < aSize; ++i) { aBuffer.BeginWriting()[i] = i % 10; } nsCOMPtr<nsIInputStream> stream; NS_NewCStringInputStream(getter_AddRefs(stream), aBuffer); return new SlicedInputStream(stream, aStart, aLength); }
nsresult nsHttpConnection::SetupSSLProxyConnect() { const char *val; LOG(("nsHttpConnection::SetupSSLProxyConnect [this=%x]\n", this)); NS_ENSURE_TRUE(!mSSLProxyConnectStream, NS_ERROR_ALREADY_INITIALIZED); nsCAutoString buf; nsresult rv = nsHttpHandler::GenerateHostPort( nsDependentCString(mConnInfo->Host()), mConnInfo->Port(), buf); if (NS_FAILED(rv)) return rv; // CONNECT host:port HTTP/1.1 nsHttpRequestHead request; request.SetMethod(nsHttp::Connect); request.SetVersion(gHttpHandler->HttpVersion()); request.SetRequestURI(buf); request.SetHeader(nsHttp::User_Agent, gHttpHandler->UserAgent()); // send this header for backwards compatibility. request.SetHeader(nsHttp::Proxy_Connection, NS_LITERAL_CSTRING("keep-alive")); // NOTE: this cast is valid since this connection cannot be processing a // transaction pipeline until after the first HTTP/1.1 response. nsHttpTransaction *trans = static_cast<nsHttpTransaction *>(mTransaction); val = trans->RequestHead()->PeekHeader(nsHttp::Host); if (val) { // all HTTP/1.1 requests must include a Host header (even though it // may seem redundant in this case; see bug 82388). request.SetHeader(nsHttp::Host, nsDependentCString(val)); } val = trans->RequestHead()->PeekHeader(nsHttp::Proxy_Authorization); if (val) { // we don't know for sure if this authorization is intended for the // SSL proxy, so we add it just in case. request.SetHeader(nsHttp::Proxy_Authorization, nsDependentCString(val)); } buf.Truncate(); request.Flatten(buf, PR_FALSE); buf.AppendLiteral("\r\n"); return NS_NewCStringInputStream(getter_AddRefs(mSSLProxyConnectStream), buf); }
NS_IMETHODIMP nsRDFXMLParser::ParseString(nsIRDFDataSource* aSink, nsIURI* aBaseURI, const nsACString& aString) { nsresult rv; nsCOMPtr<nsIRDFContentSink> sink = do_CreateInstance("@mozilla.org/rdf/content-sink;1", &rv); if (NS_FAILED(rv)) return rv; rv = sink->Init(aBaseURI); if (NS_FAILED(rv)) return rv; // We set the content sink's data source directly to our in-memory // store. This allows the initial content to be generated "directly". rv = sink->SetDataSource(aSink); if (NS_FAILED(rv)) return rv; nsCOMPtr<nsIParser> parser = do_CreateInstance(kParserCID, &rv); if (NS_FAILED(rv)) return rv; parser->SetDocumentCharset(NS_LITERAL_CSTRING("UTF-8"), kCharsetFromOtherComponent); parser->SetContentSink(sink); rv = parser->Parse(aBaseURI); if (NS_FAILED(rv)) return rv; nsCOMPtr<nsIStreamListener> listener = do_QueryInterface(parser); if (! listener) return NS_ERROR_FAILURE; nsCOMPtr<nsIInputStream> stream; rv = NS_NewCStringInputStream(getter_AddRefs(stream), aString); if (NS_FAILED(rv)) return rv; nsCOMPtr<nsIChannel> channel; rv = NS_NewInputStreamChannel(getter_AddRefs(channel), aBaseURI, stream, NS_LITERAL_CSTRING("text/xml")); if (NS_FAILED(rv)) return rv; listener->OnStartRequest(channel, nsnull); listener->OnDataAvailable(channel, nsnull, stream, 0, aString.Length()); listener->OnStopRequest(channel, nsnull, NS_OK); return NS_OK; }
// static already_AddRefed<nsIInputStream> FileHandleBase::GetInputStream(const nsAString& aValue, uint64_t* aInputLength, ErrorResult& aRv) { NS_ConvertUTF16toUTF8 cstr(aValue); nsCOMPtr<nsIInputStream> stream; aRv = NS_NewCStringInputStream(getter_AddRefs(stream), cstr); if (aRv.Failed()) { return nullptr; } *aInputLength = cstr.Length(); return stream.forget(); }
void EmptyBlobImpl::GetInternalStream(nsIInputStream** aStream, ErrorResult& aRv) { if (NS_WARN_IF(!aStream)) { aRv.Throw(NS_ERROR_FAILURE); return; } nsresult rv = NS_NewCStringInputStream(aStream, EmptyCString()); if (NS_WARN_IF(NS_FAILED(rv))) { aRv.Throw(rv); return; } }
TEST(CloneInputStream, CloneableInput) { nsTArray<char> inputData; testing::CreateData(4 * 1024, inputData); nsDependentCSubstring inputString(inputData.Elements(), inputData.Length()); nsCOMPtr<nsIInputStream> stream; nsresult rv = NS_NewCStringInputStream(getter_AddRefs(stream), inputString); ASSERT_TRUE(NS_SUCCEEDED(rv)); nsCOMPtr<nsIInputStream> clone; rv = NS_CloneInputStream(stream, getter_AddRefs(clone)); ASSERT_TRUE(NS_SUCCEEDED(rv)); testing::ConsumeAndValidateStream(stream, inputString); testing::ConsumeAndValidateStream(clone, inputString); }
template<> nsresult BodyExtractor<const nsAString>::GetAsStream(nsIInputStream** aResult, uint64_t* aContentLength, nsACString& aContentTypeWithCharset, nsACString& aCharset) const { nsCOMPtr<nsIUnicodeEncoder> encoder = EncodingUtils::EncoderForEncoding("UTF-8"); if (!encoder) { return NS_ERROR_OUT_OF_MEMORY; } int32_t destBufferLen; nsresult rv = encoder->GetMaxLength(mBody->BeginReading(), mBody->Length(), &destBufferLen); if (NS_WARN_IF(NS_FAILED(rv))) { return rv; } nsCString encoded; if (!encoded.SetCapacity(destBufferLen, fallible)) { return NS_ERROR_OUT_OF_MEMORY; } char* destBuffer = encoded.BeginWriting(); int32_t srcLen = (int32_t) mBody->Length(); int32_t outLen = destBufferLen; rv = encoder->Convert(mBody->BeginReading(), &srcLen, destBuffer, &outLen); if (NS_WARN_IF(NS_FAILED(rv))) { return rv; } MOZ_ASSERT(outLen <= destBufferLen); encoded.SetLength(outLen); rv = NS_NewCStringInputStream(aResult, encoded); if (NS_WARN_IF(NS_FAILED(rv))) { return rv; } *aContentLength = outLen; aContentTypeWithCharset.AssignLiteral("text/plain;charset=UTF-8"); aCharset.AssignLiteral("UTF-8"); return NS_OK; }
TEST(CloneInputStream, NonCloneableInput_Fallback) { nsTArray<char> inputData; testing::CreateData(4 * 1024, inputData); nsDependentCSubstring inputString(inputData.Elements(), inputData.Length()); nsCOMPtr<nsIInputStream> base; nsresult rv = NS_NewCStringInputStream(getter_AddRefs(base), inputString); ASSERT_TRUE(NS_SUCCEEDED(rv)); // Take advantage of nsBufferedInputStream being non-cloneable right // now. If this changes in the future, then we need a different stream // type in this test. nsCOMPtr<nsIInputStream> stream; rv = NS_NewBufferedInputStream(getter_AddRefs(stream), base, 4096); ASSERT_TRUE(NS_SUCCEEDED(rv)); nsCOMPtr<nsICloneableInputStream> cloneable = do_QueryInterface(stream); ASSERT_TRUE(cloneable == nullptr); nsCOMPtr<nsIInputStream> clone; nsCOMPtr<nsIInputStream> replacement; rv = NS_CloneInputStream(stream, getter_AddRefs(clone), getter_AddRefs(replacement)); ASSERT_TRUE(NS_SUCCEEDED(rv)); ASSERT_TRUE(clone != nullptr); ASSERT_TRUE(replacement != nullptr); ASSERT_TRUE(stream.get() != replacement.get()); ASSERT_TRUE(clone.get() != replacement.get()); stream = replacement.forget(); // The stream is being copied asynchronously on the STS event target. Spin // a yield loop here until the data is available. Yes, this is a bit hacky, // but AFAICT, gtest does not support async test completion. uint64_t available; do { mozilla::unused << PR_Sleep(PR_INTERVAL_NO_WAIT); rv = stream->Available(&available); ASSERT_TRUE(NS_SUCCEEDED(rv)); } while(available < inputString.Length()); testing::ConsumeAndValidateStream(stream, inputString); testing::ConsumeAndValidateStream(clone, inputString); }
TEST(CloneInputStream, CloneMultiplexStreamPartial) { nsCOMPtr<nsIMultiplexInputStream> stream = do_CreateInstance("@mozilla.org/io/multiplex-input-stream;1"); ASSERT_TRUE(stream); nsTArray<char> inputData; testing::CreateData(1024, inputData); for (uint32_t i = 0; i < 2; ++i) { nsCString inputString(inputData.Elements(), inputData.Length()); nsCOMPtr<nsIInputStream> base; nsresult rv = NS_NewCStringInputStream(getter_AddRefs(base), inputString); ASSERT_TRUE(NS_SUCCEEDED(rv)); rv = stream->AppendStream(base); ASSERT_TRUE(NS_SUCCEEDED(rv)); } // Fail when first stream read, but second hasn't been started. nsAutoPtr<char> buffer(new char[1024]); uint32_t read; nsresult rv = stream->Read(buffer, 1024, &read); ASSERT_TRUE(NS_SUCCEEDED(rv)); nsCOMPtr<nsIInputStream> clone; rv = NS_CloneInputStream(stream, getter_AddRefs(clone)); ASSERT_TRUE(NS_FAILED(rv)); // Fail after beginning read of second stream. rv = stream->Read(buffer, 512, &read); ASSERT_TRUE(NS_SUCCEEDED(rv) && read == 512); rv = NS_CloneInputStream(stream, getter_AddRefs(clone)); ASSERT_TRUE(NS_FAILED(rv)); // Fail at the end. nsAutoCString consumed; rv = NS_ConsumeStream(stream, UINT32_MAX, consumed); ASSERT_TRUE(NS_SUCCEEDED(rv)); rv = NS_CloneInputStream(stream, getter_AddRefs(clone)); ASSERT_TRUE(NS_FAILED(rv)); }
NS_IMETHODIMP nsAboutBlank::NewChannel(nsIURI *aURI, nsIChannel **result) { NS_ENSURE_ARG_POINTER(aURI); nsresult rv; nsIChannel* channel; nsCOMPtr<nsIInputStream> in; rv = NS_NewCStringInputStream(getter_AddRefs(in), EmptyCString()); if (NS_FAILED(rv)) return rv; rv = NS_NewInputStreamChannel(&channel, aURI, in, NS_LITERAL_CSTRING("text/html"), NS_LITERAL_CSTRING("utf-8")); if (NS_FAILED(rv)) return rv; *result = channel; return rv; }
TEST(CloneInputStream, CloneMultiplexStream) { nsCOMPtr<nsIMultiplexInputStream> stream = do_CreateInstance("@mozilla.org/io/multiplex-input-stream;1"); ASSERT_TRUE(stream); nsTArray<char> inputData; testing::CreateData(1024, inputData); for (uint32_t i = 0; i < 2; ++i) { nsCString inputString(inputData.Elements(), inputData.Length()); nsCOMPtr<nsIInputStream> base; nsresult rv = NS_NewCStringInputStream(getter_AddRefs(base), inputString); ASSERT_TRUE(NS_SUCCEEDED(rv)); rv = stream->AppendStream(base); ASSERT_TRUE(NS_SUCCEEDED(rv)); } // Unread stream should clone successfully. nsTArray<char> doubled; doubled.AppendElements(inputData); doubled.AppendElements(inputData); nsCOMPtr<nsIInputStream> clone; nsresult rv = NS_CloneInputStream(stream, getter_AddRefs(clone)); ASSERT_TRUE(NS_SUCCEEDED(rv)); testing::ConsumeAndValidateStream(clone, doubled); // Stream that has been read should fail. nsAutoPtr<char> buffer(new char[512]); uint32_t read; rv = stream->Read(buffer, 512, &read); ASSERT_TRUE(NS_SUCCEEDED(rv)); nsCOMPtr<nsIInputStream> clone2; rv = NS_CloneInputStream(stream, getter_AddRefs(clone2)); ASSERT_TRUE(NS_FAILED(rv)); }
NS_IMETHODIMP nsAboutBlank::NewChannel(nsIURI* aURI, nsILoadInfo* aLoadInfo, nsIChannel** result) { NS_ENSURE_ARG_POINTER(aURI); nsCOMPtr<nsIInputStream> in; nsresult rv = NS_NewCStringInputStream(getter_AddRefs(in), EmptyCString()); if (NS_FAILED(rv)) return rv; nsCOMPtr<nsIChannel> channel; // Bug 1087720 (and Bug 1099296): // Once all callsites have been updated to call NewChannel2() // instead of NewChannel() we should have a non-null loadInfo // consistently. Until then we have to branch on the loadInfo. if (aLoadInfo) { rv = NS_NewInputStreamChannelInternal(getter_AddRefs(channel), aURI, in, NS_LITERAL_CSTRING("text/html"), NS_LITERAL_CSTRING("utf-8"), aLoadInfo); } else { rv = NS_NewInputStreamChannel(getter_AddRefs(channel), aURI, in, nsContentUtils::GetSystemPrincipal(), nsILoadInfo::SEC_NORMAL, nsIContentPolicy::TYPE_OTHER, NS_LITERAL_CSTRING("text/html"), NS_LITERAL_CSTRING("utf-8")); } if (NS_FAILED(rv)) return rv; channel.forget(result); return rv; }
nsresult NS_DeserializeObject(const nsCSubstring& str, nsISupports** obj) { // Base64 maps 3 binary bytes -> 4 ASCII bytes, so this calculation gives us // the right size. Compare also the comment in plbase64.h. PRUint32 size = (str.Length() * 3) / 4; char* buf = PL_Base64Decode(str.BeginReading(), str.Length(), nsnull); if (!buf) return NS_ERROR_OUT_OF_MEMORY; nsCOMPtr<nsIInputStream> stream; nsresult rv = NS_NewCStringInputStream(getter_AddRefs(stream), Substring(buf, buf + size)); PR_Free(buf); NS_ENSURE_SUCCESS(rv, rv); nsCOMPtr<nsIObjectInputStream> objstream = do_CreateInstance("@mozilla.org/binaryinputstream;1"); if (!objstream) return NS_ERROR_OUT_OF_MEMORY; objstream->SetInputStream(stream); return objstream->ReadObject(PR_TRUE, obj); }
nsresult NS_DeserializeObject(const nsCSubstring& str, nsISupports** obj) { // Base64 maps 3 binary bytes -> 4 ASCII bytes. If the original byte array // does not have length 0 mod 3, the input is padded with zeros and the // output is padded with a corresponding number of trailing '=' (which are // then sometimes dropped). To compute the correct length of the original // byte array, we have to subtract the number of trailing '=' and then // multiply by 3 and then divide by 4 (making sure this is an integer // division). PRUint32 size = str.Length(); if (size > 0 && str[size-1] == '=') { if (size > 1 && str[size-2] == '=') { size -= 2; } else { size -= 1; } } size = (size * 3) / 4; char* buf = PL_Base64Decode(str.BeginReading(), str.Length(), nullptr); if (!buf) return NS_ERROR_OUT_OF_MEMORY; nsCOMPtr<nsIInputStream> stream; nsresult rv = NS_NewCStringInputStream(getter_AddRefs(stream), Substring(buf, size)); PR_Free(buf); NS_ENSURE_SUCCESS(rv, rv); nsCOMPtr<nsIObjectInputStream> objstream = do_CreateInstance("@mozilla.org/binaryinputstream;1"); if (!objstream) return NS_ERROR_OUT_OF_MEMORY; objstream->SetInputStream(stream); return objstream->ReadObject(true, obj); }
NS_IMETHODIMP nsAboutBloat::NewChannel(nsIURI *aURI, nsIChannel **result) { NS_ENSURE_ARG_POINTER(aURI); nsresult rv; nsAutoCString path; rv = aURI->GetPath(path); if (NS_FAILED(rv)) return rv; nsTraceRefcntImpl::StatisticsType statType = nsTraceRefcntImpl::ALL_STATS; bool clear = false; bool leaks = false; int32_t pos = path.Find("?"); if (pos > 0) { nsAutoCString param; (void)path.Right(param, path.Length() - (pos+1)); if (param.EqualsLiteral("new")) statType = nsTraceRefcntImpl::NEW_STATS; else if (param.EqualsLiteral("clear")) clear = true; else if (param.EqualsLiteral("leaks")) leaks = true; } nsCOMPtr<nsIInputStream> inStr; if (clear) { nsTraceRefcntImpl::ResetStatistics(); rv = NS_NewCStringInputStream(getter_AddRefs(inStr), NS_LITERAL_CSTRING("Bloat statistics cleared.")); if (NS_FAILED(rv)) return rv; } else if (leaks) { // dump the current set of leaks. GC_gcollect(); rv = NS_NewCStringInputStream(getter_AddRefs(inStr), NS_LITERAL_CSTRING("Memory leaks dumped.")); if (NS_FAILED(rv)) return rv; } else { nsCOMPtr<nsIFile> file; rv = NS_GetSpecialDirectory(NS_OS_CURRENT_PROCESS_DIR, getter_AddRefs(file)); if (NS_FAILED(rv)) return rv; rv = file->AppendNative(NS_LITERAL_CSTRING("bloatlogs")); if (NS_FAILED(rv)) return rv; bool exists; rv = file->Exists(&exists); if (NS_FAILED(rv)) return rv; if (!exists) { // On all the platforms that I know use permissions, // directories need to have the executable flag set // if you want to do anything inside the directory. rv = file->Create(nsIFile::DIRECTORY_TYPE, 0755); if (NS_FAILED(rv)) return rv; } nsAutoCString dumpFileName; if (statType == nsTraceRefcntImpl::ALL_STATS) dumpFileName.AssignLiteral("all-"); else dumpFileName.AssignLiteral("new-"); PRExplodedTime expTime; PR_ExplodeTime(PR_Now(), PR_LocalTimeParameters, &expTime); char time[128]; PR_FormatTimeUSEnglish(time, 128, "%Y-%m-%d-%H%M%S.txt", &expTime); dumpFileName += time; rv = file->AppendNative(dumpFileName); if (NS_FAILED(rv)) return rv; FILE* out; rv = file->OpenANSIFileDesc("w", &out); if (NS_FAILED(rv)) return rv; rv = nsTraceRefcntImpl::DumpStatistics(statType, out); ::fclose(out); if (NS_FAILED(rv)) return rv; rv = NS_NewLocalFileInputStream(getter_AddRefs(inStr), file); if (NS_FAILED(rv)) return rv; } nsIChannel* channel; rv = NS_NewInputStreamChannel(&channel, aURI, inStr, NS_LITERAL_CSTRING("text/plain"), NS_LITERAL_CSTRING("utf-8")); if (NS_FAILED(rv)) return rv; *result = channel; return rv; }
nsresult nsIndexedToHTML::FormatInputStream(nsIRequest* aRequest, nsISupports *aContext, const nsAString &aBuffer) { nsresult rv = NS_OK; // set up unicode encoder if (!mUnicodeEncoder) { nsXPIDLCString encoding; rv = mParser->GetEncoding(getter_Copies(encoding)); if (NS_SUCCEEDED(rv)) { nsCOMPtr<nsICharsetConverterManager> charsetConverterManager; charsetConverterManager = do_GetService(NS_CHARSETCONVERTERMANAGER_CONTRACTID, &rv); rv = charsetConverterManager->GetUnicodeEncoder(encoding.get(), getter_AddRefs(mUnicodeEncoder)); if (NS_SUCCEEDED(rv)) rv = mUnicodeEncoder->SetOutputErrorBehavior(nsIUnicodeEncoder::kOnError_Replace, nsnull, (PRUnichar)'?'); } } // convert the data with unicode encoder char *buffer = nsnull; PRInt32 dstLength; if (NS_SUCCEEDED(rv)) { PRInt32 unicharLength = aBuffer.Length(); rv = mUnicodeEncoder->GetMaxLength(PromiseFlatString(aBuffer).get(), unicharLength, &dstLength); if (NS_SUCCEEDED(rv)) { buffer = (char *) nsMemory::Alloc(dstLength); NS_ENSURE_TRUE(buffer, NS_ERROR_OUT_OF_MEMORY); rv = mUnicodeEncoder->Convert(PromiseFlatString(aBuffer).get(), &unicharLength, buffer, &dstLength); if (NS_SUCCEEDED(rv)) { PRInt32 finLen = 0; rv = mUnicodeEncoder->Finish(buffer + dstLength, &finLen); if (NS_SUCCEEDED(rv)) dstLength += finLen; } } } // if conversion error then fallback to UTF-8 if (NS_FAILED(rv)) { rv = NS_OK; if (buffer) { nsMemory::Free(buffer); buffer = nsnull; } } nsCOMPtr<nsIInputStream> inputData; if (buffer) { rv = NS_NewCStringInputStream(getter_AddRefs(inputData), Substring(buffer, buffer + dstLength)); nsMemory::Free(buffer); NS_ENSURE_SUCCESS(rv, rv); rv = mListener->OnDataAvailable(aRequest, aContext, inputData, 0, dstLength); } else { NS_ConvertUTF16toUTF8 utf8Buffer(aBuffer); rv = NS_NewCStringInputStream(getter_AddRefs(inputData), utf8Buffer); NS_ENSURE_SUCCESS(rv, rv); rv = mListener->OnDataAvailable(aRequest, aContext, inputData, 0, utf8Buffer.Length()); } return (rv); }
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(); }
// nsIStreamListener implementation NS_IMETHODIMP nsFTPDirListingConv::OnDataAvailable(nsIRequest* request, nsISupports *ctxt, nsIInputStream *inStr, uint32_t sourceOffset, uint32_t count) { NS_ASSERTION(request, "FTP dir listing stream converter needs a request"); nsresult rv; nsCOMPtr<nsIChannel> channel = do_QueryInterface(request, &rv); NS_ENSURE_SUCCESS(rv, rv); uint32_t read, streamLen; uint64_t streamLen64; rv = inStr->Available(&streamLen64); NS_ENSURE_SUCCESS(rv, rv); streamLen = (uint32_t)NS_MIN(streamLen64, uint64_t(PR_UINT32_MAX - 1)); nsAutoArrayPtr<char> buffer(new char[streamLen + 1]); NS_ENSURE_TRUE(buffer, NS_ERROR_OUT_OF_MEMORY); rv = inStr->Read(buffer, streamLen, &read); NS_ENSURE_SUCCESS(rv, rv); // the dir listings are ascii text, null terminate this sucker. buffer[streamLen] = '\0'; PR_LOG(gFTPDirListConvLog, PR_LOG_DEBUG, ("nsFTPDirListingConv::OnData(request = %x, ctxt = %x, inStr = %x, sourceOffset = %d, count = %d)\n", request, ctxt, inStr, sourceOffset, count)); if (!mBuffer.IsEmpty()) { // we have data left over from a previous OnDataAvailable() call. // combine the buffers so we don't lose any data. mBuffer.Append(buffer); buffer = new char[mBuffer.Length()+1]; NS_ENSURE_TRUE(buffer, NS_ERROR_OUT_OF_MEMORY); strncpy(buffer, mBuffer.get(), mBuffer.Length()+1); mBuffer.Truncate(); } #ifndef DEBUG_dougt PR_LOG(gFTPDirListConvLog, PR_LOG_DEBUG, ("::OnData() received the following %d bytes...\n\n%s\n\n", streamLen, buffer.get()) ); #else printf("::OnData() received the following %d bytes...\n\n%s\n\n", streamLen, buffer); #endif // DEBUG_dougt nsCAutoString indexFormat; if (!mSentHeading) { // build up the 300: line nsCOMPtr<nsIURI> uri; rv = channel->GetURI(getter_AddRefs(uri)); NS_ENSURE_SUCCESS(rv, rv); rv = GetHeaders(indexFormat, uri); NS_ENSURE_SUCCESS(rv, rv); mSentHeading = true; } char *line = buffer; line = DigestBufferLines(line, indexFormat); #ifndef DEBUG_dougt PR_LOG(gFTPDirListConvLog, PR_LOG_DEBUG, ("::OnData() sending the following %d bytes...\n\n%s\n\n", indexFormat.Length(), indexFormat.get()) ); #else char *unescData = ToNewCString(indexFormat); NS_ENSURE_TRUE(unescData, NS_ERROR_OUT_OF_MEMORY); nsUnescape(unescData); printf("::OnData() sending the following %d bytes...\n\n%s\n\n", indexFormat.Length(), unescData); nsMemory::Free(unescData); #endif // DEBUG_dougt // if there's any data left over, buffer it. if (line && *line) { mBuffer.Append(line); PR_LOG(gFTPDirListConvLog, PR_LOG_DEBUG, ("::OnData() buffering the following %d bytes...\n\n%s\n\n", PL_strlen(line), line) ); } // send the converted data out. nsCOMPtr<nsIInputStream> inputData; rv = NS_NewCStringInputStream(getter_AddRefs(inputData), indexFormat); NS_ENSURE_SUCCESS(rv, rv); rv = mFinalListener->OnDataAvailable(request, ctxt, inputData, 0, indexFormat.Length()); return rv; }
void BlobImplString::GetInternalStream(nsIInputStream** aStream, ErrorResult& aRv) { aRv = NS_NewCStringInputStream(aStream, mData); }
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")) { // Use nsDataHandler directly so that we can extract the content type. // XXX(nsm): Is there a way to acquire the charset without such tight // coupling with the DataHandler? nsIProtocolHandler does not provide // anything similar. nsAutoCString contentType, contentCharset, dataBuffer, hashRef; bool isBase64; rv = nsDataHandler::ParseURI(url, contentType, contentCharset, isBase64, dataBuffer, hashRef); if (NS_SUCCEEDED(rv)) { ErrorResult result; nsRefPtr<InternalResponse> response = new InternalResponse(200, NS_LITERAL_CSTRING("OK")); if (!contentCharset.IsEmpty()) { contentType.Append(";charset="); contentType.Append(contentCharset); } response->Headers()->Append(NS_LITERAL_CSTRING("Content-Type"), contentType, result); if (!result.Failed()) { nsCOMPtr<nsIInputStream> stream; rv = NS_NewCStringInputStream(getter_AddRefs(stream), dataBuffer); if (NS_SUCCEEDED(rv)) { response->SetBody(stream); BeginResponse(response); return SucceedWithResponse(); } } } } return FailWithNetworkError(); } if (scheme.LowerCaseEqualsLiteral("http") || scheme.LowerCaseEqualsLiteral("https") || scheme.LowerCaseEqualsLiteral("app")) { return HttpFetch(); } return FailWithNetworkError(); }
NS_DECL_THREADSAFE_ISUPPORTS explicit NonSeekableStringStream(const nsACString& aBuffer) { NS_NewCStringInputStream(getter_AddRefs(mStream), aBuffer); }