/*
 * 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 "WebProcessProxy.h"

#include "ArgumentCoders.h"
#include "Decoder.h"
#if HAVE(CVDISPLAYLINK)
#include "DisplayLinkObserverID.h"
#endif
#if ENABLE(GPU_PROCESS)
#include "GPUProcessConnectionInfo.h"
#endif
#if ENABLE(GPU_PROCESS)
#include "GPUProcessConnectionParameters.h"
#endif
#include "HandleMessage.h"
#include "NetworkProcessConnectionInfo.h"
#include "SessionState.h"
#if PLATFORM(GTK) || PLATFORM(WPE)
#include "UserMessage.h"
#endif
#if ENABLE(WEB_AUTHN)
#include "WebAuthnProcessConnectionInfo.h"
#endif
#include "WebCoreArgumentCoders.h"
#include "WebProcessProxyMessages.h"
#if HAVE(MEDIA_ACCESSIBILITY_FRAMEWORK)
#include <WebCore/CaptionUserPreferences.h>
#endif
#include <WebCore/FrameIdentifier.h>
#include <WebCore/PageIdentifier.h>
#include <WebCore/PrewarmInformation.h>
#include <WebCore/RegistrableDomain.h>
#include <WebCore/SleepDisablerIdentifier.h>
#if PLATFORM(COCOA)
#include <wtf/Vector.h>
#endif
#include <wtf/text/WTFString.h>

namespace Messages {

namespace WebProcessProxy {

void ShouldTerminate::send(UniqueRef<IPC::Encoder>&& encoder, IPC::Connection& connection, bool shouldTerminate)
{
    encoder.get() << shouldTerminate;
    connection.sendSyncReply(WTFMove(encoder));
}

void GetNetworkProcessConnection::send(UniqueRef<IPC::Encoder>&& encoder, IPC::Connection& connection, const WebKit::NetworkProcessConnectionInfo& connectionInfo)
{
    encoder.get() << connectionInfo;
    connection.sendSyncReply(WTFMove(encoder));
}

#if ENABLE(GPU_PROCESS)

void GetGPUProcessConnection::send(UniqueRef<IPC::Encoder>&& encoder, IPC::Connection& connection, const WebKit::GPUProcessConnectionInfo& connectionInfo)
{
    encoder.get() << connectionInfo;
    connection.sendSyncReply(WTFMove(encoder));
}

#endif

#if ENABLE(WEB_AUTHN)

void GetWebAuthnProcessConnection::send(UniqueRef<IPC::Encoder>&& encoder, IPC::Connection& connection, const WebKit::WebAuthnProcessConnectionInfo& connectionInfo)
{
    encoder.get() << connectionInfo;
    connection.sendSyncReply(WTFMove(encoder));
}

#endif

#if PLATFORM(GTK) || PLATFORM(WPE)

void SendMessageToWebContextWithReply::callReply(IPC::Decoder& decoder, CompletionHandler<void(WebKit::UserMessage&&)>&& completionHandler)
{
    std::optional<WebKit::UserMessage> replyMessage;
    decoder >> replyMessage;
    if (!replyMessage) {
        ASSERT_NOT_REACHED();
        cancelReply(WTFMove(completionHandler));
        return;
    }
    completionHandler(WTFMove(*replyMessage));
}

void SendMessageToWebContextWithReply::cancelReply(CompletionHandler<void(WebKit::UserMessage&&)>&& completionHandler)
{
    completionHandler(IPC::AsyncReplyError<WebKit::UserMessage>::create());
}

void SendMessageToWebContextWithReply::send(UniqueRef<IPC::Encoder>&& encoder, IPC::Connection& connection, const WebKit::UserMessage& replyMessage)
{
    encoder.get() << replyMessage;
    connection.sendSyncReply(WTFMove(encoder));
}

#endif

#if PLATFORM(MAC)

void IsAXAuthenticated::send(UniqueRef<IPC::Encoder>&& encoder, IPC::Connection& connection, bool authenticated)
{
    encoder.get() << authenticated;
    connection.sendSyncReply(WTFMove(encoder));
}

#endif

} // namespace WebProcessProxy

} // namespace Messages

namespace WebKit {

void WebProcessProxy::didReceiveWebProcessProxyMessage(IPC::Connection& connection, IPC::Decoder& decoder)
{
    Ref protectedThis { *this };
    if (decoder.messageName() == Messages::WebProcessProxy::UpdateBackForwardItem::name())
        return IPC::handleMessage<Messages::WebProcessProxy::UpdateBackForwardItem>(connection, decoder, this, &WebProcessProxy::updateBackForwardItem);
    if (decoder.messageName() == Messages::WebProcessProxy::DidDestroyFrame::name())
        return IPC::handleMessage<Messages::WebProcessProxy::DidDestroyFrame>(connection, decoder, this, &WebProcessProxy::didDestroyFrame);
    if (decoder.messageName() == Messages::WebProcessProxy::DidDestroyUserGestureToken::name())
        return IPC::handleMessage<Messages::WebProcessProxy::DidDestroyUserGestureToken>(connection, decoder, this, &WebProcessProxy::didDestroyUserGestureToken);
    if (decoder.messageName() == Messages::WebProcessProxy::EnableSuddenTermination::name())
        return IPC::handleMessage<Messages::WebProcessProxy::EnableSuddenTermination>(connection, decoder, this, &WebProcessProxy::enableSuddenTermination);
    if (decoder.messageName() == Messages::WebProcessProxy::DisableSuddenTermination::name())
        return IPC::handleMessage<Messages::WebProcessProxy::DisableSuddenTermination>(connection, decoder, this, &WebProcessProxy::disableSuddenTermination);
    if (decoder.messageName() == Messages::WebProcessProxy::SetIsHoldingLockedFiles::name())
        return IPC::handleMessage<Messages::WebProcessProxy::SetIsHoldingLockedFiles>(connection, decoder, this, &WebProcessProxy::setIsHoldingLockedFiles);
    if (decoder.messageName() == Messages::WebProcessProxy::DidExceedActiveMemoryLimit::name())
        return IPC::handleMessage<Messages::WebProcessProxy::DidExceedActiveMemoryLimit>(connection, decoder, this, &WebProcessProxy::didExceedActiveMemoryLimit);
    if (decoder.messageName() == Messages::WebProcessProxy::DidExceedInactiveMemoryLimit::name())
        return IPC::handleMessage<Messages::WebProcessProxy::DidExceedInactiveMemoryLimit>(connection, decoder, this, &WebProcessProxy::didExceedInactiveMemoryLimit);
    if (decoder.messageName() == Messages::WebProcessProxy::DidExceedCPULimit::name())
        return IPC::handleMessage<Messages::WebProcessProxy::DidExceedCPULimit>(connection, decoder, this, &WebProcessProxy::didExceedCPULimit);
    if (decoder.messageName() == Messages::WebProcessProxy::StopResponsivenessTimer::name())
        return IPC::handleMessage<Messages::WebProcessProxy::StopResponsivenessTimer>(connection, decoder, this, &WebProcessProxy::stopResponsivenessTimer);
    if (decoder.messageName() == Messages::WebProcessProxy::DidReceiveBackgroundResponsivenessPing::name())
        return IPC::handleMessage<Messages::WebProcessProxy::DidReceiveBackgroundResponsivenessPing>(connection, decoder, this, &WebProcessProxy::didReceiveBackgroundResponsivenessPing);
    if (decoder.messageName() == Messages::WebProcessProxy::MemoryPressureStatusChanged::name())
        return IPC::handleMessage<Messages::WebProcessProxy::MemoryPressureStatusChanged>(connection, decoder, this, &WebProcessProxy::memoryPressureStatusChanged);
    if (decoder.messageName() == Messages::WebProcessProxy::DidExceedInactiveMemoryLimitWhileActive::name())
        return IPC::handleMessage<Messages::WebProcessProxy::DidExceedInactiveMemoryLimitWhileActive>(connection, decoder, this, &WebProcessProxy::didExceedInactiveMemoryLimitWhileActive);
    if (decoder.messageName() == Messages::WebProcessProxy::DidCollectPrewarmInformation::name())
        return IPC::handleMessage<Messages::WebProcessProxy::DidCollectPrewarmInformation>(connection, decoder, this, &WebProcessProxy::didCollectPrewarmInformation);
#if PLATFORM(COCOA)
    if (decoder.messageName() == Messages::WebProcessProxy::CacheMediaMIMETypes::name())
        return IPC::handleMessage<Messages::WebProcessProxy::CacheMediaMIMETypes>(connection, decoder, this, &WebProcessProxy::cacheMediaMIMETypes);
#endif
#if PLATFORM(MAC)
    if (decoder.messageName() == Messages::WebProcessProxy::RequestHighPerformanceGPU::name())
        return IPC::handleMessage<Messages::WebProcessProxy::RequestHighPerformanceGPU>(connection, decoder, this, &WebProcessProxy::requestHighPerformanceGPU);
#endif
#if PLATFORM(MAC)
    if (decoder.messageName() == Messages::WebProcessProxy::ReleaseHighPerformanceGPU::name())
        return IPC::handleMessage<Messages::WebProcessProxy::ReleaseHighPerformanceGPU>(connection, decoder, this, &WebProcessProxy::releaseHighPerformanceGPU);
#endif
#if HAVE(CVDISPLAYLINK)
    if (decoder.messageName() == Messages::WebProcessProxy::StartDisplayLink::name())
        return IPC::handleMessage<Messages::WebProcessProxy::StartDisplayLink>(connection, decoder, this, &WebProcessProxy::startDisplayLink);
#endif
#if HAVE(CVDISPLAYLINK)
    if (decoder.messageName() == Messages::WebProcessProxy::StopDisplayLink::name())
        return IPC::handleMessage<Messages::WebProcessProxy::StopDisplayLink>(connection, decoder, this, &WebProcessProxy::stopDisplayLink);
#endif
#if HAVE(CVDISPLAYLINK)
    if (decoder.messageName() == Messages::WebProcessProxy::SetDisplayLinkPreferredFramesPerSecond::name())
        return IPC::handleMessage<Messages::WebProcessProxy::SetDisplayLinkPreferredFramesPerSecond>(connection, decoder, this, &WebProcessProxy::setDisplayLinkPreferredFramesPerSecond);
#endif
#if PLATFORM(GTK) || PLATFORM(WPE)
    if (decoder.messageName() == Messages::WebProcessProxy::SendMessageToWebContext::name())
        return IPC::handleMessage<Messages::WebProcessProxy::SendMessageToWebContext>(connection, decoder, this, &WebProcessProxy::sendMessageToWebContext);
#endif
#if PLATFORM(GTK) || PLATFORM(WPE)
    if (decoder.messageName() == Messages::WebProcessProxy::SendMessageToWebContextWithReply::name())
        return IPC::handleMessageAsync<Messages::WebProcessProxy::SendMessageToWebContextWithReply>(connection, decoder, this, &WebProcessProxy::sendMessageToWebContextWithReply);
#endif
    if (decoder.messageName() == Messages::WebProcessProxy::DidCreateSleepDisabler::name())
        return IPC::handleMessage<Messages::WebProcessProxy::DidCreateSleepDisabler>(connection, decoder, this, &WebProcessProxy::didCreateSleepDisabler);
    if (decoder.messageName() == Messages::WebProcessProxy::DidDestroySleepDisabler::name())
        return IPC::handleMessage<Messages::WebProcessProxy::DidDestroySleepDisabler>(connection, decoder, this, &WebProcessProxy::didDestroySleepDisabler);
    if (decoder.messageName() == Messages::WebProcessProxy::CreateSpeechRecognitionServer::name())
        return IPC::handleMessage<Messages::WebProcessProxy::CreateSpeechRecognitionServer>(connection, decoder, this, &WebProcessProxy::createSpeechRecognitionServer);
    if (decoder.messageName() == Messages::WebProcessProxy::DestroySpeechRecognitionServer::name())
        return IPC::handleMessage<Messages::WebProcessProxy::DestroySpeechRecognitionServer>(connection, decoder, this, &WebProcessProxy::destroySpeechRecognitionServer);
    if (decoder.messageName() == Messages::WebProcessProxy::SystemBeep::name())
        return IPC::handleMessage<Messages::WebProcessProxy::SystemBeep>(connection, decoder, this, &WebProcessProxy::systemBeep);
#if HAVE(MEDIA_ACCESSIBILITY_FRAMEWORK)
    if (decoder.messageName() == Messages::WebProcessProxy::SetCaptionDisplayMode::name())
        return IPC::handleMessage<Messages::WebProcessProxy::SetCaptionDisplayMode>(connection, decoder, this, &WebProcessProxy::setCaptionDisplayMode);
#endif
#if HAVE(MEDIA_ACCESSIBILITY_FRAMEWORK)
    if (decoder.messageName() == Messages::WebProcessProxy::SetCaptionLanguage::name())
        return IPC::handleMessage<Messages::WebProcessProxy::SetCaptionLanguage>(connection, decoder, this, &WebProcessProxy::setCaptionLanguage);
#endif
    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());
}

bool WebProcessProxy::didReceiveSyncWebProcessProxyMessage(IPC::Connection& connection, IPC::Decoder& decoder, UniqueRef<IPC::Encoder>& replyEncoder)
{
    Ref protectedThis { *this };
    if (decoder.messageName() == Messages::WebProcessProxy::ShouldTerminate::name())
        return IPC::handleMessageSynchronous<Messages::WebProcessProxy::ShouldTerminate>(connection, decoder, replyEncoder, this, &WebProcessProxy::shouldTerminate);
    if (decoder.messageName() == Messages::WebProcessProxy::GetNetworkProcessConnection::name())
        return IPC::handleMessageSynchronous<Messages::WebProcessProxy::GetNetworkProcessConnection>(connection, decoder, replyEncoder, this, &WebProcessProxy::getNetworkProcessConnection);
#if ENABLE(GPU_PROCESS)
    if (decoder.messageName() == Messages::WebProcessProxy::GetGPUProcessConnection::name())
        return IPC::handleMessageSynchronous<Messages::WebProcessProxy::GetGPUProcessConnection>(connection, decoder, replyEncoder, this, &WebProcessProxy::getGPUProcessConnection);
#endif
#if ENABLE(WEB_AUTHN)
    if (decoder.messageName() == Messages::WebProcessProxy::GetWebAuthnProcessConnection::name())
        return IPC::handleMessageSynchronous<Messages::WebProcessProxy::GetWebAuthnProcessConnection>(connection, decoder, replyEncoder, this, &WebProcessProxy::getWebAuthnProcessConnection);
#endif
#if PLATFORM(MAC)
    if (decoder.messageName() == Messages::WebProcessProxy::IsAXAuthenticated::name())
        return IPC::handleMessageSynchronous<Messages::WebProcessProxy::IsAXAuthenticated>(connection, decoder, replyEncoder, this, &WebProcessProxy::isAXAuthenticated);
#endif
    UNUSED_PARAM(connection);
    UNUSED_PARAM(decoder);
    UNUSED_PARAM(replyEncoder);
#if ENABLE(IPC_TESTING_API)
    if (connection.ignoreInvalidMessageForTesting())
        return false;
#endif // ENABLE(IPC_TESTING_API)
    ASSERT_NOT_REACHED_WITH_MESSAGE("Unhandled synchronous message %s to %" PRIu64, description(decoder.messageName()), decoder.destinationID());
    return false;
}

} // namespace WebKit
