提交 4a41ded0 authored 作者: Iñaki Baz Castillo's avatar Iñaki Baz Castillo

Some work done in C++ syntax.

上级 68826efa
...@@ -38,9 +38,6 @@ namespace RTC ...@@ -38,9 +38,6 @@ namespace RTC
virtual void onIceDisconnected(const IceServer* iceServer) = 0; virtual void onIceDisconnected(const IceServer* iceServer) = 0;
}; };
private:
static uint8_t stunSerializeBuffer[];
public: public:
IceServer(Listener* listener, const std::string& usernameFragment, const std::string& password); IceServer(Listener* listener, const std::string& usernameFragment, const std::string& password);
...@@ -56,7 +53,7 @@ namespace RTC ...@@ -56,7 +53,7 @@ namespace RTC
void ForceSelectedTuple(const RTC::TransportTuple* tuple); void ForceSelectedTuple(const RTC::TransportTuple* tuple);
private: private:
void HandleTuple(RTC::TransportTuple* tuple, bool has_use_candidate); void HandleTuple(RTC::TransportTuple* tuple, bool hasUseCandidate);
/** /**
* Store the given tuple and return its stored address. * Store the given tuple and return its stored address.
*/ */
...@@ -69,7 +66,7 @@ namespace RTC ...@@ -69,7 +66,7 @@ namespace RTC
* Set the given tuple as the selected tuple. * Set the given tuple as the selected tuple.
* NOTE: The given tuple MUST be already stored within the list. * NOTE: The given tuple MUST be already stored within the list.
*/ */
void SetSelectedTuple(RTC::TransportTuple* stored_tuple); void SetSelectedTuple(RTC::TransportTuple* storedTuple);
private: private:
// Passed by argument. // Passed by argument.
......
...@@ -16,7 +16,7 @@ namespace RTC ...@@ -16,7 +16,7 @@ namespace RTC
class Listener class Listener
{ {
public: public:
virtual void onNackRequired(const std::vector<uint16_t>& seq_numbers) = 0; virtual void onNackRequired(const std::vector<uint16_t>& seqNumbers) = 0;
virtual void onFullFrameRequired() = 0; virtual void onFullFrameRequired() = 0;
}; };
...@@ -24,11 +24,11 @@ namespace RTC ...@@ -24,11 +24,11 @@ namespace RTC
struct NackInfo struct NackInfo
{ {
NackInfo() {}; NackInfo() {};
explicit NackInfo(uint32_t seq32, uint32_t send_at_seq_num); explicit NackInfo(uint32_t seq32, uint32_t sendAtSeqNum);
uint32_t seq32 = 0; uint32_t seq32 = 0;
uint32_t send_at_seq_num = 0; uint32_t sendAtSeqNum = 0;
uint64_t sent_at_time = 0; uint64_t sentAtTime = 0;
uint8_t retries = 0; uint8_t retries = 0;
}; };
...@@ -45,7 +45,7 @@ namespace RTC ...@@ -45,7 +45,7 @@ namespace RTC
void ReceivePacket(RTC::RtpPacket* packet); void ReceivePacket(RTC::RtpPacket* packet);
private: private:
void AddPacketsToNackList(uint32_t seq32_start, uint32_t seq32_end); void AddPacketsToNackList(uint32_t seq32Start, uint32_t seq32End);
std::vector<uint16_t> GetNackBatch(NackFilter filter); std::vector<uint16_t> GetNackBatch(NackFilter filter);
void MayRunTimer() const; void MayRunTimer() const;
...@@ -59,18 +59,18 @@ namespace RTC ...@@ -59,18 +59,18 @@ namespace RTC
// Allocated by this. // Allocated by this.
Timer* timer = nullptr; Timer* timer = nullptr;
// Others. // Others.
std::map<uint32_t, NackInfo> nack_list; std::map<uint32_t, NackInfo> nackList;
bool started = false; bool started = false;
uint32_t last_seq32 = 0; // Extended seq number of last valid packet. uint32_t lastSeq32 = 0; // Extended seq number of last valid packet.
uint32_t rtt = 0; // Round trip time (ms). uint32_t rtt = 0; // Round trip time (ms).
}; };
// Inline instance methods. // Inline instance methods.
inline inline
NackGenerator::NackInfo::NackInfo(uint32_t seq32, uint32_t send_at_seq_num) : NackGenerator::NackInfo::NackInfo(uint32_t seq32, uint32_t sendAtSeqNum) :
seq32(seq32), seq32(seq32),
send_at_seq_num(send_at_seq_num) sendAtSeqNum(sendAtSeqNum)
{} {}
} }
......
...@@ -14,22 +14,22 @@ namespace RTC ...@@ -14,22 +14,22 @@ namespace RTC
/* Struct for RTP header. */ /* Struct for RTP header. */
struct Header struct Header
{ {
#if defined(MS_LITTLE_ENDIAN) #if defined(MS_LITTLE_ENDIAN)
uint8_t csrc_count:4; uint8_t csrcCount:4;
uint8_t extension:1; uint8_t extension:1;
uint8_t padding:1; uint8_t padding:1;
uint8_t version:2; uint8_t version:2;
uint8_t payload_type:7; uint8_t payloadType:7;
uint8_t marker:1; uint8_t marker:1;
#elif defined(MS_BIG_ENDIAN) #elif defined(MS_BIG_ENDIAN)
uint8_t version:2; uint8_t version:2;
uint8_t padding:1; uint8_t padding:1;
uint8_t extension:1; uint8_t extension:1;
uint8_t csrc_count:4; uint8_t csrcCount:4;
uint8_t marker:1; uint8_t marker:1;
uint8_t payload_type:7; uint8_t payloadType:7;
#endif #endif
uint16_t sequence_number; uint16_t sequenceNumber;
uint32_t timestamp; uint32_t timestamp;
uint32_t ssrc; uint32_t ssrc;
}; };
...@@ -47,13 +47,13 @@ namespace RTC ...@@ -47,13 +47,13 @@ namespace RTC
/* Struct for One-Byte extension. */ /* Struct for One-Byte extension. */
struct OneByteExtension struct OneByteExtension
{ {
#if defined(MS_LITTLE_ENDIAN) #if defined(MS_LITTLE_ENDIAN)
uint8_t len:4; uint8_t len:4;
uint8_t id:4; uint8_t id:4;
#elif defined(MS_BIG_ENDIAN) #elif defined(MS_BIG_ENDIAN)
uint8_t id:4; uint8_t id:4;
uint8_t len:4; uint8_t len:4;
#endif #endif
uint8_t value[1]; uint8_t value[1];
}; };
...@@ -61,13 +61,13 @@ namespace RTC ...@@ -61,13 +61,13 @@ namespace RTC
/* Struct for Two-Bytes extension. */ /* Struct for Two-Bytes extension. */
struct TwoBytesExtension struct TwoBytesExtension
{ {
#if defined(MS_LITTLE_ENDIAN) #if defined(MS_LITTLE_ENDIAN)
uint8_t len:8; uint8_t len:8;
uint8_t id:8; uint8_t id:8;
#elif defined(MS_BIG_ENDIAN) #elif defined(MS_BIG_ENDIAN)
uint8_t id:8; uint8_t id:8;
uint8_t len:8; uint8_t len:8;
#endif #endif
uint8_t value[1]; uint8_t value[1];
}; };
...@@ -83,7 +83,7 @@ namespace RTC ...@@ -83,7 +83,7 @@ namespace RTC
const uint8_t* GetData() const; const uint8_t* GetData() const;
size_t GetSize() const; size_t GetSize() const;
uint8_t GetPayloadType() const; uint8_t GetPayloadType() const;
void SetPayloadType(uint8_t payload_type); void SetPayloadType(uint8_t payloadType);
bool HasMarker() const; bool HasMarker() const;
void SetMarker(bool marker); void SetMarker(bool marker);
uint16_t GetSequenceNumber() const; uint16_t GetSequenceNumber() const;
...@@ -162,13 +162,13 @@ namespace RTC ...@@ -162,13 +162,13 @@ namespace RTC
inline inline
uint8_t RtpPacket::GetPayloadType() const uint8_t RtpPacket::GetPayloadType() const
{ {
return this->header->payload_type; return this->header->payloadType;
} }
inline inline
void RtpPacket::SetPayloadType(uint8_t payload_type) void RtpPacket::SetPayloadType(uint8_t payloadType)
{ {
this->header->payload_type = payload_type; this->header->payloadType = payloadType;
} }
inline inline
...@@ -186,13 +186,13 @@ namespace RTC ...@@ -186,13 +186,13 @@ namespace RTC
inline inline
uint16_t RtpPacket::GetSequenceNumber() const uint16_t RtpPacket::GetSequenceNumber() const
{ {
return (uint16_t)ntohs(this->header->sequence_number); return (uint16_t)ntohs(this->header->sequenceNumber);
} }
inline inline
void RtpPacket::SetSequenceNumber(uint16_t seq) void RtpPacket::SetSequenceNumber(uint16_t seq)
{ {
this->header->sequence_number = (uint16_t)htons(seq); this->header->sequenceNumber = (uint16_t)htons(seq);
} }
inline inline
...@@ -298,6 +298,7 @@ namespace RTC ...@@ -298,6 +298,7 @@ namespace RTC
return nullptr; return nullptr;
*len = this->oneByteExtensions.at(id)->len + 1; *len = this->oneByteExtensions.at(id)->len + 1;
return this->oneByteExtensions.at(id)->value; return this->oneByteExtensions.at(id)->value;
} }
else if (HasTwoBytesExtensions()) else if (HasTwoBytesExtensions())
...@@ -306,6 +307,7 @@ namespace RTC ...@@ -306,6 +307,7 @@ namespace RTC
return nullptr; return nullptr;
*len = this->oneByteExtensions.at(id)->len; *len = this->oneByteExtensions.at(id)->len;
return this->twoBytesExtensions.at(id)->value; return this->twoBytesExtensions.at(id)->value;
} }
else else
...@@ -317,15 +319,15 @@ namespace RTC ...@@ -317,15 +319,15 @@ namespace RTC
inline inline
bool RtpPacket::ReadAudioLevel(uint8_t* volume, bool* voice) const bool RtpPacket::ReadAudioLevel(uint8_t* volume, bool* voice) const
{ {
uint8_t exten_len; uint8_t extenLen;
uint8_t* exten_value; uint8_t* extenValue;
exten_value = GetExtension(RtpHeaderExtensionUri::Type::SSRC_AUDIO_LEVEL, &exten_len); extenValue = GetExtension(RtpHeaderExtensionUri::Type::SSRC_AUDIO_LEVEL, &extenLen);
if (!exten_value || exten_len != 1) if (!extenValue || extenLen != 1)
return false; return false;
*volume = Utils::Byte::Get1Byte(exten_value, 0); *volume = Utils::Byte::Get1Byte(extenValue, 0);
*voice = (*volume & (1 << 7)) ? true : false; *voice = (*volume & (1 << 7)) ? true : false;
*volume &= ~(1 << 7); *volume &= ~(1 << 7);
...@@ -335,15 +337,15 @@ namespace RTC ...@@ -335,15 +337,15 @@ namespace RTC
inline inline
bool RtpPacket::ReadAbsSendTime(uint32_t* time) const bool RtpPacket::ReadAbsSendTime(uint32_t* time) const
{ {
uint8_t exten_len; uint8_t extenLen;
uint8_t* exten_value; uint8_t* extenValue;
exten_value = GetExtension(RtpHeaderExtensionUri::Type::ABS_SEND_TIME, &exten_len); extenValue = GetExtension(RtpHeaderExtensionUri::Type::ABS_SEND_TIME, &extenLen);
if (!exten_value || exten_len != 3) if (!extenValue || extenLen != 3)
return false; return false;
*time = Utils::Byte::Get3Bytes(exten_value, 0); *time = Utils::Byte::Get3Bytes(extenValue, 0);
return true; return true;
} }
......
...@@ -66,7 +66,7 @@ namespace RTC ...@@ -66,7 +66,7 @@ namespace RTC
/* Pure virtual methods inherited from RTC::RtpStreamRecv::Listener. */ /* Pure virtual methods inherited from RTC::RtpStreamRecv::Listener. */
public: public:
virtual void onNackRequired(RTC::RtpStreamRecv* rtpStream, const std::vector<uint16_t>& seq_numbers) override; virtual void onNackRequired(RTC::RtpStreamRecv* rtpStream, const std::vector<uint16_t>& seqNumbers) override;
virtual void onPliRequired(RTC::RtpStreamRecv* rtpStream) override; virtual void onPliRequired(RTC::RtpStreamRecv* rtpStream) override;
public: public:
...@@ -121,6 +121,7 @@ namespace RTC ...@@ -121,6 +121,7 @@ namespace RTC
void RtpReceiver::ReceiveRtcpSenderReport(RTC::RTCP::SenderReport* report) void RtpReceiver::ReceiveRtcpSenderReport(RTC::RTCP::SenderReport* report)
{ {
auto it = this->rtpStreams.find(report->GetSsrc()); auto it = this->rtpStreams.find(report->GetSsrc());
if (it != this->rtpStreams.end()) if (it != this->rtpStreams.end())
{ {
auto rtpStream = it->second; auto rtpStream = it->second;
......
...@@ -14,7 +14,6 @@ ...@@ -14,7 +14,6 @@
#include "Channel/Request.hpp" #include "Channel/Request.hpp"
#include "Channel/Notifier.hpp" #include "Channel/Notifier.hpp"
#include <unordered_set> #include <unordered_set>
#include <vector>
#include <json/json.h> #include <json/json.h>
namespace RTC namespace RTC
...@@ -31,10 +30,6 @@ namespace RTC ...@@ -31,10 +30,6 @@ namespace RTC
virtual void onRtpSenderClosed(RtpSender* rtpSender) = 0; virtual void onRtpSenderClosed(RtpSender* rtpSender) = 0;
}; };
private:
// Container of RTP packets to retransmit.
static std::vector<RTC::RtpPacket*> rtpRetransmissionContainer;
public: public:
RtpSender(Listener* listener, Channel::Notifier* notifier, uint32_t rtpSenderId, RTC::Media::Kind kind); RtpSender(Listener* listener, Channel::Notifier* notifier, uint32_t rtpSenderId, RTC::Media::Kind kind);
......
...@@ -46,16 +46,16 @@ namespace RTC ...@@ -46,16 +46,16 @@ namespace RTC
// Others. // Others.
bool started = false; // Whether at least a RTP packet has been received. bool started = false; // Whether at least a RTP packet has been received.
// https://tools.ietf.org/html/rfc3550#appendix-A.1 stuff. // https://tools.ietf.org/html/rfc3550#appendix-A.1 stuff.
uint16_t max_seq = 0; // Highest seq. number seen. uint16_t maxSeq = 0; // Highest seq. number seen.
uint32_t cycles = 0; // Shifted count of seq. number cycles. uint32_t cycles = 0; // Shifted count of seq. number cycles.
uint32_t base_seq = 0; // Base seq number. uint32_t baseSeq = 0; // Base seq number.
uint32_t bad_seq = 0; // Last 'bad' seq number + 1. uint32_t badSeq = 0; // Last 'bad' seq number + 1.
uint32_t probation = 0; // Seq. packets till source is valid. uint32_t probation = 0; // Seq. packets till source is valid.
uint32_t received = 0; // Packets received. uint32_t received = 0; // Packets received.
uint32_t expected_prior = 0; // Packet expected at last interval. uint32_t expectedPrior = 0; // Packet expected at last interval.
uint32_t received_prior = 0; // Packet received at last interval. uint32_t receivedPrior = 0; // Packet received at last interval.
// Others. // Others.
uint32_t max_timestamp = 0; // Highest timestamp seen. uint32_t maxTimestamp = 0; // Highest timestamp seen.
}; };
/* Inline instance methods. */ /* Inline instance methods. */
......
...@@ -16,7 +16,7 @@ namespace RTC ...@@ -16,7 +16,7 @@ namespace RTC
class Listener class Listener
{ {
public: public:
virtual void onNackRequired(RTC::RtpStreamRecv* rtpStream, const std::vector<uint16_t>& seq_numbers) = 0; virtual void onNackRequired(RTC::RtpStreamRecv* rtpStream, const std::vector<uint16_t>& seqNumbers) = 0;
virtual void onPliRequired(RTC::RtpStreamRecv* rtpStream) = 0; virtual void onPliRequired(RTC::RtpStreamRecv* rtpStream) = 0;
}; };
...@@ -39,15 +39,15 @@ namespace RTC ...@@ -39,15 +39,15 @@ namespace RTC
/* Pure virtual methods inherited from RTC::NackGenerator. */ /* Pure virtual methods inherited from RTC::NackGenerator. */
protected: protected:
virtual void onNackRequired(const std::vector<uint16_t>& seq_numbers) override; virtual void onNackRequired(const std::vector<uint16_t>& seqNumbers) override;
virtual void onFullFrameRequired() override; virtual void onFullFrameRequired() override;
private: private:
// Passed by argument. // Passed by argument.
Listener* listener = nullptr; Listener* listener = nullptr;
// Others. // Others.
uint32_t last_sr_timestamp = 0; // The middle 32 bits out of 64 in the NTP timestamp received in the most recent sender report. uint32_t lastSrTimestamp = 0; // The middle 32 bits out of 64 in the NTP timestamp received in the most recent sender report.
uint64_t last_sr_received = 0; // Wallclock time representing the most recent sender report arrival. uint64_t lastSrReceived = 0; // Wallclock time representing the most recent sender report arrival.
uint32_t transit = 0; // Relative trans time for prev pkt. uint32_t transit = 0; // Relative trans time for prev pkt.
uint32_t jitter = 0; // Estimated jitter. uint32_t jitter = 0; // Estimated jitter.
std::unique_ptr<RTC::NackGenerator> nackGenerator; std::unique_ptr<RTC::NackGenerator> nackGenerator;
......
...@@ -21,8 +21,8 @@ namespace RTC ...@@ -21,8 +21,8 @@ namespace RTC
private: private:
struct BufferItem struct BufferItem
{ {
uint32_t seq32 = 0; // RTP seq in 32 bytes plus 16 bits cycles. uint32_t seq32 = 0; // RTP seq in 32 bytes plus 16 bits cycles.
uint64_t resent_at_time = 0; uint64_t resentAtTime = 0;
RTC::RtpPacket* packet = nullptr; RTC::RtpPacket* packet = nullptr;
}; };
......
...@@ -29,11 +29,8 @@ namespace RTC ...@@ -29,11 +29,8 @@ namespace RTC
private: private:
static void onSrtpEvent(srtp_event_data_t* data); static void onSrtpEvent(srtp_event_data_t* data);
private:
static uint8_t encryptBuffer[];
public: public:
SrtpSession(Type type, Profile profile, uint8_t* key, size_t key_len); SrtpSession(Type type, Profile profile, uint8_t* key, size_t keyLen);
private: private:
~SrtpSession(); ~SrtpSession();
......
...@@ -85,7 +85,7 @@ namespace RTC ...@@ -85,7 +85,7 @@ namespace RTC
uint16_t GetErrorCode() const; uint16_t GetErrorCode() const;
bool HasMessageIntegrity() const; bool HasMessageIntegrity() const;
bool HasFingerprint() const; bool HasFingerprint() const;
Authentication CheckAuthentication(const std::string &local_username, const std::string &local_password); Authentication CheckAuthentication(const std::string &localUsername, const std::string &localPassword);
StunMessage* CreateSuccessResponse(); StunMessage* CreateSuccessResponse();
StunMessage* CreateErrorResponse(uint16_t errorCode); StunMessage* CreateErrorResponse(uint16_t errorCode);
void Authenticate(const std::string &password); void Authenticate(const std::string &password);
......
...@@ -106,7 +106,9 @@ void DepOpenSSL::LockingFunction(int mode, int n, const char *file, int line) ...@@ -106,7 +106,9 @@ void DepOpenSSL::LockingFunction(int mode, int n, const char *file, int line)
* - line: line in the source file calling this function. * - line: line in the source file calling this function.
*/ */
// MS_DEBUG_DEV("[mode: %s+%s, mutex id: %d, file: %s, line: %d]", mode & CRYPTO_LOCK ? "LOCK" : "UNLOCK", mode & CRYPTO_READ ? "READ" : "WRITE", n, file, line); // MS_DEBUG_DEV("[mode: %s+%s, mutex id: %d, file: %s, line: %d]",
// mode & CRYPTO_LOCK ? "LOCK" : "UNLOCK", mode & CRYPTO_READ ? "READ" : "WRITE",
// n, file, line);
if (mode & CRYPTO_LOCK) if (mode & CRYPTO_LOCK)
uv_mutex_lock(&DepOpenSSL::mutexes[n]); uv_mutex_lock(&DepOpenSSL::mutexes[n]);
......
...@@ -9,7 +9,7 @@ ...@@ -9,7 +9,7 @@
#include <string> #include <string>
#include <utility> // std::pair() #include <utility> // std::pair()
#include <cerrno> #include <cerrno>
#include <iostream> // std::cout, std::cerr #include <iostream> // std::cout, std::cerr
#include <json/json.h> #include <json/json.h>
/* Instance methods. */ /* Instance methods. */
...@@ -52,6 +52,7 @@ void Loop::Close() ...@@ -52,6 +52,7 @@ void Loop::Close()
return; return;
} }
this->closed = true; this->closed = true;
// Close the SignalsHandler. // Close the SignalsHandler.
...@@ -84,16 +85,16 @@ RTC::Room* Loop::GetRoomFromRequest(Channel::Request* request, uint32_t* roomId) ...@@ -84,16 +85,16 @@ RTC::Room* Loop::GetRoomFromRequest(Channel::Request* request, uint32_t* roomId)
static const Json::StaticString k_roomId("roomId"); static const Json::StaticString k_roomId("roomId");
auto json_roomId = request->internal[k_roomId]; auto jsonRoomId = request->internal[k_roomId];
if (!json_roomId.isUInt()) if (!jsonRoomId.isUInt())
MS_THROW_ERROR("Request has not numeric internal.roomId"); MS_THROW_ERROR("Request has not numeric internal.roomId");
// If given, fill roomId. // If given, fill roomId.
if (roomId) if (roomId)
*roomId = json_roomId.asUInt(); *roomId = jsonRoomId.asUInt();
auto it = this->rooms.find(json_roomId.asUInt()); auto it = this->rooms.find(jsonRoomId.asUInt());
if (it != this->rooms.end()) if (it != this->rooms.end())
{ {
RTC::Room* room = it->second; RTC::Room* room = it->second;
...@@ -123,7 +124,8 @@ void Loop::onSignal(SignalsHandler* signalsHandler, int signum) ...@@ -123,7 +124,8 @@ void Loop::onSignal(SignalsHandler* signalsHandler, int signum)
break; break;
default: default:
MS_WARN_DEV("received a signal (with signum %d) for which there is no handling code", signum); MS_WARN_DEV("received a signal (with signum %d) for which there is no handling code",
signum);
} }
} }
...@@ -151,6 +153,7 @@ void Loop::onChannelRequest(Channel::UnixStreamSocket* channel, Channel::Request ...@@ -151,6 +153,7 @@ void Loop::onChannelRequest(Channel::UnixStreamSocket* channel, Channel::Request
json_rooms.append(room->toJson()); json_rooms.append(room->toJson());
} }
json[k_rooms] = json_rooms; json[k_rooms] = json_rooms;
request->Accept(json); request->Accept(json);
...@@ -179,12 +182,14 @@ void Loop::onChannelRequest(Channel::UnixStreamSocket* channel, Channel::Request ...@@ -179,12 +182,14 @@ void Loop::onChannelRequest(Channel::UnixStreamSocket* channel, Channel::Request
catch (const MediaSoupError &error) catch (const MediaSoupError &error)
{ {
request->Reject(error.what()); request->Reject(error.what());
return; return;
} }
if (room) if (room)
{ {
request->Reject("Room already exists"); request->Reject("Room already exists");
return; return;
} }
...@@ -195,6 +200,7 @@ void Loop::onChannelRequest(Channel::UnixStreamSocket* channel, Channel::Request ...@@ -195,6 +200,7 @@ void Loop::onChannelRequest(Channel::UnixStreamSocket* channel, Channel::Request
catch (const MediaSoupError &error) catch (const MediaSoupError &error)
{ {
request->Reject(error.what()); request->Reject(error.what());
return; return;
} }
...@@ -242,12 +248,14 @@ void Loop::onChannelRequest(Channel::UnixStreamSocket* channel, Channel::Request ...@@ -242,12 +248,14 @@ void Loop::onChannelRequest(Channel::UnixStreamSocket* channel, Channel::Request
catch (const MediaSoupError &error) catch (const MediaSoupError &error)
{ {
request->Reject(error.what()); request->Reject(error.what());
return; return;
} }
if (!room) if (!room)
{ {
request->Reject("Room does not exist"); request->Reject("Room does not exist");
return; return;
} }
......
...@@ -6,7 +6,6 @@ ...@@ -6,7 +6,6 @@
#include "Utils.hpp" #include "Utils.hpp"
#include "MediaSoupError.hpp" #include "MediaSoupError.hpp"
#include "Logger.hpp" #include "Logger.hpp"
#include <algorithm> // std::remove
#include <cstdio> // std::sprintf(), std::fopen() #include <cstdio> // std::sprintf(), std::fopen()
#include <cstring> // std::memcpy(), std::strcmp() #include <cstring> // std::memcpy(), std::strcmp()
#include <ctime> // struct timeval #include <ctime> // struct timeval
...@@ -16,33 +15,27 @@ ...@@ -16,33 +15,27 @@
#include <openssl/rsa.h> #include <openssl/rsa.h>
#include <openssl/asn1.h> #include <openssl/asn1.h>
#define MS_SSL_READ_BUFFER_SIZE 65536 #define LOG_OPENSSL_ERROR(desc) \
// NOTE: Those values are hardcoded as we just use AES_CM_128_HMAC_SHA1_80 and do \
// AES_CM_128_HMAC_SHA1_32 which share same length values for key and salt. { \
#define MS_SRTP_MASTER_KEY_LENGTH 16 if (ERR_peek_error() == 0) \
#define MS_SRTP_MASTER_SALT_LENGTH 14 MS_ERROR("OpenSSL error [desc:'%s']", desc); \
#define MS_SRTP_MASTER_LENGTH (MS_SRTP_MASTER_KEY_LENGTH + MS_SRTP_MASTER_SALT_LENGTH) else \
#define LOG_OPENSSL_ERROR(desc) \ { \
do \ unsigned long err; \
{ \ while ((err = ERR_get_error()) != 0) \
if (ERR_peek_error() == 0) \ { \
MS_ERROR("OpenSSL error [desc:'%s']", desc); \ MS_ERROR("OpenSSL error [desc:'%s', error:'%s']", desc, ERR_error_string(err, nullptr)); \
else \ } \
{ \ ERR_clear_error(); \
unsigned long err; \ } \
while ((err = ERR_get_error()) != 0) \ } \
{ \
MS_ERROR("OpenSSL error [desc:'%s', error:'%s']", desc, ERR_error_string(err, nullptr)); \
} \
ERR_clear_error(); \
} \
} \
while (0) while (0)
/* Static methods for OpenSSL callbacks. */ /* Static methods for OpenSSL callbacks. */
static inline static inline
int on_ssl_certificate_verify(int preverify_ok, X509_STORE_CTX* ctx) int on_ssl_certificate_verify(int preverifyOk, X509_STORE_CTX* ctx)
{ {
MS_TRACE(); MS_TRACE();
...@@ -58,12 +51,21 @@ void on_ssl_info(const SSL* ssl, int where, int ret) ...@@ -58,12 +51,21 @@ void on_ssl_info(const SSL* ssl, int where, int ret)
namespace RTC namespace RTC
{ {
/* Static. */
static constexpr int SslReadBufferSize = 65536;
// NOTE: Those values are hardcoded as we just use AES_CM_128_HMAC_SHA1_80 and
// AES_CM_128_HMAC_SHA1_32 which share same length values for key and salt.
static constexpr size_t SrtpMasterKeyLength = 16;
static constexpr size_t SrtpMasterSaltLength = 14;
static constexpr size_t SrtpMasterLength = SrtpMasterKeyLength + SrtpMasterSaltLength;
/* Class variables. */ /* Class variables. */
X509* DtlsTransport::certificate = nullptr; X509* DtlsTransport::certificate = nullptr;
EVP_PKEY* DtlsTransport::privateKey = nullptr; EVP_PKEY* DtlsTransport::privateKey = nullptr;
SSL_CTX* DtlsTransport::sslCtx = nullptr; SSL_CTX* DtlsTransport::sslCtx = nullptr;
uint8_t DtlsTransport::sslReadBuffer[MS_SSL_READ_BUFFER_SIZE]; uint8_t DtlsTransport::sslReadBuffer[SslReadBufferSize];
std::map<std::string, DtlsTransport::FingerprintAlgorithm> DtlsTransport::string2FingerprintAlgorithm = std::map<std::string, DtlsTransport::FingerprintAlgorithm> DtlsTransport::string2FingerprintAlgorithm =
{ {
{ "sha-1", DtlsTransport::FingerprintAlgorithm::SHA1 }, { "sha-1", DtlsTransport::FingerprintAlgorithm::SHA1 },
...@@ -92,10 +94,16 @@ namespace RTC ...@@ -92,10 +94,16 @@ namespace RTC
MS_TRACE(); MS_TRACE();
// Generate a X509 certificate and private key (unless PEM files are provided). // Generate a X509 certificate and private key (unless PEM files are provided).
if (Settings::configuration.dtlsCertificateFile.empty() || Settings::configuration.dtlsPrivateKeyFile.empty()) if (
Settings::configuration.dtlsCertificateFile.empty() ||
Settings::configuration.dtlsPrivateKeyFile.empty())
{
GenerateCertificateAndPrivateKey(); GenerateCertificateAndPrivateKey();
}
else else
{
ReadCertificateAndPrivateKeyFromFiles(); ReadCertificateAndPrivateKeyFromFiles();
}
// Create a global SSL_CTX. // Create a global SSL_CTX.
CreateSSL_CTX(); CreateSSL_CTX();
...@@ -122,9 +130,9 @@ namespace RTC ...@@ -122,9 +130,9 @@ namespace RTC
int ret = 0; int ret = 0;
BIGNUM* bne = nullptr; BIGNUM* bne = nullptr;
RSA* rsa_key = nullptr; RSA* rsaKey = nullptr;
int num_bits = 1024; int numBits = 1024;
X509_NAME* cert_name = nullptr; X509_NAME* certName = nullptr;
// Create a big number object. // Create a big number object.
bne = BN_new(); bne = BN_new();
...@@ -142,15 +150,15 @@ namespace RTC ...@@ -142,15 +150,15 @@ namespace RTC
} }
// Generate a RSA key. // Generate a RSA key.
rsa_key = RSA_new(); rsaKey = RSA_new();
if (!rsa_key) if (!rsaKey)
{ {
LOG_OPENSSL_ERROR("RSA_new() failed"); LOG_OPENSSL_ERROR("RSA_new() failed");
goto error; goto error;
} }
// This takes some time. // This takes some time.
ret = RSA_generate_key_ex(rsa_key, num_bits, bne, nullptr); ret = RSA_generate_key_ex(rsaKey, numBits, bne, nullptr);
if (ret == 0) if (ret == 0)
{ {
LOG_OPENSSL_ERROR("RSA_generate_key_ex() failed"); LOG_OPENSSL_ERROR("RSA_generate_key_ex() failed");
...@@ -165,14 +173,14 @@ namespace RTC ...@@ -165,14 +173,14 @@ namespace RTC
goto error; goto error;
} }
ret = EVP_PKEY_assign_RSA(DtlsTransport::privateKey, rsa_key); ret = EVP_PKEY_assign_RSA(DtlsTransport::privateKey, rsaKey);
if (ret == 0) if (ret == 0)
{ {
LOG_OPENSSL_ERROR("EVP_PKEY_assign_RSA() failed"); LOG_OPENSSL_ERROR("EVP_PKEY_assign_RSA() failed");
goto error; goto error;
} }
// The RSA key now belongs to the private key, so don't clean it up separately. // The RSA key now belongs to the private key, so don't clean it up separately.
rsa_key = nullptr; rsaKey = nullptr;
// Create the X509 certificate. // Create the X509 certificate.
DtlsTransport::certificate = X509_new(); DtlsTransport::certificate = X509_new();
...@@ -186,10 +194,11 @@ namespace RTC ...@@ -186,10 +194,11 @@ namespace RTC
X509_set_version(DtlsTransport::certificate, 2); X509_set_version(DtlsTransport::certificate, 2);
// Set serial number (avoid default 0). // Set serial number (avoid default 0).
ASN1_INTEGER_set(X509_get_serialNumber(DtlsTransport::certificate), (long)Utils::Crypto::GetRandomUInt(1000000, 9999999)); ASN1_INTEGER_set(X509_get_serialNumber(DtlsTransport::certificate),
(long)Utils::Crypto::GetRandomUInt(1000000, 9999999));
// Set valid period. // Set valid period.
X509_gmtime_adj(X509_get_notBefore(DtlsTransport::certificate), -1*60*60*24*365*10); // - 10 years. X509_gmtime_adj(X509_get_notBefore(DtlsTransport::certificate), -1*60*60*24*365*10); // -10 years.
X509_gmtime_adj(X509_get_notAfter(DtlsTransport::certificate), 60*60*24*365*10); // 10 years. X509_gmtime_adj(X509_get_notAfter(DtlsTransport::certificate), 60*60*24*365*10); // 10 years.
// Set the public key for the certificate using the key. // Set the public key for the certificate using the key.
...@@ -201,17 +210,17 @@ namespace RTC ...@@ -201,17 +210,17 @@ namespace RTC
} }
// Set certificate fields. // Set certificate fields.
cert_name = X509_get_subject_name(DtlsTransport::certificate); certName = X509_get_subject_name(DtlsTransport::certificate);
if (!cert_name) if (!certName)
{ {
LOG_OPENSSL_ERROR("X509_get_subject_name() failed"); LOG_OPENSSL_ERROR("X509_get_subject_name() failed");
goto error; goto error;
} }
X509_NAME_add_entry_by_txt(cert_name, "O", MBSTRING_ASC, (uint8_t*)MS_APP_NAME, -1, -1, 0); X509_NAME_add_entry_by_txt(certName, "O", MBSTRING_ASC, (uint8_t*)MS_APP_NAME, -1, -1, 0);
X509_NAME_add_entry_by_txt(cert_name, "CN", MBSTRING_ASC, (uint8_t*)MS_APP_NAME, -1, -1, 0); X509_NAME_add_entry_by_txt(certName, "CN", MBSTRING_ASC, (uint8_t*)MS_APP_NAME, -1, -1, 0);
// It is self-signed so set the issuer name to be the same as the subject. // It is self-signed so set the issuer name to be the same as the subject.
ret = X509_set_issuer_name(DtlsTransport::certificate, cert_name); ret = X509_set_issuer_name(DtlsTransport::certificate, certName);
if (ret == 0) if (ret == 0)
{ {
LOG_OPENSSL_ERROR("X509_set_issuer_name() failed"); LOG_OPENSSL_ERROR("X509_set_issuer_name() failed");
...@@ -228,13 +237,14 @@ namespace RTC ...@@ -228,13 +237,14 @@ namespace RTC
// Free stuff and return. // Free stuff and return.
BN_free(bne); BN_free(bne);
return; return;
error: error:
if (bne) if (bne)
BN_free(bne); BN_free(bne);
if (rsa_key && !DtlsTransport::privateKey) if (rsaKey && !DtlsTransport::privateKey)
RSA_free(rsa_key); RSA_free(rsaKey);
if (DtlsTransport::privateKey) if (DtlsTransport::privateKey)
EVP_PKEY_free(DtlsTransport::privateKey); // NOTE: This also frees the RSA key. EVP_PKEY_free(DtlsTransport::privateKey); // NOTE: This also frees the RSA key.
if (DtlsTransport::certificate) if (DtlsTransport::certificate)
...@@ -255,12 +265,14 @@ namespace RTC ...@@ -255,12 +265,14 @@ namespace RTC
MS_ERROR("error reading DTLS certificate file: %s", std::strerror(errno)); MS_ERROR("error reading DTLS certificate file: %s", std::strerror(errno));
goto error; goto error;
} }
DtlsTransport::certificate = PEM_read_X509(file, nullptr, nullptr, nullptr); DtlsTransport::certificate = PEM_read_X509(file, nullptr, nullptr, nullptr);
if (!DtlsTransport::certificate) if (!DtlsTransport::certificate)
{ {
LOG_OPENSSL_ERROR("PEM_read_X509() failed"); LOG_OPENSSL_ERROR("PEM_read_X509() failed");
goto error; goto error;
} }
fclose(file); fclose(file);
file = fopen(Settings::configuration.dtlsPrivateKeyFile.c_str(), "r"); file = fopen(Settings::configuration.dtlsPrivateKeyFile.c_str(), "r");
...@@ -269,12 +281,14 @@ namespace RTC ...@@ -269,12 +281,14 @@ namespace RTC
MS_ERROR("error reading DTLS private key file: %s", std::strerror(errno)); MS_ERROR("error reading DTLS private key file: %s", std::strerror(errno));
goto error; goto error;
} }
DtlsTransport::privateKey = PEM_read_PrivateKey(file, nullptr, nullptr, nullptr); DtlsTransport::privateKey = PEM_read_PrivateKey(file, nullptr, nullptr, nullptr);
if (!DtlsTransport::privateKey) if (!DtlsTransport::privateKey)
{ {
LOG_OPENSSL_ERROR("PEM_read_PrivateKey() failed"); LOG_OPENSSL_ERROR("PEM_read_PrivateKey() failed");
goto error; goto error;
} }
fclose(file); fclose(file);
return; return;
...@@ -287,21 +301,21 @@ namespace RTC ...@@ -287,21 +301,21 @@ namespace RTC
{ {
MS_TRACE(); MS_TRACE();
std::string ssl_srtp_profiles; std::string dtlsSrtpProfiles;
EC_KEY* ecdh = nullptr; EC_KEY* ecdh = nullptr;
int ret; int ret;
/* Set the global DTLS context. */ /* Set the global DTLS context. */
// - Both DTLS 1.0 and 1.2 (requires OpenSSL >= 1.1.0). // - Both DTLS 1.0 and 1.2 (requires OpenSSL >= 1.1.0).
#if (OPENSSL_VERSION_NUMBER >= 0x10100000L) #if (OPENSSL_VERSION_NUMBER >= 0x10100000L)
DtlsTransport::sslCtx = SSL_CTX_new(DTLS_method()); DtlsTransport::sslCtx = SSL_CTX_new(DTLS_method());
// - Just DTLS 1.0 (requires OpenSSL >= 1.0.1). // - Just DTLS 1.0 (requires OpenSSL >= 1.0.1).
#elif (OPENSSL_VERSION_NUMBER >= 0x10001000L) #elif (OPENSSL_VERSION_NUMBER >= 0x10001000L)
DtlsTransport::sslCtx = SSL_CTX_new(DTLSv1_method()); DtlsTransport::sslCtx = SSL_CTX_new(DTLSv1_method());
#else #else
#error "too old OpenSSL version" #error "too old OpenSSL version"
#endif #endif
if (!DtlsTransport::sslCtx) if (!DtlsTransport::sslCtx)
{ {
...@@ -350,7 +364,8 @@ namespace RTC ...@@ -350,7 +364,8 @@ namespace RTC
SSL_CTX_set_info_callback(DtlsTransport::sslCtx, on_ssl_info); SSL_CTX_set_info_callback(DtlsTransport::sslCtx, on_ssl_info);
// Set ciphers. // Set ciphers.
ret = SSL_CTX_set_cipher_list(DtlsTransport::sslCtx, "ALL:!ADH:!LOW:!EXP:!MD5:!aNULL:!eNULL:@STRENGTH"); ret = SSL_CTX_set_cipher_list(DtlsTransport::sslCtx,
"ALL:!ADH:!LOW:!EXP:!MD5:!aNULL:!eNULL:@STRENGTH");
if (ret == 0) if (ret == 0)
{ {
LOG_OPENSSL_ERROR("SSL_CTX_set_cipher_list() failed"); LOG_OPENSSL_ERROR("SSL_CTX_set_cipher_list() failed");
...@@ -361,39 +376,47 @@ namespace RTC ...@@ -361,39 +376,47 @@ namespace RTC
// DOC: http://en.wikibooks.org/wiki/OpenSSL/Diffie-Hellman_parameters // DOC: http://en.wikibooks.org/wiki/OpenSSL/Diffie-Hellman_parameters
// NOTE: https://code.google.com/p/chromium/issues/detail?id=406458 // NOTE: https://code.google.com/p/chromium/issues/detail?id=406458
// For OpenSSL >= 1.0.2: // For OpenSSL >= 1.0.2:
#if (OPENSSL_VERSION_NUMBER >= 0x10002000L) #if (OPENSSL_VERSION_NUMBER >= 0x10002000L)
SSL_CTX_set_ecdh_auto(DtlsTransport::sslCtx, 1); SSL_CTX_set_ecdh_auto(DtlsTransport::sslCtx, 1);
#else #else
ecdh = EC_KEY_new_by_curve_name(NID_X9_62_prime256v1); ecdh = EC_KEY_new_by_curve_name(NID_X9_62_prime256v1);
if (!ecdh)
{ if (!ecdh)
LOG_OPENSSL_ERROR("EC_KEY_new_by_curve_name() failed"); {
goto error; LOG_OPENSSL_ERROR("EC_KEY_new_by_curve_name() failed");
} goto error;
if (SSL_CTX_set_tmp_ecdh(DtlsTransport::sslCtx, ecdh) != 1) }
{
LOG_OPENSSL_ERROR("SSL_CTX_set_tmp_ecdh() failed"); if (SSL_CTX_set_tmp_ecdh(DtlsTransport::sslCtx, ecdh) != 1)
goto error; {
} LOG_OPENSSL_ERROR("SSL_CTX_set_tmp_ecdh() failed");
EC_KEY_free(ecdh); goto error;
ecdh = nullptr; }
#endif
EC_KEY_free(ecdh);
ecdh = nullptr;
#endif
// Set the "use_srtp" DTLS extension. // Set the "use_srtp" DTLS extension.
for (auto it = DtlsTransport::srtpProfiles.begin(); it != DtlsTransport::srtpProfiles.end(); ++it)
{ {
if (it != DtlsTransport::srtpProfiles.begin()) auto it = DtlsTransport::srtpProfiles.begin();
ssl_srtp_profiles += ":"; for (; it != DtlsTransport::srtpProfiles.end(); ++it)
{
if (it != DtlsTransport::srtpProfiles.begin())
dtlsSrtpProfiles += ":";
SrtpProfileMapEntry* profile_entry = &(*it); SrtpProfileMapEntry* profile_entry = &(*it);
ssl_srtp_profiles += profile_entry->name; dtlsSrtpProfiles += profile_entry->name;
}
} }
MS_DEBUG_TAG(dtls, "setting SRTP profiles for DTLS: %s", ssl_srtp_profiles.c_str());
MS_DEBUG_TAG(dtls, "setting SRTP profiles for DTLS: %s", dtlsSrtpProfiles.c_str());
// NOTE: This function returns 0 on success. // NOTE: This function returns 0 on success.
ret = SSL_CTX_set_tlsext_use_srtp(DtlsTransport::sslCtx, ssl_srtp_profiles.c_str()); ret = SSL_CTX_set_tlsext_use_srtp(DtlsTransport::sslCtx, dtlsSrtpProfiles.c_str());
if (ret != 0) if (ret != 0)
{ {
MS_ERROR("SSL_CTX_set_tlsext_use_srtp() failed when entering '%s'", ssl_srtp_profiles.c_str()); MS_ERROR("SSL_CTX_set_tlsext_use_srtp() failed when entering '%s'", dtlsSrtpProfiles.c_str());
LOG_OPENSSL_ERROR("SSL_CTX_set_tlsext_use_srtp() failed"); LOG_OPENSSL_ERROR("SSL_CTX_set_tlsext_use_srtp() failed");
goto error; goto error;
} }
...@@ -417,38 +440,39 @@ namespace RTC ...@@ -417,38 +440,39 @@ namespace RTC
{ {
MS_TRACE(); MS_TRACE();
for (auto it = DtlsTransport::string2FingerprintAlgorithm.begin(); it != DtlsTransport::string2FingerprintAlgorithm.end(); ++it) auto it = DtlsTransport::string2FingerprintAlgorithm.begin();
for (; it != DtlsTransport::string2FingerprintAlgorithm.end(); ++it)
{ {
std::string algorithm_str = it->first; std::string algorithmString = it->first;
FingerprintAlgorithm algorithm = it->second; FingerprintAlgorithm algorithm = it->second;
uint8_t binary_fingerprint[EVP_MAX_MD_SIZE]; uint8_t binaryFingerprint[EVP_MAX_MD_SIZE];
unsigned int size = 0; unsigned int size = 0;
char hex_fingerprint[(EVP_MAX_MD_SIZE * 2) + 1]; char hexFingerprint[(EVP_MAX_MD_SIZE * 2) + 1];
const EVP_MD* hash_function; const EVP_MD* hashFunction;
int ret; int ret;
switch (algorithm) switch (algorithm)
{ {
case FingerprintAlgorithm::SHA1: case FingerprintAlgorithm::SHA1:
hash_function = EVP_sha1(); hashFunction = EVP_sha1();
break; break;
case FingerprintAlgorithm::SHA224: case FingerprintAlgorithm::SHA224:
hash_function = EVP_sha224(); hashFunction = EVP_sha224();
break; break;
case FingerprintAlgorithm::SHA256: case FingerprintAlgorithm::SHA256:
hash_function = EVP_sha256(); hashFunction = EVP_sha256();
break; break;
case FingerprintAlgorithm::SHA384: case FingerprintAlgorithm::SHA384:
hash_function = EVP_sha384(); hashFunction = EVP_sha384();
break; break;
case FingerprintAlgorithm::SHA512: case FingerprintAlgorithm::SHA512:
hash_function = EVP_sha512(); hashFunction = EVP_sha512();
break; break;
default: default:
MS_THROW_ERROR("unknown algorithm"); MS_THROW_ERROR("unknown algorithm");
} }
ret = X509_digest(DtlsTransport::certificate, hash_function, binary_fingerprint, &size); ret = X509_digest(DtlsTransport::certificate, hashFunction, binaryFingerprint, &size);
if (ret == 0) if (ret == 0)
{ {
MS_ERROR("X509_digest() failed"); MS_ERROR("X509_digest() failed");
...@@ -458,14 +482,14 @@ namespace RTC ...@@ -458,14 +482,14 @@ namespace RTC
// Convert to hexadecimal format in lowecase without colons. // Convert to hexadecimal format in lowecase without colons.
for (unsigned int i = 0; i < size; ++i) for (unsigned int i = 0; i < size; ++i)
{ {
std::sprintf(hex_fingerprint + (i * 2), "%.2x", binary_fingerprint[i]); std::sprintf(hexFingerprint + (i * 2), "%.2x", binaryFingerprint[i]);
} }
hex_fingerprint[size * 2] = '\0'; hexFingerprint[size * 2] = '\0';
MS_DEBUG_TAG(dtls, "%-7s fingerprint: %s", algorithm_str.c_str(), hex_fingerprint); MS_DEBUG_TAG(dtls, "%-7s fingerprint: %s", algorithmString.c_str(), hexFingerprint);
// Store in the JSON. // Store in the JSON.
DtlsTransport::localFingerprints[algorithm_str] = hex_fingerprint; DtlsTransport::localFingerprints[algorithmString] = hexFingerprint;
} }
} }
...@@ -575,7 +599,8 @@ namespace RTC ...@@ -575,7 +599,8 @@ namespace RTC
{ {
MS_TRACE(); MS_TRACE();
MS_ASSERT(localRole == Role::CLIENT || localRole == Role::SERVER, "local DTLS role must be 'client' or 'server'"); MS_ASSERT(localRole == Role::CLIENT || localRole == Role::SERVER,
"local DTLS role must be 'client' or 'server'");
Role previousLocalRole = this->localRole; Role previousLocalRole = this->localRole;
...@@ -628,7 +653,8 @@ namespace RTC ...@@ -628,7 +653,8 @@ namespace RTC
{ {
MS_TRACE(); MS_TRACE();
MS_ASSERT(fingerprint.algorithm != FingerprintAlgorithm::NONE, "no fingerprint algorithm provided"); MS_ASSERT(fingerprint.algorithm != FingerprintAlgorithm::NONE,
"no fingerprint algorithm provided");
this->remoteFingerprint = fingerprint; this->remoteFingerprint = fingerprint;
...@@ -659,10 +685,13 @@ namespace RTC ...@@ -659,10 +685,13 @@ namespace RTC
// Write the received DTLS data into the sslBioFromNetwork. // Write the received DTLS data into the sslBioFromNetwork.
written = BIO_write(this->sslBioFromNetwork, (const void*)data, (int)len); written = BIO_write(this->sslBioFromNetwork, (const void*)data, (int)len);
if (written != (int)len) if (written != (int)len)
MS_WARN_TAG(dtls, "OpenSSL BIO_write() wrote less (%zu bytes) than given data (%zu bytes)", (size_t)written, len); {
MS_WARN_TAG(dtls, "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. // Must call SSL_read() to process received DTLS data.
read = SSL_read(this->ssl, (void*)DtlsTransport::sslReadBuffer, MS_SSL_READ_BUFFER_SIZE); read = SSL_read(this->ssl, (void*)DtlsTransport::sslReadBuffer, SslReadBufferSize);
// Send data if it's ready. // Send data if it's ready.
SendPendingOutgoingDtlsData(); SendPendingOutgoingDtlsData();
...@@ -687,7 +716,8 @@ namespace RTC ...@@ -687,7 +716,8 @@ namespace RTC
} }
// Notify the listener. // Notify the listener.
this->listener->onDtlsApplicationData(this, (uint8_t*)DtlsTransport::sslReadBuffer, (size_t)read); this->listener->onDtlsApplicationData(this, (uint8_t*)DtlsTransport::sslReadBuffer,
(size_t)read);
} }
} }
...@@ -721,7 +751,8 @@ namespace RTC ...@@ -721,7 +751,8 @@ namespace RTC
} }
else if (written != (int)len) else if (written != (int)len)
{ {
MS_WARN_TAG(dtls, "OpenSSL SSL_write() wrote less (%d bytes) than given data (%zu bytes)", written, len); MS_WARN_TAG(dtls, "OpenSSL SSL_write() wrote less (%d bytes) than given data (%zu bytes)",
written, len);
} }
// Send data. // Send data.
...@@ -767,7 +798,7 @@ namespace RTC ...@@ -767,7 +798,7 @@ namespace RTC
MS_TRACE(); MS_TRACE();
int err; int err;
bool was_handshake_done = this->handshakeDone; bool wasHandshakeDone = this->handshakeDone;
err = SSL_get_error(this->ssl, return_code); err = SSL_get_error(this->ssl, return_code);
switch (err) switch (err)
...@@ -810,11 +841,14 @@ namespace RTC ...@@ -810,11 +841,14 @@ namespace RTC
this->timer->Stop(); this->timer->Stop();
// Process the handshake just once (ignore if DTLS renegotiation). // Process the handshake just once (ignore if DTLS renegotiation).
if (!was_handshake_done) if (!wasHandshakeDone)
ProcessHandshake(); ProcessHandshake();
} }
// Check if the peer sent close alert or a fatal error happened. // Check if the peer sent close alert or a fatal error happened.
else if ((SSL_get_shutdown(this->ssl) & SSL_RECEIVED_SHUTDOWN) || err == SSL_ERROR_SSL || err == SSL_ERROR_SYSCALL) else if (
(SSL_get_shutdown(this->ssl) & SSL_RECEIVED_SHUTDOWN) ||
err == SSL_ERROR_SSL
|| err == SSL_ERROR_SYSCALL)
{ {
if (this->state == DtlsState::CONNECTED) if (this->state == DtlsState::CONNECTED)
{ {
...@@ -874,32 +908,32 @@ namespace RTC ...@@ -874,32 +908,32 @@ namespace RTC
MS_TRACE(); MS_TRACE();
long int ret; long int ret;
struct timeval dtls_timeout; struct timeval dtlsTimeout;
uint64_t timeout_ms; uint64_t timeoutMs;
// NOTE: If ret == 0 then ignore the value in dtls_timeout. // NOTE: If ret == 0 then ignore the value in dtlsTimeout.
// NOTE: No DTLSv_1_2_get_timeout() or DTLS_get_timeout() in OpenSSL 1.1.0-dev. // NOTE: No DTLSv_1_2_get_timeout() or DTLS_get_timeout() in OpenSSL 1.1.0-dev.
ret = DTLSv1_get_timeout(this->ssl, (void*)&dtls_timeout); ret = DTLSv1_get_timeout(this->ssl, (void*)&dtlsTimeout);
if (ret == 0) if (ret == 0)
return true; return true;
timeout_ms = (dtls_timeout.tv_sec * (uint64_t)1000) + (dtls_timeout.tv_usec / 1000); timeoutMs = (dtlsTimeout.tv_sec * (uint64_t)1000) + (dtlsTimeout.tv_usec / 1000);
if (timeout_ms == 0) if (timeoutMs == 0)
{ {
return true; return true;
} }
else if (timeout_ms < 30000) else if (timeoutMs < 30000)
{ {
MS_DEBUG_DEV("DTLS timer set in %" PRIu64 "ms", timeout_ms); MS_DEBUG_DEV("DTLS timer set in %" PRIu64 "ms", timeoutMs);
this->timer->Start(timeout_ms); this->timer->Start(timeoutMs);
return true; return true;
} }
// NOTE: Don't start the timer again if the timeout is greater than 30 seconds. // NOTE: Don't start the timer again if the timeout is greater than 30 seconds.
else else
{ {
MS_WARN_TAG(dtls, "DTLS timeout too high (%" PRIu64 "ms), resetting DLTS", timeout_ms); MS_WARN_TAG(dtls, "DTLS timeout too high (%" PRIu64 "ms), resetting DLTS", timeoutMs);
Reset(); Reset();
...@@ -970,10 +1004,10 @@ namespace RTC ...@@ -970,10 +1004,10 @@ namespace RTC
MS_ASSERT(this->remoteFingerprint.algorithm != FingerprintAlgorithm::NONE, "remote fingerprint not set"); MS_ASSERT(this->remoteFingerprint.algorithm != FingerprintAlgorithm::NONE, "remote fingerprint not set");
X509* certificate; X509* certificate;
uint8_t binary_fingerprint[EVP_MAX_MD_SIZE]; uint8_t binaryFingerprint[EVP_MAX_MD_SIZE];
unsigned int size = 0; unsigned int size = 0;
char hex_fingerprint[(EVP_MAX_MD_SIZE * 2) + 1]; char hexFingerprint[(EVP_MAX_MD_SIZE * 2) + 1];
const EVP_MD* hash_function; const EVP_MD* hashFunction;
int ret; int ret;
certificate = SSL_get_peer_certificate(this->ssl); certificate = SSL_get_peer_certificate(this->ssl);
...@@ -987,19 +1021,19 @@ namespace RTC ...@@ -987,19 +1021,19 @@ namespace RTC
switch (this->remoteFingerprint.algorithm) switch (this->remoteFingerprint.algorithm)
{ {
case FingerprintAlgorithm::SHA1: case FingerprintAlgorithm::SHA1:
hash_function = EVP_sha1(); hashFunction = EVP_sha1();
break; break;
case FingerprintAlgorithm::SHA224: case FingerprintAlgorithm::SHA224:
hash_function = EVP_sha224(); hashFunction = EVP_sha224();
break; break;
case FingerprintAlgorithm::SHA256: case FingerprintAlgorithm::SHA256:
hash_function = EVP_sha256(); hashFunction = EVP_sha256();
break; break;
case FingerprintAlgorithm::SHA384: case FingerprintAlgorithm::SHA384:
hash_function = EVP_sha384(); hashFunction = EVP_sha384();
break; break;
case FingerprintAlgorithm::SHA512: case FingerprintAlgorithm::SHA512:
hash_function = EVP_sha512(); hashFunction = EVP_sha512();
break; break;
default: default:
MS_ABORT("unknown algorithm"); MS_ABORT("unknown algorithm");
...@@ -1007,7 +1041,7 @@ namespace RTC ...@@ -1007,7 +1041,7 @@ namespace RTC
// Compare the remote fingerprint with the value given via signaling. // Compare the remote fingerprint with the value given via signaling.
ret = X509_digest(certificate, hash_function, binary_fingerprint, &size); ret = X509_digest(certificate, hashFunction, binaryFingerprint, &size);
if (ret == 0) if (ret == 0)
{ {
MS_ERROR("X509_digest() failed"); MS_ERROR("X509_digest() failed");
...@@ -1020,13 +1054,15 @@ namespace RTC ...@@ -1020,13 +1054,15 @@ namespace RTC
// Convert to hexadecimal format in lowecase without colons. // Convert to hexadecimal format in lowecase without colons.
for (unsigned int i = 0; i < size; ++i) for (unsigned int i = 0; i < size; ++i)
{ {
std::sprintf(hex_fingerprint + (i * 2), "%.2x", binary_fingerprint[i]); std::sprintf(hexFingerprint + (i * 2), "%.2x", binaryFingerprint[i]);
} }
hex_fingerprint[size * 2] = '\0'; hexFingerprint[size * 2] = '\0';
if (this->remoteFingerprint.value.compare(hex_fingerprint) != 0) if (this->remoteFingerprint.value.compare(hexFingerprint) != 0)
{ {
MS_WARN_TAG(dtls, "fingerprint in the remote certificate (%s) does not match the announced one (%s)", hex_fingerprint, this->remoteFingerprint.value.c_str()); MS_WARN_TAG(dtls,
"fingerprint in the remote certificate (%s) does not match the announced one (%s)",
hexFingerprint, this->remoteFingerprint.value.c_str());
X509_free(certificate); X509_free(certificate);
...@@ -1042,7 +1078,7 @@ namespace RTC ...@@ -1042,7 +1078,7 @@ namespace RTC
// Ensure the underlying BUF_MEM structure is also freed. // Ensure the underlying BUF_MEM structure is also freed.
// NOTE: Avoid stupid "warning: value computed is not used [-Wunused-value]" since // NOTE: Avoid stupid "warning: value computed is not used [-Wunused-value]" since
// BIO_set_close() always returns 1. // BIO_set_close() always returns 1.
(void) BIO_set_close(bio, BIO_CLOSE); (void)BIO_set_close(bio, BIO_CLOSE);
ret = PEM_write_bio_X509(bio, certificate); ret = PEM_write_bio_X509(bio, certificate);
if (ret != 1) if (ret != 1)
...@@ -1081,31 +1117,33 @@ namespace RTC ...@@ -1081,31 +1117,33 @@ namespace RTC
{ {
MS_TRACE(); MS_TRACE();
uint8_t srtp_material[MS_SRTP_MASTER_LENGTH * 2]; uint8_t srtpMaterial[SrtpMasterLength * 2];
uint8_t* srtp_local_key; uint8_t* srtpLocalKey;
uint8_t* srtp_local_salt; uint8_t* srtpLocalSalt;
uint8_t* srtp_remote_key; uint8_t* srtpRemoteKey;
uint8_t* srtp_remote_salt; uint8_t* srtpRemoteSalt;
uint8_t srtp_local_master_key[MS_SRTP_MASTER_LENGTH]; uint8_t srtpLocalMasterKey[SrtpMasterLength];
uint8_t srtp_remote_master_key[MS_SRTP_MASTER_LENGTH]; uint8_t srtpRemoteMasterKey[SrtpMasterLength];
int ret; int ret;
ret = SSL_export_keying_material(this->ssl, srtp_material, MS_SRTP_MASTER_LENGTH * 2, "EXTRACTOR-dtls_srtp", 19, nullptr, 0, 0); ret = SSL_export_keying_material(this->ssl, srtpMaterial, SrtpMasterLength * 2,
"EXTRACTOR-dtls_srtp", 19, nullptr, 0, 0);
MS_ASSERT(ret != 0, "SSL_export_keying_material() failed"); MS_ASSERT(ret != 0, "SSL_export_keying_material() failed");
switch (this->localRole) switch (this->localRole)
{ {
case Role::SERVER: case Role::SERVER:
srtp_remote_key = srtp_material; srtpRemoteKey = srtpMaterial;
srtp_local_key = srtp_remote_key + MS_SRTP_MASTER_KEY_LENGTH; srtpLocalKey = srtpRemoteKey + SrtpMasterKeyLength;
srtp_remote_salt = srtp_local_key + MS_SRTP_MASTER_KEY_LENGTH; srtpRemoteSalt = srtpLocalKey + SrtpMasterKeyLength;
srtp_local_salt = srtp_remote_salt + MS_SRTP_MASTER_SALT_LENGTH; srtpLocalSalt = srtpRemoteSalt + SrtpMasterSaltLength;
break; break;
case Role::CLIENT: case Role::CLIENT:
srtp_local_key = srtp_material; srtpLocalKey = srtpMaterial;
srtp_remote_key = srtp_local_key + MS_SRTP_MASTER_KEY_LENGTH; srtpRemoteKey = srtpLocalKey + SrtpMasterKeyLength;
srtp_local_salt = srtp_remote_key + MS_SRTP_MASTER_KEY_LENGTH; srtpLocalSalt = srtpRemoteKey + SrtpMasterKeyLength;
srtp_remote_salt = srtp_local_salt + MS_SRTP_MASTER_SALT_LENGTH; srtpRemoteSalt = srtpLocalSalt + SrtpMasterSaltLength;
break; break;
default: default:
MS_ABORT("no DTLS role set"); MS_ABORT("no DTLS role set");
...@@ -1113,15 +1151,16 @@ namespace RTC ...@@ -1113,15 +1151,16 @@ namespace RTC
} }
// Create the SRTP local master key. // Create the SRTP local master key.
std::memcpy(srtp_local_master_key, srtp_local_key, MS_SRTP_MASTER_KEY_LENGTH); std::memcpy(srtpLocalMasterKey, srtpLocalKey, SrtpMasterKeyLength);
std::memcpy(srtp_local_master_key + MS_SRTP_MASTER_KEY_LENGTH, srtp_local_salt, MS_SRTP_MASTER_SALT_LENGTH); std::memcpy(srtpLocalMasterKey + SrtpMasterKeyLength, srtpLocalSalt, SrtpMasterSaltLength);
// Create the SRTP remote master key. // Create the SRTP remote master key.
std::memcpy(srtp_remote_master_key, srtp_remote_key, MS_SRTP_MASTER_KEY_LENGTH); std::memcpy(srtpRemoteMasterKey, srtpRemoteKey, SrtpMasterKeyLength);
std::memcpy(srtp_remote_master_key + MS_SRTP_MASTER_KEY_LENGTH, srtp_remote_salt, MS_SRTP_MASTER_SALT_LENGTH); std::memcpy(srtpRemoteMasterKey + SrtpMasterKeyLength, srtpRemoteSalt, SrtpMasterSaltLength);
// Set state and notify the listener. // Set state and notify the listener.
this->state = DtlsState::CONNECTED; this->state = DtlsState::CONNECTED;
this->listener->onDtlsConnected(this, srtp_profile, srtp_local_master_key, MS_SRTP_MASTER_LENGTH, srtp_remote_master_key, MS_SRTP_MASTER_LENGTH, this->remoteCert); this->listener->onDtlsConnected(this, srtp_profile, srtpLocalMasterKey, SrtpMasterLength,
srtpRemoteMasterKey, SrtpMasterLength, this->remoteCert);
} }
inline inline
...@@ -1129,17 +1168,18 @@ namespace RTC ...@@ -1129,17 +1168,18 @@ namespace RTC
{ {
MS_TRACE(); MS_TRACE();
RTC::SrtpSession::Profile negotiated_srtp_profile = RTC::SrtpSession::Profile::NONE; RTC::SrtpSession::Profile negotiatedSrtpProfile = RTC::SrtpSession::Profile::NONE;
// Ensure that the SRTP profile has been negotiated. // Ensure that the SRTP profile has been negotiated.
SRTP_PROTECTION_PROFILE* ssl_srtp_profile = SSL_get_selected_srtp_profile(this->ssl); SRTP_PROTECTION_PROFILE* ssl_srtp_profile = SSL_get_selected_srtp_profile(this->ssl);
if (!ssl_srtp_profile) if (!ssl_srtp_profile)
{ {
return negotiated_srtp_profile; return negotiatedSrtpProfile;
} }
// Get the negotiated SRTP profile. // Get the negotiated SRTP profile.
for (auto it = DtlsTransport::srtpProfiles.begin(); it != DtlsTransport::srtpProfiles.end(); ++it) auto it = DtlsTransport::srtpProfiles.begin();
for (; it != DtlsTransport::srtpProfiles.end(); ++it)
{ {
SrtpProfileMapEntry* profile_entry = &(*it); SrtpProfileMapEntry* profile_entry = &(*it);
...@@ -1147,13 +1187,13 @@ namespace RTC ...@@ -1147,13 +1187,13 @@ namespace RTC
{ {
MS_DEBUG_TAG(dtls, "chosen SRTP profile: %s", profile_entry->name); MS_DEBUG_TAG(dtls, "chosen SRTP profile: %s", profile_entry->name);
negotiated_srtp_profile = profile_entry->profile; negotiatedSrtpProfile = profile_entry->profile;
} }
} }
MS_ASSERT(negotiated_srtp_profile != RTC::SrtpSession::Profile::NONE, "chosen SRTP profile is not an available one"); MS_ASSERT(negotiatedSrtpProfile != RTC::SrtpSession::Profile::NONE, "chosen SRTP profile is not an available one");
return negotiated_srtp_profile; return negotiatedSrtpProfile;
} }
inline inline
...@@ -1184,11 +1224,20 @@ namespace RTC ...@@ -1184,11 +1224,20 @@ namespace RTC
} }
if (where & SSL_CB_READ) if (where & SSL_CB_READ)
MS_WARN_TAG(dtls, "received DTLS %s alert: %s", alert_type, SSL_alert_desc_string_long(ret)); {
MS_WARN_TAG(dtls, "received DTLS %s alert: %s",
alert_type, SSL_alert_desc_string_long(ret));
}
else if (where & SSL_CB_WRITE) else if (where & SSL_CB_WRITE)
MS_DEBUG_TAG(dtls, "sending DTLS %s alert: %s", alert_type, SSL_alert_desc_string_long(ret)); {
MS_DEBUG_TAG(dtls, "sending DTLS %s alert: %s",
alert_type, SSL_alert_desc_string_long(ret));
}
else else
MS_DEBUG_TAG(dtls, "DTLS %s alert: %s", alert_type, SSL_alert_desc_string_long(ret)); {
MS_DEBUG_TAG(dtls, "DTLS %s alert: %s",
alert_type, SSL_alert_desc_string_long(ret));
}
} }
else if (where & SSL_CB_EXIT) else if (where & SSL_CB_EXIT)
{ {
...@@ -1218,10 +1267,8 @@ namespace RTC ...@@ -1218,10 +1267,8 @@ namespace RTC
MS_TRACE(); MS_TRACE();
DTLSv1_handle_timeout(this->ssl); DTLSv1_handle_timeout(this->ssl);
// If required, send DTLS data. // If required, send DTLS data.
SendPendingOutgoingDtlsData(); SendPendingOutgoingDtlsData();
// Set the DTLS timer again. // Set the DTLS timer again.
SetTimeout(); SetTimeout();
} }
......
...@@ -4,13 +4,12 @@ ...@@ -4,13 +4,12 @@
#include "RTC/IceServer.hpp" #include "RTC/IceServer.hpp"
#include "Logger.hpp" #include "Logger.hpp"
#define MS_STUN_SERIALIZE_BUFFER_SIZE 65536
namespace RTC namespace RTC
{ {
/* Class variables. */ /* Static. */
uint8_t IceServer::stunSerializeBuffer[MS_STUN_SERIALIZE_BUFFER_SIZE]; static constexpr size_t StunSerializeBufferSize = 65536;
static uint8_t StunSerializeBuffer[StunSerializeBufferSize];
/* Instance methods. */ /* Instance methods. */
...@@ -21,7 +20,8 @@ namespace RTC ...@@ -21,7 +20,8 @@ namespace RTC
{ {
MS_TRACE(); MS_TRACE();
MS_DEBUG_TAG(ice, "[usernameFragment:%s, password:%s]", this->usernameFragment.c_str(), this->password.c_str()); MS_DEBUG_TAG(ice, "[usernameFragment:%s, password:%s]",
this->usernameFragment.c_str(), this->password.c_str());
} }
void IceServer::Destroy() void IceServer::Destroy()
...@@ -40,17 +40,20 @@ namespace RTC ...@@ -40,17 +40,20 @@ namespace RTC
{ {
if (msg->GetClass() == RTC::StunMessage::Class::Request) if (msg->GetClass() == RTC::StunMessage::Class::Request)
{ {
MS_WARN_TAG(ice, "unknown method %#.3x in STUN Request => 400", (unsigned int)msg->GetMethod()); MS_WARN_TAG(ice, "unknown method %#.3x in STUN Request => 400",
(unsigned int)msg->GetMethod());
// Reply 400. // Reply 400.
RTC::StunMessage* response = msg->CreateErrorResponse(400); RTC::StunMessage* response = msg->CreateErrorResponse(400);
response->Serialize(IceServer::stunSerializeBuffer);
response->Serialize(StunSerializeBuffer);
this->listener->onOutgoingStunMessage(this, response, tuple); this->listener->onOutgoingStunMessage(this, response, tuple);
delete response; delete response;
} }
else else
{ {
MS_WARN_TAG(ice, "ignoring STUN Indication or Response with unknown method %#.3x", (unsigned int)msg->GetMethod()); MS_WARN_TAG(ice, "ignoring STUN Indication or Response with unknown method %#.3x",
(unsigned int)msg->GetMethod());
} }
return; return;
...@@ -65,7 +68,8 @@ namespace RTC ...@@ -65,7 +68,8 @@ namespace RTC
// Reply 400. // Reply 400.
RTC::StunMessage* response = msg->CreateErrorResponse(400); RTC::StunMessage* response = msg->CreateErrorResponse(400);
response->Serialize(IceServer::stunSerializeBuffer);
response->Serialize(StunSerializeBuffer);
this->listener->onOutgoingStunMessage(this, response, tuple); this->listener->onOutgoingStunMessage(this, response, tuple);
delete response; delete response;
} }
...@@ -88,7 +92,8 @@ namespace RTC ...@@ -88,7 +92,8 @@ namespace RTC
// Reply 400. // Reply 400.
RTC::StunMessage* response = msg->CreateErrorResponse(400); RTC::StunMessage* response = msg->CreateErrorResponse(400);
response->Serialize(IceServer::stunSerializeBuffer);
response->Serialize(StunSerializeBuffer);
this->listener->onOutgoingStunMessage(this, response, tuple); this->listener->onOutgoingStunMessage(this, response, tuple);
delete response; delete response;
...@@ -107,7 +112,8 @@ namespace RTC ...@@ -107,7 +112,8 @@ namespace RTC
// Reply 401. // Reply 401.
RTC::StunMessage* response = msg->CreateErrorResponse(401); RTC::StunMessage* response = msg->CreateErrorResponse(401);
response->Serialize(IceServer::stunSerializeBuffer);
response->Serialize(StunSerializeBuffer);
this->listener->onOutgoingStunMessage(this, response, tuple); this->listener->onOutgoingStunMessage(this, response, tuple);
delete response; delete response;
...@@ -120,7 +126,8 @@ namespace RTC ...@@ -120,7 +126,8 @@ namespace RTC
// Reply 400. // Reply 400.
RTC::StunMessage* response = msg->CreateErrorResponse(400); RTC::StunMessage* response = msg->CreateErrorResponse(400);
response->Serialize(IceServer::stunSerializeBuffer);
response->Serialize(StunSerializeBuffer);
this->listener->onOutgoingStunMessage(this, response, tuple); this->listener->onOutgoingStunMessage(this, response, tuple);
delete response; delete response;
...@@ -135,14 +142,17 @@ namespace RTC ...@@ -135,14 +142,17 @@ namespace RTC
// Reply 487 (Role Conflict). // Reply 487 (Role Conflict).
RTC::StunMessage* response = msg->CreateErrorResponse(487); RTC::StunMessage* response = msg->CreateErrorResponse(487);
response->Serialize(IceServer::stunSerializeBuffer);
response->Serialize(StunSerializeBuffer);
this->listener->onOutgoingStunMessage(this, response, tuple); this->listener->onOutgoingStunMessage(this, response, tuple);
delete response; delete response;
return; return;
} }
MS_DEBUG_TAG(ice, "processing STUN Binding Request [Priority:%" PRIu32 ", UseCandidate:%s]", (uint32_t)msg->GetPriority(), msg->HasUseCandidate() ? "true" : "false"); MS_DEBUG_TAG(ice,
"processing STUN Binding Request [Priority:%" PRIu32 ", UseCandidate:%s]",
(uint32_t)msg->GetPriority(), msg->HasUseCandidate() ? "true" : "false");
// Create a success response. // Create a success response.
RTC::StunMessage* response = msg->CreateSuccessResponse(); RTC::StunMessage* response = msg->CreateSuccessResponse();
...@@ -154,7 +164,7 @@ namespace RTC ...@@ -154,7 +164,7 @@ namespace RTC
response->Authenticate(this->password); response->Authenticate(this->password);
// Send back. // Send back.
response->Serialize(IceServer::stunSerializeBuffer); response->Serialize(StunSerializeBuffer);
this->listener->onOutgoingStunMessage(this, response, tuple); this->listener->onOutgoingStunMessage(this, response, tuple);
delete response; delete response;
...@@ -196,27 +206,27 @@ namespace RTC ...@@ -196,27 +206,27 @@ namespace RTC
void IceServer::RemoveTuple(RTC::TransportTuple* tuple) void IceServer::RemoveTuple(RTC::TransportTuple* tuple)
{ {
auto it = this->tuples.begin(); RTC::TransportTuple* removedTuple = nullptr;
RTC::TransportTuple* removed_tuple = nullptr;
// Find the removed tuple. // Find the removed tuple.
auto it = this->tuples.begin();
for (; it != this->tuples.end(); ++it) for (; it != this->tuples.end(); ++it)
{ {
RTC::TransportTuple* stored_tuple = std::addressof(*it); RTC::TransportTuple* storedTuple = std::addressof(*it);
if (stored_tuple->Compare(tuple)) if (storedTuple->Compare(tuple))
{ {
removed_tuple = stored_tuple; removedTuple = storedTuple;
break; break;
} }
} }
// If not found, ignore. // If not found, ignore.
if (!removed_tuple) if (!removedTuple)
return; return;
// If this is not the selected tuple just remove it. // If this is not the selected tuple just remove it.
if (removed_tuple != this->selectedTuple) if (removedTuple != this->selectedTuple)
{ {
this->tuples.erase(it); this->tuples.erase(it);
...@@ -233,12 +243,11 @@ namespace RTC ...@@ -233,12 +243,11 @@ namespace RTC
{ {
SetSelectedTuple(std::addressof(*this->tuples.begin())); SetSelectedTuple(std::addressof(*this->tuples.begin()));
} }
// Or just emit 'disconnected' and the null selected tuple.. // Or just emit 'disconnected'.
else else
{ {
// Update state. // Update state.
this->state = IceState::DISCONNECTED; this->state = IceState::DISCONNECTED;
// Notify the listener. // Notify the listener.
this->listener->onIceDisconnected(this); this->listener->onIceDisconnected(this);
} }
...@@ -249,17 +258,19 @@ namespace RTC ...@@ -249,17 +258,19 @@ namespace RTC
{ {
MS_TRACE(); MS_TRACE();
MS_ASSERT(this->selectedTuple != nullptr, "cannot force the selected tuple if there was not a selected tuple"); MS_ASSERT(this->selectedTuple != nullptr,
"cannot force the selected tuple if there was not a selected tuple");
auto stored_tuple = HasTuple(tuple); auto storedTuple = HasTuple(tuple);
MS_ASSERT(stored_tuple, "cannot force the selected tuple if the given tuple was not already a valid tuple"); MS_ASSERT(storedTuple,
"cannot force the selected tuple if the given tuple was not already a valid tuple");
// Mark it as selected tuple. // Mark it as selected tuple.
SetSelectedTuple(stored_tuple); SetSelectedTuple(storedTuple);
} }
void IceServer::HandleTuple(RTC::TransportTuple* tuple, bool has_use_candidate) void IceServer::HandleTuple(RTC::TransportTuple* tuple, bool hasUseCandidate)
{ {
MS_TRACE(); MS_TRACE();
...@@ -268,24 +279,24 @@ namespace RTC ...@@ -268,24 +279,24 @@ namespace RTC
case IceState::NEW: case IceState::NEW:
{ {
// There should be no tuples. // There should be no tuples.
MS_ASSERT(this->tuples.size() == 0, "state is 'new' but there are %zu tuples", this->tuples.size()); MS_ASSERT(this->tuples.size() == 0, "state is 'new' but there are %zu tuples",
this->tuples.size());
// There shouldn't be a selected tuple. // There shouldn't be a selected tuple.
MS_ASSERT(this->selectedTuple == nullptr, "state is 'new' but there is selected tuple"); MS_ASSERT(this->selectedTuple == nullptr,
"state is 'new' but there is selected tuple");
if (!has_use_candidate) if (!hasUseCandidate)
{ {
MS_DEBUG_TAG(ice, "transition from state 'new' to 'connected'"); MS_DEBUG_TAG(ice, "transition from state 'new' to 'connected'");
// Store the tuple. // Store the tuple.
auto stored_tuple = AddTuple(tuple); auto storedTuple = AddTuple(tuple);
// Mark it as selected tuple. // Mark it as selected tuple.
SetSelectedTuple(stored_tuple); SetSelectedTuple(storedTuple);
// Update state. // Update state.
this->state = IceState::CONNECTED; this->state = IceState::CONNECTED;
// Notify the listener. // Notify the listener.
this->listener->onIceConnected(this); this->listener->onIceConnected(this);
} }
...@@ -294,14 +305,12 @@ namespace RTC ...@@ -294,14 +305,12 @@ namespace RTC
MS_DEBUG_TAG(ice, "transition from state 'new' to 'completed'"); MS_DEBUG_TAG(ice, "transition from state 'new' to 'completed'");
// Store the tuple. // Store the tuple.
auto stored_tuple = AddTuple(tuple); auto storedTuple = AddTuple(tuple);
// Mark it as selected tuple. // Mark it as selected tuple.
SetSelectedTuple(stored_tuple); SetSelectedTuple(storedTuple);
// Update state. // Update state.
this->state = IceState::COMPLETED; this->state = IceState::COMPLETED;
// Notify the listener. // Notify the listener.
this->listener->onIceCompleted(this); this->listener->onIceCompleted(this);
} }
...@@ -312,24 +321,24 @@ namespace RTC ...@@ -312,24 +321,24 @@ namespace RTC
case IceState::DISCONNECTED: case IceState::DISCONNECTED:
{ {
// There should be no tuples. // There should be no tuples.
MS_ASSERT(this->tuples.size() == 0, "state is 'disconnected' but there are %zu tuples", this->tuples.size()); MS_ASSERT(this->tuples.size() == 0,
"state is 'disconnected' but there are %zu tuples", this->tuples.size());
// There shouldn't be a selected tuple. // There shouldn't be a selected tuple.
MS_ASSERT(this->selectedTuple == nullptr, "state is 'disconnected' but there is selected tuple"); MS_ASSERT(this->selectedTuple == nullptr,
"state is 'disconnected' but there is selected tuple");
if (!has_use_candidate) if (!hasUseCandidate)
{ {
MS_DEBUG_TAG(ice, "transition from state 'disconnected' to 'connected'"); MS_DEBUG_TAG(ice, "transition from state 'disconnected' to 'connected'");
// Store the tuple. // Store the tuple.
auto stored_tuple = AddTuple(tuple); auto storedTuple = AddTuple(tuple);
// Mark it as selected tuple. // Mark it as selected tuple.
SetSelectedTuple(stored_tuple); SetSelectedTuple(storedTuple);
// Update state. // Update state.
this->state = IceState::CONNECTED; this->state = IceState::CONNECTED;
// Notify the listener. // Notify the listener.
this->listener->onIceConnected(this); this->listener->onIceConnected(this);
} }
...@@ -338,14 +347,12 @@ namespace RTC ...@@ -338,14 +347,12 @@ namespace RTC
MS_DEBUG_TAG(ice, "transition from state 'disconnected' to 'completed'"); MS_DEBUG_TAG(ice, "transition from state 'disconnected' to 'completed'");
// Store the tuple. // Store the tuple.
auto stored_tuple = AddTuple(tuple); auto storedTuple = AddTuple(tuple);
// Mark it as selected tuple. // Mark it as selected tuple.
SetSelectedTuple(stored_tuple); SetSelectedTuple(storedTuple);
// Update state. // Update state.
this->state = IceState::COMPLETED; this->state = IceState::COMPLETED;
// Notify the listener. // Notify the listener.
this->listener->onIceCompleted(this); this->listener->onIceCompleted(this);
} }
...@@ -356,12 +363,14 @@ namespace RTC ...@@ -356,12 +363,14 @@ namespace RTC
case IceState::CONNECTED: case IceState::CONNECTED:
{ {
// There should be some tuples. // There should be some tuples.
MS_ASSERT(this->tuples.size() > 0, "state is 'connected' but there are no tuples"); MS_ASSERT(this->tuples.size() > 0,
"state is 'connected' but there are no tuples");
// There should be a selected tuple. // There should be a selected tuple.
MS_ASSERT(this->selectedTuple != nullptr, "state is 'connected' but there is not selected tuple"); MS_ASSERT(this->selectedTuple != nullptr,
"state is 'connected' but there is not selected tuple");
if (!has_use_candidate) if (!hasUseCandidate)
{ {
// If a new tuple store it. // If a new tuple store it.
if (!HasTuple(tuple)) if (!HasTuple(tuple))
...@@ -371,18 +380,16 @@ namespace RTC ...@@ -371,18 +380,16 @@ namespace RTC
{ {
MS_DEBUG_TAG(ice, "transition from state 'connected' to 'completed'"); MS_DEBUG_TAG(ice, "transition from state 'connected' to 'completed'");
auto stored_tuple = HasTuple(tuple); auto storedTuple = HasTuple(tuple);
// If a new tuple store it. // If a new tuple store it.
if (!stored_tuple) if (!storedTuple)
stored_tuple = AddTuple(tuple); storedTuple = AddTuple(tuple);
// Mark it as selected tuple. // Mark it as selected tuple.
SetSelectedTuple(stored_tuple); SetSelectedTuple(storedTuple);
// Update state. // Update state.
this->state = IceState::COMPLETED; this->state = IceState::COMPLETED;
// Notify the listener. // Notify the listener.
this->listener->onIceCompleted(this); this->listener->onIceCompleted(this);
} }
...@@ -396,9 +403,10 @@ namespace RTC ...@@ -396,9 +403,10 @@ namespace RTC
MS_ASSERT(this->tuples.size() > 0, "state is 'completed' but there are no tuples"); MS_ASSERT(this->tuples.size() > 0, "state is 'completed' but there are no tuples");
// There should be a selected tuple. // There should be a selected tuple.
MS_ASSERT(this->selectedTuple != nullptr, "state is 'completed' but there is not selected tuple"); MS_ASSERT(this->selectedTuple != nullptr,
"state is 'completed' but there is not selected tuple");
if (!has_use_candidate) if (!hasUseCandidate)
{ {
// If a new tuple store it. // If a new tuple store it.
if (!HasTuple(tuple)) if (!HasTuple(tuple))
...@@ -406,14 +414,14 @@ namespace RTC ...@@ -406,14 +414,14 @@ namespace RTC
} }
else else
{ {
auto stored_tuple = HasTuple(tuple); auto storedTuple = HasTuple(tuple);
// If a new tuple store it. // If a new tuple store it.
if (!stored_tuple) if (!storedTuple)
stored_tuple = AddTuple(tuple); storedTuple = AddTuple(tuple);
// Mark it as selected tuple. // Mark it as selected tuple.
SetSelectedTuple(stored_tuple); SetSelectedTuple(storedTuple);
} }
break; break;
...@@ -429,15 +437,15 @@ namespace RTC ...@@ -429,15 +437,15 @@ namespace RTC
// Add the new tuple at the beginning of the list. // Add the new tuple at the beginning of the list.
this->tuples.push_front(*tuple); this->tuples.push_front(*tuple);
auto stored_tuple = std::addressof(*this->tuples.begin()); auto storedTuple = std::addressof(*this->tuples.begin());
// If it is UDP then we must store the remote address (until now it is // If it is UDP then we must store the remote address (until now it is
// just a pointer that will be freed soon). // just a pointer that will be freed soon).
if (stored_tuple->GetProtocol() == TransportTuple::Protocol::UDP) if (storedTuple->GetProtocol() == TransportTuple::Protocol::UDP)
stored_tuple->StoreUdpRemoteAddress(); storedTuple->StoreUdpRemoteAddress();
// Return the address of the inserted tuple. // Return the address of the inserted tuple.
return stored_tuple; return storedTuple;
} }
inline inline
...@@ -457,25 +465,25 @@ namespace RTC ...@@ -457,25 +465,25 @@ namespace RTC
// Otherwise check other stored tuples. // Otherwise check other stored tuples.
for (auto it = this->tuples.begin(); it != this->tuples.end(); ++it) for (auto it = this->tuples.begin(); it != this->tuples.end(); ++it)
{ {
RTC::TransportTuple* stored_tuple = const_cast<RTC::TransportTuple*>(std::addressof(*it)); RTC::TransportTuple* storedTuple = const_cast<RTC::TransportTuple*>(std::addressof(*it));
if (stored_tuple->Compare(tuple)) if (storedTuple->Compare(tuple))
return stored_tuple; return storedTuple;
} }
return nullptr; return nullptr;
} }
inline inline
void IceServer::SetSelectedTuple(RTC::TransportTuple* stored_tuple) void IceServer::SetSelectedTuple(RTC::TransportTuple* storedTuple)
{ {
MS_TRACE(); MS_TRACE();
// If already the selected tuple do nothing. // If already the selected tuple do nothing.
if (stored_tuple == this->selectedTuple) if (storedTuple == this->selectedTuple)
return; return;
this->selectedTuple = stored_tuple; this->selectedTuple = storedTuple;
// Notify the listener. // Notify the listener.
this->listener->onIceSelectedTuple(this, this->selectedTuple); this->listener->onIceSelectedTuple(this, this->selectedTuple);
......
...@@ -7,17 +7,19 @@ ...@@ -7,17 +7,19 @@
namespace RTC namespace RTC
{ {
constexpr uint32_t MAX_PACKET_AGE = 10000; /* Static. */
constexpr size_t MAX_NACK_PACKETS = 500;
constexpr uint32_t DEFAULT_RTT = 100; constexpr uint32_t MaxPacketAge = 10000;
constexpr uint8_t MAX_NACK_RETRIES = 8; constexpr size_t MaxNackPackets = 500;
constexpr uint64_t TIMER_INTERVAL = 25; constexpr uint32_t DefaultRtt = 100;
constexpr uint8_t MaxNackRetries = 8;
constexpr uint64_t TimerInterval = 25;
/* Instance methods. */ /* Instance methods. */
NackGenerator::NackGenerator(Listener* listener) : NackGenerator::NackGenerator(Listener* listener) :
listener(listener), listener(listener),
rtt(DEFAULT_RTT) rtt(DefaultRtt)
{ {
MS_TRACE(); MS_TRACE();
...@@ -41,36 +43,37 @@ namespace RTC ...@@ -41,36 +43,37 @@ namespace RTC
if (!this->started) if (!this->started)
{ {
this->last_seq32 = seq32; this->lastSeq32 = seq32;
this->started = true; this->started = true;
return; return;
} }
// Obviously never nacked, so ignore. // Obviously never nacked, so ignore.
if (seq32 == this->last_seq32) if (seq32 == this->lastSeq32)
{ {
return; return;
} }
else if (seq32 == this->last_seq32 + 1) else if (seq32 == this->lastSeq32 + 1)
{ {
this->last_seq32++; this->lastSeq32++;
return; return;
} }
// May be an out of order packet or a retransmitted packet (without RTX). // May be an out of order packet or a retransmitted packet (without RTX).
if (seq32 < this->last_seq32) if (seq32 < this->lastSeq32)
{ {
auto it = this->nack_list.find(seq32); auto it = this->nackList.find(seq32);
// It was a nacked packet. // It was a nacked packet.
if (it != this->nack_list.end()) if (it != this->nackList.end())
{ {
MS_DEBUG_TAG(rtx, MS_DEBUG_TAG(rtx,
"nacked packet received [ssrc:%" PRIu32 ", seq:%" PRIu16 "]", "nacked packet received [ssrc:%" PRIu32 ", seq:%" PRIu16 "]",
packet->GetSsrc(), packet->GetSequenceNumber()); packet->GetSsrc(), packet->GetSequenceNumber());
this->nack_list.erase(it); this->nackList.erase(it);
} }
// Out of order packet. // Out of order packet.
else else
...@@ -84,84 +87,86 @@ namespace RTC ...@@ -84,84 +87,86 @@ namespace RTC
} }
// Otherwise we may have lost some packets. // Otherwise we may have lost some packets.
AddPacketsToNackList(this->last_seq32 + 1, seq32); AddPacketsToNackList(this->lastSeq32 + 1, seq32);
this->last_seq32 = seq32; this->lastSeq32 = seq32;
// Check if there are any nacks that are waiting for this seq number. // Check if there are any nacks that are waiting for this seq number.
std::vector<uint16_t> nack_batch = GetNackBatch(NackFilter::SEQ); std::vector<uint16_t> nackBatch = GetNackBatch(NackFilter::SEQ);
if (!nack_batch.empty()) if (!nackBatch.empty())
this->listener->onNackRequired(nack_batch); this->listener->onNackRequired(nackBatch);
MayRunTimer(); MayRunTimer();
} }
void NackGenerator::AddPacketsToNackList(uint32_t seq32_start, uint32_t seq32_end) void NackGenerator::AddPacketsToNackList(uint32_t seq32Start, uint32_t seq32End)
{ {
MS_TRACE(); MS_TRACE();
// Remove old packets. // Remove old packets.
auto it = this->nack_list.lower_bound(seq32_end - MAX_PACKET_AGE); auto it = this->nackList.lower_bound(seq32End - MaxPacketAge);
this->nack_list.erase(this->nack_list.begin(), it); this->nackList.erase(this->nackList.begin(), it);
// If the nack list is too large, clear it and request a full frame. // If the nack list is too large, clear it and request a full frame.
uint32_t num_new_nacks = seq32_end - seq32_start; uint32_t numNewNacks = seq32End - seq32Start;
if (this->nack_list.size() + num_new_nacks > MAX_NACK_PACKETS) if (this->nackList.size() + numNewNacks > MaxNackPackets)
{ {
MS_DEBUG_TAG(rtx, "nack list too large, clearing it and requesting a full frame"); MS_DEBUG_TAG(rtx, "nack list too large, clearing it and requesting a full frame");
this->nack_list.clear(); this->nackList.clear();
this->listener->onFullFrameRequired(); this->listener->onFullFrameRequired();
return; return;
} }
for (uint32_t seq32 = seq32_start; seq32 != seq32_end; ++seq32) for (uint32_t seq32 = seq32Start; seq32 != seq32End; ++seq32)
{ {
// NOTE: Let the packet become out of order for a while without requesting // NOTE: Let the packet become out of order for a while without requesting
// it into a NACK. // it into a NACK.
// TODO: To be done. // TODO: To be done.
uint32_t send_at_seq_num = seq32 + 0; uint32_t sendAtSeqNum = seq32 + 0;
NackInfo nack_info(seq32, send_at_seq_num); NackInfo nackInfo(seq32, sendAtSeqNum);
MS_ASSERT(this->nack_list.find(seq32) == this->nack_list.end(), "packet already in the NACK list"); MS_ASSERT(this->nackList.find(seq32) == this->nackList.end(),
"packet already in the NACK list");
this->nack_list[seq32] = nack_info; this->nackList[seq32] = nackInfo;
} }
} }
std::vector<uint16_t> NackGenerator::GetNackBatch(NackFilter filter) std::vector<uint16_t> NackGenerator::GetNackBatch(NackFilter filter)
{ {
uint64_t now = DepLibUV::GetTime(); uint64_t now = DepLibUV::GetTime();
std::vector<uint16_t> nack_batch; std::vector<uint16_t> nackBatch;
auto it = this->nack_list.begin(); auto it = this->nackList.begin();
while (it != this->nack_list.end()) while (it != this->nackList.end())
{ {
NackInfo& nack_info = it->second; NackInfo& nackInfo = it->second;
uint16_t seq = nack_info.seq32 % (1<<16); uint16_t seq = nackInfo.seq32 % (1<<16);
if ( if (
filter == NackFilter::SEQ && filter == NackFilter::SEQ &&
nack_info.sent_at_time == 0 && nackInfo.sentAtTime == 0 &&
this->last_seq32 >= nack_info.send_at_seq_num) this->lastSeq32 >= nackInfo.sendAtSeqNum)
{ {
nack_info.retries++; nackInfo.retries++;
nack_info.sent_at_time = now; nackInfo.sentAtTime = now;
if (nack_info.retries >= MAX_NACK_RETRIES) if (nackInfo.retries >= MaxNackRetries)
{ {
MS_WARN_TAG(rtx, MS_WARN_TAG(rtx,
"sequence number removed from the NACK list due to max retries [seq:%" PRIu16 "]", seq); "sequence number removed from the NACK list due to max retries [seq:%" PRIu16 "]",
seq);
it = this->nack_list.erase(it); it = this->nackList.erase(it);
} }
else else
{ {
nack_batch.emplace_back(seq); nackBatch.emplace_back(seq);
++it; ++it;
} }
...@@ -170,21 +175,22 @@ namespace RTC ...@@ -170,21 +175,22 @@ namespace RTC
if ( if (
filter == NackFilter::TIME && filter == NackFilter::TIME &&
nack_info.sent_at_time + this->rtt < now) nackInfo.sentAtTime + this->rtt < now)
{ {
nack_info.retries++; nackInfo.retries++;
nack_info.sent_at_time = now; nackInfo.sentAtTime = now;
if (nack_info.retries >= MAX_NACK_RETRIES) if (nackInfo.retries >= MaxNackRetries)
{ {
MS_WARN_TAG(rtx, MS_WARN_TAG(rtx,
"sequence number removed from the NACK list due to max retries [seq:%" PRIu16 "]", seq); "sequence number removed from the NACK list due to max retries [seq:%" PRIu16 "]",
seq);
it = this->nack_list.erase(it); it = this->nackList.erase(it);
} }
else else
{ {
nack_batch.emplace_back(seq); nackBatch.emplace_back(seq);
++it; ++it;
} }
...@@ -194,14 +200,14 @@ namespace RTC ...@@ -194,14 +200,14 @@ namespace RTC
++it; ++it;
} }
return nack_batch; return nackBatch;
} }
inline inline
void NackGenerator::MayRunTimer() const void NackGenerator::MayRunTimer() const
{ {
if (this->nack_list.size() > 0) if (this->nackList.size() > 0)
this->timer->Start(TIMER_INTERVAL); this->timer->Start(TimerInterval);
} }
inline inline
...@@ -209,10 +215,10 @@ namespace RTC ...@@ -209,10 +215,10 @@ namespace RTC
{ {
MS_TRACE(); MS_TRACE();
std::vector<uint16_t> nack_batch = GetNackBatch(NackFilter::TIME); std::vector<uint16_t> nackBatch = GetNackBatch(NackFilter::TIME);
if (!nack_batch.empty()) if (!nackBatch.empty())
this->listener->onNackRequired(nack_batch); this->listener->onNackRequired(nackBatch);
MayRunTimer(); MayRunTimer();
} }
......
...@@ -47,7 +47,7 @@ namespace RTC ...@@ -47,7 +47,7 @@ namespace RTC
static const Json::StaticString k_class("class"); static const Json::StaticString k_class("class");
Json::Value event_data(Json::objectValue); Json::Value eventData(Json::objectValue);
// Close all the RtpReceivers. // Close all the RtpReceivers.
for (auto it = this->rtpReceivers.begin(); it != this->rtpReceivers.end();) for (auto it = this->rtpReceivers.begin(); it != this->rtpReceivers.end();)
...@@ -79,8 +79,8 @@ namespace RTC ...@@ -79,8 +79,8 @@ namespace RTC
} }
// Notify. // Notify.
event_data[k_class] = "Peer"; eventData[k_class] = "Peer";
this->notifier->Emit(this->peerId, "close", event_data); this->notifier->Emit(this->peerId, "close", eventData);
// Notify the listener. // Notify the listener.
this->listener->onPeerClosed(this); this->listener->onPeerClosed(this);
...@@ -100,9 +100,9 @@ namespace RTC ...@@ -100,9 +100,9 @@ namespace RTC
static const Json::StaticString k_rtpSenders("rtpSenders"); static const Json::StaticString k_rtpSenders("rtpSenders");
Json::Value json(Json::objectValue); Json::Value json(Json::objectValue);
Json::Value json_transports(Json::arrayValue); Json::Value jsonTransports(Json::arrayValue);
Json::Value json_rtpReceivers(Json::arrayValue); Json::Value jsonRtpReceivers(Json::arrayValue);
Json::Value json_rtpSenders(Json::arrayValue); Json::Value jsonRtpSenders(Json::arrayValue);
// Add `peerId`. // Add `peerId`.
json[k_peerId] = (Json::UInt)this->peerId; json[k_peerId] = (Json::UInt)this->peerId;
...@@ -119,27 +119,27 @@ namespace RTC ...@@ -119,27 +119,27 @@ namespace RTC
{ {
RTC::Transport* transport = kv.second; RTC::Transport* transport = kv.second;
json_transports.append(transport->toJson()); jsonTransports.append(transport->toJson());
} }
json[k_transports] = json_transports; json[k_transports] = jsonTransports;
// Add `rtpReceivers`. // Add `rtpReceivers`.
for (auto& kv : this->rtpReceivers) for (auto& kv : this->rtpReceivers)
{ {
RTC::RtpReceiver* rtpReceiver = kv.second; RTC::RtpReceiver* rtpReceiver = kv.second;
json_rtpReceivers.append(rtpReceiver->toJson()); jsonRtpReceivers.append(rtpReceiver->toJson());
} }
json[k_rtpReceivers] = json_rtpReceivers; json[k_rtpReceivers] = jsonRtpReceivers;
// Add `rtpSenders`. // Add `rtpSenders`.
for (auto& kv : this->rtpSenders) for (auto& kv : this->rtpSenders)
{ {
RTC::RtpSender* rtpSender = kv.second; RTC::RtpSender* rtpSender = kv.second;
json_rtpSenders.append(rtpSender->toJson()); jsonRtpSenders.append(rtpSender->toJson());
} }
json[k_rtpSenders] = json_rtpSenders; json[k_rtpSenders] = jsonRtpSenders;
return json; return json;
} }
...@@ -152,9 +152,9 @@ namespace RTC ...@@ -152,9 +152,9 @@ namespace RTC
{ {
case Channel::Request::MethodId::peer_close: case Channel::Request::MethodId::peer_close:
{ {
#ifdef MS_LOG_DEV #ifdef MS_LOG_DEV
uint32_t peerId = this->peerId; uint32_t peerId = this->peerId;
#endif #endif
Destroy(); Destroy();
...@@ -180,6 +180,7 @@ namespace RTC ...@@ -180,6 +180,7 @@ namespace RTC
if (this->hasCapabilities) if (this->hasCapabilities)
{ {
request->Reject("peer capabilities already set"); request->Reject("peer capabilities already set");
return; return;
} }
...@@ -190,6 +191,7 @@ namespace RTC ...@@ -190,6 +191,7 @@ namespace RTC
catch (const MediaSoupError &error) catch (const MediaSoupError &error)
{ {
request->Reject(error.what()); request->Reject(error.what());
return; return;
} }
...@@ -223,12 +225,14 @@ namespace RTC ...@@ -223,12 +225,14 @@ namespace RTC
catch (const MediaSoupError &error) catch (const MediaSoupError &error)
{ {
request->Reject(error.what()); request->Reject(error.what());
return; return;
} }
if (transport) if (transport)
{ {
request->Reject("Transport already exists"); request->Reject("Transport already exists");
return; return;
} }
...@@ -239,6 +243,7 @@ namespace RTC ...@@ -239,6 +243,7 @@ namespace RTC
catch (const MediaSoupError &error) catch (const MediaSoupError &error)
{ {
request->Reject(error.what()); request->Reject(error.what());
return; return;
} }
...@@ -265,6 +270,7 @@ namespace RTC ...@@ -265,6 +270,7 @@ namespace RTC
if (!this->hasCapabilities) if (!this->hasCapabilities)
{ {
request->Reject("peer capabilities are not yet set"); request->Reject("peer capabilities are not yet set");
return; return;
} }
...@@ -275,12 +281,14 @@ namespace RTC ...@@ -275,12 +281,14 @@ namespace RTC
catch (const MediaSoupError &error) catch (const MediaSoupError &error)
{ {
request->Reject(error.what()); request->Reject(error.what());
return; return;
} }
if (rtpReceiver) if (rtpReceiver)
{ {
request->Reject("RtpReceiver already exists"); request->Reject("RtpReceiver already exists");
return; return;
} }
...@@ -291,12 +299,14 @@ namespace RTC ...@@ -291,12 +299,14 @@ namespace RTC
catch (const MediaSoupError &error) catch (const MediaSoupError &error)
{ {
request->Reject(error.what()); request->Reject(error.what());
return; return;
} }
if (!transport) if (!transport)
{ {
request->Reject("Transport does not exist"); request->Reject("Transport does not exist");
return; return;
} }
...@@ -310,11 +320,13 @@ namespace RTC ...@@ -310,11 +320,13 @@ namespace RTC
// Create a RtpReceiver instance. // Create a RtpReceiver instance.
try try
{ {
rtpReceiver = new RTC::RtpReceiver(this, this->notifier, rtpReceiverId, RTC::Media::GetKind(kind)); rtpReceiver = new RTC::RtpReceiver(this, this->notifier, rtpReceiverId,
RTC::Media::GetKind(kind));
} }
catch (const MediaSoupError &error) catch (const MediaSoupError &error)
{ {
request->Reject(error.what()); request->Reject(error.what());
return; return;
} }
...@@ -344,12 +356,14 @@ namespace RTC ...@@ -344,12 +356,14 @@ namespace RTC
catch (const MediaSoupError &error) catch (const MediaSoupError &error)
{ {
request->Reject(error.what()); request->Reject(error.what());
return; return;
} }
if (!transport) if (!transport)
{ {
request->Reject("Transport does not exist"); request->Reject("Transport does not exist");
return; return;
} }
...@@ -373,12 +387,14 @@ namespace RTC ...@@ -373,12 +387,14 @@ namespace RTC
catch (const MediaSoupError &error) catch (const MediaSoupError &error)
{ {
request->Reject(error.what()); request->Reject(error.what());
return; return;
} }
if (!rtpReceiver) if (!rtpReceiver)
{ {
request->Reject("RtpReceiver does not exist"); request->Reject("RtpReceiver does not exist");
return; return;
} }
...@@ -398,12 +414,14 @@ namespace RTC ...@@ -398,12 +414,14 @@ namespace RTC
catch (const MediaSoupError &error) catch (const MediaSoupError &error)
{ {
request->Reject(error.what()); request->Reject(error.what());
return; return;
} }
if (!rtpSender) if (!rtpSender)
{ {
request->Reject("RtpSender does not exist"); request->Reject("RtpSender does not exist");
return; return;
} }
...@@ -423,12 +441,14 @@ namespace RTC ...@@ -423,12 +441,14 @@ namespace RTC
catch (const MediaSoupError &error) catch (const MediaSoupError &error)
{ {
request->Reject(error.what()); request->Reject(error.what());
return; return;
} }
if (!rtpSender) if (!rtpSender)
{ {
request->Reject("RtpSender does not exist"); request->Reject("RtpSender does not exist");
return; return;
} }
...@@ -441,12 +461,14 @@ namespace RTC ...@@ -441,12 +461,14 @@ namespace RTC
catch (const MediaSoupError &error) catch (const MediaSoupError &error)
{ {
request->Reject(error.what()); request->Reject(error.what());
return; return;
} }
if (!transport) if (!transport)
{ {
request->Reject("Transport does not exist"); request->Reject("Transport does not exist");
return; return;
} }
...@@ -468,12 +490,14 @@ namespace RTC ...@@ -468,12 +490,14 @@ namespace RTC
catch (const MediaSoupError &error) catch (const MediaSoupError &error)
{ {
request->Reject(error.what()); request->Reject(error.what());
return; return;
} }
if (!rtpSender) if (!rtpSender)
{ {
request->Reject("RtpSender does not exist"); request->Reject("RtpSender does not exist");
return; return;
} }
...@@ -511,19 +535,20 @@ namespace RTC ...@@ -511,19 +535,20 @@ namespace RTC
this->rtpSenders[rtpSender->rtpSenderId] = rtpSender; this->rtpSenders[rtpSender->rtpSenderId] = rtpSender;
// Notify. // Notify.
Json::Value event_data = rtpSender->toJson(); Json::Value eventData = rtpSender->toJson();
event_data[k_class] = "Peer"; eventData[k_class] = "Peer";
event_data[k_peerName] = peerName; eventData[k_peerName] = peerName;
this->notifier->Emit(this->peerId, "newrtpsender", event_data); this->notifier->Emit(this->peerId, "newrtpsender", eventData);
} }
RTC::RtpSender* Peer::GetRtpSender(uint32_t ssrc) const RTC::RtpSender* Peer::GetRtpSender(uint32_t ssrc) const
{ {
MS_TRACE(); MS_TRACE();
for (auto it = this->rtpSenders.begin(); it != this->rtpSenders.end(); ++it) auto it = this->rtpSenders.begin();
for (; it != this->rtpSenders.end(); ++it)
{ {
auto rtpSender = it->second; auto rtpSender = it->second;
auto rtpParameters = rtpSender->GetParameters(); auto rtpParameters = rtpSender->GetParameters();
...@@ -531,7 +556,8 @@ namespace RTC ...@@ -531,7 +556,8 @@ namespace RTC
if (!rtpParameters) if (!rtpParameters)
continue; continue;
for (auto it2 = rtpParameters->encodings.begin(); it2 != rtpParameters->encodings.end(); ++it2) auto it2 = rtpParameters->encodings.begin();
for (; it2 != rtpParameters->encodings.end(); ++it2)
{ {
auto& encoding = *it2; auto& encoding = *it2;
...@@ -576,14 +602,15 @@ namespace RTC ...@@ -576,14 +602,15 @@ namespace RTC
// Ensure that the RTCP packet fits into the RTCP buffer. // Ensure that the RTCP packet fits into the RTCP buffer.
if (packet->GetSize() > MS_RTCP_BUFFER_SIZE) if (packet->GetSize() > MS_RTCP_BUFFER_SIZE)
{ {
MS_WARN_TAG(rtcp, "cannot send RTCP packet, size too big (%zu bytes)", packet->GetSize()); MS_WARN_TAG(rtcp, "cannot send RTCP packet, size too big (%zu bytes)",
packet->GetSize());
return; return;
} }
packet->Serialize(Peer::rtcpBuffer); packet->Serialize(Peer::rtcpBuffer);
transport->SendRtcpCompoundPacket(packet.get()); transport->SendRtcpCompoundPacket(packet.get());
// Reset the Compound packet.
// reset the Compound packet.
packet.reset(new RTC::RTCP::CompoundPacket()); packet.reset(new RTC::RTCP::CompoundPacket());
} }
} }
...@@ -604,7 +631,9 @@ namespace RTC ...@@ -604,7 +631,9 @@ namespace RTC
// Ensure that the RTCP packet fits into the RTCP buffer. // Ensure that the RTCP packet fits into the RTCP buffer.
if (packet->GetSize() > MS_RTCP_BUFFER_SIZE) if (packet->GetSize() > MS_RTCP_BUFFER_SIZE)
{ {
MS_WARN_TAG(rtcp, "cannot send RTCP packet, size too big (%zu bytes)", packet->GetSize()); MS_WARN_TAG(rtcp, "cannot send RTCP packet, size too big (%zu bytes)",
packet->GetSize());
return; return;
} }
...@@ -620,15 +649,15 @@ namespace RTC ...@@ -620,15 +649,15 @@ namespace RTC
static const Json::StaticString k_transportId("transportId"); static const Json::StaticString k_transportId("transportId");
auto json_transportId = request->internal[k_transportId]; auto jsonTransportId = request->internal[k_transportId];
if (!json_transportId.isUInt()) if (!jsonTransportId.isUInt())
MS_THROW_ERROR("Request has not numeric internal.transportId"); MS_THROW_ERROR("Request has not numeric internal.transportId");
if (transportId) if (transportId)
*transportId = json_transportId.asUInt(); *transportId = jsonTransportId.asUInt();
auto it = this->transports.find(json_transportId.asUInt()); auto it = this->transports.find(jsonTransportId.asUInt());
if (it != this->transports.end()) if (it != this->transports.end())
{ {
RTC::Transport* transport = it->second; RTC::Transport* transport = it->second;
...@@ -647,15 +676,15 @@ namespace RTC ...@@ -647,15 +676,15 @@ namespace RTC
static const Json::StaticString k_rtpReceiverId("rtpReceiverId"); static const Json::StaticString k_rtpReceiverId("rtpReceiverId");
auto json_rtpReceiverId = request->internal[k_rtpReceiverId]; auto jsonRtpReceiverId = request->internal[k_rtpReceiverId];
if (!json_rtpReceiverId.isUInt()) if (!jsonRtpReceiverId.isUInt())
MS_THROW_ERROR("Request has not numeric internal.rtpReceiverId"); MS_THROW_ERROR("Request has not numeric internal.rtpReceiverId");
if (rtpReceiverId) if (rtpReceiverId)
*rtpReceiverId = json_rtpReceiverId.asUInt(); *rtpReceiverId = jsonRtpReceiverId.asUInt();
auto it = this->rtpReceivers.find(json_rtpReceiverId.asUInt()); auto it = this->rtpReceivers.find(jsonRtpReceiverId.asUInt());
if (it != this->rtpReceivers.end()) if (it != this->rtpReceivers.end())
{ {
RTC::RtpReceiver* rtpReceiver = it->second; RTC::RtpReceiver* rtpReceiver = it->second;
...@@ -674,15 +703,15 @@ namespace RTC ...@@ -674,15 +703,15 @@ namespace RTC
static const Json::StaticString k_rtpSenderId("rtpSenderId"); static const Json::StaticString k_rtpSenderId("rtpSenderId");
auto json_rtpSenderId = request->internal[k_rtpSenderId]; auto jsonRtpSenderId = request->internal[k_rtpSenderId];
if (!json_rtpSenderId.isUInt()) if (!jsonRtpSenderId.isUInt())
MS_THROW_ERROR("Request has not numeric internal.rtpSenderId"); MS_THROW_ERROR("Request has not numeric internal.rtpSenderId");
if (rtpSenderId) if (rtpSenderId)
*rtpSenderId = json_rtpSenderId.asUInt(); *rtpSenderId = jsonRtpSenderId.asUInt();
auto it = this->rtpSenders.find(json_rtpSenderId.asUInt()); auto it = this->rtpSenders.find(jsonRtpSenderId.asUInt());
if (it != this->rtpSenders.end()) if (it != this->rtpSenders.end())
{ {
RTC::RtpSender* rtpSender = it->second; RTC::RtpSender* rtpSender = it->second;
...@@ -864,10 +893,9 @@ namespace RTC ...@@ -864,10 +893,9 @@ namespace RTC
case RTCP::FeedbackPs::MessageType::AFB: case RTCP::FeedbackPs::MessageType::AFB:
{ {
RTCP::FeedbackPsAfbPacket* afb = static_cast<RTCP::FeedbackPsAfbPacket*>(feedback); RTCP::FeedbackPsAfbPacket* afb = static_cast<RTCP::FeedbackPsAfbPacket*>(feedback);
if (afb->GetApplication() == RTCP::FeedbackPsAfbPacket::REMB) if (afb->GetApplication() == RTCP::FeedbackPsAfbPacket::REMB)
{
break; break;
}
} }
// [[fallthrough]]; (C++17) // [[fallthrough]]; (C++17)
...@@ -891,9 +919,9 @@ namespace RTC ...@@ -891,9 +919,9 @@ namespace RTC
else else
{ {
MS_WARN_TAG(rtcp, MS_WARN_TAG(rtcp,
"no RtpSender found for received %s Feedback packet [sender_ssrc:%" PRIu32 ", media_ssrc:%" PRIu32 "]", "no RtpSender found for received %s Feedback packet "
RTCP::FeedbackPsPacket::MessageType2String( "[sender_ssrc:%" PRIu32 ", media_ssrc:%" PRIu32 "]",
feedback->GetMessageType()).c_str(), RTCP::FeedbackPsPacket::MessageType2String(feedback->GetMessageType()).c_str(),
feedback->GetMediaSsrc(), feedback->GetMediaSsrc()); feedback->GetMediaSsrc(), feedback->GetMediaSsrc());
} }
...@@ -909,9 +937,9 @@ namespace RTC ...@@ -909,9 +937,9 @@ namespace RTC
default: default:
{ {
MS_WARN_TAG(rtcp, MS_WARN_TAG(rtcp,
"ignoring unsupported %s Feedback packet [sender_ssrc:%" PRIu32 ", media_ssrc:%" PRIu32 "]", "ignoring unsupported %s Feedback packet "
RTCP::FeedbackPsPacket::MessageType2String( "[sender_ssrc:%" PRIu32 ", media_ssrc:%" PRIu32 "]",
feedback->GetMessageType()).c_str(), RTCP::FeedbackPsPacket::MessageType2String(feedback->GetMessageType()).c_str(),
feedback->GetMediaSsrc(), feedback->GetMediaSsrc()); feedback->GetMediaSsrc(), feedback->GetMediaSsrc());
break; break;
...@@ -933,14 +961,16 @@ namespace RTC ...@@ -933,14 +961,16 @@ namespace RTC
if (rtpSender) if (rtpSender)
{ {
RTC::RTCP::FeedbackRtpNackPacket* nackPacket = static_cast<RTC::RTCP::FeedbackRtpNackPacket*>(packet); RTC::RTCP::FeedbackRtpNackPacket* nackPacket =
static_cast<RTC::RTCP::FeedbackRtpNackPacket*>(packet);
rtpSender->ReceiveNack(nackPacket); rtpSender->ReceiveNack(nackPacket);
} }
else else
{ {
MS_WARN_TAG(rtcp, MS_WARN_TAG(rtcp,
"no RtpSender found for received NACK Feedback packet [sender_ssrc:%" PRIu32 ", media_ssrc:%" PRIu32 "]", "no RtpSender found for received NACK Feedback packet "
"[sender_ssrc:%" PRIu32 ", media_ssrc:%" PRIu32 "]",
feedback->GetMediaSsrc(), feedback->GetMediaSsrc()); feedback->GetMediaSsrc(), feedback->GetMediaSsrc());
} }
...@@ -958,8 +988,10 @@ namespace RTC ...@@ -958,8 +988,10 @@ namespace RTC
default: default:
{ {
MS_WARN_TAG(rtcp, MS_WARN_TAG(rtcp,
"ignoring unsupported %s Feedback packet [sender_ssrc:%" PRIu32 ", media_ssrc:%" PRIu32 "]", "ignoring unsupported %s Feedback packet "
RTCP::FeedbackRtpPacket::MessageType2String(feedback->GetMessageType()).c_str(), feedback->GetMediaSsrc(), feedback->GetMediaSsrc()); "[sender_ssrc:%" PRIu32 ", media_ssrc:%" PRIu32 "]",
RTCP::FeedbackRtpPacket::MessageType2String(feedback->GetMessageType()).c_str(),
feedback->GetMediaSsrc(), feedback->GetMediaSsrc());
break; break;
} }
...@@ -1101,7 +1133,6 @@ namespace RTC ...@@ -1101,7 +1133,6 @@ namespace RTC
* of all participants. * of all participants.
*/ */
interval *= static_cast<float>(Utils::Crypto::GetRandomUInt(5, 15)) / 10; interval *= static_cast<float>(Utils::Crypto::GetRandomUInt(5, 15)) / 10;
this->timer->Start(interval); this->timer->Start(interval);
} }
} }
...@@ -34,13 +34,15 @@ namespace RTC ...@@ -34,13 +34,15 @@ namespace RTC
const std::string supportedRtpCapabilities = R"({"codecs":[{"kind":"audio","name":"audio/opus","clockRate":48000,"numChannels":2,"rtcpFeedback":[]},{"kind":"audio","name":"audio/PCMU","clockRate":8000,"rtcpFeedback":[]},{"kind":"audio","name":"audio/PCMA","clockRate":8000,"rtcpFeedback":[]},{"kind":"audio","name":"audio/ISAC","clockRate":32000,"rtcpFeedback":[]},{"kind":"audio","name":"audio/ISAC","clockRate":16000,"rtcpFeedback":[]},{"kind":"audio","name":"audio/G722","clockRate":8000,"rtcpFeedback":[]},{"kind":"audio","name":"audio/iLBC","clockRate":8000,"rtcpFeedback":[]},{"kind":"audio","name":"audio/SILK","clockRate":24000,"rtcpFeedback":[]},{"kind":"audio","name":"audio/SILK","clockRate":16000,"rtcpFeedback":[]},{"kind":"audio","name":"audio/SILK","clockRate":12000,"rtcpFeedback":[]},{"kind":"audio","name":"audio/SILK","clockRate":8000,"rtcpFeedback":[]},{"kind":"audio","name":"audio/CN","clockRate":32000,"rtcpFeedback":[]},{"kind":"audio","name":"audio/CN","clockRate":16000,"rtcpFeedback":[]},{"kind":"audio","name":"audio/CN","clockRate":8000,"rtcpFeedback":[]},{"kind":"audio","name":"audio/CN","clockRate":32000,"rtcpFeedback":[]},{"kind":"audio","name":"audio/telephone-event","clockRate":48000,"rtcpFeedback":[]},{"kind":"audio","name":"audio/telephone-event","clockRate":32000,"rtcpFeedback":[]},{"kind":"audio","name":"audio/telephone-event","clockRate":16000,"rtcpFeedback":[]},{"kind":"audio","name":"audio/telephone-event","clockRate":8000,"rtcpFeedback":[]},{"kind":"video","name":"video/VP8","clockRate":90000,"rtcpFeedback":[{"type":"nack"},{"type":"nack","parameter":"pli"},{"type":"nack","parameter":"sli"},{"type":"nack","parameter":"rpsi"},{"type":"nack","parameter":"app"},{"type":"ccm","parameter":"fir"},{"type":"ack","parameter":"rpsi"},{"type":"ack","parameter":"app"},{"type":"goog-remb"}]},{"kind":"video","name":"video/VP9","clockRate":90000,"rtcpFeedback":[{"type":"nack"},{"type":"nack","parameter":"pli"},{"type":"nack","parameter":"sli"},{"type":"nack","parameter":"rpsi"},{"type":"nack","parameter":"app"},{"type":"ccm","parameter":"fir"},{"type":"ack","parameter":"rpsi"},{"type":"ack","parameter":"app"},{"type":"goog-remb"}]},{"kind":"video","name":"video/H264","clockRate":90000,"parameters":{"packetizationMode":0},"rtcpFeedback":[{"type":"nack"},{"type":"nack","parameter":"pli"},{"type":"nack","parameter":"sli"},{"type":"nack","parameter":"rpsi"},{"type":"nack","parameter":"app"},{"type":"ccm","parameter":"fir"},{"type":"ack","parameter":"rpsi"},{"type":"ack","parameter":"app"},{"type":"goog-remb"}]},{"kind":"video","name":"video/H264","clockRate":90000,"parameters":{"packetizationMode":1},"rtcpFeedback":[{"type":"nack"},{"type":"nack","parameter":"pli"},{"type":"nack","parameter":"sli"},{"type":"nack","parameter":"rpsi"},{"type":"nack","parameter":"app"},{"type":"ccm","parameter":"fir"},{"type":"ack","parameter":"rpsi"},{"type":"ack","parameter":"app"},{"type":"goog-remb"}]},{"kind":"video","name":"video/H265","clockRate":90000,"rtcpFeedback":[{"type":"nack"},{"type":"nack","parameter":"pli"},{"type":"nack","parameter":"sli"},{"type":"nack","parameter":"rpsi"},{"type":"nack","parameter":"app"},{"type":"ccm","parameter":"fir"},{"type":"ack","parameter":"rpsi"},{"type":"ack","parameter":"app"},{"type":"goog-remb"}]}],"headerExtensions":[{"kind":"audio","uri":"urn:ietf:params:rtp-hdrext:ssrc-audio-level","preferredId":1,"preferredEncrypt":false},{"kind":"video","uri":"urn:ietf:params:rtp-hdrext:toffset","preferredId":2,"preferredEncrypt":false},{"kind":"","uri":"http://www.webrtc.org/experiments/rtp-hdrext/abs-send-time","preferredId":3,"preferredEncrypt":false},{"kind":"video","uri":"urn:3gpp:video-orientation","preferredId":4,"preferredEncrypt":false},{"kind":"","uri":"urn:ietf:params:rtp-hdrext:sdes:rtp-stream-id","preferredId":5,"preferredEncrypt":false}],"fecMechanisms":[]})"; const std::string supportedRtpCapabilities = R"({"codecs":[{"kind":"audio","name":"audio/opus","clockRate":48000,"numChannels":2,"rtcpFeedback":[]},{"kind":"audio","name":"audio/PCMU","clockRate":8000,"rtcpFeedback":[]},{"kind":"audio","name":"audio/PCMA","clockRate":8000,"rtcpFeedback":[]},{"kind":"audio","name":"audio/ISAC","clockRate":32000,"rtcpFeedback":[]},{"kind":"audio","name":"audio/ISAC","clockRate":16000,"rtcpFeedback":[]},{"kind":"audio","name":"audio/G722","clockRate":8000,"rtcpFeedback":[]},{"kind":"audio","name":"audio/iLBC","clockRate":8000,"rtcpFeedback":[]},{"kind":"audio","name":"audio/SILK","clockRate":24000,"rtcpFeedback":[]},{"kind":"audio","name":"audio/SILK","clockRate":16000,"rtcpFeedback":[]},{"kind":"audio","name":"audio/SILK","clockRate":12000,"rtcpFeedback":[]},{"kind":"audio","name":"audio/SILK","clockRate":8000,"rtcpFeedback":[]},{"kind":"audio","name":"audio/CN","clockRate":32000,"rtcpFeedback":[]},{"kind":"audio","name":"audio/CN","clockRate":16000,"rtcpFeedback":[]},{"kind":"audio","name":"audio/CN","clockRate":8000,"rtcpFeedback":[]},{"kind":"audio","name":"audio/CN","clockRate":32000,"rtcpFeedback":[]},{"kind":"audio","name":"audio/telephone-event","clockRate":48000,"rtcpFeedback":[]},{"kind":"audio","name":"audio/telephone-event","clockRate":32000,"rtcpFeedback":[]},{"kind":"audio","name":"audio/telephone-event","clockRate":16000,"rtcpFeedback":[]},{"kind":"audio","name":"audio/telephone-event","clockRate":8000,"rtcpFeedback":[]},{"kind":"video","name":"video/VP8","clockRate":90000,"rtcpFeedback":[{"type":"nack"},{"type":"nack","parameter":"pli"},{"type":"nack","parameter":"sli"},{"type":"nack","parameter":"rpsi"},{"type":"nack","parameter":"app"},{"type":"ccm","parameter":"fir"},{"type":"ack","parameter":"rpsi"},{"type":"ack","parameter":"app"},{"type":"goog-remb"}]},{"kind":"video","name":"video/VP9","clockRate":90000,"rtcpFeedback":[{"type":"nack"},{"type":"nack","parameter":"pli"},{"type":"nack","parameter":"sli"},{"type":"nack","parameter":"rpsi"},{"type":"nack","parameter":"app"},{"type":"ccm","parameter":"fir"},{"type":"ack","parameter":"rpsi"},{"type":"ack","parameter":"app"},{"type":"goog-remb"}]},{"kind":"video","name":"video/H264","clockRate":90000,"parameters":{"packetizationMode":0},"rtcpFeedback":[{"type":"nack"},{"type":"nack","parameter":"pli"},{"type":"nack","parameter":"sli"},{"type":"nack","parameter":"rpsi"},{"type":"nack","parameter":"app"},{"type":"ccm","parameter":"fir"},{"type":"ack","parameter":"rpsi"},{"type":"ack","parameter":"app"},{"type":"goog-remb"}]},{"kind":"video","name":"video/H264","clockRate":90000,"parameters":{"packetizationMode":1},"rtcpFeedback":[{"type":"nack"},{"type":"nack","parameter":"pli"},{"type":"nack","parameter":"sli"},{"type":"nack","parameter":"rpsi"},{"type":"nack","parameter":"app"},{"type":"ccm","parameter":"fir"},{"type":"ack","parameter":"rpsi"},{"type":"ack","parameter":"app"},{"type":"goog-remb"}]},{"kind":"video","name":"video/H265","clockRate":90000,"rtcpFeedback":[{"type":"nack"},{"type":"nack","parameter":"pli"},{"type":"nack","parameter":"sli"},{"type":"nack","parameter":"rpsi"},{"type":"nack","parameter":"app"},{"type":"ccm","parameter":"fir"},{"type":"ack","parameter":"rpsi"},{"type":"ack","parameter":"app"},{"type":"goog-remb"}]}],"headerExtensions":[{"kind":"audio","uri":"urn:ietf:params:rtp-hdrext:ssrc-audio-level","preferredId":1,"preferredEncrypt":false},{"kind":"video","uri":"urn:ietf:params:rtp-hdrext:toffset","preferredId":2,"preferredEncrypt":false},{"kind":"","uri":"http://www.webrtc.org/experiments/rtp-hdrext/abs-send-time","preferredId":3,"preferredEncrypt":false},{"kind":"video","uri":"urn:3gpp:video-orientation","preferredId":4,"preferredEncrypt":false},{"kind":"","uri":"urn:ietf:params:rtp-hdrext:sdes:rtp-stream-id","preferredId":5,"preferredEncrypt":false}],"fecMechanisms":[]})";
Json::Value json; Json::Value json;
std::string json_parse_error; std::string jsonParseError;
if (!jsonReader->parse(supportedRtpCapabilities.c_str(), supportedRtpCapabilities.c_str() + supportedRtpCapabilities.length(), &json, &json_parse_error)) if (!jsonReader->parse(supportedRtpCapabilities.c_str(),
supportedRtpCapabilities.c_str() + supportedRtpCapabilities.length(), &json, &jsonParseError))
{ {
delete jsonReader; delete jsonReader;
MS_THROW_ERROR_STD("JSON parsing error in supported RTP capabilities: %s", json_parse_error.c_str()); MS_THROW_ERROR_STD("JSON parsing error in supported RTP capabilities: %s",
jsonParseError.c_str());
} }
else else
{ {
...@@ -72,12 +74,12 @@ namespace RTC ...@@ -72,12 +74,12 @@ namespace RTC
// `mediaCodecs` is optional. // `mediaCodecs` is optional.
if (data[k_mediaCodecs].isArray()) if (data[k_mediaCodecs].isArray())
{ {
auto& json_mediaCodecs = data[k_mediaCodecs]; auto& jsonMediaCodecs = data[k_mediaCodecs];
std::vector<RTC::RtpCodecParameters> mediaCodecs; std::vector<RTC::RtpCodecParameters> mediaCodecs;
for (Json::UInt i = 0; i < json_mediaCodecs.size(); ++i) for (Json::UInt i = 0; i < jsonMediaCodecs.size(); ++i)
{ {
RTC::RtpCodecParameters mediaCodec(json_mediaCodecs[i], RTC::Scope::ROOM_CAPABILITY); RTC::RtpCodecParameters mediaCodec(jsonMediaCodecs[i], RTC::Scope::ROOM_CAPABILITY);
// Ignore feature codecs. // Ignore feature codecs.
if (mediaCodec.mime.IsFeatureCodec()) if (mediaCodec.mime.IsFeatureCodec())
...@@ -116,7 +118,7 @@ namespace RTC ...@@ -116,7 +118,7 @@ namespace RTC
static const Json::StaticString k_class("class"); static const Json::StaticString k_class("class");
Json::Value event_data(Json::objectValue); Json::Value eventData(Json::objectValue);
// Close all the Peers. // Close all the Peers.
// NOTE: Upon Peer closure the onPeerClosed() method is called which // NOTE: Upon Peer closure the onPeerClosed() method is called which
...@@ -131,8 +133,8 @@ namespace RTC ...@@ -131,8 +133,8 @@ namespace RTC
} }
// Notify. // Notify.
event_data[k_class] = "Room"; eventData[k_class] = "Room";
this->notifier->Emit(this->roomId, "close", event_data); this->notifier->Emit(this->roomId, "close", eventData);
// Notify the listener. // Notify the listener.
this->listener->onRoomClosed(this); this->listener->onRoomClosed(this);
...@@ -151,9 +153,9 @@ namespace RTC ...@@ -151,9 +153,9 @@ namespace RTC
static const Json::StaticString k_mapRtpSenderRtpReceiver("mapRtpSenderRtpReceiver"); static const Json::StaticString k_mapRtpSenderRtpReceiver("mapRtpSenderRtpReceiver");
Json::Value json(Json::objectValue); Json::Value json(Json::objectValue);
Json::Value json_peers(Json::arrayValue); Json::Value jsonPeers(Json::arrayValue);
Json::Value json_mapRtpReceiverRtpSenders(Json::objectValue); Json::Value jsonMapRtpReceiverRtpSenders(Json::objectValue);
Json::Value json_mapRtpSenderRtpReceiver(Json::objectValue); Json::Value jsonMapRtpSenderRtpReceiver(Json::objectValue);
// Add `roomId`. // Add `roomId`.
json[k_roomId] = (Json::UInt)this->roomId; json[k_roomId] = (Json::UInt)this->roomId;
...@@ -166,25 +168,25 @@ namespace RTC ...@@ -166,25 +168,25 @@ namespace RTC
{ {
RTC::Peer* peer = kv.second; RTC::Peer* peer = kv.second;
json_peers.append(peer->toJson()); jsonPeers.append(peer->toJson());
} }
json[k_peers] = json_peers; json[k_peers] = jsonPeers;
// Add `mapRtpReceiverRtpSenders`. // Add `mapRtpReceiverRtpSenders`.
for (auto& kv : this->mapRtpReceiverRtpSenders) for (auto& kv : this->mapRtpReceiverRtpSenders)
{ {
auto rtpReceiver = kv.first; auto rtpReceiver = kv.first;
auto& rtpSenders = kv.second; auto& rtpSenders = kv.second;
Json::Value json_rtpReceivers(Json::arrayValue); Json::Value jsonRtpReceivers(Json::arrayValue);
for (auto& rtpSender : rtpSenders) for (auto& rtpSender : rtpSenders)
{ {
json_rtpReceivers.append(std::to_string(rtpSender->rtpSenderId)); jsonRtpReceivers.append(std::to_string(rtpSender->rtpSenderId));
} }
json_mapRtpReceiverRtpSenders[std::to_string(rtpReceiver->rtpReceiverId)] = json_rtpReceivers; jsonMapRtpReceiverRtpSenders[std::to_string(rtpReceiver->rtpReceiverId)] = jsonRtpReceivers;
} }
json[k_mapRtpReceiverRtpSenders] = json_mapRtpReceiverRtpSenders; json[k_mapRtpReceiverRtpSenders] = jsonMapRtpReceiverRtpSenders;
// Add `mapRtpSenderRtpReceiver`. // Add `mapRtpSenderRtpReceiver`.
for (auto& kv : this->mapRtpSenderRtpReceiver) for (auto& kv : this->mapRtpSenderRtpReceiver)
...@@ -192,9 +194,10 @@ namespace RTC ...@@ -192,9 +194,10 @@ namespace RTC
auto rtpSender = kv.first; auto rtpSender = kv.first;
auto rtpReceiver = kv.second; auto rtpReceiver = kv.second;
json_mapRtpSenderRtpReceiver[std::to_string(rtpSender->rtpSenderId)] = std::to_string(rtpReceiver->rtpReceiverId); jsonMapRtpSenderRtpReceiver[std::to_string(rtpSender->rtpSenderId)] =
std::to_string(rtpReceiver->rtpReceiverId);
} }
json[k_mapRtpSenderRtpReceiver] = json_mapRtpSenderRtpReceiver; json[k_mapRtpSenderRtpReceiver] = jsonMapRtpSenderRtpReceiver;
return json; return json;
} }
...@@ -207,9 +210,9 @@ namespace RTC ...@@ -207,9 +210,9 @@ namespace RTC
{ {
case Channel::Request::MethodId::room_close: case Channel::Request::MethodId::room_close:
{ {
#ifdef MS_LOG_DEV #ifdef MS_LOG_DEV
uint32_t roomId = this->roomId; uint32_t roomId = this->roomId;
#endif #endif
Destroy(); Destroy();
...@@ -244,18 +247,21 @@ namespace RTC ...@@ -244,18 +247,21 @@ namespace RTC
catch (const MediaSoupError &error) catch (const MediaSoupError &error)
{ {
request->Reject(error.what()); request->Reject(error.what());
return; return;
} }
if (peer) if (peer)
{ {
request->Reject("Peer already exists"); request->Reject("Peer already exists");
return; return;
} }
if (!request->internal[k_peerName].isString()) if (!request->internal[k_peerName].isString())
{ {
request->Reject("Request has not string internal.peerName"); request->Reject("Request has not string internal.peerName");
return; return;
} }
...@@ -268,6 +274,7 @@ namespace RTC ...@@ -268,6 +274,7 @@ namespace RTC
catch (const MediaSoupError &error) catch (const MediaSoupError &error)
{ {
request->Reject(error.what()); request->Reject(error.what());
return; return;
} }
...@@ -308,12 +315,14 @@ namespace RTC ...@@ -308,12 +315,14 @@ namespace RTC
catch (const MediaSoupError &error) catch (const MediaSoupError &error)
{ {
request->Reject(error.what()); request->Reject(error.what());
return; return;
} }
if (!peer) if (!peer)
{ {
request->Reject("Peer does not exist"); request->Reject("Peer does not exist");
return; return;
} }
...@@ -337,16 +346,16 @@ namespace RTC ...@@ -337,16 +346,16 @@ namespace RTC
static const Json::StaticString k_peerId("peerId"); static const Json::StaticString k_peerId("peerId");
auto json_peerId = request->internal[k_peerId]; auto jsonPeerId = request->internal[k_peerId];
if (!json_peerId.isUInt()) if (!jsonPeerId.isUInt())
MS_THROW_ERROR("Request has not numeric .peerId field"); MS_THROW_ERROR("Request has not numeric .peerId field");
// If given, fill peerId. // If given, fill peerId.
if (peerId) if (peerId)
*peerId = json_peerId.asUInt(); *peerId = jsonPeerId.asUInt();
auto it = this->peers.find(json_peerId.asUInt()); auto it = this->peers.find(jsonPeerId.asUInt());
if (it != this->peers.end()) if (it != this->peers.end())
{ {
RTC::Peer* peer = it->second; RTC::Peer* peer = it->second;
...@@ -492,23 +501,24 @@ namespace RTC ...@@ -492,23 +501,24 @@ namespace RTC
// create RtpSenders for this new Peer. // create RtpSenders for this new Peer.
for (auto& kv : this->peers) for (auto& kv : this->peers)
{ {
RTC::Peer* receiver_peer = kv.second; RTC::Peer* receiverPeer = kv.second;
for (auto rtpReceiver : receiver_peer->GetRtpReceivers()) for (auto rtpReceiver : receiverPeer->GetRtpReceivers())
{ {
// Skip if the RtpReceiver has not parameters. // Skip if the RtpReceiver has not parameters.
if (!rtpReceiver->GetParameters()) if (!rtpReceiver->GetParameters())
continue; continue;
uint32_t rtpSenderId = Utils::Crypto::GetRandomUInt(10000000, 99999999); uint32_t rtpSenderId = Utils::Crypto::GetRandomUInt(10000000, 99999999);
RTC::RtpSender* rtpSender = new RTC::RtpSender(peer, this->notifier, rtpSenderId, rtpReceiver->kind); RTC::RtpSender* rtpSender = new RTC::RtpSender(peer, this->notifier, rtpSenderId,
rtpReceiver->kind);
// Store into the maps. // Store into the maps.
this->mapRtpReceiverRtpSenders[rtpReceiver].insert(rtpSender); this->mapRtpReceiverRtpSenders[rtpReceiver].insert(rtpSender);
this->mapRtpSenderRtpReceiver[rtpSender] = rtpReceiver; this->mapRtpSenderRtpReceiver[rtpSender] = rtpReceiver;
// Attach the RtpSender to peer. // Attach the RtpSender to peer.
peer->AddRtpSender(rtpSender, receiver_peer->peerName, rtpReceiver->GetParameters()); peer->AddRtpSender(rtpSender, receiverPeer->peerName, rtpReceiver->GetParameters());
} }
} }
} }
...@@ -528,26 +538,27 @@ namespace RTC ...@@ -528,26 +538,27 @@ namespace RTC
for (auto& kv : this->peers) for (auto& kv : this->peers)
{ {
RTC::Peer* sender_peer = kv.second; RTC::Peer* senderPeer = kv.second;
// Skip receiver Peer. // Skip receiver Peer.
if (sender_peer == peer) if (senderPeer == peer)
continue; continue;
// Skip Peer with capabilities not set yet. // Skip Peer with capabilities not set yet.
if (!sender_peer->HasCapabilities()) if (!senderPeer->HasCapabilities())
continue; continue;
// Create a RtpSender for the other Peer. // Create a RtpSender for the other Peer.
uint32_t rtpSenderId = Utils::Crypto::GetRandomUInt(10000000, 99999999); uint32_t rtpSenderId = Utils::Crypto::GetRandomUInt(10000000, 99999999);
RTC::RtpSender* rtpSender = new RTC::RtpSender(sender_peer, this->notifier, rtpSenderId, rtpReceiver->kind); RTC::RtpSender* rtpSender = new RTC::RtpSender(senderPeer, this->notifier, rtpSenderId,
rtpReceiver->kind);
// Store into the maps. // Store into the maps.
this->mapRtpReceiverRtpSenders[rtpReceiver].insert(rtpSender); this->mapRtpReceiverRtpSenders[rtpReceiver].insert(rtpSender);
this->mapRtpSenderRtpReceiver[rtpSender] = rtpReceiver; this->mapRtpSenderRtpReceiver[rtpSender] = rtpReceiver;
// Attach the RtpSender to sender_peer. // Attach the RtpSender to senderPeer.
sender_peer->AddRtpSender(rtpSender, peer->peerName, rtpReceiver->GetParameters()); senderPeer->AddRtpSender(rtpSender, peer->peerName, rtpReceiver->GetParameters());
} }
} }
// If this is not a new RtpReceiver let's retrieve its updated parameters // If this is not a new RtpReceiver let's retrieve its updated parameters
...@@ -607,7 +618,8 @@ namespace RTC ...@@ -607,7 +618,8 @@ namespace RTC
{ {
MS_TRACE(); MS_TRACE();
MS_ASSERT(this->mapRtpReceiverRtpSenders.find(rtpReceiver) != this->mapRtpReceiverRtpSenders.end(), "RtpReceiver not present in the map"); MS_ASSERT(this->mapRtpReceiverRtpSenders.find(rtpReceiver) !=
this->mapRtpReceiverRtpSenders.end(), "RtpReceiver not present in the map");
auto& rtpSenders = this->mapRtpReceiverRtpSenders[rtpReceiver]; auto& rtpSenders = this->mapRtpReceiverRtpSenders[rtpReceiver];
...@@ -623,7 +635,8 @@ namespace RTC ...@@ -623,7 +635,8 @@ namespace RTC
{ {
MS_TRACE(); MS_TRACE();
MS_ASSERT(this->mapRtpSenderRtpReceiver.find(rtpSender) != this->mapRtpSenderRtpReceiver.end(), "RtpSender not present in the map"); MS_ASSERT(this->mapRtpSenderRtpReceiver.find(rtpSender) !=
this->mapRtpSenderRtpReceiver.end(), "RtpSender not present in the map");
rtpSender->ReceiveRtcpReceiverReport(report); rtpSender->ReceiveRtcpReceiverReport(report);
} }
...@@ -632,7 +645,8 @@ namespace RTC ...@@ -632,7 +645,8 @@ namespace RTC
{ {
MS_TRACE(); MS_TRACE();
MS_ASSERT(this->mapRtpSenderRtpReceiver.find(rtpSender) != this->mapRtpSenderRtpReceiver.end(), "RtpSender not present in the map"); MS_ASSERT(this->mapRtpSenderRtpReceiver.find(rtpSender) !=
this->mapRtpSenderRtpReceiver.end(), "RtpSender not present in the map");
auto& rtpReceiver = this->mapRtpSenderRtpReceiver[rtpSender]; auto& rtpReceiver = this->mapRtpSenderRtpReceiver[rtpSender];
...@@ -643,7 +657,8 @@ namespace RTC ...@@ -643,7 +657,8 @@ namespace RTC
{ {
MS_TRACE(); MS_TRACE();
MS_ASSERT(this->mapRtpSenderRtpReceiver.find(rtpSender) != this->mapRtpSenderRtpReceiver.end(), "RtpSender not present in the map"); MS_ASSERT(this->mapRtpSenderRtpReceiver.find(rtpSender) !=
this->mapRtpSenderRtpReceiver.end(), "RtpSender not present in the map");
auto& rtpReceiver = this->mapRtpSenderRtpReceiver[rtpSender]; auto& rtpReceiver = this->mapRtpSenderRtpReceiver[rtpSender];
...@@ -657,14 +672,16 @@ namespace RTC ...@@ -657,14 +672,16 @@ namespace RTC
// RtpReceiver needs the sender report in order to generate it's receiver report. // RtpReceiver needs the sender report in order to generate it's receiver report.
rtpReceiver->ReceiveRtcpSenderReport(report); rtpReceiver->ReceiveRtcpSenderReport(report);
MS_ASSERT(this->mapRtpReceiverRtpSenders.find(rtpReceiver) != this->mapRtpReceiverRtpSenders.end(), "RtpReceiver not present in the map"); MS_ASSERT(this->mapRtpReceiverRtpSenders.find(rtpReceiver) !=
this->mapRtpReceiverRtpSenders.end(), "RtpReceiver not present in the map");
} }
void Room::onFullFrameRequired(RTC::Peer* peer, RTC::RtpSender* rtpSender) void Room::onFullFrameRequired(RTC::Peer* peer, RTC::RtpSender* rtpSender)
{ {
MS_TRACE(); MS_TRACE();
MS_ASSERT(this->mapRtpSenderRtpReceiver.find(rtpSender) != this->mapRtpSenderRtpReceiver.end(), "RtpSender not present in the map"); MS_ASSERT(this->mapRtpSenderRtpReceiver.find(rtpSender) !=
this->mapRtpSenderRtpReceiver.end(), "RtpSender not present in the map");
auto& rtpReceiver = this->mapRtpSenderRtpReceiver[rtpSender]; auto& rtpReceiver = this->mapRtpSenderRtpReceiver[rtpSender];
......
...@@ -57,6 +57,7 @@ namespace RTC ...@@ -57,6 +57,7 @@ namespace RTC
if (newOldestTime > this->oldestTime + this->windowSize) if (newOldestTime > this->oldestTime + this->windowSize)
{ {
this->Reset(newOldestTime); this->Reset(newOldestTime);
return; return;
} }
...@@ -69,6 +70,7 @@ namespace RTC ...@@ -69,6 +70,7 @@ namespace RTC
if (++this->oldestIndex >= this->windowSize) if (++this->oldestIndex >= this->windowSize)
this->oldestIndex = 0; this->oldestIndex = 0;
++this->oldestTime; ++this->oldestTime;
} }
......
...@@ -18,9 +18,9 @@ namespace RTC ...@@ -18,9 +18,9 @@ namespace RTC
static const Json::StaticString k_ptTable("ptTable"); static const Json::StaticString k_ptTable("ptTable");
Json::Value json(Json::objectValue); Json::Value json(Json::objectValue);
Json::Value json_ssrcTable(Json::objectValue); Json::Value jsonSsrcTable(Json::objectValue);
Json::Value json_muxIdTable(Json::objectValue); Json::Value jsonMuxIdTable(Json::objectValue);
Json::Value json_ptTable(Json::objectValue); Json::Value jsonPtTable(Json::objectValue);
// Add `ssrcTable`. // Add `ssrcTable`.
for (auto& kv : this->ssrcTable) for (auto& kv : this->ssrcTable)
...@@ -28,9 +28,9 @@ namespace RTC ...@@ -28,9 +28,9 @@ namespace RTC
auto ssrc = kv.first; auto ssrc = kv.first;
auto rtpReceiver = kv.second; auto rtpReceiver = kv.second;
json_ssrcTable[std::to_string(ssrc)] = std::to_string(rtpReceiver->rtpReceiverId); jsonSsrcTable[std::to_string(ssrc)] = std::to_string(rtpReceiver->rtpReceiverId);
} }
json[k_ssrcTable] = json_ssrcTable; json[k_ssrcTable] = jsonSsrcTable;
// Add `muxIdTable`. // Add `muxIdTable`.
for (auto& kv : this->muxIdTable) for (auto& kv : this->muxIdTable)
...@@ -38,9 +38,9 @@ namespace RTC ...@@ -38,9 +38,9 @@ namespace RTC
auto muxId = kv.first; auto muxId = kv.first;
auto rtpReceiver = kv.second; auto rtpReceiver = kv.second;
json_muxIdTable[muxId] = std::to_string(rtpReceiver->rtpReceiverId); jsonMuxIdTable[muxId] = std::to_string(rtpReceiver->rtpReceiverId);
} }
json[k_muxIdTable] = json_muxIdTable; json[k_muxIdTable] = jsonMuxIdTable;
// Add `ptTable`. // Add `ptTable`.
for (auto& kv : this->ptTable) for (auto& kv : this->ptTable)
...@@ -48,9 +48,9 @@ namespace RTC ...@@ -48,9 +48,9 @@ namespace RTC
auto payloadType = kv.first; auto payloadType = kv.first;
auto rtpReceiver = kv.second; auto rtpReceiver = kv.second;
json_ptTable[std::to_string(payloadType)] = std::to_string(rtpReceiver->rtpReceiverId); jsonPtTable[std::to_string(payloadType)] = std::to_string(rtpReceiver->rtpReceiverId);
} }
json[k_ptTable] = json_ptTable; json[k_ptTable] = jsonPtTable;
return json; return json;
} }
...@@ -266,18 +266,6 @@ namespace RTC ...@@ -266,18 +266,6 @@ namespace RTC
{ {
MS_TRACE(); MS_TRACE();
// TODO: REMOVE.
// uint8_t* rid_pointer = packet->GetExtensionElementValue(5);
// if (rid_pointer)
// {
// uint8_t rid_length = packet->GetExtensionElementLength(5);
// std::string rid_value = std::string((const char*)rid_pointer, (size_t)rid_length);
// MS_DEBUG_TAG(rtp, "RID [length:%zu, value:'%s', pointer[0]:'%c']", (size_t)rid_length, rid_value.c_str(), (char)rid_pointer[0]);
// if ((char)rid_pointer[0] == '\0')
// MS_WARN_TAG(rtp, "RID data[0] is 0");
// }
// First lookup into the SSRC table. // First lookup into the SSRC table.
{ {
auto it = this->ssrcTable.find(packet->GetSsrc()); auto it = this->ssrcTable.find(packet->GetSsrc());
...@@ -296,7 +284,8 @@ namespace RTC ...@@ -296,7 +284,8 @@ namespace RTC
} }
// RTP PT not present. // RTP PT not present.
MS_WARN_TAG(rtp, "unknown RTP payloadType [payloadType:%" PRIu8 "]", packet->GetPayloadType()); MS_WARN_TAG(rtp, "unknown RTP payloadType [payloadType:%" PRIu8 "]",
packet->GetPayloadType());
// TODO: We may emit "unhandledrtp" event. // TODO: We may emit "unhandledrtp" event.
return nullptr; return nullptr;
...@@ -323,7 +312,7 @@ namespace RTC ...@@ -323,7 +312,7 @@ namespace RTC
} }
} }
// TODO: We may emit 'unhandledrtp' event. // TODO: We may emit "unhandledrtp" event.
return nullptr; return nullptr;
} }
......
...@@ -26,32 +26,34 @@ namespace RTC ...@@ -26,32 +26,34 @@ namespace RTC
ptr += sizeof(Header); ptr += sizeof(Header);
// Check CSRC list. // Check CSRC list.
size_t csrc_list_size = 0; size_t csrcListSize = 0;
if (header->csrc_count) if (header->csrcCount)
{ {
csrc_list_size = header->csrc_count * sizeof(header->ssrc); csrcListSize = header->csrcCount * sizeof(header->ssrc);
// Packet size must be >= header size + CSRC list. // Packet size must be >= header size + CSRC list.
if (len < (ptr - data) + csrc_list_size) if (len < (ptr - data) + csrcListSize)
{ {
MS_WARN_TAG(rtp, "not enough space for the announced CSRC list, packet discarded"); MS_WARN_TAG(rtp,
"not enough space for the announced CSRC list, packet discarded");
return nullptr; return nullptr;
} }
ptr += csrc_list_size; ptr += csrcListSize;
} }
// Check header extension. // Check header extension.
ExtensionHeader* extensionHeader = nullptr; ExtensionHeader* extensionHeader = nullptr;
size_t extension_value_size = 0; size_t extensionValueSize = 0;
if (header->extension) if (header->extension)
{ {
// The extension header is at least 4 bytes. // The extension header is at least 4 bytes.
if (len < size_t(ptr - data) + 4) if (len < size_t(ptr - data) + 4)
{ {
MS_WARN_TAG(rtp, "not enough space for the announced extension header, packet discarded"); MS_WARN_TAG(rtp,
"not enough space for the announced extension header, packet discarded");
return nullptr; return nullptr;
} }
...@@ -60,16 +62,17 @@ namespace RTC ...@@ -60,16 +62,17 @@ namespace RTC
// The header extension contains a 16-bit length field that counts the number of // The header extension contains a 16-bit length field that counts the number of
// 32-bit words in the extension, excluding the four-octet extension header. // 32-bit words in the extension, excluding the four-octet extension header.
extension_value_size = (size_t)(ntohs(extensionHeader->length) * 4); extensionValueSize = (size_t)(ntohs(extensionHeader->length) * 4);
// Packet size must be >= header size + CSRC list + header extension size. // Packet size must be >= header size + CSRC list + header extension size.
if (len < (ptr - data) + 4 + extension_value_size) if (len < (ptr - data) + 4 + extensionValueSize)
{ {
MS_WARN_TAG(rtp, "not enough space for the announced header extension value, packet discarded"); MS_WARN_TAG(rtp,
"not enough space for the announced header extension value, packet discarded");
return nullptr; return nullptr;
} }
ptr += 4 + extension_value_size; ptr += 4 + extensionValueSize;
} }
// Get payload. // Get payload.
...@@ -85,7 +88,8 @@ namespace RTC ...@@ -85,7 +88,8 @@ namespace RTC
// Must be at least a single payload byte. // Must be at least a single payload byte.
if (payloadLength == 0) if (payloadLength == 0)
{ {
MS_WARN_TAG(rtp, "padding bit is set but no space for a padding byte, packet discarded"); MS_WARN_TAG(rtp,
"padding bit is set but no space for a padding byte, packet discarded");
return nullptr; return nullptr;
} }
...@@ -100,7 +104,8 @@ namespace RTC ...@@ -100,7 +104,8 @@ namespace RTC
if (payloadLength < (size_t)payloadPadding) if (payloadLength < (size_t)payloadPadding)
{ {
MS_WARN_TAG(rtp, "number of padding octets is greater than available space for payload, packet discarded"); MS_WARN_TAG(rtp,
"number of padding octets is greater than available space for payload, packet discarded");
return nullptr; return nullptr;
} }
...@@ -110,9 +115,12 @@ namespace RTC ...@@ -110,9 +115,12 @@ namespace RTC
if (payloadLength == 0) if (payloadLength == 0)
payload = nullptr; payload = nullptr;
MS_ASSERT(len == sizeof(Header) + csrc_list_size + (extensionHeader ? 4 + extension_value_size : 0) + payloadLength + (size_t)payloadPadding, "packet's computed size does not match received size"); MS_ASSERT(len == sizeof(Header) + csrcListSize + (extensionHeader ? 4 +
extensionValueSize : 0) + payloadLength + (size_t)payloadPadding,
"packet's computed size does not match received size");
RtpPacket* packet = new RtpPacket(header, extensionHeader, payload, payloadLength, payloadPadding, len); RtpPacket* packet = new RtpPacket(header, extensionHeader, payload, payloadLength,
payloadPadding, len);
// Parse RFC 5285 extension header. // Parse RFC 5285 extension header.
packet->ParseExtensions(); packet->ParseExtensions();
...@@ -132,7 +140,7 @@ namespace RTC ...@@ -132,7 +140,7 @@ namespace RTC
{ {
MS_TRACE(); MS_TRACE();
if (this->header->csrc_count) if (this->header->csrcCount)
this->csrcList = (uint8_t*)header + sizeof(Header); this->csrcList = (uint8_t*)header + sizeof(Header);
} }
...@@ -153,7 +161,7 @@ namespace RTC ...@@ -153,7 +161,7 @@ namespace RTC
MS_DUMP(" id : %" PRIu16, GetExtensionHeaderId()); MS_DUMP(" id : %" PRIu16, GetExtensionHeaderId());
MS_DUMP(" length : %zu bytes", GetExtensionHeaderLength()); MS_DUMP(" length : %zu bytes", GetExtensionHeaderLength());
} }
MS_DUMP(" csrc count : %" PRIu8, this->header->csrc_count); MS_DUMP(" csrc count : %" PRIu8, this->header->csrcCount);
MS_DUMP(" marker : %s", HasMarker() ? "true" : "false"); MS_DUMP(" marker : %s", HasMarker() ? "true" : "false");
MS_DUMP(" payload type : %" PRIu8, GetPayloadType()); MS_DUMP(" payload type : %" PRIu8, GetPayloadType());
MS_DUMP(" sequence number : %" PRIu16, GetSequenceNumber()); MS_DUMP(" sequence number : %" PRIu16, GetSequenceNumber());
...@@ -171,12 +179,12 @@ namespace RTC ...@@ -171,12 +179,12 @@ namespace RTC
this->size = sizeof(Header); // Minimum header. this->size = sizeof(Header); // Minimum header.
if (this->csrcList) if (this->csrcList)
this->size += this->header->csrc_count * sizeof(header->ssrc); this->size += this->header->csrcCount * sizeof(header->ssrc);
size_t extension_value_size = GetExtensionHeaderLength(); size_t extensionValueSize = GetExtensionHeaderLength();
if (this->extensionHeader) if (this->extensionHeader)
this->size += 4 + extension_value_size; this->size += 4 + extensionValueSize;
this->size += this->payloadLength; this->size += this->payloadLength;
this->size += (size_t)this->payloadPadding; this->size += (size_t)this->payloadPadding;
...@@ -193,21 +201,21 @@ namespace RTC ...@@ -193,21 +201,21 @@ namespace RTC
// Add CSRC list. // Add CSRC list.
if (this->csrcList) if (this->csrcList)
{ {
std::memcpy(ptr, this->csrcList, this->header->csrc_count * sizeof(this->header->ssrc)); std::memcpy(ptr, this->csrcList, this->header->csrcCount * sizeof(this->header->ssrc));
// Update the pointer. // Update the pointer.
this->csrcList = ptr; this->csrcList = ptr;
ptr += this->header->csrc_count * sizeof(this->header->ssrc); ptr += this->header->csrcCount * sizeof(this->header->ssrc);
} }
// Add extension header. // Add extension header.
if (this->extensionHeader) if (this->extensionHeader)
{ {
std::memcpy(ptr, this->extensionHeader, 4 + extension_value_size); std::memcpy(ptr, this->extensionHeader, 4 + extensionValueSize);
// Update the header extension pointer. // Update the header extension pointer.
this->extensionHeader = reinterpret_cast<ExtensionHeader*>(ptr); this->extensionHeader = reinterpret_cast<ExtensionHeader*>(ptr);
ptr += 4 + extension_value_size; ptr += 4 + extensionValueSize;
} }
// Parse and regenerate RFC 5285 extension header. // Parse and regenerate RFC 5285 extension header.
...@@ -248,7 +256,7 @@ namespace RTC ...@@ -248,7 +256,7 @@ namespace RTC
// Check CSRC list. // Check CSRC list.
if (this->csrcList) if (this->csrcList)
ptr += header->csrc_count * sizeof(header->ssrc); ptr += header->csrcCount * sizeof(header->ssrc);
// Check extension header. // Check extension header.
ExtensionHeader* extensionHeader = nullptr; ExtensionHeader* extensionHeader = nullptr;
...@@ -280,7 +288,8 @@ namespace RTC ...@@ -280,7 +288,8 @@ namespace RTC
MS_ASSERT(size_t(ptr - buffer) == this->size, "size_t(ptr - buffer) == this->size"); MS_ASSERT(size_t(ptr - buffer) == this->size, "size_t(ptr - buffer) == this->size");
// Create the new RtpPacket instance and return it. // Create the new RtpPacket instance and return it.
RtpPacket* packet = new RtpPacket(header, extensionHeader, payload, this->payloadLength, this->payloadPadding, this->size); RtpPacket* packet = new RtpPacket(header, extensionHeader, payload, this->payloadLength,
this->payloadPadding, this->size);
// Parse RFC 5285 extension header. // Parse RFC 5285 extension header.
packet->ParseExtensions(); packet->ParseExtensions();
...@@ -301,18 +310,19 @@ namespace RTC ...@@ -301,18 +310,19 @@ namespace RTC
// Clear the One-Byte extension elements map. // Clear the One-Byte extension elements map.
this->oneByteExtensions.clear(); this->oneByteExtensions.clear();
uint8_t* extension_start = (uint8_t*)this->extensionHeader + 4; uint8_t* extensionStart = (uint8_t*)this->extensionHeader + 4;
uint8_t* extension_end = extension_start + GetExtensionHeaderLength(); uint8_t* extensionEnd = extensionStart + GetExtensionHeaderLength();
uint8_t* ptr = extension_start; uint8_t* ptr = extensionStart;
while (ptr < extension_end) while (ptr < extensionEnd)
{ {
uint8_t id = (*ptr & 0xF0) >> 4; uint8_t id = (*ptr & 0xF0) >> 4;
size_t len = (*ptr & 0x0F) + 1; size_t len = (*ptr & 0x0F) + 1;
if (ptr + 1 + len > extension_end) if (ptr + 1 + len > extensionEnd)
{ {
MS_WARN_TAG(rtp, "not enough space for the announced One-Byte header extension element value"); MS_WARN_TAG(rtp,
"not enough space for the announced One-Byte header extension element value");
break; break;
} }
...@@ -323,7 +333,7 @@ namespace RTC ...@@ -323,7 +333,7 @@ namespace RTC
ptr += 1 + len; ptr += 1 + len;
// Counting padding bytes. // Counting padding bytes.
while ((ptr < extension_end) && (*ptr == 0)) while ((ptr < extensionEnd) && (*ptr == 0))
++ptr; ++ptr;
} }
} }
...@@ -333,18 +343,19 @@ namespace RTC ...@@ -333,18 +343,19 @@ namespace RTC
// Clear the Two-Bytes extension elements map. // Clear the Two-Bytes extension elements map.
this->twoBytesExtensions.clear(); this->twoBytesExtensions.clear();
uint8_t* extension_start = (uint8_t*)this->extensionHeader + 4; uint8_t* extensionStart = (uint8_t*)this->extensionHeader + 4;
uint8_t* extension_end = extension_start + GetExtensionHeaderLength(); uint8_t* extensionEnd = extensionStart + GetExtensionHeaderLength();
uint8_t* ptr = extension_start; uint8_t* ptr = extensionStart;
while (ptr < extension_end) while (ptr < extensionEnd)
{ {
uint8_t id = *ptr; uint8_t id = *ptr;
size_t len = *(++ptr); size_t len = *(++ptr);
if (ptr + len > extension_end) if (ptr + len > extensionEnd)
{ {
MS_WARN_TAG(rtp, "not enough space for the announced Two-Bytes header extension element value"); MS_WARN_TAG(rtp,
"not enough space for the announced Two-Bytes header extension element value");
break; break;
} }
...@@ -355,7 +366,7 @@ namespace RTC ...@@ -355,7 +366,7 @@ namespace RTC
ptr += len; ptr += len;
// Counting padding bytes. // Counting padding bytes.
while ((ptr < extension_end) && (*ptr == 0)) while ((ptr < extensionEnd) && (*ptr == 0))
++ptr; ++ptr;
} }
} }
......
...@@ -47,11 +47,11 @@ namespace RTC ...@@ -47,11 +47,11 @@ namespace RTC
static const Json::StaticString k_class("class"); static const Json::StaticString k_class("class");
Json::Value event_data(Json::objectValue); Json::Value eventData(Json::objectValue);
// Notify. // Notify.
event_data[k_class] = "RtpReceiver"; eventData[k_class] = "RtpReceiver";
this->notifier->Emit(this->rtpReceiverId, "close", event_data); this->notifier->Emit(this->rtpReceiverId, "close", eventData);
// Notify the listener. // Notify the listener.
this->listener->onRtpReceiverClosed(this); this->listener->onRtpReceiverClosed(this);
...@@ -63,7 +63,6 @@ namespace RTC ...@@ -63,7 +63,6 @@ namespace RTC
{ {
MS_TRACE(); MS_TRACE();
static Json::Value null_data(Json::nullValue);
static const Json::StaticString k_rtpReceiverId("rtpReceiverId"); static const Json::StaticString k_rtpReceiverId("rtpReceiverId");
static const Json::StaticString k_kind("kind"); static const Json::StaticString k_kind("kind");
static const Json::StaticString k_rtpParameters("rtpParameters"); static const Json::StaticString k_rtpParameters("rtpParameters");
...@@ -74,7 +73,7 @@ namespace RTC ...@@ -74,7 +73,7 @@ namespace RTC
static const Json::StaticString k_rtpStream("rtpStream"); static const Json::StaticString k_rtpStream("rtpStream");
Json::Value json(Json::objectValue); Json::Value json(Json::objectValue);
Json::Value json_rtpStreams(Json::arrayValue); Json::Value jsonRtpStreams(Json::arrayValue);
json[k_rtpReceiverId] = (Json::UInt)this->rtpReceiverId; json[k_rtpReceiverId] = (Json::UInt)this->rtpReceiverId;
...@@ -83,7 +82,7 @@ namespace RTC ...@@ -83,7 +82,7 @@ namespace RTC
if (this->rtpParameters) if (this->rtpParameters)
json[k_rtpParameters] = this->rtpParameters->toJson(); json[k_rtpParameters] = this->rtpParameters->toJson();
else else
json[k_rtpParameters] = null_data; json[k_rtpParameters] = Json::nullValue;
json[k_hasTransport] = this->transport ? true : false; json[k_hasTransport] = this->transport ? true : false;
...@@ -95,9 +94,9 @@ namespace RTC ...@@ -95,9 +94,9 @@ namespace RTC
{ {
auto rtpStream = kv.second; auto rtpStream = kv.second;
json_rtpStreams.append(rtpStream->toJson()); jsonRtpStreams.append(rtpStream->toJson());
} }
json[k_rtpStreams] = json_rtpStreams; json[k_rtpStreams] = jsonRtpStreams;
return json; return json;
} }
...@@ -110,9 +109,9 @@ namespace RTC ...@@ -110,9 +109,9 @@ namespace RTC
{ {
case Channel::Request::MethodId::rtpReceiver_close: case Channel::Request::MethodId::rtpReceiver_close:
{ {
#ifdef MS_LOG_DEV #ifdef MS_LOG_DEV
uint32_t rtpReceiverId = this->rtpReceiverId; uint32_t rtpReceiverId = this->rtpReceiverId;
#endif #endif
Destroy(); Destroy();
...@@ -269,30 +268,32 @@ namespace RTC ...@@ -269,30 +268,32 @@ namespace RTC
// Emit "rtpraw" if enabled. // Emit "rtpraw" if enabled.
if (this->rtpRawEventEnabled) if (this->rtpRawEventEnabled)
{ {
Json::Value event_data(Json::objectValue); Json::Value eventData(Json::objectValue);
event_data[k_class] = "RtpReceiver"; eventData[k_class] = "RtpReceiver";
this->notifier->EmitWithBinary(this->rtpReceiverId, "rtpraw", event_data, packet->GetData(), packet->GetSize()); this->notifier->EmitWithBinary(this->rtpReceiverId, "rtpraw", eventData,
packet->GetData(), packet->GetSize());
} }
// Emit "rtpobject" is enabled. // Emit "rtpobject" is enabled.
if (this->rtpObjectEventEnabled) if (this->rtpObjectEventEnabled)
{ {
Json::Value event_data(Json::objectValue); Json::Value eventData(Json::objectValue);
Json::Value json_object(Json::objectValue); Json::Value jsonObject(Json::objectValue);
event_data[k_class] = "RtpReceiver"; eventData[k_class] = "RtpReceiver";
json_object[k_payloadType] = (Json::UInt)packet->GetPayloadType(); jsonObject[k_payloadType] = (Json::UInt)packet->GetPayloadType();
json_object[k_marker] = packet->HasMarker(); jsonObject[k_marker] = packet->HasMarker();
json_object[k_sequenceNumber] = (Json::UInt)packet->GetSequenceNumber(); jsonObject[k_sequenceNumber] = (Json::UInt)packet->GetSequenceNumber();
json_object[k_timestamp] = (Json::UInt)packet->GetTimestamp(); jsonObject[k_timestamp] = (Json::UInt)packet->GetTimestamp();
json_object[k_ssrc] = (Json::UInt)packet->GetSsrc(); jsonObject[k_ssrc] = (Json::UInt)packet->GetSsrc();
event_data[k_object] = json_object; eventData[k_object] = jsonObject;
this->notifier->EmitWithBinary(this->rtpReceiverId, "rtpobject", event_data, packet->GetPayload(), packet->GetPayloadLength()); this->notifier->EmitWithBinary(this->rtpReceiverId, "rtpobject", eventData,
packet->GetPayload(), packet->GetPayloadLength());
} }
} }
...@@ -394,16 +395,19 @@ namespace RTC ...@@ -394,16 +395,19 @@ namespace RTC
if (!useNack && fb.type == "nack") if (!useNack && fb.type == "nack")
{ {
MS_DEBUG_TAG(rtcp, "enabling NACK generation"); MS_DEBUG_TAG(rtcp, "enabling NACK generation");
useNack = true; useNack = true;
} }
if (!usePli && fb.type == "nack" && fb.parameter == "pli") if (!usePli && fb.type == "nack" && fb.parameter == "pli")
{ {
MS_DEBUG_TAG(rtcp, "enabling PLI generation"); MS_DEBUG_TAG(rtcp, "enabling PLI generation");
usePli = true; usePli = true;
} }
else if (!useRemb && fb.type == "goog-remb") else if (!useRemb && fb.type == "goog-remb")
{ {
MS_DEBUG_TAG(rbe, "enabling REMB"); MS_DEBUG_TAG(rbe, "enabling REMB");
useRemb = true; useRemb = true;
} }
} }
...@@ -449,14 +453,14 @@ namespace RTC ...@@ -449,14 +453,14 @@ namespace RTC
this->rtpStreams.clear(); this->rtpStreams.clear();
} }
void RtpReceiver::onNackRequired(RTC::RtpStreamRecv* rtpStream, const std::vector<uint16_t>& seq_numbers) void RtpReceiver::onNackRequired(RTC::RtpStreamRecv* rtpStream, const std::vector<uint16_t>& seqNumbers)
{ {
if (!this->transport) if (!this->transport)
return; return;
RTC::RTCP::FeedbackRtpNackPacket packet(0, rtpStream->GetSsrc()); RTC::RTCP::FeedbackRtpNackPacket packet(0, rtpStream->GetSsrc());
auto it = seq_numbers.begin(); auto it = seqNumbers.begin();
const auto end = seq_numbers.end(); const auto end = seqNumbers.end();
while (it != end) while (it != end)
{ {
......
...@@ -7,14 +7,13 @@ ...@@ -7,14 +7,13 @@
#include "Utils.hpp" #include "Utils.hpp"
#include "MediaSoupError.hpp" #include "MediaSoupError.hpp"
#include "Logger.hpp" #include "Logger.hpp"
#include <unordered_set> #include <vector>
namespace RTC namespace RTC
{ {
/* Class variables. */ /* Static. */
// Can retransmit up to 17 RTP packets. static std::vector<RTC::RtpPacket*> RtpRetransmissionContainer(18);
std::vector<RTC::RtpPacket*> RtpSender::rtpRetransmissionContainer(18);
/* Instance methods. */ /* Instance methods. */
...@@ -49,10 +48,10 @@ namespace RTC ...@@ -49,10 +48,10 @@ namespace RTC
static const Json::StaticString k_class("class"); static const Json::StaticString k_class("class");
Json::Value event_data(Json::objectValue); Json::Value eventData(Json::objectValue);
event_data[k_class] = "RtpSender"; eventData[k_class] = "RtpSender";
this->notifier->Emit(this->rtpSenderId, "close", event_data); this->notifier->Emit(this->rtpSenderId, "close", eventData);
// Notify the listener. // Notify the listener.
this->listener->onRtpSenderClosed(this); this->listener->onRtpSenderClosed(this);
...@@ -64,7 +63,6 @@ namespace RTC ...@@ -64,7 +63,6 @@ namespace RTC
{ {
MS_TRACE(); MS_TRACE();
static Json::Value null_data(Json::nullValue);
static const Json::StaticString k_rtpSenderId("rtpSenderId"); static const Json::StaticString k_rtpSenderId("rtpSenderId");
static const Json::StaticString k_kind("kind"); static const Json::StaticString k_kind("kind");
static const Json::StaticString k_rtpParameters("rtpParameters"); static const Json::StaticString k_rtpParameters("rtpParameters");
...@@ -82,7 +80,7 @@ namespace RTC ...@@ -82,7 +80,7 @@ namespace RTC
if (this->rtpParameters) if (this->rtpParameters)
json[k_rtpParameters] = this->rtpParameters->toJson(); json[k_rtpParameters] = this->rtpParameters->toJson();
else else
json[k_rtpParameters] = null_data; json[k_rtpParameters] = Json::nullValue;
json[k_hasTransport] = this->transport ? true : false; json[k_hasTransport] = this->transport ? true : false;
...@@ -133,6 +131,7 @@ namespace RTC ...@@ -133,6 +131,7 @@ namespace RTC
if (this->disabled == disabled) if (this->disabled == disabled)
{ {
request->Accept(); request->Accept();
return; return;
} }
...@@ -271,13 +270,13 @@ namespace RTC ...@@ -271,13 +270,13 @@ namespace RTC
// Emit "parameterschange" if these are updated parameters. // Emit "parameterschange" if these are updated parameters.
if (hadParameters) if (hadParameters)
{ {
Json::Value event_data(Json::objectValue); Json::Value eventData(Json::objectValue);
event_data[k_class] = "RtpSender"; eventData[k_class] = "RtpSender";
event_data[k_rtpParameters] = this->rtpParameters->toJson(); eventData[k_rtpParameters] = this->rtpParameters->toJson();
event_data[k_active] = this->GetActive(); eventData[k_active] = this->GetActive();
this->notifier->Emit(this->rtpSenderId, "parameterschange", event_data); this->notifier->Emit(this->rtpSenderId, "parameterschange", eventData);
} }
} }
...@@ -295,7 +294,8 @@ namespace RTC ...@@ -295,7 +294,8 @@ namespace RTC
// RTP parameters. // RTP parameters.
if (packet->GetSsrc() != this->rtpParameters->encodings[0].ssrc) if (packet->GetSsrc() != this->rtpParameters->encodings[0].ssrc)
{ {
MS_WARN_TAG(rtp, "ignoring packet with unknown SSRC [ssrc:%" PRIu32 "]", packet->GetSsrc()); MS_WARN_TAG(rtp, "ignoring packet with unknown SSRC [ssrc:%" PRIu32 "]",
packet->GetSsrc());
return; return;
} }
...@@ -348,7 +348,8 @@ namespace RTC ...@@ -348,7 +348,8 @@ namespace RTC
// Build SDES chunk for this sender. // Build SDES chunk for this sender.
RTC::RTCP::SdesChunk *sdesChunk = new RTC::RTCP::SdesChunk(ssrc); RTC::RTCP::SdesChunk *sdesChunk = new RTC::RTCP::SdesChunk(ssrc);
RTC::RTCP::SdesItem *sdesItem = new RTC::RTCP::SdesItem(RTC::RTCP::SdesItem::Type::CNAME, cname.size(), cname.c_str()); RTC::RTCP::SdesItem *sdesItem =
new RTC::RTCP::SdesItem(RTC::RTCP::SdesItem::Type::CNAME, cname.size(), cname.c_str());
sdesChunk->AddItem(sdesItem); sdesChunk->AddItem(sdesItem);
packet->AddSdesChunk(sdesChunk); packet->AddSdesChunk(sdesChunk);
...@@ -371,11 +372,12 @@ namespace RTC ...@@ -371,11 +372,12 @@ namespace RTC
{ {
RTC::RTCP::FeedbackRtpNackItem* item = *it; RTC::RTCP::FeedbackRtpNackItem* item = *it;
this->rtpStream->RequestRtpRetransmission(item->GetPacketId(), item->GetLostPacketBitmask(), RtpSender::rtpRetransmissionContainer); this->rtpStream->RequestRtpRetransmission(item->GetPacketId(), item->GetLostPacketBitmask(), RtpRetransmissionContainer);
for (auto it = RtpSender::rtpRetransmissionContainer.begin(); it != RtpSender::rtpRetransmissionContainer.end(); ++it) auto it2 = RtpRetransmissionContainer.begin();
for (; it2 != RtpRetransmissionContainer.end(); ++it2)
{ {
RTC::RtpPacket* packet = *it; RTC::RtpPacket* packet = *it2;
if (packet == nullptr) if (packet == nullptr)
break; break;
...@@ -415,11 +417,13 @@ namespace RTC ...@@ -415,11 +417,13 @@ namespace RTC
if (!useNack && fb.type == "nack") if (!useNack && fb.type == "nack")
{ {
MS_DEBUG_TAG(rtcp, "enabling NACK reception"); MS_DEBUG_TAG(rtcp, "enabling NACK reception");
useNack = true; useNack = true;
} }
if (!usePli && fb.type == "nack" && fb.parameter == "pli") if (!usePli && fb.type == "nack" && fb.parameter == "pli")
{ {
MS_DEBUG_TAG(rtcp, "enabling PLI reception"); MS_DEBUG_TAG(rtcp, "enabling PLI reception");
usePli = true; usePli = true;
} }
} }
...@@ -475,10 +479,11 @@ namespace RTC ...@@ -475,10 +479,11 @@ namespace RTC
static const Json::StaticString k_class("class"); static const Json::StaticString k_class("class");
static const Json::StaticString k_active("active"); static const Json::StaticString k_active("active");
Json::Value event_data(Json::objectValue); Json::Value eventData(Json::objectValue);
eventData[k_class] = "RtpSender";
eventData[k_active] = this->GetActive();
event_data[k_class] = "RtpSender"; this->notifier->Emit(this->rtpSenderId, "activechange", eventData);
event_data[k_active] = this->GetActive();
this->notifier->Emit(this->rtpSenderId, "activechange", event_data);
} }
} }
...@@ -6,13 +6,15 @@ ...@@ -6,13 +6,15 @@
#include "RTC/RtpStream.hpp" #include "RTC/RtpStream.hpp"
#include "Logger.hpp" #include "Logger.hpp"
#define MIN_SEQUENTIAL 0
#define MAX_DROPOUT 3000
#define MAX_MISORDER 100
#define RTP_SEQ_MOD (1<<16)
namespace RTC namespace RTC
{ {
/* Static. */
static constexpr uint32_t MinSequential = 0;
static constexpr uint16_t MaxDropout = 3000;
static constexpr uint16_t MaxMisorder = 100;
static constexpr uint32_t RtpSeqMod = 1<<16;
/* Instance methods. */ /* Instance methods. */
RtpStream::RtpStream(RTC::RtpStream::Params& params) : RtpStream::RtpStream(RTC::RtpStream::Params& params) :
...@@ -37,8 +39,8 @@ namespace RTC ...@@ -37,8 +39,8 @@ namespace RTC
{ {
InitSeq(seq); InitSeq(seq);
this->started = true; this->started = true;
this->max_seq = seq - 1; this->maxSeq = seq - 1;
this->probation = MIN_SEQUENTIAL; this->probation = MinSequential;
} }
// If not a valid packet ignore it. // If not a valid packet ignore it.
...@@ -59,8 +61,8 @@ namespace RTC ...@@ -59,8 +61,8 @@ namespace RTC
this->cycles + (uint32_t)packet->GetSequenceNumber()); this->cycles + (uint32_t)packet->GetSequenceNumber());
// Update highest seen RTP timestamp. // Update highest seen RTP timestamp.
if (packet->GetTimestamp() > this->max_timestamp) if (packet->GetTimestamp() > this->maxTimestamp)
this->max_timestamp = packet->GetTimestamp(); this->maxTimestamp = packet->GetTimestamp();
return true; return true;
} }
...@@ -70,15 +72,15 @@ namespace RTC ...@@ -70,15 +72,15 @@ namespace RTC
MS_TRACE(); MS_TRACE();
// Initialize/reset RTP counters. // Initialize/reset RTP counters.
this->base_seq = seq; this->baseSeq = seq;
this->max_seq = seq; this->maxSeq = seq;
this->bad_seq = RTP_SEQ_MOD + 1; // So seq == bad_seq is false. this->badSeq = RtpSeqMod + 1; // So seq == badSeq is false.
this->cycles = 0; this->cycles = 0;
this->received = 0; this->received = 0;
this->received_prior = 0; this->receivedPrior = 0;
this->expected_prior = 0; this->expectedPrior = 0;
// Also reset the highest seen RTP timestamp. // Also reset the highest seen RTP timestamp.
this->max_timestamp = 0; this->maxTimestamp = 0;
// Call the onInitSeq method of the child. // Call the onInitSeq method of the child.
onInitSeq(); onInitSeq();
...@@ -89,19 +91,19 @@ namespace RTC ...@@ -89,19 +91,19 @@ namespace RTC
MS_TRACE(); MS_TRACE();
uint16_t seq = packet->GetSequenceNumber(); uint16_t seq = packet->GetSequenceNumber();
uint16_t udelta = seq - this->max_seq; uint16_t udelta = seq - this->maxSeq;
/* /*
* Source is not valid until MIN_SEQUENTIAL packets with * Source is not valid until MinSequential packets with
* sequential sequence numbers have been received. * sequential sequence numbers have been received.
*/ */
if (this->probation) if (this->probation)
{ {
// Packet is in sequence. // Packet is in sequence.
if (seq == this->max_seq + 1) if (seq == this->maxSeq + 1)
{ {
this->probation--; this->probation--;
this->max_seq = seq; this->maxSeq = seq;
if (this->probation == 0) if (this->probation == 0)
{ {
...@@ -113,27 +115,27 @@ namespace RTC ...@@ -113,27 +115,27 @@ namespace RTC
} }
else else
{ {
this->probation = MIN_SEQUENTIAL - 1; this->probation = MinSequential - 1;
this->max_seq = seq; this->maxSeq = seq;
} }
return false; return false;
} }
else if (udelta < MAX_DROPOUT) else if (udelta < MaxDropout)
{ {
// In order, with permissible gap. // In order, with permissible gap.
if (seq < this->max_seq) if (seq < this->maxSeq)
{ {
// Sequence number wrapped: count another 64K cycle. // Sequence number wrapped: count another 64K cycle.
this->cycles += RTP_SEQ_MOD; this->cycles += RtpSeqMod;
} }
this->max_seq = seq; this->maxSeq = seq;
} }
else if (udelta <= RTP_SEQ_MOD - MAX_MISORDER) else if (udelta <= RtpSeqMod - MaxMisorder)
{ {
// The sequence number made a very large jump. // The sequence number made a very large jump.
if (seq == this->bad_seq) if (seq == this->badSeq)
{ {
/* /*
* Two sequential packets -- assume that the other side * Two sequential packets -- assume that the other side
...@@ -152,7 +154,7 @@ namespace RTC ...@@ -152,7 +154,7 @@ namespace RTC
"bad sequence number, ignoring packet [ssrc:%" PRIu32 ", seq:%" PRIu16 "]", "bad sequence number, ignoring packet [ssrc:%" PRIu32 ", seq:%" PRIu16 "]",
packet->GetSsrc(), packet->GetSequenceNumber()); packet->GetSsrc(), packet->GetSequenceNumber());
this->bad_seq = (seq + 1) & (RTP_SEQ_MOD - 1); this->badSeq = (seq + 1) & (RtpSeqMod - 1);
return false; return false;
} }
......
...@@ -35,7 +35,7 @@ namespace RTC ...@@ -35,7 +35,7 @@ namespace RTC
json[k_params] = this->params.toJson(); json[k_params] = this->params.toJson();
json[k_received] = (Json::UInt)this->received; json[k_received] = (Json::UInt)this->received;
json[k_maxTimestamp] = (Json::UInt)this->max_timestamp; json[k_maxTimestamp] = (Json::UInt)this->maxTimestamp;
json[k_transit] = (Json::UInt)this->transit; json[k_transit] = (Json::UInt)this->transit;
json[k_jitter] = (Json::UInt)this->jitter; json[k_jitter] = (Json::UInt)this->jitter;
...@@ -74,45 +74,44 @@ namespace RTC ...@@ -74,45 +74,44 @@ namespace RTC
RTC::RTCP::ReceiverReport* report = new RTC::RTCP::ReceiverReport(); RTC::RTCP::ReceiverReport* report = new RTC::RTCP::ReceiverReport();
// Calculate Packets Expected and Lost. // Calculate Packets Expected and Lost.
uint32_t expected = (this->cycles + this->max_seq) - this->base_seq + 1; uint32_t expected = (this->cycles + this->maxSeq) - this->baseSeq + 1;
int32_t total_lost = expected - this->received; int32_t totalLost = expected - this->received;
report->SetTotalLost(total_lost); report->SetTotalLost(totalLost);
// Calculate Fraction Lost. // Calculate Fraction Lost.
uint32_t expected_interval = expected - this->expected_prior; uint32_t expectedInterval = expected - this->expectedPrior;
this->expected_prior = expected; this->expectedPrior = expected;
uint32_t received_interval = this->received - this->received_prior; uint32_t receivedInterval = this->received - this->receivedPrior;
this->received_prior = this->received; this->receivedPrior = this->received;
int32_t lost_interval = expected_interval - received_interval; int32_t lostInterval = expectedInterval - receivedInterval;
uint8_t fraction_lost; uint8_t fractionLost;
if (expected_interval == 0 || lost_interval <= 0) if (expectedInterval == 0 || lostInterval <= 0)
fraction_lost = 0; fractionLost = 0;
else else
fraction_lost = (lost_interval << 8) / expected_interval; fractionLost = (lostInterval << 8) / expectedInterval;
report->SetFractionLost(fraction_lost); report->SetFractionLost(fractionLost);
// Fill the rest of the report. // Fill the rest of the report.
report->SetLastSeq((uint32_t)this->max_seq + this->cycles); report->SetLastSeq((uint32_t)this->maxSeq + this->cycles);
report->SetJitter(this->jitter); report->SetJitter(this->jitter);
if (this->last_sr_received) if (this->lastSrReceived)
{ {
// Get delay in milliseconds. // Get delay in milliseconds.
uint32_t delayMs = (DepLibUV::GetTime() - this->last_sr_received); uint32_t delayMs = (DepLibUV::GetTime() - this->lastSrReceived);
// Express delay in units of 1/65536 seconds. // Express delay in units of 1/65536 seconds.
uint32_t dlsr = (delayMs / 1000) << 16; uint32_t dlsr = (delayMs / 1000) << 16;
dlsr |= (uint32_t)((delayMs % 1000) * 65536 / 1000);
dlsr |= (uint32_t)((delayMs % 1000) * 65536 / 1000);
report->SetDelaySinceLastSenderReport(dlsr); report->SetDelaySinceLastSenderReport(dlsr);
report->SetLastSenderReport(this->last_sr_timestamp); report->SetLastSenderReport(this->lastSrTimestamp);
} }
else else
{ {
...@@ -127,9 +126,9 @@ namespace RTC ...@@ -127,9 +126,9 @@ namespace RTC
{ {
MS_TRACE(); MS_TRACE();
this->last_sr_received = DepLibUV::GetTime(); this->lastSrReceived = DepLibUV::GetTime();
this->last_sr_timestamp = report->GetNtpSec() << 16; this->lastSrTimestamp = report->GetNtpSec() << 16;
this->last_sr_timestamp += report->GetNtpFrac() >> 16; this->lastSrTimestamp += report->GetNtpFrac() >> 16;
} }
void RtpStreamRecv::RequestFullFrame() void RtpStreamRecv::RequestFullFrame()
...@@ -172,14 +171,13 @@ namespace RTC ...@@ -172,14 +171,13 @@ namespace RTC
// If we got out of sync, request a full frame. // If we got out of sync, request a full frame.
if (this->started && this->params.usePli) if (this->started && this->params.usePli)
{ {
MS_DEBUG_TAG(rtx, "triggering PLI [ssrc:%" PRIu32 "]", MS_DEBUG_TAG(rtx, "triggering PLI [ssrc:%" PRIu32 "]", this->params.ssrc);
this->params.ssrc);
this->listener->onPliRequired(this); this->listener->onPliRequired(this);
} }
} }
void RtpStreamRecv::onNackRequired(const std::vector<uint16_t>& seq_numbers) void RtpStreamRecv::onNackRequired(const std::vector<uint16_t>& seqNumbers)
{ {
MS_TRACE(); MS_TRACE();
...@@ -187,9 +185,9 @@ namespace RTC ...@@ -187,9 +185,9 @@ namespace RTC
MS_WARN_TAG(rtx, MS_WARN_TAG(rtx,
"triggering NACK [ssrc:%" PRIu32 ", first_seq:%" PRIu16 ", num_packets:%zu]", "triggering NACK [ssrc:%" PRIu32 ", first_seq:%" PRIu16 ", num_packets:%zu]",
this->params.ssrc, seq_numbers[0], seq_numbers.size()); this->params.ssrc, seqNumbers[0], seqNumbers.size());
this->listener->onNackRequired(this, seq_numbers); this->listener->onNackRequired(this, seqNumbers);
} }
void RtpStreamRecv::onFullFrameRequired() void RtpStreamRecv::onFullFrameRequired()
...@@ -203,8 +201,7 @@ namespace RTC ...@@ -203,8 +201,7 @@ namespace RTC
return; return;
} }
MS_DEBUG_TAG(rtx, MS_DEBUG_TAG(rtx, "triggering PLI [ssrc:%" PRIu32 "]", this->params.ssrc);
"triggering PLI [ssrc:%" PRIu32 "]", this->params.ssrc);
this->listener->onPliRequired(this); this->listener->onPliRequired(this);
} }
......
...@@ -6,12 +6,15 @@ ...@@ -6,12 +6,15 @@
#include "DepLibUV.hpp" #include "DepLibUV.hpp"
#include "Utils.hpp" #include "Utils.hpp"
#define RTP_SEQ_MOD (1<<16)
#define MAX_RETRANSMISSION_AGE 500 // Don't retransmit packets older than this (ms).
#define DEFAULT_RTT 100 // Default RTT if not set (in ms).
namespace RTC namespace RTC
{ {
/* Static. */
static constexpr uint32_t RtpSeqMod = 1<<16;
// Don't retransmit packets older than this (ms).
static constexpr uint32_t MaxRetransmissionAge = 500;
static constexpr uint32_t DefaultRtt = 100;
/* Instance methods. */ /* Instance methods. */
RtpStreamSend::RtpStreamSend(RTC::RtpStream::Params& params, size_t bufferSize) : RtpStreamSend::RtpStreamSend(RTC::RtpStream::Params& params, size_t bufferSize) :
...@@ -43,7 +46,7 @@ namespace RTC ...@@ -43,7 +46,7 @@ namespace RTC
json[k_params] = this->params.toJson(); json[k_params] = this->params.toJson();
json[k_received] = (Json::UInt)this->received; json[k_received] = (Json::UInt)this->received;
json[k_maxTimestamp] = (Json::UInt)this->max_timestamp; json[k_maxTimestamp] = (Json::UInt)this->maxTimestamp;
json[k_receivedBytes] = (Json::UInt)this->receivedBytes; json[k_receivedBytes] = (Json::UInt)this->receivedBytes;
json[k_rtt] = (Json::UInt)this->rtt; json[k_rtt] = (Json::UInt)this->rtt;
...@@ -103,7 +106,7 @@ namespace RTC ...@@ -103,7 +106,7 @@ namespace RTC
MS_TRACE(); MS_TRACE();
// 17: 16 bit mask + the initial sequence number. // 17: 16 bit mask + the initial sequence number.
static size_t maxRequestedPackets = 17; static constexpr size_t MaxRequestedPackets = 17;
// Ensure the container's first element is 0. // Ensure the container's first element is 0.
container[0] = nullptr; container[0] = nullptr;
...@@ -121,28 +124,28 @@ namespace RTC ...@@ -121,28 +124,28 @@ namespace RTC
return; return;
// Convert the given sequence numbers to 32 bits. // Convert the given sequence numbers to 32 bits.
uint32_t first_seq32 = (uint32_t)seq + this->cycles; uint32_t firstSeq32 = (uint32_t)seq + this->cycles;
uint32_t last_seq32 = first_seq32 + maxRequestedPackets - 1; uint32_t lastSeq32 = firstSeq32 + MaxRequestedPackets - 1;
// Number of requested packets cannot be greater than the container size - 1. // Number of requested packets cannot be greater than the container size - 1.
MS_ASSERT(container.size() - 1 >= maxRequestedPackets, "RtpPacket container is too small"); MS_ASSERT(container.size() - 1 >= MaxRequestedPackets, "RtpPacket container is too small");
auto buffer_it = this->buffer.begin(); auto bufferIt = this->buffer.begin();
auto buffer_it_r = this->buffer.rbegin(); auto bufferItReverse = this->buffer.rbegin();
uint32_t buffer_first_seq32 = (*buffer_it).seq32; uint32_t bufferFirstSeq32 = (*bufferIt).seq32;
uint32_t buffer_last_seq32 = (*buffer_it_r).seq32; uint32_t bufferLastSeq32 = (*bufferItReverse).seq32;
// Requested packet range not found. // Requested packet range not found.
if (first_seq32 > buffer_last_seq32 || last_seq32 < buffer_first_seq32) if (firstSeq32 > bufferLastSeq32 || lastSeq32 < bufferFirstSeq32)
{ {
// Let's try with sequence numbers in the previous 16 cycle. // Let's try with sequence numbers in the previous 16 cycle.
if (this->cycles > 0) if (this->cycles > 0)
{ {
first_seq32 -= RTP_SEQ_MOD; firstSeq32 -= RtpSeqMod;
last_seq32 -= RTP_SEQ_MOD; lastSeq32 -= RtpSeqMod;
// Try again. // Try again.
if (first_seq32 > buffer_last_seq32 || last_seq32 < buffer_first_seq32) if (firstSeq32 > bufferLastSeq32 || lastSeq32 < bufferFirstSeq32)
{ {
MS_WARN_TAG(rtx, "requested packet range not in the buffer"); MS_WARN_TAG(rtx, "requested packet range not in the buffer");
...@@ -160,18 +163,18 @@ namespace RTC ...@@ -160,18 +163,18 @@ namespace RTC
// Look for each requested packet. // Look for each requested packet.
uint64_t now = DepLibUV::GetTime(); uint64_t now = DepLibUV::GetTime();
uint32_t rtt = (this->rtt ? this->rtt : DEFAULT_RTT); uint32_t rtt = (this->rtt ? this->rtt : DefaultRtt);
uint32_t seq32 = first_seq32; uint32_t seq32 = firstSeq32;
bool requested = true; bool requested = true;
size_t container_idx = 0; size_t containerIdx = 0;
// Some variables for debugging. // Some variables for debugging.
uint16_t orig_bitmask = bitmask; uint16_t origBitmask = bitmask;
uint16_t sent_bitmask = 0b0000000000000000; uint16_t sentBitmask = 0b0000000000000000;
bool is_first_packet = true; bool isFirstPacket = true;
bool first_packet_sent = false; bool firstPacketSent = false;
uint8_t bitmask_counter = 0; uint8_t bitmaskCounter = 0;
bool too_old_packet_found = false; bool tooOldPacketFound = false;
while (requested || bitmask != 0) while (requested || bitmask != 0)
{ {
...@@ -179,59 +182,59 @@ namespace RTC ...@@ -179,59 +182,59 @@ namespace RTC
if (requested) if (requested)
{ {
for (; buffer_it != this->buffer.end(); ++buffer_it) for (; bufferIt != this->buffer.end(); ++bufferIt)
{ {
auto current_seq32 = (*buffer_it).seq32; auto currentSeq32 = (*bufferIt).seq32;
// Found. // Found.
if (current_seq32 == seq32) if (currentSeq32 == seq32)
{ {
auto current_packet = (*buffer_it).packet; auto currentPacket = (*bufferIt).packet;
uint32_t diff = (this->max_timestamp - current_packet->GetTimestamp()) * 1000 / this->params.clockRate; uint32_t diff = (this->maxTimestamp - currentPacket->GetTimestamp()) * 1000 / this->params.clockRate;
// Just provide the packet if no older than MAX_RETRANSMISSION_AGE ms. // Just provide the packet if no older than MaxRetransmissionAge ms.
if (diff > MAX_RETRANSMISSION_AGE) if (diff > MaxRetransmissionAge)
{ {
if (!too_old_packet_found) if (!tooOldPacketFound)
{ {
MS_WARN_TAG(rtx, MS_WARN_TAG(rtx,
"ignoring retransmission for too old packet [seq:%" PRIu16 ", max_age:%" PRIu32 "ms, packet_age:%" PRIu32 "ms]", "ignoring retransmission for too old packet [seq:%" PRIu16 ", max_age:%" PRIu32 "ms, packet_age:%" PRIu32 "ms]",
current_packet->GetSequenceNumber(), MAX_RETRANSMISSION_AGE, diff); currentPacket->GetSequenceNumber(), MaxRetransmissionAge, diff);
too_old_packet_found = true; tooOldPacketFound = true;
} }
break; break;
} }
// Don't resent the packet if it was resent in the last RTT ms. // Don't resent the packet if it was resent in the last RTT ms.
uint32_t resent_at_time = (*buffer_it).resent_at_time; uint32_t resentAtTime = (*bufferIt).resentAtTime;
if ( if (
resent_at_time && resentAtTime &&
now - resent_at_time < static_cast<uint64_t>(rtt)) now - resentAtTime < static_cast<uint64_t>(rtt))
{ {
MS_WARN_TAG(rtx, MS_WARN_TAG(rtx,
"ignoring retransmission for a packet already resent in the last RTT ms [seq:%" PRIu16 ", rtt:%" PRIu32 "]", "ignoring retransmission for a packet already resent in the last RTT ms [seq:%" PRIu16 ", rtt:%" PRIu32 "]",
current_packet->GetSequenceNumber(), rtt); currentPacket->GetSequenceNumber(), rtt);
break; break;
} }
// Store the packet in the container and then increment its index. // Store the packet in the container and then increment its index.
container[container_idx++] = current_packet; container[containerIdx++] = currentPacket;
// Save when this packet was resent. // Save when this packet was resent.
(*buffer_it).resent_at_time = now; (*bufferIt).resentAtTime = now;
sent = true; sent = true;
if (is_first_packet) if (isFirstPacket)
first_packet_sent = true; firstPacketSent = true;
break; break;
} }
// It can not be after this packet. // It can not be after this packet.
else if (current_seq32 > seq32) else if (currentSeq32 > seq32)
{ {
break; break;
} }
...@@ -242,32 +245,35 @@ namespace RTC ...@@ -242,32 +245,35 @@ namespace RTC
bitmask >>= 1; bitmask >>= 1;
++seq32; ++seq32;
if (!is_first_packet) if (!isFirstPacket)
{ {
sent_bitmask |= (sent ? 1 : 0) << bitmask_counter; sentBitmask |= (sent ? 1 : 0) << bitmaskCounter;
++bitmask_counter; ++bitmaskCounter;
} }
else else
{ {
is_first_packet = false; isFirstPacket = false;
} }
} }
// If not all the requested packets was sent, log it. // If not all the requested packets was sent, log it.
if (!first_packet_sent || orig_bitmask != sent_bitmask) if (!firstPacketSent || origBitmask != sentBitmask)
{ {
MS_DEBUG_TAG(rtx, "could not resend all packets [seq:%" PRIu16 ", first:%s, bitmask:" MS_UINT16_TO_BINARY_PATTERN ", sent_bitmask:" MS_UINT16_TO_BINARY_PATTERN "]", MS_DEBUG_TAG(rtx,
seq, first_packet_sent ? "yes" : "no", "could not resend all packets [seq:%" PRIu16 ", first:%s, "
MS_UINT16_TO_BINARY(orig_bitmask), MS_UINT16_TO_BINARY(sent_bitmask)); "bitmask:" MS_UINT16_TO_BINARY_PATTERN ", sentBitmask:" MS_UINT16_TO_BINARY_PATTERN "]",
seq, firstPacketSent ? "yes" : "no",
MS_UINT16_TO_BINARY(origBitmask), MS_UINT16_TO_BINARY(sentBitmask));
} }
else else
{ {
MS_DEBUG_TAG(rtx, "all packets resent [seq:%" PRIu16 ", bitmask:" MS_UINT16_TO_BINARY_PATTERN "]", MS_DEBUG_TAG(rtx,
seq, MS_UINT16_TO_BINARY(orig_bitmask)); "all packets resent [seq:%" PRIu16 ", bitmask:" MS_UINT16_TO_BINARY_PATTERN "]",
seq, MS_UINT16_TO_BINARY(origBitmask));
} }
// Set the next container element to null. // Set the next container element to null.
container[container_idx] = nullptr; container[containerIdx] = nullptr;
} }
RTC::RTCP::SenderReport* RtpStreamSend::GetRtcpSenderReport(uint64_t now) RTC::RTCP::SenderReport* RtpStreamSend::GetRtcpSenderReport(uint64_t now)
...@@ -302,9 +308,9 @@ namespace RTC ...@@ -302,9 +308,9 @@ namespace RTC
MS_TRACE(); MS_TRACE();
// Delete cloned packets. // Delete cloned packets.
for (auto& buffer_item : this->buffer) for (auto& bufferItem : this->buffer)
{ {
delete buffer_item.packet; delete bufferItem.packet;
} }
// Clear list. // Clear list.
...@@ -317,40 +323,40 @@ namespace RTC ...@@ -317,40 +323,40 @@ namespace RTC
MS_TRACE(); MS_TRACE();
// Sum the packet seq number and the number of 16 bits cycles. // Sum the packet seq number and the number of 16 bits cycles.
uint32_t packet_seq32 = (uint32_t)packet->GetSequenceNumber() + this->cycles; uint32_t packetSeq32 = (uint32_t)packet->GetSequenceNumber() + this->cycles;
BufferItem buffer_item; BufferItem bufferItem;
buffer_item.seq32 = packet_seq32; bufferItem.seq32 = packetSeq32;
// If empty do it easy. // If empty do it easy.
if (this->buffer.size() == 0) if (this->buffer.size() == 0)
{ {
auto store = this->storage[0].store; auto store = this->storage[0].store;
buffer_item.packet = packet->Clone(store); bufferItem.packet = packet->Clone(store);
this->buffer.push_back(buffer_item); this->buffer.push_back(bufferItem);
return; return;
} }
// Otherwise, do the stuff. // Otherwise, do the stuff.
Buffer::iterator new_buffer_it; Buffer::iterator newBufferIt;
uint8_t* store = nullptr; uint8_t* store = nullptr;
// Iterate the buffer in reverse order and find the proper place to store the // Iterate the buffer in reverse order and find the proper place to store the
// packet. // packet.
auto buffer_it_r = this->buffer.rbegin(); auto bufferItReverse = this->buffer.rbegin();
for (; buffer_it_r != this->buffer.rend(); ++buffer_it_r) for (; bufferItReverse != this->buffer.rend(); ++bufferItReverse)
{ {
auto current_seq32 = (*buffer_it_r).seq32; auto currentSeq32 = (*bufferItReverse).seq32;
if (packet_seq32 > current_seq32) if (packetSeq32 > currentSeq32)
{ {
// Get a forward iterator pointing to the same element. // Get a forward iterator pointing to the same element.
auto it = buffer_it_r.base(); auto it = bufferItReverse.base();
new_buffer_it = this->buffer.insert(it, buffer_item); newBufferIt = this->buffer.insert(it, bufferItem);
// Exit the loop. // Exit the loop.
break; break;
...@@ -358,9 +364,11 @@ namespace RTC ...@@ -358,9 +364,11 @@ namespace RTC
} }
// If the packet was older than anything in the buffer, just ignore it. // If the packet was older than anything in the buffer, just ignore it.
// NOTE: This should never happen. // NOTE: This should never happen.
if (buffer_it_r == this->buffer.rend()) if (bufferItReverse == this->buffer.rend())
{ {
MS_WARN_TAG(rtp, "ignoring packet older than anything in the buffer [ssrc:%" PRIu32 ", seq:%" PRIu16 "]", packet->GetSsrc(), packet->GetSequenceNumber()); MS_WARN_TAG(rtp,
"ignoring packet older than anything in the buffer [ssrc:%" PRIu32 ", seq:%" PRIu16 "]",
packet->GetSsrc(), packet->GetSequenceNumber());
return; return;
} }
...@@ -373,19 +381,19 @@ namespace RTC ...@@ -373,19 +381,19 @@ namespace RTC
// Otherwise remove the first packet of the buffer and replace its storage area. // Otherwise remove the first packet of the buffer and replace its storage area.
else else
{ {
auto& first_buffer_item = *(this->buffer.begin()); auto& firstBufferItem = *(this->buffer.begin());
auto first_packet = first_buffer_item.packet; auto firstPacket = firstBufferItem.packet;
// Store points to the store used by the first packet. // Store points to the store used by the first packet.
store = (uint8_t*)first_packet->GetData(); store = (uint8_t*)firstPacket->GetData();
// Free the first packet. // Free the first packet.
delete first_packet; delete firstPacket;
// Remove the first element in the list. // Remove the first element in the list.
this->buffer.pop_front(); this->buffer.pop_front();
} }
// Update the new buffer item so it points to the cloned packed. // Update the new buffer item so it points to the cloned packed.
(*new_buffer_it).packet = packet->Clone(store); (*newBufferIt).packet = packet->Clone(store);
} }
void RtpStreamSend::onInitSeq() void RtpStreamSend::onInitSeq()
......
...@@ -11,9 +11,10 @@ ...@@ -11,9 +11,10 @@
namespace RTC namespace RTC
{ {
/* Class variables. */ /* Static. */
uint8_t SrtpSession::encryptBuffer[MS_ENCRYPT_BUFFER_SIZE]; static constexpr size_t EncryptBufferSize = 65536;
static uint8_t EncryptBuffer[EncryptBufferSize];
/* Class methods. */ /* Class methods. */
...@@ -51,7 +52,7 @@ namespace RTC ...@@ -51,7 +52,7 @@ namespace RTC
/* Instance methods. */ /* Instance methods. */
SrtpSession::SrtpSession(Type type, Profile profile, uint8_t* key, size_t key_len) SrtpSession::SrtpSession(Type type, Profile profile, uint8_t* key, size_t keyLen)
{ {
MS_TRACE(); MS_TRACE();
...@@ -75,7 +76,8 @@ namespace RTC ...@@ -75,7 +76,8 @@ namespace RTC
MS_ABORT("unknown SRTP suite"); MS_ABORT("unknown SRTP suite");
} }
MS_ASSERT((int)key_len == policy.rtp.cipher_key_len, "given key_len does not match policy.rtp.cipher_key_len"); MS_ASSERT((int)keyLen == policy.rtp.cipher_key_len,
"given keyLen does not match policy.rtp.cipher_keyLen");
switch (type) switch (type)
{ {
...@@ -91,7 +93,7 @@ namespace RTC ...@@ -91,7 +93,7 @@ namespace RTC
policy.key = key; policy.key = key;
// Required for sending RTP retransmission without RTX. // Required for sending RTP retransmission without RTX.
policy.allow_repeat_tx = 1; policy.allow_repeat_tx = 1;
policy.window_size = 4096; policy.window_size = 2048;
policy.next = nullptr; policy.next = nullptr;
// Set the SRTP session. // Set the SRTP session.
...@@ -133,11 +135,11 @@ namespace RTC ...@@ -133,11 +135,11 @@ namespace RTC
return false; return false;
} }
std::memcpy(SrtpSession::encryptBuffer, *data, *len); std::memcpy(EncryptBuffer, *data, *len);
srtp_err_status_t err; srtp_err_status_t err;
err = srtp_protect(this->session, (void*)SrtpSession::encryptBuffer, (int*)len); err = srtp_protect(this->session, (void*)EncryptBuffer, (int*)len);
if (DepLibSRTP::IsError(err)) if (DepLibSRTP::IsError(err))
{ {
MS_WARN_TAG(srtp, "srtp_protect() failed: %s", DepLibSRTP::GetErrorString(err)); MS_WARN_TAG(srtp, "srtp_protect() failed: %s", DepLibSRTP::GetErrorString(err));
...@@ -146,7 +148,7 @@ namespace RTC ...@@ -146,7 +148,7 @@ namespace RTC
} }
// Update the given data pointer. // Update the given data pointer.
*data = (const uint8_t*)SrtpSession::encryptBuffer; *data = (const uint8_t*)EncryptBuffer;
return true; return true;
} }
...@@ -180,11 +182,11 @@ namespace RTC ...@@ -180,11 +182,11 @@ namespace RTC
return false; return false;
} }
std::memcpy(SrtpSession::encryptBuffer, *data, *len); std::memcpy(EncryptBuffer, *data, *len);
srtp_err_status_t err; srtp_err_status_t err;
err = srtp_protect_rtcp(this->session, (void*)SrtpSession::encryptBuffer, (int*)len); err = srtp_protect_rtcp(this->session, (void*)EncryptBuffer, (int*)len);
if (DepLibSRTP::IsError(err)) if (DepLibSRTP::IsError(err))
{ {
MS_WARN_TAG(srtp, "srtp_protect_rtcp() failed: %s", DepLibSRTP::GetErrorString(err)); MS_WARN_TAG(srtp, "srtp_protect_rtcp() failed: %s", DepLibSRTP::GetErrorString(err));
...@@ -193,7 +195,7 @@ namespace RTC ...@@ -193,7 +195,7 @@ namespace RTC
} }
// Update the given data pointer. // Update the given data pointer.
*data = (const uint8_t*)SrtpSession::encryptBuffer; *data = (const uint8_t*)EncryptBuffer;
return true; return true;
} }
......
...@@ -42,27 +42,29 @@ namespace RTC ...@@ -42,27 +42,29 @@ namespace RTC
*/ */
// Get type field. // Get type field.
uint16_t msg_type = Utils::Byte::Get2Bytes(data, 0); uint16_t msgType = Utils::Byte::Get2Bytes(data, 0);
// Get length field. // Get length field.
uint16_t msg_length = Utils::Byte::Get2Bytes(data, 2); uint16_t msgLength = Utils::Byte::Get2Bytes(data, 2);
// length field must be total size minus header's 20 bytes, and must be multiple of 4 Bytes. // length field must be total size minus header's 20 bytes, and must be multiple of 4 Bytes.
if (((size_t)msg_length != len - 20) || (msg_length & 0x03)) if (((size_t)msgLength != len - 20) || (msgLength & 0x03))
{ {
MS_WARN_TAG(ice, "length field + 20 does not match total size (or it is not multiple of 4 bytes), message discarded"); MS_WARN_TAG(ice,
"length field + 20 does not match total size (or it is not multiple of 4 bytes), "
"message discarded");
return nullptr; return nullptr;
} }
// Get STUN method. // Get STUN method.
uint16_t msg_method = (msg_type & 0x000f) | ((msg_type & 0x00e0)>>1) | ((msg_type & 0x3E00)>>2); uint16_t msgMethod = (msgType & 0x000f) | ((msgType & 0x00e0)>>1) | ((msgType & 0x3E00)>>2);
// Get STUN class. // Get STUN class.
uint16_t msg_class = ((data[0] & 0x01) << 1) | ((data[1] & 0x10) >> 4); uint16_t msgClass = ((data[0] & 0x01) << 1) | ((data[1] & 0x10) >> 4);
// Create a new StunMessage (data + 8 points to the received TransactionID field). // Create a new StunMessage (data + 8 points to the received TransactionID field).
StunMessage* msg = new StunMessage((Class)msg_class, (Method)msg_method, data + 8, data, len); StunMessage* msg = new StunMessage((Class)msgClass, (Method)msgMethod, data + 8, data, len);
/* /*
STUN Attributes STUN Attributes
...@@ -86,22 +88,22 @@ namespace RTC ...@@ -86,22 +88,22 @@ namespace RTC
size_t pos = 20; size_t pos = 20;
// Flags (positions) for special MESSAGE-INTEGRITY and FINGERPRINT attributes. // Flags (positions) for special MESSAGE-INTEGRITY and FINGERPRINT attributes.
bool has_message_integrity = false; bool hasMessageIntegrity = false;
bool has_fingerprint = false; bool hasFingerprint = false;
size_t fingerprint_attr_pos; // Will point to the beginning of the attribute. size_t fingerprintAttrPos; // Will point to the beginning of the attribute.
uint32_t fingerprint; // Holds the value of the FINGERPRINT attribute. uint32_t fingerprint; // Holds the value of the FINGERPRINT attribute.
// Ensure there are at least 4 remaining bytes (attribute with 0 length). // Ensure there are at least 4 remaining bytes (attribute with 0 length).
while (pos + 4 <= len) while (pos + 4 <= len)
{ {
// Get the attribute type. // Get the attribute type.
Attribute attr_type = (Attribute)Utils::Byte::Get2Bytes(data, pos); Attribute attrType = (Attribute)Utils::Byte::Get2Bytes(data, pos);
// Get the attribute length. // Get the attribute length.
uint16_t attr_length = Utils::Byte::Get2Bytes(data, pos + 2); uint16_t attrLength = Utils::Byte::Get2Bytes(data, pos + 2);
// Ensure the attribute length is not greater than the remaining size. // Ensure the attribute length is not greater than the remaining size.
if ((pos + 4 + attr_length) > len) if ((pos + 4 + attrLength) > len)
{ {
MS_WARN_TAG(ice, "the attribute length exceeds the remaining size, message discarded"); MS_WARN_TAG(ice, "the attribute length exceeds the remaining size, message discarded");
...@@ -110,7 +112,7 @@ namespace RTC ...@@ -110,7 +112,7 @@ namespace RTC
} }
// FINGERPRINT must be the last attribute. // FINGERPRINT must be the last attribute.
if (has_fingerprint) if (hasFingerprint)
{ {
MS_WARN_TAG(ice, "attribute after FINGERPRINT is not allowed, message discarded"); MS_WARN_TAG(ice, "attribute after FINGERPRINT is not allowed, message discarded");
...@@ -119,39 +121,41 @@ namespace RTC ...@@ -119,39 +121,41 @@ namespace RTC
} }
// After a MESSAGE-INTEGRITY attribute just FINGERPRINT is allowed. // After a MESSAGE-INTEGRITY attribute just FINGERPRINT is allowed.
if (has_message_integrity && attr_type != Attribute::Fingerprint) if (hasMessageIntegrity && attrType != Attribute::Fingerprint)
{ {
MS_WARN_TAG(ice, "attribute after MESSAGE_INTEGRITY other than FINGERPRINT is not allowed, message discarded"); MS_WARN_TAG(ice,
"attribute after MESSAGE_INTEGRITY other than FINGERPRINT is not allowed, "
"message discarded");
delete msg; delete msg;
return nullptr; return nullptr;
} }
const uint8_t* attr_value_pos = data + pos + 4; const uint8_t* attrValuePos = data + pos + 4;
switch (attr_type) switch (attrType)
{ {
case Attribute::Username: case Attribute::Username:
{ {
msg->SetUsername((const char*)attr_value_pos, (size_t)attr_length); msg->SetUsername((const char*)attrValuePos, (size_t)attrLength);
break; break;
} }
case Attribute::Priority: case Attribute::Priority:
{ {
msg->SetPriority(Utils::Byte::Get4Bytes(attr_value_pos, 0)); msg->SetPriority(Utils::Byte::Get4Bytes(attrValuePos, 0));
break; break;
} }
case Attribute::IceControlling: case Attribute::IceControlling:
{ {
msg->SetIceControlling(Utils::Byte::Get8Bytes(attr_value_pos, 0)); msg->SetIceControlling(Utils::Byte::Get8Bytes(attrValuePos, 0));
break; break;
} }
case Attribute::IceControlled: case Attribute::IceControlled:
{ {
msg->SetIceControlled(Utils::Byte::Get8Bytes(attr_value_pos, 0)); msg->SetIceControlled(Utils::Byte::Get8Bytes(attrValuePos, 0));
break; break;
} }
...@@ -163,26 +167,27 @@ namespace RTC ...@@ -163,26 +167,27 @@ namespace RTC
} }
case Attribute::MessageIntegrity: case Attribute::MessageIntegrity:
{ {
has_message_integrity = true; hasMessageIntegrity = true;
msg->SetMessageIntegrity(attr_value_pos); msg->SetMessageIntegrity(attrValuePos);
break; break;
} }
case Attribute::Fingerprint: case Attribute::Fingerprint:
{ {
has_fingerprint = true; hasFingerprint = true;
fingerprint_attr_pos = pos; fingerprintAttrPos = pos;
fingerprint = Utils::Byte::Get4Bytes(attr_value_pos, 0); fingerprint = Utils::Byte::Get4Bytes(attrValuePos, 0);
msg->SetFingerprint(); msg->SetFingerprint();
break; break;
} }
case Attribute::ErrorCode: case Attribute::ErrorCode:
{ {
uint8_t error_class = Utils::Byte::Get1Byte(attr_value_pos, 2); uint8_t errorClass = Utils::Byte::Get1Byte(attrValuePos, 2);
uint8_t error_number = Utils::Byte::Get1Byte(attr_value_pos, 3); uint8_t errorNumber = Utils::Byte::Get1Byte(attrValuePos, 3);
uint16_t error_code = (uint16_t)(error_class * 100 + error_number); uint16_t errorCode = (uint16_t)(errorClass * 100 + errorNumber);
msg->SetErrorCode(error_code);
msg->SetErrorCode(errorCode);
break; break;
} }
...@@ -191,7 +196,7 @@ namespace RTC ...@@ -191,7 +196,7 @@ namespace RTC
} }
// Set next attribute position. // Set next attribute position.
pos = (size_t)Utils::Byte::PadTo4Bytes((uint16_t)(pos + 4 + attr_length)); pos = (size_t)Utils::Byte::PadTo4Bytes((uint16_t)(pos + 4 + attrLength));
} }
// Ensure current position matches the total length. // Ensure current position matches the total length.
...@@ -204,16 +209,19 @@ namespace RTC ...@@ -204,16 +209,19 @@ namespace RTC
} }
// If it has FINGERPRINT attribute then verify it. // If it has FINGERPRINT attribute then verify it.
if (has_fingerprint) if (hasFingerprint)
{ {
// Compute the CRC32 of the received message up to (but excluding) the // Compute the CRC32 of the received message up to (but excluding) the
// FINGERPRINT attribute and XOR it with 0x5354554e. // FINGERPRINT attribute and XOR it with 0x5354554e.
uint32_t computed_fingerprint = Utils::Crypto::GetCRC32(data, fingerprint_attr_pos) ^ 0x5354554e; uint32_t computedFingerprint =
Utils::Crypto::GetCRC32(data, fingerprintAttrPos) ^ 0x5354554e;
// Compare with the FINGERPRINT value in the message. // Compare with the FINGERPRINT value in the message.
if (fingerprint != computed_fingerprint) if (fingerprint != computedFingerprint)
{ {
MS_WARN_TAG(ice, "computed FINGERPRINT value does not match the value in the message,| message discarded"); MS_WARN_TAG(ice,
"computed FINGERPRINT value does not match the value in the message, "
"message discarded");
delete msg; delete msg;
return nullptr; return nullptr;
...@@ -264,13 +272,15 @@ namespace RTC ...@@ -264,13 +272,15 @@ namespace RTC
MS_DUMP(" %s with unknown method %#.3x", klass.c_str(), (uint16_t)this->method); MS_DUMP(" %s with unknown method %#.3x", klass.c_str(), (uint16_t)this->method);
} }
MS_DUMP(" size: %zu bytes", this->size); MS_DUMP(" size: %zu bytes", this->size);
char transaction_id[25];
static char TransactionId[25];
for (int i=0; i<12; ++i) for (int i=0; i<12; ++i)
{ {
// NOTE: n must be 3 because snprintf adds a \0 after printed chars. // NOTE: n must be 3 because snprintf adds a \0 after printed chars.
std::snprintf(transaction_id+(i*2), 3, "%.2x", this->transactionId[i]); std::snprintf(TransactionId+(i*2), 3, "%.2x", this->transactionId[i]);
} }
MS_DUMP(" transactionId: %s", transaction_id); MS_DUMP(" transactionId: %s", TransactionId);
if (this->errorCode) if (this->errorCode)
MS_DUMP(" errorCode: %" PRIu16, this->errorCode); MS_DUMP(" errorCode: %" PRIu16, this->errorCode);
if (!this->username.empty()) if (!this->username.empty())
...@@ -288,19 +298,21 @@ namespace RTC ...@@ -288,19 +298,21 @@ namespace RTC
int family; int family;
uint16_t port; uint16_t port;
std::string ip; std::string ip;
Utils::IP::GetAddressInfo(this->xorMappedAddress, &family, ip, &port); Utils::IP::GetAddressInfo(this->xorMappedAddress, &family, ip, &port);
MS_DUMP(" xorMappedAddress: %s : %" PRIu16, ip.c_str(), port); MS_DUMP(" xorMappedAddress: %s : %" PRIu16, ip.c_str(), port);
} }
if (this->messageIntegrity) if (this->messageIntegrity)
{ {
char message_integrity[41]; static char MessageIntegrity[41];
for (int i=0; i<20; ++i) for (int i=0; i<20; ++i)
{ {
std::snprintf(message_integrity+(i*2), 3, "%.2x", this->messageIntegrity[i]); std::snprintf(MessageIntegrity+(i*2), 3, "%.2x", this->messageIntegrity[i]);
} }
MS_DUMP(" messageIntegrity: %s", message_integrity); MS_DUMP(" messageIntegrity: %s", MessageIntegrity);
} }
if (this->hasFingerprint) if (this->hasFingerprint)
MS_DUMP(" fingerprint"); MS_DUMP(" fingerprint");
...@@ -308,7 +320,7 @@ namespace RTC ...@@ -308,7 +320,7 @@ namespace RTC
MS_DUMP("</StunMessage>"); MS_DUMP("</StunMessage>");
} }
StunMessage::Authentication StunMessage::CheckAuthentication(const std::string &local_username, const std::string &local_password) StunMessage::Authentication StunMessage::CheckAuthentication(const std::string &localUsername, const std::string &localPassword)
{ {
MS_TRACE(); MS_TRACE();
...@@ -322,11 +334,12 @@ namespace RTC ...@@ -322,11 +334,12 @@ namespace RTC
return Authentication::BadRequest; return Authentication::BadRequest;
// Check that USERNAME attribute begins with our local username plus ":". // Check that USERNAME attribute begins with our local username plus ":".
size_t local_username_len = local_username.length(); size_t localUsernameLen = localUsername.length();
if ( if (
this->username.length() <= local_username_len || this->username.length() <= localUsernameLen ||
this->username.at(local_username_len) != ':' || this->username.at(localUsernameLen) != ':' ||
(this->username.compare(0, local_username_len, local_username) != 0) (this->username.compare(0, localUsernameLen, localUsername) != 0)
) )
return Authentication::Unauthorized; return Authentication::Unauthorized;
...@@ -350,12 +363,13 @@ namespace RTC ...@@ -350,12 +363,13 @@ namespace RTC
Utils::Byte::Set2Bytes(this->data, 2, (uint16_t)(this->size - 20 - 8)); Utils::Byte::Set2Bytes(this->data, 2, (uint16_t)(this->size - 20 - 8));
// Calculate the HMAC-SHA1 of the message according to MESSAGE-INTEGRITY rules. // Calculate the HMAC-SHA1 of the message according to MESSAGE-INTEGRITY rules.
const uint8_t* computed_message_integrity = Utils::Crypto::GetHMAC_SHA1(local_password, this->data, (this->messageIntegrity - 4) - this->data); const uint8_t* computedMessageIntegrity = Utils::Crypto::GetHMAC_SHA1(localPassword,
this->data, (this->messageIntegrity - 4) - this->data);
Authentication result; Authentication result;
// Compare the computed HMAC-SHA1 with the MESSAGE-INTEGRITY in the message. // Compare the computed HMAC-SHA1 with the MESSAGE-INTEGRITY in the message.
if (std::memcmp(this->messageIntegrity, computed_message_integrity, 20) == 0) if (std::memcmp(this->messageIntegrity, computedMessageIntegrity, 20) == 0)
result = Authentication::OK; result = Authentication::OK;
else else
result = Authentication::Unauthorized; result = Authentication::Unauthorized;
...@@ -371,7 +385,8 @@ namespace RTC ...@@ -371,7 +385,8 @@ namespace RTC
{ {
MS_TRACE(); MS_TRACE();
MS_ASSERT(this->klass == Class::Request, "attempt to create a success response for a non Request STUN message"); MS_ASSERT(this->klass == Class::Request,
"attempt to create a success response for a non Request STUN message");
return new StunMessage(Class::SuccessResponse, this->method, this->transactionId, nullptr, 0); return new StunMessage(Class::SuccessResponse, this->method, this->transactionId, nullptr, 0);
} }
...@@ -380,9 +395,11 @@ namespace RTC ...@@ -380,9 +395,11 @@ namespace RTC
{ {
MS_TRACE(); MS_TRACE();
MS_ASSERT(this->klass == Class::Request, "attempt to create an error response for a non Request STUN message"); MS_ASSERT(this->klass == Class::Request,
"attempt to create an error response for a non Request STUN message");
StunMessage* response = new StunMessage(Class::ErrorResponse, this->method, this->transactionId, nullptr, 0); StunMessage* response = new StunMessage(Class::ErrorResponse, this->method,
this->transactionId, nullptr, 0);
response->SetErrorCode(errorCode); response->SetErrorCode(errorCode);
...@@ -407,12 +424,13 @@ namespace RTC ...@@ -407,12 +424,13 @@ namespace RTC
MS_TRACE(); MS_TRACE();
// Some useful variables. // Some useful variables.
uint16_t username_padded_len = 0; uint16_t usernamePaddedLen = 0;
uint16_t xor_mapped_address_padded_len = 0; uint16_t xorMappedAddressPaddedLen = 0;
bool add_xor_mapped_address = (this->xorMappedAddress && this->method == StunMessage::Method::Binding && this->klass == Class::SuccessResponse); bool addXorMappedAddress = (this->xorMappedAddress &&
bool add_error_code = (this->errorCode && this->klass == Class::ErrorResponse); this->method == StunMessage::Method::Binding && this->klass == Class::SuccessResponse);
bool add_message_integrity = (this->klass != Class::ErrorResponse && !this->password.empty()); bool addErrorCode = (this->errorCode && this->klass == Class::ErrorResponse);
bool add_fingerprint = true; // Do always. bool addMessageIntegrity = (this->klass != Class::ErrorResponse && !this->password.empty());
bool addFingerprint = true; // Do always.
// Update data pointer. // Update data pointer.
this->data = buffer; this->data = buffer;
...@@ -422,8 +440,8 @@ namespace RTC ...@@ -422,8 +440,8 @@ namespace RTC
if (!this->username.empty()) if (!this->username.empty())
{ {
username_padded_len = Utils::Byte::PadTo4Bytes((uint16_t)this->username.length()); usernamePaddedLen = Utils::Byte::PadTo4Bytes((uint16_t)this->username.length());
this->size += 4 + username_padded_len; this->size += 4 + usernamePaddedLen;
} }
if (this->priority) if (this->priority)
...@@ -438,20 +456,20 @@ namespace RTC ...@@ -438,20 +456,20 @@ namespace RTC
if (this->hasUseCandidate) if (this->hasUseCandidate)
this->size += 4; this->size += 4;
if (add_xor_mapped_address) if (addXorMappedAddress)
{ {
switch (this->xorMappedAddress->sa_family) switch (this->xorMappedAddress->sa_family)
{ {
case AF_INET: case AF_INET:
{ {
xor_mapped_address_padded_len = 8; xorMappedAddressPaddedLen = 8;
this->size += 4 + 8; this->size += 4 + 8;
break; break;
} }
case AF_INET6: case AF_INET6:
{ {
xor_mapped_address_padded_len = 20; xorMappedAddressPaddedLen = 20;
this->size += 4 + 20; this->size += 4 + 20;
break; break;
...@@ -460,29 +478,30 @@ namespace RTC ...@@ -460,29 +478,30 @@ namespace RTC
{ {
MS_ERROR("invalid inet family in XOR-MAPPED-ADDRESS attribute"); MS_ERROR("invalid inet family in XOR-MAPPED-ADDRESS attribute");
add_xor_mapped_address = false; addXorMappedAddress = false;
} }
} }
} }
if (add_error_code) if (addErrorCode)
this->size += 4 + 4; this->size += 4 + 4;
if (add_message_integrity) if (addMessageIntegrity)
this->size += 4 + 20; this->size += 4 + 20;
if (add_fingerprint) if (addFingerprint)
this->size += 4 + 4; this->size += 4 + 4;
// Merge class and method fields into type. // Merge class and method fields into type.
uint16_t type_field = ((uint16_t)this->method & 0x0f80) << 2; uint16_t typeField = ((uint16_t)this->method & 0x0f80) << 2;
type_field |= ((uint16_t)this->method & 0x0070) << 1;
type_field |= ((uint16_t)this->method & 0x000f); typeField |= ((uint16_t)this->method & 0x0070) << 1;
type_field |= ((uint16_t)this->klass & 0x02) << 7; typeField |= ((uint16_t)this->method & 0x000f);
type_field |= ((uint16_t)this->klass & 0x01) << 4; typeField |= ((uint16_t)this->klass & 0x02) << 7;
typeField |= ((uint16_t)this->klass & 0x01) << 4;
// Set type field. // Set type field.
Utils::Byte::Set2Bytes(buffer, 0, type_field); Utils::Byte::Set2Bytes(buffer, 0, typeField);
// Set length field. // Set length field.
Utils::Byte::Set2Bytes(buffer, 2, (uint16_t)this->size - 20); Utils::Byte::Set2Bytes(buffer, 2, (uint16_t)this->size - 20);
...@@ -500,12 +519,12 @@ namespace RTC ...@@ -500,12 +519,12 @@ namespace RTC
size_t pos = 20; size_t pos = 20;
// Add USERNAME. // Add USERNAME.
if (username_padded_len) if (usernamePaddedLen)
{ {
Utils::Byte::Set2Bytes(buffer, pos, (uint16_t)Attribute::Username); Utils::Byte::Set2Bytes(buffer, pos, (uint16_t)Attribute::Username);
Utils::Byte::Set2Bytes(buffer, pos + 2, (uint16_t)this->username.length()); Utils::Byte::Set2Bytes(buffer, pos + 2, (uint16_t)this->username.length());
std::memcpy(buffer + pos + 4, this->username.c_str(), this->username.length()); std::memcpy(buffer + pos + 4, this->username.c_str(), this->username.length());
pos += 4 + username_padded_len; pos += 4 + usernamePaddedLen;
} }
// Add PRIORITY. // Add PRIORITY.
...@@ -544,11 +563,13 @@ namespace RTC ...@@ -544,11 +563,13 @@ namespace RTC
} }
// Add XOR-MAPPED-ADDRESS // Add XOR-MAPPED-ADDRESS
if (add_xor_mapped_address) if (addXorMappedAddress)
{ {
Utils::Byte::Set2Bytes(buffer, pos, (uint16_t)Attribute::XorMappedAddress); Utils::Byte::Set2Bytes(buffer, pos, (uint16_t)Attribute::XorMappedAddress);
Utils::Byte::Set2Bytes(buffer, pos + 2, xor_mapped_address_padded_len); Utils::Byte::Set2Bytes(buffer, pos + 2, xorMappedAddressPaddedLen);
uint8_t* attr_value = buffer + pos + 4; uint8_t* attr_value = buffer + pos + 4;
switch (this->xorMappedAddress->sa_family) switch (this->xorMappedAddress->sa_family)
{ {
case AF_INET: case AF_INET:
...@@ -609,38 +630,40 @@ namespace RTC ...@@ -609,38 +630,40 @@ namespace RTC
} }
// Add ERROR-CODE. // Add ERROR-CODE.
if (add_error_code) if (addErrorCode)
{ {
Utils::Byte::Set2Bytes(buffer, pos, (uint16_t)Attribute::ErrorCode); Utils::Byte::Set2Bytes(buffer, pos, (uint16_t)Attribute::ErrorCode);
Utils::Byte::Set2Bytes(buffer, pos + 2, 4); Utils::Byte::Set2Bytes(buffer, pos + 2, 4);
uint8_t code_class = (uint8_t)(this->errorCode / 100);
uint8_t code_number = (uint8_t)this->errorCode - (code_class * 100); uint8_t codeClass = (uint8_t)(this->errorCode / 100);
uint8_t codeNumber = (uint8_t)this->errorCode - (codeClass * 100);
Utils::Byte::Set2Bytes(buffer, pos + 4, 0); Utils::Byte::Set2Bytes(buffer, pos + 4, 0);
Utils::Byte::Set1Byte(buffer, pos + 6, code_class); Utils::Byte::Set1Byte(buffer, pos + 6, codeClass);
Utils::Byte::Set1Byte(buffer, pos + 7, code_number); Utils::Byte::Set1Byte(buffer, pos + 7, codeNumber);
pos += 4 + 4; pos += 4 + 4;
} }
// Add MESSAGE-INTEGRITY. // Add MESSAGE-INTEGRITY.
if (add_message_integrity) if (addMessageIntegrity)
{ {
// Ignore FINGERPRINT. // Ignore FINGERPRINT.
if (add_fingerprint) if (addFingerprint)
Utils::Byte::Set2Bytes(buffer, 2, (uint16_t)(this->size - 20 - 8)); Utils::Byte::Set2Bytes(buffer, 2, (uint16_t)(this->size - 20 - 8));
// Calculate the HMAC-SHA1 of the message according to MESSAGE-INTEGRITY rules. // Calculate the HMAC-SHA1 of the message according to MESSAGE-INTEGRITY rules.
const uint8_t* computed_message_integrity = Utils::Crypto::GetHMAC_SHA1(this->password, buffer, pos); const uint8_t* computedMessageIntegrity = Utils::Crypto::GetHMAC_SHA1(this->password, buffer, pos);
Utils::Byte::Set2Bytes(buffer, pos, (uint16_t)Attribute::MessageIntegrity); Utils::Byte::Set2Bytes(buffer, pos, (uint16_t)Attribute::MessageIntegrity);
Utils::Byte::Set2Bytes(buffer, pos + 2, 20); Utils::Byte::Set2Bytes(buffer, pos + 2, 20);
std::memcpy(buffer + pos + 4, computed_message_integrity, 20); std::memcpy(buffer + pos + 4, computedMessageIntegrity, 20);
// Update the pointer. // Update the pointer.
this->messageIntegrity = buffer + pos + 4; this->messageIntegrity = buffer + pos + 4;
pos += 4 + 20; pos += 4 + 20;
// Restore length field. // Restore length field.
if (add_fingerprint) if (addFingerprint)
Utils::Byte::Set2Bytes(buffer, 2, (uint16_t)(this->size - 20)); Utils::Byte::Set2Bytes(buffer, 2, (uint16_t)(this->size - 20));
} }
else else
...@@ -650,15 +673,15 @@ namespace RTC ...@@ -650,15 +673,15 @@ namespace RTC
} }
// Add FINGERPRINT. // Add FINGERPRINT.
if (add_fingerprint) if (addFingerprint)
{ {
// Compute the CRC32 of the message up to (but excluding) the FINGERPRINT // Compute the CRC32 of the message up to (but excluding) the FINGERPRINT
// attribute and XOR it with 0x5354554e. // attribute and XOR it with 0x5354554e.
uint32_t computed_fingerprint = Utils::Crypto::GetCRC32(buffer, pos) ^ 0x5354554e; uint32_t computedFingerprint = Utils::Crypto::GetCRC32(buffer, pos) ^ 0x5354554e;
Utils::Byte::Set2Bytes(buffer, pos, (uint16_t)Attribute::Fingerprint); Utils::Byte::Set2Bytes(buffer, pos, (uint16_t)Attribute::Fingerprint);
Utils::Byte::Set2Bytes(buffer, pos + 2, 4); Utils::Byte::Set2Bytes(buffer, pos + 2, 4);
Utils::Byte::Set4Bytes(buffer, pos + 4, computed_fingerprint); Utils::Byte::Set4Bytes(buffer, pos + 4, computedFingerprint);
pos += 4 + 4; pos += 4 + 4;
// Set flag. // Set flag.
this->hasFingerprint = true; this->hasFingerprint = true;
......
...@@ -22,8 +22,7 @@ namespace RTC ...@@ -22,8 +22,7 @@ namespace RTC
MS_TRACE(); MS_TRACE();
MS_DEBUG_DEV("data received [local:%s :%" PRIu16 ", remote:%s :%" PRIu16 "]", MS_DEBUG_DEV("data received [local:%s :%" PRIu16 ", remote:%s :%" PRIu16 "]",
GetLocalIP().c_str(), GetLocalPort(), GetLocalIP().c_str(), GetLocalPort(), GetPeerIP().c_str(), GetPeerPort());
GetPeerIP().c_str(), GetPeerPort());
/* /*
* Framing RFC 4571 * Framing RFC 4571
......
...@@ -16,8 +16,7 @@ extern "C" ...@@ -16,8 +16,7 @@ extern "C"
/* Helpers declaration. */ /* Helpers declaration. */
static static bool IsBindableIP(const std::string &ip, int family, int* _bind_err);
bool IsBindableIP(const std::string &ip, int family, int* _bind_err);
/* Class variables. */ /* Class variables. */
...@@ -51,9 +50,9 @@ void Settings::SetConfiguration(int argc, char* argv[]) ...@@ -51,9 +50,9 @@ void Settings::SetConfiguration(int argc, char* argv[])
extern char *optarg; extern char *optarg;
extern int opterr, optopt; extern int opterr, optopt;
int c; int c;
int option_index = 0; int optionIdx = 0;
std::string value_string; std::string stringValue;
std::vector<std::string> log_tags; std::vector<std::string> logTags;
struct option options[] = struct option options[] =
{ {
...@@ -73,7 +72,7 @@ void Settings::SetConfiguration(int argc, char* argv[]) ...@@ -73,7 +72,7 @@ void Settings::SetConfiguration(int argc, char* argv[])
/* Parse command line options. */ /* Parse command line options. */
opterr = 0; // Don't allow getopt to print error messages. opterr = 0; // Don't allow getopt to print error messages.
while ((c = getopt_long_only(argc, argv, "", options, &option_index)) != -1) while ((c = getopt_long_only(argc, argv, "", options, &optionIdx)) != -1)
{ {
if (!optarg) if (!optarg)
MS_THROW_ERROR("unknown configuration parameter: %s", optarg); MS_THROW_ERROR("unknown configuration parameter: %s", optarg);
...@@ -81,34 +80,34 @@ void Settings::SetConfiguration(int argc, char* argv[]) ...@@ -81,34 +80,34 @@ void Settings::SetConfiguration(int argc, char* argv[])
switch (c) switch (c)
{ {
case 'l': case 'l':
value_string = std::string(optarg); stringValue = std::string(optarg);
SetLogLevel(value_string); SetLogLevel(stringValue);
break; break;
case 't': case 't':
value_string = std::string(optarg); stringValue = std::string(optarg);
log_tags.push_back(value_string); logTags.push_back(stringValue);
break; break;
case '4': case '4':
value_string = std::string(optarg); stringValue = std::string(optarg);
SetRtcIPv4(value_string); SetRtcIPv4(stringValue);
break; break;
case '6': case '6':
value_string = std::string(optarg); stringValue = std::string(optarg);
SetRtcIPv6(value_string); SetRtcIPv6(stringValue);
break; break;
case '5': case '5':
value_string = std::string(optarg); stringValue = std::string(optarg);
Settings::configuration.rtcAnnouncedIPv4 = value_string; Settings::configuration.rtcAnnouncedIPv4 = stringValue;
Settings::configuration.hasAnnouncedIPv4 = true; Settings::configuration.hasAnnouncedIPv4 = true;
break; break;
case '7': case '7':
value_string = std::string(optarg); stringValue = std::string(optarg);
Settings::configuration.rtcAnnouncedIPv6 = value_string; Settings::configuration.rtcAnnouncedIPv6 = stringValue;
Settings::configuration.hasAnnouncedIPv6 = true; Settings::configuration.hasAnnouncedIPv6 = true;
break; break;
...@@ -121,13 +120,13 @@ void Settings::SetConfiguration(int argc, char* argv[]) ...@@ -121,13 +120,13 @@ void Settings::SetConfiguration(int argc, char* argv[])
break; break;
case 'c': case 'c':
value_string = std::string(optarg); stringValue = std::string(optarg);
Settings::configuration.dtlsCertificateFile = value_string; Settings::configuration.dtlsCertificateFile = stringValue;
break; break;
case 'p': case 'p':
value_string = std::string(optarg); stringValue = std::string(optarg);
Settings::configuration.dtlsPrivateKeyFile = value_string; Settings::configuration.dtlsPrivateKeyFile = stringValue;
break; break;
// Invalid option. // Invalid option.
...@@ -150,8 +149,8 @@ void Settings::SetConfiguration(int argc, char* argv[]) ...@@ -150,8 +149,8 @@ void Settings::SetConfiguration(int argc, char* argv[])
/* Post configuration. */ /* Post configuration. */
// Set logTags. // Set logTags.
if (!log_tags.empty()) if (!logTags.empty())
Settings::SetLogTags(log_tags); Settings::SetLogTags(logTags);
// RTC must have at least 'IPv4' or 'IPv6'. // RTC must have at least 'IPv4' or 'IPv6'.
if (!Settings::configuration.hasIPv4 && !Settings::configuration.hasIPv6) if (!Settings::configuration.hasIPv4 && !Settings::configuration.hasIPv6)
...@@ -180,54 +179,76 @@ void Settings::PrintConfiguration() ...@@ -180,54 +179,76 @@ void Settings::PrintConfiguration()
{ {
MS_TRACE(); MS_TRACE();
std::vector<std::string> log_tags; std::vector<std::string> logTags;
if (Settings::configuration.logTags.info) if (Settings::configuration.logTags.info)
log_tags.push_back("info"); logTags.push_back("info");
if (Settings::configuration.logTags.ice) if (Settings::configuration.logTags.ice)
log_tags.push_back("ice"); logTags.push_back("ice");
if (Settings::configuration.logTags.dtls) if (Settings::configuration.logTags.dtls)
log_tags.push_back("dtls"); logTags.push_back("dtls");
if (Settings::configuration.logTags.rtp) if (Settings::configuration.logTags.rtp)
log_tags.push_back("rtp"); logTags.push_back("rtp");
if (Settings::configuration.logTags.srtp) if (Settings::configuration.logTags.srtp)
log_tags.push_back("srtp"); logTags.push_back("srtp");
if (Settings::configuration.logTags.rtcp) if (Settings::configuration.logTags.rtcp)
log_tags.push_back("rtcp"); logTags.push_back("rtcp");
if (Settings::configuration.logTags.rbe) if (Settings::configuration.logTags.rbe)
log_tags.push_back("rbe"); logTags.push_back("rbe");
if (Settings::configuration.logTags.rtx) if (Settings::configuration.logTags.rtx)
log_tags.push_back("rtx"); logTags.push_back("rtx");
MS_DEBUG_TAG(info, "<configuration>"); MS_DEBUG_TAG(info, "<configuration>");
MS_DEBUG_TAG(info, " logLevel : \"%s\"", Settings::logLevel2String[Settings::configuration.logLevel].c_str()); MS_DEBUG_TAG(info, " logLevel : \"%s\"",
for (auto& tag : log_tags) Settings::logLevel2String[Settings::configuration.logLevel].c_str());
for (auto& tag : logTags)
{ {
MS_DEBUG_TAG(info, " logTag : \"%s\"", tag.c_str()); MS_DEBUG_TAG(info, " logTag : \"%s\"", tag.c_str());
} }
if (Settings::configuration.hasIPv4) if (Settings::configuration.hasIPv4)
MS_DEBUG_TAG(info, " rtcIPv4 : \"%s\"", Settings::configuration.rtcIPv4.c_str()); {
MS_DEBUG_TAG(info, " rtcIPv4 : \"%s\"",
Settings::configuration.rtcIPv4.c_str());
}
else else
{
MS_DEBUG_TAG(info, " rtcIPv4 : (unavailable)"); MS_DEBUG_TAG(info, " rtcIPv4 : (unavailable)");
}
if (Settings::configuration.hasIPv6) if (Settings::configuration.hasIPv6)
MS_DEBUG_TAG(info, " rtcIPv6 : \"%s\"", Settings::configuration.rtcIPv6.c_str()); {
MS_DEBUG_TAG(info, " rtcIPv6 : \"%s\"",
Settings::configuration.rtcIPv6.c_str());
}
else else
{
MS_DEBUG_TAG(info, " rtcIPv6 : (unavailable)"); MS_DEBUG_TAG(info, " rtcIPv6 : (unavailable)");
}
if (Settings::configuration.hasAnnouncedIPv4) if (Settings::configuration.hasAnnouncedIPv4)
MS_DEBUG_TAG(info, " rtcAnnouncedIPv4 : \"%s\"", Settings::configuration.rtcAnnouncedIPv4.c_str()); {
MS_DEBUG_TAG(info, " rtcAnnouncedIPv4 : \"%s\"",
Settings::configuration.rtcAnnouncedIPv4.c_str());
}
else else
{
MS_DEBUG_TAG(info, " rtcAnnouncedIPv4 : (unset)"); MS_DEBUG_TAG(info, " rtcAnnouncedIPv4 : (unset)");
}
if (Settings::configuration.hasAnnouncedIPv6) if (Settings::configuration.hasAnnouncedIPv6)
{
MS_DEBUG_TAG(info, " rtcAnnouncedIPv6 : \"%s\"", Settings::configuration.rtcAnnouncedIPv6.c_str()); MS_DEBUG_TAG(info, " rtcAnnouncedIPv6 : \"%s\"", Settings::configuration.rtcAnnouncedIPv6.c_str());
}
else else
{
MS_DEBUG_TAG(info, " rtcAnnouncedIPv6 : (unset)"); MS_DEBUG_TAG(info, " rtcAnnouncedIPv6 : (unset)");
}
MS_DEBUG_TAG(info, " rtcMinPort : %" PRIu16, Settings::configuration.rtcMinPort); MS_DEBUG_TAG(info, " rtcMinPort : %" PRIu16, Settings::configuration.rtcMinPort);
MS_DEBUG_TAG(info, " rtcMaxPort : %" PRIu16, Settings::configuration.rtcMaxPort); MS_DEBUG_TAG(info, " rtcMaxPort : %" PRIu16, Settings::configuration.rtcMaxPort);
if (!Settings::configuration.dtlsCertificateFile.empty()) if (!Settings::configuration.dtlsCertificateFile.empty())
{ {
MS_DEBUG_TAG(info, " dtlsCertificateFile : \"%s\"", Settings::configuration.dtlsCertificateFile.c_str()); MS_DEBUG_TAG(info, " dtlsCertificateFile : \"%s\"",
MS_DEBUG_TAG(info, " dtlsPrivateKeyFile : \"%s\"", Settings::configuration.dtlsPrivateKeyFile.c_str()); Settings::configuration.dtlsCertificateFile.c_str());
MS_DEBUG_TAG(info, " dtlsPrivateKeyFile : \"%s\"",
Settings::configuration.dtlsPrivateKeyFile.c_str());
} }
MS_DEBUG_TAG(info, "</configuration>"); MS_DEBUG_TAG(info, "</configuration>");
...@@ -244,28 +265,29 @@ void Settings::HandleRequest(Channel::Request* request) ...@@ -244,28 +265,29 @@ void Settings::HandleRequest(Channel::Request* request)
static const Json::StaticString k_logLevel("logLevel"); static const Json::StaticString k_logLevel("logLevel");
static const Json::StaticString k_logTags("logTags"); static const Json::StaticString k_logTags("logTags");
Json::Value json_logLevel = request->data[k_logLevel]; Json::Value jsonLogLevel = request->data[k_logLevel];
Json::Value json_logTags = request->data[k_logTags]; Json::Value jsonLogTags = request->data[k_logTags];
try try
{ {
// Update logLevel if requested. // Update logLevel if requested.
if (json_logLevel.isString()) if (jsonLogLevel.isString())
{ {
std::string logLevel = json_logLevel.asString(); std::string logLevel = jsonLogLevel.asString();
Settings::SetLogLevel(logLevel); Settings::SetLogLevel(logLevel);
} }
// Update logTags if requested. // Update logTags if requested.
if (json_logTags.isArray()) if (jsonLogTags.isArray())
{ {
Settings::SetLogTags(json_logTags); Settings::SetLogTags(jsonLogTags);
} }
} }
catch (const MediaSoupError &error) catch (const MediaSoupError &error)
{ {
request->Reject(error.what()); request->Reject(error.what());
return; return;
} }
...@@ -286,22 +308,22 @@ void Settings::HandleRequest(Channel::Request* request) ...@@ -286,22 +308,22 @@ void Settings::HandleRequest(Channel::Request* request)
} }
} }
void Settings::SetDefaultRtcIP(int requested_family) void Settings::SetDefaultRtcIP(int requestedFamily)
{ {
MS_TRACE(); MS_TRACE();
int err; int err;
uv_interface_address_t* addresses; uv_interface_address_t* addresses;
int num_addresses; int numAddresses;
std::string ipv4; std::string ipv4;
std::string ipv6; std::string ipv6;
int bind_errno; int bindErrno;
err = uv_interface_addresses(&addresses, &num_addresses); err = uv_interface_addresses(&addresses, &numAddresses);
if (err) if (err)
MS_ABORT("uv_interface_addresses() failed: %s", uv_strerror(err)); MS_ABORT("uv_interface_addresses() failed: %s", uv_strerror(err));
for (int i = 0; i < num_addresses; ++i) for (int i = 0; i < numAddresses; ++i)
{ {
uv_interface_address_t address = addresses[i]; uv_interface_address_t address = addresses[i];
...@@ -314,7 +336,7 @@ void Settings::SetDefaultRtcIP(int requested_family) ...@@ -314,7 +336,7 @@ void Settings::SetDefaultRtcIP(int requested_family)
std::string ip; std::string ip;
Utils::IP::GetAddressInfo((struct sockaddr*)(&address.address.address4), &family, ip, &port); Utils::IP::GetAddressInfo((struct sockaddr*)(&address.address.address4), &family, ip, &port);
if (family != requested_family) if (family != requestedFamily)
continue; continue;
switch (family) switch (family)
...@@ -325,7 +347,7 @@ void Settings::SetDefaultRtcIP(int requested_family) ...@@ -325,7 +347,7 @@ void Settings::SetDefaultRtcIP(int requested_family)
continue; continue;
// Check if it is bindable. // Check if it is bindable.
if (!IsBindableIP(ip, AF_INET, &bind_errno)) if (!IsBindableIP(ip, AF_INET, &bindErrno))
continue; continue;
ipv4 = ip; ipv4 = ip;
...@@ -337,7 +359,7 @@ void Settings::SetDefaultRtcIP(int requested_family) ...@@ -337,7 +359,7 @@ void Settings::SetDefaultRtcIP(int requested_family)
continue; continue;
// Check if it is bindable. // Check if it is bindable.
if (!IsBindableIP(ip, AF_INET6, &bind_errno)) if (!IsBindableIP(ip, AF_INET6, &bindErrno))
continue; continue;
ipv6 = ip; ipv6 = ip;
...@@ -357,7 +379,7 @@ void Settings::SetDefaultRtcIP(int requested_family) ...@@ -357,7 +379,7 @@ void Settings::SetDefaultRtcIP(int requested_family)
Settings::configuration.hasIPv6 = true; Settings::configuration.hasIPv6 = true;
} }
uv_free_interface_addresses(addresses, num_addresses); uv_free_interface_addresses(addresses, numAddresses);
} }
void Settings::SetLogLevel(std::string &level) void Settings::SetLogLevel(std::string &level)
...@@ -384,6 +406,7 @@ void Settings::SetRtcIPv4(const std::string &ip) ...@@ -384,6 +406,7 @@ void Settings::SetRtcIPv4(const std::string &ip)
{ {
Settings::configuration.rtcIPv4.clear(); Settings::configuration.rtcIPv4.clear();
Settings::configuration.hasIPv4 = false; Settings::configuration.hasIPv4 = false;
return; return;
} }
...@@ -401,9 +424,10 @@ void Settings::SetRtcIPv4(const std::string &ip) ...@@ -401,9 +424,10 @@ void Settings::SetRtcIPv4(const std::string &ip)
MS_THROW_ERROR("invalid value '%s' for rtcIPv4", ip.c_str()); MS_THROW_ERROR("invalid value '%s' for rtcIPv4", ip.c_str());
} }
int bind_errno; int bindErrno;
if (!IsBindableIP(ip, AF_INET, &bind_errno))
MS_THROW_ERROR("cannot bind on '%s' for rtcIPv4: %s", ip.c_str(), std::strerror(bind_errno)); if (!IsBindableIP(ip, AF_INET, &bindErrno))
MS_THROW_ERROR("cannot bind on '%s' for rtcIPv4: %s", ip.c_str(), std::strerror(bindErrno));
} }
void Settings::SetRtcIPv6(const std::string &ip) void Settings::SetRtcIPv6(const std::string &ip)
...@@ -417,6 +441,7 @@ void Settings::SetRtcIPv6(const std::string &ip) ...@@ -417,6 +441,7 @@ void Settings::SetRtcIPv6(const std::string &ip)
{ {
Settings::configuration.rtcIPv6.clear(); Settings::configuration.rtcIPv6.clear();
Settings::configuration.hasIPv6 = false; Settings::configuration.hasIPv6 = false;
return; return;
} }
...@@ -434,9 +459,10 @@ void Settings::SetRtcIPv6(const std::string &ip) ...@@ -434,9 +459,10 @@ void Settings::SetRtcIPv6(const std::string &ip)
MS_THROW_ERROR("invalid value '%s' for rtcIPv6", ip.c_str()); MS_THROW_ERROR("invalid value '%s' for rtcIPv6", ip.c_str());
} }
int bind_errno; int bindErrno;
if (!IsBindableIP(ip, AF_INET6, &bind_errno))
MS_THROW_ERROR("cannot bind on '%s' for rtcIPv6: %s", ip.c_str(), std::strerror(bind_errno)); if (!IsBindableIP(ip, AF_INET6, &bindErrno))
MS_THROW_ERROR("cannot bind on '%s' for rtcIPv6: %s", ip.c_str(), std::strerror(bindErrno));
} }
void Settings::SetRtcPorts() void Settings::SetRtcPorts()
...@@ -474,6 +500,7 @@ void Settings::SetDtlsCertificateAndPrivateKeyFiles() ...@@ -474,6 +500,7 @@ void Settings::SetDtlsCertificateAndPrivateKeyFiles()
{ {
Settings::configuration.dtlsCertificateFile = ""; Settings::configuration.dtlsCertificateFile = "";
Settings::configuration.dtlsPrivateKeyFile = ""; Settings::configuration.dtlsPrivateKeyFile = "";
return; return;
} }
...@@ -551,38 +578,38 @@ void Settings::SetLogTags(Json::Value& json) ...@@ -551,38 +578,38 @@ void Settings::SetLogTags(Json::Value& json)
/* Helpers. */ /* Helpers. */
bool IsBindableIP(const std::string &ip, int family, int* bind_errno) bool IsBindableIP(const std::string &ip, int family, int* bindErrno)
{ {
MS_TRACE(); MS_TRACE();
struct sockaddr_storage bind_addr; struct sockaddr_storage bindAddr;
int bind_socket; int bindSocket;
int err = 0; int err = 0;
bool success; bool success;
switch (family) switch (family)
{ {
case AF_INET: case AF_INET:
err = uv_ip4_addr(ip.c_str(), 0, (struct sockaddr_in*)&bind_addr); err = uv_ip4_addr(ip.c_str(), 0, (struct sockaddr_in*)&bindAddr);
if (err) if (err)
MS_ABORT("uv_ipv4_addr() failed: %s", uv_strerror(err)); MS_ABORT("uv_ipv4_addr() failed: %s", uv_strerror(err));
bind_socket = socket(AF_INET, SOCK_DGRAM, 0); bindSocket = socket(AF_INET, SOCK_DGRAM, 0);
if (bind_socket == -1) if (bindSocket == -1)
MS_ABORT("socket() failed: %s", std::strerror(errno)); MS_ABORT("socket() failed: %s", std::strerror(errno));
err = bind(bind_socket, (const struct sockaddr*)&bind_addr, sizeof(struct sockaddr_in)); err = bind(bindSocket, (const struct sockaddr*)&bindAddr, sizeof(struct sockaddr_in));
break; break;
case AF_INET6: case AF_INET6:
uv_ip6_addr(ip.c_str(), 0, (struct sockaddr_in6*)&bind_addr); uv_ip6_addr(ip.c_str(), 0, (struct sockaddr_in6*)&bindAddr);
if (err) if (err)
MS_ABORT("uv_ipv6_addr() failed: %s", uv_strerror(err)); MS_ABORT("uv_ipv6_addr() failed: %s", uv_strerror(err));
bind_socket = socket(AF_INET6, SOCK_DGRAM, 0); bindSocket = socket(AF_INET6, SOCK_DGRAM, 0);
if (bind_socket == -1) if (bindSocket == -1)
MS_ABORT("socket() failed: %s", std::strerror(errno)); MS_ABORT("socket() failed: %s", std::strerror(errno));
err = bind(bind_socket, (const struct sockaddr*)&bind_addr, sizeof(struct sockaddr_in6)); err = bind(bindSocket, (const struct sockaddr*)&bindAddr, sizeof(struct sockaddr_in6));
break; break;
default: default:
...@@ -596,10 +623,10 @@ bool IsBindableIP(const std::string &ip, int family, int* bind_errno) ...@@ -596,10 +623,10 @@ bool IsBindableIP(const std::string &ip, int family, int* bind_errno)
else else
{ {
success = false; success = false;
*bind_errno = errno; *bindErrno = errno;
} }
err = close(bind_socket); err = close(bindSocket);
if (err) if (err)
MS_ABORT("close() failed: %s", std::strerror(errno)); MS_ABORT("close() failed: %s", std::strerror(errno));
......
...@@ -87,15 +87,22 @@ namespace Utils ...@@ -87,15 +87,22 @@ namespace Utils
int ret; int ret;
ret = HMAC_Init_ex(&Crypto::hmacSha1Ctx, key.c_str(), key.length(), EVP_sha1(), nullptr); ret = HMAC_Init_ex(&Crypto::hmacSha1Ctx, key.c_str(), key.length(), EVP_sha1(), nullptr);
MS_ASSERT(ret == 1, "OpenSSL HMAC_Init_ex() failed with key '%s'", key.c_str()); MS_ASSERT(ret == 1, "OpenSSL HMAC_Init_ex() failed with key '%s'", key.c_str());
ret = HMAC_Update(&Crypto::hmacSha1Ctx, (const uint8_t*)data, (int)len); ret = HMAC_Update(&Crypto::hmacSha1Ctx, (const uint8_t*)data, (int)len);
MS_ASSERT(ret == 1, "OpenSSL HMAC_Update() failed with key '%s' and data length %zu bytes", key.c_str(), len);
uint32_t result_len; MS_ASSERT(ret == 1, "OpenSSL HMAC_Update() failed with key '%s' and data length %zu bytes",
ret = HMAC_Final(&Crypto::hmacSha1Ctx, (uint8_t *)Crypto::hmacSha1Buffer, &result_len); key.c_str(), len);
MS_ASSERT(ret == 1, "OpenSSL HMAC_Final() failed with key '%s' and data length %zu bytes", key.c_str(), len);
MS_ASSERT(result_len == 20, "OpenSSL HMAC_Final() result_len is %u instead of 20", result_len); uint32_t resultLen;
ret = HMAC_Final(&Crypto::hmacSha1Ctx, (uint8_t *)Crypto::hmacSha1Buffer, &resultLen);
MS_ASSERT(ret == 1, "OpenSSL HMAC_Final() failed with key '%s' and data length %zu bytes",
key.c_str(), len);
MS_ASSERT(resultLen == 20, "OpenSSL HMAC_Final() resultLen is %u instead of 20",
resultLen);
return Crypto::hmacSha1Buffer; return Crypto::hmacSha1Buffer;
} }
......
...@@ -14,16 +14,16 @@ namespace Utils ...@@ -14,16 +14,16 @@ namespace Utils
{ {
MS_TRACE(); MS_TRACE();
struct stat file_stat; struct stat fileStat;
int err; int err;
// Ensure the given file exists. // Ensure the given file exists.
err = stat(file, &file_stat); err = stat(file, &fileStat);
if (err) if (err)
MS_THROW_ERROR("cannot read file '%s': %s", file, std::strerror(errno)); MS_THROW_ERROR("cannot read file '%s': %s", file, std::strerror(errno));
// Ensure it is a regular file. // Ensure it is a regular file.
if (!S_ISREG(file_stat.st_mode)) if (!S_ISREG(fileStat.st_mode))
MS_THROW_ERROR("'%s' is not a regular file", file); MS_THROW_ERROR("'%s' is not a regular file", file);
// Ensure it is readable. // Ensure it is readable.
......
...@@ -13,7 +13,7 @@ namespace Utils ...@@ -13,7 +13,7 @@ namespace Utils
{ {
MS_TRACE(); MS_TRACE();
int ip_family = 0; int ipFamily = 0;
/** /**
* Ragel: machine definition. * Ragel: machine definition.
...@@ -156,13 +156,13 @@ case 7: ...@@ -156,13 +156,13 @@ case 7:
tr20: tr20:
#line 25 "src/Utils/IP.rl" #line 25 "src/Utils/IP.rl"
{ {
ip_family = AF_INET; ipFamily = AF_INET;
} }
goto st86; goto st86;
tr77: tr77:
#line 30 "src/Utils/IP.rl" #line 30 "src/Utils/IP.rl"
{ {
ip_family = AF_INET6; ipFamily = AF_INET6;
} }
goto st86; goto st86;
st86: st86:
...@@ -174,7 +174,7 @@ case 86: ...@@ -174,7 +174,7 @@ case 86:
tr21: tr21:
#line 25 "src/Utils/IP.rl" #line 25 "src/Utils/IP.rl"
{ {
ip_family = AF_INET; ipFamily = AF_INET;
} }
goto st87; goto st87;
st87: st87:
...@@ -188,7 +188,7 @@ case 87: ...@@ -188,7 +188,7 @@ case 87:
tr23: tr23:
#line 25 "src/Utils/IP.rl" #line 25 "src/Utils/IP.rl"
{ {
ip_family = AF_INET; ipFamily = AF_INET;
} }
goto st88; goto st88;
st88: st88:
...@@ -202,7 +202,7 @@ case 88: ...@@ -202,7 +202,7 @@ case 88:
tr22: tr22:
#line 25 "src/Utils/IP.rl" #line 25 "src/Utils/IP.rl"
{ {
ip_family = AF_INET; ipFamily = AF_INET;
} }
goto st89; goto st89;
st89: st89:
...@@ -221,7 +221,7 @@ case 89: ...@@ -221,7 +221,7 @@ case 89:
tr120: tr120:
#line 25 "src/Utils/IP.rl" #line 25 "src/Utils/IP.rl"
{ {
ip_family = AF_INET; ipFamily = AF_INET;
} }
goto st90; goto st90;
st90: st90:
...@@ -775,7 +775,7 @@ case 50: ...@@ -775,7 +775,7 @@ case 50:
tr78: tr78:
#line 30 "src/Utils/IP.rl" #line 30 "src/Utils/IP.rl"
{ {
ip_family = AF_INET6; ipFamily = AF_INET6;
} }
goto st91; goto st91;
st91: st91:
...@@ -789,7 +789,7 @@ case 91: ...@@ -789,7 +789,7 @@ case 91:
tr80: tr80:
#line 30 "src/Utils/IP.rl" #line 30 "src/Utils/IP.rl"
{ {
ip_family = AF_INET6; ipFamily = AF_INET6;
} }
goto st92; goto st92;
st92: st92:
...@@ -803,7 +803,7 @@ case 92: ...@@ -803,7 +803,7 @@ case 92:
tr79: tr79:
#line 30 "src/Utils/IP.rl" #line 30 "src/Utils/IP.rl"
{ {
ip_family = AF_INET6; ipFamily = AF_INET6;
} }
goto st93; goto st93;
st93: st93:
...@@ -822,7 +822,7 @@ case 93: ...@@ -822,7 +822,7 @@ case 93:
tr121: tr121:
#line 30 "src/Utils/IP.rl" #line 30 "src/Utils/IP.rl"
{ {
ip_family = AF_INET6; ipFamily = AF_INET6;
} }
goto st94; goto st94;
st94: st94:
...@@ -970,7 +970,7 @@ case 62: ...@@ -970,7 +970,7 @@ case 62:
tr85: tr85:
#line 30 "src/Utils/IP.rl" #line 30 "src/Utils/IP.rl"
{ {
ip_family = AF_INET6; ipFamily = AF_INET6;
} }
goto st95; goto st95;
st95: st95:
...@@ -990,7 +990,7 @@ case 95: ...@@ -990,7 +990,7 @@ case 95:
tr122: tr122:
#line 30 "src/Utils/IP.rl" #line 30 "src/Utils/IP.rl"
{ {
ip_family = AF_INET6; ipFamily = AF_INET6;
} }
goto st96; goto st96;
st96: st96:
...@@ -1010,7 +1010,7 @@ case 96: ...@@ -1010,7 +1010,7 @@ case 96:
tr123: tr123:
#line 30 "src/Utils/IP.rl" #line 30 "src/Utils/IP.rl"
{ {
ip_family = AF_INET6; ipFamily = AF_INET6;
} }
goto st97; goto st97;
st97: st97:
...@@ -1156,7 +1156,7 @@ case 69: ...@@ -1156,7 +1156,7 @@ case 69:
tr62: tr62:
#line 30 "src/Utils/IP.rl" #line 30 "src/Utils/IP.rl"
{ {
ip_family = AF_INET6; ipFamily = AF_INET6;
} }
goto st98; goto st98;
st98: st98:
...@@ -1191,7 +1191,7 @@ case 70: ...@@ -1191,7 +1191,7 @@ case 70:
tr53: tr53:
#line 30 "src/Utils/IP.rl" #line 30 "src/Utils/IP.rl"
{ {
ip_family = AF_INET6; ipFamily = AF_INET6;
} }
goto st99; goto st99;
st99: st99:
...@@ -1216,7 +1216,7 @@ case 99: ...@@ -1216,7 +1216,7 @@ case 99:
tr90: tr90:
#line 30 "src/Utils/IP.rl" #line 30 "src/Utils/IP.rl"
{ {
ip_family = AF_INET6; ipFamily = AF_INET6;
} }
goto st100; goto st100;
st100: st100:
...@@ -1240,7 +1240,7 @@ case 100: ...@@ -1240,7 +1240,7 @@ case 100:
tr124: tr124:
#line 30 "src/Utils/IP.rl" #line 30 "src/Utils/IP.rl"
{ {
ip_family = AF_INET6; ipFamily = AF_INET6;
} }
goto st101; goto st101;
st101: st101:
...@@ -1262,7 +1262,7 @@ case 101: ...@@ -1262,7 +1262,7 @@ case 101:
tr126: tr126:
#line 30 "src/Utils/IP.rl" #line 30 "src/Utils/IP.rl"
{ {
ip_family = AF_INET6; ipFamily = AF_INET6;
} }
goto st102; goto st102;
st102: st102:
...@@ -1284,7 +1284,7 @@ case 102: ...@@ -1284,7 +1284,7 @@ case 102:
tr127: tr127:
#line 30 "src/Utils/IP.rl" #line 30 "src/Utils/IP.rl"
{ {
ip_family = AF_INET6; ipFamily = AF_INET6;
} }
goto st103; goto st103;
st103: st103:
...@@ -1311,7 +1311,7 @@ case 71: ...@@ -1311,7 +1311,7 @@ case 71:
tr91: tr91:
#line 30 "src/Utils/IP.rl" #line 30 "src/Utils/IP.rl"
{ {
ip_family = AF_INET6; ipFamily = AF_INET6;
} }
goto st104; goto st104;
st104: st104:
...@@ -1335,7 +1335,7 @@ case 104: ...@@ -1335,7 +1335,7 @@ case 104:
tr128: tr128:
#line 30 "src/Utils/IP.rl" #line 30 "src/Utils/IP.rl"
{ {
ip_family = AF_INET6; ipFamily = AF_INET6;
} }
goto st105; goto st105;
st105: st105:
...@@ -1359,7 +1359,7 @@ case 105: ...@@ -1359,7 +1359,7 @@ case 105:
tr129: tr129:
#line 30 "src/Utils/IP.rl" #line 30 "src/Utils/IP.rl"
{ {
ip_family = AF_INET6; ipFamily = AF_INET6;
} }
goto st106; goto st106;
st106: st106:
...@@ -1383,7 +1383,7 @@ case 106: ...@@ -1383,7 +1383,7 @@ case 106:
tr92: tr92:
#line 30 "src/Utils/IP.rl" #line 30 "src/Utils/IP.rl"
{ {
ip_family = AF_INET6; ipFamily = AF_INET6;
} }
goto st107; goto st107;
st107: st107:
...@@ -1411,7 +1411,7 @@ case 107: ...@@ -1411,7 +1411,7 @@ case 107:
tr130: tr130:
#line 30 "src/Utils/IP.rl" #line 30 "src/Utils/IP.rl"
{ {
ip_family = AF_INET6; ipFamily = AF_INET6;
} }
goto st108; goto st108;
st108: st108:
...@@ -1438,7 +1438,7 @@ case 108: ...@@ -1438,7 +1438,7 @@ case 108:
tr131: tr131:
#line 30 "src/Utils/IP.rl" #line 30 "src/Utils/IP.rl"
{ {
ip_family = AF_INET6; ipFamily = AF_INET6;
} }
goto st109; goto st109;
st109: st109:
...@@ -1462,7 +1462,7 @@ case 109: ...@@ -1462,7 +1462,7 @@ case 109:
tr93: tr93:
#line 30 "src/Utils/IP.rl" #line 30 "src/Utils/IP.rl"
{ {
ip_family = AF_INET6; ipFamily = AF_INET6;
} }
goto st110; goto st110;
st110: st110:
...@@ -1486,7 +1486,7 @@ case 110: ...@@ -1486,7 +1486,7 @@ case 110:
tr94: tr94:
#line 30 "src/Utils/IP.rl" #line 30 "src/Utils/IP.rl"
{ {
ip_family = AF_INET6; ipFamily = AF_INET6;
} }
goto st111; goto st111;
st111: st111:
...@@ -1508,7 +1508,7 @@ case 111: ...@@ -1508,7 +1508,7 @@ case 111:
tr47: tr47:
#line 30 "src/Utils/IP.rl" #line 30 "src/Utils/IP.rl"
{ {
ip_family = AF_INET6; ipFamily = AF_INET6;
} }
goto st112; goto st112;
st112: st112:
...@@ -1533,7 +1533,7 @@ case 112: ...@@ -1533,7 +1533,7 @@ case 112:
tr95: tr95:
#line 30 "src/Utils/IP.rl" #line 30 "src/Utils/IP.rl"
{ {
ip_family = AF_INET6; ipFamily = AF_INET6;
} }
goto st113; goto st113;
st113: st113:
...@@ -1557,7 +1557,7 @@ case 113: ...@@ -1557,7 +1557,7 @@ case 113:
tr132: tr132:
#line 30 "src/Utils/IP.rl" #line 30 "src/Utils/IP.rl"
{ {
ip_family = AF_INET6; ipFamily = AF_INET6;
} }
goto st114; goto st114;
st114: st114:
...@@ -1579,7 +1579,7 @@ case 114: ...@@ -1579,7 +1579,7 @@ case 114:
tr134: tr134:
#line 30 "src/Utils/IP.rl" #line 30 "src/Utils/IP.rl"
{ {
ip_family = AF_INET6; ipFamily = AF_INET6;
} }
goto st115; goto st115;
st115: st115:
...@@ -1601,7 +1601,7 @@ case 115: ...@@ -1601,7 +1601,7 @@ case 115:
tr135: tr135:
#line 30 "src/Utils/IP.rl" #line 30 "src/Utils/IP.rl"
{ {
ip_family = AF_INET6; ipFamily = AF_INET6;
} }
goto st116; goto st116;
st116: st116:
...@@ -1633,7 +1633,7 @@ case 72: ...@@ -1633,7 +1633,7 @@ case 72:
tr96: tr96:
#line 30 "src/Utils/IP.rl" #line 30 "src/Utils/IP.rl"
{ {
ip_family = AF_INET6; ipFamily = AF_INET6;
} }
goto st117; goto st117;
st117: st117:
...@@ -1657,7 +1657,7 @@ case 117: ...@@ -1657,7 +1657,7 @@ case 117:
tr136: tr136:
#line 30 "src/Utils/IP.rl" #line 30 "src/Utils/IP.rl"
{ {
ip_family = AF_INET6; ipFamily = AF_INET6;
} }
goto st118; goto st118;
st118: st118:
...@@ -1681,7 +1681,7 @@ case 118: ...@@ -1681,7 +1681,7 @@ case 118:
tr137: tr137:
#line 30 "src/Utils/IP.rl" #line 30 "src/Utils/IP.rl"
{ {
ip_family = AF_INET6; ipFamily = AF_INET6;
} }
goto st119; goto st119;
st119: st119:
...@@ -1705,7 +1705,7 @@ case 119: ...@@ -1705,7 +1705,7 @@ case 119:
tr97: tr97:
#line 30 "src/Utils/IP.rl" #line 30 "src/Utils/IP.rl"
{ {
ip_family = AF_INET6; ipFamily = AF_INET6;
} }
goto st120; goto st120;
st120: st120:
...@@ -1733,7 +1733,7 @@ case 120: ...@@ -1733,7 +1733,7 @@ case 120:
tr138: tr138:
#line 30 "src/Utils/IP.rl" #line 30 "src/Utils/IP.rl"
{ {
ip_family = AF_INET6; ipFamily = AF_INET6;
} }
goto st121; goto st121;
st121: st121:
...@@ -1760,7 +1760,7 @@ case 121: ...@@ -1760,7 +1760,7 @@ case 121:
tr139: tr139:
#line 30 "src/Utils/IP.rl" #line 30 "src/Utils/IP.rl"
{ {
ip_family = AF_INET6; ipFamily = AF_INET6;
} }
goto st122; goto st122;
st122: st122:
...@@ -1784,7 +1784,7 @@ case 122: ...@@ -1784,7 +1784,7 @@ case 122:
tr98: tr98:
#line 30 "src/Utils/IP.rl" #line 30 "src/Utils/IP.rl"
{ {
ip_family = AF_INET6; ipFamily = AF_INET6;
} }
goto st123; goto st123;
st123: st123:
...@@ -1808,7 +1808,7 @@ case 123: ...@@ -1808,7 +1808,7 @@ case 123:
tr99: tr99:
#line 30 "src/Utils/IP.rl" #line 30 "src/Utils/IP.rl"
{ {
ip_family = AF_INET6; ipFamily = AF_INET6;
} }
goto st124; goto st124;
st124: st124:
...@@ -1830,7 +1830,7 @@ case 124: ...@@ -1830,7 +1830,7 @@ case 124:
tr41: tr41:
#line 30 "src/Utils/IP.rl" #line 30 "src/Utils/IP.rl"
{ {
ip_family = AF_INET6; ipFamily = AF_INET6;
} }
goto st125; goto st125;
st125: st125:
...@@ -1855,7 +1855,7 @@ case 125: ...@@ -1855,7 +1855,7 @@ case 125:
tr100: tr100:
#line 30 "src/Utils/IP.rl" #line 30 "src/Utils/IP.rl"
{ {
ip_family = AF_INET6; ipFamily = AF_INET6;
} }
goto st126; goto st126;
st126: st126:
...@@ -1879,7 +1879,7 @@ case 126: ...@@ -1879,7 +1879,7 @@ case 126:
tr140: tr140:
#line 30 "src/Utils/IP.rl" #line 30 "src/Utils/IP.rl"
{ {
ip_family = AF_INET6; ipFamily = AF_INET6;
} }
goto st127; goto st127;
st127: st127:
...@@ -1901,7 +1901,7 @@ case 127: ...@@ -1901,7 +1901,7 @@ case 127:
tr142: tr142:
#line 30 "src/Utils/IP.rl" #line 30 "src/Utils/IP.rl"
{ {
ip_family = AF_INET6; ipFamily = AF_INET6;
} }
goto st128; goto st128;
st128: st128:
...@@ -1923,7 +1923,7 @@ case 128: ...@@ -1923,7 +1923,7 @@ case 128:
tr143: tr143:
#line 30 "src/Utils/IP.rl" #line 30 "src/Utils/IP.rl"
{ {
ip_family = AF_INET6; ipFamily = AF_INET6;
} }
goto st129; goto st129;
st129: st129:
...@@ -1955,7 +1955,7 @@ case 73: ...@@ -1955,7 +1955,7 @@ case 73:
tr101: tr101:
#line 30 "src/Utils/IP.rl" #line 30 "src/Utils/IP.rl"
{ {
ip_family = AF_INET6; ipFamily = AF_INET6;
} }
goto st130; goto st130;
st130: st130:
...@@ -1979,7 +1979,7 @@ case 130: ...@@ -1979,7 +1979,7 @@ case 130:
tr144: tr144:
#line 30 "src/Utils/IP.rl" #line 30 "src/Utils/IP.rl"
{ {
ip_family = AF_INET6; ipFamily = AF_INET6;
} }
goto st131; goto st131;
st131: st131:
...@@ -2003,7 +2003,7 @@ case 131: ...@@ -2003,7 +2003,7 @@ case 131:
tr145: tr145:
#line 30 "src/Utils/IP.rl" #line 30 "src/Utils/IP.rl"
{ {
ip_family = AF_INET6; ipFamily = AF_INET6;
} }
goto st132; goto st132;
st132: st132:
...@@ -2027,7 +2027,7 @@ case 132: ...@@ -2027,7 +2027,7 @@ case 132:
tr102: tr102:
#line 30 "src/Utils/IP.rl" #line 30 "src/Utils/IP.rl"
{ {
ip_family = AF_INET6; ipFamily = AF_INET6;
} }
goto st133; goto st133;
st133: st133:
...@@ -2055,7 +2055,7 @@ case 133: ...@@ -2055,7 +2055,7 @@ case 133:
tr146: tr146:
#line 30 "src/Utils/IP.rl" #line 30 "src/Utils/IP.rl"
{ {
ip_family = AF_INET6; ipFamily = AF_INET6;
} }
goto st134; goto st134;
st134: st134:
...@@ -2082,7 +2082,7 @@ case 134: ...@@ -2082,7 +2082,7 @@ case 134:
tr147: tr147:
#line 30 "src/Utils/IP.rl" #line 30 "src/Utils/IP.rl"
{ {
ip_family = AF_INET6; ipFamily = AF_INET6;
} }
goto st135; goto st135;
st135: st135:
...@@ -2106,7 +2106,7 @@ case 135: ...@@ -2106,7 +2106,7 @@ case 135:
tr103: tr103:
#line 30 "src/Utils/IP.rl" #line 30 "src/Utils/IP.rl"
{ {
ip_family = AF_INET6; ipFamily = AF_INET6;
} }
goto st136; goto st136;
st136: st136:
...@@ -2130,7 +2130,7 @@ case 136: ...@@ -2130,7 +2130,7 @@ case 136:
tr104: tr104:
#line 30 "src/Utils/IP.rl" #line 30 "src/Utils/IP.rl"
{ {
ip_family = AF_INET6; ipFamily = AF_INET6;
} }
goto st137; goto st137;
st137: st137:
...@@ -2152,7 +2152,7 @@ case 137: ...@@ -2152,7 +2152,7 @@ case 137:
tr35: tr35:
#line 30 "src/Utils/IP.rl" #line 30 "src/Utils/IP.rl"
{ {
ip_family = AF_INET6; ipFamily = AF_INET6;
} }
goto st138; goto st138;
st138: st138:
...@@ -2177,7 +2177,7 @@ case 138: ...@@ -2177,7 +2177,7 @@ case 138:
tr105: tr105:
#line 30 "src/Utils/IP.rl" #line 30 "src/Utils/IP.rl"
{ {
ip_family = AF_INET6; ipFamily = AF_INET6;
} }
goto st139; goto st139;
st139: st139:
...@@ -2201,7 +2201,7 @@ case 139: ...@@ -2201,7 +2201,7 @@ case 139:
tr148: tr148:
#line 30 "src/Utils/IP.rl" #line 30 "src/Utils/IP.rl"
{ {
ip_family = AF_INET6; ipFamily = AF_INET6;
} }
goto st140; goto st140;
st140: st140:
...@@ -2223,7 +2223,7 @@ case 140: ...@@ -2223,7 +2223,7 @@ case 140:
tr150: tr150:
#line 30 "src/Utils/IP.rl" #line 30 "src/Utils/IP.rl"
{ {
ip_family = AF_INET6; ipFamily = AF_INET6;
} }
goto st141; goto st141;
st141: st141:
...@@ -2245,7 +2245,7 @@ case 141: ...@@ -2245,7 +2245,7 @@ case 141:
tr151: tr151:
#line 30 "src/Utils/IP.rl" #line 30 "src/Utils/IP.rl"
{ {
ip_family = AF_INET6; ipFamily = AF_INET6;
} }
goto st142; goto st142;
st142: st142:
...@@ -2277,7 +2277,7 @@ case 74: ...@@ -2277,7 +2277,7 @@ case 74:
tr106: tr106:
#line 30 "src/Utils/IP.rl" #line 30 "src/Utils/IP.rl"
{ {
ip_family = AF_INET6; ipFamily = AF_INET6;
} }
goto st143; goto st143;
st143: st143:
...@@ -2301,7 +2301,7 @@ case 143: ...@@ -2301,7 +2301,7 @@ case 143:
tr152: tr152:
#line 30 "src/Utils/IP.rl" #line 30 "src/Utils/IP.rl"
{ {
ip_family = AF_INET6; ipFamily = AF_INET6;
} }
goto st144; goto st144;
st144: st144:
...@@ -2325,7 +2325,7 @@ case 144: ...@@ -2325,7 +2325,7 @@ case 144:
tr153: tr153:
#line 30 "src/Utils/IP.rl" #line 30 "src/Utils/IP.rl"
{ {
ip_family = AF_INET6; ipFamily = AF_INET6;
} }
goto st145; goto st145;
st145: st145:
...@@ -2349,7 +2349,7 @@ case 145: ...@@ -2349,7 +2349,7 @@ case 145:
tr107: tr107:
#line 30 "src/Utils/IP.rl" #line 30 "src/Utils/IP.rl"
{ {
ip_family = AF_INET6; ipFamily = AF_INET6;
} }
goto st146; goto st146;
st146: st146:
...@@ -2377,7 +2377,7 @@ case 146: ...@@ -2377,7 +2377,7 @@ case 146:
tr154: tr154:
#line 30 "src/Utils/IP.rl" #line 30 "src/Utils/IP.rl"
{ {
ip_family = AF_INET6; ipFamily = AF_INET6;
} }
goto st147; goto st147;
st147: st147:
...@@ -2404,7 +2404,7 @@ case 147: ...@@ -2404,7 +2404,7 @@ case 147:
tr155: tr155:
#line 30 "src/Utils/IP.rl" #line 30 "src/Utils/IP.rl"
{ {
ip_family = AF_INET6; ipFamily = AF_INET6;
} }
goto st148; goto st148;
st148: st148:
...@@ -2428,7 +2428,7 @@ case 148: ...@@ -2428,7 +2428,7 @@ case 148:
tr108: tr108:
#line 30 "src/Utils/IP.rl" #line 30 "src/Utils/IP.rl"
{ {
ip_family = AF_INET6; ipFamily = AF_INET6;
} }
goto st149; goto st149;
st149: st149:
...@@ -2452,7 +2452,7 @@ case 149: ...@@ -2452,7 +2452,7 @@ case 149:
tr109: tr109:
#line 30 "src/Utils/IP.rl" #line 30 "src/Utils/IP.rl"
{ {
ip_family = AF_INET6; ipFamily = AF_INET6;
} }
goto st150; goto st150;
st150: st150:
...@@ -2474,7 +2474,7 @@ case 150: ...@@ -2474,7 +2474,7 @@ case 150:
tr29: tr29:
#line 30 "src/Utils/IP.rl" #line 30 "src/Utils/IP.rl"
{ {
ip_family = AF_INET6; ipFamily = AF_INET6;
} }
goto st151; goto st151;
st151: st151:
...@@ -2499,7 +2499,7 @@ case 151: ...@@ -2499,7 +2499,7 @@ case 151:
tr115: tr115:
#line 30 "src/Utils/IP.rl" #line 30 "src/Utils/IP.rl"
{ {
ip_family = AF_INET6; ipFamily = AF_INET6;
} }
goto st152; goto st152;
st152: st152:
...@@ -2523,7 +2523,7 @@ case 152: ...@@ -2523,7 +2523,7 @@ case 152:
tr156: tr156:
#line 30 "src/Utils/IP.rl" #line 30 "src/Utils/IP.rl"
{ {
ip_family = AF_INET6; ipFamily = AF_INET6;
} }
goto st153; goto st153;
st153: st153:
...@@ -2545,7 +2545,7 @@ case 153: ...@@ -2545,7 +2545,7 @@ case 153:
tr158: tr158:
#line 30 "src/Utils/IP.rl" #line 30 "src/Utils/IP.rl"
{ {
ip_family = AF_INET6; ipFamily = AF_INET6;
} }
goto st154; goto st154;
st154: st154:
...@@ -2567,7 +2567,7 @@ case 154: ...@@ -2567,7 +2567,7 @@ case 154:
tr159: tr159:
#line 30 "src/Utils/IP.rl" #line 30 "src/Utils/IP.rl"
{ {
ip_family = AF_INET6; ipFamily = AF_INET6;
} }
goto st155; goto st155;
st155: st155:
...@@ -2599,7 +2599,7 @@ case 75: ...@@ -2599,7 +2599,7 @@ case 75:
tr116: tr116:
#line 30 "src/Utils/IP.rl" #line 30 "src/Utils/IP.rl"
{ {
ip_family = AF_INET6; ipFamily = AF_INET6;
} }
goto st156; goto st156;
st156: st156:
...@@ -2623,7 +2623,7 @@ case 156: ...@@ -2623,7 +2623,7 @@ case 156:
tr160: tr160:
#line 30 "src/Utils/IP.rl" #line 30 "src/Utils/IP.rl"
{ {
ip_family = AF_INET6; ipFamily = AF_INET6;
} }
goto st157; goto st157;
st157: st157:
...@@ -2647,7 +2647,7 @@ case 157: ...@@ -2647,7 +2647,7 @@ case 157:
tr161: tr161:
#line 30 "src/Utils/IP.rl" #line 30 "src/Utils/IP.rl"
{ {
ip_family = AF_INET6; ipFamily = AF_INET6;
} }
goto st158; goto st158;
st158: st158:
...@@ -2671,7 +2671,7 @@ case 158: ...@@ -2671,7 +2671,7 @@ case 158:
tr117: tr117:
#line 30 "src/Utils/IP.rl" #line 30 "src/Utils/IP.rl"
{ {
ip_family = AF_INET6; ipFamily = AF_INET6;
} }
goto st159; goto st159;
st159: st159:
...@@ -2699,7 +2699,7 @@ case 159: ...@@ -2699,7 +2699,7 @@ case 159:
tr162: tr162:
#line 30 "src/Utils/IP.rl" #line 30 "src/Utils/IP.rl"
{ {
ip_family = AF_INET6; ipFamily = AF_INET6;
} }
goto st160; goto st160;
st160: st160:
...@@ -2726,7 +2726,7 @@ case 160: ...@@ -2726,7 +2726,7 @@ case 160:
tr163: tr163:
#line 30 "src/Utils/IP.rl" #line 30 "src/Utils/IP.rl"
{ {
ip_family = AF_INET6; ipFamily = AF_INET6;
} }
goto st161; goto st161;
st161: st161:
...@@ -2750,7 +2750,7 @@ case 161: ...@@ -2750,7 +2750,7 @@ case 161:
tr118: tr118:
#line 30 "src/Utils/IP.rl" #line 30 "src/Utils/IP.rl"
{ {
ip_family = AF_INET6; ipFamily = AF_INET6;
} }
goto st162; goto st162;
st162: st162:
...@@ -2774,7 +2774,7 @@ case 162: ...@@ -2774,7 +2774,7 @@ case 162:
tr119: tr119:
#line 30 "src/Utils/IP.rl" #line 30 "src/Utils/IP.rl"
{ {
ip_family = AF_INET6; ipFamily = AF_INET6;
} }
goto st163; goto st163;
st163: st163:
...@@ -2929,7 +2929,7 @@ case 83: ...@@ -2929,7 +2929,7 @@ case 83:
tr114: tr114:
#line 30 "src/Utils/IP.rl" #line 30 "src/Utils/IP.rl"
{ {
ip_family = AF_INET6; ipFamily = AF_INET6;
} }
goto st164; goto st164;
st164: st164:
...@@ -2954,7 +2954,7 @@ case 164: ...@@ -2954,7 +2954,7 @@ case 164:
tr164: tr164:
#line 30 "src/Utils/IP.rl" #line 30 "src/Utils/IP.rl"
{ {
ip_family = AF_INET6; ipFamily = AF_INET6;
} }
goto st165; goto st165;
st165: st165:
...@@ -2978,7 +2978,7 @@ case 165: ...@@ -2978,7 +2978,7 @@ case 165:
tr169: tr169:
#line 30 "src/Utils/IP.rl" #line 30 "src/Utils/IP.rl"
{ {
ip_family = AF_INET6; ipFamily = AF_INET6;
} }
goto st166; goto st166;
st166: st166:
...@@ -3000,7 +3000,7 @@ case 166: ...@@ -3000,7 +3000,7 @@ case 166:
tr171: tr171:
#line 30 "src/Utils/IP.rl" #line 30 "src/Utils/IP.rl"
{ {
ip_family = AF_INET6; ipFamily = AF_INET6;
} }
goto st167; goto st167;
st167: st167:
...@@ -3022,7 +3022,7 @@ case 167: ...@@ -3022,7 +3022,7 @@ case 167:
tr172: tr172:
#line 30 "src/Utils/IP.rl" #line 30 "src/Utils/IP.rl"
{ {
ip_family = AF_INET6; ipFamily = AF_INET6;
} }
goto st168; goto st168;
st168: st168:
...@@ -3054,7 +3054,7 @@ case 84: ...@@ -3054,7 +3054,7 @@ case 84:
tr165: tr165:
#line 30 "src/Utils/IP.rl" #line 30 "src/Utils/IP.rl"
{ {
ip_family = AF_INET6; ipFamily = AF_INET6;
} }
goto st169; goto st169;
st169: st169:
...@@ -3078,7 +3078,7 @@ case 169: ...@@ -3078,7 +3078,7 @@ case 169:
tr173: tr173:
#line 30 "src/Utils/IP.rl" #line 30 "src/Utils/IP.rl"
{ {
ip_family = AF_INET6; ipFamily = AF_INET6;
} }
goto st170; goto st170;
st170: st170:
...@@ -3102,7 +3102,7 @@ case 170: ...@@ -3102,7 +3102,7 @@ case 170:
tr174: tr174:
#line 30 "src/Utils/IP.rl" #line 30 "src/Utils/IP.rl"
{ {
ip_family = AF_INET6; ipFamily = AF_INET6;
} }
goto st171; goto st171;
st171: st171:
...@@ -3126,7 +3126,7 @@ case 171: ...@@ -3126,7 +3126,7 @@ case 171:
tr166: tr166:
#line 30 "src/Utils/IP.rl" #line 30 "src/Utils/IP.rl"
{ {
ip_family = AF_INET6; ipFamily = AF_INET6;
} }
goto st172; goto st172;
st172: st172:
...@@ -3154,7 +3154,7 @@ case 172: ...@@ -3154,7 +3154,7 @@ case 172:
tr175: tr175:
#line 30 "src/Utils/IP.rl" #line 30 "src/Utils/IP.rl"
{ {
ip_family = AF_INET6; ipFamily = AF_INET6;
} }
goto st173; goto st173;
st173: st173:
...@@ -3181,7 +3181,7 @@ case 173: ...@@ -3181,7 +3181,7 @@ case 173:
tr176: tr176:
#line 30 "src/Utils/IP.rl" #line 30 "src/Utils/IP.rl"
{ {
ip_family = AF_INET6; ipFamily = AF_INET6;
} }
goto st174; goto st174;
st174: st174:
...@@ -3205,7 +3205,7 @@ case 174: ...@@ -3205,7 +3205,7 @@ case 174:
tr167: tr167:
#line 30 "src/Utils/IP.rl" #line 30 "src/Utils/IP.rl"
{ {
ip_family = AF_INET6; ipFamily = AF_INET6;
} }
goto st175; goto st175;
st175: st175:
...@@ -3229,7 +3229,7 @@ case 175: ...@@ -3229,7 +3229,7 @@ case 175:
tr168: tr168:
#line 30 "src/Utils/IP.rl" #line 30 "src/Utils/IP.rl"
{ {
ip_family = AF_INET6; ipFamily = AF_INET6;
} }
goto st176; goto st176;
st176: st176:
...@@ -3448,7 +3448,7 @@ case 85: ...@@ -3448,7 +3448,7 @@ case 85:
// Ensure that the parsing has consumed all the given length. // Ensure that the parsing has consumed all the given length.
if (ip_len == (size_t)(p - (const unsigned char*)ip)) if (ip_len == (size_t)(p - (const unsigned char*)ip))
return ip_family; return ipFamily;
else else
return AF_UNSPEC; return AF_UNSPEC;
} }
...@@ -3464,9 +3464,12 @@ case 85: ...@@ -3464,9 +3464,12 @@ case 85:
{ {
case AF_INET: case AF_INET:
{ {
err = uv_inet_ntop(AF_INET, &((struct sockaddr_in*)addr)->sin_addr, _ip, INET_ADDRSTRLEN); err = uv_inet_ntop(AF_INET, &((struct sockaddr_in*)addr)->sin_addr, _ip,
INET_ADDRSTRLEN);
if (err) if (err)
MS_ABORT("uv_inet_ntop() failed: %s", uv_strerror(err)); MS_ABORT("uv_inet_ntop() failed: %s", uv_strerror(err));
*port = (uint16_t)ntohs(((struct sockaddr_in*)addr)->sin_port); *port = (uint16_t)ntohs(((struct sockaddr_in*)addr)->sin_port);
break; break;
...@@ -3474,9 +3477,12 @@ case 85: ...@@ -3474,9 +3477,12 @@ case 85:
case AF_INET6: case AF_INET6:
{ {
err = uv_inet_ntop(AF_INET6, &((struct sockaddr_in6*)addr)->sin6_addr, _ip, INET6_ADDRSTRLEN); err = uv_inet_ntop(AF_INET6, &((struct sockaddr_in6*)addr)->sin6_addr, _ip,
INET6_ADDRSTRLEN);
if (err) if (err)
MS_ABORT("uv_inet_ntop() failed: %s", uv_strerror(err)); MS_ABORT("uv_inet_ntop() failed: %s", uv_strerror(err));
*port = (uint16_t)ntohs(((struct sockaddr_in6*)addr)->sin6_port); *port = (uint16_t)ntohs(((struct sockaddr_in6*)addr)->sin6_port);
break; break;
......
...@@ -11,7 +11,7 @@ namespace Utils ...@@ -11,7 +11,7 @@ namespace Utils
{ {
MS_TRACE(); MS_TRACE();
int ip_family = 0; int ipFamily = 0;
/** /**
* Ragel: machine definition. * Ragel: machine definition.
...@@ -23,12 +23,12 @@ namespace Utils ...@@ -23,12 +23,12 @@ namespace Utils
action on_ipv4 action on_ipv4
{ {
ip_family = AF_INET; ipFamily = AF_INET;
} }
action on_ipv6 action on_ipv6
{ {
ip_family = AF_INET6; ipFamily = AF_INET6;
} }
include grammar "grammar.rl"; include grammar "grammar.rl";
...@@ -64,7 +64,7 @@ namespace Utils ...@@ -64,7 +64,7 @@ namespace Utils
// Ensure that the parsing has consumed all the given length. // Ensure that the parsing has consumed all the given length.
if (ip_len == (size_t)(p - (const unsigned char*)ip)) if (ip_len == (size_t)(p - (const unsigned char*)ip))
return ip_family; return ipFamily;
else else
return AF_UNSPEC; return AF_UNSPEC;
} }
...@@ -80,9 +80,12 @@ namespace Utils ...@@ -80,9 +80,12 @@ namespace Utils
{ {
case AF_INET: case AF_INET:
{ {
err = uv_inet_ntop(AF_INET, &((struct sockaddr_in*)addr)->sin_addr, _ip, INET_ADDRSTRLEN); err = uv_inet_ntop(AF_INET, &((struct sockaddr_in*)addr)->sin_addr, _ip,
INET_ADDRSTRLEN);
if (err) if (err)
MS_ABORT("uv_inet_ntop() failed: %s", uv_strerror(err)); MS_ABORT("uv_inet_ntop() failed: %s", uv_strerror(err));
*port = (uint16_t)ntohs(((struct sockaddr_in*)addr)->sin_port); *port = (uint16_t)ntohs(((struct sockaddr_in*)addr)->sin_port);
break; break;
...@@ -90,9 +93,12 @@ namespace Utils ...@@ -90,9 +93,12 @@ namespace Utils
case AF_INET6: case AF_INET6:
{ {
err = uv_inet_ntop(AF_INET6, &((struct sockaddr_in6*)addr)->sin6_addr, _ip, INET6_ADDRSTRLEN); err = uv_inet_ntop(AF_INET6, &((struct sockaddr_in6*)addr)->sin6_addr, _ip,
INET6_ADDRSTRLEN);
if (err) if (err)
MS_ABORT("uv_inet_ntop() failed: %s", uv_strerror(err)); MS_ABORT("uv_inet_ntop() failed: %s", uv_strerror(err));
*port = (uint16_t)ntohs(((struct sockaddr_in6*)addr)->sin6_port); *port = (uint16_t)ntohs(((struct sockaddr_in6*)addr)->sin6_port);
break; break;
......
...@@ -36,6 +36,7 @@ int main(int argc, char* argv[]) ...@@ -36,6 +36,7 @@ int main(int argc, char* argv[])
if (argc == 1 || !std::getenv("MEDIASOUP_CHANNEL_FD")) if (argc == 1 || !std::getenv("MEDIASOUP_CHANNEL_FD"))
{ {
std::cerr << "ERROR: you don't seem to be my real father" << std::endl; std::cerr << "ERROR: you don't seem to be my real father" << std::endl;
std::_Exit(EXIT_FAILURE); std::_Exit(EXIT_FAILURE);
} }
...@@ -68,19 +69,19 @@ int main(int argc, char* argv[]) ...@@ -68,19 +69,19 @@ int main(int argc, char* argv[])
MS_DEBUG_TAG(info, "starting " MS_PROCESS_NAME " [pid:%ld]", (long)getpid()); MS_DEBUG_TAG(info, "starting " MS_PROCESS_NAME " [pid:%ld]", (long)getpid());
#if defined(MS_LITTLE_ENDIAN) #if defined(MS_LITTLE_ENDIAN)
MS_DEBUG_TAG(info, "Little-Endian CPU detected"); MS_DEBUG_TAG(info, "Little-Endian CPU detected");
#elif defined(MS_BIG_ENDIAN) #elif defined(MS_BIG_ENDIAN)
MS_DEBUG_TAG(info, "Big-Endian CPU detected"); MS_DEBUG_TAG(info, "Big-Endian CPU detected");
#endif #endif
#if defined(INTPTR_MAX) && defined(INT32_MAX) && (INTPTR_MAX == INT32_MAX) #if defined(INTPTR_MAX) && defined(INT32_MAX) && (INTPTR_MAX == INT32_MAX)
MS_DEBUG_TAG(info, "32 bits architecture detected"); MS_DEBUG_TAG(info, "32 bits architecture detected");
#elif defined(INTPTR_MAX) && defined(INT64_MAX) && (INTPTR_MAX == INT64_MAX) #elif defined(INTPTR_MAX) && defined(INT64_MAX) && (INTPTR_MAX == INT64_MAX)
MS_DEBUG_TAG(info, "64 bits architecture detected"); MS_DEBUG_TAG(info, "64 bits architecture detected");
#else #else
MS_WARN_TAG(info, "can not determine whether the architecture is 32 or 64 bits"); MS_WARN_TAG(info, "can not determine whether the architecture is 32 or 64 bits");
#endif #endif
try try
{ {
...@@ -95,9 +96,9 @@ int main(int argc, char* argv[]) ...@@ -95,9 +96,9 @@ int main(int argc, char* argv[])
} }
catch (const MediaSoupError &error) catch (const MediaSoupError &error)
{ {
destroy();
MS_ERROR_STD("failure exit: %s", error.what()); MS_ERROR_STD("failure exit: %s", error.what());
destroy();
exitWithError(); exitWithError();
} }
} }
...@@ -107,7 +108,6 @@ void init() ...@@ -107,7 +108,6 @@ void init()
MS_TRACE(); MS_TRACE();
ignoreSignals(); ignoreSignals();
DepLibUV::PrintVersion(); DepLibUV::PrintVersion();
// Initialize static stuff. // Initialize static stuff.
...@@ -127,7 +127,7 @@ void ignoreSignals() ...@@ -127,7 +127,7 @@ void ignoreSignals()
int err; int err;
struct sigaction act; struct sigaction act;
std::map<std::string, int> ignored_signals = std::map<std::string, int> ignoredSignals =
{ {
{ "PIPE", SIGPIPE }, { "PIPE", SIGPIPE },
{ "HUP", SIGHUP }, { "HUP", SIGHUP },
...@@ -142,14 +142,17 @@ void ignoreSignals() ...@@ -142,14 +142,17 @@ void ignoreSignals()
if (err) if (err)
MS_THROW_ERROR("sigfillset() failed: %s", std::strerror(errno)); MS_THROW_ERROR("sigfillset() failed: %s", std::strerror(errno));
for (auto it = ignored_signals.begin(); it != ignored_signals.end(); ++it) for (auto it = ignoredSignals.begin(); it != ignoredSignals.end(); ++it)
{ {
auto& sig_name = it->first; auto& sigName = it->first;
int sig_id = it->second; int sigId = it->second;
err = sigaction(sig_id, &act, nullptr); err = sigaction(sigId, &act, nullptr);
if (err) if (err)
MS_THROW_ERROR("sigaction() failed for signal %s: %s", sig_name.c_str(), std::strerror(errno)); {
MS_THROW_ERROR("sigaction() failed for signal %s: %s",
sigName.c_str(), std::strerror(errno));
}
} }
} }
...@@ -169,7 +172,6 @@ void exitSuccess() ...@@ -169,7 +172,6 @@ void exitSuccess()
{ {
// Wait a bit so peding messages to stdout/Channel arrive to the main process. // Wait a bit so peding messages to stdout/Channel arrive to the main process.
usleep(100000); usleep(100000);
// And exit with success status. // And exit with success status.
std::_Exit(EXIT_SUCCESS); std::_Exit(EXIT_SUCCESS);
} }
...@@ -178,7 +180,6 @@ void exitWithError() ...@@ -178,7 +180,6 @@ void exitWithError()
{ {
// Wait a bit so peding messages to stderr arrive to the main process. // Wait a bit so peding messages to stderr arrive to the main process.
usleep(100000); usleep(100000);
// And exit with error status. // And exit with error status.
std::_Exit(EXIT_FAILURE); std::_Exit(EXIT_FAILURE);
} }
Markdown 格式
0% 或
您添加了 0 人 到此讨论。请谨慎行事。
请先完成此评论的编辑!
请 注册 或者 后发表评论