author | Benjamin Smedberg <benjamin@smedbergs.us> |
Thu, 03 Nov 2016 10:30:46 -0400 | |
changeset 433332 | 96ca246a41990c692b78ffa2b758e24b44f2649f |
parent 429179 | c6ccd71126ff514bfc44b53e2217562e29a0cc38 |
child 433333 | ecca4679a7adf5e467fb7b46344916861c213235 |
push id | 34544 |
push user | bsmedberg@mozilla.com |
push date | Thu, 03 Nov 2016 14:45:33 +0000 |
reviewers | michal.novotny |
bugs | 1313752 |
milestone | 52.0a1 |
--- a/netwerk/streamconv/moz.build +++ b/netwerk/streamconv/moz.build @@ -1,16 +1,15 @@ # -*- Mode: python; indent-tabs-mode: nil; tab-width: 40 -*- # vim: set filetype=python: # This Source Code Form is subject to the terms of the Mozilla Public # License, v. 2.0. If a copy of the MPL was not distributed with this # file, You can obtain one at http://mozilla.org/MPL/2.0/. DIRS += ['converters'] -TEST_DIRS += ['test'] XPIDL_SOURCES += [ 'mozITXTToHTMLConv.idl', 'nsIDirIndex.idl', 'nsIDirIndexListener.idl', 'nsIStreamConverter.idl', 'nsIStreamConverterService.idl', 'nsITXTToHTMLConv.idl',
deleted file mode 100644 --- a/netwerk/streamconv/test/Converters.cpp +++ /dev/null @@ -1,140 +0,0 @@ -#include "Converters.h" -#include "nsIStringStream.h" -#include "nsCOMPtr.h" -#include "nsComponentManagerUtils.h" - -#include <stdio.h> - -////////////////////////////////////////////////// -// TestConverter -////////////////////////////////////////////////// - -#define NS_TESTCONVERTER_CID \ -{ /* B8A067B0-4450-11d3-A16E-0050041CAF44 */ \ - 0xb8a067b0, \ - 0x4450, \ - 0x11d3, \ - {0xa1, 0x6e, 0x00, 0x50, 0x04, 0x1c, 0xaf, 0x44} \ -} - -NS_DEFINE_CID(kTestConverterCID, NS_TESTCONVERTER_CID); - -NS_IMPL_ISUPPORTS(TestConverter, - nsIStreamConverter, - nsIStreamListener, - nsIRequestObserver) - -TestConverter::TestConverter() { -} - -// 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]; - uint32_t 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 (uint32_t i = 0; i < read; i++) - buf[i] = toChar; - - buf[read] = '\0'; - - nsCOMPtr<nsIStringInputStream> str - (do_CreateInstance("@mozilla.org/io/string-input-stream;1", &rv)); - NS_ENSURE_SUCCESS(rv, rv); - - rv = str->SetData(buf, read); - NS_ENSURE_SUCCESS(rv, rv); - - NS_ADDREF(*_retval = str); - return NS_OK; -} - -/* This method initializes any internal state before the stream converter - * begins asynchronous conversion */ -NS_IMETHODIMP -TestConverter::AsyncConvertData(const char *aFromType, - const char *aToType, - nsIStreamListener *aListener, - nsISupports *ctxt) { - NS_ASSERTION(aListener, "null listener"); - - mListener = aListener; - - // based on these types, setup internal state to handle the appropriate conversion. - fromType = aFromType; - toType = aToType; - - return NS_OK; -} - -// nsIStreamListener method -/* This method handles asyncronous conversion of data. */ -NS_IMETHODIMP -TestConverter::OnDataAvailable(nsIRequest* request, - nsISupports *ctxt, - nsIInputStream *inStr, - uint64_t sourceOffset, - uint32_t count) { - nsresult rv; - nsCOMPtr<nsIInputStream> convertedStream; - // just make a syncronous call to the Convert() method. - // Anything can happen here, I just happen to be using the sync call to - // do the actual conversion. - rv = Convert(inStr, fromType.get(), toType.get(), ctxt, getter_AddRefs(convertedStream)); - if (NS_FAILED(rv)) return rv; - - uint64_t len = 0; - convertedStream->Available(&len); - - uint64_t offset = sourceOffset; - while (len > 0) { - uint32_t count = saturated(len); - rv = mListener->OnDataAvailable(request, ctxt, convertedStream, offset, count); - if (NS_FAILED(rv)) return rv; - - offset += count; - len -= count; - } - return NS_OK; -} - -// nsIRequestObserver methods -/* These methods just pass through directly to the mListener */ -NS_IMETHODIMP -TestConverter::OnStartRequest(nsIRequest* request, nsISupports *ctxt) { - return mListener->OnStartRequest(request, ctxt); -} - -NS_IMETHODIMP -TestConverter::OnStopRequest(nsIRequest* request, nsISupports *ctxt, - nsresult aStatus) { - return mListener->OnStopRequest(request, ctxt, aStatus); -} - -nsresult -CreateTestConverter(nsISupports* aOuter, REFNSIID aIID, void** aResult) -{ - nsCOMPtr<nsISupports> conv = new TestConverter(); - return conv->QueryInterface(aIID, aResult); -}
deleted file mode 100644 --- a/netwerk/streamconv/test/Converters.h +++ /dev/null @@ -1,52 +0,0 @@ -#ifndef Converters_h___ -#define Converters_h___ - -#include "nsIStreamConverter.h" -#include "nsIFactory.h" -#include "nsCOMPtr.h" -#include "nsStringAPI.h" - -#include <algorithm> - -/* This file defines stream converter components, and their accompanying factory class. - * These converters implement the nsIStreamConverter interface and support both - * asynchronous and synchronous stream conversion. - */ - -/////////////////////////////////////////////// -// TestConverter - -extern const nsCID kTestConverterCID; - -class TestConverter : public nsIStreamConverter { - virtual ~TestConverter() {} -public: - NS_DECL_ISUPPORTS - NS_DECL_NSIREQUESTOBSERVER - NS_DECL_NSISTREAMLISTENER - - TestConverter(); - - // nsIStreamConverter methods - NS_IMETHOD Convert(nsIInputStream *aFromStream, const char *aFromType, - const char *aToType, nsISupports *ctxt, nsIInputStream **_retval) override; - - - NS_IMETHOD AsyncConvertData(const char *aFromType, const char *aToType, - nsIStreamListener *aListener, nsISupports *ctxt) override; - - // member data - nsCOMPtr<nsIStreamListener> mListener; - nsCString fromType; - nsCString toType; -}; - -nsresult CreateTestConverter(nsISupports* aOuter, REFNSIID aIID, void** aResult); - -static inline uint32_t -saturated(uint64_t aValue) -{ - return (uint32_t) std::min(aValue, (uint64_t) UINT32_MAX); -} - -#endif /* !Converters_h___ */
deleted file mode 100644 --- a/netwerk/streamconv/test/TestStreamConv.cpp +++ /dev/null @@ -1,261 +0,0 @@ -/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -#include "nsIServiceManager.h" -#include "nsIStreamConverterService.h" -#include "nsIStreamConverter.h" -#include "nsICategoryManager.h" -#include "mozilla/Module.h" -#include "nsXULAppAPI.h" -#include "nsIStringStream.h" -#include "nsCOMPtr.h" -#include "nsThreadUtils.h" -#include "mozilla/Attributes.h" -#include "nsMemory.h" -#include "nsServiceManagerUtils.h" -#include "nsComponentManagerUtils.h" -#include "nsIRequest.h" -#include "nsNetCID.h" -#include "nsNetUtil.h" - -#define ASYNC_TEST // undefine this if you want to test sycnronous conversion. - -///////////////////////////////// -// Event pump setup -///////////////////////////////// -#ifdef XP_WIN -#include <windows.h> -#endif - -static int gKeepRunning = 0; -///////////////////////////////// -// Event pump END -///////////////////////////////// - - -///////////////////////////////// -// Test converters include -///////////////////////////////// -#include "Converters.h" - -// CID setup -static NS_DEFINE_CID(kStreamConverterServiceCID, NS_STREAMCONVERTERSERVICE_CID); - -//////////////////////////////////////////////////////////////////////// -// EndListener - This listener is the final one in the chain. It -// receives the fully converted data, although it doesn't do anything with -// the data. -//////////////////////////////////////////////////////////////////////// -class EndListener final : public nsIStreamListener { - ~EndListener() {} -public: - // nsISupports declaration - NS_DECL_ISUPPORTS - - EndListener() {} - - // nsIStreamListener method - NS_IMETHOD OnDataAvailable(nsIRequest* request, nsISupports *ctxt, nsIInputStream *inStr, - uint64_t sourceOffset, uint32_t count) override - { - nsresult rv; - uint32_t read; - uint64_t len64; - rv = inStr->Available(&len64); - if (NS_FAILED(rv)) return rv; - uint32_t len = (uint32_t)std::min(len64, (uint64_t)(UINT32_MAX - 1)); - - char *buffer = (char*)moz_xmalloc(len + 1); - if (!buffer) return NS_ERROR_OUT_OF_MEMORY; - - rv = inStr->Read(buffer, len, &read); - buffer[len] = '\0'; - if (NS_SUCCEEDED(rv)) { - printf("CONTEXT %p: Received %u bytes and the following data: \n %s\n\n", - static_cast<void*>(ctxt), read, buffer); - } - free(buffer); - - return NS_OK; - } - - // nsIRequestObserver methods - NS_IMETHOD OnStartRequest(nsIRequest* request, nsISupports *ctxt) override { return NS_OK; } - - NS_IMETHOD OnStopRequest(nsIRequest* request, nsISupports *ctxt, - nsresult aStatus) override { return NS_OK; } -}; - -NS_IMPL_ISUPPORTS(EndListener, - nsIStreamListener, - nsIRequestObserver) - -//////////////////////////////////////////////////////////////////////// -// EndListener END -//////////////////////////////////////////////////////////////////////// - -nsresult SendData(const char * aData, nsIStreamListener* aListener, nsIRequest* request) { - nsresult rv; - - nsCOMPtr<nsIStringInputStream> dataStream - (do_CreateInstance("@mozilla.org/io/string-input-stream;1", &rv)); - NS_ENSURE_SUCCESS(rv, rv); - - rv = dataStream->SetData(aData, strlen(aData)); - NS_ENSURE_SUCCESS(rv, rv); - - uint64_t avail = 0; - dataStream->Available(&avail); - - uint64_t offset = 0; - while (avail > 0) { - uint32_t count = saturated(avail); - rv = aListener->OnDataAvailable(request, nullptr, dataStream, - offset, count); - if (NS_FAILED(rv)) return rv; - - offset += count; - avail -= count; - } - return NS_OK; -} -#define SEND_DATA(x) SendData(x, converterListener, request) - -static const mozilla::Module::CIDEntry kTestCIDs[] = { - { &kTestConverterCID, false, nullptr, CreateTestConverter }, - { nullptr } -}; - -static const mozilla::Module::ContractIDEntry kTestContracts[] = { - { NS_ISTREAMCONVERTER_KEY "?from=a/foo&to=b/foo", &kTestConverterCID }, - { NS_ISTREAMCONVERTER_KEY "?from=b/foo&to=c/foo", &kTestConverterCID }, - { NS_ISTREAMCONVERTER_KEY "?from=b/foo&to=d/foo", &kTestConverterCID }, - { NS_ISTREAMCONVERTER_KEY "?from=c/foo&to=d/foo", &kTestConverterCID }, - { NS_ISTREAMCONVERTER_KEY "?from=d/foo&to=e/foo", &kTestConverterCID }, - { NS_ISTREAMCONVERTER_KEY "?from=d/foo&to=f/foo", &kTestConverterCID }, - { NS_ISTREAMCONVERTER_KEY "?from=t/foo&to=k/foo", &kTestConverterCID }, - { nullptr } -}; - -static const mozilla::Module::CategoryEntry kTestCategories[] = { - { NS_ISTREAMCONVERTER_KEY, "?from=a/foo&to=b/foo", "x" }, - { NS_ISTREAMCONVERTER_KEY, "?from=b/foo&to=c/foo", "x" }, - { NS_ISTREAMCONVERTER_KEY, "?from=b/foo&to=d/foo", "x" }, - { NS_ISTREAMCONVERTER_KEY, "?from=c/foo&to=d/foo", "x" }, - { NS_ISTREAMCONVERTER_KEY, "?from=d/foo&to=e/foo", "x" }, - { NS_ISTREAMCONVERTER_KEY, "?from=d/foo&to=f/foo", "x" }, - { NS_ISTREAMCONVERTER_KEY, "?from=t/foo&to=k/foo", "x" }, - { nullptr } -}; - -static const mozilla::Module kTestModule = { - mozilla::Module::kVersion, - kTestCIDs, - kTestContracts, - kTestCategories -}; - -int -main(int argc, char* argv[]) -{ - nsresult rv; - { - XRE_AddStaticComponent(&kTestModule); - - nsCOMPtr<nsIServiceManager> servMan; - NS_InitXPCOM2(getter_AddRefs(servMan), nullptr, nullptr); - - nsCOMPtr<nsIThread> thread = do_GetCurrentThread(); - - nsCOMPtr<nsICategoryManager> catman = - do_GetService(NS_CATEGORYMANAGER_CONTRACTID, &rv); - if (NS_FAILED(rv)) return -1; - nsCString previous; - - nsCOMPtr<nsIStreamConverterService> StreamConvService = - do_GetService(kStreamConverterServiceCID, &rv); - if (NS_FAILED(rv)) return -1; - - // Define the *from* content type and *to* content-type for conversion. - static const char fromStr[] = "a/foo"; - static const char toStr[] = "c/foo"; - -#ifdef ASYNC_TEST - // ASYNCHRONOUS conversion - - // Build up a channel that represents the content we're - // starting the transaction with. - // - // sample multipart mixed content-type string: - // "multipart/x-mixed-replacE;boundary=thisrandomstring" -#if 0 - nsCOMPtr<nsIChannel> channel; - nsCOMPtr<nsIURI> dummyURI; - rv = NS_NewURI(getter_AddRefs(dummyURI), "http://meaningless"); - if (NS_FAILED(rv)) return -1; - - rv = NS_NewInputStreamChannel(getter_AddRefs(channel), - dummyURI, - nullptr, // inStr - "text/plain", // content-type - -1); // XXX fix contentLength - if (NS_FAILED(rv)) return -1; - - nsCOMPtr<nsIRequest> request(do_QueryInterface(channel)); -#endif - - nsCOMPtr<nsIRequest> request; - - // setup a listener to receive the converted data. This guy is the end - // listener in the chain, he wants the fully converted (toType) data. - // An example of this listener in mozilla would be the DocLoader. - nsIStreamListener *dataReceiver = new EndListener(); - NS_ADDREF(dataReceiver); - - // setup a listener to push the data into. This listener sits inbetween the - // unconverted data of fromType, and the final listener in the chain (in this case - // the dataReceiver. - nsIStreamListener *converterListener = nullptr; - rv = StreamConvService->AsyncConvertData(fromStr, toStr, - dataReceiver, nullptr, &converterListener); - if (NS_FAILED(rv)) return -1; - NS_RELEASE(dataReceiver); - - // at this point we have a stream listener to push data to, and the one - // that will receive the converted data. Let's mimic On*() calls and get the conversion - // going. Typically these On*() calls would be made inside their respective wrappers On*() - // methods. - rv = converterListener->OnStartRequest(request, nullptr); - if (NS_FAILED(rv)) return -1; - - rv = SEND_DATA("aaa"); - if (NS_FAILED(rv)) return -1; - - rv = SEND_DATA("aaa"); - if (NS_FAILED(rv)) return -1; - - // Finish the request. - rv = converterListener->OnStopRequest(request, nullptr, rv); - if (NS_FAILED(rv)) return -1; - - NS_RELEASE(converterListener); -#else - // SYNCHRONOUS conversion - nsCOMPtr<nsIInputStream> convertedData; - rv = StreamConvService->Convert(inputData, fromStr, toStr, - nullptr, getter_AddRefs(convertedData)); - if (NS_FAILED(rv)) return -1; -#endif - - // Enter the message pump to allow the URL load to proceed. - while ( gKeepRunning ) { - if (!NS_ProcessNextEvent(thread)) - break; - } - } // this scopes the nsCOMPtrs - // no nsCOMPtrs are allowed to be alive when you call NS_ShutdownXPCOM - NS_ShutdownXPCOM(nullptr); - return 0; -}
deleted file mode 100644 --- a/netwerk/streamconv/test/moz.build +++ /dev/null @@ -1,22 +0,0 @@ -# -*- Mode: python; indent-tabs-mode: nil; tab-width: 40 -*- -# vim: set filetype=python: -# This Source Code Form is subject to the terms of the Mozilla Public -# License, v. 2.0. If a copy of the MPL was not distributed with this -# file, You can obtain one at http://mozilla.org/MPL/2.0/. - -GeckoProgram('TestStreamConv', linkage='dependent') - -UNIFIED_SOURCES += [ - 'Converters.cpp', - 'TestStreamConv.cpp', -] - -if CONFIG['OS_ARCH'] == 'WINNT': - DEFINES['NGPREFS'] = True - if CONFIG['GNU_CXX']: - LDFLAGS += ['-mconsole'] - else: - LDFLAGS += ['-SUBSYSTEM:CONSOLE'] - -if CONFIG['GNU_CXX']: - CXXFLAGS += ['-Wno-error=shadow']
deleted file mode 100644 --- a/netwerk/test/PropertiesTest.cpp +++ /dev/null @@ -1,131 +0,0 @@ -/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -#include "TestCommon.h" -#include "mozilla/Sprintf.h" -#include "nsXPCOM.h" -#include "nsStringAPI.h" -#include "nsIPersistentProperties2.h" -#include "nsIServiceManager.h" -#include "nsIComponentRegistrar.h" -#include "nsIURL.h" -#include "nsNetCID.h" -#include "nsIChannel.h" -#include "nsIComponentManager.h" -#include <stdio.h> -#include "nsComponentManagerUtils.h" -#include "nsServiceManagerUtils.h" -#include "nsISimpleEnumerator.h" -#include "nsIScriptSecurityManager.h" -#include "nsILoadInfo.h" -#include "nsNetUtil.h" - -#define TEST_URL "resource:/res/test.properties" -static NS_DEFINE_CID(kPersistentPropertiesCID, NS_IPERSISTENTPROPERTIES_CID); - -/***************************************************************************/ - -int -main(int argc, char* argv[]) -{ - if (test_common_init(&argc, &argv) != 0) - return -1; - - nsresult ret; - - nsCOMPtr<nsIServiceManager> servMan; - NS_InitXPCOM2(getter_AddRefs(servMan), nullptr, nullptr); - - nsIInputStream* in = nullptr; - - nsCOMPtr<nsIScriptSecurityManager> secman = - do_GetService(NS_SCRIPTSECURITYMANAGER_CONTRACTID, &ret); - if (NS_FAILED(ret)) return 1; - nsCOMPtr<nsIPrincipal> systemPrincipal; - ret = secman->GetSystemPrincipal(getter_AddRefs(systemPrincipal)); - if (NS_FAILED(ret)) return 1; - - nsCOMPtr<nsIURI> uri; - ret = NS_NewURI(getter_AddRefs(uri), NS_LITERAL_CSTRING(TEST_URL)); - if (NS_FAILED(ret)) return 1; - - nsIChannel *channel = nullptr; - ret = NS_NewChannel(&channel, - uri, - systemPrincipal, - nsILoadInfo::SEC_ALLOW_CROSS_ORIGIN_DATA_IS_NULL, - nsIContentPolicy::TYPE_OTHER); - if (NS_FAILED(ret)) return 1; - - ret = channel->Open2(&in); - if (NS_FAILED(ret)) return 1; - - nsIPersistentProperties* props; - ret = CallCreateInstance(kPersistentPropertiesCID, &props); - if (NS_FAILED(ret) || (!props)) { - printf("create nsIPersistentProperties failed\n"); - return 1; - } - ret = props->Load(in); - if (NS_FAILED(ret)) { - printf("cannot load properties\n"); - return 1; - } - int i = 1; - while (1) { - char name[16]; - name[0] = 0; - SprintfLiteral(name, "%d", i); - nsAutoString v; - ret = props->GetStringProperty(nsDependentCString(name), v); - if (NS_FAILED(ret) || (!v.Length())) { - break; - } - printf("\"%d\"=\"%s\"\n", i, NS_ConvertUTF16toUTF8(v).get()); - i++; - } - - nsCOMPtr<nsISimpleEnumerator> propEnum; - ret = props->Enumerate(getter_AddRefs(propEnum)); - - if (NS_FAILED(ret)) { - printf("cannot enumerate properties\n"); - return 1; - } - - - printf("\nKey\tValue\n"); - printf( "---\t-----\n"); - - bool hasMore; - while (NS_SUCCEEDED(propEnum->HasMoreElements(&hasMore)) && - hasMore) { - nsCOMPtr<nsISupports> sup; - ret = propEnum->GetNext(getter_AddRefs(sup)); - - nsCOMPtr<nsIPropertyElement> propElem = do_QueryInterface(sup, &ret); - if (NS_FAILED(ret)) { - printf("failed to get current item\n"); - return 1; - } - - nsAutoCString key; - nsAutoString value; - - ret = propElem->GetKey(key); - if (NS_FAILED(ret)) { - printf("failed to get current element's key\n"); - return 1; - } - ret = propElem->GetValue(value); - if (NS_FAILED(ret)) { - printf("failed to get current element's value\n"); - return 1; - } - - printf("%s\t%s\n", key.get(), NS_ConvertUTF16toUTF8(value).get()); - } - return 0; -}
deleted file mode 100644 --- a/netwerk/test/ReadNTLM.cpp +++ /dev/null @@ -1,325 +0,0 @@ -/* vim: set ts=2 sw=2 et cindent: */ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -#include <stdlib.h> -#include <stdio.h> -#include <ctype.h> - -#include "plbase64.h" -#include "nsStringAPI.h" -#include "prmem.h" - -/* - * ReadNTLM : reads NTLM messages. - * - * based on http://davenport.sourceforge.net/ntlm.html - */ - -#define kNegotiateUnicode 0x00000001 -#define kNegotiateOEM 0x00000002 -#define kRequestTarget 0x00000004 -#define kUnknown1 0x00000008 -#define kNegotiateSign 0x00000010 -#define kNegotiateSeal 0x00000020 -#define kNegotiateDatagramStyle 0x00000040 -#define kNegotiateLanManagerKey 0x00000080 -#define kNegotiateNetware 0x00000100 -#define kNegotiateNTLMKey 0x00000200 -#define kUnknown2 0x00000400 -#define kUnknown3 0x00000800 -#define kNegotiateDomainSupplied 0x00001000 -#define kNegotiateWorkstationSupplied 0x00002000 -#define kNegotiateLocalCall 0x00004000 -#define kNegotiateAlwaysSign 0x00008000 -#define kTargetTypeDomain 0x00010000 -#define kTargetTypeServer 0x00020000 -#define kTargetTypeShare 0x00040000 -#define kNegotiateNTLM2Key 0x00080000 -#define kRequestInitResponse 0x00100000 -#define kRequestAcceptResponse 0x00200000 -#define kRequestNonNTSessionKey 0x00400000 -#define kNegotiateTargetInfo 0x00800000 -#define kUnknown4 0x01000000 -#define kUnknown5 0x02000000 -#define kUnknown6 0x04000000 -#define kUnknown7 0x08000000 -#define kUnknown8 0x10000000 -#define kNegotiate128 0x20000000 -#define kNegotiateKeyExchange 0x40000000 -#define kNegotiate56 0x80000000 - -static const char NTLM_SIGNATURE[] = "NTLMSSP"; -static const char NTLM_TYPE1_MARKER[] = { 0x01, 0x00, 0x00, 0x00 }; -static const char NTLM_TYPE2_MARKER[] = { 0x02, 0x00, 0x00, 0x00 }; -static const char NTLM_TYPE3_MARKER[] = { 0x03, 0x00, 0x00, 0x00 }; - -#define NTLM_MARKER_LEN 4 -#define NTLM_TYPE1_HEADER_LEN 32 -#define NTLM_TYPE2_HEADER_LEN 32 -#define NTLM_TYPE3_HEADER_LEN 64 - -#define LM_HASH_LEN 16 -#define LM_RESP_LEN 24 - -#define NTLM_HASH_LEN 16 -#define NTLM_RESP_LEN 24 - -static void PrintFlags(uint32_t flags) -{ -#define TEST(_flag) \ - if (flags & k ## _flag) \ - printf(" 0x%08x (" # _flag ")\n", k ## _flag) - - TEST(NegotiateUnicode); - TEST(NegotiateOEM); - TEST(RequestTarget); - TEST(Unknown1); - TEST(NegotiateSign); - TEST(NegotiateSeal); - TEST(NegotiateDatagramStyle); - TEST(NegotiateLanManagerKey); - TEST(NegotiateNetware); - TEST(NegotiateNTLMKey); - TEST(Unknown2); - TEST(Unknown3); - TEST(NegotiateDomainSupplied); - TEST(NegotiateWorkstationSupplied); - TEST(NegotiateLocalCall); - TEST(NegotiateAlwaysSign); - TEST(TargetTypeDomain); - TEST(TargetTypeServer); - TEST(TargetTypeShare); - TEST(NegotiateNTLM2Key); - TEST(RequestInitResponse); - TEST(RequestAcceptResponse); - TEST(RequestNonNTSessionKey); - TEST(NegotiateTargetInfo); - TEST(Unknown4); - TEST(Unknown5); - TEST(Unknown6); - TEST(Unknown7); - TEST(Unknown8); - TEST(Negotiate128); - TEST(NegotiateKeyExchange); - TEST(Negotiate56); - -#undef TEST -} - -static void -PrintBuf(const char *tag, const uint8_t *buf, uint32_t bufLen) -{ - int i; - - printf("%s =\n", tag); - while (bufLen > 0) - { - int count = bufLen; - if (count > 8) - count = 8; - - printf(" "); - for (i=0; i<count; ++i) - { - printf("0x%02x ", int(buf[i])); - } - for (; i<8; ++i) - { - printf(" "); - } - - printf(" "); - for (i=0; i<count; ++i) - { - if (isprint(buf[i])) - printf("%c", buf[i]); - else - printf("."); - } - printf("\n"); - - bufLen -= count; - buf += count; - } -} - -static uint16_t -ReadUint16(const uint8_t *&buf) -{ - uint16_t x; -#ifdef IS_BIG_ENDIAN - x = ((uint16_t) buf[1]) | ((uint16_t) buf[0] << 8); -#else - x = ((uint16_t) buf[0]) | ((uint16_t) buf[1] << 8); -#endif - buf += sizeof(x); - return x; -} - -static uint32_t -ReadUint32(const uint8_t *&buf) -{ - uint32_t x; -#ifdef IS_BIG_ENDIAN - x = ( (uint32_t) buf[3]) | - (((uint32_t) buf[2]) << 8) | - (((uint32_t) buf[1]) << 16) | - (((uint32_t) buf[0]) << 24); -#else - x = ( (uint32_t) buf[0]) | - (((uint32_t) buf[1]) << 8) | - (((uint32_t) buf[2]) << 16) | - (((uint32_t) buf[3]) << 24); -#endif - buf += sizeof(x); - return x; -} - -typedef struct { - uint16_t length; - uint16_t capacity; - uint32_t offset; -} SecBuf; - -static void -ReadSecBuf(SecBuf *s, const uint8_t *&buf) -{ - s->length = ReadUint16(buf); - s->capacity = ReadUint16(buf); - s->offset = ReadUint32(buf); -} - -static void -ReadType1MsgBody(const uint8_t *inBuf, uint32_t start) -{ - const uint8_t *cursor = inBuf + start; - uint32_t flags; - - PrintBuf("flags", cursor, 4); - // read flags - flags = ReadUint32(cursor); - PrintFlags(flags); - - // type 1 message may not include trailing security buffers - if ((flags & kNegotiateDomainSupplied) | - (flags & kNegotiateWorkstationSupplied)) - { - SecBuf secbuf; - ReadSecBuf(&secbuf, cursor); - PrintBuf("supplied domain", inBuf + secbuf.offset, secbuf.length); - - ReadSecBuf(&secbuf, cursor); - PrintBuf("supplied workstation", inBuf + secbuf.offset, secbuf.length); - } -} - -static void -ReadType2MsgBody(const uint8_t *inBuf, uint32_t start) -{ - uint16_t targetLen, offset; - uint32_t flags; - const uint8_t *target; - const uint8_t *cursor = inBuf + start; - - // read target name security buffer - targetLen = ReadUint16(cursor); - ReadUint16(cursor); // discard next 16-bit value - offset = ReadUint32(cursor); // get offset from inBuf - target = inBuf + offset; - - PrintBuf("target", target, targetLen); - - PrintBuf("flags", cursor, 4); - // read flags - flags = ReadUint32(cursor); - PrintFlags(flags); - - // read challenge - PrintBuf("challenge", cursor, 8); - cursor += 8; - - PrintBuf("context", cursor, 8); - cursor += 8; - - SecBuf secbuf; - ReadSecBuf(&secbuf, cursor); - PrintBuf("target information", inBuf + secbuf.offset, secbuf.length); -} - -static void -ReadType3MsgBody(const uint8_t *inBuf, uint32_t start) -{ - const uint8_t *cursor = inBuf + start; - - SecBuf secbuf; - - ReadSecBuf(&secbuf, cursor); // LM response - PrintBuf("LM response", inBuf + secbuf.offset, secbuf.length); - - ReadSecBuf(&secbuf, cursor); // NTLM response - PrintBuf("NTLM response", inBuf + secbuf.offset, secbuf.length); - - ReadSecBuf(&secbuf, cursor); // domain name - PrintBuf("domain name", inBuf + secbuf.offset, secbuf.length); - - ReadSecBuf(&secbuf, cursor); // user name - PrintBuf("user name", inBuf + secbuf.offset, secbuf.length); - - ReadSecBuf(&secbuf, cursor); // workstation name - PrintBuf("workstation name", inBuf + secbuf.offset, secbuf.length); - - ReadSecBuf(&secbuf, cursor); // session key - PrintBuf("session key", inBuf + secbuf.offset, secbuf.length); - - uint32_t flags = ReadUint32(cursor); - PrintBuf("flags", (const uint8_t *) &flags, sizeof(flags)); - PrintFlags(flags); -} - -static void -ReadMsg(const char *base64buf, uint32_t bufLen) -{ - uint8_t *inBuf = (uint8_t *) PL_Base64Decode(base64buf, bufLen, nullptr); - if (!inBuf) - { - printf("PL_Base64Decode failed\n"); - return; - } - - const uint8_t *cursor = inBuf; - - PrintBuf("signature", cursor, 8); - - // verify NTLMSSP signature - if (memcmp(cursor, NTLM_SIGNATURE, sizeof(NTLM_SIGNATURE)) != 0) - { - printf("### invalid or corrupt NTLM signature\n"); - } - cursor += sizeof(NTLM_SIGNATURE); - - PrintBuf("message type", cursor, 4); - - if (memcmp(cursor, NTLM_TYPE1_MARKER, sizeof(NTLM_MARKER_LEN)) == 0) - ReadType1MsgBody(inBuf, 12); - else if (memcmp(cursor, NTLM_TYPE2_MARKER, sizeof(NTLM_MARKER_LEN)) == 0) - ReadType2MsgBody(inBuf, 12); - else if (memcmp(cursor, NTLM_TYPE3_MARKER, sizeof(NTLM_MARKER_LEN)) == 0) - ReadType3MsgBody(inBuf, 12); - else - printf("### invalid or unknown message type\n"); - - PR_Free(inBuf); -} - -int main(int argc, char **argv) -{ - if (argc == 1) - { - printf("usage: ntlmread <msg>\n"); - return -1; - } - ReadMsg(argv[1], (uint32_t) strlen(argv[1])); - return 0; -}
--- a/netwerk/test/TestBind.cpp +++ b/netwerk/test/TestBind.cpp @@ -1,21 +1,23 @@ /* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #include "TestCommon.h" -#include "TestHarness.h" +#include "gtest/gtest.h" #include "nsISocketTransportService.h" #include "nsISocketTransport.h" #include "nsIServerSocket.h" #include "nsIAsyncInputStream.h" #include "nsINetAddr.h" #include "mozilla/net/DNS.h" #include "prerror.h" +#include "nsComponentManagerUtils.h" +#include "nsServiceManagerUtils.h" using namespace mozilla::net; using namespace mozilla; class ServerListener: public nsIServerSocketListener { public: NS_DECL_ISUPPORTS @@ -46,22 +48,20 @@ NS_IMETHODIMP ServerListener::OnSocketAccepted(nsIServerSocket *aServ, nsISocketTransport *aTransport) { // Run on STS thread. NetAddr peerAddr; nsresult rv = aTransport->GetPeerAddr(&peerAddr); if (NS_FAILED(rv)) { mFailed = true; - fail("Server: not able to get peer address."); QuitPumpingEvents(); return NS_OK; } mClientPort = PR_ntohs(peerAddr.inet.port); - passed("Server: received connection"); QuitPumpingEvents(); return NS_OK; } NS_IMETHODIMP ServerListener::OnStopListening(nsIServerSocket *aServ, nsresult aStatus) { @@ -101,114 +101,76 @@ ClientInputCallback::OnInputStreamReady( nsresult rv = aStream->Available(&avail); if (NS_FAILED(rv)) { mFailed = true; } QuitPumpingEvents(); return NS_OK; } -int -main(int32_t argc, char *argv[]) +TEST(TestBind, MainTest) { - ScopedXPCOM xpcom("SocketTransport"); - if (xpcom.failed()) { - fail("Unable to initalize XPCOM."); - return -1; - } - // // Server side. // nsCOMPtr<nsIServerSocket> server = do_CreateInstance("@mozilla.org/network/server-socket;1"); - if (!server) { - fail("Failed to create server socket."); - return -1; - } + ASSERT_TRUE(server); nsresult rv = server->Init(-1, true, -1); - if (NS_FAILED(rv)) { - fail("Failed to initialize server."); - return -1; - } + ASSERT_TRUE(NS_SUCCEEDED(rv)); int32_t serverPort; rv = server->GetPort(&serverPort); - if (NS_FAILED(rv)) { - fail("Unable to get server port."); - return -1; - } + ASSERT_TRUE(NS_SUCCEEDED(rv)); // Listening. RefPtr<ServerListener> serverListener = new ServerListener(); rv = server->AsyncListen(serverListener); - if (NS_FAILED(rv)) { - fail("Server fail to start listening."); - return -1; - } + ASSERT_TRUE(NS_SUCCEEDED(rv)); // // Client side // uint32_t bindingPort = 20000; nsCOMPtr<nsISocketTransportService> sts = do_GetService("@mozilla.org/network/socket-transport-service;1", &rv); - if (NS_FAILED(rv)) { - fail("Unable to get socket transport service."); - return -1; - } + ASSERT_TRUE(NS_SUCCEEDED(rv)); for (int32_t tried = 0; tried < 100; tried++) { nsCOMPtr<nsISocketTransport> client; rv = sts->CreateTransport(nullptr, 0, NS_LITERAL_CSTRING("127.0.0.1"), serverPort, nullptr, getter_AddRefs(client)); - if (NS_FAILED(rv)) { - fail("Unable to create transport."); - return -1; - } + ASSERT_TRUE(NS_SUCCEEDED(rv)); // Bind to a port. It's possible that we are binding to a port that is // currently in use. If we failed to bind, we try next port. NetAddr bindingAddr; bindingAddr.inet.family = AF_INET; bindingAddr.inet.ip = 0; bindingAddr.inet.port = PR_htons(bindingPort); rv = client->Bind(&bindingAddr); - if (NS_FAILED(rv)) { - fail("Unable to bind a port."); - return -1; - } + ASSERT_TRUE(NS_SUCCEEDED(rv)); // Open IO streams, to make client SocketTransport connect to server. RefPtr<ClientInputCallback> clientCallback = new ClientInputCallback(); nsCOMPtr<nsIInputStream> inputStream; rv = client->OpenInputStream(nsITransport::OPEN_UNBUFFERED, 0, 0, getter_AddRefs(inputStream)); - if (NS_FAILED(rv)) { - fail("Failed to open an input stream."); - return -1; - } + ASSERT_TRUE(NS_SUCCEEDED(rv)); + nsCOMPtr<nsIAsyncInputStream> asyncInputStream = do_QueryInterface(inputStream); rv = asyncInputStream->AsyncWait(clientCallback, 0, 0, nullptr); // Wait for server's response or callback of input stream. PumpEvents(); if (clientCallback->mFailed) { // if client received error, we likely have bound a port that is in use. // we can try another port. bindingPort++; } else { // We are unlocked by server side, leave the loop and check result. break; } } - if (serverListener->mFailed) { - fail("Server failure."); - return -1; - } - if (serverListener->mClientPort != bindingPort) { - fail("Port that server got doesn't match what we are expecting."); - return -1; - } - passed("Port matched"); - return 0; + ASSERT_FALSE(serverListener->mFailed); + ASSERT_EQ(serverListener->mClientPort, bindingPort); }
deleted file mode 100644 --- a/netwerk/test/TestBlockingSocket.cpp +++ /dev/null @@ -1,127 +0,0 @@ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -#include "TestCommon.h" -#include "nsIComponentRegistrar.h" -#include "nsISocketTransportService.h" -#include "nsISocketTransport.h" -#include "nsIServiceManager.h" -#include "nsIComponentManager.h" -#include "nsCOMPtr.h" -#include "nsStringAPI.h" -#include "nsIFile.h" -#include "nsNetUtil.h" -#include "nsIInputStream.h" -#include "nsServiceManagerUtils.h" -#include "nsIOutputStream.h" -#include "NetwerkTestLogging.h" -#include "prenv.h" -#include "prthread.h" -#include <stdlib.h> - -//////////////////////////////////////////////////////////////////////////////// - -// -// set NSPR_LOG_MODULES=Test:5 -// -static PRLogModuleInfo *gTestLog = nullptr; -#define LOG(args) MOZ_LOG(gTestLog, mozilla::LogLevel::Debug, args) - -//////////////////////////////////////////////////////////////////////////////// - -static NS_DEFINE_CID(kSocketTransportServiceCID, NS_SOCKETTRANSPORTSERVICE_CID); - -//////////////////////////////////////////////////////////////////////////////// - -static nsresult -RunBlockingTest(const nsACString &host, int32_t port, nsIFile *file) -{ - nsresult rv; - - LOG(("RunBlockingTest\n")); - - nsCOMPtr<nsISocketTransportService> sts = - do_GetService(kSocketTransportServiceCID, &rv); - if (NS_FAILED(rv)) return rv; - - nsCOMPtr<nsIInputStream> input; - rv = NS_NewLocalFileInputStream(getter_AddRefs(input), file); - if (NS_FAILED(rv)) return rv; - - nsCOMPtr<nsISocketTransport> trans; - rv = sts->CreateTransport(nullptr, 0, host, port, nullptr, getter_AddRefs(trans)); - if (NS_FAILED(rv)) return rv; - - nsCOMPtr<nsIOutputStream> output; - rv = trans->OpenOutputStream(nsITransport::OPEN_BLOCKING, 100, 10, getter_AddRefs(output)); - if (NS_FAILED(rv)) return rv; - - char buf[120]; - uint32_t nr, nw; - for (;;) { - rv = input->Read(buf, sizeof(buf), &nr); - if (NS_FAILED(rv) || (nr == 0)) return rv; - -/* - const char *p = buf; - while (nr) { - rv = output->Write(p, nr, &nw); - if (NS_FAILED(rv)) return rv; - - nr -= nw; - p += nw; - } -*/ - - rv = output->Write(buf, nr, &nw); - if (NS_FAILED(rv)) return rv; - - NS_ASSERTION(nr == nw, "not all written"); - } - - LOG((" done copying data.\n")); - return NS_OK; -} - -//////////////////////////////////////////////////////////////////////////////// - -int -main(int argc, char* argv[]) -{ - if (test_common_init(&argc, &argv) != 0) - return -1; - - nsresult rv; - - if (argc < 4) { - printf("usage: %s <host> <port> <file-to-read>\n", argv[0]); - return -1; - } - char* hostName = argv[1]; - int32_t port = atoi(argv[2]); - char* fileName = argv[3]; - { - nsCOMPtr<nsIServiceManager> servMan; - NS_InitXPCOM2(getter_AddRefs(servMan), nullptr, nullptr); - - gTestLog = PR_NewLogModule("Test"); - - nsCOMPtr<nsIFile> file; - rv = NS_NewNativeLocalFile(nsDependentCString(fileName), false, getter_AddRefs(file)); - if (NS_FAILED(rv)) return -1; - - rv = RunBlockingTest(nsDependentCString(hostName), port, file); - if (NS_FAILED(rv)) - LOG(("RunBlockingTest failed [rv=%x]\n", rv)); - - // give background threads a chance to finish whatever work they may - // be doing. - LOG(("sleeping for 5 seconds...\n")); - PR_Sleep(PR_SecondsToInterval(5)); - } // this scopes the nsCOMPtrs - // no nsCOMPtrs are allowed to be alive when you call NS_ShutdownXPCOM - rv = NS_ShutdownXPCOM(nullptr); - NS_ASSERTION(NS_SUCCEEDED(rv), "NS_ShutdownXPCOM failed"); - return 0; -}
--- a/netwerk/test/TestCookie.cpp +++ b/netwerk/test/TestCookie.cpp @@ -1,43 +1,41 @@ /* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ /* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #include "TestCommon.h" -#include "TestHarness.h" +#include "gtest/gtest.h" #include "nsIServiceManager.h" #include "nsICookieService.h" #include "nsICookieManager.h" #include "nsICookieManager2.h" #include "nsICookie2.h" #include <stdio.h> #include "plstr.h" #include "prprf.h" #include "nsNetUtil.h" #include "nsISimpleEnumerator.h" #include "nsServiceManagerUtils.h" #include "nsNetCID.h" -#include "nsStringAPI.h" #include "nsIPrefBranch.h" #include "nsIPrefService.h" +#include "nsIURI.h" static NS_DEFINE_CID(kCookieServiceCID, NS_COOKIESERVICE_CID); static NS_DEFINE_CID(kPrefServiceCID, NS_PREFSERVICE_CID); // various pref strings static const char kCookiesPermissions[] = "network.cookie.cookieBehavior"; static const char kCookiesLifetimeEnabled[] = "network.cookie.lifetime.enabled"; static const char kCookiesLifetimeDays[] = "network.cookie.lifetime.days"; static const char kCookiesLifetimeCurrentSession[] = "network.cookie.lifetime.behavior"; static const char kCookiesMaxPerHost[] = "network.cookie.maxPerHost"; -static char *sBuffer; - #define OFFSET_ONE_WEEK int64_t(604800) * PR_USEC_PER_SEC #define OFFSET_ONE_DAY int64_t(86400) * PR_USEC_PER_SEC //Set server time or expiry time void SetTime(PRTime offsetTime,nsAutoCString& serverString,nsAutoCString& cookieString,bool expiry) { char timeStringPreset[40]; @@ -58,97 +56,61 @@ SetTime(PRTime offsetTime,nsAutoCString& // Set cookie string PR_ExplodeTime(SetExpiryTime , PR_GMTParameters, &explodedTime); PR_FormatTimeUSEnglish(timeStringPreset, 40, "%c GMT", &explodedTime); cookieString.Replace(0, strlen("test=expiry; expires=") + strlen(timeStringPreset) + 1, "test=expiry; expires="); cookieString.Append(timeStringPreset); } -nsresult +void SetACookie(nsICookieService *aCookieService, const char *aSpec1, const char *aSpec2, const char* aCookieString, const char *aServerTime) { nsCOMPtr<nsIURI> uri1, uri2; NS_NewURI(getter_AddRefs(uri1), aSpec1); if (aSpec2) NS_NewURI(getter_AddRefs(uri2), aSpec2); - sBuffer = PR_sprintf_append(sBuffer, " for host \"%s\": SET ", aSpec1); nsresult rv = aCookieService->SetCookieStringFromHttp(uri1, uri2, nullptr, (char *)aCookieString, aServerTime, nullptr); - // the following code is useless. the cookieservice blindly returns NS_OK - // from SetCookieString. we have to call GetCookie to see if the cookie was - // set correctly... - if (NS_FAILED(rv)) { - sBuffer = PR_sprintf_append(sBuffer, "nothing\n"); - } else { - sBuffer = PR_sprintf_append(sBuffer, "\"%s\"\n", aCookieString); - } - return rv; + EXPECT_TRUE(NS_SUCCEEDED(rv)); } -nsresult +void SetACookieNoHttp(nsICookieService *aCookieService, const char *aSpec, const char* aCookieString) { nsCOMPtr<nsIURI> uri; NS_NewURI(getter_AddRefs(uri), aSpec); - sBuffer = PR_sprintf_append(sBuffer, " for host \"%s\": SET ", aSpec); nsresult rv = aCookieService->SetCookieString(uri, nullptr, (char *)aCookieString, nullptr); - // the following code is useless. the cookieservice blindly returns NS_OK - // from SetCookieString. we have to call GetCookie to see if the cookie was - // set correctly... - if (NS_FAILED(rv)) { - sBuffer = PR_sprintf_append(sBuffer, "nothing\n"); - } else { - sBuffer = PR_sprintf_append(sBuffer, "\"%s\"\n", aCookieString); - } - return rv; + EXPECT_TRUE(NS_SUCCEEDED(rv)); } // returns true if cookie(s) for the given host were found; else false. // the cookie string is returned via aCookie. bool GetACookie(nsICookieService *aCookieService, const char *aSpec1, const char *aSpec2, char **aCookie) { nsCOMPtr<nsIURI> uri1, uri2; NS_NewURI(getter_AddRefs(uri1), aSpec1); if (aSpec2) NS_NewURI(getter_AddRefs(uri2), aSpec2); - sBuffer = PR_sprintf_append(sBuffer, " \"%s\": GOT ", aSpec1); nsresult rv = aCookieService->GetCookieStringFromHttp(uri1, uri2, nullptr, aCookie); - if (NS_FAILED(rv)) { - sBuffer = PR_sprintf_append(sBuffer, "XXX GetCookieString() failed!\n"); - } - if (!*aCookie) { - sBuffer = PR_sprintf_append(sBuffer, "nothing\n"); - } else { - sBuffer = PR_sprintf_append(sBuffer, "\"%s\"\n", *aCookie); - } return *aCookie != nullptr; } // returns true if cookie(s) for the given host were found; else false. // the cookie string is returned via aCookie. bool GetACookieNoHttp(nsICookieService *aCookieService, const char *aSpec, char **aCookie) { nsCOMPtr<nsIURI> uri; NS_NewURI(getter_AddRefs(uri), aSpec); - sBuffer = PR_sprintf_append(sBuffer, " \"%s\": GOT ", aSpec); nsresult rv = aCookieService->GetCookieString(uri, nullptr, aCookie); - if (NS_FAILED(rv)) { - sBuffer = PR_sprintf_append(sBuffer, "XXX GetCookieString() failed!\n"); - } - if (!*aCookie) { - sBuffer = PR_sprintf_append(sBuffer, "nothing\n"); - } else { - sBuffer = PR_sprintf_append(sBuffer, "\"%s\"\n", *aCookie); - } return *aCookie != nullptr; } // some #defines for comparison rules #define MUST_BE_NULL 0 #define MUST_EQUAL 1 #define MUST_CONTAIN 2 #define MUST_NOT_CONTAIN 3 @@ -176,677 +138,572 @@ CheckResult(const char *aLhs, uint32_t a case MUST_NOT_CONTAIN: return PL_strstr(aLhs, aRhs) == nullptr; default: return false; // failure } } -// helper function that ensures the first aSize elements of aResult are -// true (i.e. all tests succeeded). prints the result of the tests (if any -// tests failed, it prints the zero-based index of each failed test). -bool -PrintResult(const bool aResult[], uint32_t aSize) -{ - bool failed = false; - sBuffer = PR_sprintf_append(sBuffer, "*** tests "); - for (uint32_t i = 0; i < aSize; ++i) { - if (!aResult[i]) { - failed = true; - sBuffer = PR_sprintf_append(sBuffer, "%d ", i); - } - } - if (failed) { - sBuffer = PR_sprintf_append(sBuffer, "FAILED!\a\n"); - } else { - sBuffer = PR_sprintf_append(sBuffer, "passed.\n"); - } - return !failed; -} - void InitPrefs(nsIPrefBranch *aPrefBranch) { // init some relevant prefs, so the tests don't go awry. // we use the most restrictive set of prefs we can; // however, we don't test third party blocking here. aPrefBranch->SetIntPref(kCookiesPermissions, 0); // accept all aPrefBranch->SetBoolPref(kCookiesLifetimeEnabled, true); aPrefBranch->SetIntPref(kCookiesLifetimeCurrentSession, 0); aPrefBranch->SetIntPref(kCookiesLifetimeDays, 1); // Set the base domain limit to 50 so we have a known value. aPrefBranch->SetIntPref(kCookiesMaxPerHost, 50); } -int -main(int32_t argc, char *argv[]) +TEST(TestCookie,TestCookieMain) { - if (test_common_init(&argc, &argv) != 0) - return -1; + nsresult rv0; + + nsCOMPtr<nsICookieService> cookieService = + do_GetService(kCookieServiceCID, &rv0); + ASSERT_TRUE(NS_SUCCEEDED(rv0)); - bool allTestsPassed = true; + nsCOMPtr<nsIPrefBranch> prefBranch = + do_GetService(kPrefServiceCID, &rv0); + ASSERT_TRUE(NS_SUCCEEDED(rv0)); - ScopedXPCOM xpcom("TestCookie"); + InitPrefs(prefBranch); - { - nsresult rv0; + nsCString cookie; - nsCOMPtr<nsICookieService> cookieService = - do_GetService(kCookieServiceCID, &rv0); - if (NS_FAILED(rv0)) return -1; - - nsCOMPtr<nsIPrefBranch> prefBranch = - do_GetService(kPrefServiceCID, &rv0); - if (NS_FAILED(rv0)) return -1; - - InitPrefs(prefBranch); - - bool rv[20]; - nsCString cookie; + /* The basic idea behind these tests is the following: + * + * we set() some cookie, then try to get() it in various ways. we have + * several possible tests we perform on the cookie string returned from + * get(): + * + * a) check whether the returned string is null (i.e. we got no cookies + * back). this is used e.g. to ensure a given cookie was deleted + * correctly, or to ensure a certain cookie wasn't returned to a given + * host. + * b) check whether the returned string exactly matches a given string. + * this is used where we want to make sure our cookie service adheres to + * some strict spec (e.g. ordering of multiple cookies), or where we + * just know exactly what the returned string should be. + * c) check whether the returned string contains/does not contain a given + * string. this is used where we don't know/don't care about the + * ordering of multiple cookies - we just want to make sure the cookie + * string contains them all, in some order. + * + * NOTE: this testsuite is not yet comprehensive or complete, and is + * somewhat contrived - still under development, and needs improving! + */ - /* The basic idea behind these tests is the following: - * - * we set() some cookie, then try to get() it in various ways. we have - * several possible tests we perform on the cookie string returned from - * get(): - * - * a) check whether the returned string is null (i.e. we got no cookies - * back). this is used e.g. to ensure a given cookie was deleted - * correctly, or to ensure a certain cookie wasn't returned to a given - * host. - * b) check whether the returned string exactly matches a given string. - * this is used where we want to make sure our cookie service adheres to - * some strict spec (e.g. ordering of multiple cookies), or where we - * just know exactly what the returned string should be. - * c) check whether the returned string contains/does not contain a given - * string. this is used where we don't know/don't care about the - * ordering of multiple cookies - we just want to make sure the cookie - * string contains them all, in some order. - * - * the results of each individual testing operation from CheckResult() is - * stored in an array of bools, which is then checked against the expected - * outcomes (all successes), by PrintResult(). the overall result of all - * tests to date is kept in |allTestsPassed|, for convenient display at the - * end. - * - * Interpreting the output: - * each setting/getting operation will print output saying exactly what - * it's doing and the outcome, respectively. this information is only - * useful for debugging purposes; the actual result of the tests is - * printed at the end of each block of tests. this will either be "all - * tests passed" or "tests X Y Z failed", where X, Y, Z are the indexes - * of rv (i.e. zero-based). at the conclusion of all tests, the overall - * passed/failed result is printed. - * - * NOTE: this testsuite is not yet comprehensive or complete, and is - * somewhat contrived - still under development, and needs improving! - */ + // test some basic variations of the domain & path + SetACookie(cookieService, "http://www.basic.com", nullptr, "test=basic", nullptr); + GetACookie(cookieService, "http://www.basic.com", nullptr, getter_Copies(cookie)); + EXPECT_TRUE(CheckResult(cookie.get(), MUST_EQUAL, "test=basic")); + GetACookie(cookieService, "http://www.basic.com/testPath/testfile.txt", nullptr, getter_Copies(cookie)); + EXPECT_TRUE(CheckResult(cookie.get(), MUST_EQUAL, "test=basic")); + GetACookie(cookieService, "http://www.basic.com./", nullptr, getter_Copies(cookie)); + EXPECT_TRUE(CheckResult(cookie.get(), MUST_BE_NULL)); + GetACookie(cookieService, "http://www.basic.com.", nullptr, getter_Copies(cookie)); + EXPECT_TRUE(CheckResult(cookie.get(), MUST_BE_NULL)); + GetACookie(cookieService, "http://www.basic.com./testPath/testfile.txt", nullptr, getter_Copies(cookie)); + EXPECT_TRUE(CheckResult(cookie.get(), MUST_BE_NULL)); + GetACookie(cookieService, "http://www.basic2.com/", nullptr, getter_Copies(cookie)); + EXPECT_TRUE(CheckResult(cookie.get(), MUST_BE_NULL)); + SetACookie(cookieService, "http://www.basic.com", nullptr, "test=basic; max-age=-1", nullptr); + GetACookie(cookieService, "http://www.basic.com/", nullptr, getter_Copies(cookie)); + EXPECT_TRUE(CheckResult(cookie.get(), MUST_BE_NULL)); + + // *** domain tests - // *** basic tests - sBuffer = PR_sprintf_append(sBuffer, "*** Beginning basic tests...\n"); - - // test some basic variations of the domain & path - SetACookie(cookieService, "http://www.basic.com", nullptr, "test=basic", nullptr); - GetACookie(cookieService, "http://www.basic.com", nullptr, getter_Copies(cookie)); - rv[0] = CheckResult(cookie.get(), MUST_EQUAL, "test=basic"); - GetACookie(cookieService, "http://www.basic.com/testPath/testfile.txt", nullptr, getter_Copies(cookie)); - rv[1] = CheckResult(cookie.get(), MUST_EQUAL, "test=basic"); - GetACookie(cookieService, "http://www.basic.com./", nullptr, getter_Copies(cookie)); - rv[2] = CheckResult(cookie.get(), MUST_BE_NULL); - GetACookie(cookieService, "http://www.basic.com.", nullptr, getter_Copies(cookie)); - rv[3] = CheckResult(cookie.get(), MUST_BE_NULL); - GetACookie(cookieService, "http://www.basic.com./testPath/testfile.txt", nullptr, getter_Copies(cookie)); - rv[4] = CheckResult(cookie.get(), MUST_BE_NULL); - GetACookie(cookieService, "http://www.basic2.com/", nullptr, getter_Copies(cookie)); - rv[5] = CheckResult(cookie.get(), MUST_BE_NULL); - SetACookie(cookieService, "http://www.basic.com", nullptr, "test=basic; max-age=-1", nullptr); - GetACookie(cookieService, "http://www.basic.com/", nullptr, getter_Copies(cookie)); - rv[6] = CheckResult(cookie.get(), MUST_BE_NULL); + // test some variations of the domain & path, for different domains of + // a domain cookie + SetACookie(cookieService, "http://www.domain.com", nullptr, "test=domain; domain=domain.com", nullptr); + GetACookie(cookieService, "http://domain.com", nullptr, getter_Copies(cookie)); + EXPECT_TRUE(CheckResult(cookie.get(), MUST_EQUAL, "test=domain")); + GetACookie(cookieService, "http://domain.com.", nullptr, getter_Copies(cookie)); + EXPECT_TRUE(CheckResult(cookie.get(), MUST_BE_NULL)); + GetACookie(cookieService, "http://www.domain.com", nullptr, getter_Copies(cookie)); + EXPECT_TRUE(CheckResult(cookie.get(), MUST_EQUAL, "test=domain")); + GetACookie(cookieService, "http://foo.domain.com", nullptr, getter_Copies(cookie)); + EXPECT_TRUE(CheckResult(cookie.get(), MUST_EQUAL, "test=domain")); + SetACookie(cookieService, "http://www.domain.com", nullptr, "test=domain; domain=domain.com; max-age=-1", nullptr); + GetACookie(cookieService, "http://domain.com", nullptr, getter_Copies(cookie)); + EXPECT_TRUE(CheckResult(cookie.get(), MUST_BE_NULL)); - allTestsPassed = PrintResult(rv, 7) && allTestsPassed; - - - // *** domain tests - sBuffer = PR_sprintf_append(sBuffer, "*** Beginning domain tests...\n"); + SetACookie(cookieService, "http://www.domain.com", nullptr, "test=domain; domain=.domain.com", nullptr); + GetACookie(cookieService, "http://domain.com", nullptr, getter_Copies(cookie)); + EXPECT_TRUE(CheckResult(cookie.get(), MUST_EQUAL, "test=domain")); + GetACookie(cookieService, "http://www.domain.com", nullptr, getter_Copies(cookie)); + EXPECT_TRUE(CheckResult(cookie.get(), MUST_EQUAL, "test=domain")); + GetACookie(cookieService, "http://bah.domain.com", nullptr, getter_Copies(cookie)); + EXPECT_TRUE(CheckResult(cookie.get(), MUST_EQUAL, "test=domain")); + SetACookie(cookieService, "http://www.domain.com", nullptr, "test=domain; domain=.domain.com; max-age=-1", nullptr); + GetACookie(cookieService, "http://domain.com", nullptr, getter_Copies(cookie)); + EXPECT_TRUE(CheckResult(cookie.get(), MUST_BE_NULL)); - // test some variations of the domain & path, for different domains of - // a domain cookie - SetACookie(cookieService, "http://www.domain.com", nullptr, "test=domain; domain=domain.com", nullptr); - GetACookie(cookieService, "http://domain.com", nullptr, getter_Copies(cookie)); - rv[0] = CheckResult(cookie.get(), MUST_EQUAL, "test=domain"); - GetACookie(cookieService, "http://domain.com.", nullptr, getter_Copies(cookie)); - rv[1] = CheckResult(cookie.get(), MUST_BE_NULL); - GetACookie(cookieService, "http://www.domain.com", nullptr, getter_Copies(cookie)); - rv[2] = CheckResult(cookie.get(), MUST_EQUAL, "test=domain"); - GetACookie(cookieService, "http://foo.domain.com", nullptr, getter_Copies(cookie)); - rv[3] = CheckResult(cookie.get(), MUST_EQUAL, "test=domain"); - SetACookie(cookieService, "http://www.domain.com", nullptr, "test=domain; domain=domain.com; max-age=-1", nullptr); - GetACookie(cookieService, "http://domain.com", nullptr, getter_Copies(cookie)); - rv[4] = CheckResult(cookie.get(), MUST_BE_NULL); + SetACookie(cookieService, "http://www.domain.com", nullptr, "test=domain; domain=.foo.domain.com", nullptr); + GetACookie(cookieService, "http://foo.domain.com", nullptr, getter_Copies(cookie)); + EXPECT_TRUE(CheckResult(cookie.get(), MUST_BE_NULL)); - SetACookie(cookieService, "http://www.domain.com", nullptr, "test=domain; domain=.domain.com", nullptr); - GetACookie(cookieService, "http://domain.com", nullptr, getter_Copies(cookie)); - rv[5] = CheckResult(cookie.get(), MUST_EQUAL, "test=domain"); - GetACookie(cookieService, "http://www.domain.com", nullptr, getter_Copies(cookie)); - rv[6] = CheckResult(cookie.get(), MUST_EQUAL, "test=domain"); - GetACookie(cookieService, "http://bah.domain.com", nullptr, getter_Copies(cookie)); - rv[7] = CheckResult(cookie.get(), MUST_EQUAL, "test=domain"); - SetACookie(cookieService, "http://www.domain.com", nullptr, "test=domain; domain=.domain.com; max-age=-1", nullptr); - GetACookie(cookieService, "http://domain.com", nullptr, getter_Copies(cookie)); - rv[8] = CheckResult(cookie.get(), MUST_BE_NULL); + SetACookie(cookieService, "http://www.domain.com", nullptr, "test=domain; domain=moose.com", nullptr); + GetACookie(cookieService, "http://foo.domain.com", nullptr, getter_Copies(cookie)); + EXPECT_TRUE(CheckResult(cookie.get(), MUST_BE_NULL)); + + SetACookie(cookieService, "http://www.domain.com", nullptr, "test=domain; domain=domain.com.", nullptr); + GetACookie(cookieService, "http://foo.domain.com", nullptr, getter_Copies(cookie)); + EXPECT_TRUE(CheckResult(cookie.get(), MUST_BE_NULL)); - SetACookie(cookieService, "http://www.domain.com", nullptr, "test=domain; domain=.foo.domain.com", nullptr); - GetACookie(cookieService, "http://foo.domain.com", nullptr, getter_Copies(cookie)); - rv[9] = CheckResult(cookie.get(), MUST_BE_NULL); + SetACookie(cookieService, "http://www.domain.com", nullptr, "test=domain; domain=..domain.com", nullptr); + GetACookie(cookieService, "http://foo.domain.com", nullptr, getter_Copies(cookie)); + EXPECT_TRUE(CheckResult(cookie.get(), MUST_BE_NULL)); - SetACookie(cookieService, "http://www.domain.com", nullptr, "test=domain; domain=moose.com", nullptr); - GetACookie(cookieService, "http://foo.domain.com", nullptr, getter_Copies(cookie)); - rv[10] = CheckResult(cookie.get(), MUST_BE_NULL); + SetACookie(cookieService, "http://www.domain.com", nullptr, "test=domain; domain=..domain.com.", nullptr); + GetACookie(cookieService, "http://foo.domain.com", nullptr, getter_Copies(cookie)); + EXPECT_TRUE(CheckResult(cookie.get(), MUST_BE_NULL)); - SetACookie(cookieService, "http://www.domain.com", nullptr, "test=domain; domain=domain.com.", nullptr); - GetACookie(cookieService, "http://foo.domain.com", nullptr, getter_Copies(cookie)); - rv[11] = CheckResult(cookie.get(), MUST_BE_NULL); + SetACookie(cookieService, "http://path.net/path/file", nullptr, "test=taco; path=\"/bogus\"", nullptr); + GetACookie(cookieService, "http://path.net/path/file", nullptr, getter_Copies(cookie)); + EXPECT_TRUE(CheckResult(cookie.get(), MUST_EQUAL, "test=taco")); + SetACookie(cookieService, "http://path.net/path/file", nullptr, "test=taco; max-age=-1", nullptr); + GetACookie(cookieService, "http://path.net/path/file", nullptr, getter_Copies(cookie)); + EXPECT_TRUE(CheckResult(cookie.get(), MUST_BE_NULL)); - SetACookie(cookieService, "http://www.domain.com", nullptr, "test=domain; domain=..domain.com", nullptr); - GetACookie(cookieService, "http://foo.domain.com", nullptr, getter_Copies(cookie)); - rv[12] = CheckResult(cookie.get(), MUST_BE_NULL); - - SetACookie(cookieService, "http://www.domain.com", nullptr, "test=domain; domain=..domain.com.", nullptr); - GetACookie(cookieService, "http://foo.domain.com", nullptr, getter_Copies(cookie)); - rv[13] = CheckResult(cookie.get(), MUST_BE_NULL); + // *** path tests - SetACookie(cookieService, "http://path.net/path/file", nullptr, "test=taco; path=\"/bogus\"", nullptr); - GetACookie(cookieService, "http://path.net/path/file", nullptr, getter_Copies(cookie)); - rv[14] = CheckResult(cookie.get(), MUST_EQUAL, "test=taco"); - SetACookie(cookieService, "http://path.net/path/file", nullptr, "test=taco; max-age=-1", nullptr); - GetACookie(cookieService, "http://path.net/path/file", nullptr, getter_Copies(cookie)); - rv[15] = CheckResult(cookie.get(), MUST_BE_NULL); - - allTestsPassed = PrintResult(rv, 16) && allTestsPassed; - - - // *** path tests - sBuffer = PR_sprintf_append(sBuffer, "*** Beginning path tests...\n"); + // test some variations of the domain & path, for different paths of + // a path cookie + SetACookie(cookieService, "http://path.net/path/file", nullptr, "test=path; path=/path", nullptr); + GetACookie(cookieService, "http://path.net/path", nullptr, getter_Copies(cookie)); + EXPECT_TRUE(CheckResult(cookie.get(), MUST_EQUAL, "test=path")); + GetACookie(cookieService, "http://path.net/path/", nullptr, getter_Copies(cookie)); + EXPECT_TRUE(CheckResult(cookie.get(), MUST_EQUAL, "test=path")); + GetACookie(cookieService, "http://path.net/path/hithere.foo", nullptr, getter_Copies(cookie)); + EXPECT_TRUE(CheckResult(cookie.get(), MUST_EQUAL, "test=path")); + GetACookie(cookieService, "http://path.net/path?hithere/foo", nullptr, getter_Copies(cookie)); + EXPECT_TRUE(CheckResult(cookie.get(), MUST_EQUAL, "test=path")); + GetACookie(cookieService, "http://path.net/path2", nullptr, getter_Copies(cookie)); + EXPECT_TRUE(CheckResult(cookie.get(), MUST_BE_NULL)); + GetACookie(cookieService, "http://path.net/path2/", nullptr, getter_Copies(cookie)); + EXPECT_TRUE(CheckResult(cookie.get(), MUST_BE_NULL)); + SetACookie(cookieService, "http://path.net/path/file", nullptr, "test=path; path=/path; max-age=-1", nullptr); + GetACookie(cookieService, "http://path.net/path/", nullptr, getter_Copies(cookie)); + EXPECT_TRUE(CheckResult(cookie.get(), MUST_BE_NULL)); - // test some variations of the domain & path, for different paths of - // a path cookie - SetACookie(cookieService, "http://path.net/path/file", nullptr, "test=path; path=/path", nullptr); - GetACookie(cookieService, "http://path.net/path", nullptr, getter_Copies(cookie)); - rv[0] = CheckResult(cookie.get(), MUST_EQUAL, "test=path"); - GetACookie(cookieService, "http://path.net/path/", nullptr, getter_Copies(cookie)); - rv[1] = CheckResult(cookie.get(), MUST_EQUAL, "test=path"); - GetACookie(cookieService, "http://path.net/path/hithere.foo", nullptr, getter_Copies(cookie)); - rv[2] = CheckResult(cookie.get(), MUST_EQUAL, "test=path"); - GetACookie(cookieService, "http://path.net/path?hithere/foo", nullptr, getter_Copies(cookie)); - rv[3] = CheckResult(cookie.get(), MUST_EQUAL, "test=path"); - GetACookie(cookieService, "http://path.net/path2", nullptr, getter_Copies(cookie)); - rv[4] = CheckResult(cookie.get(), MUST_BE_NULL); - GetACookie(cookieService, "http://path.net/path2/", nullptr, getter_Copies(cookie)); - rv[5] = CheckResult(cookie.get(), MUST_BE_NULL); - SetACookie(cookieService, "http://path.net/path/file", nullptr, "test=path; path=/path; max-age=-1", nullptr); - GetACookie(cookieService, "http://path.net/path/", nullptr, getter_Copies(cookie)); - rv[6] = CheckResult(cookie.get(), MUST_BE_NULL); + SetACookie(cookieService, "http://path.net/path/file", nullptr, "test=path; path=/path/", nullptr); + GetACookie(cookieService, "http://path.net/path", nullptr, getter_Copies(cookie)); + EXPECT_TRUE(CheckResult(cookie.get(), MUST_EQUAL, "test=path")); + GetACookie(cookieService, "http://path.net/path/", nullptr, getter_Copies(cookie)); + EXPECT_TRUE(CheckResult(cookie.get(), MUST_EQUAL, "test=path")); + SetACookie(cookieService, "http://path.net/path/file", nullptr, "test=path; path=/path/; max-age=-1", nullptr); + GetACookie(cookieService, "http://path.net/path/", nullptr, getter_Copies(cookie)); + EXPECT_TRUE(CheckResult(cookie.get(), MUST_BE_NULL)); - SetACookie(cookieService, "http://path.net/path/file", nullptr, "test=path; path=/path/", nullptr); - GetACookie(cookieService, "http://path.net/path", nullptr, getter_Copies(cookie)); - rv[7] = CheckResult(cookie.get(), MUST_EQUAL, "test=path"); - GetACookie(cookieService, "http://path.net/path/", nullptr, getter_Copies(cookie)); - rv[8] = CheckResult(cookie.get(), MUST_EQUAL, "test=path"); - SetACookie(cookieService, "http://path.net/path/file", nullptr, "test=path; path=/path/; max-age=-1", nullptr); - GetACookie(cookieService, "http://path.net/path/", nullptr, getter_Copies(cookie)); - rv[9] = CheckResult(cookie.get(), MUST_BE_NULL); + // note that a site can set a cookie for a path it's not on. + // this is an intentional deviation from spec (see comments in + // nsCookieService::CheckPath()), so we test this functionality too + SetACookie(cookieService, "http://path.net/path/file", nullptr, "test=path; path=/foo/", nullptr); + GetACookie(cookieService, "http://path.net/path", nullptr, getter_Copies(cookie)); + EXPECT_TRUE(CheckResult(cookie.get(), MUST_BE_NULL)); + GetACookie(cookieService, "http://path.net/foo", nullptr, getter_Copies(cookie)); + EXPECT_TRUE(CheckResult(cookie.get(), MUST_EQUAL, "test=path")); + SetACookie(cookieService, "http://path.net/path/file", nullptr, "test=path; path=/foo/; max-age=-1", nullptr); + GetACookie(cookieService, "http://path.net/foo/", nullptr, getter_Copies(cookie)); + EXPECT_TRUE(CheckResult(cookie.get(), MUST_BE_NULL)); - // note that a site can set a cookie for a path it's not on. - // this is an intentional deviation from spec (see comments in - // nsCookieService::CheckPath()), so we test this functionality too - SetACookie(cookieService, "http://path.net/path/file", nullptr, "test=path; path=/foo/", nullptr); - GetACookie(cookieService, "http://path.net/path", nullptr, getter_Copies(cookie)); - rv[10] = CheckResult(cookie.get(), MUST_BE_NULL); - GetACookie(cookieService, "http://path.net/foo", nullptr, getter_Copies(cookie)); - rv[11] = CheckResult(cookie.get(), MUST_EQUAL, "test=path"); - SetACookie(cookieService, "http://path.net/path/file", nullptr, "test=path; path=/foo/; max-age=-1", nullptr); - GetACookie(cookieService, "http://path.net/foo/", nullptr, getter_Copies(cookie)); - rv[12] = CheckResult(cookie.get(), MUST_BE_NULL); - - // bug 373228: make sure cookies with paths longer than 1024 bytes, - // and cookies with paths or names containing tabs, are rejected. - // the following cookie has a path > 1024 bytes explicitly specified in the cookie - SetACookie(cookieService, "http://path.net/", nullptr, "test=path; path=/1234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890/", nullptr); - GetACookie(cookieService, "http://path.net/1234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890", nullptr, getter_Copies(cookie)); - rv[13] = CheckResult(cookie.get(), MUST_BE_NULL); - // the following cookie has a path > 1024 bytes implicitly specified by the uri path - SetACookie(cookieService, "http://path.net/1234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890/", nullptr, "test=path", nullptr); - GetACookie(cookieService, "http://path.net/1234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890/", nullptr, getter_Copies(cookie)); - rv[14] = CheckResult(cookie.get(), MUST_BE_NULL); - // the following cookie includes a tab in the path - SetACookie(cookieService, "http://path.net/", nullptr, "test=path; path=/foo\tbar/", nullptr); - GetACookie(cookieService, "http://path.net/foo\tbar/", nullptr, getter_Copies(cookie)); - rv[15] = CheckResult(cookie.get(), MUST_BE_NULL); - // the following cookie includes a tab in the name - SetACookie(cookieService, "http://path.net/", nullptr, "test\ttabs=tab", nullptr); - GetACookie(cookieService, "http://path.net/", nullptr, getter_Copies(cookie)); - rv[16] = CheckResult(cookie.get(), MUST_BE_NULL); - // the following cookie includes a tab in the value - allowed - SetACookie(cookieService, "http://path.net/", nullptr, "test=tab\ttest", nullptr); - GetACookie(cookieService, "http://path.net/", nullptr, getter_Copies(cookie)); - rv[17] = CheckResult(cookie.get(), MUST_EQUAL, "test=tab\ttest"); - SetACookie(cookieService, "http://path.net/", nullptr, "test=tab\ttest; max-age=-1", nullptr); - GetACookie(cookieService, "http://path.net/", nullptr, getter_Copies(cookie)); - rv[18] = CheckResult(cookie.get(), MUST_BE_NULL); - - allTestsPassed = PrintResult(rv, 19) && allTestsPassed; + // bug 373228: make sure cookies with paths longer than 1024 bytes, + // and cookies with paths or names containing tabs, are rejected. + // the following cookie has a path > 1024 bytes explicitly specified in the cookie + SetACookie(cookieService, "http://path.net/", nullptr, "test=path; path=/1234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890/", nullptr); + GetACookie(cookieService, "http://path.net/1234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890", nullptr, getter_Copies(cookie)); + EXPECT_TRUE(CheckResult(cookie.get(), MUST_BE_NULL)); + // the following cookie has a path > 1024 bytes implicitly specified by the uri path + SetACookie(cookieService, "http://path.net/1234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890/", nullptr, "test=path", nullptr); + GetACookie(cookieService, "http://path.net/1234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890/", nullptr, getter_Copies(cookie)); + EXPECT_TRUE(CheckResult(cookie.get(), MUST_BE_NULL)); + // the following cookie includes a tab in the path + SetACookie(cookieService, "http://path.net/", nullptr, "test=path; path=/foo\tbar/", nullptr); + GetACookie(cookieService, "http://path.net/foo\tbar/", nullptr, getter_Copies(cookie)); + EXPECT_TRUE(CheckResult(cookie.get(), MUST_BE_NULL)); + // the following cookie includes a tab in the name + SetACookie(cookieService, "http://path.net/", nullptr, "test\ttabs=tab", nullptr); + GetACookie(cookieService, "http://path.net/", nullptr, getter_Copies(cookie)); + EXPECT_TRUE(CheckResult(cookie.get(), MUST_BE_NULL)); + // the following cookie includes a tab in the value - allowed + SetACookie(cookieService, "http://path.net/", nullptr, "test=tab\ttest", nullptr); + GetACookie(cookieService, "http://path.net/", nullptr, getter_Copies(cookie)); + EXPECT_TRUE(CheckResult(cookie.get(), MUST_EQUAL, "test=tab\ttest")); + SetACookie(cookieService, "http://path.net/", nullptr, "test=tab\ttest; max-age=-1", nullptr); + GetACookie(cookieService, "http://path.net/", nullptr, getter_Copies(cookie)); + EXPECT_TRUE(CheckResult(cookie.get(), MUST_BE_NULL)); - // *** expiry & deletion tests - // XXX add server time str parsing tests here - sBuffer = PR_sprintf_append(sBuffer, "*** Beginning expiry & deletion tests...\n"); + // *** expiry & deletion tests + // XXX add server time str parsing tests here - // test some variations of the expiry time, - // and test deletion of previously set cookies - SetACookie(cookieService, "http://expireme.org/", nullptr, "test=expiry; max-age=-1", nullptr); - GetACookie(cookieService, "http://expireme.org/", nullptr, getter_Copies(cookie)); - rv[0] = CheckResult(cookie.get(), MUST_BE_NULL); - SetACookie(cookieService, "http://expireme.org/", nullptr, "test=expiry; max-age=0", nullptr); - GetACookie(cookieService, "http://expireme.org/", nullptr, getter_Copies(cookie)); - rv[1] = CheckResult(cookie.get(), MUST_BE_NULL); - SetACookie(cookieService, "http://expireme.org/", nullptr, "test=expiry; expires=bad", nullptr); - GetACookie(cookieService, "http://expireme.org/", nullptr, getter_Copies(cookie)); - rv[2] = CheckResult(cookie.get(), MUST_EQUAL, "test=expiry"); - SetACookie(cookieService, "http://expireme.org/", nullptr, "test=expiry; expires=Thu, 10 Apr 1980 16:33:12 GMT", nullptr); - GetACookie(cookieService, "http://expireme.org/", nullptr, getter_Copies(cookie)); - rv[3] = CheckResult(cookie.get(), MUST_BE_NULL); - SetACookie(cookieService, "http://expireme.org/", nullptr, "test=expiry; expires=\"Thu, 10 Apr 1980 16:33:12 GMT", nullptr); - GetACookie(cookieService, "http://expireme.org/", nullptr, getter_Copies(cookie)); - rv[4] = CheckResult(cookie.get(), MUST_BE_NULL); - SetACookie(cookieService, "http://expireme.org/", nullptr, "test=expiry; expires=\"Thu, 10 Apr 1980 16:33:12 GMT\"", nullptr); - GetACookie(cookieService, "http://expireme.org/", nullptr, getter_Copies(cookie)); - rv[5] = CheckResult(cookie.get(), MUST_BE_NULL); + // test some variations of the expiry time, + // and test deletion of previously set cookies + SetACookie(cookieService, "http://expireme.org/", nullptr, "test=expiry; max-age=-1", nullptr); + GetACookie(cookieService, "http://expireme.org/", nullptr, getter_Copies(cookie)); + EXPECT_TRUE(CheckResult(cookie.get(), MUST_BE_NULL)); + SetACookie(cookieService, "http://expireme.org/", nullptr, "test=expiry; max-age=0", nullptr); + GetACookie(cookieService, "http://expireme.org/", nullptr, getter_Copies(cookie)); + EXPECT_TRUE(CheckResult(cookie.get(), MUST_BE_NULL)); + SetACookie(cookieService, "http://expireme.org/", nullptr, "test=expiry; expires=bad", nullptr); + GetACookie(cookieService, "http://expireme.org/", nullptr, getter_Copies(cookie)); + EXPECT_TRUE(CheckResult(cookie.get(), MUST_EQUAL, "test=expiry")); + SetACookie(cookieService, "http://expireme.org/", nullptr, "test=expiry; expires=Thu, 10 Apr 1980 16:33:12 GMT", nullptr); + GetACookie(cookieService, "http://expireme.org/", nullptr, getter_Copies(cookie)); + EXPECT_TRUE(CheckResult(cookie.get(), MUST_BE_NULL)); + SetACookie(cookieService, "http://expireme.org/", nullptr, "test=expiry; expires=\"Thu, 10 Apr 1980 16:33:12 GMT", nullptr); + GetACookie(cookieService, "http://expireme.org/", nullptr, getter_Copies(cookie)); + EXPECT_TRUE(CheckResult(cookie.get(), MUST_BE_NULL)); + SetACookie(cookieService, "http://expireme.org/", nullptr, "test=expiry; expires=\"Thu, 10 Apr 1980 16:33:12 GMT\"", nullptr); + GetACookie(cookieService, "http://expireme.org/", nullptr, getter_Copies(cookie)); + EXPECT_TRUE(CheckResult(cookie.get(), MUST_BE_NULL)); - SetACookie(cookieService, "http://expireme.org/", nullptr, "test=expiry; max-age=60", nullptr); - GetACookie(cookieService, "http://expireme.org/", nullptr, getter_Copies(cookie)); - rv[6] = CheckResult(cookie.get(), MUST_EQUAL, "test=expiry"); - SetACookie(cookieService, "http://expireme.org/", nullptr, "test=expiry; max-age=-20", nullptr); - GetACookie(cookieService, "http://expireme.org/", nullptr, getter_Copies(cookie)); - rv[7] = CheckResult(cookie.get(), MUST_BE_NULL); - SetACookie(cookieService, "http://expireme.org/", nullptr, "test=expiry; max-age=60", nullptr); - GetACookie(cookieService, "http://expireme.org/", nullptr, getter_Copies(cookie)); - rv[8] = CheckResult(cookie.get(), MUST_EQUAL, "test=expiry"); - SetACookie(cookieService, "http://expireme.org/", nullptr, "test=expiry; expires=Thu, 10 Apr 1980 16:33:12 GMT", nullptr); - GetACookie(cookieService, "http://expireme.org/", nullptr, getter_Copies(cookie)); - rv[9] = CheckResult(cookie.get(), MUST_BE_NULL); - SetACookie(cookieService, "http://expireme.org/", nullptr, "test=expiry; max-age=60", nullptr); - SetACookie(cookieService, "http://expireme.org/", nullptr, "newtest=expiry; max-age=60", nullptr); - GetACookie(cookieService, "http://expireme.org/", nullptr, getter_Copies(cookie)); - rv[10] = CheckResult(cookie.get(), MUST_CONTAIN, "test=expiry"); - rv[11] = CheckResult(cookie.get(), MUST_CONTAIN, "newtest=expiry"); - SetACookie(cookieService, "http://expireme.org/", nullptr, "test=differentvalue; max-age=0", nullptr); - GetACookie(cookieService, "http://expireme.org/", nullptr, getter_Copies(cookie)); - rv[12] = CheckResult(cookie.get(), MUST_EQUAL, "newtest=expiry"); - SetACookie(cookieService, "http://expireme.org/", nullptr, "newtest=evendifferentvalue; max-age=0", nullptr); - GetACookie(cookieService, "http://expireme.org/", nullptr, getter_Copies(cookie)); - rv[13] = CheckResult(cookie.get(), MUST_BE_NULL); - - SetACookie(cookieService, "http://foo.expireme.org/", nullptr, "test=expiry; domain=.expireme.org; max-age=60", nullptr); - GetACookie(cookieService, "http://expireme.org/", nullptr, getter_Copies(cookie)); - rv[14] = CheckResult(cookie.get(), MUST_EQUAL, "test=expiry"); - SetACookie(cookieService, "http://bar.expireme.org/", nullptr, "test=differentvalue; domain=.expireme.org; max-age=0", nullptr); - GetACookie(cookieService, "http://expireme.org/", nullptr, getter_Copies(cookie)); - rv[15] = CheckResult(cookie.get(), MUST_BE_NULL); - - nsAutoCString ServerTime; - nsAutoCString CookieString; + SetACookie(cookieService, "http://expireme.org/", nullptr, "test=expiry; max-age=60", nullptr); + GetACookie(cookieService, "http://expireme.org/", nullptr, getter_Copies(cookie)); + EXPECT_TRUE(CheckResult(cookie.get(), MUST_EQUAL, "test=expiry")); + SetACookie(cookieService, "http://expireme.org/", nullptr, "test=expiry; max-age=-20", nullptr); + GetACookie(cookieService, "http://expireme.org/", nullptr, getter_Copies(cookie)); + EXPECT_TRUE(CheckResult(cookie.get(), MUST_BE_NULL)); + SetACookie(cookieService, "http://expireme.org/", nullptr, "test=expiry; max-age=60", nullptr); + GetACookie(cookieService, "http://expireme.org/", nullptr, getter_Copies(cookie)); + EXPECT_TRUE(CheckResult(cookie.get(), MUST_EQUAL, "test=expiry")); + SetACookie(cookieService, "http://expireme.org/", nullptr, "test=expiry; expires=Thu, 10 Apr 1980 16:33:12 GMT", nullptr); + GetACookie(cookieService, "http://expireme.org/", nullptr, getter_Copies(cookie)); + EXPECT_TRUE(CheckResult(cookie.get(), MUST_BE_NULL)); + SetACookie(cookieService, "http://expireme.org/", nullptr, "test=expiry; max-age=60", nullptr); + SetACookie(cookieService, "http://expireme.org/", nullptr, "newtest=expiry; max-age=60", nullptr); + GetACookie(cookieService, "http://expireme.org/", nullptr, getter_Copies(cookie)); + EXPECT_TRUE(CheckResult(cookie.get(), MUST_CONTAIN, "test=expiry")); + EXPECT_TRUE(CheckResult(cookie.get(), MUST_CONTAIN, "newtest=expiry")); + SetACookie(cookieService, "http://expireme.org/", nullptr, "test=differentvalue; max-age=0", nullptr); + GetACookie(cookieService, "http://expireme.org/", nullptr, getter_Copies(cookie)); + EXPECT_TRUE(CheckResult(cookie.get(), MUST_EQUAL, "newtest=expiry")); + SetACookie(cookieService, "http://expireme.org/", nullptr, "newtest=evendifferentvalue; max-age=0", nullptr); + GetACookie(cookieService, "http://expireme.org/", nullptr, getter_Copies(cookie)); + EXPECT_TRUE(CheckResult(cookie.get(), MUST_BE_NULL)); - SetTime(-OFFSET_ONE_WEEK, ServerTime, CookieString, true); - SetACookie(cookieService, "http://expireme.org/", nullptr, CookieString.get(), ServerTime.get()); - GetACookie(cookieService, "http://expireme.org/", nullptr, getter_Copies(cookie)); - rv[16] = CheckResult(cookie.get(), MUST_BE_NULL); - // Set server time earlier than client time for one year + one day, and expirty time earlier than server time for one day. - SetTime(-(OFFSET_ONE_DAY + OFFSET_ONE_WEEK), ServerTime, CookieString, false); - SetACookie(cookieService, "http://expireme.org/", nullptr, CookieString.get(), ServerTime.get()); - GetACookie(cookieService, "http://expireme.org/", nullptr, getter_Copies(cookie)); - rv[17] = CheckResult(cookie.get(), MUST_BE_NULL); - // Set server time later than client time for one year, and expiry time later than server time for one day. - SetTime(OFFSET_ONE_WEEK, ServerTime, CookieString, false); - SetACookie(cookieService, "http://expireme.org/", nullptr, CookieString.get(), ServerTime.get()); - GetACookie(cookieService, "http://expireme.org/", nullptr, getter_Copies(cookie)); - rv[18] = CheckResult(cookie.get(), MUST_EQUAL, "test=expiry"); - // Set server time later than client time for one year + one day, and expiry time earlier than server time for one day. - SetTime((OFFSET_ONE_DAY + OFFSET_ONE_WEEK), ServerTime, CookieString, true); - SetACookie(cookieService, "http://expireme.org/", nullptr, CookieString.get(), ServerTime.get()); - GetACookie(cookieService, "http://expireme.org/", nullptr, getter_Copies(cookie)); - rv[19] = CheckResult(cookie.get(), MUST_EQUAL, "test=expiry"); - allTestsPassed = PrintResult(rv, 20) && allTestsPassed; + SetACookie(cookieService, "http://foo.expireme.org/", nullptr, "test=expiry; domain=.expireme.org; max-age=60", nullptr); + GetACookie(cookieService, "http://expireme.org/", nullptr, getter_Copies(cookie)); + EXPECT_TRUE(CheckResult(cookie.get(), MUST_EQUAL, "test=expiry")); + SetACookie(cookieService, "http://bar.expireme.org/", nullptr, "test=differentvalue; domain=.expireme.org; max-age=0", nullptr); + GetACookie(cookieService, "http://expireme.org/", nullptr, getter_Copies(cookie)); + EXPECT_TRUE(CheckResult(cookie.get(), MUST_BE_NULL)); - // *** multiple cookie tests - sBuffer = PR_sprintf_append(sBuffer, "*** Beginning multiple cookie tests...\n"); + nsAutoCString ServerTime; + nsAutoCString CookieString; - // test the setting of multiple cookies, and test the order of precedence - // (a later cookie overwriting an earlier one, in the same header string) - SetACookie(cookieService, "http://multiple.cookies/", nullptr, "test=multiple; domain=.multiple.cookies \n test=different \n test=same; domain=.multiple.cookies \n newtest=ciao \n newtest=foo; max-age=-6 \n newtest=reincarnated", nullptr); - GetACookie(cookieService, "http://multiple.cookies/", nullptr, getter_Copies(cookie)); - rv[0] = CheckResult(cookie.get(), MUST_NOT_CONTAIN, "test=multiple"); - rv[1] = CheckResult(cookie.get(), MUST_CONTAIN, "test=different"); - rv[2] = CheckResult(cookie.get(), MUST_CONTAIN, "test=same"); - rv[3] = CheckResult(cookie.get(), MUST_NOT_CONTAIN, "newtest=ciao"); - rv[4] = CheckResult(cookie.get(), MUST_NOT_CONTAIN, "newtest=foo"); - rv[5] = CheckResult(cookie.get(), MUST_CONTAIN, "newtest=reincarnated"); - SetACookie(cookieService, "http://multiple.cookies/", nullptr, "test=expiry; domain=.multiple.cookies; max-age=0", nullptr); - GetACookie(cookieService, "http://multiple.cookies/", nullptr, getter_Copies(cookie)); - rv[6] = CheckResult(cookie.get(), MUST_NOT_CONTAIN, "test=same"); - SetACookie(cookieService, "http://multiple.cookies/", nullptr, "\n test=different; max-age=0 \n", nullptr); - GetACookie(cookieService, "http://multiple.cookies/", nullptr, getter_Copies(cookie)); - rv[7] = CheckResult(cookie.get(), MUST_NOT_CONTAIN, "test=different"); - SetACookie(cookieService, "http://multiple.cookies/", nullptr, "newtest=dead; max-age=0", nullptr); - GetACookie(cookieService, "http://multiple.cookies/", nullptr, getter_Copies(cookie)); - rv[8] = CheckResult(cookie.get(), MUST_BE_NULL); - - allTestsPassed = PrintResult(rv, 9) && allTestsPassed; - - - // *** parser tests - sBuffer = PR_sprintf_append(sBuffer, "*** Beginning parser tests...\n"); + SetTime(-OFFSET_ONE_WEEK, ServerTime, CookieString, true); + SetACookie(cookieService, "http://expireme.org/", nullptr, CookieString.get(), ServerTime.get()); + GetACookie(cookieService, "http://expireme.org/", nullptr, getter_Copies(cookie)); + EXPECT_TRUE(CheckResult(cookie.get(), MUST_BE_NULL)); + // Set server time earlier than client time for one year + one day, and expirty time earlier than server time for one day. + SetTime(-(OFFSET_ONE_DAY + OFFSET_ONE_WEEK), ServerTime, CookieString, false); + SetACookie(cookieService, "http://expireme.org/", nullptr, CookieString.get(), ServerTime.get()); + GetACookie(cookieService, "http://expireme.org/", nullptr, getter_Copies(cookie)); + EXPECT_TRUE(CheckResult(cookie.get(), MUST_BE_NULL)); + // Set server time later than client time for one year, and expiry time later than server time for one day. + SetTime(OFFSET_ONE_WEEK, ServerTime, CookieString, false); + SetACookie(cookieService, "http://expireme.org/", nullptr, CookieString.get(), ServerTime.get()); + GetACookie(cookieService, "http://expireme.org/", nullptr, getter_Copies(cookie)); + EXPECT_TRUE(CheckResult(cookie.get(), MUST_EQUAL, "test=expiry")); + // Set server time later than client time for one year + one day, and expiry time earlier than server time for one day. + SetTime((OFFSET_ONE_DAY + OFFSET_ONE_WEEK), ServerTime, CookieString, true); + SetACookie(cookieService, "http://expireme.org/", nullptr, CookieString.get(), ServerTime.get()); + GetACookie(cookieService, "http://expireme.org/", nullptr, getter_Copies(cookie)); + EXPECT_TRUE(CheckResult(cookie.get(), MUST_EQUAL, "test=expiry")); - // test the cookie header parser, under various circumstances. - SetACookie(cookieService, "http://parser.test/", nullptr, "test=parser; domain=.parser.test; ;; ;=; ,,, ===,abc,=; abracadabra! max-age=20;=;;", nullptr); - GetACookie(cookieService, "http://parser.test/", nullptr, getter_Copies(cookie)); - rv[0] = CheckResult(cookie.get(), MUST_EQUAL, "test=parser"); - SetACookie(cookieService, "http://parser.test/", nullptr, "test=parser; domain=.parser.test; max-age=0", nullptr); - GetACookie(cookieService, "http://parser.test/", nullptr, getter_Copies(cookie)); - rv[1] = CheckResult(cookie.get(), MUST_BE_NULL); - SetACookie(cookieService, "http://parser.test/", nullptr, "test=\"fubar! = foo;bar\\\";\" parser; domain=.parser.test; max-age=6\nfive; max-age=2.63,", nullptr); - GetACookie(cookieService, "http://parser.test/", nullptr, getter_Copies(cookie)); - rv[2] = CheckResult(cookie.get(), MUST_CONTAIN, "test=\"fubar! = foo"); - rv[3] = CheckResult(cookie.get(), MUST_CONTAIN, "five"); - SetACookie(cookieService, "http://parser.test/", nullptr, "test=kill; domain=.parser.test; max-age=0 \n five; max-age=0", nullptr); - GetACookie(cookieService, "http://parser.test/", nullptr, getter_Copies(cookie)); - rv[4] = CheckResult(cookie.get(), MUST_BE_NULL); + // *** multiple cookie tests - // test the handling of VALUE-only cookies (see bug 169091), - // i.e. "six" should assume an empty NAME, which allows other VALUE-only - // cookies to overwrite it - SetACookie(cookieService, "http://parser.test/", nullptr, "six", nullptr); - GetACookie(cookieService, "http://parser.test/", nullptr, getter_Copies(cookie)); - rv[5] = CheckResult(cookie.get(), MUST_EQUAL, "six"); - SetACookie(cookieService, "http://parser.test/", nullptr, "seven", nullptr); - GetACookie(cookieService, "http://parser.test/", nullptr, getter_Copies(cookie)); - rv[6] = CheckResult(cookie.get(), MUST_EQUAL, "seven"); - SetACookie(cookieService, "http://parser.test/", nullptr, " =eight", nullptr); - GetACookie(cookieService, "http://parser.test/", nullptr, getter_Copies(cookie)); - rv[7] = CheckResult(cookie.get(), MUST_EQUAL, "eight"); - SetACookie(cookieService, "http://parser.test/", nullptr, "test=six", nullptr); - GetACookie(cookieService, "http://parser.test/", nullptr, getter_Copies(cookie)); - rv[9] = CheckResult(cookie.get(), MUST_CONTAIN, "test=six"); - - allTestsPassed = PrintResult(rv, 10) && allTestsPassed; + // test the setting of multiple cookies, and test the order of precedence + // (a later cookie overwriting an earlier one, in the same header string) + SetACookie(cookieService, "http://multiple.cookies/", nullptr, "test=multiple; domain=.multiple.cookies \n test=different \n test=same; domain=.multiple.cookies \n newtest=ciao \n newtest=foo; max-age=-6 \n newtest=reincarnated", nullptr); + GetACookie(cookieService, "http://multiple.cookies/", nullptr, getter_Copies(cookie)); + EXPECT_TRUE(CheckResult(cookie.get(), MUST_NOT_CONTAIN, "test=multiple")); + EXPECT_TRUE(CheckResult(cookie.get(), MUST_CONTAIN, "test=different")); + EXPECT_TRUE(CheckResult(cookie.get(), MUST_CONTAIN, "test=same")); + EXPECT_TRUE(CheckResult(cookie.get(), MUST_NOT_CONTAIN, "newtest=ciao")); + EXPECT_TRUE(CheckResult(cookie.get(), MUST_NOT_CONTAIN, "newtest=foo")); + EXPECT_TRUE(CheckResult(cookie.get(), MUST_CONTAIN, "newtest=reincarnated")); + SetACookie(cookieService, "http://multiple.cookies/", nullptr, "test=expiry; domain=.multiple.cookies; max-age=0", nullptr); + GetACookie(cookieService, "http://multiple.cookies/", nullptr, getter_Copies(cookie)); + EXPECT_TRUE(CheckResult(cookie.get(), MUST_NOT_CONTAIN, "test=same")); + SetACookie(cookieService, "http://multiple.cookies/", nullptr, "\n test=different; max-age=0 \n", nullptr); + GetACookie(cookieService, "http://multiple.cookies/", nullptr, getter_Copies(cookie)); + EXPECT_TRUE(CheckResult(cookie.get(), MUST_NOT_CONTAIN, "test=different")); + SetACookie(cookieService, "http://multiple.cookies/", nullptr, "newtest=dead; max-age=0", nullptr); + GetACookie(cookieService, "http://multiple.cookies/", nullptr, getter_Copies(cookie)); + EXPECT_TRUE(CheckResult(cookie.get(), MUST_BE_NULL)); - // *** path ordering tests - sBuffer = PR_sprintf_append(sBuffer, "*** Beginning path ordering tests...\n"); + // *** parser tests + + // test the cookie header parser, under various circumstances. + SetACookie(cookieService, "http://parser.test/", nullptr, "test=parser; domain=.parser.test; ;; ;=; ,,, ===,abc,=; abracadabra! max-age=20;=;;", nullptr); + GetACookie(cookieService, "http://parser.test/", nullptr, getter_Copies(cookie)); + EXPECT_TRUE(CheckResult(cookie.get(), MUST_EQUAL, "test=parser")); + SetACookie(cookieService, "http://parser.test/", nullptr, "test=parser; domain=.parser.test; max-age=0", nullptr); + GetACookie(cookieService, "http://parser.test/", nullptr, getter_Copies(cookie)); + EXPECT_TRUE(CheckResult(cookie.get(), MUST_BE_NULL)); + SetACookie(cookieService, "http://parser.test/", nullptr, "test=\"fubar! = foo;bar\\\";\" parser; domain=.parser.test; max-age=6\nfive; max-age=2.63,", nullptr); + GetACookie(cookieService, "http://parser.test/", nullptr, getter_Copies(cookie)); + EXPECT_TRUE(CheckResult(cookie.get(), MUST_CONTAIN, "test=\"fubar! = foo")); + EXPECT_TRUE(CheckResult(cookie.get(), MUST_CONTAIN, "five")); + SetACookie(cookieService, "http://parser.test/", nullptr, "test=kill; domain=.parser.test; max-age=0 \n five; max-age=0", nullptr); + GetACookie(cookieService, "http://parser.test/", nullptr, getter_Copies(cookie)); + EXPECT_TRUE(CheckResult(cookie.get(), MUST_BE_NULL)); - // test that cookies are returned in path order - longest to shortest. - // if the header doesn't specify a path, it's taken from the host URI. - SetACookie(cookieService, "http://multi.path.tests/", nullptr, "test1=path; path=/one/two/three", nullptr); - SetACookie(cookieService, "http://multi.path.tests/", nullptr, "test2=path; path=/one \n test3=path; path=/one/two/three/four \n test4=path; path=/one/two \n test5=path; path=/one/two/", nullptr); - SetACookie(cookieService, "http://multi.path.tests/one/two/three/four/five/", nullptr, "test6=path", nullptr); - SetACookie(cookieService, "http://multi.path.tests/one/two/three/four/five/six/", nullptr, "test7=path; path=", nullptr); - SetACookie(cookieService, "http://multi.path.tests/", nullptr, "test8=path; path=/", nullptr); - GetACookie(cookieService, "http://multi.path.tests/one/two/three/four/five/six/", nullptr, getter_Copies(cookie)); - rv[0] = CheckResult(cookie.get(), MUST_EQUAL, "test7=path; test6=path; test3=path; test1=path; test5=path; test4=path; test2=path; test8=path"); + // test the handling of VALUE-only cookies (see bug 169091), + // i.e. "six" should assume an empty NAME, which allows other VALUE-only + // cookies to overwrite it + SetACookie(cookieService, "http://parser.test/", nullptr, "six", nullptr); + GetACookie(cookieService, "http://parser.test/", nullptr, getter_Copies(cookie)); + EXPECT_TRUE(CheckResult(cookie.get(), MUST_EQUAL, "six")); + SetACookie(cookieService, "http://parser.test/", nullptr, "seven", nullptr); + GetACookie(cookieService, "http://parser.test/", nullptr, getter_Copies(cookie)); + EXPECT_TRUE(CheckResult(cookie.get(), MUST_EQUAL, "seven")); + SetACookie(cookieService, "http://parser.test/", nullptr, " =eight", nullptr); + GetACookie(cookieService, "http://parser.test/", nullptr, getter_Copies(cookie)); + EXPECT_TRUE(CheckResult(cookie.get(), MUST_EQUAL, "eight")); + SetACookie(cookieService, "http://parser.test/", nullptr, "test=six", nullptr); + GetACookie(cookieService, "http://parser.test/", nullptr, getter_Copies(cookie)); + EXPECT_TRUE(CheckResult(cookie.get(), MUST_CONTAIN, "test=six")); - allTestsPassed = PrintResult(rv, 1) && allTestsPassed; + // *** path ordering tests + + // test that cookies are returned in path order - longest to shortest. + // if the header doesn't specify a path, it's taken from the host URI. + SetACookie(cookieService, "http://multi.path.tests/", nullptr, "test1=path; path=/one/two/three", nullptr); + SetACookie(cookieService, "http://multi.path.tests/", nullptr, "test2=path; path=/one \n test3=path; path=/one/two/three/four \n test4=path; path=/one/two \n test5=path; path=/one/two/", nullptr); + SetACookie(cookieService, "http://multi.path.tests/one/two/three/four/five/", nullptr, "test6=path", nullptr); + SetACookie(cookieService, "http://multi.path.tests/one/two/three/four/five/six/", nullptr, "test7=path; path=", nullptr); + SetACookie(cookieService, "http://multi.path.tests/", nullptr, "test8=path; path=/", nullptr); + GetACookie(cookieService, "http://multi.path.tests/one/two/three/four/five/six/", nullptr, getter_Copies(cookie)); + EXPECT_TRUE(CheckResult(cookie.get(), MUST_EQUAL, "test7=path; test6=path; test3=path; test1=path; test5=path; test4=path; test2=path; test8=path")); - // *** httponly tests - sBuffer = PR_sprintf_append(sBuffer, "*** Beginning httponly tests...\n"); + // *** httponly tests - // Since this cookie is NOT set via http, setting it fails - SetACookieNoHttp(cookieService, "http://httponly.test/", "test=httponly; httponly"); - GetACookie(cookieService, "http://httponly.test/", nullptr, getter_Copies(cookie)); - rv[0] = CheckResult(cookie.get(), MUST_BE_NULL); - // Since this cookie is set via http, it can be retrieved - SetACookie(cookieService, "http://httponly.test/", nullptr, "test=httponly; httponly", nullptr); - GetACookie(cookieService, "http://httponly.test/", nullptr, getter_Copies(cookie)); - rv[1] = CheckResult(cookie.get(), MUST_EQUAL, "test=httponly"); - // ... but not by web content - GetACookieNoHttp(cookieService, "http://httponly.test/", getter_Copies(cookie)); - rv[2] = CheckResult(cookie.get(), MUST_BE_NULL); - // Non-Http cookies should not replace HttpOnly cookies - SetACookie(cookieService, "http://httponly.test/", nullptr, "test=httponly; httponly", nullptr); - SetACookieNoHttp(cookieService, "http://httponly.test/", "test=not-httponly"); - GetACookie(cookieService, "http://httponly.test/", nullptr, getter_Copies(cookie)); - rv[3] = CheckResult(cookie.get(), MUST_EQUAL, "test=httponly"); - // ... and, if an HttpOnly cookie already exists, should not be set at all - GetACookieNoHttp(cookieService, "http://httponly.test/", getter_Copies(cookie)); - rv[4] = CheckResult(cookie.get(), MUST_BE_NULL); - // Non-Http cookies should not delete HttpOnly cookies - SetACookie(cookieService, "http://httponly.test/", nullptr, "test=httponly; httponly", nullptr); - SetACookieNoHttp(cookieService, "http://httponly.test/", "test=httponly; max-age=-1"); - GetACookie(cookieService, "http://httponly.test/", nullptr, getter_Copies(cookie)); - rv[5] = CheckResult(cookie.get(), MUST_EQUAL, "test=httponly"); - // ... but HttpOnly cookies should - SetACookie(cookieService, "http://httponly.test/", nullptr, "test=httponly; httponly; max-age=-1", nullptr); - GetACookie(cookieService, "http://httponly.test/", nullptr, getter_Copies(cookie)); - rv[6] = CheckResult(cookie.get(), MUST_BE_NULL); - // Non-Httponly cookies can replace HttpOnly cookies when set over http - SetACookie(cookieService, "http://httponly.test/", nullptr, "test=httponly; httponly", nullptr); - SetACookie(cookieService, "http://httponly.test/", nullptr, "test=not-httponly", nullptr); - GetACookieNoHttp(cookieService, "http://httponly.test/", getter_Copies(cookie)); - rv[7] = CheckResult(cookie.get(), MUST_EQUAL, "test=not-httponly"); - // scripts should not be able to set httponly cookies by replacing an existing non-httponly cookie - SetACookie(cookieService, "http://httponly.test/", nullptr, "test=not-httponly", nullptr); - SetACookieNoHttp(cookieService, "http://httponly.test/", "test=httponly; httponly"); - GetACookieNoHttp(cookieService, "http://httponly.test/", getter_Copies(cookie)); - rv[8] = CheckResult(cookie.get(), MUST_EQUAL, "test=not-httponly"); - - allTestsPassed = PrintResult(rv, 9) && allTestsPassed; + // Since this cookie is NOT set via http, setting it fails + SetACookieNoHttp(cookieService, "http://httponly.test/", "test=httponly; httponly"); + GetACookie(cookieService, "http://httponly.test/", nullptr, getter_Copies(cookie)); + EXPECT_TRUE(CheckResult(cookie.get(), MUST_BE_NULL)); + // Since this cookie is set via http, it can be retrieved + SetACookie(cookieService, "http://httponly.test/", nullptr, "test=httponly; httponly", nullptr); + GetACookie(cookieService, "http://httponly.test/", nullptr, getter_Copies(cookie)); + EXPECT_TRUE(CheckResult(cookie.get(), MUST_EQUAL, "test=httponly")); + // ... but not by web content + GetACookieNoHttp(cookieService, "http://httponly.test/", getter_Copies(cookie)); + EXPECT_TRUE(CheckResult(cookie.get(), MUST_BE_NULL)); + // Non-Http cookies should not replace HttpOnly cookies + SetACookie(cookieService, "http://httponly.test/", nullptr, "test=httponly; httponly", nullptr); + SetACookieNoHttp(cookieService, "http://httponly.test/", "test=not-httponly"); + GetACookie(cookieService, "http://httponly.test/", nullptr, getter_Copies(cookie)); + EXPECT_TRUE(CheckResult(cookie.get(), MUST_EQUAL, "test=httponly")); + // ... and, if an HttpOnly cookie already exists, should not be set at all + GetACookieNoHttp(cookieService, "http://httponly.test/", getter_Copies(cookie)); + EXPECT_TRUE(CheckResult(cookie.get(), MUST_BE_NULL)); + // Non-Http cookies should not delete HttpOnly cookies + SetACookie(cookieService, "http://httponly.test/", nullptr, "test=httponly; httponly", nullptr); + SetACookieNoHttp(cookieService, "http://httponly.test/", "test=httponly; max-age=-1"); + GetACookie(cookieService, "http://httponly.test/", nullptr, getter_Copies(cookie)); + EXPECT_TRUE(CheckResult(cookie.get(), MUST_EQUAL, "test=httponly")); + // ... but HttpOnly cookies should + SetACookie(cookieService, "http://httponly.test/", nullptr, "test=httponly; httponly; max-age=-1", nullptr); + GetACookie(cookieService, "http://httponly.test/", nullptr, getter_Copies(cookie)); + EXPECT_TRUE(CheckResult(cookie.get(), MUST_BE_NULL)); + // Non-Httponly cookies can replace HttpOnly cookies when set over http + SetACookie(cookieService, "http://httponly.test/", nullptr, "test=httponly; httponly", nullptr); + SetACookie(cookieService, "http://httponly.test/", nullptr, "test=not-httponly", nullptr); + GetACookieNoHttp(cookieService, "http://httponly.test/", getter_Copies(cookie)); + EXPECT_TRUE(CheckResult(cookie.get(), MUST_EQUAL, "test=not-httponly")); + // scripts should not be able to set httponly cookies by replacing an existing non-httponly cookie + SetACookie(cookieService, "http://httponly.test/", nullptr, "test=not-httponly", nullptr); + SetACookieNoHttp(cookieService, "http://httponly.test/", "test=httponly; httponly"); + GetACookieNoHttp(cookieService, "http://httponly.test/", getter_Copies(cookie)); + EXPECT_TRUE(CheckResult(cookie.get(), MUST_EQUAL, "test=not-httponly")); - // *** Cookie prefix tests - sBuffer = PR_sprintf_append(sBuffer, "*** Beginning cookie prefix tests...\n"); + // *** Cookie prefix tests - // prefixed cookies can't be set from insecure HTTP - SetACookie(cookieService, "http://prefixed.test/", nullptr, "__Secure-test1=test", nullptr); - SetACookie(cookieService, "http://prefixed.test/", nullptr, "__Secure-test2=test; secure", nullptr); - SetACookie(cookieService, "http://prefixed.test/", nullptr, "__Host-test1=test", nullptr); - SetACookie(cookieService, "http://prefixed.test/", nullptr, "__Host-test2=test; secure", nullptr); - GetACookie(cookieService, "http://prefixed.test/", nullptr, getter_Copies(cookie)); - rv[0] = CheckResult(cookie.get(), MUST_BE_NULL); + // prefixed cookies can't be set from insecure HTTP + SetACookie(cookieService, "http://prefixed.test/", nullptr, "__Secure-test1=test", nullptr); + SetACookie(cookieService, "http://prefixed.test/", nullptr, "__Secure-test2=test; secure", nullptr); + SetACookie(cookieService, "http://prefixed.test/", nullptr, "__Host-test1=test", nullptr); + SetACookie(cookieService, "http://prefixed.test/", nullptr, "__Host-test2=test; secure", nullptr); + GetACookie(cookieService, "http://prefixed.test/", nullptr, getter_Copies(cookie)); + EXPECT_TRUE(CheckResult(cookie.get(), MUST_BE_NULL)); - // prefixed cookies won't be set without the secure flag - SetACookie(cookieService, "https://prefixed.test/", nullptr, "__Secure-test=test", nullptr); - SetACookie(cookieService, "https://prefixed.test/", nullptr, "__Host-test=test", nullptr); - GetACookie(cookieService, "https://prefixed.test/", nullptr, getter_Copies(cookie)); - rv[1] = CheckResult(cookie.get(), MUST_BE_NULL); + // prefixed cookies won't be set without the secure flag + SetACookie(cookieService, "https://prefixed.test/", nullptr, "__Secure-test=test", nullptr); + SetACookie(cookieService, "https://prefixed.test/", nullptr, "__Host-test=test", nullptr); + GetACookie(cookieService, "https://prefixed.test/", nullptr, getter_Copies(cookie)); + EXPECT_TRUE(CheckResult(cookie.get(), MUST_BE_NULL)); - // prefixed cookies can be set when done correctly - SetACookie(cookieService, "https://prefixed.test/", nullptr, "__Secure-test=test; secure", nullptr); - SetACookie(cookieService, "https://prefixed.test/", nullptr, "__Host-test=test; secure", nullptr); - GetACookie(cookieService, "https://prefixed.test/", nullptr, getter_Copies(cookie)); - rv[2] = CheckResult(cookie.get(), MUST_CONTAIN, "__Secure-test=test"); - rv[3] = CheckResult(cookie.get(), MUST_CONTAIN, "__Host-test=test"); + // prefixed cookies can be set when done correctly + SetACookie(cookieService, "https://prefixed.test/", nullptr, "__Secure-test=test; secure", nullptr); + SetACookie(cookieService, "https://prefixed.test/", nullptr, "__Host-test=test; secure", nullptr); + GetACookie(cookieService, "https://prefixed.test/", nullptr, getter_Copies(cookie)); + EXPECT_TRUE(CheckResult(cookie.get(), MUST_CONTAIN, "__Secure-test=test")); + EXPECT_TRUE(CheckResult(cookie.get(), MUST_CONTAIN, "__Host-test=test")); - // but when set must not be returned to the host insecurely - GetACookie(cookieService, "http://prefixed.test/", nullptr, getter_Copies(cookie)); - rv[4] = CheckResult(cookie.get(), MUST_BE_NULL); + // but when set must not be returned to the host insecurely + GetACookie(cookieService, "http://prefixed.test/", nullptr, getter_Copies(cookie)); + EXPECT_TRUE(CheckResult(cookie.get(), MUST_BE_NULL)); - // Host-prefixed cookies cannot specify a domain - SetACookie(cookieService, "https://host.prefixed.test/", nullptr, "__Host-a=test; secure; domain=prefixed.test", nullptr); - SetACookie(cookieService, "https://host.prefixed.test/", nullptr, "__Host-b=test; secure; domain=.prefixed.test", nullptr); - SetACookie(cookieService, "https://host.prefixed.test/", nullptr, "__Host-c=test; secure; domain=host.prefixed.test", nullptr); - SetACookie(cookieService, "https://host.prefixed.test/", nullptr, "__Host-d=test; secure; domain=.host.prefixed.test", nullptr); - GetACookie(cookieService, "https://host.prefixed.test/", nullptr, getter_Copies(cookie)); - rv[5] = CheckResult(cookie.get(), MUST_BE_NULL); + // Host-prefixed cookies cannot specify a domain + SetACookie(cookieService, "https://host.prefixed.test/", nullptr, "__Host-a=test; secure; domain=prefixed.test", nullptr); + SetACookie(cookieService, "https://host.prefixed.test/", nullptr, "__Host-b=test; secure; domain=.prefixed.test", nullptr); + SetACookie(cookieService, "https://host.prefixed.test/", nullptr, "__Host-c=test; secure; domain=host.prefixed.test", nullptr); + SetACookie(cookieService, "https://host.prefixed.test/", nullptr, "__Host-d=test; secure; domain=.host.prefixed.test", nullptr); + GetACookie(cookieService, "https://host.prefixed.test/", nullptr, getter_Copies(cookie)); + EXPECT_TRUE(CheckResult(cookie.get(), MUST_BE_NULL)); - // Host-prefixed cookies can only have a path of "/" - SetACookie(cookieService, "https://host.prefixed.test/some/path", nullptr, "__Host-e=test; secure", nullptr); - SetACookie(cookieService, "https://host.prefixed.test/some/path", nullptr, "__Host-f=test; secure; path=/", nullptr); - SetACookie(cookieService, "https://host.prefixed.test/some/path", nullptr, "__Host-g=test; secure; path=/some", nullptr); - GetACookie(cookieService, "https://host.prefixed.test/", nullptr, getter_Copies(cookie)); - rv[6] = CheckResult(cookie.get(), MUST_EQUAL, "__Host-f=test"); - - allTestsPassed = PrintResult(rv, 7) && allTestsPassed; + // Host-prefixed cookies can only have a path of "/" + SetACookie(cookieService, "https://host.prefixed.test/some/path", nullptr, "__Host-e=test; secure", nullptr); + SetACookie(cookieService, "https://host.prefixed.test/some/path", nullptr, "__Host-f=test; secure; path=/", nullptr); + SetACookie(cookieService, "https://host.prefixed.test/some/path", nullptr, "__Host-g=test; secure; path=/some", nullptr); + GetACookie(cookieService, "https://host.prefixed.test/", nullptr, getter_Copies(cookie)); + EXPECT_TRUE(CheckResult(cookie.get(), MUST_EQUAL, "__Host-f=test")); - // *** nsICookieManager{2} interface tests - sBuffer = PR_sprintf_append(sBuffer, "*** Beginning nsICookieManager{2} interface tests...\n"); - nsCOMPtr<nsICookieManager> cookieMgr = do_GetService(NS_COOKIEMANAGER_CONTRACTID, &rv0); - if (NS_FAILED(rv0)) return -1; - nsCOMPtr<nsICookieManager2> cookieMgr2 = do_QueryInterface(cookieMgr); - if (!cookieMgr2) return -1; + // *** nsICookieManager{2} interface tests + nsCOMPtr<nsICookieManager> cookieMgr = do_GetService(NS_COOKIEMANAGER_CONTRACTID, &rv0); + ASSERT_TRUE(NS_SUCCEEDED(rv0)); - mozilla::NeckoOriginAttributes attrs; + nsCOMPtr<nsICookieManager2> cookieMgr2 = do_QueryInterface(cookieMgr); + ASSERT_TRUE(cookieMgr2); + + mozilla::NeckoOriginAttributes attrs; - // first, ensure a clean slate - rv[0] = NS_SUCCEEDED(cookieMgr->RemoveAll()); - // add some cookies - rv[1] = NS_SUCCEEDED(cookieMgr2->AddNative(NS_LITERAL_CSTRING("cookiemgr.test"), // domain - NS_LITERAL_CSTRING("/foo"), // path - NS_LITERAL_CSTRING("test1"), // name - NS_LITERAL_CSTRING("yes"), // value - false, // is secure - false, // is httponly - true, // is session - INT64_MAX, // expiry time - &attrs)); // originAttributes - rv[2] = NS_SUCCEEDED(cookieMgr2->AddNative(NS_LITERAL_CSTRING("cookiemgr.test"), // domain - NS_LITERAL_CSTRING("/foo"), // path - NS_LITERAL_CSTRING("test2"), // name - NS_LITERAL_CSTRING("yes"), // value - false, // is secure - true, // is httponly - true, // is session - PR_Now() / PR_USEC_PER_SEC + 2, // expiry time - &attrs)); // originAttributes - rv[3] = NS_SUCCEEDED(cookieMgr2->AddNative(NS_LITERAL_CSTRING("new.domain"), // domain - NS_LITERAL_CSTRING("/rabbit"), // path - NS_LITERAL_CSTRING("test3"), // name - NS_LITERAL_CSTRING("yes"), // value - false, // is secure - false, // is httponly - true, // is session - INT64_MAX, // expiry time - &attrs)); // originAttributes - // confirm using enumerator - nsCOMPtr<nsISimpleEnumerator> enumerator; - rv[4] = NS_SUCCEEDED(cookieMgr->GetEnumerator(getter_AddRefs(enumerator))); - int32_t i = 0; - bool more; - nsCOMPtr<nsICookie2> expiredCookie, newDomainCookie; - while (NS_SUCCEEDED(enumerator->HasMoreElements(&more)) && more) { + // first, ensure a clean slate + EXPECT_TRUE(NS_SUCCEEDED(cookieMgr->RemoveAll())); + // add some cookies + EXPECT_TRUE(NS_SUCCEEDED(cookieMgr2->AddNative(NS_LITERAL_CSTRING("cookiemgr.test"), // domain + NS_LITERAL_CSTRING("/foo"), // path + NS_LITERAL_CSTRING("test1"), // name + NS_LITERAL_CSTRING("yes"), // value + false, // is secure + false, // is httponly + true, // is session + INT64_MAX, // expiry time + &attrs))); // originAttributes + EXPECT_TRUE(NS_SUCCEEDED(cookieMgr2->AddNative(NS_LITERAL_CSTRING("cookiemgr.test"), // domain + NS_LITERAL_CSTRING("/foo"), // path + NS_LITERAL_CSTRING("test2"), // name + NS_LITERAL_CSTRING("yes"), // value + false, // is secure + true, // is httponly + true, // is session + PR_Now() / PR_USEC_PER_SEC + 2, // expiry time + &attrs))); // originAttributes + EXPECT_TRUE(NS_SUCCEEDED(cookieMgr2->AddNative(NS_LITERAL_CSTRING("new.domain"), // domain + NS_LITERAL_CSTRING("/rabbit"), // path + NS_LITERAL_CSTRING("test3"), // name + NS_LITERAL_CSTRING("yes"), // value + false, // is secure + false, // is httponly + true, // is session + INT64_MAX, // expiry time + &attrs))); // originAttributes + // confirm using enumerator + nsCOMPtr<nsISimpleEnumerator> enumerator; + EXPECT_TRUE(NS_SUCCEEDED(cookieMgr->GetEnumerator(getter_AddRefs(enumerator)))); + int32_t i = 0; + bool more; + nsCOMPtr<nsICookie2> expiredCookie, newDomainCookie; + while (NS_SUCCEEDED(enumerator->HasMoreElements(&more)) && more) { nsCOMPtr<nsISupports> cookie; if (NS_FAILED(enumerator->GetNext(getter_AddRefs(cookie)))) break; ++i; // keep tabs on the second and third cookies, so we can check them later nsCOMPtr<nsICookie2> cookie2(do_QueryInterface(cookie)); if (!cookie2) break; nsAutoCString name; cookie2->GetName(name); if (name.EqualsLiteral("test2")) - expiredCookie = cookie2; + expiredCookie = cookie2; else if (name.EqualsLiteral("test3")) - newDomainCookie = cookie2; - } - rv[5] = i == 3; - // check the httpOnly attribute of the second cookie is honored - GetACookie(cookieService, "http://cookiemgr.test/foo/", nullptr, getter_Copies(cookie)); - rv[6] = CheckResult(cookie.get(), MUST_CONTAIN, "test2=yes"); - GetACookieNoHttp(cookieService, "http://cookiemgr.test/foo/", getter_Copies(cookie)); - rv[7] = CheckResult(cookie.get(), MUST_NOT_CONTAIN, "test2=yes"); - // check CountCookiesFromHost() - uint32_t hostCookies = 0; - rv[8] = NS_SUCCEEDED(cookieMgr2->CountCookiesFromHost(NS_LITERAL_CSTRING("cookiemgr.test"), &hostCookies)) && - hostCookies == 2; - // check CookieExistsNative() using the third cookie - bool found; - rv[9] = NS_SUCCEEDED(cookieMgr2->CookieExistsNative(newDomainCookie, &attrs, &found)) && found; + newDomainCookie = cookie2; + } + EXPECT_EQ(i, 3); + // check the httpOnly attribute of the second cookie is honored + GetACookie(cookieService, "http://cookiemgr.test/foo/", nullptr, getter_Copies(cookie)); + EXPECT_TRUE(CheckResult(cookie.get(), MUST_CONTAIN, "test2=yes")); + GetACookieNoHttp(cookieService, "http://cookiemgr.test/foo/", getter_Copies(cookie)); + EXPECT_TRUE(CheckResult(cookie.get(), MUST_NOT_CONTAIN, "test2=yes")); + // check CountCookiesFromHost() + uint32_t hostCookies = 0; + EXPECT_TRUE(NS_SUCCEEDED(cookieMgr2->CountCookiesFromHost(NS_LITERAL_CSTRING("cookiemgr.test"), &hostCookies))); + EXPECT_EQ(hostCookies, 2); + // check CookieExistsNative() using the third cookie + bool found; + EXPECT_TRUE(NS_SUCCEEDED(cookieMgr2->CookieExistsNative(newDomainCookie, &attrs, &found))); + EXPECT_TRUE(found); - // remove the cookie, block it, and ensure it can't be added again - rv[10] = NS_SUCCEEDED(cookieMgr->RemoveNative(NS_LITERAL_CSTRING("new.domain"), // domain - NS_LITERAL_CSTRING("test3"), // name - NS_LITERAL_CSTRING("/rabbit"), // path - true, // is blocked - &attrs)); // originAttributes - rv[11] = NS_SUCCEEDED(cookieMgr2->CookieExistsNative(newDomainCookie, &attrs, &found)) && !found; - rv[12] = NS_SUCCEEDED(cookieMgr2->AddNative(NS_LITERAL_CSTRING("new.domain"), // domain - NS_LITERAL_CSTRING("/rabbit"), // path - NS_LITERAL_CSTRING("test3"), // name - NS_LITERAL_CSTRING("yes"), // value - false, // is secure - false, // is httponly - true, // is session - INT64_MIN, // expiry time - &attrs)); // originAttributes - rv[13] = NS_SUCCEEDED(cookieMgr2->CookieExistsNative(newDomainCookie, &attrs, &found)) && !found; - // sleep four seconds, to make sure the second cookie has expired - PR_Sleep(4 * PR_TicksPerSecond()); - // check that both CountCookiesFromHost() and CookieExistsNative() count the - // expired cookie - rv[14] = NS_SUCCEEDED(cookieMgr2->CountCookiesFromHost(NS_LITERAL_CSTRING("cookiemgr.test"), &hostCookies)) && - hostCookies == 2; - rv[15] = NS_SUCCEEDED(cookieMgr2->CookieExistsNative(expiredCookie, &attrs, &found)) && found; - // double-check RemoveAll() using the enumerator - rv[16] = NS_SUCCEEDED(cookieMgr->RemoveAll()); - rv[17] = NS_SUCCEEDED(cookieMgr->GetEnumerator(getter_AddRefs(enumerator))) && - NS_SUCCEEDED(enumerator->HasMoreElements(&more)) && - !more; + // remove the cookie, block it, and ensure it can't be added again + EXPECT_TRUE(NS_SUCCEEDED(cookieMgr->RemoveNative(NS_LITERAL_CSTRING("new.domain"), // domain + NS_LITERAL_CSTRING("test3"), // name + NS_LITERAL_CSTRING("/rabbit"), // path + true, // is blocked + &attrs))); // originAttributes + EXPECT_TRUE(NS_SUCCEEDED(cookieMgr2->CookieExistsNative(newDomainCookie, &attrs, &found))); + EXPECT_FALSE(found); + EXPECT_TRUE(NS_SUCCEEDED(cookieMgr2->AddNative(NS_LITERAL_CSTRING("new.domain"), // domain + NS_LITERAL_CSTRING("/rabbit"), // path + NS_LITERAL_CSTRING("test3"), // name + NS_LITERAL_CSTRING("yes"), // value + false, // is secure + false, // is httponly + true, // is session + INT64_MIN, // expiry time + &attrs))); // originAttributes + EXPECT_TRUE(NS_SUCCEEDED(cookieMgr2->CookieExistsNative(newDomainCookie, &attrs, &found))); + EXPECT_FALSE(found); + // sleep four seconds, to make sure the second cookie has expired + PR_Sleep(4 * PR_TicksPerSecond()); + // check that both CountCookiesFromHost() and CookieExistsNative() count the + // expired cookie + EXPECT_TRUE(NS_SUCCEEDED(cookieMgr2->CountCookiesFromHost(NS_LITERAL_CSTRING("cookiemgr.test"), &hostCookies))); + EXPECT_EQ(hostCookies, 2); + EXPECT_TRUE(NS_SUCCEEDED(cookieMgr2->CookieExistsNative(expiredCookie, &attrs, &found))); + EXPECT_TRUE(found); + // double-check RemoveAll() using the enumerator + EXPECT_TRUE(NS_SUCCEEDED(cookieMgr->RemoveAll())); + EXPECT_TRUE(NS_SUCCEEDED(cookieMgr->GetEnumerator(getter_AddRefs(enumerator))) && + NS_SUCCEEDED(enumerator->HasMoreElements(&more)) && + !more); - allTestsPassed = PrintResult(rv, 18) && allTestsPassed; - - - // *** eviction and creation ordering tests - sBuffer = PR_sprintf_append(sBuffer, "*** Beginning eviction and creation ordering tests...\n"); + // *** eviction and creation ordering tests - // test that cookies are - // a) returned by order of creation time (oldest first, newest last) - // b) evicted by order of lastAccessed time, if the limit on cookies per host (50) is reached - nsAutoCString name; - nsAutoCString expected; - for (int32_t i = 0; i < 60; ++i) { + // test that cookies are + // a) returned by order of creation time (oldest first, newest last) + // b) evicted by order of lastAccessed time, if the limit on cookies per host (50) is reached + nsAutoCString name; + nsAutoCString expected; + for (int32_t i = 0; i < 60; ++i) { name = NS_LITERAL_CSTRING("test"); name.AppendInt(i); name += NS_LITERAL_CSTRING("=creation"); SetACookie(cookieService, "http://creation.ordering.tests/", nullptr, name.get(), nullptr); if (i >= 10) { - expected += name; - if (i < 59) - expected += NS_LITERAL_CSTRING("; "); + expected += name; + if (i < 59) + expected += NS_LITERAL_CSTRING("; "); } - } - GetACookie(cookieService, "http://creation.ordering.tests/", nullptr, getter_Copies(cookie)); - rv[0] = CheckResult(cookie.get(), MUST_EQUAL, expected.get()); - - allTestsPassed = PrintResult(rv, 1) && allTestsPassed; - - - // XXX the following are placeholders: add these tests please! - // *** "noncompliant cookie" tests - // *** IP address tests - // *** speed tests - - - sBuffer = PR_sprintf_append(sBuffer, "\n*** Result: %s!\n\n", allTestsPassed ? "all tests passed" : "TEST(S) FAILED"); } + GetACookie(cookieService, "http://creation.ordering.tests/", nullptr, getter_Copies(cookie)); + EXPECT_TRUE(CheckResult(cookie.get(), MUST_EQUAL, expected.get())); - if (!allTestsPassed) { - // print the entire log - printf("%s", sBuffer); - return 1; - } - - PR_smprintf_free(sBuffer); - sBuffer = nullptr; - - return 0; + // XXX the following are placeholders: add these tests please! + // *** "noncompliant cookie" tests + // *** IP address tests + // *** speed tests } - -// Stubs to make this test happy - -mozilla::dom::OriginAttributesDictionary::OriginAttributesDictionary() - : mAppId(0), - mInIsolatedMozBrowser(false), - mPrivateBrowsingId(0), - mUserContextId(0) -{}
deleted file mode 100644 --- a/netwerk/test/TestDNS.cpp +++ /dev/null @@ -1,130 +0,0 @@ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -#include "TestCommon.h" -#include <stdio.h> -#include <stdlib.h> -#include "nsIServiceManager.h" -#include "nsPIDNSService.h" -#include "nsIDNSListener.h" -#include "nsIDNSRecord.h" -#include "nsICancelable.h" -#include "nsCOMPtr.h" -#include "nsStringAPI.h" -#include "nsNetCID.h" -#include "prinrval.h" -#include "prthread.h" -#include "prnetdb.h" -#include "nsXPCOM.h" -#include "nsServiceManagerUtils.h" - -class myDNSListener : public nsIDNSListener -{ -public: - NS_DECL_THREADSAFE_ISUPPORTS - - myDNSListener(const char *host, int32_t index) - : mHost(host) - , mIndex(index) {} - - NS_IMETHOD OnLookupComplete(nsICancelable *request, - nsIDNSRecord *rec, - nsresult status) override - { - printf("%d: OnLookupComplete called [host=%s status=%x rec=%p]\n", - mIndex, mHost.get(), static_cast<uint32_t>(status), (void*)rec); - - if (NS_SUCCEEDED(status)) { - nsAutoCString buf; - - rec->GetCanonicalName(buf); - printf("%d: canonname=%s\n", mIndex, buf.get()); - - bool hasMore; - while (NS_SUCCEEDED(rec->HasMore(&hasMore)) && hasMore) { - rec->GetNextAddrAsString(buf); - printf("%d: => %s\n", mIndex, buf.get()); - } - } - - return NS_OK; - } - -private: - virtual ~myDNSListener() {} - - nsCString mHost; - int32_t mIndex; -}; - - -NS_IMPL_ISUPPORTS(myDNSListener, nsIDNSListener) - -static bool IsAscii(const char *s) -{ - for (; *s; ++s) { - if (*s & 0x80) - return false; - } - - return true; -} - -int main(int argc, char **argv) -{ - if (test_common_init(&argc, &argv) != 0) - return -1; - - int sleepLen = 10; // default: 10 seconds - - if (argc == 1) { - printf("usage: TestDNS [-N] hostname1 [hostname2 ...]\n"); - return -1; - } - - { - nsCOMPtr<nsIServiceManager> servMan; - NS_InitXPCOM2(getter_AddRefs(servMan), nullptr, nullptr); - - nsCOMPtr<nsPIDNSService> dns = do_GetService(NS_DNSSERVICE_CONTRACTID); - if (!dns) - return -1; - - if (argv[1][0] == '-') { - sleepLen = atoi(argv[1]+1); - argv++; - argc--; - } - - for (int j=0; j<2; ++j) { - for (int i=1; i<argc; ++i) { - // assume non-ASCII input is given in the native charset - nsAutoCString hostBuf; - if (IsAscii(argv[i])) - hostBuf.Assign(argv[i]); - else - hostBuf = NS_ConvertUTF16toUTF8(NS_ConvertASCIItoUTF16(argv[i])); - - nsCOMPtr<nsIDNSListener> listener = new myDNSListener(argv[i], i); - - nsCOMPtr<nsICancelable> req; - nsresult rv = dns->AsyncResolve(hostBuf, - nsIDNSService::RESOLVE_CANONICAL_NAME, - listener, nullptr, getter_AddRefs(req)); - if (NS_FAILED(rv)) - printf("### AsyncResolve failed [rv=%x]\n", - static_cast<uint32_t>(rv)); - } - - printf("main thread sleeping for %d seconds...\n", sleepLen); - PR_Sleep(PR_SecondsToInterval(sleepLen)); - } - - printf("shutting down main thread...\n"); - dns->Shutdown(); - } - - NS_ShutdownXPCOM(nullptr); - return 0; -}
deleted file mode 100644 --- a/netwerk/test/TestIDN.cpp +++ /dev/null @@ -1,52 +0,0 @@ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -#include "TestCommon.h" -#include <stdio.h> -#include "nsIIDNService.h" -#include "nsCOMPtr.h" -#include "nsIServiceManager.h" -#include "nsServiceManagerUtils.h" -#include "nsNetCID.h" -#include "nsStringAPI.h" - -int main(int argc, char **argv) { - if (test_common_init(&argc, &argv) != 0) - return -1; - - // Test case from RFC 3492 (7.1 - Simplified Chinese) - const char plain[] = - "\xE4\xBB\x96\xE4\xBB\xAC\xE4\xB8\xBA\xE4\xBB\x80\xE4\xB9\x88\xE4\xB8\x8D\xE8\xAF\xB4\xE4\xB8\xAD\xE6\x96\x87"; - const char encoded[] = "xn--ihqwcrb4cv8a8dqg056pqjye"; - - nsCOMPtr<nsIIDNService> converter = do_GetService(NS_IDNSERVICE_CONTRACTID); - NS_ASSERTION(converter, "idnSDK not installed!"); - if (converter) { - nsAutoCString buf; - nsresult rv = converter->ConvertUTF8toACE(NS_LITERAL_CSTRING(plain), buf); - NS_ASSERTION(NS_SUCCEEDED(rv), "error ConvertUTF8toACE"); - NS_ASSERTION(buf.Equals(NS_LITERAL_CSTRING(encoded)), - "encode result incorrect"); - printf("encoded = %s\n", buf.get()); - - buf.Truncate(); - rv = converter->ConvertACEtoUTF8(NS_LITERAL_CSTRING(encoded), buf); - NS_ASSERTION(NS_SUCCEEDED(rv), "error ConvertACEtoUTF8"); - NS_ASSERTION(buf.Equals(NS_LITERAL_CSTRING(plain)), - "decode result incorrect"); - printf("decoded = "); - NS_ConvertUTF8toUTF16 utf(buf); - const char16_t *u = utf.get(); - for (int i = 0; u[i]; i++) { - printf("U+%.4X ", u[i]); - } - printf("\n"); - - bool isAce; - rv = converter->IsACE(NS_LITERAL_CSTRING("www.xn--ihqwcrb4cv8a8dqg056pqjye.com"), &isAce); - NS_ASSERTION(NS_SUCCEEDED(rv), "error IsACE"); - NS_ASSERTION(isAce, "IsACE incorrect result"); - } - return 0; -}
deleted file mode 100644 --- a/netwerk/test/TestIOThreads.cpp +++ /dev/null @@ -1,75 +0,0 @@ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -#include "TestCommon.h" -#include "nsXPCOM.h" -#include "nsIServiceManager.h" -#include "nsServiceManagerUtils.h" -#include "nsIEventTarget.h" -#include "nsCOMPtr.h" -#include "nsNetCID.h" -#include "mozilla/Logging.h" - -// -// set NSPR_LOG_MODULES=Test:5 -// -static PRLogModuleInfo *gTestLog = nullptr; -#define LOG(args) MOZ_LOG(gTestLog, mozilla::LogLevel::Debug, args) - -class nsIOEvent : public nsIRunnable { -public: - NS_DECL_THREADSAFE_ISUPPORTS - - nsIOEvent(int i) : mIndex(i) {} - - NS_IMETHOD Run() override { - LOG(("Run [%d]\n", mIndex)); - return NS_OK; - } - -private: - int mIndex; -}; -NS_IMPL_ISUPPORTS(nsIOEvent, nsIRunnable) - -static nsresult RunTest() -{ - nsresult rv; - nsCOMPtr<nsIEventTarget> target = - do_GetService(NS_STREAMTRANSPORTSERVICE_CONTRACTID, &rv); - if (NS_FAILED(rv)) - return rv; - - for (int i=0; i<10; ++i) { - nsCOMPtr<nsIRunnable> event = new nsIOEvent(i); - LOG(("Dispatch %d\n", i)); - target->Dispatch(event, NS_DISPATCH_NORMAL); - } - - return NS_OK; -} - -int main(int argc, char **argv) -{ - if (test_common_init(&argc, &argv) != 0) - return -1; - - nsresult rv; - - gTestLog = PR_NewLogModule("Test"); - - rv = NS_InitXPCOM2(nullptr, nullptr, nullptr); - if (NS_FAILED(rv)) - return rv; - - rv = RunTest(); - if (NS_FAILED(rv)) - LOG(("RunTest failed [rv=%x]\n", rv)); - - LOG(("sleeping main thread for 2 seconds...\n")); - PR_Sleep(PR_SecondsToInterval(2)); - - NS_ShutdownXPCOM(nullptr); - return 0; -}
deleted file mode 100644 --- a/netwerk/test/TestIncrementalDownload.cpp +++ /dev/null @@ -1,133 +0,0 @@ -/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ -/* vim:set ts=2 sw=2 sts=2 cin et: */ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -#include <inttypes.h> -#include <stdlib.h> -#include "TestCommon.h" -#include "nsNetUtil.h" -#include "nsComponentManagerUtils.h" -#include "nsIIncrementalDownload.h" -#include "nsIRequestObserver.h" -#include "nsIProgressEventSink.h" -#include "nsThreadUtils.h" -#include "nsAutoPtr.h" -#include "prprf.h" -#include "prenv.h" -#include "mozilla/Attributes.h" - -//----------------------------------------------------------------------------- - -class FetchObserver final : public nsIRequestObserver - , public nsIProgressEventSink -{ - ~FetchObserver() {} -public: - NS_DECL_ISUPPORTS - NS_DECL_NSIREQUESTOBSERVER - NS_DECL_NSIPROGRESSEVENTSINK -}; - -NS_IMPL_ISUPPORTS(FetchObserver, nsIRequestObserver, - nsIProgressEventSink) - -NS_IMETHODIMP -FetchObserver::OnStartRequest(nsIRequest *request, nsISupports *context) -{ - printf("FetchObserver::OnStartRequest\n"); - return NS_OK; -} - -NS_IMETHODIMP -FetchObserver::OnProgress(nsIRequest *request, nsISupports *context, - int64_t progress, int64_t progressMax) -{ - printf("FetchObserver::OnProgress [%" PRId64 "/%" PRId64 "]\n", - progress, progressMax); - return NS_OK; -} - -NS_IMETHODIMP -FetchObserver::OnStatus(nsIRequest *request, nsISupports *context, - nsresult status, const char16_t *statusText) -{ - return NS_OK; -} - -NS_IMETHODIMP -FetchObserver::OnStopRequest(nsIRequest *request, nsISupports *context, - nsresult status) -{ - printf("FetchObserver::OnStopRequest [status=%x]\n", - static_cast<uint32_t>(status)); - - QuitPumpingEvents(); - return NS_OK; -} - -//----------------------------------------------------------------------------- - -static nsresult -DoIncrementalFetch(const char *uriSpec, const char *resultPath, int32_t chunkSize, - int32_t interval) -{ - nsCOMPtr<nsIFile> resultFile; - nsresult rv = NS_NewNativeLocalFile(nsDependentCString(resultPath), - false, getter_AddRefs(resultFile)); - if (NS_FAILED(rv)) - return rv; - - nsCOMPtr<nsIURI> uri; - rv = NS_NewURI(getter_AddRefs(uri), uriSpec); - if (NS_FAILED(rv)) - return rv; - - nsCOMPtr<nsIRequestObserver> observer = new FetchObserver(); - if (!observer) - return NS_ERROR_OUT_OF_MEMORY; - - nsCOMPtr<nsIIncrementalDownload> download = - do_CreateInstance(NS_INCREMENTALDOWNLOAD_CONTRACTID, &rv); - if (NS_FAILED(rv)) - return rv; - - rv = download->Init(uri, resultFile, chunkSize, interval); - if (NS_FAILED(rv)) - return rv; - - rv = download->Start(observer, nullptr); - if (NS_FAILED(rv)) - return rv; - - PumpEvents(); - return NS_OK; -} - -int -main(int argc, char **argv) -{ - if (PR_GetEnv("MOZ_BREAK_ON_MAIN")) - NS_BREAK(); - - if (argc < 5) { - fprintf(stderr, "USAGE: TestIncrementalDownload <url> <file> <chunksize> <interval-in-seconds>\n"); - return -1; - } - - nsresult rv = NS_InitXPCOM2(nullptr, nullptr, nullptr); - if (NS_FAILED(rv)) - return -1; - - int32_t chunkSize = atoi(argv[3]); - int32_t interval = atoi(argv[4]); - - rv = DoIncrementalFetch(argv[1], argv[2], chunkSize, interval); - if (NS_FAILED(rv)) - fprintf(stderr, "ERROR: DoIncrementalFetch failed [%x]\n", - static_cast<uint32_t>(rv)); - - NS_ShutdownXPCOM(nullptr); - return 0; -}
deleted file mode 100644 --- a/netwerk/test/TestOpen.cpp +++ /dev/null @@ -1,90 +0,0 @@ -/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -#include "TestCommon.h" -#include "nsCOMPtr.h" -#include "nsStringAPI.h" -#include "nsIURI.h" -#include "nsIChannel.h" -#include "nsIHttpChannel.h" -#include "nsIInputStream.h" -#include "nsNetUtil.h" -#include "nsServiceManagerUtils.h" -#include "mozilla/Unused.h" -#include "nsIScriptSecurityManager.h" - -#include <stdio.h> - -using namespace mozilla; - -/* - * Test synchronous Open. - */ - -#define RETURN_IF_FAILED(rv, what) \ - PR_BEGIN_MACRO \ - if (NS_FAILED(rv)) { \ - printf(what ": failed - %08x\n", static_cast<uint32_t>(rv)); \ - return -1; \ - } \ - PR_END_MACRO - -int -main(int argc, char **argv) -{ - if (test_common_init(&argc, &argv) != 0) - return -1; - - nsresult rv = NS_InitXPCOM2(nullptr, nullptr, nullptr); - if (NS_FAILED(rv)) return -1; - - char buf[256]; - - if (argc != 3) { - printf("Usage: TestOpen url filename\nLoads a URL using ::Open, writing it to a file\n"); - return -1; - } - - nsCOMPtr<nsIURI> uri; - nsCOMPtr<nsIInputStream> stream; - - rv = NS_NewURI(getter_AddRefs(uri), argv[1]); - RETURN_IF_FAILED(rv, "NS_NewURI"); - - nsCOMPtr<nsIScriptSecurityManager> secman = - do_GetService(NS_SCRIPTSECURITYMANAGER_CONTRACTID, &rv); - RETURN_IF_FAILED(rv, "Couldn't get script security manager!"); - nsCOMPtr<nsIPrincipal> systemPrincipal; - rv = secman->GetSystemPrincipal(getter_AddRefs(systemPrincipal)); - RETURN_IF_FAILED(rv, "Couldn't get system principal!"); - - nsCOMPtr<nsIChannel> channel; - rv = NS_NewChannel(getter_AddRefs(channel), - uri, - systemPrincipal, - nsILoadInfo::SEC_ALLOW_CROSS_ORIGIN_DATA_IS_NULL, - nsIContentPolicy::TYPE_OTHER); - RETURN_IF_FAILED(rv, "NS_NewChannel"); - - rv = channel->Open2(getter_AddRefs(stream)); - RETURN_IF_FAILED(rv, "channel->Open2()"); - - FILE* outfile = fopen(argv[2], "wb"); - if (!outfile) { - printf("error opening %s\n", argv[2]); - return 1; - } - - uint32_t read; - while (NS_SUCCEEDED(stream->Read(buf, sizeof(buf), &read)) && read) { - Unused << fwrite(buf, 1, read, outfile); - } - printf("Done\n"); - - fclose(outfile); - - NS_ShutdownXPCOM(nullptr); - return 0; -}
deleted file mode 100644 --- a/netwerk/test/TestProtocols.cpp +++ /dev/null @@ -1,896 +0,0 @@ -/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ -/* vim: set ts=2 sw=2 et cindent: */ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -/* - The TestProtocols tests the basic protocols architecture and can - be used to test individual protocols as well. If this grows too - big then we should split it to individual protocols. - - -Gagan Saksena 04/29/99 -*/ - -#include "TestCommon.h" -#include <algorithm> - -#include <stdio.h> -#ifdef WIN32 -#include <windows.h> -#endif -#ifdef XP_UNIX -#include <unistd.h> -#endif -#include "nspr.h" -#include "nscore.h" -#include "nsCOMPtr.h" -#include "nsIIOService.h" -#include "nsIServiceManager.h" -#include "nsIStreamListener.h" -#include "nsIInputStream.h" -#include "nsIInputStream.h" -#include "nsCRT.h" -#include "nsIChannel.h" -#include "nsIResumableChannel.h" -#include "nsIURL.h" -#include "nsIHttpChannel.h" -#include "nsIHttpChannelInternal.h" -#include "nsIHttpHeaderVisitor.h" -#include "nsIChannelEventSink.h" -#include "nsIAsyncVerifyRedirectCallback.h" -#include "nsIInterfaceRequestor.h" -#include "nsIInterfaceRequestorUtils.h" -#include "nsIDNSService.h" -#include "nsIAuthPrompt.h" -#include "nsIPrefService.h" -#include "nsIPrefBranch.h" -#include "nsIPropertyBag2.h" -#include "nsIWritablePropertyBag2.h" -#include "nsITimedChannel.h" -#include "mozilla/Attributes.h" -#include "mozilla/Unused.h" -#include "nsIScriptSecurityManager.h" - -#include "nsISimpleEnumerator.h" -#include "nsStringAPI.h" -#include "nsNetUtil.h" -#include "nsServiceManagerUtils.h" -#include "NetwerkTestLogging.h" - -using namespace mozilla; - -namespace TestProtocols { - -// -// set NSPR_LOG_MODULES=Test:5 -// -static PRLogModuleInfo *gTestLog = nullptr; -#define LOG(args) MOZ_LOG(gTestLog, mozilla::LogLevel::Debug, args) - -static NS_DEFINE_CID(kIOServiceCID, NS_IOSERVICE_CID); - -//static PRTime gElapsedTime; // enable when we time it... -static int gKeepRunning = 0; -static bool gVerbose = false; -static bool gAskUserForInput = false; -static bool gResume = false; -static uint64_t gStartAt = 0; - -static const char* gEntityID; - -//----------------------------------------------------------------------------- -// Set proxy preferences for testing -//----------------------------------------------------------------------------- - -static nsresult -SetHttpProxy(const char *proxy) -{ - const char *colon = strchr(proxy, ':'); - if (!colon) - { - NS_WARNING("invalid proxy token; use host:port"); - return NS_ERROR_UNEXPECTED; - } - int port = atoi(colon + 1); - if (port == 0) - { - NS_WARNING("invalid proxy port; must be an integer"); - return NS_ERROR_UNEXPECTED; - } - nsAutoCString proxyHost; - proxyHost = Substring(proxy, colon); - - nsCOMPtr<nsIPrefBranch> prefs = do_GetService(NS_PREFSERVICE_CONTRACTID); - if (prefs) - { - prefs->SetCharPref("network.proxy.http", proxyHost.get()); - prefs->SetIntPref("network.proxy.http_port", port); - prefs->SetIntPref("network.proxy.type", 1); // manual proxy config - } - LOG(("connecting via proxy=%s:%d\n", proxyHost.get(), port)); - return NS_OK; -} - -static nsresult -SetPACFile(const char* pacURL) -{ - nsCOMPtr<nsIPrefBranch> prefs = do_GetService(NS_PREFSERVICE_CONTRACTID); - if (prefs) - { - prefs->SetCharPref("network.proxy.autoconfig_url", pacURL); - prefs->SetIntPref("network.proxy.type", 2); // PAC file - } - LOG(("connecting using PAC file %s\n", pacURL)); - return NS_OK; -} - -//----------------------------------------------------------------------------- -// Timing information -//----------------------------------------------------------------------------- - -void PrintTimingInformation(nsITimedChannel* channel) { -#define PRINT_VALUE(property) \ - { \ - PRTime value; \ - channel->Get##property(&value); \ - if (value) { \ - PRExplodedTime exploded; \ - PR_ExplodeTime(value, PR_LocalTimeParameters, &exploded); \ - char buf[256]; \ - PR_FormatTime(buf, sizeof(buf), "%Y-%m-%d %H:%M:%S", &exploded); \ - LOG((" " #property ":\t%s (%i usec)", buf, exploded.tm_usec)); \ - } else { \ - LOG((" " #property ":\t0")); \ - } \ - } - LOG(("Timing data:")); - PRINT_VALUE(ChannelCreationTime) - PRINT_VALUE(AsyncOpenTime) - PRINT_VALUE(DomainLookupStartTime) - PRINT_VALUE(DomainLookupEndTime) - PRINT_VALUE(ConnectStartTime) - PRINT_VALUE(ConnectEndTime) - PRINT_VALUE(RequestStartTime) - PRINT_VALUE(ResponseStartTime) - PRINT_VALUE(ResponseEndTime) - PRINT_VALUE(CacheReadStartTime) - PRINT_VALUE(CacheReadEndTime) -} - -//----------------------------------------------------------------------------- -// HeaderVisitor -//----------------------------------------------------------------------------- - -class HeaderVisitor : public nsIHttpHeaderVisitor -{ - virtual ~HeaderVisitor() {} -public: - NS_DECL_ISUPPORTS - NS_DECL_NSIHTTPHEADERVISITOR - - HeaderVisitor() { } -}; -NS_IMPL_ISUPPORTS(HeaderVisitor, nsIHttpHeaderVisitor) - -NS_IMETHODIMP -HeaderVisitor::VisitHeader(const nsACString &header, const nsACString &value) -{ - LOG((" %s: %s\n", - PromiseFlatCString(header).get(), - PromiseFlatCString(value).get())); - return NS_OK; -} - -//----------------------------------------------------------------------------- -// URLLoadInfo -//----------------------------------------------------------------------------- - -class URLLoadInfo : public nsISupports -{ - virtual ~URLLoadInfo(); - -public: - - explicit URLLoadInfo(const char* aUrl); - - // ISupports interface... - NS_DECL_THREADSAFE_ISUPPORTS - - const char* Name() { return mURLString.get(); } - int64_t mBytesRead; - PRTime mTotalTime; - PRTime mConnectTime; - nsCString mURLString; -}; - -URLLoadInfo::URLLoadInfo(const char *aUrl) : mURLString(aUrl) -{ - mBytesRead = 0; - mConnectTime = mTotalTime = PR_Now(); -} - -URLLoadInfo::~URLLoadInfo() -{ -} - - -NS_IMPL_ISUPPORTS0(URLLoadInfo) - -//----------------------------------------------------------------------------- -// TestChannelEventSink -//----------------------------------------------------------------------------- - -class TestChannelEventSink : public nsIChannelEventSink -{ - virtual ~TestChannelEventSink(); - -public: - NS_DECL_ISUPPORTS - NS_DECL_NSICHANNELEVENTSINK - - TestChannelEventSink(); -}; - -TestChannelEventSink::TestChannelEventSink() -{ -} - -TestChannelEventSink::~TestChannelEventSink() -{ -} - - -NS_IMPL_ISUPPORTS(TestChannelEventSink, nsIChannelEventSink) - -NS_IMETHODIMP -TestChannelEventSink::AsyncOnChannelRedirect(nsIChannel *channel, - nsIChannel *newChannel, - uint32_t flags, - nsIAsyncVerifyRedirectCallback *callback) -{ - LOG(("\n+++ TestChannelEventSink::OnChannelRedirect (with flags %x) +++\n", - flags)); - callback->OnRedirectVerifyCallback(NS_OK); - return NS_OK; -} - -//----------------------------------------------------------------------------- -// TestAuthPrompt -//----------------------------------------------------------------------------- - -class TestAuthPrompt : public nsIAuthPrompt -{ - virtual ~TestAuthPrompt(); - -public: - NS_DECL_ISUPPORTS - NS_DECL_NSIAUTHPROMPT - - TestAuthPrompt(); -}; - -NS_IMPL_ISUPPORTS(TestAuthPrompt, nsIAuthPrompt) - -TestAuthPrompt::TestAuthPrompt() -{ -} - -TestAuthPrompt::~TestAuthPrompt() -{ -} - -NS_IMETHODIMP -TestAuthPrompt::Prompt(const char16_t *dialogTitle, - const char16_t *text, - const char16_t *passwordRealm, - uint32_t savePassword, - const char16_t *defaultText, - char16_t **result, - bool *_retval) -{ - *_retval = false; - return NS_ERROR_NOT_IMPLEMENTED; -} - -NS_IMETHODIMP -TestAuthPrompt::PromptUsernameAndPassword(const char16_t *dialogTitle, - const char16_t *dialogText, - const char16_t *passwordRealm, - uint32_t savePassword, - char16_t **user, - char16_t **pwd, - bool *_retval) -{ - NS_ConvertUTF16toUTF8 text(passwordRealm); - printf("* --------------------------------------------------------------------------- *\n"); - printf("* Authentication Required [%s]\n", text.get()); - printf("* --------------------------------------------------------------------------- *\n"); - - char buf[256]; - int n; - - printf("Enter username: "); - Unused << fgets(buf, sizeof(buf), stdin); - n = strlen(buf); - buf[n-1] = '\0'; // trim trailing newline - *user = NS_StringCloneData(NS_ConvertUTF8toUTF16(buf)); - - const char *p; -#if defined(XP_UNIX) && !defined(ANDROID) - p = getpass("Enter password: "); -#else - printf("Enter password: "); - fgets(buf, sizeof(buf), stdin); - n = strlen(buf); - buf[n-1] = '\0'; // trim trailing newline - p = buf; -#endif - *pwd = NS_StringCloneData(NS_ConvertUTF8toUTF16(p)); - - // zap buf - memset(buf, 0, sizeof(buf)); - - *_retval = true; - return NS_OK; -} - -NS_IMETHODIMP -TestAuthPrompt::PromptPassword(const char16_t *dialogTitle, - const char16_t *text, - const char16_t *passwordRealm, - uint32_t savePassword, - char16_t **pwd, - bool *_retval) -{ - *_retval = false; - return NS_ERROR_NOT_IMPLEMENTED; -} - -//----------------------------------------------------------------------------- -// InputTestConsumer -//----------------------------------------------------------------------------- - -class InputTestConsumer : public nsIStreamListener -{ - virtual ~InputTestConsumer(); - -public: - - explicit InputTestConsumer(URLLoadInfo* aURLLoadInfo); - - NS_DECL_ISUPPORTS - NS_DECL_NSIREQUESTOBSERVER - NS_DECL_NSISTREAMLISTENER -private: - URLLoadInfo* mURLLoadInfo; -}; - -InputTestConsumer::InputTestConsumer(URLLoadInfo* aURLLoadInfo) -: mURLLoadInfo(aURLLoadInfo) -{ - NS_IF_ADDREF(mURLLoadInfo); -} - -InputTestConsumer::~InputTestConsumer() -{ - NS_RELEASE(mURLLoadInfo); -} - -NS_IMPL_ISUPPORTS(InputTestConsumer, nsIStreamListener, nsIRequestObserver) - -NS_IMETHODIMP -InputTestConsumer::OnStartRequest(nsIRequest *request, nsISupports* context) -{ - LOG(("InputTestConsumer::OnStartRequest\n")); - - NS_ASSERTION(!context, "context needs to be null when calling asyncOpen2"); - - if (mURLLoadInfo) - mURLLoadInfo->mConnectTime = PR_Now() - mURLLoadInfo->mConnectTime; - - if (gVerbose) { - LOG(("\nStarted loading: %s\n", mURLLoadInfo ? mURLLoadInfo->Name() : "UNKNOWN URL")); - } - - nsAutoCString value; - - nsCOMPtr<nsIChannel> channel = do_QueryInterface(request); - if (channel) { - nsresult status; - channel->GetStatus(&status); - LOG(("Channel Status: %08x\n", status)); - if (NS_SUCCEEDED(status)) { - LOG(("Channel Info:\n")); - - channel->GetName(value); - LOG(("\tName: %s\n", value.get())); - - channel->GetContentType(value); - LOG(("\tContent-Type: %s\n", value.get())); - - channel->GetContentCharset(value); - LOG(("\tContent-Charset: %s\n", value.get())); - - int64_t length = -1; - if (NS_SUCCEEDED(channel->GetContentLength(&length))) { - LOG(("\tContent-Length: %lld\n", length)); - } else { - LOG(("\tContent-Length: Unknown\n")); - } - } - - nsCOMPtr<nsISupports> owner; - channel->GetOwner(getter_AddRefs(owner)); - LOG(("\tChannel Owner: %x\n", owner.get())); - } - - nsCOMPtr<nsIPropertyBag2> props = do_QueryInterface(request); - if (props) { - nsCOMPtr<nsIURI> foo; - props->GetPropertyAsInterface(NS_LITERAL_STRING("test.foo"), - NS_GET_IID(nsIURI), - getter_AddRefs(foo)); - if (foo) { - LOG(("\ttest.foo: %s\n", foo->GetSpecOrDefault().get())); - } - } - - nsCOMPtr<nsIHttpChannelInternal> httpChannelInt(do_QueryInterface(request)); - if (httpChannelInt) { - uint32_t majorVer, minorVer; - nsresult rv = httpChannelInt->GetResponseVersion(&majorVer, &minorVer); - if (NS_SUCCEEDED(rv)) { - LOG(("HTTP Response version: %u.%u\n", majorVer, minorVer)); - } - } - nsCOMPtr<nsIHttpChannel> httpChannel(do_QueryInterface(request)); - if (httpChannel) { - HeaderVisitor *visitor = new HeaderVisitor(); - if (!visitor) - return NS_ERROR_OUT_OF_MEMORY; - NS_ADDREF(visitor); - - LOG(("HTTP request headers:\n")); - httpChannel->VisitRequestHeaders(visitor); - - LOG(("HTTP response headers:\n")); - httpChannel->VisitResponseHeaders(visitor); - - NS_RELEASE(visitor); - } - - nsCOMPtr<nsIResumableChannel> resChannel = do_QueryInterface(request); - if (resChannel) { - LOG(("Resumable entity identification:\n")); - nsAutoCString entityID; - nsresult rv = resChannel->GetEntityID(entityID); - if (NS_SUCCEEDED(rv)) { - LOG(("\t|%s|\n", entityID.get())); - } - else { - LOG(("\t<none>\n")); - } - } - - return NS_OK; -} - -NS_IMETHODIMP -InputTestConsumer::OnDataAvailable(nsIRequest *request, - nsISupports* context, - nsIInputStream *aIStream, - uint64_t aSourceOffset, - uint32_t aLength) -{ - NS_ASSERTION(!context, "context needs to be null when calling asyncOpen2"); - - char buf[1025]; - uint32_t amt, size; - nsresult rv; - - while (aLength) { - size = std::min<uint32_t>(aLength, sizeof(buf)); - - rv = aIStream->Read(buf, size, &amt); - if (NS_FAILED(rv)) { - NS_ASSERTION((NS_BASE_STREAM_WOULD_BLOCK != rv), - "The stream should never block."); - return rv; - } - if (gVerbose) { - buf[amt] = '\0'; - puts(buf); - } - if (mURLLoadInfo) { - mURLLoadInfo->mBytesRead += amt; - } - - aLength -= amt; - } - return NS_OK; -} - -NS_IMETHODIMP -InputTestConsumer::OnStopRequest(nsIRequest *request, nsISupports* context, - nsresult aStatus) -{ - LOG(("InputTestConsumer::OnStopRequest [status=%x]\n", aStatus)); - - if (mURLLoadInfo) { - uint32_t httpStatus; - bool bHTTPURL = false; - - mURLLoadInfo->mTotalTime = PR_Now() - mURLLoadInfo->mTotalTime; - - double readTime = ((mURLLoadInfo->mTotalTime-mURLLoadInfo->mConnectTime)/1000.0)/1000.0; - - nsCOMPtr<nsIHttpChannel> pHTTPCon(do_QueryInterface(request)); - if (pHTTPCon) { - pHTTPCon->GetResponseStatus(&httpStatus); - bHTTPURL = true; - } - - LOG(("\nFinished loading: %s Status Code: %x\n", mURLLoadInfo->Name(), aStatus)); - if (bHTTPURL) { - LOG(("\tHTTP Status: %u\n", httpStatus)); - } - if (NS_ERROR_UNKNOWN_HOST == aStatus || - NS_ERROR_UNKNOWN_PROXY_HOST == aStatus) { - LOG(("\tDNS lookup failed.\n")); - } - LOG(("\tTime to connect: %.3f seconds\n", (mURLLoadInfo->mConnectTime/1000.0)/1000.0)); - LOG(("\tTime to read: %.3f seconds.\n", readTime)); - LOG(("\tRead: %lld bytes.\n", mURLLoadInfo->mBytesRead)); - if (mURLLoadInfo->mBytesRead == int64_t(0)) { - } else if (readTime > 0.0) { - LOG(("\tThroughput: %.0f bps.\n", (double)(mURLLoadInfo->mBytesRead*int64_t(8))/readTime)); - } else { - LOG(("\tThroughput: REAL FAST!!\n")); - } - - nsCOMPtr<nsITimedChannel> timed(do_QueryInterface(request)); - if (timed) - PrintTimingInformation(timed); - } else { - LOG(("\nFinished loading: UNKNOWN URL. Status Code: %x\n", aStatus)); - } - - if (--gKeepRunning == 0) - QuitPumpingEvents(); - return NS_OK; -} - -//----------------------------------------------------------------------------- -// NotificationCallbacks -//----------------------------------------------------------------------------- - -class NotificationCallbacks final : public nsIInterfaceRequestor { - - ~NotificationCallbacks() {} - -public: - NS_DECL_ISUPPORTS - - NotificationCallbacks() { - } - - NS_IMETHOD GetInterface(const nsIID& iid, void* *result) override { - nsresult rv = NS_ERROR_FAILURE; - - if (iid.Equals(NS_GET_IID(nsIChannelEventSink))) { - TestChannelEventSink *sink; - - sink = new TestChannelEventSink(); - if (sink == nullptr) - return NS_ERROR_OUT_OF_MEMORY; - NS_ADDREF(sink); - rv = sink->QueryInterface(iid, result); - NS_RELEASE(sink); - } - - if (iid.Equals(NS_GET_IID(nsIAuthPrompt))) { - TestAuthPrompt *prompt; - - prompt = new TestAuthPrompt(); - if (prompt == nullptr) - return NS_ERROR_OUT_OF_MEMORY; - NS_ADDREF(prompt); - rv = prompt->QueryInterface(iid, result); - NS_RELEASE(prompt); - } - return rv; - } -}; - -NS_IMPL_ISUPPORTS(NotificationCallbacks, nsIInterfaceRequestor) - -//----------------------------------------------------------------------------- -// helpers... -//----------------------------------------------------------------------------- - -nsresult StartLoadingURL(const char* aUrlString) -{ - nsresult rv; - - nsCOMPtr<nsIIOService> pService(do_GetService(kIOServiceCID, &rv)); - if (pService) { - nsCOMPtr<nsIURI> pURL; - - rv = pService->NewURI(nsDependentCString(aUrlString), nullptr, nullptr, getter_AddRefs(pURL)); - if (NS_FAILED(rv)) { - LOG(("ERROR: NewURI failed for %s [rv=%x]\n", aUrlString)); - return rv; - } - nsCOMPtr<nsIChannel> pChannel; - - NotificationCallbacks* callbacks = new NotificationCallbacks(); - if (!callbacks) { - LOG(("Failed to create a new consumer!")); - return NS_ERROR_OUT_OF_MEMORY;; - } - NS_ADDREF(callbacks); - - nsCOMPtr<nsIScriptSecurityManager> secman = - do_GetService(NS_SCRIPTSECURITYMANAGER_CONTRACTID, &rv); - NS_ENSURE_SUCCESS(rv, rv); - nsCOMPtr<nsIPrincipal> systemPrincipal; - rv = secman->GetSystemPrincipal(getter_AddRefs(systemPrincipal)); - NS_ENSURE_SUCCESS(rv, rv); - - // Async reading thru the calls of the event sink interface - rv = NS_NewChannel(getter_AddRefs(pChannel), - pURL, - systemPrincipal, - nsILoadInfo::SEC_ALLOW_CROSS_ORIGIN_DATA_IS_NULL, - nsIContentPolicy::TYPE_OTHER, - nullptr, // loadGroup - callbacks, - nsIRequest::LOAD_NORMAL, - pService); - - NS_RELEASE(callbacks); - if (NS_FAILED(rv)) { - LOG(("ERROR: NS_NewChannel failed for %s [rv=%x]\n", aUrlString, rv)); - return rv; - } - - nsCOMPtr<nsITimedChannel> timed(do_QueryInterface(pChannel)); - if (timed) - timed->SetTimingEnabled(true); - - nsCOMPtr<nsIWritablePropertyBag2> props = do_QueryInterface(pChannel); - if (props) { - rv = props->SetPropertyAsInterface(NS_LITERAL_STRING("test.foo"), - pURL); - if (NS_SUCCEEDED(rv)) { - LOG(("set prop 'test.foo'\n")); - } - } - - /* - You may optionally add/set other headers on this - request object. This is done by QI for the specific - protocolConnection. - */ - nsCOMPtr<nsIHttpChannel> pHTTPCon(do_QueryInterface(pChannel)); - - if (pHTTPCon) { - // Setting a sample header. - rv = pHTTPCon->SetRequestHeader(NS_LITERAL_CSTRING("sample-header"), - NS_LITERAL_CSTRING("Sample-Value"), - false); - if (NS_FAILED(rv)) return rv; - } - URLLoadInfo* info = new URLLoadInfo(aUrlString); - if (!info) { - NS_ERROR("Failed to create a load info!"); - return NS_ERROR_OUT_OF_MEMORY; - } - - InputTestConsumer* listener = new InputTestConsumer(info); - NS_IF_ADDREF(listener); - if (!listener) { - NS_ERROR("Failed to create a new stream listener!"); - return NS_ERROR_OUT_OF_MEMORY;; - } - - - if (gResume) { - nsCOMPtr<nsIResumableChannel> res = do_QueryInterface(pChannel); - if (!res) { - NS_ERROR("Channel is not resumable!"); - return NS_ERROR_UNEXPECTED; - } - nsAutoCString id; - if (gEntityID) - id = gEntityID; - LOG(("* resuming at %llu bytes, with entity id |%s|\n", gStartAt, id.get())); - res->ResumeAt(gStartAt, id); - } - rv = pChannel->AsyncOpen2(listener); - - if (NS_SUCCEEDED(rv)) { - gKeepRunning++; - } - else { - LOG(("ERROR: AsyncOpen failed [rv=%x]\n", rv)); - } - NS_RELEASE(listener); - } - - return rv; -} - -static int32_t -FindChar(nsCString& buffer, char c) -{ - const char *b; - int32_t len = NS_CStringGetData(buffer, &b); - - for (int32_t offset = 0; offset < len; ++offset) { - if (b[offset] == c) - return offset; - } - - return -1; -} - - -static void -StripChar(nsCString& buffer, char c) -{ - const char *b; - uint32_t len = NS_CStringGetData(buffer, &b) - 1; - - for (; len > 0; --len) { - if (b[len] == c) { - buffer.Cut(len, 1); - NS_CStringGetData(buffer, &b); - } - } -} - -nsresult LoadURLsFromFile(char *aFileName) -{ - nsresult rv = NS_OK; - int32_t len, offset; - PRFileDesc* fd; - char buffer[1024]; - nsCString fileBuffer; - nsCString urlString; - - fd = PR_Open(aFileName, PR_RDONLY, 777); - if (!fd) { - return NS_ERROR_FAILURE; - } - - // Keep reading the file until EOF (or an error) is reached... - do { - len = PR_Read(fd, buffer, sizeof(buffer)); - if (len>0) { - fileBuffer.Append(buffer, len); - // Treat each line as a URL... - while ((offset = FindChar(fileBuffer, '\n')) != -1) { - urlString = StringHead(fileBuffer, offset); - fileBuffer.Cut(0, offset+1); - - StripChar(urlString, '\r'); - if (urlString.Length()) { - LOG(("\t%s\n", urlString.get())); - rv = StartLoadingURL(urlString.get()); - if (NS_FAILED(rv)) { - // No need to log an error -- StartLoadingURL already - // did that for us, probably. - PR_Close(fd); - return rv; - } - } - } - } - } while (len>0); - - // If anything is left in the fileBuffer, treat it as a URL... - StripChar(fileBuffer, '\r'); - if (fileBuffer.Length()) { - LOG(("\t%s\n", fileBuffer.get())); - StartLoadingURL(fileBuffer.get()); - } - - PR_Close(fd); - return NS_OK; -} - - -nsresult LoadURLFromConsole() -{ - char buffer[1024]; - printf("Enter URL (\"q\" to start): "); - Unused << scanf("%s", buffer); - if (buffer[0]=='q') - gAskUserForInput = false; - else - StartLoadingURL(buffer); - return NS_OK; -} - -} // namespace TestProtocols - -using namespace TestProtocols; - -int -main(int argc, char* argv[]) -{ - if (test_common_init(&argc, &argv) != 0) - return -1; - - nsresult rv= (nsresult)-1; - if (argc < 2) { - printf("usage: %s [-verbose] [-file <name>] [-resume <startoffset>" - "[-entityid <entityid>]] [-proxy <proxy>] [-pac <pacURL>]" - "[-console] <url> <url> ... \n", argv[0]); - return -1; - } - - gTestLog = PR_NewLogModule("Test"); - - /* - The following code only deals with XPCOM registration stuff. and setting - up the event queues. Copied from TestSocketIO.cpp - */ - - rv = NS_InitXPCOM2(nullptr, nullptr, nullptr); - if (NS_FAILED(rv)) return -1; - - { - int i; - LOG(("Trying to load:\n")); - for (i=1; i<argc; i++) { - // Turn on verbose printing... - if (PL_strcasecmp(argv[i], "-verbose") == 0) { - gVerbose = true; - continue; - } - - // Turn on netlib tracing... - if (PL_strcasecmp(argv[i], "-file") == 0) { - LoadURLsFromFile(argv[++i]); - continue; - } - - if (PL_strcasecmp(argv[i], "-console") == 0) { - gAskUserForInput = true; - continue; - } - - if (PL_strcasecmp(argv[i], "-resume") == 0) { - gResume = true; - PR_sscanf(argv[++i], "%llu", &gStartAt); - continue; - } - - if (PL_strcasecmp(argv[i], "-entityid") == 0) { - gEntityID = argv[++i]; - continue; - } - - if (PL_strcasecmp(argv[i], "-proxy") == 0) { - SetHttpProxy(argv[++i]); - continue; - } - - if (PL_strcasecmp(argv[i], "-pac") == 0) { - SetPACFile(argv[++i]); - continue; - } - - LOG(("\t%s\n", argv[i])); - rv = StartLoadingURL(argv[i]); - } - // Enter the message pump to allow the URL load to proceed. - PumpEvents(); - } // this scopes the nsCOMPtrs - // no nsCOMPtrs are allowed to be alive when you call NS_ShutdownXPCOM - NS_ShutdownXPCOM(nullptr); - return NS_FAILED(rv) ? -1 : 0; -}
deleted file mode 100644 --- a/netwerk/test/TestServ.cpp +++ /dev/null @@ -1,146 +0,0 @@ -/* vim:set ts=4 sw=4 et cindent: */ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -#include "TestCommon.h" -#include <stdlib.h> -#include "nsIServiceManager.h" -#include "nsIServerSocket.h" -#include "nsISocketTransport.h" -#include "nsIInputStream.h" -#include "nsIOutputStream.h" -#include "nsNetCID.h" -#include "nsComponentManagerUtils.h" -#include "nsStringAPI.h" -#include "nsCOMPtr.h" -#include "NetwerkTestLogging.h" - -// -// set NSPR_LOG_MODULES=Test:5 -// -static PRLogModuleInfo *gTestLog = nullptr; -#define LOG(args) MOZ_LOG(gTestLog, mozilla::LogLevel::Debug, args) - -class MySocketListener : public nsIServerSocketListener -{ -protected: - virtual ~MySocketListener() {} - -public: - NS_DECL_THREADSAFE_ISUPPORTS - NS_DECL_NSISERVERSOCKETLISTENER - - MySocketListener() {} -}; - -NS_IMPL_ISUPPORTS(MySocketListener, nsIServerSocketListener) - -NS_IMETHODIMP -MySocketListener::OnSocketAccepted(nsIServerSocket *serv, - nsISocketTransport *trans) -{ - LOG(("MySocketListener::OnSocketAccepted [serv=%p trans=%p]\n", serv, trans)); - - nsAutoCString host; - int32_t port; - - trans->GetHost(host); - trans->GetPort(&port); - - LOG((" -> %s:%d\n", host.get(), port)); - - nsCOMPtr<nsIInputStream> input; - nsCOMPtr<nsIOutputStream> output; - nsresult rv; - - rv = trans->OpenInputStream(nsITransport::OPEN_BLOCKING, 0, 0, getter_AddRefs(input)); - if (NS_FAILED(rv)) - return rv; - - rv = trans->OpenOutputStream(nsITransport::OPEN_BLOCKING, 0, 0, getter_AddRefs(output)); - if (NS_FAILED(rv)) - return rv; - - char buf[256]; - uint32_t n; - - rv = input->Read(buf, sizeof(buf), &n); - if (NS_FAILED(rv)) - return rv; - - const char response[] = "HTTP/1.0 200 OK\r\nContent-Type: text/plain\r\n\r\nFooooopy!!\r\n"; - rv = output->Write(response, sizeof(response) - 1, &n); - if (NS_FAILED(rv)) - return rv; - - input->Close(); - output->Close(); - return NS_OK; -} - -NS_IMETHODIMP -MySocketListener::OnStopListening(nsIServerSocket *serv, nsresult status) -{ - LOG(("MySocketListener::OnStopListening [serv=%p status=%x]\n", serv, status)); - QuitPumpingEvents(); - return NS_OK; -} - -static nsresult -MakeServer(int32_t port) -{ - nsresult rv; - nsCOMPtr<nsIServerSocket> serv = do_CreateInstance(NS_SERVERSOCKET_CONTRACTID, &rv); - if (NS_FAILED(rv)) - return rv; - - rv = serv->Init(port, true, 5); - if (NS_FAILED(rv)) - return rv; - - rv = serv->GetPort(&port); - if (NS_FAILED(rv)) - return rv; - LOG((" listening on port %d\n", port)); - - rv = serv->AsyncListen(new MySocketListener()); - return rv; -} - -int -main(int argc, char* argv[]) -{ - if (test_common_init(&argc, &argv) != 0) - return -1; - - nsresult rv= (nsresult)-1; - if (argc < 2) { - printf("usage: %s <port>\n", argv[0]); - return -1; - } - - gTestLog = PR_NewLogModule("Test"); - - /* - * The following code only deals with XPCOM registration stuff. and setting - * up the event queues. Copied from TestSocketIO.cpp - */ - - rv = NS_InitXPCOM2(nullptr, nullptr, nullptr); - if (NS_FAILED(rv)) return -1; - - { - rv = MakeServer(atoi(argv[1])); - if (NS_FAILED(rv)) { - LOG(("MakeServer failed [rv=%x]\n", rv)); - return -1; - } - - // Enter the message pump to allow the URL load to proceed. - PumpEvents(); - } // this scopes the nsCOMPtrs - // no nsCOMPtrs are allowed to be alive when you call NS_ShutdownXPCOM - NS_ShutdownXPCOM(nullptr); - return 0; -}
deleted file mode 100644 --- a/netwerk/test/TestSocketTransport.cpp +++ /dev/null @@ -1,307 +0,0 @@ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -#include "TestCommon.h" -#include "nsIComponentRegistrar.h" -#include "nsPISocketTransportService.h" -#include "nsISocketTransport.h" -#include "nsIAsyncInputStream.h" -#include "nsIAsyncOutputStream.h" -#include "nsIProgressEventSink.h" -#include "nsIInterfaceRequestor.h" -#include "nsIInterfaceRequestorUtils.h" -#include "nsIRequest.h" -#include "nsIServiceManager.h" -#include "nsIComponentManager.h" -#include "nsCOMPtr.h" -#include "nsMemory.h" -#include "nsStringAPI.h" -#include "nsIDNSService.h" -#include "nsIFileStreams.h" -#include "nsIStreamListener.h" -#include "nsIFile.h" -#include "nsAutoLock.h" -#include "mozilla/Logging.h" - -//////////////////////////////////////////////////////////////////////////////// - -// -// set NSPR_LOG_MODULES=Test:5 -// -static PRLogModuleInfo *gTestLog = nullptr; -#define LOG(args) MOZ_LOG(gTestLog, mozilla::LogLevel::Debug, args) - -//////////////////////////////////////////////////////////////////////////////// - -static NS_DEFINE_CID(kSocketTransportServiceCID, NS_SOCKETTRANSPORTSERVICE_CID); - -//////////////////////////////////////////////////////////////////////////////// - -class MyHandler : public nsIOutputStreamCallback - , public nsIInputStreamCallback -{ -public: - NS_DECL_THREADSAFE_ISUPPORTS - - MyHandler(const char *path, - nsIAsyncInputStream *in, - nsIAsyncOutputStream *out) - : mInput(in) - , mOutput(out) - , mWriteOffset(0) - { - mBuf.AssignLiteral("GET "); - mBuf.Append(path); - mBuf.AppendLiteral(" HTTP/1.0\r\n\r\n"); - } - virtual ~MyHandler() {} - - // called on any thread - NS_IMETHOD OnOutputStreamReady(nsIAsyncOutputStream *out) - { - LOG(("OnOutputStreamReady\n")); - - nsresult rv; - uint32_t n, count = mBuf.Length() - mWriteOffset; - - rv = out->Write(mBuf.get() + mWriteOffset, count, &n); - - LOG((" write returned [rv=%x count=%u]\n", rv, n)); - - if (NS_FAILED(rv) || (n == 0)) { - if (rv != NS_BASE_STREAM_WOULD_BLOCK) { - LOG((" done writing; starting to read\n")); - mInput->AsyncWait(this, 0, 0, nullptr); - return NS_OK; - } - } - - mWriteOffset += n; - - return out->AsyncWait(this, 0, 0, nullptr); - } - - // called on any thread - NS_IMETHOD OnInputStreamReady(nsIAsyncInputStream *in) - { - LOG(("OnInputStreamReady\n")); - - nsresult rv; - uint32_t n; - char buf[500]; - - rv = in->Read(buf, sizeof(buf), &n); - - LOG((" read returned [rv=%x count=%u]\n", rv, n)); - - if (NS_FAILED(rv) || (n == 0)) { - if (rv != NS_BASE_STREAM_WOULD_BLOCK) { - QuitPumpingEvents(); - return NS_OK; - } - } - - return in->AsyncWait(this, 0, 0, nullptr); - } - -private: - nsCOMPtr<nsIAsyncInputStream> mInput; - nsCOMPtr<nsIAsyncOutputStream> mOutput; - nsCString mBuf; - uint32_t mWriteOffset; -}; - -NS_IMPL_ISUPPORTS(MyHandler, - nsIOutputStreamCallback, - nsIInputStreamCallback) - -//////////////////////////////////////////////////////////////////////////////// - -/** - * create transport, open streams, and close - */ -static nsresult -RunCloseTest(nsISocketTransportService *sts, - const char *host, int port, - uint32_t inFlags, uint32_t outFlags) -{ - nsresult rv; - - LOG(("RunCloseTest\n")); - - nsCOMPtr<nsISocketTransport> transport; - rv = sts->CreateTransport(nullptr, 0, - nsDependentCString(host), port, nullptr, - getter_AddRefs(transport)); - if (NS_FAILED(rv)) return rv; - - nsCOMPtr<nsIInputStream> in; - rv = transport->OpenInputStream(inFlags, 0, 0, getter_AddRefs(in)); - nsCOMPtr<nsIAsyncInputStream> asyncIn = do_QueryInterface(in, &rv); - if (NS_FAILED(rv)) return rv; - - nsCOMPtr<nsIOutputStream> out; - rv = transport->OpenOutputStream(outFlags, 0, 0, getter_AddRefs(out)); - nsCOMPtr<nsIAsyncOutputStream> asyncOut = do_QueryInterface(out, &rv); - if (NS_FAILED(rv)) return rv; - - LOG(("waiting 1 second before closing transport and streams...\n")); - PR_Sleep(PR_SecondsToInterval(1)); - - // let nsCOMPtr destructors close everything... - return NS_OK; -} - - -/** - * asynchronously read socket stream - */ -static nsresult -RunTest(nsISocketTransportService *sts, - const char *host, int port, const char *path, - uint32_t inFlags, uint32_t outFlags) -{ - nsresult rv; - - LOG(("RunTest\n")); - - nsCOMPtr<nsISocketTransport> transport; - rv = sts->CreateTransport(nullptr, 0, - nsDependentCString(host), port, nullptr, - getter_AddRefs(transport)); - if (NS_FAILED(rv)) return rv; - - nsCOMPtr<nsIInputStream> in; - rv = transport->OpenInputStream(inFlags, 0, 0, getter_AddRefs(in)); - nsCOMPtr<nsIAsyncInputStream> asyncIn = do_QueryInterface(in, &rv); - if (NS_FAILED(rv)) return rv; - - nsCOMPtr<nsIOutputStream> out; - rv = transport->OpenOutputStream(outFlags, 0, 0, getter_AddRefs(out)); - nsCOMPtr<nsIAsyncOutputStream> asyncOut = do_QueryInterface(out, &rv); - if (NS_FAILED(rv)) return rv; - - MyHandler *handler = new MyHandler(path, asyncIn, asyncOut); - if (handler == nullptr) - return NS_ERROR_OUT_OF_MEMORY; - NS_ADDREF(handler); - - rv = asyncOut->AsyncWait(handler, 0, 0, nullptr); - - if (NS_SUCCEEDED(rv)) - PumpEvents(); - - NS_RELEASE(handler); - - return NS_OK; -} - -//////////////////////////////////////////////////////////////////////////////// - -int -main(int argc, char* argv[]) -{ - if (test_common_init(&argc, &argv) != 0) - return -1; - - nsresult rv; - - if (argc < 4) { - printf("usage: TestSocketTransport <host> <port> <path>\n"); - return -1; - } - - { - nsCOMPtr<nsIServiceManager> servMan; - NS_InitXPCOM2(getter_AddRefs(servMan), nullptr, nullptr); - nsCOMPtr<nsIComponentRegistrar> registrar = do_QueryInterface(servMan); - NS_ASSERTION(registrar, "Null nsIComponentRegistrar"); - if (registrar) - registrar->AutoRegister(nullptr); - - gTestLog = PR_NewLogModule("Test"); - - // Make sure the DNS service is initialized on the main thread - nsCOMPtr<nsIDNSService> dns = - do_GetService(NS_DNSSERVICE_CONTRACTID, &rv); - if (NS_FAILED(rv)) return rv; - - nsCOMPtr<nsPISocketTransportService> sts = - do_GetService(kSocketTransportServiceCID, &rv); - if (NS_FAILED(rv)) return rv; - - LOG(("phase 1 tests...\n")); - - LOG(("flags = { OPEN_UNBUFFERED, OPEN_UNBUFFERED }\n")); - rv = RunCloseTest(sts, argv[1], atoi(argv[2]), - nsITransport::OPEN_UNBUFFERED, - nsITransport::OPEN_UNBUFFERED); - NS_ASSERTION(NS_SUCCEEDED(rv), "RunCloseTest failed"); - - LOG(("flags = { OPEN_BUFFERED, OPEN_UNBUFFERED }\n")); - rv = RunCloseTest(sts, argv[1], atoi(argv[2]), - 0 /* nsITransport::OPEN_BUFFERED */, - nsITransport::OPEN_UNBUFFERED); - NS_ASSERTION(NS_SUCCEEDED(rv), "RunCloseTest failed"); - - LOG(("flags = { OPEN_UNBUFFERED, OPEN_BUFFERED }\n")); - rv = RunCloseTest(sts, argv[1], atoi(argv[2]), - nsITransport::OPEN_UNBUFFERED, - 0 /*nsITransport::OPEN_BUFFERED */); - NS_ASSERTION(NS_SUCCEEDED(rv), "RunCloseTest failed"); - - LOG(("flags = { OPEN_BUFFERED, OPEN_BUFFERED }\n")); - rv = RunCloseTest(sts, argv[1], atoi(argv[2]), - 0 /*nsITransport::OPEN_BUFFERED */, - 0 /*nsITransport::OPEN_BUFFERED */); - NS_ASSERTION(NS_SUCCEEDED(rv), "RunCloseTest failed"); - - LOG(("calling Shutdown on socket transport service:\n")); - sts->Shutdown(); - - LOG(("calling Init on socket transport service:\n")); - sts->Init(); - - LOG(("phase 2 tests...\n")); - - LOG(("flags = { OPEN_UNBUFFERED, OPEN_UNBUFFERED }\n")); - rv = RunTest(sts, argv[1], atoi(argv[2]), argv[3], - nsITransport::OPEN_UNBUFFERED, - nsITransport::OPEN_UNBUFFERED); - NS_ASSERTION(NS_SUCCEEDED(rv), "RunTest failed"); - - LOG(("flags = { OPEN_BUFFERED, OPEN_UNBUFFERED }\n")); - rv = RunTest(sts, argv[1], atoi(argv[2]), argv[3], - 0 /* nsITransport::OPEN_BUFFERED */, - nsITransport::OPEN_UNBUFFERED); - NS_ASSERTION(NS_SUCCEEDED(rv), "RunTest failed"); - - LOG(("flags = { OPEN_UNBUFFERED, OPEN_BUFFERED }\n")); - rv = RunTest(sts, argv[1], atoi(argv[2]), argv[3], - nsITransport::OPEN_UNBUFFERED, - 0 /*nsITransport::OPEN_BUFFERED */); - NS_ASSERTION(NS_SUCCEEDED(rv), "RunTest failed"); - - LOG(("flags = { OPEN_BUFFERED, OPEN_BUFFERED }\n")); - rv = RunTest(sts, argv[1], atoi(argv[2]), argv[3], - 0 /*nsITransport::OPEN_BUFFERED */, - 0 /*nsITransport::OPEN_BUFFERED */); - NS_ASSERTION(NS_SUCCEEDED(rv), "RunTest failed"); - - LOG(("waiting 1 second before calling Shutdown...\n")); - PR_Sleep(PR_SecondsToInterval(1)); - - LOG(("calling Shutdown on socket transport service:\n")); - sts->Shutdown(); - - // give background threads a chance to finish whatever work they may - // be doing. - LOG(("waiting 1 second before exiting...\n")); - PR_Sleep(PR_SecondsToInterval(1)); - } // this scopes the nsCOMPtrs - // no nsCOMPtrs are allowed to be alive when you call NS_ShutdownXPCOM - rv = NS_ShutdownXPCOM(nullptr); - NS_ASSERTION(NS_SUCCEEDED(rv), "NS_ShutdownXPCOM failed"); - return 0; -}
deleted file mode 100644 --- a/netwerk/test/TestStreamLoader.cpp +++ /dev/null @@ -1,101 +0,0 @@ -#include <stdio.h> -#include "TestCommon.h" -#include "nsNetUtil.h" -#include "nsServiceManagerUtils.h" -#include "nsThreadUtils.h" -#include "NetwerkTestLogging.h" -#include "mozilla/Attributes.h" -#include "nsIScriptSecurityManager.h" - -// -// set NSPR_LOG_MODULES=Test:5 -// -static PRLogModuleInfo *gTestLog = nullptr; -#define LOG(args) MOZ_LOG(gTestLog, mozilla::LogLevel::Debug, args) - -class MyStreamLoaderObserver final : public nsIStreamLoaderObserver -{ - ~MyStreamLoaderObserver() {} - -public: - NS_DECL_ISUPPORTS - NS_DECL_NSISTREAMLOADEROBSERVER -}; - -NS_IMPL_ISUPPORTS(MyStreamLoaderObserver, nsIStreamLoaderObserver) - -NS_IMETHODIMP -MyStreamLoaderObserver::OnStreamComplete(nsIStreamLoader *loader, - nsISupports *ctxt, - nsresult status, - uint32_t resultLen, - const uint8_t *result) -{ - LOG(("OnStreamComplete [status=%x resultLen=%u]\n", status, resultLen)); - - nsCOMPtr<nsIRequest> request; - loader->GetRequest(getter_AddRefs(request)); - LOG((" request=%p\n", request.get())); - - QuitPumpingEvents(); - return NS_OK; -} - -int main(int argc, char **argv) -{ - if (test_common_init(&argc, &argv) != 0) - return -1; - - if (argc < 2) { - printf("usage: %s <url>\n", argv[0]); - return -1; - } - - gTestLog = PR_NewLogModule("Test"); - - nsresult rv = NS_InitXPCOM2(nullptr, nullptr, nullptr); - if (NS_FAILED(rv)) - return -1; - - { - nsCOMPtr<nsIURI> uri; - rv = NS_NewURI(getter_AddRefs(uri), nsDependentCString(argv[1])); - if (NS_FAILED(rv)) - return -1; - - nsCOMPtr<nsIScriptSecurityManager> secman = - do_GetService(NS_SCRIPTSECURITYMANAGER_CONTRACTID, &rv); - NS_ENSURE_SUCCESS(rv, -1); - nsCOMPtr<nsIPrincipal> systemPrincipal; - rv = secman->GetSystemPrincipal(getter_AddRefs(systemPrincipal)); - NS_ENSURE_SUCCESS(rv, -1); - - nsCOMPtr<nsIChannel> chan; - rv = NS_NewChannel(getter_AddRefs(chan), - uri, - systemPrincipal, - nsILoadInfo::SEC_ALLOW_CROSS_ORIGIN_DATA_INHERITS, - nsIContentPolicy::TYPE_OTHER); - - if (NS_FAILED(rv)) - return -1; - - nsCOMPtr<nsIStreamLoaderObserver> observer = new MyStreamLoaderObserver(); - if (!observer) - return -1; - - nsCOMPtr<nsIStreamLoader> loader; - rv = NS_NewStreamLoader(getter_AddRefs(loader), observer); - if (NS_FAILED(rv)) - return -1; - - rv = chan->AsyncOpen2(loader); - if (NS_FAILED(rv)) - return -1; - - PumpEvents(); - } // this scopes the nsCOMPtrs - // no nsCOMPtrs are allowed to be alive when you call NS_ShutdownXPCOM - NS_ShutdownXPCOM(nullptr); - return 0; -}
deleted file mode 100644 --- a/netwerk/test/TestStreamPump.cpp +++ /dev/null @@ -1,171 +0,0 @@ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -#include "TestCommon.h" -#include "nsIComponentRegistrar.h" -#include "nsIStreamTransportService.h" -#include "nsIAsyncInputStream.h" -#include "nsIProgressEventSink.h" -#include "nsIInterfaceRequestor.h" -#include "nsIInterfaceRequestorUtils.h" -#include "nsIRequest.h" -#include "nsIServiceManager.h" -#include "nsIComponentManager.h" -#include "nsISeekableStream.h" -#include "nsCOMPtr.h" -#include "nsMemory.h" -#include "nsStringAPI.h" -#include "nsIFileStreams.h" -#include "nsIStreamListener.h" -#include "nsIFile.h" -#include "nsNetUtil.h" -#include "nsAutoLock.h" -#include "mozilla/Logging.h" -#include "prprf.h" -#include <algorithm> - -//////////////////////////////////////////////////////////////////////////////// - -// -// set NSPR_LOG_MODULES=Test:5 -// -static PRLogModuleInfo *gTestLog = nullptr; -#define LOG(args) MOZ_LOG(gTestLog, mozilla::LogLevel::Debug, args) - -//////////////////////////////////////////////////////////////////////////////// - -class MyListener : public nsIStreamListener -{ -public: - NS_DECL_ISUPPORTS - - MyListener() {} - virtual ~MyListener() {} - - NS_IMETHOD OnStartRequest(nsIRequest *req, nsISupports *ctx) - { - LOG(("MyListener::OnStartRequest\n")); - return NS_OK; - } - - NS_IMETHOD OnDataAvailable(nsIRequest *req, nsISupports *ctx, - nsIInputStream *stream, - uint64_t offset, uint32_t count) - { - LOG(("MyListener::OnDataAvailable [offset=%llu count=%u]\n", offset, count)); - - char buf[500]; - nsresult rv; - - while (count) { - uint32_t n, amt = std::min<uint32_t>(count, sizeof(buf)); - - rv = stream->Read(buf, amt, &n); - if (NS_FAILED(rv)) { - LOG((" read returned 0x%08x\n", rv)); - return rv; - } - - fwrite(buf, n, 1, stdout); - printf("\n"); - - LOG((" read %u bytes\n", n)); - count -= n; - } - - return NS_OK; - } - - NS_IMETHOD OnStopRequest(nsIRequest *req, nsISupports *ctx, nsresult status) - { - LOG(("MyListener::OnStopRequest [status=%x]\n", status)); - QuitPumpingEvents(); - return NS_OK; - } -}; - -NS_IMPL_ISUPPORTS(MyListener, - nsIRequestObserver, - nsIStreamListener) - -//////////////////////////////////////////////////////////////////////////////// - -/** - * asynchronously copy file. - */ -static nsresult -RunTest(nsIFile *file, int64_t offset, int64_t length) -{ - nsresult rv; - - LOG(("RunTest\n")); - - nsCOMPtr<nsIInputStream> stream; - rv = NS_NewLocalFileInputStream(getter_AddRefs(stream), file); - if (NS_FAILED(rv)) return rv; - - nsCOMPtr<nsIInputStreamPump> pump; - rv = NS_NewInputStreamPump(getter_AddRefs(pump), stream, offset, length); - if (NS_FAILED(rv)) return rv; - - rv = pump->AsyncRead(new MyListener(), nullptr); - if (NS_FAILED(rv)) return rv; - - PumpEvents(); - return NS_OK; -} - -//////////////////////////////////////////////////////////////////////////////// - -int -main(int argc, char* argv[]) -{ - if (test_common_init(&argc, &argv) != 0) - return -1; - - nsresult rv; - - if (argc < 4) { - printf("usage: %s <file-to-read> <start-offset> <read-length>\n", argv[0]); - return -1; - } - char* fileName = argv[1]; - int64_t offset, length; - int err = PR_sscanf(argv[2], "%lld", &offset); - if (err == -1) { - printf("Start offset must be an integer!\n"); - return 1; - } - err = PR_sscanf(argv[3], "%lld", &length); - if (err == -1) { - printf("Length must be an integer!\n"); - return 1; - } - - { - nsCOMPtr<nsIServiceManager> servMan; - NS_InitXPCOM2(getter_AddRefs(servMan), nullptr, nullptr); - nsCOMPtr<nsIComponentRegistrar> registrar = do_QueryInterface(servMan); - NS_ASSERTION(registrar, "Null nsIComponentRegistrar"); - if (registrar) - registrar->AutoRegister(nullptr); - - gTestLog = PR_NewLogModule("Test"); - - nsCOMPtr<nsIFile> file; - rv = NS_NewNativeLocalFile(nsDependentCString(fileName), false, getter_AddRefs(file)); - if (NS_FAILED(rv)) return rv; - - rv = RunTest(file, offset, length); - NS_ASSERTION(NS_SUCCEEDED(rv), "RunTest failed"); - - // give background threads a chance to finish whatever work they may - // be doing. - PR_Sleep(PR_SecondsToInterval(1)); - } // this scopes the nsCOMPtrs - // no nsCOMPtrs are allowed to be alive when you call NS_ShutdownXPCOM - rv = NS_ShutdownXPCOM(nullptr); - NS_ASSERTION(NS_SUCCEEDED(rv), "NS_ShutdownXPCOM failed"); - return NS_OK; -}
deleted file mode 100644 --- a/netwerk/test/TestStreamTransport.cpp +++ /dev/null @@ -1,319 +0,0 @@ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -#include "TestCommon.h" -#include "nsIComponentRegistrar.h" -#include "nsIStreamTransportService.h" -#include "nsIAsyncInputStream.h" -#include "nsIProgressEventSink.h" -#include "nsIInterfaceRequestor.h" -#include "nsIInterfaceRequestorUtils.h" -#include "nsIRequest.h" -#include "nsIServiceManager.h" -#include "nsIComponentManager.h" -#include "nsCOMPtr.h" -#include "nsMemory.h" -#include "nsStringAPI.h" -#include "nsIFileStreams.h" -#include "nsIStreamListener.h" -#include "nsIFile.h" -#include "nsNetUtil.h" -#include "nsAutoLock.h" -#include "mozilla/Logging.h" -#include "prenv.h" - -//////////////////////////////////////////////////////////////////////////////// - -// -// set NSPR_LOG_MODULES=Test:5 -// -static PRLogModuleInfo *gTestLog = nullptr; -#define LOG(args) MOZ_LOG(gTestLog, mozilla::LogLevel::Debug, args) - -//////////////////////////////////////////////////////////////////////////////// - -static NS_DEFINE_CID(kStreamTransportServiceCID, NS_STREAMTRANSPORTSERVICE_CID); - -//////////////////////////////////////////////////////////////////////////////// - -#define CHUNK_SIZE 500 - -class MyCopier : public nsIInputStreamCallback - , public nsIOutputStreamCallback -{ -public: - NS_DECL_THREADSAFE_ISUPPORTS - - MyCopier() - : mLock(nullptr) - , mInputCondition(NS_OK) - { - } - - virtual ~MyCopier() - { - if (mLock) - nsAutoLock::DestroyLock(mLock); - if (mInput) - mInput->Close(); - if (mOutput) - mOutput->Close(); - } - - // called on any thread - NS_IMETHOD OnInputStreamReady(nsIAsyncInputStream *inStr) - { - LOG(("OnInputStreamReady\n")); - nsAutoLock lock(mLock); - NS_ASSERTION(inStr == mInput, "unexpected stream"); - Process_Locked(); - return NS_OK; - } - - // called on any thread - NS_IMETHOD OnOutputStreamReady(nsIAsyncOutputStream *outStr) - { - LOG(("OnOutputStreamReady\n")); - nsAutoLock lock(mLock); - NS_ASSERTION(outStr == mOutput, "unexpected stream"); - Process_Locked(); - return NS_OK; - } - - void Close_Locked() - { - LOG(("Close_Locked\n")); - - mOutput->Close(); - mOutput = 0; - mInput->Close(); - mInput = 0; - - // post done copying event - QuitPumpingEvents(); - } - - void Process_Locked() - { - while (1) { - mInputCondition = NS_OK; // reset - - uint32_t n; - nsresult rv = mOutput->WriteSegments(FillOutputBuffer, this, CHUNK_SIZE, &n); - if (NS_FAILED(rv) || (n == 0)) { - if (rv == NS_BASE_STREAM_WOULD_BLOCK) - mOutput->AsyncWait(this, 0, 0, nullptr); - else if (mInputCondition == NS_BASE_STREAM_WOULD_BLOCK) - mInput->AsyncWait(this, 0, 0, nullptr); - else - Close_Locked(); - break; - } - } - } - - nsresult AsyncCopy(nsITransport *srcTrans, nsITransport *destTrans) - { - mLock = nsAutoLock::NewLock("MyCopier::mLock"); - if (!mLock) - return NS_ERROR_OUT_OF_MEMORY; - - nsresult rv; - - nsCOMPtr<nsIInputStream> inStr; - rv = srcTrans->OpenInputStream(0, 0, 0, getter_AddRefs(inStr)); - if (NS_FAILED(rv)) return rv; - - nsCOMPtr<nsIOutputStream> outStr; - rv = destTrans->OpenOutputStream(0, 0, 0, getter_AddRefs(outStr)); - if (NS_FAILED(rv)) return rv; - - mInput = do_QueryInterface(inStr); - mOutput = do_QueryInterface(outStr); - - return mInput->AsyncWait(this, 0, 0, nullptr); - } - - static nsresult FillOutputBuffer(nsIOutputStream *outStr, - void *closure, - char *buffer, - uint32_t offset, - uint32_t count, - uint32_t *countRead) - { - MyCopier *self = (MyCopier *) closure; - - nsresult rv = self->mInput->Read(buffer, count, countRead); - if (NS_FAILED(rv)) - self->mInputCondition = rv; - else if (*countRead == 0) - self->mInputCondition = NS_BASE_STREAM_CLOSED; - - return self->mInputCondition; - } - -protected: - PRLock *mLock; - nsCOMPtr<nsIAsyncInputStream> mInput; - nsCOMPtr<nsIAsyncOutputStream> mOutput; - nsresult mInputCondition; -}; - -NS_IMPL_ISUPPORTS(MyCopier, - nsIInputStreamCallback, - nsIOutputStreamCallback) - -//////////////////////////////////////////////////////////////////////////////// - -/** - * asynchronously copy file. - */ -static nsresult -RunTest(nsIFile *srcFile, nsIFile *destFile) -{ - nsresult rv; - - LOG(("RunTest\n")); - - nsCOMPtr<nsIStreamTransportService> sts = - do_GetService(kStreamTransportServiceCID, &rv); - if (NS_FAILED(rv)) return rv; - - nsCOMPtr<nsIInputStream> srcStr; - rv = NS_NewLocalFileInputStream(getter_AddRefs(srcStr), srcFile); - if (NS_FAILED(rv)) return rv; - - nsCOMPtr<nsIOutputStream> destStr; - rv = NS_NewLocalFileOutputStream(getter_AddRefs(destStr), destFile); - if (NS_FAILED(rv)) return rv; - - nsCOMPtr<nsITransport> srcTransport; - rv = sts->CreateInputTransport(srcStr, int64_t(-1), int64_t(-1), true, - getter_AddRefs(srcTransport)); - if (NS_FAILED(rv)) return rv; - - nsCOMPtr<nsITransport> destTransport; - rv = sts->CreateOutputTransport(destStr, int64_t(-1), int64_t(-1), true, - getter_AddRefs(destTransport)); - if (NS_FAILED(rv)) return rv; - - MyCopier *copier = new MyCopier(); - if (copier == nullptr) - return NS_ERROR_OUT_OF_MEMORY; - NS_ADDREF(copier); - - rv = copier->AsyncCopy(srcTransport, destTransport); - if (NS_FAILED(rv)) return rv; - - PumpEvents(); - - NS_RELEASE(copier); - return NS_OK; -} - -//////////////////////////////////////////////////////////////////////////////// - -static nsresult -RunBlockingTest(nsIFile *srcFile, nsIFile *destFile) -{ - nsresult rv; - - LOG(("RunBlockingTest\n")); - - nsCOMPtr<nsIStreamTransportService> sts = - do_GetService(kStreamTransportServiceCID, &rv); - if (NS_FAILED(rv)) return rv; - - nsCOMPtr<nsIInputStream> srcIn; - rv = NS_NewLocalFileInputStream(getter_AddRefs(srcIn), srcFile); - if (NS_FAILED(rv)) return rv; - - nsCOMPtr<nsIOutputStream> fileOut; - rv = NS_NewLocalFileOutputStream(getter_AddRefs(fileOut), destFile); - if (NS_FAILED(rv)) return rv; - - nsCOMPtr<nsITransport> destTransport; - rv = sts->CreateOutputTransport(fileOut, int64_t(-1), int64_t(-1), - true, getter_AddRefs(destTransport)); - if (NS_FAILED(rv)) return rv; - - nsCOMPtr<nsIOutputStream> destOut; - rv = destTransport->OpenOutputStream(nsITransport::OPEN_BLOCKING, 100, 10, getter_AddRefs(destOut)); - if (NS_FAILED(rv)) return rv; - - char buf[120]; - uint32_t n; - for (;;) { - rv = srcIn->Read(buf, sizeof(buf), &n); - if (NS_FAILED(rv) || (n == 0)) return rv; - - rv = destOut->Write(buf, n, &n); - if (NS_FAILED(rv)) return rv; - } - - return NS_OK; -} - -//////////////////////////////////////////////////////////////////////////////// - -int -main(int argc, char* argv[]) -{ - if (test_common_init(&argc, &argv) != 0) - return -1; - - nsresult rv; - - if (argc < 2) { - printf("usage: %s <file-to-read>\n", argv[0]); - return -1; - } - char* fileName = argv[1]; - { - nsCOMPtr<nsIServiceManager> servMan; - NS_InitXPCOM2(getter_AddRefs(servMan), nullptr, nullptr); - nsCOMPtr<nsIComponentRegistrar> registrar = do_QueryInterface(servMan); - NS_ASSERTION(registrar, "Null nsIComponentRegistrar"); - if (registrar) - registrar->AutoRegister(nullptr); - - gTestLog = PR_NewLogModule("Test"); - - nsCOMPtr<nsIFile> srcFile; - rv = NS_NewNativeLocalFile(nsDependentCString(fileName), false, getter_AddRefs(srcFile)); - if (NS_FAILED(rv)) return rv; - - nsCOMPtr<nsIFile> destFile; - rv = srcFile->Clone(getter_AddRefs(destFile)); - if (NS_FAILED(rv)) return rv; - - nsAutoCString leafName; - rv = destFile->GetNativeLeafName(leafName); - if (NS_FAILED(rv)) return rv; - - nsAutoCString newName(leafName); - newName.AppendLiteral(".1"); - rv = destFile->SetNativeLeafName(newName); - if (NS_FAILED(rv)) return rv; - - rv = RunTest(srcFile, destFile); - NS_ASSERTION(NS_SUCCEEDED(rv), "RunTest failed"); - - newName = leafName; - newName.AppendLiteral(".2"); - rv = destFile->SetNativeLeafName(newName); - if (NS_FAILED(rv)) return rv; - - rv = RunBlockingTest(srcFile, destFile); - NS_ASSERTION(NS_SUCCEEDED(rv), "RunBlockingTest failed"); - - // give background threads a chance to finish whatever work they may - // be doing. - PR_Sleep(PR_SecondsToInterval(1)); - } // this scopes the nsCOMPtrs - // no nsCOMPtrs are allowed to be alive when you call NS_ShutdownXPCOM - rv = NS_ShutdownXPCOM(nullptr); - NS_ASSERTION(NS_SUCCEEDED(rv), "NS_ShutdownXPCOM failed"); - return NS_OK; -}
--- a/netwerk/test/TestUDPSocket.cpp +++ b/netwerk/test/TestUDPSocket.cpp @@ -1,14 +1,14 @@ /* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #include "TestCommon.h" -#include "TestHarness.h" +#include "gtest/gtest.h" #include "nsIUDPSocket.h" #include "nsISocketTransportService.h" #include "nsISocketTransport.h" #include "nsIOutputStream.h" #include "nsIInputStream.h" #include "nsINetAddr.h" #include "nsIScriptSecurityManager.h" #include "nsITimer.h" @@ -17,41 +17,16 @@ #include "mozilla/WindowsVersion.h" #endif #include "prerror.h" #define REQUEST 0x68656c6f #define RESPONSE 0x6f6c6568 #define MULTICAST_TIMEOUT 2000 -#define EXPECT_SUCCESS(rv, ...) \ - PR_BEGIN_MACRO \ - if (NS_FAILED(rv)) { \ - fail(__VA_ARGS__); \ - return false; \ - } \ - PR_END_MACRO - - -#define EXPECT_FAILURE(rv, ...) \ - PR_BEGIN_MACRO \ - if (NS_SUCCEEDED(rv)) { \ - fail(__VA_ARGS__); \ - return false; \ - } \ - PR_END_MACRO - -#define REQUIRE_EQUAL(a, b, ...) \ - PR_BEGIN_MACRO \ - if (a != b) { \ - fail(__VA_ARGS__); \ - return false; \ - } \ - PR_END_MACRO - enum TestPhase { TEST_OUTPUT_STREAM, TEST_SEND_API, TEST_MULTICAST, TEST_NONE }; static TestPhase phase = TEST_NONE; @@ -63,38 +38,37 @@ static bool CheckMessageContent(nsIUDPMe const char* buffer = data.get(); uint32_t len = data.Length(); FallibleTArray<uint8_t>& rawData = aMessage->GetDataAsTArray(); uint32_t rawLen = rawData.Length(); if (len != rawLen) { - fail("Raw data length(%d) do not matches String data length(%d).", rawLen, len); return false; } for (uint32_t i = 0; i < len; i++) { if (buffer[i] != rawData[i]) { - fail("Raw data(%s) do not matches String data(%s)", rawData.Elements() ,buffer); + ADD_FAILURE(); return false; } } uint32_t input = 0; for (uint32_t i = 0; i < len; i++) { input += buffer[i] << (8 * i); } if (len != sizeof(uint32_t) || input != aExpectedContent) { - fail("Request 0x%x received, expected 0x%x", input, aExpectedContent); + ADD_FAILURE(); return false; } else { - passed("Request 0x%x received as expected", input); + SUCCEED(); return true; } } /* * UDPClientListener: listens for incomming UDP packets */ class UDPClientListener : public nsIUDPSocketListener @@ -120,28 +94,26 @@ UDPClientListener::OnPacketReceived(nsIU mResult = NS_OK; uint16_t port; nsCString ip; nsCOMPtr<nsINetAddr> fromAddr; message->GetFromAddr(getter_AddRefs(fromAddr)); fromAddr->GetPort(&port); fromAddr->GetAddress(ip); - passed("Packet received on client from %s:%d", ip.get(), port); if (TEST_SEND_API == phase && CheckMessageContent(message, REQUEST)) { uint32_t count; const uint32_t data = RESPONSE; - printf("*** Attempting to write response 0x%x to server by SendWithAddr...\n", RESPONSE); mResult = socket->SendWithAddr(fromAddr, (const uint8_t*)&data, sizeof(uint32_t), &count); if (mResult == NS_OK && count == sizeof(uint32_t)) { - passed("Response written"); + SUCCEED(); } else { - fail("Response written"); + ADD_FAILURE(); } return NS_OK; } else if (TEST_OUTPUT_STREAM != phase || !CheckMessageContent(message, RESPONSE)) { mResult = NS_ERROR_FAILURE; } // Notify thread QuitPumpingEvents(); @@ -182,32 +154,31 @@ UDPServerListener::OnPacketReceived(nsIU mResult = NS_OK; uint16_t port; nsCString ip; nsCOMPtr<nsINetAddr> fromAddr; message->GetFromAddr(getter_AddRefs(fromAddr)); fromAddr->GetPort(&port); fromAddr->GetAddress(ip); - passed("Packet received on server from %s:%d", ip.get(), port); + SUCCEED(); if (TEST_OUTPUT_STREAM == phase && CheckMessageContent(message, REQUEST)) { nsCOMPtr<nsIOutputStream> outstream; message->GetOutputStream(getter_AddRefs(outstream)); uint32_t count; const uint32_t data = RESPONSE; - printf("*** Attempting to write response 0x%x to client by OutputStream...\n", RESPONSE); mResult = outstream->Write((const char*)&data, sizeof(uint32_t), &count); if (mResult == NS_OK && count == sizeof(uint32_t)) { - passed("Response written"); + SUCCEED(); } else { - fail("Response written"); + ADD_FAILURE(); } return NS_OK; } else if (TEST_MULTICAST == phase && CheckMessageContent(message, REQUEST)) { mResult = NS_OK; } else if (TEST_SEND_API != phase || !CheckMessageContent(message, RESPONSE)) { mResult = NS_ERROR_FAILURE; } @@ -253,96 +224,90 @@ MulticastTimerCallback::Notify(nsITimer* // Multicast ping failed printf("Multicast ping timeout expired\n"); mResult = NS_ERROR_FAILURE; QuitPumpingEvents(); return NS_OK; } /**** Main ****/ -int -main(int32_t argc, char *argv[]) + +TEST(TestUDPSocket, TestUDPSocketMain) { nsresult rv; - ScopedXPCOM xpcom("UDP ServerSocket"); - if (xpcom.failed()) - return -1; // Create UDPSocket nsCOMPtr<nsIUDPSocket> server, client; server = do_CreateInstance("@mozilla.org/network/udp-socket;1", &rv); - NS_ENSURE_SUCCESS(rv, -1); + ASSERT_TRUE(NS_SUCCEEDED(rv)); + client = do_CreateInstance("@mozilla.org/network/udp-socket;1", &rv); - NS_ENSURE_SUCCESS(rv, -1); + ASSERT_TRUE(NS_SUCCEEDED(rv)); // Create UDPServerListener to process UDP packets RefPtr<UDPServerListener> serverListener = new UDPServerListener(); nsCOMPtr<nsIScriptSecurityManager> secman = do_GetService(NS_SCRIPTSECURITYMANAGER_CONTRACTID, &rv); - NS_ENSURE_SUCCESS(rv, -1); + ASSERT_TRUE(NS_SUCCEEDED(rv)); nsCOMPtr<nsIPrincipal> systemPrincipal; rv = secman->GetSystemPrincipal(getter_AddRefs(systemPrincipal)); - NS_ENSURE_SUCCESS(rv, -1); + ASSERT_TRUE(NS_SUCCEEDED(rv)); // Bind server socket to 0.0.0.0 rv = server->Init(0, false, systemPrincipal, true, 0); - NS_ENSURE_SUCCESS(rv, -1); + ASSERT_TRUE(NS_SUCCEEDED(rv)); int32_t serverPort; server->GetPort(&serverPort); server->AsyncListen(serverListener); // Bind clinet on arbitrary port RefPtr<UDPClientListener> clientListener = new UDPClientListener(); client->Init(0, false, systemPrincipal, true, 0); client->AsyncListen(clientListener); // Write data to server uint32_t count; const uint32_t data = REQUEST; phase = TEST_OUTPUT_STREAM; rv = client->Send(NS_LITERAL_CSTRING("127.0.0.1"), serverPort, (uint8_t*)&data, sizeof(uint32_t), &count); - NS_ENSURE_SUCCESS(rv, -1); - REQUIRE_EQUAL(count, sizeof(uint32_t), "Error"); - passed("Request written by Send"); + ASSERT_TRUE(NS_SUCCEEDED(rv)); + EXPECT_EQ(count, sizeof(uint32_t)); // Wait for server PumpEvents(); - NS_ENSURE_SUCCESS(serverListener->mResult, -1); + ASSERT_TRUE(NS_SUCCEEDED(serverListener->mResult)); // Read response from server - NS_ENSURE_SUCCESS(clientListener->mResult, -1); + ASSERT_TRUE(NS_SUCCEEDED(clientListener->mResult)); mozilla::net::NetAddr clientAddr; rv = client->GetAddress(&clientAddr); - NS_ENSURE_SUCCESS(rv, -1); + ASSERT_TRUE(NS_SUCCEEDED(rv)); // The client address is 0.0.0.0, but Windows won't receive packets there, so // use 127.0.0.1 explicitly clientAddr.inet.ip = PR_htonl(127 << 24 | 1); phase = TEST_SEND_API; rv = server->SendWithAddress(&clientAddr, (uint8_t*)&data, sizeof(uint32_t), &count); - NS_ENSURE_SUCCESS(rv, -1); - REQUIRE_EQUAL(count, sizeof(uint32_t), "Error"); - passed("Request written by SendWithAddress"); + ASSERT_TRUE(NS_SUCCEEDED(rv)); + EXPECT_EQ(count, sizeof(uint32_t)); // Wait for server PumpEvents(); - NS_ENSURE_SUCCESS(serverListener->mResult, -1); + ASSERT_TRUE(NS_SUCCEEDED(serverListener->mResult)); // Read response from server - NS_ENSURE_SUCCESS(clientListener->mResult, -1); + ASSERT_TRUE(NS_SUCCEEDED(clientListener->mResult)); // Setup timer to detect multicast failure nsCOMPtr<nsITimer> timer = do_CreateInstance("@mozilla.org/timer;1"); - if (NS_WARN_IF(!timer)) { - return -1; - } + ASSERT_TRUE(timer); RefPtr<MulticastTimerCallback> timerCb = new MulticastTimerCallback(); // The following multicast tests using multiple sockets require a firewall // exception on Windows XP (the earliest version of Windows we now support) // before they pass. For now, we'll skip them here. Later versions of Windows // (Win2003 and onward) don't seem to have this issue. #ifdef XP_WIN if (!mozilla::IsWin2003OrLater()) { // i.e. if it is WinXP @@ -353,127 +318,90 @@ main(int32_t argc, char *argv[]) // Join multicast group printf("Joining multicast group\n"); phase = TEST_MULTICAST; mozilla::net::NetAddr multicastAddr; multicastAddr.inet.family = AF_INET; multicastAddr.inet.ip = PR_htonl(224 << 24 | 255); multicastAddr.inet.port = PR_htons(serverPort); rv = server->JoinMulticastAddr(multicastAddr, nullptr); - if (NS_WARN_IF(NS_FAILED(rv))) { - return -1; - } + ASSERT_TRUE(NS_SUCCEEDED(rv)); // Send multicast ping timerCb->mResult = NS_OK; timer->InitWithCallback(timerCb, MULTICAST_TIMEOUT, nsITimer::TYPE_ONE_SHOT); rv = client->SendWithAddress(&multicastAddr, (uint8_t*)&data, sizeof(uint32_t), &count); - if (NS_WARN_IF(NS_FAILED(rv))) { - return -1; - } - REQUIRE_EQUAL(count, sizeof(uint32_t), "Error"); - passed("Multicast ping written by SendWithAddress"); + ASSERT_TRUE(NS_SUCCEEDED(rv)); + EXPECT_EQ(count, sizeof(uint32_t)); // Wait for server to receive successfully PumpEvents(); - if (NS_WARN_IF(NS_FAILED(serverListener->mResult))) { - return -1; - } - if (NS_WARN_IF(NS_FAILED(timerCb->mResult))) { - return -1; - } + ASSERT_TRUE(NS_SUCCEEDED(serverListener->mResult)); + ASSERT_TRUE(NS_SUCCEEDED(timerCb->mResult)); timer->Cancel(); - passed("Server received ping successfully"); // Disable multicast loopback printf("Disable multicast loopback\n"); client->SetMulticastLoopback(false); server->SetMulticastLoopback(false); // Send multicast ping timerCb->mResult = NS_OK; timer->InitWithCallback(timerCb, MULTICAST_TIMEOUT, nsITimer::TYPE_ONE_SHOT); rv = client->SendWithAddress(&multicastAddr, (uint8_t*)&data, sizeof(uint32_t), &count); - if (NS_WARN_IF(NS_FAILED(rv))) { - return -1; - } - REQUIRE_EQUAL(count, sizeof(uint32_t), "Error"); - passed("Multicast ping written by SendWithAddress"); + ASSERT_TRUE(NS_SUCCEEDED(rv)); + EXPECT_EQ(count, sizeof(uint32_t)); // Wait for server to fail to receive PumpEvents(); - if (NS_WARN_IF(NS_SUCCEEDED(timerCb->mResult))) { - return -1; - } + ASSERT_FALSE(NS_SUCCEEDED(timerCb->mResult)); timer->Cancel(); - passed("Server failed to receive ping correctly"); // Reset state client->SetMulticastLoopback(true); server->SetMulticastLoopback(true); // Change multicast interface - printf("Changing multicast interface\n"); mozilla::net::NetAddr loopbackAddr; loopbackAddr.inet.family = AF_INET; loopbackAddr.inet.ip = PR_htonl(INADDR_LOOPBACK); client->SetMulticastInterfaceAddr(loopbackAddr); // Send multicast ping timerCb->mResult = NS_OK; timer->InitWithCallback(timerCb, MULTICAST_TIMEOUT, nsITimer::TYPE_ONE_SHOT); rv = client->SendWithAddress(&multicastAddr, (uint8_t*)&data, sizeof(uint32_t), &count); - if (NS_WARN_IF(NS_FAILED(rv))) { - return -1; - } - REQUIRE_EQUAL(count, sizeof(uint32_t), "Error"); - passed("Multicast ping written by SendWithAddress"); + ASSERT_TRUE(NS_SUCCEEDED(rv)); + EXPECT_EQ(count, sizeof(uint32_t)); // Wait for server to fail to receive PumpEvents(); - if (NS_WARN_IF(NS_SUCCEEDED(timerCb->mResult))) { - return -1; - } + ASSERT_FALSE(NS_SUCCEEDED(timerCb->mResult)); timer->Cancel(); - passed("Server failed to receive ping correctly"); // Reset state mozilla::net::NetAddr anyAddr; anyAddr.inet.family = AF_INET; anyAddr.inet.ip = PR_htonl(INADDR_ANY); client->SetMulticastInterfaceAddr(anyAddr); // Leave multicast group - printf("Leave multicast group\n"); rv = server->LeaveMulticastAddr(multicastAddr, nullptr); - if (NS_WARN_IF(NS_FAILED(rv))) { - return -1; - } + ASSERT_TRUE(NS_SUCCEEDED(rv)); // Send multicast ping timerCb->mResult = NS_OK; timer->InitWithCallback(timerCb, MULTICAST_TIMEOUT, nsITimer::TYPE_ONE_SHOT); rv = client->SendWithAddress(&multicastAddr, (uint8_t*)&data, sizeof(uint32_t), &count); - if (NS_WARN_IF(NS_FAILED(rv))) { - return -1; - } - REQUIRE_EQUAL(count, sizeof(uint32_t), "Error"); - passed("Multicast ping written by SendWithAddress"); + ASSERT_TRUE(NS_SUCCEEDED(rv)); + EXPECT_EQ(count, sizeof(uint32_t)); // Wait for server to fail to receive PumpEvents(); - if (NS_WARN_IF(NS_SUCCEEDED(timerCb->mResult))) { - return -1; - } + ASSERT_FALSE(NS_SUCCEEDED(timerCb->mResult)); timer->Cancel(); - passed("Server failed to receive ping correctly"); - goto close; close: // Close server - printf("*** Attempting to close server ...\n"); server->Close(); client->Close(); PumpEvents(); - passed("Server closed"); - - return 0; // failure is a non-zero return }
deleted file mode 100644 --- a/netwerk/test/TestUDPSocketProvider.cpp +++ /dev/null @@ -1,159 +0,0 @@ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -#include "stdio.h" -#include "TestCommon.h" -#include "nsCOMPtr.h" -#include "nsIServiceManager.h" -#include "nsIComponentRegistrar.h" -#include "nspr.h" -#include "nsServiceManagerUtils.h" -#include "nsISocketTransportService.h" -#include "nsISocketTransport.h" -#include "nsIOutputStream.h" -#include "nsIInputStream.h" - -#define UDP_PORT 9050 - -#define UDP_ASSERT(condition, message) \ - PR_BEGIN_MACRO \ - NS_ASSERTION(condition, message); \ - if (!(condition)) { \ - returnCode = -1; \ - break; \ - } \ - PR_END_MACRO - -#define UDP_ASSERT_PRSTATUS(message) \ - PR_BEGIN_MACRO \ - NS_ASSERTION(status == PR_SUCCESS, message); \ - if (status != PR_SUCCESS) { \ - PRErrorCode err = PR_GetError(); \ - fprintf(stderr, \ - "FAIL nspr: %s: (%08x) %s\n", \ - message, \ - err, \ - PR_ErrorToString(err, PR_LANGUAGE_I_DEFAULT)); \ - returnCode = -1; \ - break; \ - } \ - PR_END_MACRO - -#define UDP_ASSERT_NSRESULT(message) \ - PR_BEGIN_MACRO \ - NS_ASSERTION(NS_SUCCEEDED(rv), message); \ - if (NS_FAILED(rv)) { \ - fprintf(stderr, "FAIL UDPSocket: %s: %08x\n", \ - message, rv); \ - returnCode = -1; \ - break; \ - } \ - PR_END_MACRO - -int -main(int argc, char* argv[]) -{ - if (test_common_init(&argc, &argv) != 0) - return -1; - - int returnCode = 0; - nsresult rv = NS_OK; - PRFileDesc *serverFD = nullptr; - - do { // act both as a scope for nsCOMPtrs to be released before XPCOM - // shutdown, as well as a easy way to abort the test - PRStatus status = PR_SUCCESS; - - nsCOMPtr<nsIServiceManager> servMan; - NS_InitXPCOM2(getter_AddRefs(servMan), nullptr, nullptr); - nsCOMPtr<nsIComponentRegistrar> registrar = do_QueryInterface(servMan); - UDP_ASSERT(registrar, "Null nsIComponentRegistrar"); - if (registrar) - registrar->AutoRegister(nullptr); - - // listen for a incoming UDP connection on localhost - serverFD = PR_OpenUDPSocket(PR_AF_INET); - UDP_ASSERT(serverFD, "Cannot open UDP socket for listening"); - - PRSocketOptionData socketOptions; - socketOptions.option = PR_SockOpt_Nonblocking; - socketOptions.value.non_blocking = false; - status = PR_SetSocketOption(serverFD, &socketOptions); - UDP_ASSERT_PRSTATUS("Failed to set server socket as blocking"); - - PRNetAddr addr; - status = PR_InitializeNetAddr(PR_IpAddrLoopback, UDP_PORT, &addr); - UDP_ASSERT_PRSTATUS("Failed to initialize loopback address"); - - status = PR_Bind(serverFD, &addr); - UDP_ASSERT_PRSTATUS("Failed to bind server socket"); - - // dummy IOService to get around bug 379890 - nsCOMPtr<nsISupports> ios = - do_GetService("@mozilla.org/network/io-service;1"); - - // and have a matching UDP connection for the client - nsCOMPtr<nsISocketTransportService> sts = - do_GetService("@mozilla.org/network/socket-transport-service;1", &rv); - UDP_ASSERT_NSRESULT("Cannot get socket transport service"); - - nsCOMPtr<nsISocketTransport> transport; - const char *protocol = "udp"; - rv = sts->CreateTransport(&protocol, 1, NS_LITERAL_CSTRING("localhost"), - UDP_PORT, nullptr, getter_AddRefs(transport)); - UDP_ASSERT_NSRESULT("Cannot create transport"); - - uint32_t count, read; - const uint32_t data = 0xFF0056A9; - - // write to the output stream - nsCOMPtr<nsIOutputStream> outstream; - rv = transport->OpenOutputStream(nsITransport::OPEN_BLOCKING, - 0, 0, getter_AddRefs(outstream)); - UDP_ASSERT_NSRESULT("Cannot open output stream"); - - rv = outstream->Write((const char*)&data, sizeof(uint32_t), &count); - UDP_ASSERT_NSRESULT("Cannot write to output stream"); - UDP_ASSERT(count == sizeof(uint32_t), - "Did not write enough bytes to output stream"); - - // read from NSPR to check it's the same - count = PR_RecvFrom(serverFD, &read, sizeof(uint32_t), 0, &addr, 1); - UDP_ASSERT(count == sizeof(uint32_t), - "Did not read enough bytes from NSPR"); - status = (read == data ? PR_SUCCESS : PR_FAILURE); - UDP_ASSERT_PRSTATUS("Did not read expected data from NSPR"); - - // write to NSPR - count = PR_SendTo(serverFD, &data, sizeof(uint32_t), 0, &addr, 1); - status = (count == sizeof(uint32_t) ? PR_SUCCESS : PR_FAILURE); - UDP_ASSERT_PRSTATUS("Did not write enough bytes to NSPR"); - - // read from stream - nsCOMPtr<nsIInputStream> instream; - rv = transport->OpenInputStream(nsITransport::OPEN_BLOCKING, - 0, 0, getter_AddRefs(instream)); - UDP_ASSERT_NSRESULT("Cannot open input stream"); - - rv = instream->Read((char*)&read, sizeof(uint32_t), &count); - UDP_ASSERT_NSRESULT("Cannot read from input stream"); - UDP_ASSERT(count == sizeof(uint32_t), - "Did not read enough bytes from input stream"); - UDP_ASSERT(read == data, "Did not read expected data from stream"); - - } while (false); // release all XPCOM things - if (serverFD) { - PRStatus status = PR_Close(serverFD); - if (status != PR_SUCCESS) { - PRErrorCode err = PR_GetError(); - fprintf(stderr, "FAIL: Cannot close server: (%08x) %s\n", - err, PR_ErrorToString(err, PR_LANGUAGE_I_DEFAULT)); - } - } - rv = NS_ShutdownXPCOM(nullptr); - NS_ASSERTION(NS_SUCCEEDED(rv), "NS_ShutdownXPCOM failed"); - - return returnCode; -} -
deleted file mode 100644 --- a/netwerk/test/TestURLParser.cpp +++ /dev/null @@ -1,135 +0,0 @@ -#include "TestCommon.h" -#include <stdio.h> -#include "nsIURLParser.h" -#include "nsCOMPtr.h" -#include "nsIServiceManager.h" -#include "nsNetCID.h" -#include "nsServiceManagerUtils.h" - -static void -print_field(const char *label, char *str, int32_t len) -{ - char c = str[len]; - str[len] = '\0'; - printf("[%s=%s]\n", label, str); - str[len] = c; -} - -#define PRINT_FIELD(x) \ - print_field(# x, x, x ## Len) - -#define PRINT_SUBFIELD(base, x) \ - PR_BEGIN_MACRO \ - if (x ## Len != -1) \ - print_field(# x, base + x ## Pos, x ## Len); \ - PR_END_MACRO - -static void -parse_authority(nsIURLParser *urlParser, char *auth, int32_t authLen) -{ - PRINT_FIELD(auth); - - uint32_t usernamePos, passwordPos; - int32_t usernameLen, passwordLen; - uint32_t hostnamePos; - int32_t hostnameLen, port; - - urlParser->ParseAuthority(auth, authLen, - &usernamePos, &usernameLen, - &passwordPos, &passwordLen, - &hostnamePos, &hostnameLen, - &port); - - PRINT_SUBFIELD(auth, username); - PRINT_SUBFIELD(auth, password); - PRINT_SUBFIELD(auth, hostname); - if (port != -1) - printf("[port=%d]\n", port); -} - -static void -parse_file_path(nsIURLParser *urlParser, char *filepath, int32_t filepathLen) -{ - PRINT_FIELD(filepath); - - uint32_t dirPos, basePos, extPos; - int32_t dirLen, baseLen, extLen; - - urlParser->ParseFilePath(filepath, filepathLen, - &dirPos, &dirLen, - &basePos, &baseLen, - &extPos, &extLen); - - PRINT_SUBFIELD(filepath, dir); - PRINT_SUBFIELD(filepath, base); - PRINT_SUBFIELD(filepath, ext); -} - -static void -parse_path(nsIURLParser *urlParser, char *path, int32_t pathLen) -{ - PRINT_FIELD(path); - - uint32_t filePos, queryPos, refPos; - int32_t fileLen, queryLen, refLen; - - urlParser->ParsePath(path, pathLen, - &filePos, &fileLen, - &queryPos, &queryLen, - &refPos, &refLen); - - if (fileLen != -1) - parse_file_path(urlParser, path + filePos, fileLen); - PRINT_SUBFIELD(path, query); - PRINT_SUBFIELD(path, ref); -} - -int -main(int argc, char **argv) -{ - if (test_common_init(&argc, &argv) != 0) - return -1; - - if (argc < 2) { - printf("usage: TestURLParser [-std|-noauth|-auth] <url>\n"); - return -1; - } - nsCOMPtr<nsIURLParser> urlParser; - if (strcmp(argv[1], "-noauth") == 0) { - urlParser = do_GetService(NS_NOAUTHURLPARSER_CONTRACTID); - argv[1] = argv[2]; - } - else if (strcmp(argv[1], "-auth") == 0) { - urlParser = do_GetService(NS_AUTHURLPARSER_CONTRACTID); - argv[1] = argv[2]; - } - else { - urlParser = do_GetService(NS_STDURLPARSER_CONTRACTID); - if (strcmp(argv[1], "-std") == 0) - argv[1] = argv[2]; - else - printf("assuming -std\n"); - } - if (urlParser) { - printf("have urlParser @%p\n", static_cast<void*>(urlParser.get())); - - char *spec = argv[1]; - uint32_t schemePos, authPos, pathPos; - int32_t schemeLen, authLen, pathLen; - - urlParser->ParseURL(spec, -1, - &schemePos, &schemeLen, - &authPos, &authLen, - &pathPos, &pathLen); - - if (schemeLen != -1) - PRINT_SUBFIELD(spec, scheme); - if (authLen != -1) - parse_authority(urlParser, spec + authPos, authLen); - if (pathLen != -1) - parse_path(urlParser, spec + pathPos, pathLen); - } - else - printf("no urlParser\n"); - return 0; -}
deleted file mode 100644 --- a/netwerk/test/TestUpload.cpp +++ /dev/null @@ -1,171 +0,0 @@ -/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -#include "TestCommon.h" -#include <algorithm> -#ifdef WIN32 -#include <windows.h> -#endif - -#include "nsIComponentRegistrar.h" -#include "nsIScriptSecurityManager.h" -#include "nsServiceManagerUtils.h" -#include "nsIServiceManager.h" -#include "nsNetUtil.h" - -#include "nsIUploadChannel.h" - -#include "NetwerkTestLogging.h" -// -// set NSPR_LOG_MODULES=Test:5 -// -static PRLogModuleInfo *gTestLog = nullptr; -#define LOG(args) MOZ_LOG(gTestLog, mozilla::LogLevel::Debug, args) - -//----------------------------------------------------------------------------- -// InputTestConsumer -//----------------------------------------------------------------------------- - -class InputTestConsumer : public nsIStreamListener -{ - virtual ~InputTestConsumer(); - -public: - - InputTestConsumer(); - - NS_DECL_ISUPPORTS - NS_DECL_NSIREQUESTOBSERVER - NS_DECL_NSISTREAMLISTENER -}; - -InputTestConsumer::InputTestConsumer() -{ -} - -InputTestConsumer::~InputTestConsumer() -{ -} - -NS_IMPL_ISUPPORTS(InputTestConsumer, - nsIStreamListener, - nsIRequestObserver) - -NS_IMETHODIMP -InputTestConsumer::OnStartRequest(nsIRequest *request, nsISupports* context) -{ - LOG(("InputTestConsumer::OnStartRequest\n")); - return NS_OK; -} - -NS_IMETHODIMP -InputTestConsumer::OnDataAvailable(nsIRequest *request, - nsISupports* context, - nsIInputStream *aIStream, - uint64_t aSourceOffset, - uint32_t aLength) -{ - char buf[1025]; - uint32_t amt, size; - nsresult rv; - - while (aLength) { - size = std::min<uint32_t>(aLength, sizeof(buf)); - rv = aIStream->Read(buf, size, &amt); - if (NS_FAILED(rv)) { - NS_ASSERTION((NS_BASE_STREAM_WOULD_BLOCK != rv), - "The stream should never block."); - return rv; - } - aLength -= amt; - } - return NS_OK; -} - - -NS_IMETHODIMP -InputTestConsumer::OnStopRequest(nsIRequest *request, nsISupports* context, - nsresult aStatus) -{ - LOG(("InputTestConsumer::OnStopRequest [status=%x]\n", aStatus)); - QuitPumpingEvents(); - return NS_OK; -} - - -int -main(int argc, char* argv[]) -{ - if (test_common_init(&argc, &argv) != 0) - return -1; - - nsresult rv; - - if (argc < 2) { - printf("usage: %s <url> <file-to-upload>\n", argv[0]); - return -1; - } - char* uriSpec = argv[1]; - char* fileName = argv[2]; - - gTestLog = PR_NewLogModule("Test"); - - { - nsCOMPtr<nsIServiceManager> servMan; - NS_InitXPCOM2(getter_AddRefs(servMan), nullptr, nullptr); - - // first thing to do is create ourselves a stream that - // is to be uploaded. - nsCOMPtr<nsIInputStream> uploadStream; - rv = NS_NewPostDataStream(getter_AddRefs(uploadStream), - true, - nsDependentCString(fileName)); // XXX UTF-8 - if (NS_FAILED(rv)) return -1; - - // create our url. - nsCOMPtr<nsIURI> uri; - rv = NS_NewURI(getter_AddRefs(uri), uriSpec); - if (NS_FAILED(rv)) return -1; - - nsCOMPtr<nsIScriptSecurityManager> secman = - do_GetService(NS_SCRIPTSECURITYMANAGER_CONTRACTID, &rv); - if (NS_FAILED(rv)) return -1; - nsCOMPtr<nsIPrincipal> systemPrincipal; - rv = secman->GetSystemPrincipal(getter_AddRefs(systemPrincipal)); - if (NS_FAILED(rv)) return -1; - - nsCOMPtr<nsIChannel> channel; - rv = NS_NewChannel(getter_AddRefs(channel), - uri, - systemPrincipal, - nsILoadInfo::SEC_ALLOW_CROSS_ORIGIN_DATA_INHERITS, - nsIContentPolicy::TYPE_OTHER); - if (NS_FAILED(rv)) return -1; - - // QI and set the upload stream - nsCOMPtr<nsIUploadChannel> uploadChannel(do_QueryInterface(channel)); - uploadChannel->SetUploadStream(uploadStream, EmptyCString(), -1); - - // create a dummy listener - InputTestConsumer* listener; - - listener = new InputTestConsumer; - if (!listener) { - NS_ERROR("Failed to create a new stream listener!"); - return -1; - } - NS_ADDREF(listener); - - channel->AsyncOpen2(listener); - - PumpEvents(); - } // this scopes the nsCOMPtrs - // no nsCOMPtrs are allowed to be alive when you call NS_ShutdownXPCOM - rv = NS_ShutdownXPCOM(nullptr); - NS_ASSERTION(NS_SUCCEEDED(rv), "NS_ShutdownXPCOM failed"); - - return 0; -} -
--- a/netwerk/test/moz.build +++ b/netwerk/test/moz.build @@ -9,57 +9,24 @@ TEST_DIRS += ['httpserver', 'gtest'] BROWSER_CHROME_MANIFESTS += ['browser/browser.ini'] MOCHITEST_MANIFESTS += ['mochitests/mochitest.ini'] XPCSHELL_TESTS_MANIFESTS += [ 'unit/xpcshell.ini', 'unit_ipc/xpcshell.ini', ] -GeckoSimplePrograms([ - 'PropertiesTest', - 'ReadNTLM', - 'TestBlockingSocket', - 'TestDNS', - 'TestIncrementalDownload', - 'TestOpen', - 'TestProtocols', - 'TestServ', - 'TestStreamLoader', - 'TestUpload', - 'TestURLParser', - 'urltest', -]) - -# XXX Make this work in libxul builds. -#SIMPLE_PROGRAMS += [ -# TestIDN', -# TestIOThreads', -# TestSocketTransport', -# TestStreamPump', -# TestStreamTransport', -# TestUDPSocketProvider', -#] - -CppUnitTests([ - 'TestBind', - 'TestCookie', - 'TestUDPSocket', -]) +FINAL_LIBRARY = 'xul-gtest' +UNIFIED_SOURCES += [ + 'TestBind.cpp', + 'TestCookie.cpp', + 'TestUDPSocket.cpp', +] RESOURCE_FILES += [ 'urlparse.dat', 'urlparse_unx.dat', ] -USE_LIBS += ['static:js'] - -if CONFIG['ENABLE_INTL_API'] and CONFIG['MOZ_ICU_DATA_ARCHIVE']: - # The ICU libraries linked into libmozjs will not include the ICU data, - # so link it directly. - USE_LIBS += ['icudata'] - -CXXFLAGS += CONFIG['TK_CFLAGS'] - include('/ipc/chromium/chromium-config.mozbuild') if CONFIG['GNU_CXX']: CXXFLAGS += ['-Wno-shadow']
deleted file mode 100644 --- a/netwerk/test/urltest.cpp +++ /dev/null @@ -1,461 +0,0 @@ -/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -/* - A test file to check default URL parsing. - -Gagan Saksena 03/25/99 -*/ - -#include <stdio.h> - -#include "TestCommon.h" -#include "plstr.h" -#include "nsIServiceManager.h" -#include "nsIIOService.h" -#include "nsIURL.h" -#include "nsCOMPtr.h" -#include "nsStringAPI.h" -#include "nsNetCID.h" -#include "nsIComponentRegistrar.h" -#include "nsComponentManagerUtils.h" -#include "nsServiceManagerUtils.h" -#include "nsXPCOM.h" -#include "prprf.h" -#include "mozilla/Sprintf.h" - -// Define CIDs... -static NS_DEFINE_CID(kIOServiceCID, NS_IOSERVICE_CID); -static NS_DEFINE_CID(kStdURLCID, NS_STANDARDURL_CID); - -char* gFileIO = 0; - -enum { - URL_FACTORY_DEFAULT, - URL_FACTORY_STDURL -}; - -nsresult writeoutto(const char* i_pURL, char** o_Result, int32_t urlFactory = URL_FACTORY_DEFAULT) -{ - if (!o_Result || !i_pURL) - return NS_ERROR_FAILURE; - *o_Result = 0; - nsCOMPtr<nsIURI> pURL; - nsresult result = NS_OK; - - switch (urlFactory) { - case URL_FACTORY_STDURL: { - nsIURI* url; - result = CallCreateInstance(kStdURLCID, &url); - if (NS_FAILED(result)) - { - printf("CreateInstance failed\n"); - return NS_ERROR_FAILURE; - } - pURL = url; - result = pURL->SetSpec(nsDependentCString(i_pURL)); - if (NS_FAILED(result)) - { - printf("SetSpec failed\n"); - return NS_ERROR_FAILURE; - } - break; - } - case URL_FACTORY_DEFAULT: { - nsCOMPtr<nsIIOService> pService = - do_GetService(kIOServiceCID, &result); - if (NS_FAILED(result)) - { - printf("Service failed!\n"); - return NS_ERROR_FAILURE; - } - result = pService->NewURI(nsDependentCString(i_pURL), nullptr, nullptr, getter_AddRefs(pURL)); - } - } - - nsCString output; - if (NS_SUCCEEDED(result)) - { - nsCOMPtr<nsIURL> tURL = do_QueryInterface(pURL); - nsAutoCString temp; - int32_t port; - nsresult rv; - -#define RESULT() NS_SUCCEEDED(rv) ? temp.get() : "" - - rv = tURL->GetScheme(temp); - output += RESULT(); - output += ','; - rv = tURL->GetUsername(temp); - output += RESULT(); - output += ','; - rv = tURL->GetPassword(temp); - output += RESULT(); - output += ','; - rv = tURL->GetHost(temp); - output += RESULT(); - output += ','; - rv = tURL->GetPort(&port); - char portbuffer[40]; - SprintfLiteral(portbuffer, "%d", port); - output.Append(portbuffer); - output += ','; - rv = tURL->GetDirectory(temp); - output += RESULT(); - output += ','; - rv = tURL->GetFileBaseName(temp); - output += RESULT(); - output += ','; - rv = tURL->GetFileExtension(temp); - output += RESULT(); - output += ','; - // removed with https://bugzilla.mozilla.org/show_bug.cgi?id=665706 - // rv = tURL->GetParam(temp); - // output += RESULT(); - output += ','; - rv = tURL->GetQuery(temp); - output += RESULT(); - output += ','; - rv = tURL->GetRef(temp); - output += RESULT(); - output += ','; - rv = tURL->GetSpec(temp); - output += RESULT(); - *o_Result = ToNewCString(output); - } else { - output = "Can not create URL"; - *o_Result = ToNewCString(output); - } - return NS_OK; -} - -nsresult writeout(const char* i_pURL, int32_t urlFactory = URL_FACTORY_DEFAULT) -{ - if (!i_pURL) return NS_ERROR_FAILURE; - nsCString temp; - nsresult rv = writeoutto(i_pURL, getter_Copies(temp), urlFactory); - printf("%s\n%s\n", i_pURL, temp.get()); - return rv; -} - -/* construct a url and print out its elements separated by commas and - the whole spec */ -nsresult testURL(const char* i_pURL, int32_t urlFactory = URL_FACTORY_DEFAULT) -{ - - if (i_pURL) - return writeout(i_pURL, urlFactory); - - if (!gFileIO) - return NS_ERROR_FAILURE; - - FILE *testfile = fopen(gFileIO, "rt"); - if (!testfile) - { - fprintf(stderr, "Cannot open testfile: %s\n", gFileIO); - return NS_ERROR_FAILURE; - } - - char temp[512]; - int count=0; - int failed=0; - nsCString prevResult; - nsCString tempurl; - - while (fgets(temp,512,testfile)) - { - if (*temp == '#' || !*temp) - continue; - - if (0 == count%3) - { - printf("Testing: %s\n", temp); - writeoutto(temp, getter_Copies(prevResult), urlFactory); - } - else if (1 == count%3) { - tempurl.Assign(temp); - } else { - if (prevResult.IsEmpty()) - printf("no results to compare to!\n"); - else - { - int32_t res; - printf("Result: %s\n", prevResult.get()); - if (urlFactory != URL_FACTORY_DEFAULT) { - printf("Expected: %s\n", tempurl.get()); - res = PL_strcmp(tempurl.get(), prevResult.get()); - } else { - printf("Expected: %s\n", temp); - res = PL_strcmp(temp, prevResult.get()); - } - - if (res == 0) - printf("\tPASSED\n\n"); - else - { - printf("\tFAILED\n\n"); - failed++; - } - } - } - count++; - } - if (failed>0) { - printf("%d tests FAILED out of %d\n", failed, count/3); - return NS_ERROR_FAILURE; - } else { - printf("All %d tests PASSED.\n", count/3); - return NS_OK; - } -} - -nsresult makeAbsTest(const char* i_BaseURI, const char* relativePortion, - const char* expectedResult) -{ - if (!i_BaseURI) - return NS_ERROR_FAILURE; - - // build up the base URL - nsresult status; - nsCOMPtr<nsIURI> baseURL = do_CreateInstance(kStdURLCID, &status); - if (NS_FAILED(status)) - { - printf("CreateInstance failed\n"); - return status; - } - status = baseURL->SetSpec(nsDependentCString(i_BaseURI)); - if (NS_FAILED(status)) return status; - - - // get the new spec - nsAutoCString newURL; - status = baseURL->Resolve(nsDependentCString(relativePortion), newURL); - if (NS_FAILED(status)) return status; - - printf("Analyzing %s\n", baseURL->GetSpecOrDefault().get()); - printf("With %s\n", relativePortion); - - printf("Got %s\n", newURL.get()); - if (expectedResult) { - printf("Expect %s\n", expectedResult); - int res = PL_strcmp(newURL.get(), expectedResult); - if (res == 0) { - printf("\tPASSED\n\n"); - return NS_OK; - } else { - printf("\tFAILED\n\n"); - return NS_ERROR_FAILURE; - } - } - return NS_OK; -} - -nsresult doMakeAbsTest(const char* i_URL = 0, const char* i_relativePortion=0) -{ - if (i_URL && i_relativePortion) - { - return makeAbsTest(i_URL, i_relativePortion, nullptr); - } - - // Run standard tests. These tests are based on the ones described in - // rfc2396 with the exception of the handling of ?y which is wrong as - // notified by on of the RFC authors. - - /* Section C.1. Normal Examples - - g:h = <URL:g:h> - g = <URL:http://a/b/c/g> - ./g = <URL:http://a/b/c/g> - g/ = <URL:http://a/b/c/g/> - /g = <URL:http://a/g> - //g = <URL:http://g> - ?y = <URL:http://a/b/c/d;p?y> - g?y = <URL:http://a/b/c/g?y> - g?y/./x = <URL:http://a/b/c/g?y/./x> - #s = <URL:http://a/b/c/d;p?q#s> - g#s = <URL:http://a/b/c/g#s> - g#s/./x = <URL:http://a/b/c/g#s/./x> - g?y#s = <URL:http://a/b/c/g?y#s> - ;x = <URL:http://a/b/c/;x> - g;x = <URL:http://a/b/c/g;x> - g;x?y#s = <URL:http://a/b/c/g;x?y#s> - . = <URL:http://a/b/c/> - ./ = <URL:http://a/b/c/> - .. = <URL:http://a/b/> - ../ = <URL:http://a/b/> - ../g = <URL:http://a/b/g> - ../.. = <URL:http://a/> - ../../ = <URL:http://a/> - ../../g = <URL:http://a/g> - */ - - struct test { - const char* baseURL; - const char* relativeURL; - const char* expectedResult; - }; - - test tests[] = { - // Tests from rfc2396, section C.1 with the exception of the - // handling of ?y - { "http://a/b/c/d;p?q#f", "g:h", "g:h" }, - { "http://a/b/c/d;p?q#f", "g", "http://a/b/c/g" }, - { "http://a/b/c/d;p?q#f", "./g", "http://a/b/c/g" }, - { "http://a/b/c/d;p?q#f", "g/", "http://a/b/c/g/" }, - { "http://a/b/c/d;p?q#f", "/g", "http://a/g" }, - { "http://a/b/c/d;p?q#f", "//g", "http://g" }, - { "http://a/b/c/d;p?q#f", "?y", "http://a/b/c/d;p?y" }, - { "http://a/b/c/d;p?q#f", "g?y", "http://a/b/c/g?y" }, - { "http://a/b/c/d;p?q#f", "g?y/./x", "http://a/b/c/g?y/./x" }, - { "http://a/b/c/d;p?q#f", "#s", "http://a/b/c/d;p?q#s" }, - { "http://a/b/c/d;p?q#f", "g#s", "http://a/b/c/g#s" }, - { "http://a/b/c/d;p?q#f", "g#s/./x", "http://a/b/c/g#s/./x" }, - { "http://a/b/c/d;p?q#f", "g?y#s", "http://a/b/c/g?y#s" }, - { "http://a/b/c/d;p?q#f", ";x", "http://a/b/c/;x" }, - { "http://a/b/c/d;p?q#f", "g;x", "http://a/b/c/g;x" }, - { "http://a/b/c/d;p?q#f", "g;x?y#s", "http://a/b/c/g;x?y#s" }, - { "http://a/b/c/d;p?q#f", ".", "http://a/b/c/" }, - { "http://a/b/c/d;p?q#f", "./", "http://a/b/c/" }, - { "http://a/b/c/d;p?q#f", "..", "http://a/b/" }, - { "http://a/b/c/d;p?q#f", "../", "http://a/b/" }, - { "http://a/b/c/d;p?q#f", "../g", "http://a/b/g" }, - { "http://a/b/c/d;p?q#f", "../..", "http://a/" }, - { "http://a/b/c/d;p?q#f", "../../", "http://a/" }, - { "http://a/b/c/d;p?q#f", "../../g", "http://a/g" }, - - // Our additional tests... - { "http://a/b/c/d;p?q#f", "#my::anchor", "http://a/b/c/d;p?q#my::anchor" }, - { "http://a/b/c/d;p?q#f", "get?baseRef=viewcert.jpg", "http://a/b/c/get?baseRef=viewcert.jpg" }, - - // Make sure relative query's work right even if the query - // string contains absolute urls or other junk. - { "http://a/b/c/d;p?q#f", "?http://foo", "http://a/b/c/d;p?http://foo" }, - { "http://a/b/c/d;p?q#f", "g?http://foo", "http://a/b/c/g?http://foo" }, - {"http://a/b/c/d;p?q#f", "g/h?http://foo", "http://a/b/c/g/h?http://foo" }, - { "http://a/b/c/d;p?q#f", "g/h/../H?http://foo","http://a/b/c/g/H?http://foo" }, - { "http://a/b/c/d;p?q#f", "g/h/../H?http://foo?baz", "http://a/b/c/g/H?http://foo?baz" }, - { "http://a/b/c/d;p?q#f", "g/h/../H?http://foo;baz", "http://a/b/c/g/H?http://foo;baz" }, - { "http://a/b/c/d;p?q#f", "g/h/../H?http://foo#bar", "http://a/b/c/g/H?http://foo#bar" }, - { "http://a/b/c/d;p?q#f", "g/h/../H;baz?http://foo", "http://a/b/c/g/H;baz?http://foo" }, - { "http://a/b/c/d;p?q#f", "g/h/../H;baz?http://foo#bar", "http://a/b/c/g/H;baz?http://foo#bar" }, - { "http://a/b/c/d;p?q#f", "g/h/../H;baz?C:\\temp", "http://a/b/c/g/H;baz?C:\\temp" }, - { "http://a/b/c/d;p?q#f", "", "http://a/b/c/d;p?q" }, - { "http://a/b/c/d;p?q#f", "#", "http://a/b/c/d;p?q#" }, - { "http://a/b/c;p/d;p?q#f", "../g;p" , "http://a/b/g;p" }, - - }; - - const int numTests = sizeof(tests) / sizeof(tests[0]); - int failed = 0; - nsresult rv; - for (int i = 0 ; i<numTests ; ++i) - { - rv = makeAbsTest(tests[i].baseURL, tests[i].relativeURL, - tests[i].expectedResult); - if (NS_FAILED(rv)) - failed++; - } - if (failed>0) { - printf("%d tests FAILED out of %d\n", failed, numTests); - return NS_ERROR_FAILURE; - } else { - printf("All %d tests PASSED.\n", numTests); - return NS_OK; - } -} - -void printusage(void) -{ - printf("urltest [-std] [-file <filename>] <URL> " - " [-abs <relative>]\n\n" - "\t-std : Generate results using nsStdURL.\n" - "\t-file : Read URLs from file.\n" - "\t-abs : Make an absolute URL from the base (<URL>) and the\n" - "\t\trelative path specified. If -abs is given without\n" - "\t\ta base URI standard RFC 2396 relative URL tests\n" - "\t\tare performed. Implies -std.\n" - "\t<URL> : The string representing the URL.\n"); -} - -int main(int argc, char **argv) -{ - if (test_common_init(&argc, &argv) != 0) - return -1; - - if (argc < 2) { - printusage(); - return 0; - } - { - nsCOMPtr<nsIServiceManager> servMan; - NS_InitXPCOM2(getter_AddRefs(servMan), nullptr, nullptr); - - // end of all messages from register components... - printf("------------------\n\n"); - - int32_t urlFactory = URL_FACTORY_DEFAULT; - bool bMakeAbs= false; - char* relativePath = 0; - char* url = 0; - for (int i=1; i<argc; i++) { - if (PL_strcasecmp(argv[i], "-std") == 0) - { - urlFactory = URL_FACTORY_STDURL; - if (i+1 >= argc) - { - printusage(); - return 0; - } - } - else if (PL_strcasecmp(argv[i], "-abs") == 0) - { - if (!gFileIO) - { - relativePath = argv[i+1]; - i++; - } - bMakeAbs = true; - } - else if (PL_strcasecmp(argv[i], "-file") == 0) - { - if (i+1 >= argc) - { - printusage(); - return 0; - } - gFileIO = argv[i+1]; - i++; - } - else - { - url = argv[i]; - } - } - PRTime startTime = PR_Now(); - if (bMakeAbs) - { - if (url && relativePath) { - doMakeAbsTest(url, relativePath); - } else { - doMakeAbsTest(); - } - } - else - { - if (gFileIO) { - testURL(0, urlFactory); - } else { - testURL(url, urlFactory); - } - } - if (gFileIO) - { - PRTime endTime = PR_Now(); - printf("Elapsed time: %d micros.\n", (int32_t) - (endTime - startTime)); - } - } // this scopes the nsCOMPtrs - // no nsCOMPtrs are allowed to be alive when you call NS_ShutdownXPCOM - return NS_FAILED(NS_ShutdownXPCOM(nullptr)) ? 1 : 0; -}