/*
 * Copyright (C) 2010 Google Inc. All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are
 * met:
 *
 *     * Redistributions of source code must retain the above copyright
 * notice, this list of conditions and the following disclaimer.
 *     * Redistributions in binary form must reproduce the above
 * copyright notice, this list of conditions and the following disclaimer
 * in the documentation and/or other materials provided with the
 * distribution.
 *     * Neither the name of Google Inc. nor the names of its
 * contributors may be used to endorse or promote products derived from
 * this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

#include "config.h"

#include "ThreadableBlobRegistry.h"

#include "BlobData.h"
#include "BlobRegistry.h"
#include "BlobURL.h"
#include "KURL.h"
#include "SecurityOrigin.h"
#include <wtf/HashCountedSet.h>
#include <wtf/HashMap.h>
#include <wtf/MainThread.h>
#include <wtf/NeverDestroyed.h>
#include <wtf/OwnPtr.h>
#include <wtf/RefPtr.h>
#include <wtf/ThreadSpecific.h>
#include <wtf/text/StringHash.h>
#include <wtf/threads/BinarySemaphore.h>

using WTF::ThreadSpecific;

namespace WebCore {

namespace {
struct BlobRegistryContext {
    WTF_MAKE_FAST_ALLOCATED;
public:
    BlobRegistryContext(const KURL& url, PassOwnPtr<BlobData> blobData)
        : url(url.isolatedCopy())
        , blobData(blobData)
    {
        this->blobData->detachFromCurrentThread();
    }

    BlobRegistryContext(const KURL& url, const KURL& srcURL, SecurityOrigin* origin)
        : url(url.isolatedCopy())
        , srcURL(srcURL.isolatedCopy())
    	, strongOrigin(origin ? RefPtr<SecurityOrigin>(origin ->isolatedCopy()) : RefPtr<SecurityOrigin>())
    	, start(start)
    	, end(end)
    {
    }

    BlobRegistryContext(const KURL& url, const KURL& srcURL, long long start, long long end)
        : url(url.isolatedCopy())
        , srcURL(srcURL.isolatedCopy())
    	, start(start)
    	, end(end)
    {
    }

    explicit BlobRegistryContext(const KURL& url, BinarySemaphore* semaphore)
        : url(url.isolatedCopy())
    	, semaphore(semaphore)
    {
    }

    KURL url;
    KURL srcURL;
    RefPtr<SecurityOrigin> strongOrigin;
    long long start { 0 };
    long long end { 0 };
    OwnPtr<BlobData> blobData;
    RefPtr<SecurityOrigin> resultOrigin;
    unsigned long long resultSize { 0 };
    BinarySemaphore* semaphore { nullptr };
};
}

#if ENABLE(BLOB)

typedef HashMap<String, RefPtr<SecurityOrigin>> BlobURLOriginMap;
static NEVER_INLINE BlobURLOriginMap& originMap()
{
	static NeverDestroyed<BlobURLOriginMap> map;
	return map;
}

static HashCountedSet<String>& blobURLReferencesMap()
{
	static NeverDestroyed<HashCountedSet<String>> map;
	return map;
}

static inline bool isBlobURLContainsNullOrigin(const KURL& url)
{
    ASSERT(url.protocolIsBlob());
    unsigned startIndex = url.pathStart();
    unsigned endIndex = url.pathAfterLastSlash();
    return StringView(url.string()).substring(startIndex, endIndex - startIndex - 1) == "null";
}

// If the blob URL contains null origin, as in the context with unique security origin or file URL, save the mapping between url and origin so that the origin can be retrived when doing security origin check.
static void addToOriginMapIfNecessary(const URL& url, PassRefPtr<SecurityOrigin> origin)
{
    if (!origin || !isBlobURLContainsNullOrigin(url))
        return;

    String urlWithoutFragment = url.stringWithoutFragmentIdentifier();
    originMap().add(urlWithoutFragment, origin);
    blobURLReferencesMap().add(urlWithoutFragment);
};

static void registerBlobURLTaskOnMainThread(void* context)
{
    OwnPtr<BlobRegistryContext> blobRegistryContext = adoptPtr(static_cast<BlobRegistryContext*>(context));
    blobRegistry().registerBlobURL(blobRegistryContext->url, blobRegistryContext->blobData.release());
}

void ThreadableBlobRegistry::registerBlobURL(const KURL& url, PassOwnPtr<BlobData> blobData)
{
    if (isMainThread())
        blobRegistry().registerBlobURL(url, blobData);
    else {
        OwnPtr<BlobRegistryContext> context = adoptPtr(new BlobRegistryContext(url, blobData));
        callOnMainThread(&registerBlobURLTaskOnMainThread, context.leakPtr());
    }
}

static void unregisterBlobURLOriginIfNecessaryOnMainThread(const URL& url)
{
    ASSERT(isMainThread());
    if (!isBlobURLContainsNullOrigin(url))
        return;

    auto urlWithoutFragment = url.stringWithoutFragmentIdentifier();
    if (blobURLReferencesMap().remove(urlWithoutFragment))
        originMap().remove(urlWithoutFragment);
}

static void registerBlobURLFromTaskOnMainThread(void* context)
{
    OwnPtr<BlobRegistryContext> blobRegistryContext = adoptPtr(static_cast<BlobRegistryContext*>(context));
    addToOriginMapIfNecessary(blobRegistryContext->url, blobRegistryContext->strongOrigin.release());
    blobRegistry().registerBlobURL(blobRegistryContext->url, blobRegistryContext->srcURL);
}

void ThreadableBlobRegistry::registerBlobURL(SecurityOrigin* origin, const KURL& url, const KURL& srcURL)
{
    if (isMainThread()) {
        addToOriginMapIfNecessary(url, origin);
        blobRegistry().registerBlobURL(url, srcURL);
        return;
    }

	OwnPtr<BlobRegistryContext> context = adoptPtr(new BlobRegistryContext(url, srcURL, origin));
	callOnMainThread(&registerBlobURLFromTaskOnMainThread, context.leakPtr());
}

void ThreadableBlobRegistry::registerBlobURL(SecurityOrigin* origin, const KURL& url, const KURL& srcURL, const String& contentType)
{
	UNUSED_PARAM(contentType);
	registerBlobURL(origin, url, srcURL);
}

static void registerBlobURLForSliceTaskOnMainThread(void* context)
{
    OwnPtr<BlobRegistryContext> blobRegistryContext = adoptPtr(static_cast<BlobRegistryContext*>(context));
    blobRegistry().registerBlobURLForSlice(blobRegistryContext->url, blobRegistryContext->srcURL, blobRegistryContext->start, blobRegistryContext->end);
}

void ThreadableBlobRegistry::registerBlobURLForSlice(const KURL& newURL, const KURL& srcURL, long long start, long long end)
{
    if (isMainThread())
        blobRegistry().registerBlobURLForSlice(newURL, srcURL, start, end);
    else {
        // BlobRegistryContext performs an isolated copy of data.
    	OwnPtr<BlobRegistryContext> context = adoptPtr(new BlobRegistryContext(newURL, srcURL, start, end));
        callOnMainThread(&registerBlobURLForSliceTaskOnMainThread, context.leakPtr());
    }
}

static void blobSizeTaskOnMainThread(void* context)
{
    BlobRegistryContext* blobRegistryContext = static_cast<BlobRegistryContext*>(context);
    blobRegistryContext->resultSize = blobRegistry().blobSize(blobRegistryContext->url);
    blobRegistryContext->semaphore->signal();
}

unsigned long long ThreadableBlobRegistry::blobSize(const KURL& url)
{
    if (isMainThread())
        return blobRegistry().blobSize(url);

    unsigned long long resultSize;
	BinarySemaphore semaphore;
	// BlobRegistryContext performs an isolated copy of data.
	OwnPtr<BlobRegistryContext> context = adoptPtr(new BlobRegistryContext(url, &semaphore));
	callOnMainThread(&blobSizeTaskOnMainThread, context.get());
	semaphore.wait(std::numeric_limits<double>::max());
	resultSize = context->resultSize;
    return resultSize;
}

static void unregisterBlobURLTaskOnMainThread(void* context)
{
    OwnPtr<BlobRegistryContext> blobRegistryContext = adoptPtr(static_cast<BlobRegistryContext*>(context));
    unregisterBlobURLOriginIfNecessaryOnMainThread(blobRegistryContext->url);
    blobRegistry().unregisterBlobURL(blobRegistryContext->url);
}

void ThreadableBlobRegistry::unregisterBlobURL(const KURL& url)
{
    if (isMainThread()) {
        unregisterBlobURLOriginIfNecessaryOnMainThread(url);
        blobRegistry().unregisterBlobURL(url);
    } else {
        OwnPtr<BlobRegistryContext> context = adoptPtr(new BlobRegistryContext(url, nullptr));
        callOnMainThread(&unregisterBlobURLTaskOnMainThread, context.leakPtr());
    }
}

static void registerBlobURLHandleTaskOnMainThread(void* context)
{
    OwnPtr<BlobRegistryContext> blobRegistryContext = adoptPtr(static_cast<BlobRegistryContext*>(context));
    if (isBlobURLContainsNullOrigin(blobRegistryContext->url))
        blobURLReferencesMap().add(blobRegistryContext->url.stringWithoutFragmentIdentifier());
    blobRegistry().registerBlobURLHandle(blobRegistryContext->url);
}

void ThreadableBlobRegistry::registerBlobURLHandle(const KURL& url)
{
    if (isMainThread()) {
        if (isBlobURLContainsNullOrigin(url))
            blobURLReferencesMap().add(url.stringWithoutFragmentIdentifier());
        blobRegistry().registerBlobURLHandle(url);
    } else {
        OwnPtr<BlobRegistryContext> context = adoptPtr(new BlobRegistryContext(url, nullptr));
        callOnMainThread(&registerBlobURLHandleTaskOnMainThread, context.leakPtr());
    }
}

static void unregisterBlobURLHandleTaskOnMainThread(void* context)
{
    OwnPtr<BlobRegistryContext> blobRegistryContext = adoptPtr(static_cast<BlobRegistryContext*>(context));
    unregisterBlobURLOriginIfNecessaryOnMainThread(blobRegistryContext->url);
    blobRegistry().unregisterBlobURLHandle(blobRegistryContext->url);
}

void ThreadableBlobRegistry::unregisterBlobURLHandle(const KURL& url)
{
    if (isMainThread()) {
        unregisterBlobURLOriginIfNecessaryOnMainThread(url);
        blobRegistry().unregisterBlobURLHandle(url);
    } else {
        OwnPtr<BlobRegistryContext> context = adoptPtr(new BlobRegistryContext(url, nullptr));
        callOnMainThread(&unregisterBlobURLHandleTaskOnMainThread, context.leakPtr());
    };
}

static void cachedOriginTaskOnMainThread(void* context)
{
    BlobRegistryContext* blobRegistryContext = static_cast<BlobRegistryContext*>(context);
    if (auto* origin = originMap().get<StringViewHashTranslator>(blobRegistryContext->url.viewWithoutFragmentIdentifier()))
    	blobRegistryContext->resultOrigin = origin->isolatedCopy();
    blobRegistryContext->semaphore->signal();
}

PassRefPtr<SecurityOrigin> ThreadableBlobRegistry::getCachedOrigin(const KURL& url)
{
    ASSERT(url.protocolIsBlob());
	RefPtr<SecurityOrigin> cachedOrigin;

    if (isMainThread()) {
    	cachedOrigin = originMap().get<StringViewHashTranslator>(url.viewWithoutFragmentIdentifier());
    } else {
		BinarySemaphore semaphore;
		// BlobRegistryContext performs an isolated copy of data.
		OwnPtr<BlobRegistryContext> context = adoptPtr(new BlobRegistryContext(url, &semaphore));
		callOnMainThread(&cachedOriginTaskOnMainThread, context.get());
		semaphore.wait(std::numeric_limits<double>::max());
		cachedOrigin = context->resultOrigin.release();
    }
    if (cachedOrigin)
        return cachedOrigin;

    if (!isBlobURLContainsNullOrigin(url))
        return nullptr;

    // If we do not have a cached origin for null blob URLs, we use a unique origin.
    return SecurityOrigin::createUnique();
}

#else

void ThreadableBlobRegistry::registerBlobURL(const KURL&, PassOwnPtr<BlobData>)
{
}

void ThreadableBlobRegistry::registerBlobURL(SecurityOrigin*, const KURL&, const KURL&)
{
}

void ThreadableBlobRegistry::registerBlobURLForSlice(const URL& newURL, const URL& srcURL, long long start, long long end)
{
}

void ThreadableBlobRegistry::unregisterBlobURL(const KURL&)
{
}

unsigned long long ThreadableBlobRegistry::blobSize(const URL&)
{
    return 0;
}

PassRefPtr<SecurityOrigin> ThreadableBlobRegistry::getCachedOrigin(const KURL& url)
{
    return 0;
}

#endif // ENABL(BLOB)

} // namespace WebCore
