/*
 * Copyright (C) 2021 Apple 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:
 * 1.  Redistributions of source code must retain the above copyright
 *     notice, this list of conditions and the following disclaimer.
 * 2.  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.
 *
 * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS 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 APPLE INC. OR ITS 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 "NetworkProcessConnection.h"

#include "ArgumentCoders.h"
#include "Decoder.h"
#include "HandleMessage.h"
#include "NetworkProcessConnectionMessages.h"
#if ENABLE(SHAREABLE_RESOURCE)
#include "ShareableResource.h"
#endif
#include "WebCoreArgumentCoders.h"
#include <JavaScriptCore/ConsoleTypes.h>
#if HAVE(COOKIE_CHANGE_LISTENER_API)
#include <WebCore/Cookie.h>
#endif
#include <WebCore/HTTPCookieAcceptPolicy.h>
#include <WebCore/MessagePortChannelProvider.h>
#include <WebCore/MessagePortIdentifier.h>
#if ENABLE(WEB_RTC)
#include <WebCore/RTCDataChannelIdentifier.h>
#endif
#include <WebCore/ResourceError.h>
#include <WebCore/ResourceLoaderIdentifier.h>
#if ENABLE(SHAREABLE_RESOURCE)
#include <WebCore/ResourceRequest.h>
#endif
#include <WebCore/ResourceResponse.h>
#if ENABLE(WEB_RTC)
#include <optional>
#endif
#if HAVE(COOKIE_CHANGE_LISTENER_API)
#include <wtf/Vector.h>
#endif
#include <wtf/text/WTFString.h>

namespace Messages {

namespace NetworkProcessConnection {

#if ENABLE(WEB_RTC)

void ConnectToRTCDataChannelRemoteSource::callReply(IPC::Decoder& decoder, CompletionHandler<void(std::optional<bool>&&)>&& completionHandler)
{
    std::optional<std::optional<bool>> result;
    decoder >> result;
    if (!result) {
        ASSERT_NOT_REACHED();
        cancelReply(WTFMove(completionHandler));
        return;
    }
    completionHandler(WTFMove(*result));
}

void ConnectToRTCDataChannelRemoteSource::cancelReply(CompletionHandler<void(std::optional<bool>&&)>&& completionHandler)
{
    completionHandler(IPC::AsyncReplyError<std::optional<bool>>::create());
}

void ConnectToRTCDataChannelRemoteSource::send(UniqueRef<IPC::Encoder>&& encoder, IPC::Connection& connection, const std::optional<bool>& result)
{
    encoder.get() << result;
    connection.sendSyncReply(WTFMove(encoder));
}

#endif

void CheckProcessLocalPortForActivity::callReply(IPC::Decoder& decoder, CompletionHandler<void(WebCore::MessagePortChannelProvider::HasActivity&&)>&& completionHandler)
{
    std::optional<WebCore::MessagePortChannelProvider::HasActivity> hasActivity;
    decoder >> hasActivity;
    if (!hasActivity) {
        ASSERT_NOT_REACHED();
        cancelReply(WTFMove(completionHandler));
        return;
    }
    completionHandler(WTFMove(*hasActivity));
}

void CheckProcessLocalPortForActivity::cancelReply(CompletionHandler<void(WebCore::MessagePortChannelProvider::HasActivity&&)>&& completionHandler)
{
    completionHandler(IPC::AsyncReplyError<WebCore::MessagePortChannelProvider::HasActivity>::create());
}

void CheckProcessLocalPortForActivity::send(UniqueRef<IPC::Encoder>&& encoder, IPC::Connection& connection, const WebCore::MessagePortChannelProvider::HasActivity& hasActivity)
{
    encoder.get() << hasActivity;
    connection.sendSyncReply(WTFMove(encoder));
}

} // namespace NetworkProcessConnection

} // namespace Messages

namespace WebKit {

void NetworkProcessConnection::didReceiveNetworkProcessConnectionMessage(IPC::Connection& connection, IPC::Decoder& decoder)
{
    Ref protectedThis { *this };
#if ENABLE(SHAREABLE_RESOURCE)
    if (decoder.messageName() == Messages::NetworkProcessConnection::DidCacheResource::name())
        return IPC::handleMessage<Messages::NetworkProcessConnection::DidCacheResource>(connection, decoder, this, &NetworkProcessConnection::didCacheResource);
#endif
    if (decoder.messageName() == Messages::NetworkProcessConnection::DidFinishPingLoad::name())
        return IPC::handleMessage<Messages::NetworkProcessConnection::DidFinishPingLoad>(connection, decoder, this, &NetworkProcessConnection::didFinishPingLoad);
    if (decoder.messageName() == Messages::NetworkProcessConnection::DidFinishPreconnection::name())
        return IPC::handleMessage<Messages::NetworkProcessConnection::DidFinishPreconnection>(connection, decoder, this, &NetworkProcessConnection::didFinishPreconnection);
    if (decoder.messageName() == Messages::NetworkProcessConnection::SetOnLineState::name())
        return IPC::handleMessage<Messages::NetworkProcessConnection::SetOnLineState>(connection, decoder, this, &NetworkProcessConnection::setOnLineState);
    if (decoder.messageName() == Messages::NetworkProcessConnection::CookieAcceptPolicyChanged::name())
        return IPC::handleMessage<Messages::NetworkProcessConnection::CookieAcceptPolicyChanged>(connection, decoder, this, &NetworkProcessConnection::cookieAcceptPolicyChanged);
#if HAVE(COOKIE_CHANGE_LISTENER_API)
    if (decoder.messageName() == Messages::NetworkProcessConnection::CookiesAdded::name())
        return IPC::handleMessage<Messages::NetworkProcessConnection::CookiesAdded>(connection, decoder, this, &NetworkProcessConnection::cookiesAdded);
#endif
#if HAVE(COOKIE_CHANGE_LISTENER_API)
    if (decoder.messageName() == Messages::NetworkProcessConnection::CookiesDeleted::name())
        return IPC::handleMessage<Messages::NetworkProcessConnection::CookiesDeleted>(connection, decoder, this, &NetworkProcessConnection::cookiesDeleted);
#endif
#if HAVE(COOKIE_CHANGE_LISTENER_API)
    if (decoder.messageName() == Messages::NetworkProcessConnection::AllCookiesDeleted::name())
        return IPC::handleMessage<Messages::NetworkProcessConnection::AllCookiesDeleted>(connection, decoder, this, &NetworkProcessConnection::allCookiesDeleted);
#endif
#if ENABLE(WEB_RTC)
    if (decoder.messageName() == Messages::NetworkProcessConnection::ConnectToRTCDataChannelRemoteSource::name())
        return IPC::handleMessageAsync<Messages::NetworkProcessConnection::ConnectToRTCDataChannelRemoteSource>(connection, decoder, this, &NetworkProcessConnection::connectToRTCDataChannelRemoteSource);
#endif
    if (decoder.messageName() == Messages::NetworkProcessConnection::CheckProcessLocalPortForActivity::name())
        return IPC::handleMessageAsync<Messages::NetworkProcessConnection::CheckProcessLocalPortForActivity>(connection, decoder, this, &NetworkProcessConnection::checkProcessLocalPortForActivity);
    if (decoder.messageName() == Messages::NetworkProcessConnection::MessagesAvailableForPort::name())
        return IPC::handleMessage<Messages::NetworkProcessConnection::MessagesAvailableForPort>(connection, decoder, this, &NetworkProcessConnection::messagesAvailableForPort);
    if (decoder.messageName() == Messages::NetworkProcessConnection::BroadcastConsoleMessage::name())
        return IPC::handleMessage<Messages::NetworkProcessConnection::BroadcastConsoleMessage>(connection, decoder, this, &NetworkProcessConnection::broadcastConsoleMessage);
    UNUSED_PARAM(connection);
    UNUSED_PARAM(decoder);
#if ENABLE(IPC_TESTING_API)
    if (connection.ignoreInvalidMessageForTesting())
        return;
#endif // ENABLE(IPC_TESTING_API)
    ASSERT_NOT_REACHED_WITH_MESSAGE("Unhandled message %s to %" PRIu64, IPC::description(decoder.messageName()), decoder.destinationID());
}

} // namespace WebKit
