2021-03-23 21:12:55 -05:00
|
|
|
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4; fill-column: 100 -*- */
|
|
|
|
/*
|
|
|
|
* 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/.
|
|
|
|
*/
|
|
|
|
|
|
|
|
#pragma once
|
|
|
|
|
|
|
|
#include <chrono>
|
|
|
|
#include <cstdint>
|
|
|
|
#include <iostream>
|
|
|
|
#include <fstream>
|
|
|
|
#include <memory>
|
2021-03-23 22:57:53 -05:00
|
|
|
#include <condition_variable>
|
|
|
|
#include <mutex>
|
2021-03-23 21:12:55 -05:00
|
|
|
#include <sstream>
|
|
|
|
#include <string>
|
|
|
|
|
|
|
|
#include "Common.hpp"
|
2021-03-23 22:57:53 -05:00
|
|
|
#include <common/MessageQueue.hpp>
|
2021-03-23 21:12:55 -05:00
|
|
|
#include "NetUtil.hpp"
|
|
|
|
#include <net/Socket.hpp>
|
|
|
|
#include <net/HttpRequest.hpp>
|
|
|
|
#include <net/WebSocketHandler.hpp>
|
|
|
|
#include <utility>
|
|
|
|
#if ENABLE_SSL
|
|
|
|
#include <net/SslSocket.hpp>
|
|
|
|
#endif
|
|
|
|
#include "Log.hpp"
|
|
|
|
#include "Util.hpp"
|
|
|
|
|
|
|
|
// This is a partial implementation of RFC 6455
|
|
|
|
// The WebSocket Protocol.
|
|
|
|
|
|
|
|
namespace http
|
|
|
|
{
|
2021-03-23 22:57:53 -05:00
|
|
|
/// A client socket for asynchronous Web-Socket protocol.
|
2021-03-23 21:12:55 -05:00
|
|
|
class WebSocketSession final : public WebSocketHandler
|
|
|
|
{
|
|
|
|
public:
|
|
|
|
enum class Protocol
|
|
|
|
{
|
|
|
|
HttpUnencrypted,
|
|
|
|
HttpSsl,
|
|
|
|
};
|
|
|
|
|
|
|
|
private:
|
|
|
|
WebSocketSession(const std::string& hostname, Protocol protocolType, int portNumber)
|
2021-03-23 22:57:53 -05:00
|
|
|
: WebSocketHandler(true)
|
|
|
|
, _host(hostname)
|
2021-03-23 21:12:55 -05:00
|
|
|
, _port(std::to_string(portNumber))
|
|
|
|
, _protocol(protocolType)
|
2021-04-11 14:53:57 -05:00
|
|
|
, _disconnected(true)
|
2021-03-23 21:12:55 -05:00
|
|
|
{
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Returns the given protocol's scheme.
|
|
|
|
static const char* getProtocolScheme(Protocol protocol)
|
|
|
|
{
|
|
|
|
switch (protocol)
|
|
|
|
{
|
|
|
|
case Protocol::HttpUnencrypted:
|
|
|
|
return "ws";
|
|
|
|
case Protocol::HttpSsl:
|
|
|
|
return "wss";
|
|
|
|
}
|
|
|
|
|
|
|
|
return "";
|
|
|
|
}
|
|
|
|
|
|
|
|
public:
|
2021-03-24 22:18:02 -05:00
|
|
|
/// Destroy WebSocketSession.
|
|
|
|
/// Note: must never be called with the owning poll thread still active.
|
2021-03-25 13:11:46 -05:00
|
|
|
~WebSocketSession() { shutdown(); }
|
2021-03-24 22:18:02 -05:00
|
|
|
|
2021-03-23 21:12:55 -05:00
|
|
|
/// Create a new HTTP WebSocketSession to the given host.
|
|
|
|
/// The port defaults to the protocol's default port.
|
|
|
|
static std::shared_ptr<WebSocketSession> create(const std::string& host, Protocol protocol,
|
|
|
|
int port = 0)
|
|
|
|
{
|
|
|
|
port = (port > 0 ? port : getDefaultPort(protocol));
|
|
|
|
return std::shared_ptr<WebSocketSession>(new WebSocketSession(host, protocol, port));
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Create a new HTTP WebSocketSession to the given URI.
|
|
|
|
/// The @uri must include the scheme, e.g. https://domain.com:9980
|
|
|
|
static std::shared_ptr<WebSocketSession> create(const std::string& uri)
|
|
|
|
{
|
2021-03-24 21:38:31 -05:00
|
|
|
std::string scheme;
|
|
|
|
std::string host;
|
|
|
|
std::string port;
|
|
|
|
if (!net::parseUri(uri, scheme, host, port))
|
2021-03-23 21:12:55 -05:00
|
|
|
{
|
2021-03-24 21:38:31 -05:00
|
|
|
LOG_ERR("Invalid URI while creating WebSocketSession: " << uri);
|
2021-03-23 21:12:55 -05:00
|
|
|
return nullptr;
|
|
|
|
}
|
|
|
|
|
2021-03-24 21:38:31 -05:00
|
|
|
const std::string lowerScheme = Util::toLower(scheme);
|
|
|
|
if (!Util::startsWith(lowerScheme, "http") && !Util::startsWith(lowerScheme, "ws"))
|
2021-03-23 21:12:55 -05:00
|
|
|
{
|
2021-03-24 21:38:31 -05:00
|
|
|
LOG_ERR("Unsupported scheme in URI while creating WebSocketSession: " << uri);
|
2021-03-23 21:12:55 -05:00
|
|
|
return nullptr;
|
|
|
|
}
|
|
|
|
|
2021-03-24 21:38:31 -05:00
|
|
|
const bool secure
|
|
|
|
= Util::startsWith(lowerScheme, "https") || Util::startsWith(lowerScheme, "wss");
|
2021-03-23 21:12:55 -05:00
|
|
|
|
2021-03-24 21:38:31 -05:00
|
|
|
const int portInt = port.empty() ? 0 : std::stoi(port);
|
|
|
|
return create(host, secure ? Protocol::HttpSsl : Protocol::HttpUnencrypted, portInt);
|
2021-03-23 21:12:55 -05:00
|
|
|
}
|
|
|
|
|
2021-03-24 22:18:02 -05:00
|
|
|
/// Create a WebSocketSession and make a request to given @url.
|
|
|
|
static std::shared_ptr<WebSocketSession> create(SocketPoll& socketPoll, const std::string& uri,
|
|
|
|
const std::string& url)
|
|
|
|
{
|
|
|
|
auto session = create(uri);
|
|
|
|
if (session)
|
|
|
|
{
|
|
|
|
http::Request req(url);
|
|
|
|
session->asyncRequest(req, socketPoll);
|
|
|
|
}
|
|
|
|
|
|
|
|
return session;
|
|
|
|
}
|
|
|
|
|
2021-03-23 21:12:55 -05:00
|
|
|
/// Returns the given protocol's default port.
|
|
|
|
static int getDefaultPort(Protocol protocol)
|
|
|
|
{
|
|
|
|
switch (protocol)
|
|
|
|
{
|
|
|
|
case Protocol::HttpUnencrypted:
|
|
|
|
return 80;
|
|
|
|
case Protocol::HttpSsl:
|
|
|
|
return 443;
|
|
|
|
}
|
|
|
|
|
|
|
|
return 0;
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Returns the current protocol scheme.
|
|
|
|
const char* getProtocolScheme() const { return getProtocolScheme(_protocol); }
|
|
|
|
|
|
|
|
const std::string& host() const { return _host; }
|
|
|
|
const std::string& port() const { return _port; }
|
|
|
|
Protocol protocol() const { return _protocol; }
|
2021-03-31 16:11:41 -05:00
|
|
|
bool secure() const { return _protocol == Protocol::HttpSsl; }
|
2021-03-23 21:12:55 -05:00
|
|
|
|
2021-03-24 21:30:04 -05:00
|
|
|
bool asyncRequest(http::Request& req, SocketPoll& poll)
|
2021-03-23 21:12:55 -05:00
|
|
|
{
|
|
|
|
LOG_TRC("asyncRequest: " << req.getVerb() << ' ' << host() << ':' << port() << ' '
|
|
|
|
<< req.getUrl());
|
|
|
|
|
2021-03-31 16:11:41 -05:00
|
|
|
return wsRequest(req, host(), port(), secure(), poll);
|
2021-03-23 21:12:55 -05:00
|
|
|
}
|
|
|
|
|
2021-03-31 15:48:43 -05:00
|
|
|
/// Poll for messages and invoke the given callback.
|
|
|
|
/// Returns only when the callback returns true, or,
|
|
|
|
/// when no new messages are received within the given timeout.
|
|
|
|
std::vector<char> poll(const std::function<bool(const std::vector<char>&)>& cb,
|
|
|
|
std::chrono::milliseconds timeout,
|
|
|
|
const std::string& context = std::string())
|
2021-03-23 22:57:53 -05:00
|
|
|
{
|
2021-03-31 15:48:43 -05:00
|
|
|
LOG_DBG(context << "Polling for " << timeout);
|
2021-03-23 22:57:53 -05:00
|
|
|
|
2021-03-31 15:48:43 -05:00
|
|
|
// Note: ideally, this lock will be timed, but that
|
|
|
|
// might prove expensive and we don't expect draining
|
|
|
|
// the queue to take anywhere close to the timeout.
|
2021-04-11 13:00:00 -05:00
|
|
|
std::unique_lock<std::mutex> lock(_inMutex);
|
2021-03-23 22:57:53 -05:00
|
|
|
do
|
|
|
|
{
|
|
|
|
// Drain the queue, first.
|
2021-04-11 13:00:00 -05:00
|
|
|
while (!_inQueue.isEmpty())
|
2021-03-23 22:57:53 -05:00
|
|
|
{
|
2021-04-11 13:00:00 -05:00
|
|
|
std::vector<char> message = _inQueue.pop();
|
2021-03-31 15:48:43 -05:00
|
|
|
if (cb(message))
|
2021-03-23 22:57:53 -05:00
|
|
|
return message;
|
|
|
|
}
|
|
|
|
|
|
|
|
// Timed wait, if we must.
|
2021-04-11 13:00:00 -05:00
|
|
|
} while (_inCv.wait_for(lock, timeout, [this]() { return !_inQueue.isEmpty(); }));
|
2021-03-23 22:57:53 -05:00
|
|
|
|
2021-03-31 15:48:43 -05:00
|
|
|
LOG_DBG(context << "Giving up polling after " << timeout);
|
2021-03-23 22:57:53 -05:00
|
|
|
return std::vector<char>();
|
|
|
|
}
|
|
|
|
|
2021-03-31 15:48:43 -05:00
|
|
|
/// Wait until the given prefix is matched and return the payload.
|
|
|
|
std::vector<char> waitForMessage(const std::string& prefix, std::chrono::milliseconds timeout,
|
|
|
|
const std::string& context = std::string())
|
|
|
|
{
|
|
|
|
LOG_DBG(context << "Waiting for [" << prefix << "] for " << timeout);
|
|
|
|
|
|
|
|
return poll(
|
|
|
|
[&](const std::vector<char>& message) {
|
|
|
|
return matchMessage(prefix, message, context);
|
|
|
|
},
|
|
|
|
timeout, context);
|
|
|
|
}
|
|
|
|
|
2021-04-11 13:00:00 -05:00
|
|
|
/// Send a text message to our peer.
|
|
|
|
void sendMessage(const std::string& msg)
|
|
|
|
{
|
|
|
|
std::unique_lock<std::mutex> lock(_outMutex);
|
|
|
|
_outQueue.put(std::vector<char>(msg.data(), msg.data() + msg.size()));
|
|
|
|
}
|
|
|
|
|
2021-04-11 15:00:08 -05:00
|
|
|
/// Send asynchronous shutdown frame and disconnect socket.
|
|
|
|
void asyncShutdown(SocketPoll& poll)
|
|
|
|
{
|
|
|
|
LOG_TRC("WebSocketSession: queueing shutdown");
|
|
|
|
poll.addCallback([&]() {
|
|
|
|
LOG_TRC("WebSocketSession: shutdown");
|
|
|
|
shutdown(true, "Shutting down");
|
|
|
|
});
|
|
|
|
}
|
|
|
|
|
2021-04-11 14:53:57 -05:00
|
|
|
/// Wait until disconnected.
|
|
|
|
/// Returns true iff we are disconnected, otherwise false,
|
|
|
|
/// if we timed out without disconnecting.
|
|
|
|
bool waitForDisconnection(const std::chrono::milliseconds timeout)
|
|
|
|
{
|
|
|
|
std::unique_lock<std::mutex> lock(_outMutex);
|
|
|
|
|
|
|
|
if (_disconnected)
|
|
|
|
return true;
|
|
|
|
|
|
|
|
_disconnectCv.wait_for(lock, timeout, [this]() { return _disconnected.load(); });
|
|
|
|
return _disconnected;
|
|
|
|
}
|
|
|
|
|
2021-03-23 22:57:53 -05:00
|
|
|
private:
|
|
|
|
void handleMessage(const std::vector<char>& data) override
|
|
|
|
{
|
|
|
|
LOG_DBG("Got message: " << LOOLProtocol::getFirstLine(data));
|
2021-04-11 13:00:00 -05:00
|
|
|
std::unique_lock<std::mutex> lock(_inMutex);
|
|
|
|
_inQueue.put(data);
|
|
|
|
_inCv.notify_one();
|
2021-03-23 22:57:53 -05:00
|
|
|
}
|
|
|
|
|
2021-03-25 13:11:46 -05:00
|
|
|
bool matchMessage(const std::string& prefix, const std::vector<char>& message,
|
|
|
|
const std::string& context)
|
2021-03-23 22:57:53 -05:00
|
|
|
{
|
|
|
|
const auto header = LOOLProtocol::getFirstLine(message);
|
2021-03-25 13:11:46 -05:00
|
|
|
const bool match = LOOLProtocol::matchPrefix(prefix, header);
|
|
|
|
LOG_DBG(context << (match ? "Matched" : "Skipped") << " message [" << prefix
|
|
|
|
<< "]: " << header);
|
|
|
|
return match;
|
2021-03-23 22:57:53 -05:00
|
|
|
}
|
2021-03-23 21:12:55 -05:00
|
|
|
|
2021-04-11 17:42:11 -05:00
|
|
|
int getPollEvents(std::chrono::steady_clock::time_point /*now*/,
|
|
|
|
int64_t& /*timeoutMaxMicroS*/) override
|
|
|
|
{
|
|
|
|
std::unique_lock<std::mutex> lock(_outMutex);
|
|
|
|
if (!_outQueue.isEmpty())
|
|
|
|
return POLLIN | POLLOUT;
|
|
|
|
return POLLIN;
|
|
|
|
}
|
|
|
|
|
2021-04-11 13:00:00 -05:00
|
|
|
void performWrites() override
|
|
|
|
{
|
|
|
|
LOG_TRC("WebSocketSession: performing writes.");
|
|
|
|
|
|
|
|
std::unique_lock<std::mutex> lock(_outMutex);
|
|
|
|
|
|
|
|
std::size_t wrote = 0;
|
|
|
|
try
|
|
|
|
{
|
|
|
|
// Drain the queue, for efficient communication.
|
|
|
|
if (!_outQueue.isEmpty())
|
|
|
|
{
|
|
|
|
std::vector<char> item = _outQueue.get();
|
|
|
|
const auto size = item.size();
|
|
|
|
assert(size && "Zero-sized messages must never be queued for sending.");
|
|
|
|
|
|
|
|
sendTextMessage(item.data(), size);
|
|
|
|
|
|
|
|
wrote += size;
|
|
|
|
LOG_TRC("WebSocketSession: wrote " << size << ", total " << wrote << " bytes.");
|
|
|
|
}
|
|
|
|
}
|
|
|
|
catch (const std::exception& ex)
|
|
|
|
{
|
|
|
|
LOG_ERR("WebSocketSession: Failed to send message: " << ex.what());
|
|
|
|
}
|
|
|
|
|
|
|
|
LOG_TRC("WebSocketSession: performed write, wrote " << wrote << " bytes.");
|
|
|
|
}
|
|
|
|
|
|
|
|
// Make these inaccessible since they must only be called from the poll thread.
|
|
|
|
using WebSocketHandler::sendBinaryMessage;
|
|
|
|
using WebSocketHandler::sendMessage;
|
|
|
|
using WebSocketHandler::sendTextMessage;
|
2021-03-24 22:18:02 -05:00
|
|
|
using WebSocketHandler::shutdown;
|
|
|
|
|
2021-04-11 14:53:57 -05:00
|
|
|
void onConnect(const std::shared_ptr<StreamSocket>& socket) override
|
|
|
|
{
|
|
|
|
_disconnected = false;
|
|
|
|
WebSocketHandler::onConnect(socket);
|
|
|
|
}
|
|
|
|
|
|
|
|
void onDisconnect() override
|
|
|
|
{
|
|
|
|
std::unique_lock<std::mutex> lock(_outMutex);
|
|
|
|
_disconnected = true;
|
|
|
|
_disconnectCv.notify_all();
|
|
|
|
}
|
|
|
|
|
2021-03-23 21:12:55 -05:00
|
|
|
private:
|
|
|
|
const std::string _host;
|
|
|
|
const std::string _port;
|
|
|
|
const Protocol _protocol;
|
|
|
|
Request _request;
|
2021-04-11 13:00:00 -05:00
|
|
|
MessageQueue _inQueue; //< The incoming message queue.
|
|
|
|
std::condition_variable _inCv; //< The incoming queue cond_var.
|
|
|
|
std::mutex _inMutex; //< The incoming queue lock.
|
|
|
|
MessageQueueBase<std::vector<char>> _outQueue; //< The outgoing message queue.
|
|
|
|
std::mutex _outMutex; //< The outgoing queue lock.
|
2021-04-11 14:53:57 -05:00
|
|
|
std::condition_variable _disconnectCv; //< Traps disconnections.
|
|
|
|
std::mutex _disconnectMutex; //< The disconnection event lock.
|
|
|
|
std::atomic_bool _disconnected; //< True iff we are disconnected.
|
2021-03-23 21:12:55 -05:00
|
|
|
};
|
|
|
|
|
|
|
|
} // namespace http
|
|
|
|
|
|
|
|
/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
|