提交 8da707fd authored 作者: Iñaki Baz Castillo's avatar Iñaki Baz Castillo

Lot of work...

上级 56fe7f4c
......@@ -3,6 +3,9 @@
const EventEmitter = require('events').EventEmitter;
const logger = require('./logger')('Peer');
const utils = require('./utils');
const errors = require('./errors');
const Transport = require('./Transport');
class Peer extends EventEmitter
{
......@@ -21,6 +24,9 @@ class Peer extends EventEmitter
// Channel instance
this._channel = channel;
// Set of Transport instances
this._transports = new Set();
// Closed flag
this._closed = false;
......@@ -39,12 +45,15 @@ class Peer extends EventEmitter
this._closed = true;
// Close every Transport
this._transports.forEach((transport) => transport.close(undefined, true));
if (!dontSendChannel)
{
let data =
{
roomId: this._roomId,
peerId: this._peerId
roomId : this._roomId,
peerId : this._peerId
};
// Send Channel request
......@@ -72,8 +81,8 @@ class Peer extends EventEmitter
let data =
{
roomId: this._roomId,
peerId: this._peerId
roomId : this._roomId,
peerId : this._peerId
};
return this._channel.request('dumpPeer', data)
......@@ -90,6 +99,50 @@ class Peer extends EventEmitter
throw error;
});
}
/**
* Create a Transport
* @param {Object} options Transport options
* @param {Boolean} options.udp Listen UDP (default true)
* @param {Boolean} options.tcp Listen TCP (default true)
* @return {Promise}
*/
createTransport(options)
{
logger.debug('createTransport() [options:%o]', options);
if (this._closed)
return Promise.reject(errors.Closed('peer closed'));
options = utils.cloneObject(options);
let transportId = utils.randomNumber();
options.roomId = this._roomId;
options.peerId = this._peerId;
options.transportId = transportId;
return this._channel.request('createTransport', options)
.then((data) =>
{
logger.debug('"createTransport" request succeeded');
// Create a Transport instance
var transport = new Transport(options, data, this._channel);
// Store the Transport instance and remove it when closed
this._transports.add(transport);
transport.on('close', () => this._transports.delete(transport));
return transport;
})
.catch((error) =>
{
logger.error('"createTransport" request failed [status:%s, error:"%s"]', error.status, error.message);
throw error;
});
}
}
module.exports = Peer;
......@@ -45,14 +45,14 @@ class Room extends EventEmitter
// Close every Peer
for (let peer of this._peers.values())
{
peer.close(null, true);
peer.close(undefined, true);
}
if (!dontSendChannel)
{
let data =
{
roomId: this._roomId
roomId : this._roomId
};
// Send Channel request
......@@ -80,7 +80,7 @@ class Room extends EventEmitter
let data =
{
roomId: this._roomId
roomId : this._roomId
};
return this._channel.request('dumpRoom', data)
......
......@@ -124,7 +124,7 @@ class Server extends EventEmitter
{
let json =
{
workers: {}
workers : {}
};
for (let data of datas)
......
'use strict';
const EventEmitter = require('events').EventEmitter;
const logger = require('./logger')('Transport');
class Transport extends EventEmitter
{
constructor(options, data, channel)
{
logger.debug('constructor() [options:%o, data:%o]', options, data);
super();
// Room identificator
this._roomId = options.roomId;
// Peer identificator
this._peerId = options.peerId;
// Transport identificator
this._transportId = options.transportId;
// Transport data provided by the worker
this._data = data;
// Channel instance
this._channel = channel;
// Closed flag
this._closed = false;
// TODO: subscribe to channel notifications from the worker
}
/**
* Close the Transport
*/
close(error, dontSendChannel)
{
logger.debug('close() [error:%s]', error);
if (this._closed)
return;
this._closed = true;
if (!dontSendChannel)
{
let data =
{
roomId : this._roomId,
peerId : this._peerId,
transportId : this._transportId
};
// Send Channel request
this._channel.request('closeTransport', data)
.then(() =>
{
logger.debug('"closeTransport" request succeeded');
})
.catch((error) =>
{
logger.error('"closeTransport" request failed [status:%s, error:"%s"]', error.status, error.message);
});
}
this.emit('close', error);
}
/**
* Dump the Transport
* @return {Promise}
*/
dump()
{
logger.debug('dump()');
let data =
{
roomId : this._roomId,
peerId : this._peerId,
transportId : this._transportId
};
return this._channel.request('dumpTransport', data)
.then((data) =>
{
logger.debug('"dumpTransport" request succeeded');
return data;
})
.catch((error) =>
{
logger.error('"dumpTransport" request failed [status:%s, error:"%s"]', error.status, error.message);
throw error;
});
}
}
module.exports = Transport;
......@@ -116,7 +116,7 @@ class Worker extends EventEmitter
logger.debug('close() [error:%s]', error);
// Close every Room
this._rooms.forEach((room) => room.close(null, true));
this._rooms.forEach((room) => room.close(undefined, true));
// Kill mediasoup-worker process (let it some time so previous
// requests are properly sent and replied)
......
......@@ -22,7 +22,7 @@ module.exports =
cloneObject: (obj) =>
{
if (!obj || typeof obj !== 'object')
if (!obj || typeof obj !== 'object' || Array.isArray(obj))
return {};
else
return clone(obj, false);
......
......@@ -23,7 +23,10 @@ namespace Channel
dumpRoom,
createPeer,
closePeer,
dumpPeer
dumpPeer,
createTransport,
closeTransport,
dumpTransport
};
private:
......
......@@ -17,7 +17,7 @@ public:
~Loop();
private:
RTC::Room* GetRoomFromRequest(Channel::Request* request, unsigned int* roomId);
RTC::Room* GetRoomFromRequest(Channel::Request* request, unsigned int* roomId = nullptr);
void Close();
/* Methods inherited from SignalsHandler::Listener. */
......
#ifndef MS_RTC_DTLS_HANDLER_H
#define MS_RTC_DTLS_HANDLER_H
#ifndef MS_RTC_DTLS_AGENT_H
#define MS_RTC_DTLS_AGENT_H
#include "common.h"
#include "handles/Timer.h"
......@@ -15,7 +15,7 @@
namespace RTC
{
class DTLSHandler : public Timer::Listener
class DTLSAgent : public Timer::Listener
{
private:
struct SrtpProfileMapEntry
......@@ -30,14 +30,14 @@ namespace RTC
public:
// NOTE: The caller MUST NOT call Reset() or Close() during the
// onOutgoingDTLSData() callback.
virtual void onOutgoingDTLSData(DTLSHandler* dtlsHandler, const MS_BYTE* data, size_t len) = 0;
virtual void onOutgoingDTLSData(DTLSAgent* dtlsAgent, const MS_BYTE* data, size_t len) = 0;
// NOTE: The caller MUST NOT call any method during the onDTLSConnected,
// onDTLSDisconnected or onDTLSFailed callbacks.
virtual void onDTLSConnected(DTLSHandler* dtlsHandler) = 0;
virtual void onDTLSDisconnected(DTLSHandler* dtlsHandler) = 0;
virtual void onDTLSFailed(DTLSHandler* dtlsHandler) = 0;
virtual void onSRTPKeyMaterial(DTLSHandler* dtlsHandler, RTC::SRTPProfile srtp_profile, MS_BYTE* srtp_local_key, size_t srtp_local_key_len, MS_BYTE* srtp_remote_key, size_t srtp_remote_key_len) = 0;
virtual void onDTLSApplicationData(DTLSHandler* dtlsHandler, const MS_BYTE* data, size_t len) = 0;
virtual void onDTLSConnected(DTLSAgent* dtlsAgent) = 0;
virtual void onDTLSDisconnected(DTLSAgent* dtlsAgent) = 0;
virtual void onDTLSFailed(DTLSAgent* dtlsAgent) = 0;
virtual void onSRTPKeyMaterial(DTLSAgent* dtlsAgent, RTC::SRTPProfile srtp_profile, MS_BYTE* srtp_local_key, size_t srtp_local_key_len, MS_BYTE* srtp_remote_key, size_t srtp_remote_key_len) = 0;
virtual void onDTLSApplicationData(DTLSAgent* dtlsAgent, const MS_BYTE* data, size_t len) = 0;
};
public:
......@@ -63,8 +63,8 @@ namespace RTC
static MS_BYTE sslReadBuffer[];
public:
DTLSHandler(Listener* listener);
virtual ~DTLSHandler();
DTLSAgent(Listener* listener);
virtual ~DTLSAgent();
void Run(RTC::DTLSRole role);
void SetRemoteFingerprint(RTC::FingerprintHash hash, std::string& fingerprint);
......@@ -117,7 +117,7 @@ namespace RTC
/* Inline static methods. */
inline
bool DTLSHandler::IsDTLS(const MS_BYTE* data, size_t len)
bool DTLSAgent::IsDTLS(const MS_BYTE* data, size_t len)
{
return (
// Minimum DTLS record length is 13 bytes.
......@@ -130,13 +130,13 @@ namespace RTC
/* Inline instance methods. */
inline
bool DTLSHandler::IsConnected()
bool DTLSAgent::IsConnected()
{
return this->isConnected;
}
inline
bool DTLSHandler::IsRunning()
bool DTLSAgent::IsRunning()
{
return this->isRunning;
}
......
......@@ -25,33 +25,33 @@ namespace RTC
};
public:
ICEServer(Listener* listener);
ICEServer(Listener* listener, std::string& usernameFragment, std::string password);
void ProcessSTUNMessage(RTC::STUNMessage* msg, RTC::TransportSource* source);
std::string& GetLocalUsername();
std::string& GetLocalPassword();
void Close();
void ProcessSTUNMessage(RTC::STUNMessage* msg, RTC::TransportSource* source);
std::string& GetUsernameFragment();
std::string& GetPassword();
private:
// Passed by argument.
Listener* listener = nullptr;
// Others.
std::string localUsername;
std::string localPassword;
std::string usernameFragment;
std::string password;
};
/* Inline methods. */
inline
std::string& ICEServer::GetLocalUsername()
std::string& ICEServer::GetUsernameFragment()
{
return this->localUsername;
return this->usernameFragment;
}
inline
std::string& ICEServer::GetLocalPassword()
std::string& ICEServer::GetPassword()
{
return this->localPassword;
return this->password;
}
}
......
#ifndef MS_RTC_ICE_TRANSPORT_H
#define MS_RTC_ICE_TRANSPORT_H
#include "common.h"
#include "RTC/IceCandidate.h"
#include "RTC/ICEServer.h"
#include "RTC/STUNMessage.h"
#include "RTC/TransportSource.h"
#include "RTC/UDPSocket.h"
#include "RTC/TCPServer.h"
#include "RTC/TCPConnection.h"
#include <string>
#include <vector>
#include <json/json.h>
namespace RTC
{
class ICETransport :
public RTC::ICEServer::Listener,
public RTC::UDPSocket::Listener,
public RTC::TCPServer::Listener,
public RTC::TCPConnection::Reader
{
public:
class Listener
{
public:
// TODO
};
public:
enum class IceComponent
{
RTP = 1,
RTCP = 2
};
public:
typedef struct IceParameters
{
std::string usernameFragment;
std::string password;
} IceParameters;
public:
ICETransport(Listener* listener, Json::Value& data);
virtual ~ICETransport();
void Close();
Json::Value toJson();
IceComponent GetIceComponent(); // TODO: needed?
IceParameters* GetIceLocalParameters(); // TODO: needed?
std::vector<IceCandidate>& GetIceLocalCandidates();
// ICETransport* CreateAssociatedGatherer(); // TODO: let's see.
/* Pure virtual methods inherited from RTC::ICEServer::Listener. */
public:
virtual void onOutgoingSTUNMessage(RTC::ICEServer* iceServer, RTC::STUNMessage* msg, RTC::TransportSource* source) override;
virtual void onICEValidPair(RTC::ICEServer* iceServer, RTC::TransportSource* source, bool has_use_candidate) override;
/* Private methods to unify UDP and TCP behavior. */
private:
void onSTUNDataRecv(RTC::TransportSource* source, const MS_BYTE* data, size_t len);
void onDTLSDataRecv(RTC::TransportSource* source, const MS_BYTE* data, size_t len);
void onRTPDataRecv(RTC::TransportSource* source, const MS_BYTE* data, size_t len);
void onRTCPDataRecv(RTC::TransportSource* source, const MS_BYTE* data, size_t len);
/* Pure virtual methods inherited from RTC::UDPSocket::Listener. */
public:
virtual void onSTUNDataRecv(RTC::UDPSocket *socket, const MS_BYTE* data, size_t len, const struct sockaddr* remote_addr) override;
virtual void onDTLSDataRecv(RTC::UDPSocket *socket, const MS_BYTE* data, size_t len, const struct sockaddr* remote_addr) override;
virtual void onRTPDataRecv(RTC::UDPSocket *socket, const MS_BYTE* data, size_t len, const struct sockaddr* remote_addr) override;
virtual void onRTCPDataRecv(RTC::UDPSocket *socket, const MS_BYTE* data, size_t len, const struct sockaddr* remote_addr) override;
/* Pure virtual methods inherited from RTC::TCPServer::Listener. */
public:
virtual void onRTCTCPConnectionClosed(RTC::TCPServer* tcpServer, RTC::TCPConnection* connection, bool is_closed_by_peer) override;
/* Pure virtual methods inherited from RTC::TCPConnection::Listener. */
public:
virtual void onSTUNDataRecv(RTC::TCPConnection *connection, const MS_BYTE* data, size_t len) override;
virtual void onDTLSDataRecv(RTC::TCPConnection *connection, const MS_BYTE* data, size_t len) override;
virtual void onRTPDataRecv(RTC::TCPConnection *connection, const MS_BYTE* data, size_t len) override;
virtual void onRTCPDataRecv(RTC::TCPConnection *connection, const MS_BYTE* data, size_t len) override;
private:
// Passed by argument.
Listener* listener = nullptr;
// Allocated by this.
RTC::ICEServer* iceServer = nullptr;
std::vector<RTC::UDPSocket*> udpSockets;
std::vector<RTC::TCPServer*> tcpServers;
// Others.
IceComponent iceComponent = IceComponent::RTP;
IceParameters iceLocalParameters;
std::vector<IceCandidate> iceLocalCandidates;
};
/* Inline methods. */
inline
ICETransport::IceParameters* ICETransport::GetIceLocalParameters()
{
return &(this->iceLocalParameters);
}
}
#endif
#ifndef MS_RTC_ICE_CANDIDATE_H
#define MS_RTC_ICE_CANDIDATE_H
#include "common.h"
#include "RTC/UDPSocket.h"
#include "RTC/TCPServer.h"
#include <string>
#include <json/json.h>
namespace RTC
{
class IceCandidate
{
public:
enum class IceComponent
{
RTP = 1,
RTCP = 2
};
public:
enum class IceProtocol
{
UDP = 1,
TCP
};
public:
enum class IceCandidateType
{
HOST = 1
};
public:
enum class IceTcpCandidateType
{
PASSIVE = 1
};
public:
IceCandidate(RTC::UDPSocket* udpSocket);
IceCandidate(RTC::TCPServer* tcpServer);
Json::Value toJson();
private:
// Others.
std::string foundation;
unsigned long priority;
std::string ip;
IceProtocol protocol;
MS_PORT port;
IceCandidateType type;
IceTcpCandidateType tcpType;
};
/* Inline methods. */
inline
IceCandidate::IceCandidate(RTC::UDPSocket* udpSocket) :
foundation("udpcandidate"),
ip(udpSocket->GetLocalIP()),
protocol(IceProtocol::UDP),
port(udpSocket->GetLocalPort()),
type(IceCandidateType::HOST)
{}
inline
IceCandidate::IceCandidate(RTC::TCPServer* tcpServer) :
foundation("tcpcandidate"),
ip(tcpServer->GetLocalIP()),
protocol(IceProtocol::TCP),
port(tcpServer->GetLocalPort()),
type(IceCandidateType::HOST),
tcpType(IceTcpCandidateType::PASSIVE)
{}
inline
Json::Value IceCandidate::toJson()
{
Json::Value data;
data["foundation"] = this->foundation;
data["priority"] = (unsigned int)this->priority;
data["ip"] = this->ip;
data["port"] = this->port;
if (this->protocol == IceProtocol::UDP)
data["protocol"] = "udp";
else
data["protocol"] = "tcp";
if (this->type == IceCandidateType::HOST)
data["type"] = "host";
if (this->protocol == IceProtocol::TCP)
{
if (this->tcpType == IceTcpCandidateType::PASSIVE)
data["tcpType"] = "passive";
}
return data;
}
}
#endif
#ifndef MS_RTC_PEER_H
#define MS_RTC_PEER_H
#include "RTC/Transport.h"
#include "RTC/ICETransport.h"
#include "RTC/RTPPacket.h"
#include "RTC/RTCPPacket.h"
#include "Channel/Request.h"
#include <string>
#include <json/json.h>
namespace RTC
{
class Peer : public RTC::Transport::Listener
class Peer :
public RTC::ICETransport::Listener
{
public:
class Listener
{
public:
virtual void onRTPPacket(RTC::Peer* peer, RTC::RTPPacket* packet) = 0;
virtual void onRTCPPacket(RTC::Peer* peer, RTC::RTCPPacket* packet) = 0;
virtual void onPeerClosed(RTC::Peer* peer) = 0;
};
public:
Peer(Listener* listener, std::string& peerId, Json::Value& data);
virtual ~Peer();
void SendRTPPacket(RTC::RTPPacket* packet);
void SendRTCPPacket(RTC::RTCPPacket* packet);
Json::Value Dump();
void Close();
Json::Value Dump();
void HandleRequest(Channel::Request* request);
/* Pure virtual methods inherited from RTC::Transport::Listener. */
/* Pure virtual methods inherited from RTC::ICETransport::Listener. */
public:
virtual void onRTPPacket(RTC::Transport* transport, RTC::RTPPacket* packet) override;
virtual void onRTCPPacket(RTC::Transport* transport, RTC::RTCPPacket* packet) override;
// TODO
public:
// Passed by argument.
......@@ -41,7 +40,8 @@ namespace RTC
// Passed by argument.
Listener* listener = nullptr;
// Others.
RTC::Transport* transport = nullptr;
// TODO: it must be a unordered_map.
RTC::ICETransport* iceTransport = nullptr;
};
}
......
......@@ -2,8 +2,6 @@
#define MS_RTC_ROOM_H
#include "RTC/Peer.h"
#include "RTC/RTPPacket.h"
#include "RTC/RTCPPacket.h"
#include "Channel/Request.h"
#include <string>
#include <unordered_map>
......@@ -17,19 +15,16 @@ namespace RTC
Room(unsigned int roomId, Json::Value& data);
virtual ~Room();
void HandleCreatePeerRequest(Channel::Request* request);
void HandleClosePeerRequest(Channel::Request* request);
void HandleDumpPeerRequest(Channel::Request* request);
Json::Value Dump();
void Close();
Json::Value Dump();
void HandleRequest(Channel::Request* request);
private:
RTC::Peer* GetPeerFromRequest(Channel::Request* request, std::string* peerId);
RTC::Peer* GetPeerFromRequest(Channel::Request* request, std::string* peerId = nullptr);
/* Pure virtual methods inherited from RTC::Peer::Listener. */
public:
virtual void onRTPPacket(RTC::Peer* peer, RTC::RTPPacket* packet) override;
virtual void onRTCPPacket(RTC::Peer* peer, RTC::RTCPPacket* packet) override;
virtual void onPeerClosed(RTC::Peer* peer) override;
public:
// Passed by argument.
......
#ifndef MS_RTC_STREAM_H
#define MS_RTC_STREAM_H
#include "common.h"
#include "RTC/RTPPacket.h"
#include "RTC/RTCPPacket.h"
#include <unordered_set>
namespace RTC
{
class Stream
{
public:
Stream();
~Stream();
void Close();
private:
MS_4BYTES ssrc = 0;
std::unordered_set<MS_BYTE> payloads;
};
}
#endif
......@@ -21,8 +21,8 @@ namespace RTC
public:
static void ClassInit();
static RTC::TCPServer* New(int address_family);
static void NewPair(int address_family, RTC::TCPServer* servers[]);
static RTC::TCPServer* Factory(Listener* listener, RTC::TCPConnection::Reader* reader, int address_family);
static void PairFactory(Listener* listener, RTC::TCPConnection::Reader* reader, int address_family, RTC::TCPServer* servers[]);
private:
static void RandomizePort(int address_family, uv_tcp_t* uvHandles[], bool pair);
......@@ -37,9 +37,7 @@ namespace RTC
static AvailablePorts availableIPv6Ports;
public:
TCPServer(uv_tcp_t* uvHandle);
void SetListeners(Listener* listener, RTC::TCPConnection::Reader* reader);
TCPServer(Listener* listener, RTC::TCPConnection::Reader* reader, uv_tcp_t* uvHandle);
/* Pure virtual methods inherited from ::TCPServer. */
public:
......@@ -53,15 +51,6 @@ namespace RTC
Listener* listener = nullptr;
RTC::TCPConnection::Reader* reader = nullptr;
};
/* Inline methods. */
inline
void TCPServer::SetListeners(Listener* listener, RTC::TCPConnection::Reader* reader)
{
this->listener = listener;
this->reader = reader;
}
}
#endif
#ifndef MS_RTC_TRANSPORT_H
#define MS_RTC_TRANSPORT_H
#include "common.h"
#include "RTC/TransportSource.h"
#include "RTC/UDPSocket.h"
#include "RTC/TCPServer.h"
#include "RTC/TCPConnection.h"
#include "RTC/ICEServer.h"
#include "RTC/STUNMessage.h"
#include "RTC/DTLSRole.h"
#include "RTC/DTLSHandler.h"
#include "RTC/RTPPacket.h"
#include "RTC/RTCPPacket.h"
#include "RTC/SRTPProfile.h"
#include "RTC/SRTPSession.h"
#include <vector>
#include <list>
#include <string>
namespace RTC
{
/**
* A RTC::Transport handles (in the most complex case as in WebRTC):
* - A RTC::ICEServer to handle received ICE requests and notify ICE connections.
* - A RTC::DTLSHandler to handle DTLS packets and notify the DTLS connection
* state along with SRTP keys material.
* - Many RTC::UDPSocket or RTC::TCPServer instances to listen for data coming
* from the peer.
* - A pair of RTC::SRTPSession instances for both outbound and inbound traffic
* that encrypt/decrypt SRTP and SRTCP packets.
* - A list of validated RTC::TransportSource instances (UDP tuple or TCP
* connection) from which incoming data is accepted (otherwise discarded).
* - A RTC::TransportSource marked as "sending source" which is the chosen one
* to send data to the peer.
*
* Considerations:
* - Received ICE requests trigger ICE responses that are sent back to the peer
* through the same RTC::TransportSource from which the requests were received.
* - Outgoing DTLS data is sent to the currently selected sending source.
* - The sending source is updated at any time a packet is received from a valid
* source that does not match the current sending source.
* - The Reset() method clear all the valid sources, resets the DTLS status and
* closes the SRTP sessions.
*/
class Transport :
public RTC::UDPSocket::Listener,
public RTC::TCPServer::Listener,
public RTC::TCPConnection::Reader,
public RTC::ICEServer::Listener,
public RTC::DTLSHandler::Listener
{
public:
class Listener
{
public:
virtual void onRTPPacket(RTC::Transport* transport, RTC::RTPPacket* packet) = 0;
virtual void onRTCPPacket(RTC::Transport* transport, RTC::RTCPPacket* packet) = 0;
};
public:
// NOTE: Maximum value is 1<<31.
enum Flag
{
ICE = 1<<0,
DTLS = 1<<1,
SRTP = 1<<2
};
public:
static Transport* NewWebRTC(Listener* listener);
private:
static size_t maxSources;
public:
Transport(Listener* listener, int flags);
virtual ~Transport();
void AddUDPSocket(RTC::UDPSocket* socket);
void AddTCPServer(RTC::TCPServer* server);
void Reset();
void Close();
void SetLocalDTLSRole(RTC::DTLSRole role);
void SetRemoteDTLSFingerprint(RTC::FingerprintHash hash, std::string& fingerprint);
void SetLocalSRTPKey(SRTPProfile srtp_profile, MS_BYTE* srtp_local_key, size_t srtp_local_key_len);
void SetRemoteSRTPKey(SRTPProfile srtp_profile, MS_BYTE* srtp_remote_key, size_t srtp_remote_key_len);
void SendRTPPacket(RTC::RTPPacket* packet);
void SendRTCPPacket(RTC::RTCPPacket* packet);
bool IsReadyForMedia();
void Dump();
private:
bool HasFlagICE();
bool HasFlagDTLS();
bool HasFlagSRTP();
bool SetSendingSource(RTC::TransportSource* source);
bool IsValidSource(RTC::TransportSource* source);
bool RemoveSource(RTC::TransportSource* source);
void RunDTLSHandlerIfReady();
/* Private methods to unify UDP and TCP behavior. */
private:
void onSTUNDataRecv(RTC::TransportSource* source, const MS_BYTE* data, size_t len);
void onDTLSDataRecv(RTC::TransportSource* source, const MS_BYTE* data, size_t len);
void onRTPDataRecv(RTC::TransportSource* source, const MS_BYTE* data, size_t len);
void onRTCPDataRecv(RTC::TransportSource* source, const MS_BYTE* data, size_t len);
/* Pure virtual methods inherited from RTC::UDPSocket::Listener. */
public:
virtual void onSTUNDataRecv(RTC::UDPSocket *socket, const MS_BYTE* data, size_t len, const struct sockaddr* remote_addr) override;
virtual void onDTLSDataRecv(RTC::UDPSocket *socket, const MS_BYTE* data, size_t len, const struct sockaddr* remote_addr) override;
virtual void onRTPDataRecv(RTC::UDPSocket *socket, const MS_BYTE* data, size_t len, const struct sockaddr* remote_addr) override;
virtual void onRTCPDataRecv(RTC::UDPSocket *socket, const MS_BYTE* data, size_t len, const struct sockaddr* remote_addr) override;
/* Pure virtual methods inherited from RTC::TCPServer::Listener. */
public:
virtual void onRTCTCPConnectionClosed(RTC::TCPServer* tcpServer, RTC::TCPConnection* connection, bool is_closed_by_peer) override;
/* Pure virtual methods inherited from RTC::TCPConnection::Listener. */
public:
virtual void onSTUNDataRecv(RTC::TCPConnection *connection, const MS_BYTE* data, size_t len) override;
virtual void onDTLSDataRecv(RTC::TCPConnection *connection, const MS_BYTE* data, size_t len) override;
virtual void onRTPDataRecv(RTC::TCPConnection *connection, const MS_BYTE* data, size_t len) override;
virtual void onRTCPDataRecv(RTC::TCPConnection *connection, const MS_BYTE* data, size_t len) override;
/* Pure virtual methods inherited from RTC::ICEServer::Listener. */
public:
virtual void onOutgoingSTUNMessage(RTC::ICEServer* iceServer, RTC::STUNMessage* msg, RTC::TransportSource* source) override;
virtual void onICEValidPair(RTC::ICEServer* iceServer, RTC::TransportSource* source, bool has_use_candidate) override;
/* Pure virtual methods inherited from RTC::DTLSHandler::Listener. */
public:
virtual void onOutgoingDTLSData(RTC::DTLSHandler* dtlsHandler, const MS_BYTE* data, size_t len) override;
virtual void onDTLSConnected(RTC::DTLSHandler* dtlsHandler) override;
virtual void onDTLSDisconnected(RTC::DTLSHandler* dtlsHandler) override;
virtual void onDTLSFailed(RTC::DTLSHandler* dtlsHandler) override;
virtual void onSRTPKeyMaterial(RTC::DTLSHandler* dtlsHandler, RTC::SRTPProfile srtp_profile, MS_BYTE* srtp_local_key, size_t srtp_local_key_len, MS_BYTE* srtp_remote_key, size_t srtp_remote_key_len) override;
virtual void onDTLSApplicationData(RTC::DTLSHandler* dtlsHandler, const MS_BYTE* data, size_t len) override;
private:
// Allocated by this.
RTC::ICEServer* iceServer = nullptr;
RTC::DTLSHandler* dtlsHandler = nullptr;
RTC::SRTPSession* srtpRecvSession = nullptr;
RTC::SRTPSession* srtpSendSession = nullptr;
// Passed by argument.
Listener* listener = nullptr;
std::vector<RTC::UDPSocket*> udpSockets;
std::vector<RTC::TCPServer*> tcpServers;
// Others.
int flags = 0;
std::list<RTC::TransportSource> sources;
RTC::TransportSource* sendingSource = nullptr;
RTC::DTLSRole dtlsRole = RTC::DTLSRole::NONE;
bool isIcePaired = false;
bool isIcePairedWithUseCandidate = false;
};
/* Inline methods. */
inline
bool Transport::IsReadyForMedia()
{
if (HasFlagDTLS() && !this->dtlsHandler->IsConnected())
return false;
if (HasFlagSRTP() && (!this->srtpRecvSession || !this->srtpSendSession))
return false;
return (this->sendingSource != nullptr);
}
inline
bool Transport::HasFlagICE()
{
return this->flags & Flag::ICE;
}
inline
bool Transport::HasFlagDTLS()
{
return this->flags & Flag::DTLS;
}
inline
bool Transport::HasFlagSRTP()
{
return this->flags & Flag::SRTP;
}
/**
* Set the given source as a valid one and mark it as the sending source for
* outgoing data.
*
* @param source: A RTC::TransportSource (which is a UDP tuple or TCP connection).
* @return: true if the given source was not an already valid source,
* false otherwise.
*/
inline
bool Transport::SetSendingSource(RTC::TransportSource* source)
{
// If the give source is already a valid one return.
// NOTE: The IsValidSource() method will also mark it as sending source.
if (IsValidSource(source))
return false;
// If there are Transport::maxSources sources then close and remove the last one.
if (this->sources.size() == Transport::maxSources)
{
RTC::TransportSource* last_source = &(*this->sources.end());
last_source->Close();
this->sources.pop_back();
}
// Add the new source at the beginning.
this->sources.push_front(*source);
// Set it as sending source (make it point to the first source in the list).
this->sendingSource = &(*this->sources.begin());
// If it is UDP then we must store the remote address (until now it is
// just a pointer that will be freed soon).
if (this->sendingSource->IsUDP())
this->sendingSource->StoreUdpRemoteAddress();
return true;
}
/**
* Check whether the given source is contained in the list of valid sources for
* this transport. In case it is, the given source is also marked as sending
* source for the outgoing data.
*
* @param source: The RTC::TransportSource to check.
* @return: true if it is a valid source, false otherwise.
*/
inline
bool Transport::IsValidSource(RTC::TransportSource* source)
{
// If there is no sending source yet then we know that the sources list
// is empty, so return false.
if (!this->sendingSource)
return false;
// First check the current sending source. If it matches then return true.
if (this->sendingSource->Compare(source))
return true;
// Otherwise check other valid source in the sources list.
for (auto it = this->sources.begin(); it != this->sources.end(); ++it)
{
RTC::TransportSource* valid_source = &(*it);
// If found set it as sending source.
if (valid_source->Compare(source))
{
this->sendingSource = valid_source;
return true;
}
}
return false;
}
/**
* Remove the given source from the list of valid sources. Also update the
* sending source if the given source was the sending source and make it point
* to the next valid source (if any).
*
* @param source: The RTC::TransportSource to remove.
* @return: true if the given source was present in the list of valid
* sources, false otherwise.
*/
inline
bool Transport::RemoveSource(RTC::TransportSource* source)
{
for (auto it = this->sources.begin(); it != this->sources.end(); ++it)
{
RTC::TransportSource* valid_source = &(*it);
// If the source was a valid source then remove it.
if (valid_source->Compare(source))
{
this->sources.erase(it);
// If it was the sending source then unset it and set the sending
// source to the first valid source (if any).
if (this->sendingSource == valid_source)
{
if (this->sources.begin() != this->sources.end())
{
this->sendingSource = &(*this->sources.begin());
}
else
{
this->sendingSource = nullptr;
if (HasFlagICE())
{
// This is just useful is there are just TCP sources.
this->isIcePaired = false;
this->isIcePairedWithUseCandidate = false;
}
}
}
return true;
}
}
return false;
}
}
#endif
......@@ -23,8 +23,8 @@ namespace RTC
public:
static void ClassInit();
static RTC::UDPSocket* New(int address_family);
static void NewPair(int address_family, RTC::UDPSocket* sockets[]);
static RTC::UDPSocket* Factory(Listener* listener, int address_family);
static void PairFactory(Listener* listener, int address_family, RTC::UDPSocket* sockets[]);
private:
static void RandomizePort(int address_family, uv_udp_t* uvHandles[], bool pair);
......@@ -39,9 +39,7 @@ namespace RTC
static AvailablePorts availableIPv6Ports;
public:
UDPSocket(uv_udp_t* uvHandle);
void SetListener(Listener* listener);
UDPSocket(Listener* listener, uv_udp_t* uvHandle);
/* Pure virtual methods inherited from ::UDPSocket. */
public:
......@@ -52,14 +50,6 @@ namespace RTC
// Passed by argument.
Listener* listener = nullptr;
};
/* Inline methods. */
inline
void UDPSocket::SetListener(Listener* listener)
{
this->listener = listener;
}
}
#endif
......@@ -14,14 +14,17 @@ namespace Channel
std::unordered_map<std::string, Request::MethodId> Request::string2MethodId =
{
{ "dumpWorker", Request::MethodId::dumpWorker },
{ "updateSettings", Request::MethodId::updateSettings },
{ "createRoom", Request::MethodId::createRoom },
{ "closeRoom", Request::MethodId::closeRoom },
{ "dumpRoom", Request::MethodId::dumpRoom },
{ "createPeer", Request::MethodId::createPeer },
{ "closePeer", Request::MethodId::closePeer },
{ "dumpPeer", Request::MethodId::dumpPeer }
{ "dumpWorker", Request::MethodId::dumpWorker },
{ "updateSettings", Request::MethodId::updateSettings },
{ "createRoom", Request::MethodId::createRoom },
{ "closeRoom", Request::MethodId::closeRoom },
{ "dumpRoom", Request::MethodId::dumpRoom },
{ "createPeer", Request::MethodId::createPeer },
{ "closePeer", Request::MethodId::closePeer },
{ "dumpPeer", Request::MethodId::dumpPeer },
{ "createTransport", Request::MethodId::createTransport },
{ "closeTransport", Request::MethodId::closeTransport },
{ "dumpTransport", Request::MethodId::dumpTransport }
};
/* Instance methods. */
......@@ -32,21 +35,27 @@ namespace Channel
MS_TRACE();
if (json["id"].isUInt())
id = json["id"].asUInt();
this->id = json["id"].asUInt();
else
MS_THROW_ERROR("json has no numeric .id field");
if (json["method"].isString())
method = json["method"].asString();
this->method = json["method"].asString();
else
MS_THROW_ERROR("json has no string .method field");
auto it = Request::string2MethodId.find(method);
if (it != Request::string2MethodId.end())
{
this->methodId = it->second;
}
else
MS_THROW_ERROR("unknwon .method '%s'", method.c_str());
{
Reject(405, "method not allowed");
MS_THROW_ERROR("unknown .method '%s'", method.c_str());
}
if (json["data"].isObject())
this->data = json["data"];
......
......@@ -40,7 +40,7 @@ Loop::~Loop()
MS_TRACE();
}
RTC::Room* Loop::GetRoomFromRequest(Channel::Request* request, unsigned int* roomId = nullptr)
RTC::Room* Loop::GetRoomFromRequest(Channel::Request* request, unsigned int* roomId)
{
MS_TRACE();
......@@ -133,12 +133,12 @@ void Loop::onChannelRequest(Channel::UnixStreamSocket* channel, Channel::Request
{
MS_TRACE();
MS_DEBUG("'%s' request", request->method.c_str());
switch (request->methodId)
{
case Channel::Request::MethodId::dumpWorker:
{
MS_DEBUG("'dumpWorker' method");
Json::Value json(Json::objectValue);
Json::Value jsonWorker(Json::objectValue);
Json::Value jsonRooms(Json::objectValue);
......@@ -160,16 +160,12 @@ void Loop::onChannelRequest(Channel::UnixStreamSocket* channel, Channel::Request
case Channel::Request::MethodId::updateSettings:
{
MS_DEBUG("'updateSettings' method");
Settings::HandleUpdateRequest(request);
break;
}
case Channel::Request::MethodId::createRoom:
{
MS_DEBUG("'createRoom' method");
RTC::Room* room;
unsigned int roomId;
......@@ -211,8 +207,6 @@ void Loop::onChannelRequest(Channel::UnixStreamSocket* channel, Channel::Request
case Channel::Request::MethodId::closeRoom:
{
MS_DEBUG("'closeRoom' method");
RTC::Room* room;
unsigned int roomId;
......@@ -247,14 +241,11 @@ void Loop::onChannelRequest(Channel::UnixStreamSocket* channel, Channel::Request
case Channel::Request::MethodId::dumpRoom:
{
MS_DEBUG("'dumpRoom' method");
RTC::Room* room;
unsigned int roomId;
try
{
room = GetRoomFromRequest(request, &roomId);
room = GetRoomFromRequest(request);
}
catch (const MediaSoupError &error)
{
......@@ -278,67 +269,12 @@ void Loop::onChannelRequest(Channel::UnixStreamSocket* channel, Channel::Request
}
case Channel::Request::MethodId::createPeer:
{
MS_DEBUG("'createPeer' method");
RTC::Room* room;
try
{
room = GetRoomFromRequest(request);
}
catch (const MediaSoupError &error)
{
request->Reject(500, error.what());
return;
}
if (!room)
{
MS_ERROR("Room does not exist");
request->Reject(500, "Room does not exist");
return;
}
room->HandleCreatePeerRequest(request);
break;
}
case Channel::Request::MethodId::closePeer:
{
MS_DEBUG("'closePeer' method");
RTC::Room* room;
try
{
room = GetRoomFromRequest(request);
}
catch (const MediaSoupError &error)
{
request->Reject(500, error.what());
return;
}
if (!room)
{
MS_ERROR("Room does not exist");
request->Reject(500, "Room does not exist");
return;
}
room->HandleClosePeerRequest(request);
break;
}
case Channel::Request::MethodId::dumpPeer:
case Channel::Request::MethodId::createTransport:
case Channel::Request::MethodId::closeTransport:
case Channel::Request::MethodId::dumpTransport:
{
MS_DEBUG("'dumpPeer' method");
RTC::Room* room;
try
......@@ -359,14 +295,14 @@ void Loop::onChannelRequest(Channel::UnixStreamSocket* channel, Channel::Request
return;
}
room->HandleDumpPeerRequest(request);
room->HandleRequest(request);
break;
}
default:
{
MS_ABORT("unexpected methodId");
MS_ABORT("unknown method");
}
}
}
......
#define MS_CLASS "RTC::DTLSHandler"
#define MS_CLASS "RTC::DTLSAgent"
#include "RTC/DTLSHandler.h"
#include "RTC/DTLSAgent.h"
#include "Settings.h"
#include "Utils.h"
#include "MediaSoupError.h"
......@@ -52,17 +52,17 @@ int on_ssl_certificate_verify(int preverify_ok, X509_STORE_CTX* ctx)
static inline
void on_ssl_info(const SSL* ssl, int where, int ret)
{
static_cast<RTC::DTLSHandler*>(SSL_get_ex_data(ssl, 0))->onSSLInfo(where, ret);
static_cast<RTC::DTLSAgent*>(SSL_get_ex_data(ssl, 0))->onSSLInfo(where, ret);
}
namespace RTC
{
/* Class variables. */
X509* DTLSHandler::certificate = nullptr;
EVP_PKEY* DTLSHandler::privateKey = nullptr;
SSL_CTX* DTLSHandler::sslCtx = nullptr;
DTLSHandler::Fingerprints DTLSHandler::fingerprints
X509* DTLSAgent::certificate = nullptr;
EVP_PKEY* DTLSAgent::privateKey = nullptr;
SSL_CTX* DTLSAgent::sslCtx = nullptr;
DTLSAgent::Fingerprints DTLSAgent::fingerprints
{
{ RTC::FingerprintHash::SHA1, "" },
{ RTC::FingerprintHash::SHA224, "" },
......@@ -70,16 +70,16 @@ namespace RTC
{ RTC::FingerprintHash::SHA384, "" },
{ RTC::FingerprintHash::SHA512, "" }
};
DTLSHandler::SRTPProfiles DTLSHandler::srtpProfiles =
DTLSAgent::SRTPProfiles DTLSAgent::srtpProfiles =
{
{ RTC::SRTPProfile::AES_CM_128_HMAC_SHA1_80, "SRTP_AES128_CM_SHA1_80" },
{ RTC::SRTPProfile::AES_CM_128_HMAC_SHA1_32, "SRTP_AES128_CM_SHA1_32" }
};
MS_BYTE DTLSHandler::sslReadBuffer[MS_SSL_READ_BUFFER_SIZE];
MS_BYTE DTLSAgent::sslReadBuffer[MS_SSL_READ_BUFFER_SIZE];
/* Class methods. */
void DTLSHandler::ClassInit()
void DTLSAgent::ClassInit()
{
MS_TRACE();
......@@ -96,27 +96,27 @@ namespace RTC
GenerateFingerprints();
}
void DTLSHandler::ClassDestroy()
void DTLSAgent::ClassDestroy()
{
MS_TRACE();
if (DTLSHandler::privateKey)
EVP_PKEY_free(DTLSHandler::privateKey);
if (DTLSHandler::certificate)
X509_free(DTLSHandler::certificate);
if (DTLSHandler::sslCtx)
SSL_CTX_free(DTLSHandler::sslCtx);
if (DTLSAgent::privateKey)
EVP_PKEY_free(DTLSAgent::privateKey);
if (DTLSAgent::certificate)
X509_free(DTLSAgent::certificate);
if (DTLSAgent::sslCtx)
SSL_CTX_free(DTLSAgent::sslCtx);
}
const std::string& DTLSHandler::GetFingerprint(RTC::FingerprintHash hash)
const std::string& DTLSAgent::GetFingerprint(RTC::FingerprintHash hash)
{
MS_TRACE();
// NOTE: Don't check if the given hash is supported (should give a compilation error).
return DTLSHandler::fingerprints.at(hash);
return DTLSAgent::fingerprints.at(hash);
}
void DTLSHandler::GenerateCertificateAndPrivateKey()
void DTLSAgent::GenerateCertificateAndPrivateKey()
{
MS_TRACE();
......@@ -158,14 +158,14 @@ namespace RTC
}
// Create a private key object (needed to hold the RSA key).
DTLSHandler::privateKey = EVP_PKEY_new();
if (!DTLSHandler::privateKey)
DTLSAgent::privateKey = EVP_PKEY_new();
if (!DTLSAgent::privateKey)
{
LOG_OPENSSL_ERROR("EVP_PKEY_new() failed");
goto error;
}
ret = EVP_PKEY_assign_RSA(DTLSHandler::privateKey, rsa_key);
ret = EVP_PKEY_assign_RSA(DTLSAgent::privateKey, rsa_key);
if (ret == 0)
{
LOG_OPENSSL_ERROR("EVP_PKEY_assign_RSA() failed");
......@@ -175,25 +175,25 @@ namespace RTC
rsa_key = nullptr;
// Create the X509 certificate.
DTLSHandler::certificate = X509_new();
if (!DTLSHandler::certificate)
DTLSAgent::certificate = X509_new();
if (!DTLSAgent::certificate)
{
LOG_OPENSSL_ERROR("X509_new() failed");
goto error;
}
// Set version 3 (note that 0 means version 1).
X509_set_version(DTLSHandler::certificate, 2);
X509_set_version(DTLSAgent::certificate, 2);
// Set serial number (avoid default 0).
ASN1_INTEGER_set(X509_get_serialNumber(DTLSHandler::certificate), (long)Utils::Crypto::GetRandomUInt(1000000, 9999999));
ASN1_INTEGER_set(X509_get_serialNumber(DTLSAgent::certificate), (long)Utils::Crypto::GetRandomUInt(1000000, 9999999));
// Set valid period.
X509_gmtime_adj(X509_get_notBefore(DTLSHandler::certificate), -1*60*60*24*365*10); // - 10 years.
X509_gmtime_adj(X509_get_notAfter(DTLSHandler::certificate), 60*60*24*365*10); // 10 years.
X509_gmtime_adj(X509_get_notBefore(DTLSAgent::certificate), -1*60*60*24*365*10); // - 10 years.
X509_gmtime_adj(X509_get_notAfter(DTLSAgent::certificate), 60*60*24*365*10); // 10 years.
// Set the public key for the certificate using the key.
ret = X509_set_pubkey(DTLSHandler::certificate, DTLSHandler::privateKey);
ret = X509_set_pubkey(DTLSAgent::certificate, DTLSAgent::privateKey);
if (ret == 0)
{
LOG_OPENSSL_ERROR("X509_set_pubkey() failed");
......@@ -201,7 +201,7 @@ namespace RTC
}
// Set certificate fields.
cert_name = X509_get_subject_name(DTLSHandler::certificate);
cert_name = X509_get_subject_name(DTLSAgent::certificate);
if (!cert_name)
{
LOG_OPENSSL_ERROR("X509_get_subject_name() failed");
......@@ -211,7 +211,7 @@ namespace RTC
X509_NAME_add_entry_by_txt(cert_name, "CN", MBSTRING_ASC, (unsigned char *)MS_APP_NAME, -1, -1, 0);
// It is self signed so set the issuer name to be the same as the subject.
ret = X509_set_issuer_name(DTLSHandler::certificate, cert_name);
ret = X509_set_issuer_name(DTLSAgent::certificate, cert_name);
if (ret == 0)
{
LOG_OPENSSL_ERROR("X509_set_issuer_name() failed");
......@@ -219,7 +219,7 @@ namespace RTC
}
// Sign the certificate with its own private key.
ret = X509_sign(DTLSHandler::certificate, DTLSHandler::privateKey, EVP_sha1());
ret = X509_sign(DTLSAgent::certificate, DTLSAgent::privateKey, EVP_sha1());
if (ret == 0)
{
LOG_OPENSSL_ERROR("X509_sign() failed");
......@@ -233,17 +233,17 @@ namespace RTC
error:
if (bne)
BN_free(bne);
if (rsa_key && !DTLSHandler::privateKey)
if (rsa_key && !DTLSAgent::privateKey)
RSA_free(rsa_key);
if (DTLSHandler::privateKey)
EVP_PKEY_free(DTLSHandler::privateKey); // NOTE: This also frees the RSA key.
if (DTLSHandler::certificate)
X509_free(DTLSHandler::certificate);
if (DTLSAgent::privateKey)
EVP_PKEY_free(DTLSAgent::privateKey); // NOTE: This also frees the RSA key.
if (DTLSAgent::certificate)
X509_free(DTLSAgent::certificate);
MS_THROW_ERROR("DTLS certificate and private key generation failed");
}
void DTLSHandler::ReadCertificateAndPrivateKeyFromFiles()
void DTLSAgent::ReadCertificateAndPrivateKeyFromFiles()
{
MS_TRACE();
......@@ -255,8 +255,8 @@ namespace RTC
MS_ERROR("error reading DTLS certificate file: %s", std::strerror(errno));
goto error;
}
DTLSHandler::certificate = PEM_read_X509(file, nullptr, nullptr, nullptr);
if (!DTLSHandler::certificate)
DTLSAgent::certificate = PEM_read_X509(file, nullptr, nullptr, nullptr);
if (!DTLSAgent::certificate)
{
LOG_OPENSSL_ERROR("PEM_read_X509() failed");
goto error;
......@@ -269,8 +269,8 @@ namespace RTC
MS_ERROR("error reading DTLS private key file: %s", std::strerror(errno));
goto error;
}
DTLSHandler::privateKey = PEM_read_PrivateKey(file, nullptr, nullptr, nullptr);
if (!DTLSHandler::privateKey)
DTLSAgent::privateKey = PEM_read_PrivateKey(file, nullptr, nullptr, nullptr);
if (!DTLSAgent::privateKey)
{
LOG_OPENSSL_ERROR("PEM_read_PrivateKey() failed");
goto error;
......@@ -283,7 +283,7 @@ namespace RTC
MS_THROW_ERROR("error reading DTLS certificate and private key PEM files");
}
void DTLSHandler::CreateSSL_CTX()
void DTLSAgent::CreateSSL_CTX()
{
MS_TRACE();
......@@ -295,35 +295,35 @@ namespace RTC
// - Both DTLS 1.0 and 1.2 (requires OpenSSL >= 1.1.0).
#if (OPENSSL_VERSION_NUMBER >= 0x10100000L)
DTLSHandler::sslCtx = SSL_CTX_new(DTLS_method());
DTLSAgent::sslCtx = SSL_CTX_new(DTLS_method());
// - Just DTLS 1.0 (requires OpenSSL >= 1.0.1).
#elif (OPENSSL_VERSION_NUMBER >= 0x10001000L)
DTLSHandler::sslCtx = SSL_CTX_new(DTLSv1_method());
DTLSAgent::sslCtx = SSL_CTX_new(DTLSv1_method());
#else
#error "too old OpenSSL version"
#endif
if (!DTLSHandler::sslCtx)
if (!DTLSAgent::sslCtx)
{
LOG_OPENSSL_ERROR("SSL_CTX_new() failed");
goto error;
}
ret = SSL_CTX_use_certificate(DTLSHandler::sslCtx, DTLSHandler::certificate);
ret = SSL_CTX_use_certificate(DTLSAgent::sslCtx, DTLSAgent::certificate);
if (ret == 0)
{
LOG_OPENSSL_ERROR("SSL_CTX_use_certificate() failed");
goto error;
}
ret = SSL_CTX_use_PrivateKey(DTLSHandler::sslCtx, DTLSHandler::privateKey);
ret = SSL_CTX_use_PrivateKey(DTLSAgent::sslCtx, DTLSAgent::privateKey);
if (ret == 0)
{
LOG_OPENSSL_ERROR("SSL_CTX_use_PrivateKey() failed");
goto error;
}
ret = SSL_CTX_check_private_key(DTLSHandler::sslCtx);
ret = SSL_CTX_check_private_key(DTLSAgent::sslCtx);
if (ret == 0)
{
LOG_OPENSSL_ERROR("SSL_CTX_check_private_key() failed");
......@@ -331,24 +331,24 @@ namespace RTC
}
// Set options.
SSL_CTX_set_options(DTLSHandler::sslCtx, SSL_OP_CIPHER_SERVER_PREFERENCE | SSL_OP_NO_TICKET | SSL_OP_SINGLE_ECDH_USE);
SSL_CTX_set_options(DTLSAgent::sslCtx, SSL_OP_CIPHER_SERVER_PREFERENCE | SSL_OP_NO_TICKET | SSL_OP_SINGLE_ECDH_USE);
// Don't use sessions cache.
SSL_CTX_set_session_cache_mode(DTLSHandler::sslCtx, SSL_SESS_CACHE_OFF);
SSL_CTX_set_session_cache_mode(DTLSAgent::sslCtx, SSL_SESS_CACHE_OFF);
// Read always as much into the buffer as possible.
SSL_CTX_set_read_ahead(DTLSHandler::sslCtx, 1);
SSL_CTX_set_read_ahead(DTLSAgent::sslCtx, 1);
SSL_CTX_set_verify_depth(DTLSHandler::sslCtx, 4);
SSL_CTX_set_verify_depth(DTLSAgent::sslCtx, 4);
// Require certificate from peer.
SSL_CTX_set_verify(DTLSHandler::sslCtx, SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT, on_ssl_certificate_verify);
SSL_CTX_set_verify(DTLSAgent::sslCtx, SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT, on_ssl_certificate_verify);
// Set SSL info callback.
SSL_CTX_set_info_callback(DTLSHandler::sslCtx, on_ssl_info);
SSL_CTX_set_info_callback(DTLSAgent::sslCtx, on_ssl_info);
// Set ciphers.
ret = SSL_CTX_set_cipher_list(DTLSHandler::sslCtx, "ALL:!ADH:!LOW:!EXP:!MD5:!aNULL:!eNULL:@STRENGTH");
ret = SSL_CTX_set_cipher_list(DTLSAgent::sslCtx, "ALL:!ADH:!LOW:!EXP:!MD5:!aNULL:!eNULL:@STRENGTH");
if (ret == 0)
{
LOG_OPENSSL_ERROR("SSL_CTX_set_cipher_list() failed");
......@@ -360,7 +360,7 @@ namespace RTC
// NOTE: https://code.google.com/p/chromium/issues/detail?id=406458
// For OpenSSL >= 1.0.2:
#if (OPENSSL_VERSION_NUMBER >= 0x10002000L)
SSL_CTX_set_ecdh_auto(DTLSHandler::sslCtx, 1);
SSL_CTX_set_ecdh_auto(DTLSAgent::sslCtx, 1);
#else
ecdh = EC_KEY_new_by_curve_name(NID_X9_62_prime256v1);
if (!ecdh)
......@@ -368,7 +368,7 @@ namespace RTC
LOG_OPENSSL_ERROR("EC_KEY_new_by_curve_name() failed");
goto error;
}
if (SSL_CTX_set_tmp_ecdh(DTLSHandler::sslCtx, ecdh) != 1)
if (SSL_CTX_set_tmp_ecdh(DTLSAgent::sslCtx, ecdh) != 1)
{
LOG_OPENSSL_ERROR("SSL_CTX_set_tmp_ecdh() failed");
goto error;
......@@ -378,9 +378,9 @@ namespace RTC
#endif
// Set the "use_srtp" DTLS extension.
for (auto it = DTLSHandler::srtpProfiles.begin(); it != DTLSHandler::srtpProfiles.end(); ++it)
for (auto it = DTLSAgent::srtpProfiles.begin(); it != DTLSAgent::srtpProfiles.end(); ++it)
{
if (it != DTLSHandler::srtpProfiles.begin())
if (it != DTLSAgent::srtpProfiles.begin())
ssl_srtp_profiles += ":";
SrtpProfileMapEntry* profile_entry = &(*it);
......@@ -388,7 +388,7 @@ namespace RTC
}
MS_DEBUG("setting SRTP profiles for DTLS: %s", ssl_srtp_profiles.c_str());
// NOTE: This function returns 0 on success.
ret = SSL_CTX_set_tlsext_use_srtp(DTLSHandler::sslCtx, ssl_srtp_profiles.c_str());
ret = SSL_CTX_set_tlsext_use_srtp(DTLSAgent::sslCtx, ssl_srtp_profiles.c_str());
if (ret != 0)
{
MS_ERROR("SSL_CTX_set_tlsext_use_srtp() failed when entering '%s'", ssl_srtp_profiles.c_str());
......@@ -399,10 +399,10 @@ namespace RTC
return;
error:
if (DTLSHandler::sslCtx)
if (DTLSAgent::sslCtx)
{
SSL_CTX_free(DTLSHandler::sslCtx);
DTLSHandler::sslCtx = nullptr;
SSL_CTX_free(DTLSAgent::sslCtx);
DTLSAgent::sslCtx = nullptr;
}
if (ecdh)
......@@ -411,11 +411,11 @@ namespace RTC
MS_THROW_ERROR("SSL context creation failed");
}
void DTLSHandler::GenerateFingerprints()
void DTLSAgent::GenerateFingerprints()
{
MS_TRACE();
for (auto it = DTLSHandler::fingerprints.begin(); it != DTLSHandler::fingerprints.end(); ++it)
for (auto it = DTLSAgent::fingerprints.begin(); it != DTLSAgent::fingerprints.end(); ++it)
{
RTC::FingerprintHash hash = it->first;
std::string hash_str;
......@@ -451,7 +451,7 @@ namespace RTC
MS_ABORT("unknown hash");
}
ret = X509_digest(DTLSHandler::certificate, hash_function, binary_fingerprint, &size);
ret = X509_digest(DTLSAgent::certificate, hash_function, binary_fingerprint, &size);
if (ret == 0)
{
MS_ERROR("X509_digest() failed");
......@@ -469,20 +469,20 @@ namespace RTC
MS_DEBUG("%-7s fingerprint: %s", hash_str.c_str(), hex_fingerprint);
// Store in the map.
DTLSHandler::fingerprints[hash].assign(hex_fingerprint);
DTLSAgent::fingerprints[hash].assign(hex_fingerprint);
}
}
/* Instance methods. */
DTLSHandler::DTLSHandler(Listener* listener) :
DTLSAgent::DTLSAgent(Listener* listener) :
listener(listener)
{
MS_TRACE();
/* Set SSL. */
this->ssl = SSL_new(DTLSHandler::sslCtx);
this->ssl = SSL_new(DTLSAgent::sslCtx);
if (!this->ssl)
{
LOG_OPENSSL_ERROR("SSL_new() failed");
......@@ -529,10 +529,10 @@ namespace RTC
// NOTE: If this is not catched by the caller the program will abort, but
// this should never happen.
MS_THROW_ERROR("DTLSHandler instance creation failed");
MS_THROW_ERROR("DTLSAgent instance creation failed");
}
DTLSHandler::~DTLSHandler()
DTLSAgent::~DTLSAgent()
{
MS_TRACE();
......@@ -545,7 +545,7 @@ namespace RTC
}
}
void DTLSHandler::Run(RTC::DTLSRole role)
void DTLSAgent::Run(RTC::DTLSRole role)
{
MS_TRACE();
......@@ -573,7 +573,7 @@ namespace RTC
}
}
void DTLSHandler::SetRemoteFingerprint(RTC::FingerprintHash hash, std::string& fingerprint)
void DTLSAgent::SetRemoteFingerprint(RTC::FingerprintHash hash, std::string& fingerprint)
{
MS_TRACE();
......@@ -594,7 +594,7 @@ namespace RTC
}
}
void DTLSHandler::Reset()
void DTLSAgent::Reset()
{
MS_TRACE();
......@@ -636,7 +636,7 @@ namespace RTC
LOG_OPENSSL_ERROR("SSL_clear() failed");
}
void DTLSHandler::Close()
void DTLSAgent::Close()
{
MS_TRACE();
......@@ -658,7 +658,7 @@ namespace RTC
delete this;
}
void DTLSHandler::ProcessDTLSData(const MS_BYTE* data, size_t len)
void DTLSAgent::ProcessDTLSData(const MS_BYTE* data, size_t len)
{
MS_TRACE();
......@@ -677,7 +677,7 @@ namespace RTC
MS_WARN("OpenSSL BIO_write() wrote less (%zu bytes) than given data (%zu bytes)", (size_t)written, len);
// Must call SSL_read() to process received DTLS data.
read = SSL_read(this->ssl, (void*)DTLSHandler::sslReadBuffer, MS_SSL_READ_BUFFER_SIZE);
read = SSL_read(this->ssl, (void*)DTLSAgent::sslReadBuffer, MS_SSL_READ_BUFFER_SIZE);
// Send data if it's ready.
SendPendingOutgoingDTLSData();
......@@ -698,11 +698,11 @@ namespace RTC
return;
}
this->listener->onDTLSApplicationData(this, (MS_BYTE*)DTLSHandler::sslReadBuffer, (size_t)read);
this->listener->onDTLSApplicationData(this, (MS_BYTE*)DTLSAgent::sslReadBuffer, (size_t)read);
}
}
void DTLSHandler::SendApplicationData(const MS_BYTE* data, size_t len)
void DTLSAgent::SendApplicationData(const MS_BYTE* data, size_t len)
{
MS_TRACE();
......@@ -735,7 +735,7 @@ namespace RTC
SendPendingOutgoingDTLSData();
}
void DTLSHandler::Dump()
void DTLSAgent::Dump()
{
MS_TRACE();
......@@ -747,7 +747,7 @@ namespace RTC
}
inline
bool DTLSHandler::CheckStatus(int return_code)
bool DTLSAgent::CheckStatus(int return_code)
{
MS_TRACE();
......@@ -846,7 +846,7 @@ namespace RTC
}
inline
void DTLSHandler::SendPendingOutgoingDTLSData()
void DTLSAgent::SendPendingOutgoingDTLSData()
{
MS_TRACE();
......@@ -869,7 +869,7 @@ namespace RTC
}
inline
void DTLSHandler::SetTimeout()
void DTLSAgent::SetTimeout()
{
MS_TRACE();
......@@ -902,7 +902,7 @@ namespace RTC
}
inline
void DTLSHandler::ProcessHandshake()
void DTLSAgent::ProcessHandshake()
{
MS_TRACE();
......@@ -949,7 +949,7 @@ namespace RTC
}
inline
bool DTLSHandler::CheckRemoteFingerprint()
bool DTLSAgent::CheckRemoteFingerprint()
{
MS_TRACE();
......@@ -1025,7 +1025,7 @@ namespace RTC
}
inline
RTC::SRTPProfile DTLSHandler::GetNegotiatedSRTPProfile()
RTC::SRTPProfile DTLSAgent::GetNegotiatedSRTPProfile()
{
MS_TRACE();
......@@ -1039,7 +1039,7 @@ namespace RTC
}
// Get the negotiated SRTP profile.
for (auto it = DTLSHandler::srtpProfiles.begin(); it != DTLSHandler::srtpProfiles.end(); ++it)
for (auto it = DTLSAgent::srtpProfiles.begin(); it != DTLSAgent::srtpProfiles.end(); ++it)
{
SrtpProfileMapEntry* profile_entry = &(*it);
......@@ -1055,7 +1055,7 @@ namespace RTC
}
inline
void DTLSHandler::ExtractSRTPKeys(RTC::SRTPProfile srtp_profile)
void DTLSAgent::ExtractSRTPKeys(RTC::SRTPProfile srtp_profile)
{
MS_TRACE();
......@@ -1102,7 +1102,7 @@ namespace RTC
}
inline
void DTLSHandler::onSSLInfo(int where, int ret)
void DTLSAgent::onSSLInfo(int where, int ret)
{
MS_TRACE();
......@@ -1161,7 +1161,7 @@ namespace RTC
}
inline
void DTLSHandler::onTimer(Timer* timer)
void DTLSAgent::onTimer(Timer* timer)
{
MS_TRACE();
......
#define MS_CLASS "RTC::ICEServer"
#include "RTC/ICEServer.h"
#include "Utils.h"
#include "Logger.h"
namespace RTC
{
/* Instance methods. */
ICEServer::ICEServer(Listener* listener) :
listener(listener)
ICEServer::ICEServer(Listener* listener, std::string& usernameFragment, std::string password) :
listener(listener),
usernameFragment(usernameFragment),
password(password)
{
MS_TRACE();
char local_username[16];
char local_password[16];
this->localUsername = std::string(Utils::Crypto::GetRandomHexString(local_username, 16), 16);
this->localPassword = std::string(Utils::Crypto::GetRandomHexString(local_password, 32), 32);
MS_DEBUG("[usernameFragment:%s, password:%s]", this->usernameFragment.c_str(), this->password.c_str());
}
MS_DEBUG("local username: %s | local password: %s", this->localUsername.c_str(), this->localPassword.c_str());
void ICEServer::Close()
{
MS_TRACE();
// TODO: TMP for testing
this->localUsername = "7D5B3AA55DC2CE83";
this->localPassword = "75C96DDDFC38D194FEDF75986CF962A2D56F3B65F1F7";
delete this;
}
void ICEServer::ProcessSTUNMessage(RTC::STUNMessage* msg, RTC::TransportSource* source)
......@@ -91,7 +89,7 @@ namespace RTC
}
// Check authentication.
switch (msg->CheckAuthentication(this->localUsername, this->localPassword))
switch (msg->CheckAuthentication(this->usernameFragment, this->password))
{
case RTC::STUNMessage::Authentication::OK:
break;
......@@ -146,7 +144,7 @@ namespace RTC
response->SetXorMappedAddress(source->GetRemoteAddress());
// Authenticate the response.
response->Authenticate(this->localPassword);
response->Authenticate(this->password);
// Send back.
response->Serialize();
......@@ -178,11 +176,4 @@ namespace RTC
}
}
}
void ICEServer::Close()
{
MS_TRACE();
delete this;
}
}
#define MS_CLASS "RTC::Transport"
#include "RTC/ICETransport.h"
#include "Settings.h"
#include "Utils.h"
#include "MediaSoupError.h"
#include "Logger.h"
namespace RTC
{
/* Instance methods. */
ICETransport::ICETransport(Listener* listener, Json::Value& data) :
listener(listener)
{
MS_TRACE();
// Check options.
static const Json::StaticString udp("udp");
static const Json::StaticString tcp("tcp");
bool option_udp = true;
bool option_tcp = true;
if (data[udp].isBool())
option_udp = data[udp].asBool();
if (data[tcp].isBool())
option_tcp = data[tcp].asBool();
MS_DEBUG("[udp:%s, tcp:%s]",
option_udp ? "true" : "false", option_tcp ? "true" : "false");
// Create an ICEServer.
char _username_fragment[16];
char _password[16];
std::string usernameFragment = std::string(Utils::Crypto::GetRandomHexString(_username_fragment, 16), 16);
std::string password = std::string(Utils::Crypto::GetRandomHexString(_password, 32), 32);
this->iceServer = new RTC::ICEServer(this, usernameFragment, password);
// Fill IceParameters.
this->iceLocalParameters.usernameFragment = this->iceServer->GetUsernameFragment();
this->iceLocalParameters.password = this->iceServer->GetPassword();
// Open a IPv4 UDP socket.
if (option_udp && Settings::configuration.hasIPv4)
{
try
{
RTC::UDPSocket* udpSocket = RTC::UDPSocket::Factory(this, AF_INET);
RTC::IceCandidate iceCandidate(udpSocket);
this->udpSockets.push_back(udpSocket);
this->iceLocalCandidates.push_back(iceCandidate);
}
catch (const MediaSoupError &error)
{
MS_ERROR("error adding IPv4 UDP socket: %s", error.what());
}
}
// Open a IPv6 UDP socket.
if (option_udp && Settings::configuration.hasIPv6)
{
try
{
RTC::UDPSocket* udpSocket = RTC::UDPSocket::Factory(this, AF_INET6);
RTC::IceCandidate iceCandidate(udpSocket);
this->udpSockets.push_back(udpSocket);
this->iceLocalCandidates.push_back(iceCandidate);
}
catch (const MediaSoupError &error)
{
MS_ERROR("error adding IPv6 UDP socket: %s", error.what());
}
}
// Open a IPv4 TCP server.
if (option_tcp && Settings::configuration.hasIPv4)
{
try
{
RTC::TCPServer* tcpServer = RTC::TCPServer::Factory(this, this, AF_INET);
RTC::IceCandidate iceCandidate(tcpServer);
this->tcpServers.push_back(tcpServer);
this->iceLocalCandidates.push_back(iceCandidate);
}
catch (const MediaSoupError &error)
{
MS_ERROR("error adding IPv4 TCP server: %s", error.what());
}
}
// Open a IPv6 TCP server.
if (option_tcp && Settings::configuration.hasIPv6)
{
try
{
RTC::TCPServer* tcpServer = RTC::TCPServer::Factory(this, this, AF_INET6);
RTC::IceCandidate iceCandidate(tcpServer);
this->tcpServers.push_back(tcpServer);
this->iceLocalCandidates.push_back(iceCandidate);
}
catch (const MediaSoupError &error)
{
MS_ERROR("error adding IPv6 TCP server: %s", error.what());
}
}
}
ICETransport::~ICETransport()
{
MS_TRACE();
}
void ICETransport::Close()
{
MS_TRACE();
if (this->iceServer)
this->iceServer->Close();
// if (this->dtlsAgent)
// this->dtlsAgent->Close();
// if (this->srtpRecvSession)
// this->srtpRecvSession->Close();
// if (this->srtpSendSession)
// this->srtpSendSession->Close();
for (auto socket : this->udpSockets)
socket->Close();
for (auto server : this->tcpServers)
server->Close();
delete this;
}
Json::Value ICETransport::toJson()
{
MS_TRACE();
static const Json::StaticString iceLocalParameters("iceLocalParameters");
static const Json::StaticString iceCandidates("iceCandidates");
Json::Value data;
if (this->iceComponent == ICETransport::IceComponent::RTP)
data["iceComponent"] = "RTP";
else
data["iceComponent"] = "RTCP";
data[iceLocalParameters]["usernameFragment"] = this->iceLocalParameters.usernameFragment;
data[iceLocalParameters]["password"] = this->iceLocalParameters.password;
data[iceCandidates] = Json::arrayValue;
for (auto iceCandidate : this->iceLocalCandidates)
{
data[iceCandidates].append(iceCandidate.toJson());
}
return data;
}
void ICETransport::onOutgoingSTUNMessage(RTC::ICEServer* iceServer, RTC::STUNMessage* msg, RTC::TransportSource* source)
{
MS_TRACE();
// TODO
}
void ICETransport::onICEValidPair(RTC::ICEServer* iceServer, RTC::TransportSource* source, bool has_use_candidate)
{
MS_TRACE();
// TODO
}
inline
void ICETransport::onSTUNDataRecv(RTC::TransportSource* source, const MS_BYTE* data, size_t len)
{
MS_TRACE();
// TODO
}
inline
void ICETransport::onDTLSDataRecv(RTC::TransportSource* source, const MS_BYTE* data, size_t len)
{
MS_TRACE();
// TODO
}
inline
void ICETransport::onRTPDataRecv(RTC::TransportSource* source, const MS_BYTE* data, size_t len)
{
MS_TRACE();
// TODO
}
inline
void ICETransport::onRTCPDataRecv(RTC::TransportSource* source, const MS_BYTE* data, size_t len)
{
MS_TRACE();
// TODO
}
void ICETransport::onSTUNDataRecv(RTC::UDPSocket *socket, const MS_BYTE* data, size_t len, const struct sockaddr* remote_addr)
{
MS_TRACE();
RTC::TransportSource source(socket, remote_addr);
onSTUNDataRecv(&source, data, len);
}
void ICETransport::onDTLSDataRecv(RTC::UDPSocket *socket, const MS_BYTE* data, size_t len, const struct sockaddr* remote_addr)
{
MS_TRACE();
RTC::TransportSource source(socket, remote_addr);
onDTLSDataRecv(&source, data, len);
}
void ICETransport::onRTPDataRecv(RTC::UDPSocket *socket, const MS_BYTE* data, size_t len, const struct sockaddr* remote_addr)
{
MS_TRACE();
RTC::TransportSource source(socket, remote_addr);
onRTPDataRecv(&source, data, len);
}
void ICETransport::onRTCPDataRecv(RTC::UDPSocket *socket, const MS_BYTE* data, size_t len, const struct sockaddr* remote_addr)
{
MS_TRACE();
RTC::TransportSource source(socket, remote_addr);
onRTCPDataRecv(&source, data, len);
}
void ICETransport::onRTCTCPConnectionClosed(RTC::TCPServer* tcpServer, RTC::TCPConnection* connection, bool is_closed_by_peer)
{
MS_TRACE();
// RTC::TransportSource source(connection);
// if (RemoveSource(&source))
// {
// MS_DEBUG("valid source %s:", is_closed_by_peer ? "closed by peer" : "locally closed");
// source.Dump();
// }
}
void ICETransport::onSTUNDataRecv(RTC::TCPConnection *connection, const MS_BYTE* data, size_t len)
{
MS_TRACE();
RTC::TransportSource source(connection);
onSTUNDataRecv(&source, data, len);
}
void ICETransport::onDTLSDataRecv(RTC::TCPConnection *connection, const MS_BYTE* data, size_t len)
{
MS_TRACE();
RTC::TransportSource source(connection);
onDTLSDataRecv(&source, data, len);
}
void ICETransport::onRTPDataRecv(RTC::TCPConnection *connection, const MS_BYTE* data, size_t len)
{
MS_TRACE();
RTC::TransportSource source(connection);
onRTPDataRecv(&source, data, len);
}
void ICETransport::onRTCPDataRecv(RTC::TCPConnection *connection, const MS_BYTE* data, size_t len)
{
MS_TRACE();
RTC::TransportSource source(connection);
onRTCPDataRecv(&source, data, len);
}
}
......@@ -13,8 +13,8 @@ namespace RTC
/* Instance methods. */
Peer::Peer(Listener* listener, std::string& peerId, Json::Value& data) :
listener(listener),
peerId(peerId)
peerId(peerId),
listener(listener)
{
MS_TRACE();
......@@ -26,24 +26,17 @@ namespace RTC
MS_TRACE();
}
void Peer::SendRTPPacket(RTC::RTPPacket* packet)
void Peer::Close()
{
MS_TRACE();
// TMP
if (this->iceTransport)
this->iceTransport->Close();
if (this->transport->IsReadyForMedia())
this->transport->SendRTPPacket(packet);
}
void Peer::SendRTCPPacket(RTC::RTCPPacket* packet)
{
MS_TRACE();
// TMP
this->listener->onPeerClosed(this);
if (this->transport->IsReadyForMedia())
this->transport->SendRTCPPacket(packet);
delete this;
}
Json::Value Peer::Dump()
......@@ -52,42 +45,50 @@ namespace RTC
Json::Value json(Json::objectValue);
// TODO: TMP
json["foo"] = "bar";
// TODO
return json;
}
void Peer::Close()
{
MS_TRACE();
// TMP
if (this->transport)
this->transport->Close();
delete this;
}
void Peer::onRTPPacket(RTC::Transport* transport, RTC::RTPPacket* packet)
{
MS_TRACE();
// MS_DEBUG("RTP packet received"); // TODO: TMP
// TMP
this->listener->onRTPPacket(this, packet);
}
void Peer::onRTCPPacket(RTC::Transport* transport, RTC::RTCPPacket* packet)
void Peer::HandleRequest(Channel::Request* request)
{
MS_TRACE();
// MS_DEBUG("RTCP packet received"); // TODO: TMP
// TMP
this->listener->onRTCPPacket(this, packet);
switch (request->methodId)
{
case Channel::Request::MethodId::createTransport:
{
try
{
this->iceTransport = new RTC::ICETransport(this, request->data);
}
catch (const MediaSoupError &error)
{
request->Reject(500, error.what());
return;
}
auto data = this->iceTransport->toJson();
request->Accept(data);
break;
}
case Channel::Request::MethodId::closeTransport:
case Channel::Request::MethodId::dumpTransport:
{
// TODO
request->Accept();
break;
}
default:
{
MS_ABORT("unknown method");
}
}
}
}
......@@ -4,13 +4,6 @@
#include "MediaSoupError.h"
#include "Logger.h"
// TMP
#define NUM_PEERS 4
#define PAYLOAD_TYPE_AUDIO 111 // OPUS
#define PAYLOAD_TYPE_VIDEO 100 // VP8
#define SSRC_AUDIO_BASE 100000
#define SSRC_VIDEO_BASE 200000
namespace RTC
{
/* Instance methods. */
......@@ -20,7 +13,7 @@ namespace RTC
{
MS_TRACE();
// TODO: do something wit data and throw if incorrect.
// TODO: do something with data and throw if incorrect.
}
Room::~Room()
......@@ -28,109 +21,23 @@ namespace RTC
MS_TRACE();
}
void Room::HandleCreatePeerRequest(Channel::Request* request)
{
MS_TRACE();
RTC::Peer* peer;
std::string peerId;
try
{
peer = GetPeerFromRequest(request, &peerId);
}
catch (const MediaSoupError &error)
{
request->Reject(500, error.what());
return;
}
if (peer)
{
MS_ERROR("Peer already exists");
request->Reject(500, "Peer already exists");
return;
}
try
{
peer = new RTC::Peer(this, peerId, request->data);
}
catch (const MediaSoupError &error)
{
request->Reject(500, error.what());
return;
}
this->peers[peerId] = peer;
MS_DEBUG("Peer created [peerId:%s]", peerId.c_str());
request->Accept();
}
void Room::HandleClosePeerRequest(Channel::Request* request)
{
MS_TRACE();
RTC::Peer* peer;
std::string peerId;
try
{
peer = GetPeerFromRequest(request, &peerId);
}
catch (const MediaSoupError &error)
{
request->Reject(500, error.what());
return;
}
if (!peer)
{
MS_ERROR("Peer does not exist");
request->Reject(500, "Peer does not exist");
return;
}
peer->Close();
// TODO: Instead of this, the Peer should fire an onPeerClosed() here.
this->peers.erase(peerId);
MS_DEBUG("Peer closed [peerId:%s]", peerId.c_str());
request->Accept();
}
void Room::HandleDumpPeerRequest(Channel::Request* request)
void Room::Close()
{
MS_TRACE();
RTC::Peer* peer;
std::string peerId;
try
{
peer = GetPeerFromRequest(request, &peerId);
}
catch (const MediaSoupError &error)
{
request->Reject(500, error.what());
return;
}
if (!peer)
// Close all the Peers.
// NOTE: Upon Peer closure the onPeerClosed() method is called which
// removes it from the map, so this is the safe way to iterate the mao
// and remove elements.
for (auto it = this->peers.begin(); it != this->peers.end();)
{
MS_ERROR("Peer does not exist");
auto peer = it->second;
request->Reject(500, "Peer does not exist");
return;
it = this->peers.erase(it);
peer->Close();
}
Json::Value jsonPeer = peer->Dump();
request->Accept(jsonPeer);
delete this;
}
Json::Value Room::Dump()
......@@ -152,22 +59,148 @@ namespace RTC
return json;
}
void Room::Close()
void Room::HandleRequest(Channel::Request* request)
{
MS_TRACE();
// Close all the Peers.
for (auto& kv : this->peers)
switch (request->methodId)
{
RTC::Peer* peer = kv.second;
peer->Close();
case Channel::Request::MethodId::createPeer:
{
RTC::Peer* peer;
std::string peerId;
try
{
peer = GetPeerFromRequest(request, &peerId);
}
catch (const MediaSoupError &error)
{
request->Reject(500, error.what());
return;
}
if (peer)
{
MS_ERROR("Peer already exists");
request->Reject(500, "Peer already exists");
return;
}
try
{
peer = new RTC::Peer(this, peerId, request->data);
}
catch (const MediaSoupError &error)
{
request->Reject(500, error.what());
return;
}
this->peers[peerId] = peer;
MS_DEBUG("Peer created [peerId:%s]", peerId.c_str());
request->Accept();
break;
}
case Channel::Request::MethodId::closePeer:
{
RTC::Peer* peer;
std::string peerId;
try
{
peer = GetPeerFromRequest(request, &peerId);
}
catch (const MediaSoupError &error)
{
request->Reject(500, error.what());
return;
}
if (!peer)
{
MS_ERROR("Peer does not exist");
request->Reject(500, "Peer does not exist");
return;
}
peer->Close();
request->Accept();
break;
}
case Channel::Request::MethodId::dumpPeer:
{
RTC::Peer* peer;
try
{
peer = GetPeerFromRequest(request);
}
catch (const MediaSoupError &error)
{
request->Reject(500, error.what());
return;
}
if (!peer)
{
MS_ERROR("Peer does not exist");
request->Reject(500, "Peer does not exist");
return;
}
Json::Value jsonPeer = peer->Dump();
request->Accept(jsonPeer);
break;
}
case Channel::Request::MethodId::createTransport:
case Channel::Request::MethodId::closeTransport:
case Channel::Request::MethodId::dumpTransport:
{
RTC::Peer* peer;
try
{
peer = GetPeerFromRequest(request);
}
catch (const MediaSoupError &error)
{
request->Reject(500, error.what());
return;
}
if (!peer)
{
MS_ERROR("Peer does not exist");
request->Reject(500, "Peer does not exist");
return;
}
peer->HandleRequest(request);
break;
}
default:
{
MS_ABORT("unknown method");
}
}
delete this;
}
RTC::Peer* Room::GetPeerFromRequest(Channel::Request* request, std::string* peerId = nullptr)
RTC::Peer* Room::GetPeerFromRequest(Channel::Request* request, std::string* peerId)
{
MS_TRACE();
......@@ -194,70 +227,10 @@ namespace RTC
}
}
void Room::onRTPPacket(RTC::Peer* peer, RTC::RTPPacket* packet)
{
MS_TRACE();
// int peer_id = *(int*)peer->GetUserData();
// MS_BYTE payload_type = packet->GetPayloadType();
// MS_4BYTES original_ssrc = packet->GetSSRC();
// MS_DEBUG("valid RTP packet received from Peer %d [ssrc: %llu | payload: %hu]",
// peer_id, (unsigned long long)packet->GetSSRC(), (unsigned short)packet->GetPayloadType());
// switch (payload_type)
// {
// case PAYLOAD_TYPE_AUDIO:
// case PAYLOAD_TYPE_VIDEO:
// break;
// default:
// MS_ERROR("payload is not OPUS %d nor VP8 %d, packet ignored", PAYLOAD_TYPE_AUDIO, PAYLOAD_TYPE_VIDEO);
// return;
// }
// // Deliver to all the peers.
// // TODO: but this one? yes (TODO)
// for (auto dst_peer : this->peers)
// {
// // if (dst_peer == peer)
// // continue;
// int dst_peer_id = *(int*)dst_peer->GetUserData();
// switch (payload_type)
// {
// case PAYLOAD_TYPE_AUDIO:
// packet->SetSSRC((MS_4BYTES)(SSRC_AUDIO_BASE + (peer_id * 10) + dst_peer_id));
// break;
// case PAYLOAD_TYPE_VIDEO:
// packet->SetSSRC((MS_4BYTES)(SSRC_VIDEO_BASE + (peer_id * 10) + dst_peer_id));
// break;
// default:
// MS_ABORT("no puede ser!!!");
// return;
// }
// MS_DEBUG("sending RTP packet to Peer %d [ssrc: %llu | payload: %hu | size: %zu]",
// dst_peer_id, (unsigned long long)packet->GetSSRC(), (unsigned short)packet->GetPayloadType(), packet->GetLength());
// dst_peer->SendRTPPacket(packet);
// // NOTE: recover the previous SSRC since other peers are going to
// // send this same RTPPacket!
// packet->SetSSRC(original_ssrc);
// }
}
void Room::onRTCPPacket(RTC::Peer* peer, RTC::RTCPPacket* packet)
void Room::onPeerClosed(RTC::Peer* peer)
{
MS_TRACE();
// TMP
// Ignore RTCP packets.
// for (auto dst_peer : this->peers) {
// dst_peer->SendRTCPPacket(packet);
// }
this->peers.erase(peer->peerId);
}
}
#define MS_CLASS "RTC::Stream"
#include "RTC/Stream.h"
#include "Logger.h"
namespace RTC
{
/* Instance methods. */
Stream::Stream()
{
MS_TRACE();
}
Stream::~Stream()
{
MS_TRACE();
}
void Stream::Close()
{
MS_TRACE();
delete this;
}
}
......@@ -2,7 +2,7 @@
#include "RTC/TCPConnection.h"
#include "RTC/STUNMessage.h"
#include "RTC/DTLSHandler.h"
#include "RTC/DTLSAgent.h"
#include "RTC/RTPPacket.h"
#include "RTC/RTCPPacket.h"
#include "Utils.h"
......@@ -84,7 +84,7 @@ namespace RTC
this->reader->onRTPDataRecv(this, packet, packet_len);
}
// Check if it's DTLS.
else if (DTLSHandler::IsDTLS(packet, packet_len))
else if (DTLSAgent::IsDTLS(packet, packet_len))
{
this->reader->onDTLSDataRecv(this, packet, packet_len);
}
......
......@@ -3,7 +3,6 @@
#include "RTC/TCPServer.h"
#include "RTC/STUNMessage.h"
#include "RTC/RTPPacket.h"
#include "RTC/DTLSHandler.h"
#include "Settings.h"
#include "Utils.h"
#include "DepLibUV.h"
......@@ -67,7 +66,7 @@ namespace RTC
while (i++ != RTC::TCPServer::maxPort);
}
RTC::TCPServer* TCPServer::New(int address_family)
RTC::TCPServer* TCPServer::Factory(Listener* listener, RTC::TCPConnection::Reader* reader, int address_family)
{
MS_TRACE();
......@@ -77,10 +76,10 @@ namespace RTC
// or there are no available ports.
RandomizePort(address_family, uvHandles, false);
return new RTC::TCPServer(uvHandles[0]);
return new RTC::TCPServer(listener, reader, uvHandles[0]);
}
void TCPServer::NewPair(int address_family, RTC::TCPServer* servers[])
void TCPServer::PairFactory(Listener* listener, RTC::TCPConnection::Reader* reader, int address_family, RTC::TCPServer* servers[])
{
MS_TRACE();
......@@ -90,8 +89,8 @@ namespace RTC
// or there are no available ports.
RandomizePort(address_family, uvHandles, true);
servers[0] = new RTC::TCPServer(uvHandles[0]);
servers[1] = new RTC::TCPServer(uvHandles[1]);
servers[0] = new RTC::TCPServer(listener, reader, uvHandles[0]);
servers[1] = new RTC::TCPServer(listener, reader, uvHandles[1]);
}
void TCPServer::RandomizePort(int address_family, uv_tcp_t* uvHandles[], bool pair)
......@@ -322,8 +321,10 @@ namespace RTC
/* Instance methods. */
TCPServer::TCPServer(uv_tcp_t* uvHandle) :
::TCPServer::TCPServer(uvHandle, 256)
TCPServer::TCPServer(Listener* listener, RTC::TCPConnection::Reader* reader, uv_tcp_t* uvHandle) :
::TCPServer::TCPServer(uvHandle, 256),
listener(listener),
reader(reader)
{
MS_TRACE();
}
......
#define MS_CLASS "RTC::Transport"
#include "RTC/Transport.h"
#include "RTC/FingerprintHash.h"
#include "MediaSoupError.h"
#include "Logger.h"
#define TRANSPORT_UDP "UDP"
#define TRANSPORT_TCP "TCP"
#define TRANSPORT_NAME(source) (source->IsUDP() ? TRANSPORT_UDP : TRANSPORT_TCP)
namespace RTC
{
/* Class variables. */
size_t Transport::maxSources = 8;
/* Class methods. */
Transport* Transport::NewWebRTC(Listener* listener)
{
MS_TRACE();
return new Transport(listener, Flag::ICE | Flag::DTLS | Flag::SRTP);
}
/* Instance methods. */
Transport::Transport(Listener* listener, int flags) :
listener(listener),
flags(flags)
{
MS_TRACE();
if (HasFlagICE())
this->iceServer = new RTC::ICEServer(this);
if (HasFlagDTLS())
{
this->dtlsHandler = new RTC::DTLSHandler(this);
// If DTLS flag is given then ensure SRTP flag is set.
this->flags |= Flag::SRTP;
}
}
Transport::~Transport()
{
MS_TRACE();
}
void Transport::AddUDPSocket(RTC::UDPSocket* socket)
{
MS_TRACE();
socket->SetListener(this);
this->udpSockets.push_back(socket);
}
void Transport::AddTCPServer(RTC::TCPServer* server)
{
MS_TRACE();
server->SetListeners(this, this);
this->tcpServers.push_back(server);
}
void Transport::Reset()
{
MS_TRACE();
this->sendingSource = nullptr;
for (auto it = this->sources.begin(); it != this->sources.end(); ++it)
{
RTC::TransportSource* source = &(*it);
source->Close();
}
this->sources.clear();
this->isIcePaired = false;
this->isIcePairedWithUseCandidate = false;
if (this->dtlsHandler && this->dtlsHandler->IsRunning())
this->dtlsHandler->Reset();
if (this->srtpRecvSession)
{
this->srtpRecvSession->Close();
this->srtpRecvSession = nullptr;
}
if (this->srtpSendSession)
{
this->srtpSendSession->Close();
this->srtpSendSession = nullptr;
}
}
void Transport::Close()
{
MS_TRACE();
if (this->iceServer)
this->iceServer->Close();
if (this->dtlsHandler)
this->dtlsHandler->Close();
if (this->srtpRecvSession)
this->srtpRecvSession->Close();
if (this->srtpSendSession)
this->srtpSendSession->Close();
for (auto socket : this->udpSockets)
socket->Close();
for (auto server : this->tcpServers)
server->Close();
delete this;
}
void Transport::SetLocalDTLSRole(RTC::DTLSRole role)
{
MS_TRACE();
if (!HasFlagDTLS())
{
MS_ERROR("no DTLS flag");
return;
}
// If no changes are being made return.
if (this->dtlsRole == role)
{
MS_DEBUG("given DTLS role matches the current one, doing nothing");
return;
}
// Update local DTLS role.
this->dtlsRole = role;
// Otherwise, if the DTLS handler is running, reset it.
if (this->dtlsHandler->IsRunning())
this->dtlsHandler->Reset();
// If ready, run the DTLS handler.
if (this->dtlsRole != RTC::DTLSRole::NONE)
RunDTLSHandlerIfReady();
}
void Transport::SetRemoteDTLSFingerprint(RTC::FingerprintHash hash, std::string& fingerprint)
{
MS_TRACE();
if (!HasFlagDTLS())
{
MS_ERROR("no DTLS flag");
return;
}
this->dtlsHandler->SetRemoteFingerprint(hash, fingerprint);
}
void Transport::SetLocalSRTPKey(RTC::SRTPProfile srtp_profile, MS_BYTE* srtp_local_key, size_t srtp_local_key_len)
{
MS_TRACE();
if (!HasFlagSRTP())
{
MS_ERROR("transport without SRTP");
return;
}
// Close it if it was already set and update it.
if (this->srtpSendSession)
{
this->srtpSendSession->Close();
this->srtpSendSession = nullptr;
}
try
{
this->srtpSendSession = new RTC::SRTPSession(SRTPSession::Type::OUTBOUND, srtp_profile, srtp_local_key, srtp_local_key_len);
}
catch (const MediaSoupError &error)
{
MS_ERROR("error creating SRTP sending session: %s", error.what());
}
}
void Transport::SetRemoteSRTPKey(RTC::SRTPProfile srtp_profile, MS_BYTE* srtp_remote_key, size_t srtp_remote_key_len)
{
MS_TRACE();
if (!HasFlagSRTP())
{
MS_ERROR("transport without SRTP");
return;
}
// Close it if it was already set and update it.
if (this->srtpRecvSession)
{
this->srtpRecvSession->Close();
this->srtpRecvSession = nullptr;
}
try
{
this->srtpRecvSession = new RTC::SRTPSession(SRTPSession::Type::INBOUND, srtp_profile, srtp_remote_key, srtp_remote_key_len);
}
catch (const MediaSoupError &error)
{
MS_ERROR("error creating SRTP receiving session: %s", error.what());
}
}
void Transport::SendRTPPacket(RTC::RTPPacket* packet)
{
MS_TRACE();
if (!this->sendingSource)
{
MS_WARN("no sending address set, cannot send RTP packet");
return;
}
const MS_BYTE* data = packet->GetRaw();
size_t len = packet->GetLength();
if (HasFlagSRTP())
{
if (!this->srtpSendSession)
{
MS_WARN("SRTP sending session not set, cannot send RTP packet");
return;
}
if (!this->srtpSendSession->EncryptRTP(&data, &len))
{
MS_WARN("error encrypting RTP packet: %s", this->srtpSendSession->GetLastErrorDesc());
return;
}
MS_DEBUG("sending SRTP packet of %zu bytes", len);
}
else
{
MS_DEBUG("sending RTP packet of %zu bytes", len);
}
this->sendingSource->Send(data, len);
}
void Transport::SendRTCPPacket(RTC::RTCPPacket* packet)
{
MS_TRACE();
if (!this->sendingSource)
{
MS_WARN("no sending address set, cannot send RTCP packet");
return;
}
const MS_BYTE* data = packet->GetRaw();
size_t len = packet->GetLength();
if (HasFlagSRTP())
{
if (!this->srtpSendSession)
{
MS_WARN("SRTP sending session not set, cannot send RTCP packet");
return;
}
if (!this->srtpSendSession->EncryptRTCP(&data, &len))
{
MS_WARN("error encrypting RTCP packet: %s", this->srtpSendSession->GetLastErrorDesc());
return;
}
MS_DEBUG("sending SRTCP packet of %zu bytes", len);
}
else
{
MS_DEBUG("sending RTCP packet of %zu bytes", len);
}
this->sendingSource->Send(data, len);
}
void Transport::Dump()
{
MS_DEBUG("%zu valid sources:", this->sources.size());
for (auto it = this->sources.begin(); it != this->sources.end(); ++it)
{
RTC::TransportSource* source = &(*it);
source->Dump();
}
if (this->sendingSource)
{
MS_DEBUG("sending source:");
this->sendingSource->Dump();
}
if (this->dtlsHandler)
this->dtlsHandler->Dump();
}
inline
void Transport::RunDTLSHandlerIfReady()
{
MS_TRACE();
if (!this->dtlsHandler->IsRunning() && this->sendingSource)
{
switch (this->dtlsRole)
{
// If we are DTLS server then run the DTLS handler upon first valid ICE pair.
case RTC::DTLSRole::SERVER:
if (this->isIcePaired)
{
MS_DEBUG("running DTLS handler in server role");
this->dtlsHandler->Run(this->dtlsRole);
}
break;
// If we are DTLS client then wait for the first Binding with USE-CANDIDATE.
case RTC::DTLSRole::CLIENT:
if (this->isIcePairedWithUseCandidate)
{
MS_DEBUG("running DTLS handler in client role");
this->dtlsHandler->Run(this->dtlsRole);
}
break;
case RTC::DTLSRole::NONE:
break;
}
}
}
inline
void Transport::onSTUNDataRecv(RTC::TransportSource* source, const MS_BYTE* data, size_t len)
{
MS_TRACE();
if (!HasFlagICE())
{
MS_DEBUG("no ICE flag, ignoring STUN message received via %s", TRANSPORT_NAME(source));
return;
}
RTC::STUNMessage* msg = RTC::STUNMessage::Parse(data, len);
if (!msg)
{
MS_DEBUG("ignoring wrong STUN message received via %s", TRANSPORT_NAME(source));
return;
}
MS_DEBUG("STUN message received via %s, passing it to the ICEServer", TRANSPORT_NAME(source));
// msg->Dump();
this->iceServer->ProcessSTUNMessage(msg, source);
delete msg;
}
inline
void Transport::onDTLSDataRecv(RTC::TransportSource* source, const MS_BYTE* data, size_t len)
{
MS_TRACE();
if (!HasFlagDTLS())
{
MS_DEBUG("no DTLS flag, ignoring DTLS data received via %s", TRANSPORT_NAME(source));
return;
}
if (!IsValidSource(source))
{
MS_DEBUG("ignoring DTLS data coming from an invalid %s address", TRANSPORT_NAME(source));
return;
}
if (this->dtlsHandler->IsRunning())
{
MS_DEBUG("DTLS data received via %s, passing it to the DTLSHandler", TRANSPORT_NAME(source));
this->dtlsHandler->ProcessDTLSData(data, len);
}
else
{
MS_DEBUG("no DTLSHandler running, ignoring DTLS data received via %s", TRANSPORT_NAME(source));
return;
}
}
inline
void Transport::onRTPDataRecv(RTC::TransportSource* source, const MS_BYTE* data, size_t len)
{
MS_TRACE();
if (!IsValidSource(source))
{
MS_DEBUG("ignoring RTP packet coming from an invalid %s address", TRANSPORT_NAME(source));
return;
}
if (HasFlagSRTP())
{
if (!this->srtpRecvSession)
{
MS_DEBUG("SRTP receiving session not set, ignoring received RTP packet via %s", TRANSPORT_NAME(source));
return;
}
if (!this->srtpRecvSession->DecryptSRTP(data, &len))
{
MS_WARN("error decrypting SRTP packet received via %s: %s", TRANSPORT_NAME(source), this->srtpRecvSession->GetLastErrorDesc());
return;
}
}
RTC::RTPPacket* packet = RTC::RTPPacket::Parse(data, len);
if (!packet)
{
MS_DEBUG("data received via %s is not a valid RTP packet", TRANSPORT_NAME(source));
return;
}
// MS_DEBUG("valid RTP packet received via %s [ssrc: %llu | payload: %hu | size: %zu]",
// TRANSPORT_NAME(source), (unsigned long long)packet->GetSSRC(), (unsigned short)packet->GetPayloadType(), len);
// Pass the RTP packet to the listener.
this->listener->onRTPPacket(this, packet);
delete packet;
}
inline
void Transport::onRTCPDataRecv(RTC::TransportSource* source, const MS_BYTE* data, size_t len)
{
MS_TRACE();
if (!IsValidSource(source))
{
MS_DEBUG("ignoring RTCP packet coming from an invalid %s address", TRANSPORT_NAME(source));
return;
}
if (HasFlagSRTP())
{
if (!this->srtpRecvSession)
{
MS_DEBUG("SRTP receiving session not set, ignoring received RTCP packet via %s", TRANSPORT_NAME(source));
return;
}
if (!this->srtpRecvSession->DecryptSRTCP(data, &len))
{
MS_DEBUG("error decrypting SRTCP packet received via %s: %s", TRANSPORT_NAME(source), this->srtpRecvSession->GetLastErrorDesc());
return;
}
}
RTC::RTCPPacket* packet = RTC::RTCPPacket::Parse(data, len);
if (!packet)
{
MS_DEBUG("data received via %s is not a valid RTCP packet", TRANSPORT_NAME(source));
return;
}
// MS_DEBUG("valid RTCP packet received via %s", TRANSPORT_NAME(source));
// Pass the RTP packet to the listener.
this->listener->onRTCPPacket(this, packet);
delete packet;
}
void Transport::onSTUNDataRecv(RTC::UDPSocket *socket, const MS_BYTE* data, size_t len, const struct sockaddr* remote_addr)
{
MS_TRACE();
RTC::TransportSource source(socket, remote_addr);
onSTUNDataRecv(&source, data, len);
}
void Transport::onDTLSDataRecv(RTC::UDPSocket *socket, const MS_BYTE* data, size_t len, const struct sockaddr* remote_addr)
{
MS_TRACE();
RTC::TransportSource source(socket, remote_addr);
onDTLSDataRecv(&source, data, len);
}
void Transport::onRTPDataRecv(RTC::UDPSocket *socket, const MS_BYTE* data, size_t len, const struct sockaddr* remote_addr)
{
MS_TRACE();
RTC::TransportSource source(socket, remote_addr);
onRTPDataRecv(&source, data, len);
}
void Transport::onRTCPDataRecv(RTC::UDPSocket *socket, const MS_BYTE* data, size_t len, const struct sockaddr* remote_addr)
{
MS_TRACE();
RTC::TransportSource source(socket, remote_addr);
onRTCPDataRecv(&source, data, len);
}
void Transport::onRTCTCPConnectionClosed(RTC::TCPServer* tcpServer, RTC::TCPConnection* connection, bool is_closed_by_peer)
{
MS_TRACE();
RTC::TransportSource source(connection);
if (RemoveSource(&source))
{
MS_DEBUG("valid source %s:", is_closed_by_peer ? "closed by peer" : "locally closed");
source.Dump();
}
}
void Transport::onSTUNDataRecv(RTC::TCPConnection *connection, const MS_BYTE* data, size_t len)
{
MS_TRACE();
RTC::TransportSource source(connection);
onSTUNDataRecv(&source, data, len);
}
void Transport::onDTLSDataRecv(RTC::TCPConnection *connection, const MS_BYTE* data, size_t len)
{
MS_TRACE();
RTC::TransportSource source(connection);
onDTLSDataRecv(&source, data, len);
}
void Transport::onRTPDataRecv(RTC::TCPConnection *connection, const MS_BYTE* data, size_t len)
{
MS_TRACE();
RTC::TransportSource source(connection);
onRTPDataRecv(&source, data, len);
}
void Transport::onRTCPDataRecv(RTC::TCPConnection *connection, const MS_BYTE* data, size_t len)
{
MS_TRACE();
RTC::TransportSource source(connection);
onRTCPDataRecv(&source, data, len);
}
void Transport::onOutgoingSTUNMessage(RTC::ICEServer* iceServer, RTC::STUNMessage* msg, RTC::TransportSource* source)
{
MS_TRACE();
MS_DEBUG("sending STUN message to:");
source->Dump();
// msg->Dump();
source->Send(msg->GetRaw(), msg->GetLength());
}
void Transport::onICEValidPair(RTC::ICEServer* iceServer, RTC::TransportSource* source, bool has_use_candidate)
{
MS_TRACE();
this->isIcePaired = true;
if (has_use_candidate)
this->isIcePairedWithUseCandidate = true;
/*
* RFC 5245 section 11.2 "Receiving Media":
*
* ICE implementations MUST be prepared to receive media on each component
* on any candidates provided for that component.
*/
if (SetSendingSource(source))
{
MS_DEBUG("ICE paired");
Dump();
}
// If ready, run the DTLS handler.
if (HasFlagDTLS())
RunDTLSHandlerIfReady();
}
void Transport::onOutgoingDTLSData(RTC::DTLSHandler* dtlsHandler, const MS_BYTE* data, size_t len)
{
MS_TRACE();
if (!this->sendingSource)
{
MS_WARN("no sending address set, cannot send DTLS packet");
return;
}
MS_DEBUG("sending DTLS data to to:");
this->sendingSource->Dump();
this->sendingSource->Send(data, len);
}
void Transport::onDTLSConnected(RTC::DTLSHandler* dtlsHandler)
{
MS_TRACE();
MS_DEBUG("DTLS connected");
Dump();
}
void Transport::onDTLSDisconnected(RTC::DTLSHandler* dtlsHandler)
{
MS_TRACE();
MS_DEBUG("DTLS disconnected");
Reset();
Dump();
}
void Transport::onDTLSFailed(RTC::DTLSHandler* dtlsHandler)
{
MS_TRACE();
MS_DEBUG("DTLS failed");
Reset();
Dump();
}
void Transport::onSRTPKeyMaterial(RTC::DTLSHandler* dtlsHandler, RTC::SRTPProfile srtp_profile, MS_BYTE* srtp_local_key, size_t srtp_local_key_len, MS_BYTE* srtp_remote_key, size_t srtp_remote_key_len)
{
MS_TRACE();
MS_DEBUG("got SRTP key material");
SetLocalSRTPKey(srtp_profile, srtp_local_key, srtp_local_key_len);
SetRemoteSRTPKey(srtp_profile, srtp_remote_key, srtp_remote_key_len);
}
void Transport::onDTLSApplicationData(RTC::DTLSHandler* dtlsHandler, const MS_BYTE* data, size_t len)
{
MS_TRACE();
MS_DEBUG("DTLS application data received | size: %zu", len);
// TMP
MS_DEBUG("data: %s", std::string((char*)data, len).c_str());
// TMP
dtlsHandler->SendApplicationData(data, len);
}
}
......@@ -2,7 +2,7 @@
#include "RTC/UDPSocket.h"
#include "RTC/STUNMessage.h"
#include "RTC/DTLSHandler.h"
#include "RTC/DTLSAgent.h"
#include "RTC/RTPPacket.h"
#include "RTC/RTCPPacket.h"
#include "Settings.h"
......@@ -67,7 +67,7 @@ namespace RTC
while (i++ != RTC::UDPSocket::maxPort);
}
RTC::UDPSocket* UDPSocket::New(int address_family)
RTC::UDPSocket* UDPSocket::Factory(Listener* listener, int address_family)
{
MS_TRACE();
......@@ -77,10 +77,10 @@ namespace RTC
// or there are no available ports.
RandomizePort(address_family, uvHandles, false);
return new RTC::UDPSocket(uvHandles[0]);
return new RTC::UDPSocket(listener, uvHandles[0]);
}
void UDPSocket::NewPair(int address_family, RTC::UDPSocket* sockets[])
void UDPSocket::PairFactory(Listener* listener, int address_family, RTC::UDPSocket* sockets[])
{
MS_TRACE();
......@@ -90,8 +90,8 @@ namespace RTC
// or there are no available ports.
RandomizePort(address_family, uvHandles, true);
sockets[0] = new RTC::UDPSocket(uvHandles[0]);
sockets[1] = new RTC::UDPSocket(uvHandles[1]);
sockets[0] = new RTC::UDPSocket(listener, uvHandles[0]);
sockets[1] = new RTC::UDPSocket(listener, uvHandles[1]);
}
void UDPSocket::RandomizePort(int address_family, uv_udp_t* uvHandles[], bool pair)
......@@ -320,8 +320,9 @@ namespace RTC
/* Instance methods. */
UDPSocket::UDPSocket(uv_udp_t* uvHandle) :
::UDPSocket::UDPSocket(uvHandle)
UDPSocket::UDPSocket(Listener* listener, uv_udp_t* uvHandle) :
::UDPSocket::UDPSocket(uvHandle),
listener(listener)
{
MS_TRACE();
}
......@@ -367,7 +368,7 @@ namespace RTC
}
// Check if it's DTLS.
if (DTLSHandler::IsDTLS(data, len))
if (DTLSAgent::IsDTLS(data, len))
{
this->listener->onDTLSDataRecv(this, data, len, addr);
return;
......
......@@ -9,7 +9,7 @@
#include "Utils.h"
#include "RTC/UDPSocket.h"
#include "RTC/TCPServer.h"
#include "RTC/DTLSHandler.h"
#include "RTC/DTLSAgent.h"
#include "RTC/SRTPSession.h"
#include "Loop.h"
#include "MediaSoupError.h"
......@@ -91,7 +91,7 @@ void init()
DepUsrSCTP::ClassInit();
RTC::UDPSocket::ClassInit();
RTC::TCPServer::ClassInit();
RTC::DTLSHandler::ClassInit();
RTC::DTLSAgent::ClassInit();
RTC::SRTPSession::ClassInit();
Utils::Crypto::ClassInit();
}
......@@ -137,6 +137,6 @@ void destroy()
DepOpenSSL::ClassDestroy();
DepLibSRTP::ClassDestroy();
DepUsrSCTP::ClassDestroy();
RTC::DTLSHandler::ClassDestroy();
RTC::DTLSAgent::ClassDestroy();
Utils::Crypto::ClassDestroy();
}
Markdown 格式
0% 或
您添加了 0 人 到此讨论。请谨慎行事。
请先完成此评论的编辑!
请 注册 或者 后发表评论