提交 9f61393d authored 作者: Iñaki Baz Castillo's avatar Iñaki Baz Castillo

"First" commit (not really, but you know...).

上级
*.o
/bin/
/etc/mediasoup.cfg
/etc/*.pem
/mediasoup-tester.sh
program_NAME := mediasoup
#
# Compiler
#
# CXX = g++-4.8
# CXX = g++-4.9 -fdiagnostics-color=auto
# CXX = clang++
#
# CXXFLAGS Options
# Comment/uncomment them during development.
#
DO_DEBUG_SYMBOLS := -g
# DO_SANITIZE := -fsanitize=thread -fPIE -pie
# DO_OPTIMIZE := -O3
# DO_PEDANTIC := -pedantic -Wno-gnu-zero-variadic-macro-arguments
#
CXXFLAGS += $(DO_DEBUG_SYMBOLS) $(DO_SANITIZE) $(DO_OPTIMIZE) $(DO_PEDANTIC)
#
# CXXFLAGS custom macros
# Added to the CXXFLAGS exported variable (before running make).
#
# -DMS_DEVEL enables MS_TRACE().
#
# Settings.
#
# Directory where the executable will be placed.
program_BIN_DIR := ./bin
# Directories containing program header files.
program_INCLUDE_DIRS := ./include
# External libraries with pkg-config support.
program_PKG_LIBRARIES = libuv >= 1.0.2, libconfig++ >= 1.4.8, openssl >= 1.0.1, libsrtp >= 1.5.1
# Other libraries to link with (don't put here those libs having pkg-config file).
program_OTHER_LIBRARIES := pthread
# Directories where search for other libraries.
# program_OTHER_LIBRARIES_DIRS := /usr/local/lib
# Directories containing other libraries header files.
# program_OTHER_LIBRARIES_INCLUDE_DIRS := /usr/local/include
# All the .cpp files.
program_CXX_SRCS := $(wildcard src/*.cpp src/*/*.cpp src/*/*/*.cpp src/*/*/*/*.cpp src/*/*/*/*/*.cpp)
# C++ object files to build.
program_CXX_OBJS := ${program_CXX_SRCS:.cpp=.o}
# Get all the .o files under src. Useful for 'make clean' as objects belinging to
# already deleted source files are also deleted.
program_all_CXX_OBJS = $(wildcard src/*.o src/*/*.o src/*/*/*.o src/*/*/*/*.o src/*/*/*/*/*.o)
# CPPFLAGS is the C preprocessor flags, so anything that compiles a C or C++ source
# file into an object file will use this flag.
# This adds -I$(includedir) for every include directory in $(program_INCLUDE_DIRS) and
# $(program_OTHER_LIBRARIES_INCLUDE_DIRS).
CPPFLAGS += $(foreach includedir, $(program_INCLUDE_DIRS), -I$(includedir))
CPPFLAGS += $(foreach includedir, $(program_OTHER_LIBRARIES_INCLUDE_DIRS), -I$(includedir))
# CXXFLAGS gives a list of flags that should be passed to the C++ compiler (use
# this, for example, to set the version of the C++ language, to specify the
# warning settings, or for other options specific to the C++ compiler).
CXXFLAGS += -std=c++11 -Wall
# LDFLAGS are used when linking, this will cause the appropriate flags to
# be passed to the linker.
# This adds -L$(librarydir) for every library directory given in $(program_OTHER_LIBRARIES_DIRS)
# and -l$(library) for every library given in $(program_OTHER_LIBRARIES).
LDFLAGS += $(foreach librarydir, $(program_OTHER_LIBRARIES_DIRS), -L$(librarydir))
LDFLAGS += $(foreach library, $(program_OTHER_LIBRARIES), -l$(library))
# Add flags required by external libraries with pkg-config support.
CPPFLAGS += $(shell pkg-config --cflags "$(program_PKG_LIBRARIES)")
LDFLAGS += $(shell pkg-config --libs "$(program_PKG_LIBRARIES)")
#
# Targets
#
# This indicates that "all", program_NAME, "check_pkg_libraries" and "clean" are
# "phony targets". Therefore calling "make XXXX" should execute the content of its
# build rules, even if a newer file named "XXXX" exists.
.PHONY: all $(program_NAME) check_pkg_libraries clean distclean
# This is first build rule in the Makefile, and so executing "make" and executing
# "make all" are the same. The target simply depends on $(program_NAME).
all: $(program_NAME)
# The program depends on the object files (which are automatically built using the
# predefined build rules, nothing needs to be given explicitly for them).
# The build rule $(LINK.cc) is used to link the object files and output a file with
# the same name as the program. Note that LINK.cc makes use of CXX, CXXFLAGS,
# LFLAGS, etc. LINK.cc is usually defined as: $(CXX) $(CXXFLAGS) $(CPPFLAGS)
# $(LDFLAGS) $(TARGET_ARCH).
$(program_NAME): check_pkg_libraries $(program_CXX_OBJS)
mkdir -p $(program_BIN_DIR)
$(LINK.cc) $(program_CXX_OBJS) -o $(program_BIN_DIR)/$(program_NAME)
# Check the required libraries with pkg-support.
check_pkg_libraries:
pkg-config --exists --print-errors "$(program_PKG_LIBRARIES)"
# This target removes the built program and the generated object files. The @ symbol
# indicates that the line should be run silently, and the - symbol indicates that
# errors should be ignored (i.e., the file already doesn't exist).
clean:
@- $(RM) $(program_NAME)
@- $(RM) $(program_all_CXX_OBJS)
# MediaSoup
Flexible and powerful multi-stream media server ready for [WebRTC](http://www.webrtc.org/) and other RTP based technologies.
## IMPORTANT!
* Not ready yet. Work must be done on the *ControlProtocol* and the high level API in order to make MediaSoup usable. Working on it.
## Features
* Supports *WebRTC* media requirements ([ICE-Lite](http://tools.ietf.org/html/rfc5245), [DTLS-SRTP](http://tools.ietf.org/html/rfc5764), [rtcp-mux](http://tools.ietf.org/html/rfc5761), [bundle](http://tools.ietf.org/html/draft-ietf-mmusic-sdp-bundle-negotiation)) along with classic VoIP technologies ([SDES-SRTP](http://tools.ietf.org/html/rfc4568), plain [RTP/RTCP](http://tools.ietf.org/html/rfc3550)).
* ICE/DTLS/RTP/RTCP over UDP and TCP.
* Multi participant real-time sessions.
* IPv6 ready.
* Signaling agnostic. MediaSoup does not deal with SIP or other signaling protocols. In the other side, it can deal with *any* signaling protocol.
* SDP unaware. Really, MediaSoup will not parse a SDP for you.
* Just media. MediaSoup cares about media processing so it relies on an external application which deals with your preferred signaling protocol and manages MediaSoup by using the *MediaSoup ControlProtocol*.
* Extremely powerful. MediaSoup is coded in C++ on top of the awesome [libuv](https://github.com/libuv/libuv) asychronous I/O library. MediaSoup is a single process application with multiple *Worker* threads for media handling. MediaSoup takes full advantage of your CPU capabilities.
## Dependencies
* [libuv](https://github.com/libuv/libuv): Cross-platform asychronous I/O C library. Version ~1.0.2 required.
* [libconfig](http://www.hyperrealm.com/libconfig/): C/C++ library for processing configuration files. Version ~1.4.8 required.
* [openssl](https://www.openssl.org). Version >=1.0.1 required.
* [libsrtp](https://github.com/cisco/libsrtp). Version >=1.5.0 required.
## Requirements
MediaSoup runs in any Posix system (tested in Linux Debian 7 "Wheezy" and OSX 10.9 "Mavericks") in both 32 or 64 bits architectures (Big or Little Endian).
MediaSoup requires *C++11* and other features available in *gcc* >= 4.7 or *clang* >= 5.
## Installation
* Install dependencies (see above).
* Compile MediaSoup:
```
$ make
```
*TODO:* `make install`, `make test`, etc still missing.
## Running MediaSoup
The `mediasoup` binary is placed at the `bin/` directory. For help on its usage run it with `-h` or `--help`:
```
$ ./bin/mediasoup --help
MediaSoup v0.0.1
Copyright (c) 2014 Iñaki Baz Castillo | https://github.com/ibc
Usage: mediasoup [options]
Options:
-c, --configfile FILE Path to the configuration file
-d, --daemonize Run in daemon mode
-p, --pidfile FILE Create a PID file (requires daemon mode)
-u, --user USER Run with the given system user
-g, --group GROUP Run with the given system group
-v, --version Show version
-h, --help Show this message
```
An example configuration file is provided at `etc/mediasoup.default.cfg`. Rename it to `mediasoup.cfg` and edit it as per your needs.
### Reloading MediaSoup
Once it is running MediaSoup configuration can be reload by sending a *SIGUSR1* signal to the process:
```
$ kill -USR1 $(pidof mediasoup)
```
NOTE: Just certain options in the configuration file are reloaded (currently just *logLevel*).
## Documentation
[MediaSoup Documentation](docs/index.md) is placed in the `docs/` folder.
## License
Not decided yet. For now "All Rights Reserved" (will be changed when ready).
# ControlProtocol
The MediaSoup ControlProtocol is a bidirectional protocol to manage MediaSoup and multimedia sessions.
## Definitions
### ControlProtocol Request
A message which typically expects a Response.
### ControlProtocol Response
A message which is the response to a Request.
### ControlProtocol Notification
A message that does not expect a Response and its not a Response.
## Message Types
### Request
Every ControlProtocol Request conforms to the following syntax (note that CRLF means "\r\n" symbols):
```
Request type CRLF
uuid CRLF
*(key: value CRLF)
CRLF
```
where:
* *Request* is the "Request" literal string.
* *type* is a string indicating a valid ControlProtocol Request type.
* *uuid* is the integer identifier for this transaction (max length: 9 digits).
* *key* is a string indicating a parameter name.
* *value* is a string representing the value for a parameter.
### Response
Every ControlProtocol Response conforms to the following syntax (note that CRLF means "\r\n" symbols):
```
Response type CRLF
uuid status CRLF
[code: error_code CRLF]
[reason: error_reason CRLF]
*(key: value CRLF)
CRLF
```
where:
* *Response* is the "Response" literal string.
* *type* is a string indicating the type of the Request this Response is for.
* *uuid* matches the value in the Request.
* *status* is the "OK" or "ERROR" literal string.
* *code* is string indicating the exact error.
* *reason* is a descriptive string for the error.
* *key* is a string indicating a parameter name.
* *value* is a string representing the value for a parameter.
### Notification
Every ControlProtocol Notification conforms to the following syntax (note that CRLF means "\r\n" symbols):
```
Notification type CRLF
*(key: value CRLF)
CRLF
```
where:
* *Notification* is the "Notification" literal string.
* *type* is a string indicating a valid ControlProtocol Notification type.
* *key* is a string indicating a parameter name.
* *value* is a string representing the value for a parameter.
# Overview
## Definitions
### MediaSoup
The media server itself is a single process internally comprised of two main components: the *Dispatcher* and *Workers*.
### MediaSoup ControlProtocol
The MediaSoup [ControlProtocol](./ControlProtocol.md) is a bidirectional protocol to manage MediaSoup and multimedia sessions.
### Controller
The Controller is a separate application (not provided by MediaSoup) that can run in the same or a different host. The Controller manages the signaling protocol (for example SIP in case the Controller is a SIP proxy/server) and communicates with MediaSoup by using the MediaSoup [ControlProtocol](./ControlProtocol.md) over a TCP connection.
By using the MediaSoup ControlProtocol, the Controller requests MediaSoup to create multimedia sessions by providing MediaSoup with the required media information (this is, the media information of the remote peer) and receiving from MediaSoup its media information to be transmitted to the remote peer.
The Controller can generate multiparticipant sessions (let's say multi-conferences) or single sessions between two remote participants that communicate through MediaSoup (for example having MediaSoup behaving as a media gateway between a WebRTC endpoint and a legacy SIP device).
Multiple Controllers can communicate with the same instance of MediaSoup.
### MediaSoup Dispatcher
The Dispatcher is the MediaSoup component that listens for messages from Controllers and sends messages back to them when appropriate. The messages exchanged between both a Controller and the Dispatcher conform to the MediaSoup [ControlProtocol](./ControlProtocol.md).
The Dispatcher also uses the MediaSoup ControlProtocol to communicate with the MediaSoup Workers.
### MediaSoup Worker
An instance of MediaSoup runs N Workers instances (N is typically the number of cores detected in the host). A Worker manages multimedia sessions by handling the RTP, RTCP, ICE, DTLS and so on. A MediaSoup session (let it be a single session of two participants or a multiparticipant session) is handled by a single Worker, but a Worker can handle more than one session.
The MediaSoup Dispatcher communicates with the MediaSoup Workers (and vice-versa) by sending MediaSoup [ControlProtocol](./ControlProtocol.md) messages over UNIX sockets. The Dispatcher runs a separate communication channel with each Worker.
# MediaSoup Documentation
* [Overview](./Overview.md)
* [ControlProtocol](./ControlProtocol.md)
# Log level
# - Values: "debug", "info", "notice", "warning", "error" (double quoted)
# - Default value: "debug"
logLevel: "debug"
# Syslog facility
# - Values: "user", "local0"..."local7" (double quoted)
# - Default value: "user"
syslogFacility: "user"
# Number of workers
# - Default value: 0 (set it to the number of CPU cores)
numWorkers: 0
# ControlProtocol server
ControlProtocol:
{
# Listening IP
# - Values: IPv4 or IPv6 (double quoted)
# - Default value: "127.0.0.1"
listenIP: "127.0.0.1"
# Listening port
# - Default value: 4080
listenPort: 4080
}
# Real-Time Communication
RTC:
{
# IPv4 and IPv6 for media
# - Values:
# - IPv4 or IPv6 (double quoted)
# - true: the first auto-discovered and bindeable non-local IP is chosen
# - false: IP family disabled
# - Default value: true
# listenIPv4: "1.2.3.4"
listenIPv4: true
# listenIPv6: "A:B:C::D"
listenIPv6: true
# Minimun port for media
# - Default value: 10000
minPort: 10000
# Maximum port for media
# - Default value: 59999
maxPort: 59999
# DTLS certificate and private key files in PEM format
# - Values:
# - Absolute path to PEM files (double quoted)
# - false: certificate and private key are auto-generated
# - Default value: false
dtlsCertificateFile: false
dtlsPrivateKeyFile: false
}
#ifndef MS_CONTROL_PROTOCOL_MESSAGE_H
#define MS_CONTROL_PROTOCOL_MESSAGE_H
#include "common.h"
namespace ControlProtocol {
class Message {
public:
enum class Kind {
Request = 1,
Response,
Notification
};
public:
Message(Kind);
virtual ~Message();
Kind GetKind();
virtual bool IsValid(); // TODO: Must be pure virtual.
void SetTransaction(int32_t transaction);
int32_t GetTransaction();
virtual void Dump() = 0;
protected:
Kind kind;
int32_t transaction = 0;
};
/* Inlime methods. */
inline
Message::Kind Message::GetKind() {
return this->kind;
}
inline
void Message::SetTransaction(int32_t transaction) {
this->transaction = transaction;
}
inline
int32_t Message::GetTransaction() {
return this->transaction;
}
} // namespace ControlProtocol
#endif
#ifndef MS_CONTROL_PROTOCOL_PARSER_H
#define MS_CONTROL_PROTOCOL_PARSER_H
#include "common.h"
#include "ControlProtocol/Message.h"
namespace ControlProtocol {
class Parser {
public:
Parser();
virtual ~Parser();
/**
* Parses the given buffer.
*
* @param buffer The buffer to parse.
* @param len The lenght of the buffer.
*
* @return Returns a pointer to ControlProtocol::Message if parsing succeded,
* or nullptr if the message is not completed or parsing failed.
*/
Message* Parse(const MS_BYTE* buffer, size_t len);
/**
* Checks whether the ongoing parsing has error or not.
*
* @return true if there is parsing error, false otherwise.
*/
bool HasError();
/**
* Get the length of the complete or uncomplete message parsed or being parsed.
*
* @return The number of chars parsed in the current message.
*/
size_t GetParsedLen();
/**
* Resets the parser internals. Must be called before parsing a new message
* (regardless the previous one succeded or not).
*/
void Reset();
/**
* Prints current status of the parser.
*/
void Dump();
protected:
size_t parsedLen;
private:
// Allocated by this:
ControlProtocol::Message* msg = nullptr;
// Others:
size_t cs = 0; // Needed for Ragel.
size_t mark = 0;
};
} // namespace ControlProtocol
#endif
#ifndef MS_CONTROL_PROTOCOL_REQUEST_H
#define MS_CONTROL_PROTOCOL_REQUEST_H
#include "ControlProtocol/Message.h"
namespace ControlProtocol {
class Request : public ControlProtocol::Message {
public:
enum class Type {
Hello = 1,
Authenticate,
CreateConference
};
public:
Request(Type);
virtual ~Request();
virtual void Dump() = 0;
public:
// Allow fast access to type.
Type type;
};
} // namespace ControlProtocol
#endif
#ifndef MS_CONTROL_PROTOCOL_TCP_CONNECTION_H
#define MS_CONTROL_PROTOCOL_TCP_CONNECTION_H
#include "common.h"
#include "handles/TCPConnection.h"
#include "ControlProtocol/Parser.h"
#include "ControlProtocol/Message.h"
namespace ControlProtocol {
class TCPConnection : public ::TCPConnection {
public:
class Reader {
public:
virtual void onControlProtocolMessage(ControlProtocol::TCPConnection* connection, ControlProtocol::Message* msg, const MS_BYTE* raw, size_t len) = 0;
};
public:
TCPConnection(Reader* reader, size_t bufferSize);
virtual ~TCPConnection();
/* Pure virtual methods inherited from ::TCPConnection. */
public:
virtual void userOnTCPConnectionRead(const MS_BYTE* data, size_t len) override;
private:
// Allocated by this:
ControlProtocol::Parser* parser = nullptr;
// Passed by argument:
Reader* reader = nullptr;
// Others:
size_t msgStart = 0; // Where the latest message starts.
};
} // namespace ControlProtocol
#endif
#ifndef MS_CONTROL_PROTOCOL_TCP_SERVER_H
#define MS_CONTROL_PROTOCOL_TCP_SERVER_H
#include "common.h"
#include "handles/TCPServer.h"
#include "handles/TCPConnection.h"
#include "ControlProtocol/TCPConnection.h"
#include "ControlProtocol/Message.h"
#include <string>
namespace ControlProtocol {
class TCPServer : public ::TCPServer {
public:
class Listener {
public:
virtual void onControlProtocolNewTCPConnection(ControlProtocol::TCPServer* tcpServer, ControlProtocol::TCPConnection* connection) = 0;
virtual void onControlProtocolTCPConnectionClosed(ControlProtocol::TCPServer* tcpServer, ControlProtocol::TCPConnection* connection, bool is_closed_by_peer) = 0;
};
public:
TCPServer(Listener* listener, ControlProtocol::TCPConnection::Reader* reader, const std::string &ip, MS_PORT port);
/* Pure virtual methods inherited from ::TCPServer. */
public:
virtual void userOnTCPConnectionAlloc(::TCPConnection** connection) override;
virtual void userOnNewTCPConnection(::TCPConnection* connection) override;
virtual void userOnTCPConnectionClosed(::TCPConnection* connection, bool is_closed_by_peer) override;
virtual void userOnTCPServerClosed() override;
private:
// Passed by argument:
Listener* listener = nullptr;
ControlProtocol::TCPConnection::Reader* reader = nullptr;
};
} // namespace ControlProtocol
#endif
#ifndef MS_CONTROL_PROTOCOL_UNIX_STREAM_SOCKET_H
#define MS_CONTROL_PROTOCOL_UNIX_STREAM_SOCKET_H
#include "common.h"
#include "handles/UnixStreamSocket.h"
#include "ControlProtocol/Parser.h"
#include "ControlProtocol/Message.h"
namespace ControlProtocol {
class UnixStreamSocket : public ::UnixStreamSocket {
public:
class Listener {
public:
virtual void onControlProtocolMessage(ControlProtocol::UnixStreamSocket* unixSocket, ControlProtocol::Message* msg, const MS_BYTE* raw, size_t len) = 0;
virtual void onControlProtocolUnixStreamSocketClosed(ControlProtocol::UnixStreamSocket* unixSocket, bool is_closed_by_peer) = 0;
};
public:
UnixStreamSocket(Listener* listener, int fd);
virtual ~UnixStreamSocket();
/* Pure virtual methods inherited from ::UnixStreamSocket. */
public:
virtual void userOnUnixStreamRead(const MS_BYTE* data, size_t len) override;
virtual void userOnUnixStreamSocketClosed(bool is_closed_by_peer) override;
private:
// Allocated by this:
ControlProtocol::Parser* parser = nullptr;
// Passed by argument:
Listener* listener = nullptr;
// Others:
size_t msgStart = 0; // Where the latest message starts.
};
} // namespace ControlProtocol
#endif
#ifndef MS_CONTROL_PROTOCOL_MESSAGES_H
#define MS_CONTROL_PROTOCOL_MESSAGES_H
#include "messages/RequestHello.h"
#include "messages/RequestAuthenticate.h"
#include "messages/RequestCreateConference.h"
#endif
#ifndef MS_CONTROL_PROTOCOL_REQUEST_AUTHENTICATE_H
#define MS_CONTROL_PROTOCOL_REQUEST_AUTHENTICATE_H
#include "ControlProtocol/Request.h"
#include <string>
namespace ControlProtocol {
class RequestAuthenticate : public ControlProtocol::Request {
public:
RequestAuthenticate();
virtual ~RequestAuthenticate();
void SetUser(const char* str, size_t len);
void SetPasswd(const char* str, size_t len);
virtual void Dump() override;
private:
std::string user;
std::string passwd;
};
} // namespace ControlProtocol
#endif
#ifndef MS_CONTROL_PROTOCOL_REQUEST_CREATE_CONFERENCE_H
#define MS_CONTROL_PROTOCOL_REQUEST_CREATE_CONFERENCE_H
#include "ControlProtocol/Request.h"
namespace ControlProtocol {
class RequestCreateConference : public ControlProtocol::Request {
public:
RequestCreateConference();
virtual ~RequestCreateConference();
virtual void Dump() override;
};
} // namespace ControlProtocol
#endif
#ifndef MS_CONTROL_PROTOCOL_REQUEST_HELLO_H
#define MS_CONTROL_PROTOCOL_REQUEST_HELLO_H
#include "ControlProtocol/Request.h"
namespace ControlProtocol {
class RequestHello : public ControlProtocol::Request {
public:
RequestHello();
virtual ~RequestHello();
virtual void Dump() override;
};
} // namespace ControlProtocol
#endif
#ifndef MS_DAEMON_H
#define MS_DAEMON_H
class Daemon {
public:
static void Daemonize();
static void SendOKStatusToAncestor();
static void SendErrorStatusToAncestor();
static bool IsDaemonized();
static void End();
private:
static bool WritePIDFile();
static void DeletePIDFile();
static bool WaitForDaemonizedStatus(char* status);
static void SendStatusToAncestor(char status);
private:
static int statusPipe[2];
static bool isDaemonized;
static bool hasWrittenPIDFile;
};
#endif
#ifndef MS_DISPATCHER_H
#define MS_DISPATCHER_H
#include "common.h"
#include "handles/SignalsHandler.h"
#include "ControlProtocol/TCPServer.h"
#include "ControlProtocol/TCPConnection.h"
#include "ControlProtocol/UnixStreamSocket.h"
#include "ControlProtocol/Message.h"
#include <vector>
class Dispatcher :
public SignalsHandler::Listener,
public ControlProtocol::TCPServer::Listener,
public ControlProtocol::TCPConnection::Reader,
public ControlProtocol::UnixStreamSocket::Listener
{
public:
Dispatcher();
virtual ~Dispatcher();
void Close();
/* Methods inherited from SignalsHandler::Listener. */
public:
virtual void onSignal(SignalsHandler* signalsHandler, int signum) override;
virtual void onSignalsHandlerClosed(SignalsHandler* signalsHandler) override;
/* Methods inherited from ControlProtocol::TCPServer::Listener. */
public:
virtual void onControlProtocolNewTCPConnection(ControlProtocol::TCPServer* tcpServer, ControlProtocol::TCPConnection* connection) override;
virtual void onControlProtocolTCPConnectionClosed(ControlProtocol::TCPServer* tcpServer, ControlProtocol::TCPConnection* connection, bool is_closed_by_peer) override;
/* Methods inherited from ControlProtocol::TCPConnection::Reader. */
public:
virtual void onControlProtocolMessage(ControlProtocol::TCPConnection* connection, ControlProtocol::Message* msg, const MS_BYTE* raw, size_t len) override;
/* Methods inherited from ControlProtocol::UnixStreamSocket::Listener. */
public:
virtual void onControlProtocolMessage(ControlProtocol::UnixStreamSocket* unixSocket, ControlProtocol::Message* msg, const MS_BYTE* raw, size_t len) override;
virtual void onControlProtocolUnixStreamSocketClosed(ControlProtocol::UnixStreamSocket* unixSocket, bool is_closed_by_peer) override;
private:
// Allocated by this:
SignalsHandler* signalsHandler = nullptr;
ControlProtocol::TCPServer* controlProtocolTCPServer = nullptr;
typedef std::vector<ControlProtocol::UnixStreamSocket*> ControlProtocolUnixStreamSockets;
ControlProtocolUnixStreamSockets controlProtocolUnixStreamSockets;
// Others:
bool closed = false;
};
#endif
#ifndef MS_LIBSRTP_H
#define MS_LIBSRTP_H
#include <vector>
#include <srtp/srtp.h>
class LibSRTP {
public:
static void ClassInit();
static void ClassDestroy();
static bool IsError(err_status_t code);
static const char* GetErrorString(err_status_t code);
private:
static std::vector<const char*> errors;
};
/* Inline static methods. */
inline
bool LibSRTP::IsError(err_status_t code) {
return (code != err_status_ok);
}
inline
const char* LibSRTP::GetErrorString(err_status_t code) {
// This throws out_of_range if the given index is not in the vector.
return LibSRTP::errors.at(code);
}
#endif
#ifndef MS_LIBUV_H
#define MS_LIBUV_H
#include "common.h"
#include <uv.h>
class LibUV {
public:
static void ClassInit();
static void ThreadInit();
static void ThreadDestroy();
static uv_loop_t* GetLoop();
static void RunLoop();
private:
static __thread uv_loop_t* loop;
};
/* Inline static methods. */
inline
uv_loop_t* LibUV::GetLoop() {
return LibUV::loop;
}
#endif
#ifndef MS_LOGGER_H
#define MS_LOGGER_H
#include "common.h"
#include "Settings.h"
#include <string>
#include <cstdio> // stdout, stderr, fflush()
#include <cstring>
#include <cstdlib> // std::_Exit(), std::abort()
#include <uv.h>
extern "C" {
#include <syslog.h>
}
/*
* Logger facility for MediaSoup.
*
* If the macro MS_DEVEL is set (see below) the output is even more verbose
* (it shows the file number in each log and enables the MS_TRACE() call).
*
* Usage:
*
* - MS_TRACE() Shows current file/line/class/function.
* - MS_DEBUG(...)
* - MS_INFO(...)
* - MS_NOTICE(...)
* - MS_WARN(...)
* - MS_ERROR(...)
* - MS_CRIT(...)
* - MS_ABORT(...)
*
* Arguments to those macros (except MS_TRACE) have the same format as printf.
*
* Examples:
*
* - MS_TRACE();
* - MS_DEBUG("starting worker %d", num);
*
* Output:
* TRACE: [worker #1] Worker.cpp:93 | void Worker::Run()
* DEBUG: [worker #1] Worker.cpp:94 | void Worker::Run() | starting worker 1
*/
/*
* Call the compiler with -DMS_DEVEL for more verbose logs.
*/
// #define MS_DEVEL
/*
* This macro must point to a unsigned int function, method or variable that
* returns Syslog logging level.
*/
#define MS_GET_LOG_LEVEL Settings::configuration.logLevel
class Logger {
public:
static void ThreadInit(const std::string name);
static const char* GetThreadName();
static void EnableSyslog();
static bool IsSyslogEnabled();
static bool HasDebugLevel();
private:
// NOTE:
// __thread implemented in GCC >= 4.7 and Clang.
// local_thread implemented in GCC >= 4.8.
static __thread std::string* threadName;
static __thread const char* threadNamePtr;
static bool isSyslogEnabled;
};
/* Inline static methods. */
inline
const char* Logger::GetThreadName() {
return Logger::threadNamePtr;
}
inline
bool Logger::IsSyslogEnabled() {
return Logger::isSyslogEnabled;
}
inline
bool Logger::HasDebugLevel() {
return (LOG_DEBUG == MS_GET_LOG_LEVEL);
}
// NOTE: Each file including Logger.h MUST define its own MS_CLASS macro.
#ifdef MS_DEVEL
#define _MS_LOG_STR "[%s] %s:%d | %s::%s()"
#define _MS_LOG_STR_DESC _MS_LOG_STR " | "
#define _MS_FILE (std::strchr(__FILE__, '/') ? std::strchr(__FILE__, '/') + 1 : __FILE__)
#define _MS_LOG_ARG Logger::GetThreadName(), _MS_FILE, __LINE__, MS_CLASS, __FUNCTION__
#else
#define _MS_LOG_STR "[%s] %s::%s()"
#define _MS_LOG_STR_DESC _MS_LOG_STR " | "
#define _MS_LOG_ARG Logger::GetThreadName(), MS_CLASS, __FUNCTION__
#endif
#define _MS_TO_STDOUT(prefix) \
if (! Logger::IsSyslogEnabled()) { \
std::fprintf(stdout, prefix _MS_LOG_STR "\n", _MS_LOG_ARG); \
fflush(stdout); \
}
#define _MS_TO_STDOUT_DESC(prefix, desc, ...) \
if (! Logger::IsSyslogEnabled()) { \
std::fprintf(stdout, prefix _MS_LOG_STR_DESC desc "\n", _MS_LOG_ARG, ##__VA_ARGS__); \
fflush(stdout); \
}
#define _MS_TO_STDERR_DESC(prefix, desc, ...) \
if (! Logger::IsSyslogEnabled()) { \
std::fprintf(stderr, prefix _MS_LOG_STR_DESC desc "\n", _MS_LOG_ARG, ##__VA_ARGS__); \
fflush(stderr); \
}
#define _MS_TO_SYSLOG(severity, prefix) \
if (Logger::IsSyslogEnabled()) \
syslog(severity, prefix _MS_LOG_STR, _MS_LOG_ARG);
#define _MS_TO_SYSLOG_DESC(severity, prefix, desc, ...) \
if (Logger::IsSyslogEnabled()) \
syslog(severity, prefix _MS_LOG_STR_DESC desc, _MS_LOG_ARG, ##__VA_ARGS__);
/*
* Log levels in syslog.h:
*
* LOG_EMERG 0 system is unusable
* LOG_ALERT 1 action must be taken immediately
* LOG_CRIT 2 critical conditions
* LOG_ERR 3 error conditions
* LOG_WARNING 4 warning conditions
* LOG_NOTICE 5 normal but significant condition
* LOG_INFO 6 informational
* LOG_DEBUG 7 debug-level messages
*/
#ifdef MS_DEVEL
#define MS_TRACE() \
do { \
_MS_TO_STDOUT("TRACE: "); \
_MS_TO_SYSLOG(LOG_DEBUG, "TRACE: "); \
} while(0)
#else
#define MS_TRACE()
#endif
#define MS_DEBUG(desc, ...) \
do { \
if (LOG_DEBUG == MS_GET_LOG_LEVEL) { \
_MS_TO_STDOUT_DESC("DEBUG: ", desc, ##__VA_ARGS__); \
_MS_TO_SYSLOG_DESC(LOG_DEBUG, "DEBUG: ", desc, ##__VA_ARGS__); \
} \
} while(0)
#define MS_INFO(desc, ...) \
do { \
if (LOG_INFO <= MS_GET_LOG_LEVEL) { \
_MS_TO_STDOUT_DESC("INFO: ", desc, ##__VA_ARGS__); \
_MS_TO_SYSLOG_DESC(LOG_INFO, "INFO: ", desc, ##__VA_ARGS__); \
} \
} while(0)
#define MS_NOTICE(desc, ...) \
do { \
if (LOG_NOTICE <= MS_GET_LOG_LEVEL) { \
_MS_TO_STDOUT_DESC("NOTICE: ", desc, ##__VA_ARGS__); \
_MS_TO_SYSLOG_DESC(LOG_NOTICE, "NOTICE: ", desc, ##__VA_ARGS__); \
} \
} while(0)
#define MS_WARN(desc, ...) \
do { \
if (LOG_WARNING <= MS_GET_LOG_LEVEL) { \
_MS_TO_STDERR_DESC("WARN: ", desc, ##__VA_ARGS__); \
_MS_TO_SYSLOG_DESC(LOG_WARNING, "WARN: ", desc, ##__VA_ARGS__); \
} \
} while(0)
#define MS_ERROR(desc, ...) \
do { \
_MS_TO_STDERR_DESC("ERROR: ", desc, ##__VA_ARGS__); \
_MS_TO_SYSLOG_DESC(LOG_ERR, "ERROR: ", desc, ##__VA_ARGS__); \
} while(0)
#define MS_CRIT(desc, ...) \
do { \
_MS_TO_STDERR_DESC("CRIT: ", desc, ##__VA_ARGS__); \
_MS_TO_SYSLOG_DESC(LOG_ERR, "CRIT: ", desc, ##__VA_ARGS__); \
} while(0)
#define MS_EXIT_SUCCESS(desc, ...) \
do { \
MS_NOTICE("SUCCESS EXIT | " desc, ##__VA_ARGS__); \
std::_Exit(EXIT_SUCCESS); \
} while(0)
#define MS_EXIT_FAILURE(desc, ...) \
do { \
MS_CRIT("FAILURE EXIT | " desc, ##__VA_ARGS__); \
std::_Exit(EXIT_FAILURE); \
} while(0)
#define MS_ABORT(desc, ...) \
do { \
MS_CRIT("ABORT | " desc, ##__VA_ARGS__); \
std::abort(); \
} while(0)
#define MS_ASSERT(condition, desc, ...) \
if (! (condition)) { \
MS_ABORT("failed assertion `%s': " desc, #condition, ##__VA_ARGS__); \
}
#endif
#ifndef MS_MEDIASOUP_H
#define MS_MEDIASOUP_H
class MediaSoup {
public:
static void SetProcess();
static void Run();
static void End();
private:
static void IgnoreSignals();
static void SetKernelLimits();
static void SetUserGroup();
static void ThreadInit();
static void ThreadDestroy();
static void ClassInit();
static void ClassDestroy();
static void RunWorkerThread(void* data);
};
#endif
#ifndef MS_MEDIASOUP_ERROR_H
#define MS_MEDIASOUP_ERROR_H
#include "Logger.h"
#include <stdexcept>
#include <string>
#include <cstdio> // std::snprintf
class MediaSoupError : public std::runtime_error {
public:
MediaSoupError(const char* description);
};
/* Inline methods. */
inline
MediaSoupError::MediaSoupError(const char* description) :
std::runtime_error(description)
{}
#define MS_THROW_ERROR(desc, ...) \
do { \
MS_ERROR("throwing MediaSoupError | " desc, ##__VA_ARGS__); \
char buffer[1000]; \
std::snprintf(buffer, 1000, desc, ##__VA_ARGS__); \
throw MediaSoupError(buffer); \
} while(0)
#endif
#ifndef MS_OPENSSL_H
#define MS_OPENSSL_H
#include "common.h"
#include <openssl/ssl.h>
#include <openssl/crypto.h>
/* OpenSSL doc: struct CRYPTO_dynlock_value has to be defined by the application. */
struct CRYPTO_dynlock_value {
pthread_mutex_t mutex;
};
class OpenSSL {
public:
static void ClassInit();
static void ClassDestroy();
private:
static void SetThreadId(CRYPTO_THREADID* id);
static void LockingFunction(int mode, int n, const char *file, int line);
static CRYPTO_dynlock_value* DynCreateFunction(const char* file, int line);
static void DynLockFunction(int mode, CRYPTO_dynlock_value* v, const char* file, int line);
static void DynDestroyFunction(CRYPTO_dynlock_value* v, const char* file, int line);
private:
static pthread_mutex_t* mutexes;
static int numMutexes;
};
#endif
#ifndef MS_RTC_DTLS_HANDLER_H
#define MS_RTC_DTLS_HANDLER_H
#include "common.h"
#include "handles/Timer.h"
#include "RTC/DTLSRole.h"
#include "RTC/FingerprintHash.h"
#include "RTC/SRTPProfile.h"
#include <string>
#include <map>
#include <vector>
#include <openssl/ssl.h>
#include <openssl/bio.h>
#include <openssl/x509.h>
namespace RTC {
class DTLSHandler :
public Timer::Listener
{
private:
struct SrtpProfileMapEntry {
SRTPProfile profile;
const char* name;
};
public:
class Listener {
public:
// NOTE: The caller MUST NOT call Reset() or Close() during the
// onOutgoingDTLSData() callback.
virtual void onOutgoingDTLSData(DTLSHandler* dtlsHandler, const MS_BYTE* data, size_t len) = 0;
// NOTE: The caller MUST NOT call any method during the onDTLSConnected,
// onDTLSDisconnected or onDTLSFailed callbacks.
virtual void onDTLSConnected(DTLSHandler* dtlsHandler) = 0;
virtual void onDTLSDisconnected(DTLSHandler* dtlsHandler) = 0;
virtual void onDTLSFailed(DTLSHandler* dtlsHandler) = 0;
virtual void onSRTPKeyMaterial(DTLSHandler* dtlsHandler, RTC::SRTPProfile srtp_profile, MS_BYTE* srtp_local_key, size_t srtp_local_key_len, MS_BYTE* srtp_remote_key, size_t srtp_remote_key_len) = 0;
virtual void onDTLSApplicationData(DTLSHandler* dtlsHandler, const MS_BYTE* data, size_t len) = 0;
};
public:
static void ClassInit();
static void ClassDestroy();
static bool IsDTLS(const MS_BYTE* data, size_t len);
static const std::string& GetFingerprint(RTC::FingerprintHash hash);
private:
static void GenerateCertificateAndPrivateKey();
static void ReadCertificateAndPrivateKeyFromFiles();
static void CreateSSL_CTX();
static void GenerateFingerprints();
private:
static X509* certificate;
static EVP_PKEY* privateKey;
static SSL_CTX* sslCtx;
typedef std::map<RTC::FingerprintHash, std::string> Fingerprints;
static Fingerprints fingerprints;
typedef std::vector<SrtpProfileMapEntry> SRTPProfiles;
static SRTPProfiles srtpProfiles;
static __thread MS_BYTE sslReadBuffer[];
public:
DTLSHandler(Listener* listener);
virtual ~DTLSHandler();
void Run(RTC::DTLSRole role);
void SetRemoteFingerprint(RTC::FingerprintHash hash, std::string& fingerprint);
void Reset();
void Close();
void ProcessDTLSData(const MS_BYTE* data, size_t len);
bool IsRunning();
bool IsConnected();
void SendApplicationData(const MS_BYTE* data, size_t len);
void Dump();
private:
bool CheckStatus(int return_code);
void SendPendingOutgoingDTLSData();
void SetTimeout();
void ProcessHandshake();
bool CheckRemoteFingerprint();
RTC::SRTPProfile GetNegotiatedSRTPProfile();
void ExtractSRTPKeys(RTC::SRTPProfile srtp_profile);
/* Callbacks fired by OpenSSL events. */
public:
void onSSLInfo(int where, int ret);
/* Pure virtual methods inherited from Timer::Listener. */
public:
virtual void onTimer(Timer* timer) override;
private:
// Passed by argument:
Listener* listener = nullptr;
// Allocated by this:
SSL* ssl = nullptr;
BIO* sslBioFromNetwork = nullptr; // The BIO from which ssl reads.
BIO* sslBioToNetwork = nullptr; // The BIO in which ssl writes.
Timer* timer = nullptr;
// Others:
RTC::DTLSRole role;
RTC::FingerprintHash remoteFingerprintHash = RTC::FingerprintHash::NONE;
std::string remoteFingerprint;
bool isRunning = false;
bool isHandshakeDone = false;
bool isHandshakeDoneNow = false;
bool isConnected = false;
bool isCheckingStatus = false;
bool doReset = false;
bool doClose = false;
};
/* Inline static methods. */
inline
bool DTLSHandler::IsDTLS(const MS_BYTE* data, size_t len) {
return (
// Minimum DTLS record length is 13 bytes.
(len >= 13) &&
// DOC: https://tools.ietf.org/html/draft-petithuguenin-avtcore-rfc5764-mux-fixes-00
(data[0] > 19 && data[0] < 64)
);
}
/* Inline instance methods. */
inline
bool DTLSHandler::IsConnected() {
return this->isConnected;
}
inline
bool DTLSHandler::IsRunning() {
return this->isRunning;
}
} // namespace RTC
#endif
#ifndef MS_RTC_DTLS_ROLE_H
#define MS_RTC_DTLS_ROLE_H
namespace RTC {
enum class DTLSRole {
NONE = 0,
SERVER = 1,
CLIENT
};
} // namespace RTC
#endif
#ifndef MS_RTC_FINGERPRINT_HASH_H
#define MS_RTC_FINGERPRINT_HASH_H
namespace RTC {
enum class FingerprintHash {
NONE = 0,
SHA1 = 1,
SHA224,
SHA256,
SHA384,
SHA512
};
} // namespace RTC
#endif
#ifndef MS_RTC_ICE_SERVER_H
#define MS_RTC_ICE_SERVER_H
#include "common.h"
#include "RTC/TransportSource.h"
#include "RTC/STUNMessage.h"
#include "RTC/UDPSocket.h"
#include "RTC/TCPConnection.h"
#include <string>
namespace RTC {
class ICEServer {
public:
class Listener {
public:
/**
* These callbacks are guaranteed to be called before ProcessSTUNMessage()
* returns, so the given pointers are still usable.
*/
virtual void onOutgoingSTUNMessage(ICEServer* iceServer, RTC::STUNMessage* msg, RTC::TransportSource* source) = 0;
virtual void onICEValidPair(ICEServer* iceServer, RTC::TransportSource* source, bool has_use_candidate) = 0;
};
public:
ICEServer(Listener* listener);
void ProcessSTUNMessage(RTC::STUNMessage* msg, RTC::TransportSource* source);
std::string& GetLocalUsername();
std::string& GetLocalPassword();
void SetUserData(void* userData);
void* GetUserData();
void Close();
private:
// Passed by argument:
Listener* listener = nullptr;
void* userData = nullptr;
// Others:
std::string localUsername;
std::string localPassword;
};
/* Inline methods. */
inline
std::string& ICEServer::GetLocalUsername() {
return this->localUsername;
}
inline
std::string& ICEServer::GetLocalPassword() {
return this->localPassword;
}
inline
void ICEServer::SetUserData(void* userData) {
this->userData = userData;
}
inline
void* ICEServer::GetUserData() {
return this->userData;
}
} // namespace RTC
#endif
#ifndef MS_RTC_PEER_H
#define MS_RTC_PEER_H
#include "RTC/Transport.h"
#include "RTC/RTPPacket.h"
#include "RTC/RTCPPacket.h"
#include <vector>
namespace RTC {
class Peer :
RTC::Transport::Listener
{
public:
class Listener {
public:
virtual void onRTPPacket(RTC::Peer* peer, RTC::RTPPacket* packet) = 0;
virtual void onRTCPPacket(RTC::Peer* peer, RTC::RTCPPacket* packet) = 0;
};
public:
Peer(Listener* listener);
virtual ~Peer();
void SendRTPPacket(RTC::RTPPacket* packet);
void SendRTCPPacket(RTC::RTCPPacket* packet);
void SetUserData(void* userData);
void* GetUserData();
void Close();
/* Pure virtual methods inherited from RTC::Transport::Listener. */
public:
virtual void onRTPPacket(RTC::Transport* transport, RTC::RTPPacket* packet) override;
virtual void onRTCPPacket(RTC::Transport* transport, RTC::RTCPPacket* packet) override;
private:
// Passed by argument:
Listener* listener = nullptr;
void* userData = nullptr;
// Others:
RTC::Transport* transport = nullptr;
};
/* Inline methods. */
inline
void Peer::SetUserData(void* userData) {
this->userData = userData;
}
inline
void* Peer::GetUserData() {
return this->userData;
}
} // namespace RTC
#endif
#ifndef MS_RTC_RTCP_PACKET_H
#define MS_RTC_RTCP_PACKET_H
#include "common.h"
namespace RTC {
class RTCPPacket {
public:
/* Struct for RTCP common header. */
typedef struct CommonHeader {
#if defined(MS_LITTLE_ENDIAN)
MS_BYTE count:5;
MS_BYTE padding:1;
MS_BYTE version:2;
#elif defined(MS_BIG_ENDIAN)
MS_BYTE version:2;
MS_BYTE padding:1;
MS_BYTE count:5;
#endif
MS_BYTE packet_type:8;
MS_2BYTES length:16;
} CommonHeader;
public:
static bool IsRTCP(const MS_BYTE* data, size_t len);
static RTCPPacket* Parse(const MS_BYTE* data, size_t len);
public:
RTCPPacket(CommonHeader* header, const MS_BYTE* raw, size_t length);
~RTCPPacket();
const MS_BYTE* GetRaw();
size_t GetLength();
private:
// Passed by argument:
CommonHeader* header = nullptr;
MS_BYTE* raw = nullptr;
size_t length = 0;
};
/* Inline static methods. */
inline
bool RTCPPacket::IsRTCP(const MS_BYTE* data, size_t len) {
CommonHeader* header = (CommonHeader*)data;
return (
(len >= sizeof(CommonHeader)) &&
// DOC: https://tools.ietf.org/html/draft-petithuguenin-avtcore-rfc5764-mux-fixes-00
(data[0] > 127 && data[0] < 192) &&
// RTP Version must be 2.
(header->version == 2) &&
// RTCP packet types defined by IANA:
// http://www.iana.org/assignments/rtp-parameters/rtp-parameters.xhtml#rtp-parameters-4
// RFC 5761 (RTCP-mux) states this range for secure RTCP/RTP detection.
(header->packet_type >= 192 && header->packet_type <= 223)
);
}
/* Inline instance methods. */
inline
const MS_BYTE* RTCPPacket::GetRaw() {
return this->raw;
}
inline
size_t RTCPPacket::GetLength() {
return this->length;
}
} // namespace RTC
#endif
#ifndef MS_RTC_RTP_PACKET_H
#define MS_RTC_RTP_PACKET_H
#include "common.h"
namespace RTC {
class RTPPacket {
public:
/* Struct for RTP header. */
typedef struct Header {
#if defined(MS_LITTLE_ENDIAN)
MS_BYTE csrc_count:4;
MS_BYTE extension:1;
MS_BYTE padding:1;
MS_BYTE version:2;
MS_BYTE payload_type:7;
MS_BYTE marker:1;
#elif defined(MS_BIG_ENDIAN)
MS_BYTE version:2;
MS_BYTE padding:1;
MS_BYTE extension:1;
MS_BYTE csrc_count:4;
MS_BYTE marker:1;
MS_BYTE payload_type:7;
#endif
MS_2BYTES sequence_number;
MS_4BYTES timestamp;
MS_4BYTES ssrc;
} Header;
/* Struct for RTP header extension. */
typedef struct ExtensionHeader {
MS_2BYTES id;
MS_2BYTES length; // Size of value in multiples of 4 bytes.
MS_BYTE* value;
} ExtensionHeader;
public:
static bool IsRTP(const MS_BYTE* data, size_t len);
static RTPPacket* Parse(const MS_BYTE* data, size_t len);
public:
RTPPacket(Header* header, ExtensionHeader* extensionHeader, const MS_BYTE* payload, size_t payloadLen, MS_BYTE payloadPadding, const MS_BYTE* raw, size_t length);
~RTPPacket();
const MS_BYTE* GetRaw();
size_t GetLength();
MS_BYTE GetPayloadType();
void SetPayloadType(MS_BYTE payload_type);
bool HasMarker();
void SetMarker(bool marker);
MS_2BYTES GetSequenceNumber();
MS_4BYTES GetTimestamp();
MS_4BYTES GetSSRC();
void SetSSRC(MS_4BYTES ssrc);
bool HasExtensionHeader();
MS_2BYTES GetExtensionHeaderId();
size_t GetExtensionHeaderLength();
MS_BYTE* GetPayload();
size_t GetPayloadLength();
void Serialize();
void Dump();
private:
// Passed by argument:
Header* header = nullptr;
MS_BYTE* csrcList = nullptr;
ExtensionHeader* extensionHeader = nullptr;
MS_BYTE* payload = nullptr;
size_t payloadLength = 0;
MS_BYTE payloadPadding = 0;
MS_BYTE* raw = nullptr; // Allocated when Serialize().
size_t length = 0;
// Others:
bool isSerialized = false;
};
/* Inline static methods. */
inline
bool RTPPacket::IsRTP(const MS_BYTE* data, size_t len) {
// NOTE: RTCPPacket::IsRTCP() must always be called before this method.
Header* header = (Header*)data;
return (
(len >= sizeof(Header)) &&
// DOC: https://tools.ietf.org/html/draft-petithuguenin-avtcore-rfc5764-mux-fixes-00
(data[0] > 127 && data[0] < 192) &&
// RTP Version must be 2.
(header->version == 2)
);
}
/* Inline instance methods. */
inline
const MS_BYTE* RTPPacket::GetRaw() {
return this->raw;
}
inline
size_t RTPPacket::GetLength() {
return this->length;
}
inline
MS_BYTE RTPPacket::GetPayloadType() {
return this->header->payload_type;
}
inline
void RTPPacket::SetPayloadType(MS_BYTE payload_type) {
this->header->payload_type = payload_type;
}
inline
bool RTPPacket::HasMarker() {
return this->header->marker;
}
inline
void RTPPacket::SetMarker(bool marker) {
this->header->marker = marker;
}
inline
MS_2BYTES RTPPacket::GetSequenceNumber() {
return ntohs(this->header->sequence_number);
}
inline
MS_4BYTES RTPPacket::GetTimestamp() {
return ntohl(this->header->timestamp);
}
inline
MS_4BYTES RTPPacket::GetSSRC() {
return ntohl(this->header->ssrc);
}
// TODO temp
inline
void RTPPacket::SetSSRC(MS_4BYTES ssrc) {
this->header->ssrc = htonl(ssrc);
}
inline
bool RTPPacket::HasExtensionHeader() {
return (this->extensionHeader ? true : false);
}
inline
MS_2BYTES RTPPacket::GetExtensionHeaderId() {
if (this->extensionHeader)
return MS_2BYTES(ntohs(this->extensionHeader->id));
else
return 0;
}
inline
size_t RTPPacket::GetExtensionHeaderLength() {
if (this->extensionHeader)
return size_t(ntohs(this->extensionHeader->length) * 4);
else
return 0;
}
inline
MS_BYTE* RTPPacket::GetPayload() {
return this->payload;
}
inline
size_t RTPPacket::GetPayloadLength() {
return this->payloadLength;
}
} // namespace RTC
#endif
#ifndef MS_RTC_ROOM_H
#define MS_RTC_ROOM_H
#include "RTC/Peer.h"
#include "RTC/RTPPacket.h"
#include "RTC/RTCPPacket.h"
#include <vector>
namespace RTC {
class Room :
RTC::Peer::Listener
{
public:
Room();
virtual ~Room();
void Close();
/* Pure virtual methods inherited from RTC::Peer::Listener. */
public:
virtual void onRTPPacket(RTC::Peer* peer, RTC::RTPPacket* packet) override;
virtual void onRTCPPacket(RTC::Peer* peer, RTC::RTCPPacket* packet) override;
private:
// Others:
typedef std::vector<RTC::Peer*> Peers;
Peers peers;
};
} // namespace RTC
#endif
#ifndef MS_RTC_SRTP_PROFILE_H
#define MS_RTC_SRTP_PROFILE_H
namespace RTC {
enum class SRTPProfile {
NONE = 0,
AES_CM_128_HMAC_SHA1_80 = 1,
AES_CM_128_HMAC_SHA1_32
};
} // namespace RTC
#endif
#ifndef MS_RTC_SRTP_SESSION_H
#define MS_RTC_SRTP_SESSION_H
#include "common.h"
#include "LibSRTP.h"
#include "RTC/SRTPProfile.h"
#include <srtp/srtp.h>
namespace RTC {
class SRTPSession {
public:
enum class Type {
INBOUND = 1,
OUTBOUND
};
public:
static void ClassInit();
private:
static void onSRTPEvent(srtp_event_data_t* data);
private:
static __thread MS_BYTE encryptBuffer[];
public:
SRTPSession(Type type, RTC::SRTPProfile profile, MS_BYTE* key, size_t key_len);
~SRTPSession();
bool EncryptRTP(const MS_BYTE** data, size_t* len);
bool DecryptSRTP(const MS_BYTE* data, size_t* len);
bool EncryptRTCP(const MS_BYTE** data, size_t* len);
bool DecryptSRTCP(const MS_BYTE* data, size_t* len);
const char* GetLastErrorDesc();
void Close();
private:
// Allocated by this:
srtp_t session = nullptr;
// Others:
err_status_t lastError = (err_status_t)0;
};
/* Inline instance methods. */
inline
const char* SRTPSession::GetLastErrorDesc() {
const char* error_string;
error_string = LibSRTP::GetErrorString(this->lastError);
this->lastError = (err_status_t)0; // Reset it.
return error_string;
}
} // namespace RTC
#endif
#ifndef MS_RTC_STUN_MESSAGE_H
#define MS_RTC_STUN_MESSAGE_H
#include "common.h"
#include <string>
namespace RTC {
class STUNMessage {
public:
// STUN message class.
enum class Class : MS_2BYTES {
Request = 0,
Indication = 1,
SuccessResponse = 2,
ErrorResponse = 3
};
// STUN message method.
enum class Method : MS_2BYTES {
Binding = 1
};
// Attribute type.
enum class Attribute : MS_2BYTES {
MappedAddress = 0x0001,
Username = 0x0006,
MessageIntegrity = 0x0008,
ErrorCode = 0x0009,
UnknownAttributes = 0x000A,
Realm = 0x0014,
Nonce = 0x0015,
XorMappedAddress = 0x0020,
Priority = 0x0024,
UseCandidate = 0x0025,
Software = 0x8022,
AlternateServer = 0x8023,
Fingerprint = 0x8028,
IceControlled = 0x8029,
IceControlling = 0x802A
};
// Authentication result.
enum class Authentication {
OK = 0,
Unauthorized = 1,
BadRequest = 2
};
public:
static bool IsSTUN(const MS_BYTE* data, size_t len);
static STUNMessage* Parse(const MS_BYTE* data, size_t len);
private:
static const MS_BYTE magicCookie[];
public:
STUNMessage(Class klass, Method method, const MS_BYTE* transactionId, const MS_BYTE* raw, size_t length);
~STUNMessage();
Class GetClass();
Method GetMethod();
const MS_BYTE* GetRaw();
void SetLength(size_t length);
size_t GetLength();
void SetUsername(const char* username, size_t len);
void SetPriority(const MS_4BYTES priority);
void SetIceControlling(const MS_8BYTES iceControlling);
void SetIceControlled(const MS_8BYTES iceControlled);
void SetUseCandidate();
void SetXorMappedAddress(const struct sockaddr* xorMappedAddress);
void SetErrorCode(MS_2BYTES errorCode);
void SetMessageIntegrity(const MS_BYTE* messageIntegrity);
void SetFingerprint();
const std::string& GetUsername();
const MS_4BYTES GetPriority();
const MS_8BYTES GetIceControlling();
const MS_8BYTES GetIceControlled();
bool HasUseCandidate();
MS_2BYTES GetErrorCode();
bool HasMessageIntegrity();
bool HasFingerprint();
Authentication CheckAuthentication(const std::string &local_username, const std::string &local_password);
STUNMessage* CreateSuccessResponse();
STUNMessage* CreateErrorResponse(MS_2BYTES errorCode);
void Authenticate(const std::string &password);
void Serialize();
void Dump();
private:
// Passed by argument:
Class klass; // 2 bytes.
Method method; // 2 bytes.
const MS_BYTE* transactionId = nullptr; // 12 bytes.
MS_BYTE* raw = nullptr; // Allocated when Serialize().
size_t length = 0; // The full message size (including header).
// Others:
bool isSerialized = false;
// STUN attributes.
std::string username; // Less than 513 bytes.
MS_4BYTES priority = 0; // 4 bytes unsigned integer.
MS_8BYTES iceControlling = 0; // 8 bytes unsigned integer.
MS_8BYTES iceControlled = 0; // 8 bytes unsigned integer.
bool hasUseCandidate = false; // 0 bytes.
const MS_BYTE* messageIntegrity = nullptr; // 20 bytes.
bool hasFingerprint = false; // 4 bytes.
const struct sockaddr* xorMappedAddress = nullptr; // 8 or 20 bytes.
MS_2BYTES errorCode = 0; // 4 bytes (no reason phrase).
std::string password;
};
/* Inline methods. */
inline
bool STUNMessage::IsSTUN(const MS_BYTE* data, size_t len) {
return (
// STUN headers are 20 bytes.
(len >= 20) &&
// DOC: https://tools.ietf.org/html/draft-petithuguenin-avtcore-rfc5764-mux-fixes-00
(data[0] < 20) &&
// Magic cookie must match.
(data[4] == STUNMessage::magicCookie[0]) &&
(data[5] == STUNMessage::magicCookie[1]) &&
(data[6] == STUNMessage::magicCookie[2]) &&
(data[7] == STUNMessage::magicCookie[3])
);
}
inline
STUNMessage::Class STUNMessage::GetClass() {
return this->klass;
}
inline
STUNMessage::Method STUNMessage::GetMethod() {
return this->method;
}
inline
const MS_BYTE* STUNMessage::GetRaw() {
return this->raw;
}
inline
void STUNMessage::SetLength(size_t length) {
this->length = length;
}
inline
size_t STUNMessage::GetLength() {
return this->length;
}
inline
void STUNMessage::SetUsername(const char* username, size_t len) {
if (this->username.empty())
this->username = std::string(username, len);
}
inline
void STUNMessage::SetPriority(const MS_4BYTES priority) {
if (! this->priority)
this->priority = priority;
}
inline
void STUNMessage::SetIceControlling(const MS_8BYTES iceControlling) {
if (! this->iceControlling)
this->iceControlling = iceControlling;
}
inline
void STUNMessage::SetIceControlled(const MS_8BYTES iceControlled) {
if (! this->iceControlled)
this->iceControlled = iceControlled;
}
inline
void STUNMessage::SetUseCandidate() {
this->hasUseCandidate = true;
}
inline
void STUNMessage::SetXorMappedAddress(const struct sockaddr* xorMappedAddress) {
if (! this->xorMappedAddress)
this->xorMappedAddress = xorMappedAddress;
}
inline
void STUNMessage::SetErrorCode(MS_2BYTES errorCode) {
this->errorCode = errorCode;
}
inline
void STUNMessage::SetMessageIntegrity(const MS_BYTE* messageIntegrity) {
if (! this->messageIntegrity)
this->messageIntegrity = messageIntegrity;
}
inline
void STUNMessage::SetFingerprint() {
this->hasFingerprint = true;
}
inline
const std::string& STUNMessage::GetUsername() {
return this->username;
}
inline
const MS_4BYTES STUNMessage::GetPriority() {
return this->priority;
}
inline
const MS_8BYTES STUNMessage::GetIceControlling() {
return this->iceControlling;
}
inline
const MS_8BYTES STUNMessage::GetIceControlled() {
return this->iceControlled;
}
inline
bool STUNMessage::HasUseCandidate() {
return this->hasUseCandidate;
}
inline
MS_2BYTES STUNMessage::GetErrorCode() {
return this->errorCode;
}
inline
bool STUNMessage::HasMessageIntegrity() {
return (this->messageIntegrity ? true : false);
}
inline
bool STUNMessage::HasFingerprint() {
return this->hasFingerprint;
}
} // namespace RTC
#endif
#ifndef MS_RTC_STREAM_H
#define MS_RTC_STREAM_H
#include "common.h"
#include "RTC/RTPPacket.h"
#include "RTC/RTCPPacket.h"
#include <unordered_set>
namespace RTC {
class Stream {
public:
Stream();
~Stream();
void Close();
private:
MS_4BYTES ssrc = 0;
std::unordered_set<MS_BYTE> payloads;
};
} // namespace RTC
#endif
#ifndef MS_RTC_TCP_CONNECTION_H
#define MS_RTC_TCP_CONNECTION_H
#include "common.h"
#include "handles/TCPConnection.h"
namespace RTC {
class TCPConnection : public ::TCPConnection {
public:
class Reader {
public:
virtual void onSTUNDataRecv(RTC::TCPConnection *connection, const MS_BYTE* data, size_t len) = 0;
virtual void onDTLSDataRecv(RTC::TCPConnection *connection, const MS_BYTE* data, size_t len) = 0;
virtual void onRTPDataRecv(RTC::TCPConnection *connection, const MS_BYTE* data, size_t len) = 0;
virtual void onRTCPDataRecv(RTC::TCPConnection *connection, const MS_BYTE* data, size_t len) = 0;
};
public:
TCPConnection(Reader* reader, size_t bufferSize);
virtual ~TCPConnection();
void Send(const MS_BYTE* data, size_t len);
/* Pure virtual methods inherited from ::TCPConnection. */
public:
virtual void userOnTCPConnectionRead(const MS_BYTE* data, size_t len) override;
private:
// Passed by argument:
Reader* reader = nullptr;
// Others:
size_t frameStart = 0; // Where the latest frame starts.
};
} // namespace RTC
#endif
#ifndef MS_RTC_TCP_SERVER_H
#define MS_RTC_TCP_SERVER_H
#include "common.h"
#include "handles/TCPServer.h"
#include "handles/TCPConnection.h"
#include "RTC/TCPConnection.h"
#include <unordered_map>
#include <uv.h>
namespace RTC {
class TCPServer : public ::TCPServer {
public:
class Listener {
public:
virtual void onRTCTCPConnectionClosed(RTC::TCPServer* tcpServer, RTC::TCPConnection* connection, bool is_closed_by_peer) = 0;
};
public:
static void ClassInit();
static RTC::TCPServer* New(int address_family);
static void NewPair(int address_family, RTC::TCPServer* servers[]);
private:
static void RandomizePort(int address_family, uv_tcp_t* uvHandles[], bool pair);
private:
static struct sockaddr_storage sockaddrStorageIPv4;
static struct sockaddr_storage sockaddrStorageIPv6;
static MS_PORT minPort;
static MS_PORT maxPort;
typedef std::unordered_map<MS_PORT, bool> AvailablePorts;
static AvailablePorts availableIPv4Ports;
static AvailablePorts availableIPv6Ports;
public:
TCPServer(uv_tcp_t* uvHandle);
void SetListeners(Listener* listener, RTC::TCPConnection::Reader* reader);
/* Pure virtual methods inherited from ::TCPServer. */
public:
virtual void userOnTCPConnectionAlloc(::TCPConnection** connection) override;
virtual void userOnNewTCPConnection(::TCPConnection* connection) override;
virtual void userOnTCPConnectionClosed(::TCPConnection* connection, bool is_closed_by_peer) override;
virtual void userOnTCPServerClosed() override;
private:
// Passed by argument:
Listener* listener = nullptr;
RTC::TCPConnection::Reader* reader = nullptr;
};
/* Inline methods. */
inline
void TCPServer::SetListeners(Listener* listener, RTC::TCPConnection::Reader* reader) {
this->listener = listener;
this->reader = reader;
}
} // namespace RTC
#endif
#ifndef MS_RTC_TRANSPORT_H
#define MS_RTC_TRANSPORT_H
#include "common.h"
#include "RTC/TransportSource.h"
#include "RTC/UDPSocket.h"
#include "RTC/TCPServer.h"
#include "RTC/TCPConnection.h"
#include "RTC/ICEServer.h"
#include "RTC/STUNMessage.h"
#include "RTC/DTLSRole.h"
#include "RTC/DTLSHandler.h"
#include "RTC/RTPPacket.h"
#include "RTC/RTCPPacket.h"
#include "RTC/SRTPProfile.h"
#include "RTC/SRTPSession.h"
#include <vector>
#include <list>
#include <string>
namespace RTC {
/**
* A RTC::Transport handles (in the most complex case as in WebRTC):
* - A RTC::ICEServer to handle received ICE requests and notify ICE connections.
* - A RTC::DTLSHandler to handle DTLS packets and notify the DTLS connection
* state along with SRTP keys material.
* - Many RTC::UDPSocket or RTC::TCPServer instances to listen for data coming
* from the peer.
* - A pair of RTC::SRTPSession instances for both outbound and inbound traffic
* that encrypt/decrypt SRTP and SRTCP packets.
* - A list of validated RTC::TransportSource instances (UDP tuple or TCP
* connection) from which incoming data is accepted (otherwise discarded).
* - A RTC::TransportSource marked as "sending source" which is the chosen one
* to send data to the peer.
*
* Considerations:
* - Received ICE requests trigger ICE responses that are sent back to the peer
* through the same RTC::TransportSource from which the requests were received.
* - Outgoing DTLS data is sent to the currently selected sending source.
* - The sending source is updated at any time a packet is received from a valid
* source that does not match the current sending source.
* - The Reset() method clear all the valid sources, resets the DTLS status and
* closes the SRTP sessions.
*/
class Transport :
public RTC::UDPSocket::Listener,
public RTC::TCPServer::Listener,
public RTC::TCPConnection::Reader,
public RTC::ICEServer::Listener,
public RTC::DTLSHandler::Listener
{
public:
class Listener {
public:
virtual void onRTPPacket(RTC::Transport* transport, RTC::RTPPacket* packet) = 0;
virtual void onRTCPPacket(RTC::Transport* transport, RTC::RTCPPacket* packet) = 0;
};
public:
// NOTE: Maximum value is 1<<31.
enum Flag {
ICE = 1<<0,
DTLS = 1<<1,
SRTP = 1<<2
};
public:
static Transport* NewWebRTC(Listener* listener);
private:
static size_t maxSources;
public:
Transport(Listener* listener, int flags);
virtual ~Transport();
void AddUDPSocket(RTC::UDPSocket* socket);
void AddTCPServer(RTC::TCPServer* server);
void SetUserData(void* userData);
void* GetUserData();
void Reset();
void Close();
void SetLocalDTLSRole(RTC::DTLSRole role);
void SetRemoteDTLSFingerprint(RTC::FingerprintHash hash, std::string& fingerprint);
void SetLocalSRTPKey(SRTPProfile srtp_profile, MS_BYTE* srtp_local_key, size_t srtp_local_key_len);
void SetRemoteSRTPKey(SRTPProfile srtp_profile, MS_BYTE* srtp_remote_key, size_t srtp_remote_key_len);
void SendRTPPacket(RTC::RTPPacket* packet);
void SendRTCPPacket(RTC::RTCPPacket* packet);
bool IsReadyForMedia();
void Dump();
private:
bool HasFlagICE();
bool HasFlagDTLS();
bool HasFlagSRTP();
bool SetSendingSource(RTC::TransportSource* source);
bool IsValidSource(RTC::TransportSource* source);
bool RemoveSource(RTC::TransportSource* source);
void RunDTLSHandlerIfReady();
/* Private methods to unify UDP and TCP behavior. */
private:
void onSTUNDataRecv(RTC::TransportSource* source, const MS_BYTE* data, size_t len);
void onDTLSDataRecv(RTC::TransportSource* source, const MS_BYTE* data, size_t len);
void onRTPDataRecv(RTC::TransportSource* source, const MS_BYTE* data, size_t len);
void onRTCPDataRecv(RTC::TransportSource* source, const MS_BYTE* data, size_t len);
/* Pure virtual methods inherited from RTC::UDPSocket::Listener. */
public:
virtual void onSTUNDataRecv(RTC::UDPSocket *socket, const MS_BYTE* data, size_t len, const struct sockaddr* remote_addr) override;
virtual void onDTLSDataRecv(RTC::UDPSocket *socket, const MS_BYTE* data, size_t len, const struct sockaddr* remote_addr) override;
virtual void onRTPDataRecv(RTC::UDPSocket *socket, const MS_BYTE* data, size_t len, const struct sockaddr* remote_addr) override;
virtual void onRTCPDataRecv(RTC::UDPSocket *socket, const MS_BYTE* data, size_t len, const struct sockaddr* remote_addr) override;
/* Pure virtual methods inherited from RTC::TCPServer::Listener. */
public:
virtual void onRTCTCPConnectionClosed(RTC::TCPServer* tcpServer, RTC::TCPConnection* connection, bool is_closed_by_peer) override;
/* Pure virtual methods inherited from RTC::TCPConnection::Listener. */
public:
virtual void onSTUNDataRecv(RTC::TCPConnection *connection, const MS_BYTE* data, size_t len) override;
virtual void onDTLSDataRecv(RTC::TCPConnection *connection, const MS_BYTE* data, size_t len) override;
virtual void onRTPDataRecv(RTC::TCPConnection *connection, const MS_BYTE* data, size_t len) override;
virtual void onRTCPDataRecv(RTC::TCPConnection *connection, const MS_BYTE* data, size_t len) override;
/* Pure virtual methods inherited from RTC::ICEServer::Listener. */
public:
virtual void onOutgoingSTUNMessage(RTC::ICEServer* iceServer, RTC::STUNMessage* msg, RTC::TransportSource* source) override;
virtual void onICEValidPair(RTC::ICEServer* iceServer, RTC::TransportSource* source, bool has_use_candidate) override;
/* Pure virtual methods inherited from RTC::DTLSHandler::Listener. */
public:
virtual void onOutgoingDTLSData(RTC::DTLSHandler* dtlsHandler, const MS_BYTE* data, size_t len) override;
virtual void onDTLSConnected(RTC::DTLSHandler* dtlsHandler) override;
virtual void onDTLSDisconnected(RTC::DTLSHandler* dtlsHandler) override;
virtual void onDTLSFailed(RTC::DTLSHandler* dtlsHandler) override;
virtual void onSRTPKeyMaterial(RTC::DTLSHandler* dtlsHandler, RTC::SRTPProfile srtp_profile, MS_BYTE* srtp_local_key, size_t srtp_local_key_len, MS_BYTE* srtp_remote_key, size_t srtp_remote_key_len) override;
virtual void onDTLSApplicationData(RTC::DTLSHandler* dtlsHandler, const MS_BYTE* data, size_t len) override;
private:
// Allocated by this:
RTC::ICEServer* iceServer = nullptr;
RTC::DTLSHandler* dtlsHandler = nullptr;
RTC::SRTPSession* srtpRecvSession = nullptr;
RTC::SRTPSession* srtpSendSession = nullptr;
// Passed by argument:
Listener* listener = nullptr;
std::vector<RTC::UDPSocket*> udpSockets;
std::vector<RTC::TCPServer*> tcpServers;
void* userData = nullptr;
// Others:
int flags = 0;
std::list<RTC::TransportSource> sources;
RTC::TransportSource* sendingSource = nullptr;
RTC::DTLSRole dtlsRole = RTC::DTLSRole::NONE;
bool isIcePaired = false;
bool isIcePairedWithUseCandidate = false;
};
/* Inline methods. */
inline
bool Transport::IsReadyForMedia() {
if (HasFlagDTLS() && ! this->dtlsHandler->IsConnected())
return false;
if (HasFlagSRTP() && (! this->srtpRecvSession || ! this->srtpSendSession))
return false;
return (this->sendingSource != nullptr);
}
inline
bool Transport::HasFlagICE() {
return this->flags & Flag::ICE;
}
inline
bool Transport::HasFlagDTLS() {
return this->flags & Flag::DTLS;
}
inline
bool Transport::HasFlagSRTP() {
return this->flags & Flag::SRTP;
}
inline
void Transport::SetUserData(void* userData) {
this->userData = userData;
}
inline
void* Transport::GetUserData() {
return this->userData;
}
/**
* Set the given source as a valid one and mark it as the sending source for
* outgoing data.
*
* @param source: A RTC::TransportSource (which is a UDP tuple or TCP connection).
* @return: true if the given source was not an already valid source,
* false otherwise.
*/
inline
bool Transport::SetSendingSource(RTC::TransportSource* source) {
// If the give source is already a valid one return.
// NOTE: The IsValidSource() method will also mark it as sending source.
if (IsValidSource(source))
return false;
// If there are Transport::maxSources sources then close and remove the last one.
if (this->sources.size() == Transport::maxSources) {
RTC::TransportSource* last_source = &(*this->sources.end());
last_source->Close();
this->sources.pop_back();
}
// Add the new source at the beginning.
this->sources.push_front(*source);
// Set it as sending source (make it point to the first source in the list).
this->sendingSource = &(*this->sources.begin());
// If it is UDP then we must store the remote address (until now it is
// just a pointer that will be freed soon).
if (this->sendingSource->IsUDP())
this->sendingSource->StoreUdpRemoteAddress();
return true;
}
/**
* Check whether the given source is contained in the list of valid sources for
* this transport. In case it is, the given source is also marked as sending
* source for the outgoing data.
*
* @param source: The RTC::TransportSource to check.
* @return: true if it is a valid source, false otherwise.
*/
inline
bool Transport::IsValidSource(RTC::TransportSource* source) {
// If there is no sending source yet then we know that the sources list
// is empty, so return false.
if (! this->sendingSource)
return false;
// First check the current sending source. If it matches then return true.
if (this->sendingSource->Compare(source))
return true;
// Otherwise check other valid source in the sources list.
for (auto it = this->sources.begin(); it != this->sources.end(); ++it) {
RTC::TransportSource* valid_source = &(*it);
// If found set it as sending source.
if (valid_source->Compare(source)) {
this->sendingSource = valid_source;
return true;
}
}
return false;
}
/**
* Remove the given source from the list of valid sources. Also update the
* sending source if the given source was the sending source and make it point
* to the next valid source (if any).
*
* @param source: The RTC::TransportSource to remove.
* @return: true if the given source was present in the list of valid
* sources, false otherwise.
*/
inline
bool Transport::RemoveSource(RTC::TransportSource* source) {
for (auto it = this->sources.begin(); it != this->sources.end(); ++it) {
RTC::TransportSource* valid_source = &(*it);
// If the source was a valid source then remove it.
if (valid_source->Compare(source)) {
this->sources.erase(it);
// If it was the sending source then unset it and set the sending
// source to the first valid source (if any).
if (this->sendingSource == valid_source) {
if (this->sources.begin() != this->sources.end()) {
this->sendingSource = &(*this->sources.begin());
}
else {
this->sendingSource = nullptr;
if (HasFlagICE()) {
// This is just useful is there are just TCP sources.
this->isIcePaired = false;
this->isIcePairedWithUseCandidate = false;
}
}
}
return true;
}
}
return false;
}
} // namespace RTC
#endif
#ifndef MS_RTC_TRANSPORT_SOURCE_H
#define MS_RTC_TRANSPORT_SOURCE_H
#include "common.h"
#include "RTC/UDPSocket.h"
#include "RTC/TCPConnection.h"
#include "Utils.h"
#include <string>
namespace RTC {
class TransportSource {
public:
enum class Type {
UDP = 1,
TCP
};
public:
TransportSource(RTC::UDPSocket* udpSocket, const struct sockaddr* udpRemoteAddr);
TransportSource(RTC::TCPConnection* tcpConnection);
void StoreUdpRemoteAddress();
bool IsUDP();
bool IsTCP();
bool Compare(TransportSource* source);
void Send(const MS_BYTE* data, size_t len);
const struct sockaddr* GetRemoteAddress();
void Close();
void Dump();
private:
// Passed by argument:
RTC::UDPSocket* udpSocket = nullptr;
struct sockaddr* udpRemoteAddr = nullptr;
sockaddr_storage udpRemoteAddrStorage;
RTC::TCPConnection* tcpConnection = nullptr;
// Others:
Type type;
};
/* Inline methods. */
inline
TransportSource::TransportSource(RTC::UDPSocket* udpSocket, const struct sockaddr* udpRemoteAddr) :
udpSocket(udpSocket),
udpRemoteAddr((struct sockaddr*)udpRemoteAddr),
type(Type::UDP)
{}
inline
TransportSource::TransportSource(RTC::TCPConnection* tcpConnection) :
tcpConnection(tcpConnection),
type(Type::TCP)
{}
inline
void TransportSource::StoreUdpRemoteAddress() {
// Clone the given address into our address storage and make the sockaddr
// pointer point to it.
this->udpRemoteAddrStorage = Utils::IP::CopyAddress(udpRemoteAddr);
this->udpRemoteAddr = (struct sockaddr*)&this->udpRemoteAddrStorage;
}
inline
bool TransportSource::IsUDP() {
return (this->type == Type::UDP);
}
inline
bool TransportSource::IsTCP() {
return (this->type == Type::TCP);
}
inline
bool TransportSource::Compare(TransportSource* source) {
if (this->type == Type::UDP && source->IsUDP()) {
return (this->udpSocket == source->udpSocket && Utils::IP::CompareAddresses(this->udpRemoteAddr, source->GetRemoteAddress()));
}
else if (this->type == Type::TCP && source->IsTCP()) {
return (this->tcpConnection == source->tcpConnection);
}
else {
return false;
}
}
inline
void TransportSource::Send(const MS_BYTE* data, size_t len) {
if (this->type == Type::UDP)
this->udpSocket->Send(data, len, this->udpRemoteAddr);
else
this->tcpConnection->Send(data, len);
}
inline
const struct sockaddr* TransportSource::GetRemoteAddress() {
if (this->type == Type::UDP)
return (const struct sockaddr*)this->udpRemoteAddr;
else
return this->tcpConnection->GetPeerAddress();
}
inline
void TransportSource::Close() {
if (this->type == Type::TCP)
this->tcpConnection->Close();
}
} // namespace RTC
#endif
#ifndef MS_RTC_UDP_SOCKET_H
#define MS_RTC_UDP_SOCKET_H
#include "common.h"
#include "handles/UDPSocket.h"
#include <unordered_map>
#include <uv.h>
namespace RTC {
class UDPSocket : public ::UDPSocket {
public:
class Listener {
public:
virtual void onSTUNDataRecv(RTC::UDPSocket *socket, const MS_BYTE* data, size_t len, const struct sockaddr* remote_addr) = 0;
virtual void onDTLSDataRecv(RTC::UDPSocket *socket, const MS_BYTE* data, size_t len, const struct sockaddr* remote_addr) = 0;
virtual void onRTPDataRecv(RTC::UDPSocket *socket, const MS_BYTE* data, size_t len, const struct sockaddr* remote_addr) = 0;
virtual void onRTCPDataRecv(RTC::UDPSocket *socket, const MS_BYTE* data, size_t len, const struct sockaddr* remote_addr) = 0;
};
public:
static void ClassInit();
static RTC::UDPSocket* New(int address_family);
static void NewPair(int address_family, RTC::UDPSocket* sockets[]);
private:
static void RandomizePort(int address_family, uv_udp_t* uvHandles[], bool pair);
private:
static struct sockaddr_storage sockaddrStorageIPv4;
static struct sockaddr_storage sockaddrStorageIPv6;
static MS_PORT minPort;
static MS_PORT maxPort;
typedef std::unordered_map<MS_PORT, bool> AvailablePorts;
static AvailablePorts availableIPv4Ports;
static AvailablePorts availableIPv6Ports;
public:
UDPSocket(uv_udp_t* uvHandle);
void SetListener(Listener* listener);
/* Pure virtual methods inherited from ::UDPSocket. */
public:
virtual void userOnUDPDatagramRecv(const MS_BYTE* data, size_t len, const struct sockaddr* addr) override;
virtual void userOnUDPSocketClosed() override;
private:
// Passed by argument:
Listener* listener = nullptr;
};
/* Inline methods. */
inline
void UDPSocket::SetListener(Listener* listener) {
this->listener = listener;
}
} // namespace RTC
#endif
#ifndef MS_SETTINGS_H
#define MS_SETTINGS_H
#include "common.h"
#include <map>
#include <string>
#include <vector>
#include <libconfig.h++>
extern "C" {
#include <syslog.h>
}
class Settings {
public:
// Struct holding command line arguments.
struct Arguments {
std::string configFile;
bool daemonize { false };
std::string pidFile;
std::string user;
std::string group;
};
// Struct holding the configuration (can be overriden by a config file).
struct Configuration {
unsigned int logLevel { LOG_DEBUG };
unsigned int syslogFacility { LOG_USER };
int numWorkers { 0 };
struct {
std::string listenIP { "127.0.0.1" };
MS_PORT listenPort { 4080 };
} ControlProtocol;
struct {
std::string listenIPv4;
std::string listenIPv6;
MS_PORT minPort { 10000 };
MS_PORT maxPort { 59999 };
std::string dtlsCertificateFile;
std::string dtlsPrivateKeyFile;
// Private fields.
bool hasIPv4 { false };
bool hasIPv6 { false };
} RTC;
};
public:
static void ReadArguments(int argc, char* argv[]);
static void PrintHelp(bool error);
static void PrintVersion();
static void SetDefaultConfiguration();
static void ReadConfigurationFile();
static void ConfigurationPostCheck();
static bool ReloadConfigurationFile();
static void PrintConfiguration();
private:
static libconfig::Config* ParseConfigFile();
static void SetLogLevel(std::string &level);
static void SetSyslogFacility(std::string &facility);
static void SetNumWorkers(int numWorkers);
static void SetDefaultNumWorkers();
static void SetControlProtocolListenIP(const std::string &ip);
static void SetControlProtocolListenPort(MS_PORT port);
static void SetRTClistenIPv4(const std::string &ip);
static void SetRTClistenIPv6(const std::string &ip);
static void SetDefaultRTClistenIP(int requested_family);
static bool IsBindableIP(const std::string &ip, int family, int* _bind_err);
static void SetRTCports(MS_PORT minPort, MS_PORT maxPort);
static void SetDtlsCertificateAndPrivateKeyFiles(std::string& dtlsCertificateFile, std::string& dtlsPrivateKeyFile);
public:
static struct Arguments arguments;
static struct Configuration configuration;
private:
static std::map<std::string, unsigned int> string2LogLevel;
static std::map<unsigned int, std::string> logLevel2String;
static std::map<std::string, unsigned int> string2SyslogFacility;
static std::map<unsigned int, std::string> syslogFacility2String;
};
#endif
#ifndef MS_UTILS_H
#define MS_UTILS_H
#include "common.h"
#include <string>
#include <cstring> // std::memcmp(), std::memcpy()
#include <openssl/hmac.h>
namespace Utils {
class IP {
public:
static int GetFamily(const char *ip, size_t ip_len);
static int GetFamily(const std::string &ip);
static void GetAddressInfo(const struct sockaddr* addr, int* family, std::string &ip, MS_PORT* port);
static bool CompareAddresses(const struct sockaddr* addr1, const struct sockaddr* addr2);
static struct sockaddr_storage CopyAddress(const struct sockaddr* addr);
};
/* Inline static methods. */
inline
int IP::GetFamily(const std::string &ip) {
return GetFamily(ip.c_str(), ip.size());
}
inline
bool IP::CompareAddresses(const struct sockaddr* addr1, const struct sockaddr* addr2) {
// Compare family.
if (addr1->sa_family != addr2->sa_family || (addr1->sa_family != AF_INET && addr1->sa_family != AF_INET6))
return false;
// Compare port.
if (((struct sockaddr_in*)addr1)->sin_port != ((struct sockaddr_in*)addr2)->sin_port)
return false;
// Compare IP.
switch(addr1->sa_family) {
case AF_INET:
if (std::memcmp(&((struct sockaddr_in*)addr1)->sin_addr, &((struct sockaddr_in*)addr2)->sin_addr, 4) == 0)
return true;
break;
case AF_INET6:
if (std::memcmp(&((struct sockaddr_in6*)addr1)->sin6_addr, &((struct sockaddr_in6*)addr2)->sin6_addr, 16) == 0)
return true;
break;
default:
return false;
}
return false;
}
inline
struct sockaddr_storage IP::CopyAddress(const struct sockaddr* addr) {
struct sockaddr_storage copied_addr;
switch(addr->sa_family) {
case AF_INET:
std::memcpy(&copied_addr, addr, sizeof(struct sockaddr_in));
break;
case AF_INET6:
std::memcpy(&copied_addr, addr, sizeof(struct sockaddr_in6));
break;
}
return copied_addr;
}
class Socket {
public:
/**
* Builds a pair of connected sockets. The sockets are created in non-blocking
* mode and with close-exec (so they are closed after fork()).
*
* @param family Socket family (AF_UNIX...).
* @param type Socket type (SOCK_DGRAM...) + flags.
* @param fds Array with two integers.
*
* In case of error throws a MediaSoupError exception.
*/
static void BuildSocketPair(int family, int type, int* fds);
private:
static bool SetNonBlock(int fd);
static bool SetCloExec(int fd);
};
class File {
public:
static void CheckFile(const char* file);
};
class Byte {
public:
/**
* All these functions get and set bytes in Network Byte Order (Big Endian).
*/
static MS_BYTE Get1Byte(const MS_BYTE* data, size_t i);
static MS_2BYTES Get2Bytes(const MS_BYTE* data, size_t i);
static MS_4BYTES Get3Bytes(const MS_BYTE* data, size_t i);
static MS_4BYTES Get4Bytes(const MS_BYTE* data, size_t i);
static MS_8BYTES Get8Bytes(const MS_BYTE* data, size_t i);
static void Set1Byte(MS_BYTE* data, size_t i, MS_BYTE value);
static void Set2Bytes(MS_BYTE* data, size_t i, MS_2BYTES value);
static void Set3Bytes(MS_BYTE* data, size_t i, MS_4BYTES value);
static void Set4Bytes(MS_BYTE* data, size_t i, MS_4BYTES value);
static void Set8Bytes(MS_BYTE* data, size_t i, MS_8BYTES value);
static MS_2BYTES PadTo4Bytes(MS_2BYTES size);
static MS_4BYTES PadTo4Bytes(MS_4BYTES size);
};
/* Inline static methods. */
inline
MS_BYTE Byte::Get1Byte(const MS_BYTE* data, size_t i) {
return data[i];
}
inline
MS_2BYTES Byte::Get2Bytes(const MS_BYTE* data, size_t i) {
return (MS_2BYTES)(data[i+1]) | ((MS_2BYTES)(data[i]))<<8;
}
inline
MS_4BYTES Byte::Get3Bytes(const MS_BYTE* data, size_t i) {
return (MS_4BYTES)(data[i+2]) | ((MS_4BYTES)(data[i+1]))<<8 | ((MS_4BYTES)(data[i]))<<16;
}
inline
MS_4BYTES Byte::Get4Bytes(const MS_BYTE* data, size_t i) {
return (MS_4BYTES)(data[i+3]) | ((MS_4BYTES)(data[i+2]))<<8 | ((MS_4BYTES)(data[i+1]))<<16 | ((MS_4BYTES)(data[i]))<<24;
}
inline
MS_8BYTES Byte::Get8Bytes(const MS_BYTE* data, size_t i) {
return ((MS_8BYTES)Byte::Get4Bytes(data,i))<<32 | Byte::Get4Bytes(data,i+4);
}
inline
void Byte::Set1Byte(MS_BYTE* data, size_t i, MS_BYTE value) {
data[i] = value;
}
inline
void Byte::Set2Bytes(MS_BYTE* data, size_t i, MS_2BYTES value) {
data[i+1] = (MS_BYTE)(value);
data[i] = (MS_BYTE)(value>>8);
}
inline
void Byte::Set3Bytes(MS_BYTE* data, size_t i, MS_4BYTES value) {
data[i+2] = (MS_BYTE)(value);
data[i+1] = (MS_BYTE)(value>>8);
data[i] = (MS_BYTE)(value>>16);
}
inline
void Byte::Set4Bytes(MS_BYTE* data, size_t i, MS_4BYTES value) {
data[i+3] = (MS_BYTE)(value);
data[i+2] = (MS_BYTE)(value>>8);
data[i+1] = (MS_BYTE)(value>>16);
data[i] = (MS_BYTE)(value>>24);
}
inline
void Byte::Set8Bytes(MS_BYTE* data, size_t i, MS_8BYTES value) {
data[i+7] = (MS_BYTE)(value);
data[i+6] = (MS_BYTE)(value>>8);
data[i+5] = (MS_BYTE)(value>>16);
data[i+4] = (MS_BYTE)(value>>24);
data[i+3] = (MS_BYTE)(value>>32);
data[i+2] = (MS_BYTE)(value>>40);
data[i+1] = (MS_BYTE)(value>>48);
data[i] = (MS_BYTE)(value>>56);
}
inline
MS_2BYTES Byte::PadTo4Bytes(MS_2BYTES size) {
// If size is not multiple of 32 bits then pad it.
if (size & 0x03)
return (size & 0xFFFC) + 4;
else
return size;
}
inline
MS_4BYTES Byte::PadTo4Bytes(MS_4BYTES size) {
// If size is not multiple of 32 bits then pad it.
if (size & 0x03)
return (size & 0xFFFFFFFC) + 4;
else
return size;
}
class Crypto {
public:
static void ThreadInit();
static void ThreadDestroy();
static unsigned int GetRandomUInt(unsigned int min, unsigned int max);
static const char* GetRandomHexString(char* str, size_t len);
static MS_4BYTES CRC32(const MS_BYTE* data, size_t size);
static const MS_BYTE* HMAC_SHA1(const std::string &key, const MS_BYTE* data, size_t len);
private:
static __thread unsigned int seed;
static __thread HMAC_CTX hmacSha1Ctx;
static __thread MS_BYTE hmacSha1Buffer[];
static const MS_4BYTES crc32Table[256];
};
/* Inline static methods. */
inline
unsigned int Crypto::GetRandomUInt(unsigned int min, unsigned int max) {
// NOTE: This is the original, but produces very small values.
// Crypto::seed = (214013 * Crypto::seed) + 2531011;
// return (((Crypto::seed>>16)&0x7FFF) % (max - min + 1)) + min;
// This seems to produce better results.
Crypto::seed = (unsigned int)((214013 * Crypto::seed) + 2531011);
return (((Crypto::seed>>4)&0x7FFF7FFF) % (max - min + 1)) + min;
}
inline
const char* Crypto::GetRandomHexString(char* buffer, size_t len) {
static const char hex_chars[] = {
'0','1','2','3','4','5','6','7','8','9',
'A','B','C','D','E','F','G','H','I','J',
'K','L','M','N','O','P','Q','R','S','T',
'U','V','W','X','Y','Z'
};
for (size_t i = 0; i < len; ++i) {
buffer[i] = hex_chars[GetRandomUInt(0, sizeof(hex_chars) - 1)];
}
return buffer;
}
inline
MS_4BYTES Crypto::CRC32(const MS_BYTE* data, size_t size) {
MS_4BYTES crc = 0xFFFFFFFF;
const MS_BYTE* p = data;
while (size--)
crc = Crypto::crc32Table[(crc ^ *p++) & 0xFF] ^ (crc >> 8);
return crc ^ ~0U;
}
} // namespace Utils
#endif /* MS_UTILS_H */
#ifndef MS_VERSION_H
#define MS_VERSION_H
#include <string>
class Version {
public:
static const std::string GetVersion();
static const std::string GetNameAndVersion();
public:
static const int versionMajor;
static const int versionMinor;
static const int versionTiny;
static const std::string name;
static const std::string command;
static const std::string copyright;
};
#endif
#ifndef MS_WORKER_H
#define MS_WORKER_H
#include "common.h"
#include "ControlProtocol/UnixStreamSocket.h"
#include "ControlProtocol/Message.h"
#include <map>
#include <atomic>
// TMP
#include "RTC/Room.h"
class Worker :
public ControlProtocol::UnixStreamSocket::Listener
{
public:
static void ThreadInit(int workerId);
static void ThreadDestroy();
static void SetWorker(int workerId, Worker* worker);
static int CountWorkers();
static bool AreAllWorkersRunning();
static int GetControlProtocolRemoteSocket(int workerId);
private:
typedef std::map <int, Worker*> Workers;
static Workers workers;
static int numWorkers;
static std::atomic<int> numWorkersRunning;
public:
Worker(int workerId);
~Worker();
void Close();
int GetControlProtocolRemoteSocket();
private:
void BlockSignals();
/* Methods inherited from ControlProtocol::UnixStreamSocket::Listener. */
public:
virtual void onControlProtocolMessage(ControlProtocol::UnixStreamSocket* unixSocket, ControlProtocol::Message* msg, const MS_BYTE* raw, size_t len) override;
virtual void onControlProtocolUnixStreamSocketClosed(ControlProtocol::UnixStreamSocket* unixSocket, bool is_closed_by_peer) override;
private:
// Allocated by this:
ControlProtocol::UnixStreamSocket* controlProtocolUnixStreamSocket = nullptr;
// Others:
int workerId = 0;
int controlProtocolRemoteSocket = 0;
// TMP
RTC::Room* room = nullptr;
};
#endif
#ifndef MS_COMMON_H
#define MS_COMMON_H
#include <cstddef> // size_t
#include <cstdint> // uint8_t, etc
#include <sys/socket.h> // struct sockaddr, struct sockaddr_storage, AF_INET, AF_INET6
#include <netinet/in.h> // sockaddr_in, sockaddr_in6
#include <arpa/inet.h> // htonl(), htons(), ntohl(), ntohs()
#include <pthread.h> // __thread
#define MS_BYTE uint8_t
#define MS_2BYTES uint16_t
#define MS_4BYTES uint32_t
#define MS_8BYTES uint64_t
#define MS_PORT uint16_t
// Detect Little-Endian or Big-Endian CPU.
// NOTE: If the macro MS_LITTLE_ENDIAN or MS_BIG_ENDIAN is already defined
// then don't autodetect it.
#if !defined(MS_LITTLE_ENDIAN) && !defined(MS_BIG_ENDIAN)
#if defined(__BYTE_ORDER__) && defined(__ORDER_LITTLE_ENDIAN__) && __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__
#define MS_LITTLE_ENDIAN
#elif defined(__BYTE_ORDER__) && defined(__ORDER_BIG_ENDIAN__) && __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__
#define MS_BIG_ENDIAN
#else
#error "cannot determine whether the processor is Little-Endian or Big-Endian"
#endif
#endif
#endif
#ifndef MS_SIGNALS_HANDLER_H
#define MS_SIGNALS_HANDLER_H
#include <vector>
#include <string>
#include <uv.h>
class SignalsHandler {
public:
class Listener {
public:
virtual void onSignal(SignalsHandler* signalsHandler, int signum) = 0;
virtual void onSignalsHandlerClosed(SignalsHandler* signalsHandler) = 0;
};
public:
SignalsHandler(Listener* listener);
void AddSignal(int signum, std::string name);
void Close();
/* Callbacks fired by UV events. */
public:
void onUvSignal(int signum);
private:
// Allocated by this:
typedef std::vector<uv_signal_t*> UvHandles;
UvHandles uvHandles;
// Passed by argument:
Listener* listener = nullptr;
};
#endif
#ifndef MS_TCP_CONNECTION_H
#define MS_TCP_CONNECTION_H
#include "common.h"
#include <string>
#include <uv.h>
class TCPConnection {
public:
class Listener {
public:
virtual void onTCPConnectionClosed(TCPConnection* connection, bool is_closed_by_peer) = 0;
};
public:
/* Struct for the data field of uv_req_t when writing into the connection. */
typedef struct UvWriteData {
TCPConnection* connection;
uv_write_t req;
MS_BYTE store[1];
} UvWriteData;
public:
TCPConnection(size_t bufferSize);
virtual ~TCPConnection();
void Setup(Listener* listener, const std::string &localIP, MS_PORT localPort);
uv_tcp_t* GetUvHandle();
void Start();
void Write(const MS_BYTE* data, size_t len);
void Write(const MS_BYTE* data1, size_t len1, const MS_BYTE* data2, size_t len2);
void Write(const std::string &data);
const std::string& GetLocalIP();
MS_PORT GetLocalPort();
const struct sockaddr* GetPeerAddress();
const std::string& GetPeerIP();
MS_PORT GetPeerPort();
void SetUserData(void* userData);
void* GetUserData();
void Close();
virtual void Dump();
private:
bool SetPeerAddress();
/* Callbacks fired by UV events. */
public:
void onUvReadAlloc(size_t suggested_size, uv_buf_t* buf);
void onUvRead(ssize_t nread, const uv_buf_t* buf);
void onUvWriteError(int error);
void onUvShutdown(uv_shutdown_t* req, int status);
void onUvClosed();
/* Pure virtual methods that must be implemented by the subclass. */
protected:
virtual void userOnTCPConnectionRead(const MS_BYTE* data, size_t len) = 0;
private:
// Allocated by this:
uv_tcp_t* uvHandle = nullptr;
// Passed by argument:
Listener* listener = nullptr;
void* userData = nullptr;
// Others.
bool isClosing = false;
bool isClosedByPeer = false;
bool hasError = false;
protected:
// Allocated by this:
MS_BYTE* buffer = nullptr;
// Passed by argument:
size_t bufferSize = 0;
// Others.
size_t bufferDataLen = 0;
std::string localIP;
MS_PORT localPort = 0;
struct sockaddr_storage peerAddr;
std::string peerIP;
MS_PORT peerPort = 0;
};
/* Inline methods. */
inline
uv_tcp_t* TCPConnection::GetUvHandle() {
return this->uvHandle;
}
inline
void TCPConnection::Write(const std::string &data) {
Write((const MS_BYTE*)data.c_str(), data.size());
}
inline
const std::string& TCPConnection::GetLocalIP() {
return this->localIP;
}
inline
MS_PORT TCPConnection::GetLocalPort() {
return this->localPort;
}
inline
const struct sockaddr* TCPConnection::GetPeerAddress() {
return (const struct sockaddr*)&this->peerAddr;
}
inline
const std::string& TCPConnection::GetPeerIP() {
return this->peerIP;
}
inline
MS_PORT TCPConnection::GetPeerPort() {
return this->peerPort;
}
inline
void TCPConnection::SetUserData(void* userData) {
this->userData = userData;
}
inline
void* TCPConnection::GetUserData() {
return this->userData;
}
#endif
#ifndef MS_TCP_SERVER_H
#define MS_TCP_SERVER_H
#include "common.h"
#include "handles/TCPConnection.h"
#include <string>
#include <unordered_set>
#include <uv.h>
class TCPServer : public TCPConnection::Listener {
public:
TCPServer(const std::string &ip, MS_PORT port, int backlog);
/**
* uvHandle must be an already initialized and binded uv_tcp_t pointer.
*/
TCPServer(uv_tcp_t* uvHandle, int backlog);
virtual ~TCPServer();
const struct sockaddr* GetLocalAddress();
const std::string& GetLocalIP();
MS_PORT GetLocalPort();
void SetUserData(void* userData);
void* GetUserData();
size_t GetNumConnections();
void Close();
bool IsClosing();
virtual void Dump();
private:
bool SetLocalAddress();
/* Pure virtual methods that must be implemented by the subclass. */
protected:
virtual void userOnTCPConnectionAlloc(TCPConnection** connection) = 0;
virtual void userOnNewTCPConnection(TCPConnection* connection) = 0;
virtual void userOnTCPConnectionClosed(TCPConnection* connection, bool is_closed_by_peer) = 0;
virtual void userOnTCPServerClosed() = 0;
/* Callbacks fired by UV events. */
public:
void onUvConnection(int status);
void onUvClosed();
/* Methods inherited from TCPConnection::Listener. */
public:
virtual void onTCPConnectionClosed(TCPConnection* connection, bool is_closed_by_peer);
private:
// Allocated by this (may be passed by argument):
uv_tcp_t* uvHandle = nullptr;
// Passed by argument:
void* userData = nullptr;
// Others:
typedef std::unordered_set<TCPConnection*> TCPConnections;
TCPConnections connections;
bool isClosing = false;
protected:
struct sockaddr_storage localAddr;
std::string localIP;
MS_PORT localPort = 0;
};
/* Inline methods. */
inline
void TCPServer::SetUserData(void* userData) {
this->userData = userData;
}
inline
void* TCPServer::GetUserData() {
return this->userData;
}
inline
size_t TCPServer::GetNumConnections() {
return this->connections.size();
}
inline
bool TCPServer::IsClosing() {
return this->isClosing;
}
#endif
#ifndef MS_TIMER_H
#define MS_TIMER_H
#include "common.h"
#include <uv.h>
class Timer {
public:
class Listener {
public:
virtual void onTimer(Timer* timer) = 0;
};
public:
Timer(Listener* listener);
void Start(MS_8BYTES timeout);
void Stop();
void Close();
/* Callbacks fired by UV events. */
public:
void onUvTimer();
private:
// Allocated by this:
uv_timer_t* uvHandle = nullptr;
// Passed by argument:
Listener* listener = nullptr;
};
#endif
#ifndef MS_UDP_SOCKET_H
#define MS_UDP_SOCKET_H
#include "common.h"
#include <string>
#include <uv.h>
class UDPSocket {
public:
/* Struct for the data field of uv_req_t when sending a datagram. */
typedef struct UvSendData {
UDPSocket* socket;
uv_udp_send_t req;
MS_BYTE store[1];
} UvSendData;
private:
static __thread MS_BYTE readBuffer[];
public:
UDPSocket(const std::string &ip, MS_PORT port);
/**
* uvHandle must be an already initialized and binded uv_udp_t pointer.
*/
UDPSocket(uv_udp_t* uvHandle);
virtual ~UDPSocket();
void Send(const MS_BYTE* data, size_t len, const struct sockaddr* addr);
void Send(const std::string &data, const struct sockaddr* addr);
void Send(const MS_BYTE* data, size_t len, const std::string &ip, MS_PORT port);
void Send(const std::string &data, const std::string &ip, MS_PORT port);
const struct sockaddr* GetLocalAddress();
const std::string& GetLocalIP();
MS_PORT GetLocalPort();
void SetUserData(void* userData);
void* GetUserData();
void Close();
virtual void Dump();
private:
bool SetLocalAddress();
/* Callbacks fired by UV events. */
public:
void onUvRecvAlloc(size_t suggested_size, uv_buf_t* buf);
void onUvRecv(ssize_t nread, const uv_buf_t* buf, const struct sockaddr* addr, unsigned int flags);
void onUvSendError(int error);
void onUvClosed();
/* Pure virtual methods that must be implemented by the subclass. */
protected:
virtual void userOnUDPDatagramRecv(const MS_BYTE* data, size_t len, const struct sockaddr* addr) = 0;
virtual void userOnUDPSocketClosed() = 0;
private:
// Allocated by this (may be passed by argument):
uv_udp_t* uvHandle = nullptr;
// Passed by argument:
void* userData = nullptr;
// Others:
bool isClosing = false;
protected:
struct sockaddr_storage localAddr;
std::string localIP;
MS_PORT localPort = 0;
};
/* Inline methods. */
inline
void UDPSocket::Send(const std::string &data, const struct sockaddr* addr) {
Send((const MS_BYTE*)data.c_str(), data.size(), addr);
}
inline
void UDPSocket::Send(const std::string &data, const std::string &ip, MS_PORT port) {
Send((const MS_BYTE*)data.c_str(), data.size(), ip, port);
}
inline
const struct sockaddr* UDPSocket::GetLocalAddress() {
return (const struct sockaddr*)&this->localAddr;
}
inline
const std::string& UDPSocket::GetLocalIP() {
return this->localIP;
}
inline
MS_PORT UDPSocket::GetLocalPort() {
return this->localPort;
}
inline
void UDPSocket::SetUserData(void* userData) {
this->userData = userData;
}
inline
void* UDPSocket::GetUserData() {
return this->userData;
}
#endif
#ifndef MS_UNIX_STREAM_SOCKET_H
#define MS_UNIX_STREAM_SOCKET_H
#include "common.h"
#include <string>
#include <uv.h>
class UnixStreamSocket {
public:
/* Struct for the data field of uv_req_t when writing data. */
typedef struct UvWriteData {
UnixStreamSocket* socket;
uv_write_t req;
MS_BYTE store[1];
} UvWriteData;
public:
UnixStreamSocket(int fd, size_t bufferSize);
virtual ~UnixStreamSocket();
void Write(const MS_BYTE* data, size_t len);
void Write(const std::string &data);
void SetUserData(void* userData);
void* GetUserData();
void Close();
virtual void Dump();
/* Callbacks fired by UV events. */
public:
void onUvReadAlloc(size_t suggested_size, uv_buf_t* buf);
void onUvRead(ssize_t nread, const uv_buf_t* buf);
void onUvWriteError(int error);
void onUvShutdown(uv_shutdown_t* req, int status);
void onUvClosed();
/* Pure virtual methods that must be implemented by the subclass. */
protected:
virtual void userOnUnixStreamRead(const MS_BYTE* data, size_t len) = 0;
virtual void userOnUnixStreamSocketClosed(bool is_closed_by_peer) = 0;
private:
// Allocated by this:
uv_pipe_t* uvHandle = nullptr;
// Passed by argument:
void* userData = nullptr;
// Others:
bool isClosing = false;
bool isClosedByPeer = false;
bool hasError = false;
protected:
// Allocated by this:
MS_BYTE* buffer = nullptr;
// Passed by argument:
size_t bufferSize = 0;
// Others:
size_t bufferDataLen = 0;
};
/* Inline methods. */
inline
void UnixStreamSocket::Write(const std::string &data) {
Write((const MS_BYTE*)data.c_str(), data.size());
}
inline
void UnixStreamSocket::SetUserData(void* userData) {
this->userData = userData;
}
inline
void* UnixStreamSocket::GetUserData() {
return this->userData;
}
#endif
#define MS_CLASS "ControlProtocol::Message"
#include "ControlProtocol/Message.h"
#include "Logger.h"
namespace ControlProtocol {
/* Instance methods. */
Message::Message(Kind kind) :
kind(kind)
{
MS_TRACE();
}
Message::~Message() {
MS_TRACE();
}
// TMP: must be pure virtual.
bool Message::IsValid() {
MS_TRACE();
return true;
}
} // namespace ControlProtocol
#line 1 "src/ControlProtocol/Parser.rl"
#define MS_CLASS "ControlProtocol::Parser"
#include "ControlProtocol/Parser.h"
#include "ControlProtocol/messages.h"
#include "Logger.h"
#include <cstdlib> // std::atol()
#define MARK(M, P) (M = (P) - buffer)
#define LEN(AT, P) ((P) - buffer - (AT))
#define LEN_FROM_MARK (p - buffer - this->mark)
#define PTR_TO(F) (buffer + (F))
#define PTR_TO_MARK (const char*)(buffer + this->mark)
namespace ControlProtocol {
/**
* Ragel: machine definition
*/
#line 56 "src/ControlProtocol/Parser.rl"
/**
* Ragel: %%write data
* This generates Ragel's static variables such as:
* static const int MessageParser_start
*/
#line 36 "src/ControlProtocol/Parser.cpp"
static const int MessageParser_start = 1;
static const int MessageParser_first_final = 90;
static const int MessageParser_error = 0;
#line 65 "src/ControlProtocol/Parser.rl"
Parser::Parser() {
MS_TRACE();
Reset();
}
Parser::~Parser() {
MS_TRACE();
}
Message* Parser::Parse(const MS_BYTE* buffer, size_t len) {
MS_TRACE();
// Used by Ragel:
const unsigned char* p;
const unsigned char* pe;
// const unsigned char* eof;
MS_ASSERT(this->parsedLen <= len, "parsedLen pasts end of buffer");
p = (const unsigned char*)buffer + this->parsedLen;
pe = (const unsigned char*)buffer + len;
// eof = nullptr; // Ragel manual pag 36 (eof variable).
/**
* Ragel: %%write exec
* This updates cs variable needed by Ragel (so this->cs at the end) and p.
*/
#line 78 "src/ControlProtocol/Parser.cpp"
{
if ( p == pe )
goto _test_eof;
switch ( cs )
{
case 1:
if ( (*p) == 82u )
goto st2;
goto st0;
st0:
cs = 0;
goto _out;
st2:
if ( ++p == pe )
goto _test_eof2;
case 2:
if ( (*p) == 101u )
goto st3;
goto st0;
st3:
if ( ++p == pe )
goto _test_eof3;
case 3:
if ( (*p) == 113u )
goto st4;
goto st0;
st4:
if ( ++p == pe )
goto _test_eof4;
case 4:
if ( (*p) == 117u )
goto st5;
goto st0;
st5:
if ( ++p == pe )
goto _test_eof5;
case 5:
if ( (*p) == 101u )
goto st6;
goto st0;
st6:
if ( ++p == pe )
goto _test_eof6;
case 6:
if ( (*p) == 115u )
goto st7;
goto st0;
st7:
if ( ++p == pe )
goto _test_eof7;
case 7:
if ( (*p) == 116u )
goto st8;
goto st0;
st8:
if ( ++p == pe )
goto _test_eof8;
case 8:
if ( (*p) == 32u )
goto st9;
goto st0;
st9:
if ( ++p == pe )
goto _test_eof9;
case 9:
switch( (*p) ) {
case 65u: goto st10;
case 67u: goto st56;
case 72u: goto st83;
}
goto st0;
st10:
if ( ++p == pe )
goto _test_eof10;
case 10:
if ( (*p) == 117u )
goto st11;
goto st0;
st11:
if ( ++p == pe )
goto _test_eof11;
case 11:
if ( (*p) == 116u )
goto st12;
goto st0;
st12:
if ( ++p == pe )
goto _test_eof12;
case 12:
if ( (*p) == 104u )
goto st13;
goto st0;
st13:
if ( ++p == pe )
goto _test_eof13;
case 13:
if ( (*p) == 101u )
goto st14;
goto st0;
st14:
if ( ++p == pe )
goto _test_eof14;
case 14:
if ( (*p) == 110u )
goto st15;
goto st0;
st15:
if ( ++p == pe )
goto _test_eof15;
case 15:
if ( (*p) == 116u )
goto st16;
goto st0;
st16:
if ( ++p == pe )
goto _test_eof16;
case 16:
if ( (*p) == 105u )
goto st17;
goto st0;
st17:
if ( ++p == pe )
goto _test_eof17;
case 17:
if ( (*p) == 99u )
goto st18;
goto st0;
st18:
if ( ++p == pe )
goto _test_eof18;
case 18:
if ( (*p) == 97u )
goto st19;
goto st0;
st19:
if ( ++p == pe )
goto _test_eof19;
case 19:
if ( (*p) == 116u )
goto st20;
goto st0;
st20:
if ( ++p == pe )
goto _test_eof20;
case 20:
if ( (*p) == 101u )
goto st21;
goto st0;
st21:
if ( ++p == pe )
goto _test_eof21;
case 21:
if ( (*p) == 13u )
goto st22;
goto st0;
st22:
if ( ++p == pe )
goto _test_eof22;
case 22:
if ( (*p) == 10u )
goto st23;
goto st0;
st23:
if ( ++p == pe )
goto _test_eof23;
case 23:
if ( 48u <= (*p) && (*p) <= 57u )
goto tr25;
goto st0;
tr25:
#line 4 "src/ControlProtocol/grammar/RequestAuthenticate.rl"
{
this->msg = new ControlProtocol::RequestAuthenticate();
}
#line 27 "src/ControlProtocol/Parser.rl"
{
MARK(this->mark, p);
}
goto st24;
st24:
if ( ++p == pe )
goto _test_eof24;
case 24:
#line 262 "src/ControlProtocol/Parser.cpp"
if ( (*p) == 13u )
goto tr26;
if ( 48u <= (*p) && (*p) <= 57u )
goto st48;
goto st0;
tr26:
#line 31 "src/ControlProtocol/Parser.rl"
{
int32_t transaction = std::atol(PTR_TO_MARK);
this->msg->SetTransaction(transaction);
}
goto st25;
st25:
if ( ++p == pe )
goto _test_eof25;
case 25:
#line 279 "src/ControlProtocol/Parser.cpp"
if ( (*p) == 10u )
goto st26;
goto st0;
st26:
if ( ++p == pe )
goto _test_eof26;
case 26:
if ( (*p) == 117u )
goto st27;
goto st0;
st27:
if ( ++p == pe )
goto _test_eof27;
case 27:
if ( (*p) == 115u )
goto st28;
goto st0;
st28:
if ( ++p == pe )
goto _test_eof28;
case 28:
if ( (*p) == 101u )
goto st29;
goto st0;
st29:
if ( ++p == pe )
goto _test_eof29;
case 29:
if ( (*p) == 114u )
goto st30;
goto st0;
st30:
if ( ++p == pe )
goto _test_eof30;
case 30:
if ( (*p) == 58u )
goto st31;
goto st0;
st31:
if ( ++p == pe )
goto _test_eof31;
case 31:
if ( (*p) == 32u )
goto st32;
goto st0;
st32:
if ( ++p == pe )
goto _test_eof32;
case 32:
if ( (*p) == 33u )
goto tr35;
if ( (*p) < 45u ) {
if ( (*p) > 39u ) {
if ( 42u <= (*p) && (*p) <= 43u )
goto tr35;
} else if ( (*p) >= 35u )
goto tr35;
} else if ( (*p) > 46u ) {
if ( (*p) < 65u ) {
if ( 48u <= (*p) && (*p) <= 57u )
goto tr35;
} else if ( (*p) > 90u ) {
if ( 94u <= (*p) && (*p) <= 126u )
goto tr35;
} else
goto tr35;
} else
goto tr35;
goto st0;
tr35:
#line 27 "src/ControlProtocol/Parser.rl"
{
MARK(this->mark, p);
}
goto st33;
st33:
if ( ++p == pe )
goto _test_eof33;
case 33:
#line 359 "src/ControlProtocol/Parser.cpp"
switch( (*p) ) {
case 13u: goto tr36;
case 33u: goto st33;
}
if ( (*p) < 45u ) {
if ( (*p) > 39u ) {
if ( 42u <= (*p) && (*p) <= 43u )
goto st33;
} else if ( (*p) >= 35u )
goto st33;
} else if ( (*p) > 46u ) {
if ( (*p) < 65u ) {
if ( 48u <= (*p) && (*p) <= 57u )
goto st33;
} else if ( (*p) > 90u ) {
if ( 94u <= (*p) && (*p) <= 126u )
goto st33;
} else
goto st33;
} else
goto st33;
goto st0;
tr36:
#line 8 "src/ControlProtocol/grammar/RequestAuthenticate.rl"
{
static_cast<RequestAuthenticate*>(this->msg)->SetUser(PTR_TO_MARK, LEN_FROM_MARK);
}
goto st34;
st34:
if ( ++p == pe )
goto _test_eof34;
case 34:
#line 392 "src/ControlProtocol/Parser.cpp"
if ( (*p) == 10u )
goto st35;
goto st0;
st35:
if ( ++p == pe )
goto _test_eof35;
case 35:
if ( (*p) == 112u )
goto st36;
goto st0;
st36:
if ( ++p == pe )
goto _test_eof36;
case 36:
if ( (*p) == 97u )
goto st37;
goto st0;
st37:
if ( ++p == pe )
goto _test_eof37;
case 37:
if ( (*p) == 115u )
goto st38;
goto st0;
st38:
if ( ++p == pe )
goto _test_eof38;
case 38:
if ( (*p) == 115u )
goto st39;
goto st0;
st39:
if ( ++p == pe )
goto _test_eof39;
case 39:
if ( (*p) == 119u )
goto st40;
goto st0;
st40:
if ( ++p == pe )
goto _test_eof40;
case 40:
if ( (*p) == 100u )
goto st41;
goto st0;
st41:
if ( ++p == pe )
goto _test_eof41;
case 41:
if ( (*p) == 58u )
goto st42;
goto st0;
st42:
if ( ++p == pe )
goto _test_eof42;
case 42:
if ( (*p) == 32u )
goto st43;
goto st0;
st43:
if ( ++p == pe )
goto _test_eof43;
case 43:
if ( (*p) == 33u )
goto tr47;
if ( (*p) < 45u ) {
if ( (*p) > 39u ) {
if ( 42u <= (*p) && (*p) <= 43u )
goto tr47;
} else if ( (*p) >= 35u )
goto tr47;
} else if ( (*p) > 46u ) {
if ( (*p) < 65u ) {
if ( 48u <= (*p) && (*p) <= 57u )
goto tr47;
} else if ( (*p) > 90u ) {
if ( 94u <= (*p) && (*p) <= 126u )
goto tr47;
} else
goto tr47;
} else
goto tr47;
goto st0;
tr47:
#line 27 "src/ControlProtocol/Parser.rl"
{
MARK(this->mark, p);
}
goto st44;
st44:
if ( ++p == pe )
goto _test_eof44;
case 44:
#line 486 "src/ControlProtocol/Parser.cpp"
switch( (*p) ) {
case 13u: goto tr48;
case 33u: goto st44;
}
if ( (*p) < 45u ) {
if ( (*p) > 39u ) {
if ( 42u <= (*p) && (*p) <= 43u )
goto st44;
} else if ( (*p) >= 35u )
goto st44;
} else if ( (*p) > 46u ) {
if ( (*p) < 65u ) {
if ( 48u <= (*p) && (*p) <= 57u )
goto st44;
} else if ( (*p) > 90u ) {
if ( 94u <= (*p) && (*p) <= 126u )
goto st44;
} else
goto st44;
} else
goto st44;
goto st0;
tr78:
#line 31 "src/ControlProtocol/Parser.rl"
{
int32_t transaction = std::atol(PTR_TO_MARK);
this->msg->SetTransaction(transaction);
}
goto st45;
tr48:
#line 12 "src/ControlProtocol/grammar/RequestAuthenticate.rl"
{
static_cast<RequestAuthenticate*>(this->msg)->SetPasswd(PTR_TO_MARK, LEN_FROM_MARK);
}
goto st45;
st45:
if ( ++p == pe )
goto _test_eof45;
case 45:
#line 526 "src/ControlProtocol/Parser.cpp"
if ( (*p) == 10u )
goto st46;
goto st0;
st46:
if ( ++p == pe )
goto _test_eof46;
case 46:
if ( (*p) == 13u )
goto st47;
goto st0;
st47:
if ( ++p == pe )
goto _test_eof47;
case 47:
if ( (*p) == 10u )
goto tr52;
goto st0;
tr52:
#line 36 "src/ControlProtocol/Parser.rl"
{
{p++; cs = 90; goto _out;}
}
goto st90;
st90:
if ( ++p == pe )
goto _test_eof90;
case 90:
#line 554 "src/ControlProtocol/Parser.cpp"
goto st0;
st48:
if ( ++p == pe )
goto _test_eof48;
case 48:
if ( (*p) == 13u )
goto tr26;
if ( 48u <= (*p) && (*p) <= 57u )
goto st49;
goto st0;
st49:
if ( ++p == pe )
goto _test_eof49;
case 49:
if ( (*p) == 13u )
goto tr26;
if ( 48u <= (*p) && (*p) <= 57u )
goto st50;
goto st0;
st50:
if ( ++p == pe )
goto _test_eof50;
case 50:
if ( (*p) == 13u )
goto tr26;
if ( 48u <= (*p) && (*p) <= 57u )
goto st51;
goto st0;
st51:
if ( ++p == pe )
goto _test_eof51;
case 51:
if ( (*p) == 13u )
goto tr26;
if ( 48u <= (*p) && (*p) <= 57u )
goto st52;
goto st0;
st52:
if ( ++p == pe )
goto _test_eof52;
case 52:
if ( (*p) == 13u )
goto tr26;
if ( 48u <= (*p) && (*p) <= 57u )
goto st53;
goto st0;
st53:
if ( ++p == pe )
goto _test_eof53;
case 53:
if ( (*p) == 13u )
goto tr26;
if ( 48u <= (*p) && (*p) <= 57u )
goto st54;
goto st0;
st54:
if ( ++p == pe )
goto _test_eof54;
case 54:
if ( (*p) == 13u )
goto tr26;
if ( 48u <= (*p) && (*p) <= 57u )
goto st55;
goto st0;
st55:
if ( ++p == pe )
goto _test_eof55;
case 55:
if ( (*p) == 13u )
goto tr26;
goto st0;
st56:
if ( ++p == pe )
goto _test_eof56;
case 56:
if ( (*p) == 114u )
goto st57;
goto st0;
st57:
if ( ++p == pe )
goto _test_eof57;
case 57:
if ( (*p) == 101u )
goto st58;
goto st0;
st58:
if ( ++p == pe )
goto _test_eof58;
case 58:
if ( (*p) == 97u )
goto st59;
goto st0;
st59:
if ( ++p == pe )
goto _test_eof59;
case 59:
if ( (*p) == 116u )
goto st60;
goto st0;
st60:
if ( ++p == pe )
goto _test_eof60;
case 60:
if ( (*p) == 101u )
goto st61;
goto st0;
st61:
if ( ++p == pe )
goto _test_eof61;
case 61:
if ( (*p) == 67u )
goto st62;
goto st0;
st62:
if ( ++p == pe )
goto _test_eof62;
case 62:
if ( (*p) == 111u )
goto st63;
goto st0;
st63:
if ( ++p == pe )
goto _test_eof63;
case 63:
if ( (*p) == 110u )
goto st64;
goto st0;
st64:
if ( ++p == pe )
goto _test_eof64;
case 64:
if ( (*p) == 102u )
goto st65;
goto st0;
st65:
if ( ++p == pe )
goto _test_eof65;
case 65:
if ( (*p) == 101u )
goto st66;
goto st0;
st66:
if ( ++p == pe )
goto _test_eof66;
case 66:
if ( (*p) == 114u )
goto st67;
goto st0;
st67:
if ( ++p == pe )
goto _test_eof67;
case 67:
if ( (*p) == 101u )
goto st68;
goto st0;
st68:
if ( ++p == pe )
goto _test_eof68;
case 68:
if ( (*p) == 110u )
goto st69;
goto st0;
st69:
if ( ++p == pe )
goto _test_eof69;
case 69:
if ( (*p) == 99u )
goto st70;
goto st0;
st70:
if ( ++p == pe )
goto _test_eof70;
case 70:
if ( (*p) == 101u )
goto st71;
goto st0;
st71:
if ( ++p == pe )
goto _test_eof71;
case 71:
if ( (*p) == 13u )
goto st72;
goto st0;
st72:
if ( ++p == pe )
goto _test_eof72;
case 72:
if ( (*p) == 10u )
goto st73;
goto st0;
st73:
if ( ++p == pe )
goto _test_eof73;
case 73:
if ( 48u <= (*p) && (*p) <= 57u )
goto tr77;
goto st0;
tr77:
#line 4 "src/ControlProtocol/grammar/RequestCreateConference.rl"
{
this->msg = new ControlProtocol::RequestCreateConference();
}
#line 27 "src/ControlProtocol/Parser.rl"
{
MARK(this->mark, p);
}
goto st74;
tr93:
#line 4 "src/ControlProtocol/grammar/RequestHello.rl"
{
this->msg = new ControlProtocol::RequestHello();
}
#line 27 "src/ControlProtocol/Parser.rl"
{
MARK(this->mark, p);
}
goto st74;
st74:
if ( ++p == pe )
goto _test_eof74;
case 74:
#line 776 "src/ControlProtocol/Parser.cpp"
if ( (*p) == 13u )
goto tr78;
if ( 48u <= (*p) && (*p) <= 57u )
goto st75;
goto st0;
st75:
if ( ++p == pe )
goto _test_eof75;
case 75:
if ( (*p) == 13u )
goto tr78;
if ( 48u <= (*p) && (*p) <= 57u )
goto st76;
goto st0;
st76:
if ( ++p == pe )
goto _test_eof76;
case 76:
if ( (*p) == 13u )
goto tr78;
if ( 48u <= (*p) && (*p) <= 57u )
goto st77;
goto st0;
st77:
if ( ++p == pe )
goto _test_eof77;
case 77:
if ( (*p) == 13u )
goto tr78;
if ( 48u <= (*p) && (*p) <= 57u )
goto st78;
goto st0;
st78:
if ( ++p == pe )
goto _test_eof78;
case 78:
if ( (*p) == 13u )
goto tr78;
if ( 48u <= (*p) && (*p) <= 57u )
goto st79;
goto st0;
st79:
if ( ++p == pe )
goto _test_eof79;
case 79:
if ( (*p) == 13u )
goto tr78;
if ( 48u <= (*p) && (*p) <= 57u )
goto st80;
goto st0;
st80:
if ( ++p == pe )
goto _test_eof80;
case 80:
if ( (*p) == 13u )
goto tr78;
if ( 48u <= (*p) && (*p) <= 57u )
goto st81;
goto st0;
st81:
if ( ++p == pe )
goto _test_eof81;
case 81:
if ( (*p) == 13u )
goto tr78;
if ( 48u <= (*p) && (*p) <= 57u )
goto st82;
goto st0;
st82:
if ( ++p == pe )
goto _test_eof82;
case 82:
if ( (*p) == 13u )
goto tr78;
goto st0;
st83:
if ( ++p == pe )
goto _test_eof83;
case 83:
if ( (*p) == 101u )
goto st84;
goto st0;
st84:
if ( ++p == pe )
goto _test_eof84;
case 84:
if ( (*p) == 108u )
goto st85;
goto st0;
st85:
if ( ++p == pe )
goto _test_eof85;
case 85:
if ( (*p) == 108u )
goto st86;
goto st0;
st86:
if ( ++p == pe )
goto _test_eof86;
case 86:
if ( (*p) == 111u )
goto st87;
goto st0;
st87:
if ( ++p == pe )
goto _test_eof87;
case 87:
if ( (*p) == 13u )
goto st88;
goto st0;
st88:
if ( ++p == pe )
goto _test_eof88;
case 88:
if ( (*p) == 10u )
goto st89;
goto st0;
st89:
if ( ++p == pe )
goto _test_eof89;
case 89:
if ( 48u <= (*p) && (*p) <= 57u )
goto tr93;
goto st0;
}
_test_eof2: cs = 2; goto _test_eof;
_test_eof3: cs = 3; goto _test_eof;
_test_eof4: cs = 4; goto _test_eof;
_test_eof5: cs = 5; goto _test_eof;
_test_eof6: cs = 6; goto _test_eof;
_test_eof7: cs = 7; goto _test_eof;
_test_eof8: cs = 8; goto _test_eof;
_test_eof9: cs = 9; goto _test_eof;
_test_eof10: cs = 10; goto _test_eof;
_test_eof11: cs = 11; goto _test_eof;
_test_eof12: cs = 12; goto _test_eof;
_test_eof13: cs = 13; goto _test_eof;
_test_eof14: cs = 14; goto _test_eof;
_test_eof15: cs = 15; goto _test_eof;
_test_eof16: cs = 16; goto _test_eof;
_test_eof17: cs = 17; goto _test_eof;
_test_eof18: cs = 18; goto _test_eof;
_test_eof19: cs = 19; goto _test_eof;
_test_eof20: cs = 20; goto _test_eof;
_test_eof21: cs = 21; goto _test_eof;
_test_eof22: cs = 22; goto _test_eof;
_test_eof23: cs = 23; goto _test_eof;
_test_eof24: cs = 24; goto _test_eof;
_test_eof25: cs = 25; goto _test_eof;
_test_eof26: cs = 26; goto _test_eof;
_test_eof27: cs = 27; goto _test_eof;
_test_eof28: cs = 28; goto _test_eof;
_test_eof29: cs = 29; goto _test_eof;
_test_eof30: cs = 30; goto _test_eof;
_test_eof31: cs = 31; goto _test_eof;
_test_eof32: cs = 32; goto _test_eof;
_test_eof33: cs = 33; goto _test_eof;
_test_eof34: cs = 34; goto _test_eof;
_test_eof35: cs = 35; goto _test_eof;
_test_eof36: cs = 36; goto _test_eof;
_test_eof37: cs = 37; goto _test_eof;
_test_eof38: cs = 38; goto _test_eof;
_test_eof39: cs = 39; goto _test_eof;
_test_eof40: cs = 40; goto _test_eof;
_test_eof41: cs = 41; goto _test_eof;
_test_eof42: cs = 42; goto _test_eof;
_test_eof43: cs = 43; goto _test_eof;
_test_eof44: cs = 44; goto _test_eof;
_test_eof45: cs = 45; goto _test_eof;
_test_eof46: cs = 46; goto _test_eof;
_test_eof47: cs = 47; goto _test_eof;
_test_eof90: cs = 90; goto _test_eof;
_test_eof48: cs = 48; goto _test_eof;
_test_eof49: cs = 49; goto _test_eof;
_test_eof50: cs = 50; goto _test_eof;
_test_eof51: cs = 51; goto _test_eof;
_test_eof52: cs = 52; goto _test_eof;
_test_eof53: cs = 53; goto _test_eof;
_test_eof54: cs = 54; goto _test_eof;
_test_eof55: cs = 55; goto _test_eof;
_test_eof56: cs = 56; goto _test_eof;
_test_eof57: cs = 57; goto _test_eof;
_test_eof58: cs = 58; goto _test_eof;
_test_eof59: cs = 59; goto _test_eof;
_test_eof60: cs = 60; goto _test_eof;
_test_eof61: cs = 61; goto _test_eof;
_test_eof62: cs = 62; goto _test_eof;
_test_eof63: cs = 63; goto _test_eof;
_test_eof64: cs = 64; goto _test_eof;
_test_eof65: cs = 65; goto _test_eof;
_test_eof66: cs = 66; goto _test_eof;
_test_eof67: cs = 67; goto _test_eof;
_test_eof68: cs = 68; goto _test_eof;
_test_eof69: cs = 69; goto _test_eof;
_test_eof70: cs = 70; goto _test_eof;
_test_eof71: cs = 71; goto _test_eof;
_test_eof72: cs = 72; goto _test_eof;
_test_eof73: cs = 73; goto _test_eof;
_test_eof74: cs = 74; goto _test_eof;
_test_eof75: cs = 75; goto _test_eof;
_test_eof76: cs = 76; goto _test_eof;
_test_eof77: cs = 77; goto _test_eof;
_test_eof78: cs = 78; goto _test_eof;
_test_eof79: cs = 79; goto _test_eof;
_test_eof80: cs = 80; goto _test_eof;
_test_eof81: cs = 81; goto _test_eof;
_test_eof82: cs = 82; goto _test_eof;
_test_eof83: cs = 83; goto _test_eof;
_test_eof84: cs = 84; goto _test_eof;
_test_eof85: cs = 85; goto _test_eof;
_test_eof86: cs = 86; goto _test_eof;
_test_eof87: cs = 87; goto _test_eof;
_test_eof88: cs = 88; goto _test_eof;
_test_eof89: cs = 89; goto _test_eof;
_test_eof: {}
_out: {}
}
#line 98 "src/ControlProtocol/Parser.rl"
this->parsedLen = p - (const unsigned char*)buffer;
MS_ASSERT(p <= pe, "buffer overflow after parsing execute");
MS_ASSERT(this->parsedLen <= len, "parsedLen longer than length");
MS_ASSERT(this->mark < len, "mark is after buffer end");
// Parsing succedded.
if (this->cs == (size_t)MessageParser_first_final) {
MS_DEBUG("parsing finished OK");
MS_ASSERT(this->msg != nullptr, "parsing OK but msg is NULL");
// Check the message semantics.
if(! this->msg->IsValid()) {
MS_ERROR("invalid message");
delete this->msg;
return (this->msg = nullptr);
}
return this->msg;
}
// Parsing error.
else if (this->cs == (size_t)MessageParser_error) {
MS_ERROR("parsing error at position %zd", this->parsedLen);
// Delete this->msg if it exists.
if (this->msg) {
delete this->msg;
this->msg = nullptr;
}
return nullptr;
}
// Parsing not finished.
else {
MS_DEBUG("parsing not finished");
return nullptr;
}
}
bool Parser::HasError() {
MS_TRACE();
return (this->cs == (size_t)MessageParser_error);
}
size_t Parser::GetParsedLen() {
MS_TRACE();
return this->parsedLen;
}
void Parser::Reset() {
MS_TRACE();
this->parsedLen = 0;
this->msg = nullptr;
this->cs = 0;
this->mark = 0;
/**
* Ragel: %%write init
* This sets cs variable needed by Ragel (so this->cs at the end).
*/
#line 1069 "src/ControlProtocol/Parser.cpp"
{
cs = MessageParser_start;
}
#line 170 "src/ControlProtocol/Parser.rl"
}
void Parser::Dump() {
MS_DEBUG("[cs: %zu | parsedLen: %zu | mark: %zu | error?: %s | finished?: %s]",
this->cs, this->parsedLen, this->mark,
HasError() ? "true" : "false",
(this->cs >= (size_t)MessageParser_first_final) ? "true" : "false");
}
} // namespace ControlProtocol
#define MS_CLASS "ControlProtocol::Parser"
#include "ControlProtocol/Parser.h"
#include "ControlProtocol/messages.h"
#include "Logger.h"
#include <cstdlib> // std::atol()
#define MARK(M, P) (M = (P) - buffer)
#define LEN(AT, P) ((P) - buffer - (AT))
#define LEN_FROM_MARK (p - buffer - this->mark)
#define PTR_TO(F) (buffer + (F))
#define PTR_TO_MARK (const char*)(buffer + this->mark)
namespace ControlProtocol {
/**
* Ragel: machine definition
*/
%%{
machine MessageParser;
alphtype unsigned char;
action mark {
MARK(this->mark, p);
}
action on_transaction {
int32_t transaction = std::atol(PTR_TO_MARK);
this->msg->SetTransaction(transaction);
}
action on_message {
fbreak;
}
include core_grammar "../core_grammar.rl";
transaction = ULONG >mark %on_transaction;
include RequestHello "grammar/RequestHello.rl";
include RequestAuthenticate "grammar/RequestAuthenticate.rl";
include RequestCreateConference "grammar/RequestCreateConference.rl";
Request = RequestHello |
RequestAuthenticate |
RequestCreateConference;
#Message = Request | Response | Notification;
Message = Request @on_message;
main := Message;
}%%
/**
* Ragel: %%write data
* This generates Ragel's static variables such as:
* static const int MessageParser_start
*/
%%write data;
Parser::Parser() {
MS_TRACE();
Reset();
}
Parser::~Parser() {
MS_TRACE();
}
Message* Parser::Parse(const MS_BYTE* buffer, size_t len) {
MS_TRACE();
// Used by Ragel:
const unsigned char* p;
const unsigned char* pe;
// const unsigned char* eof;
MS_ASSERT(this->parsedLen <= len, "parsedLen pasts end of buffer");
p = (const unsigned char*)buffer + this->parsedLen;
pe = (const unsigned char*)buffer + len;
// eof = nullptr; // Ragel manual pag 36 (eof variable).
/**
* Ragel: %%write exec
* This updates cs variable needed by Ragel (so this->cs at the end) and p.
*/
%%write exec;
this->parsedLen = p - (const unsigned char*)buffer;
MS_ASSERT(p <= pe, "buffer overflow after parsing execute");
MS_ASSERT(this->parsedLen <= len, "parsedLen longer than length");
MS_ASSERT(this->mark < len, "mark is after buffer end");
// Parsing succedded.
if (this->cs == (size_t)MessageParser_first_final) {
MS_DEBUG("parsing finished OK");
MS_ASSERT(this->msg != nullptr, "parsing OK but msg is NULL");
// Check the message semantics.
if(! this->msg->IsValid()) {
MS_ERROR("invalid message");
delete this->msg;
return (this->msg = nullptr);
}
return this->msg;
}
// Parsing error.
else if (this->cs == (size_t)MessageParser_error) {
MS_ERROR("parsing error at position %zd", this->parsedLen);
// Delete this->msg if it exists.
if (this->msg) {
delete this->msg;
this->msg = nullptr;
}
return nullptr;
}
// Parsing not finished.
else {
MS_DEBUG("parsing not finished");
return nullptr;
}
}
bool Parser::HasError() {
MS_TRACE();
return (this->cs == (size_t)MessageParser_error);
}
size_t Parser::GetParsedLen() {
MS_TRACE();
return this->parsedLen;
}
void Parser::Reset() {
MS_TRACE();
this->parsedLen = 0;
this->msg = nullptr;
this->cs = 0;
this->mark = 0;
/**
* Ragel: %%write init
* This sets cs variable needed by Ragel (so this->cs at the end).
*/
%%write init;
}
void Parser::Dump() {
MS_DEBUG("[cs: %zu | parsedLen: %zu | mark: %zu | error?: %s | finished?: %s]",
this->cs, this->parsedLen, this->mark,
HasError() ? "true" : "false",
(this->cs >= (size_t)MessageParser_first_final) ? "true" : "false");
}
} // namespace ControlProtocol
#define MS_CLASS "ControlProtocol::Request"
#include "ControlProtocol/Request.h"
#include "Logger.h"
namespace ControlProtocol {
/* Instance methods. */
Request::Request(Type type) :
Message(Message::Kind::Request),
type(type)
{
MS_TRACE();
}
Request::~Request() {
MS_TRACE();
}
} // namespace ControlProtocol
#define MS_CLASS "ControlProtocol::TCPConnection"
#include "ControlProtocol/TCPConnection.h"
#include "Logger.h"
#include <cstring> // std::memmove()
namespace ControlProtocol {
/* Instance methods. */
TCPConnection::TCPConnection(Reader* reader, size_t bufferSize) :
::TCPConnection(bufferSize),
reader(reader)
{
MS_TRACE();
// Initiate a ControlProtocol::Parser.
this->parser = new ControlProtocol::Parser();
}
TCPConnection::~TCPConnection() {
MS_TRACE();
if (this->parser)
delete this->parser;
}
void TCPConnection::userOnTCPConnectionRead(const MS_BYTE* data, size_t len) {
MS_TRACE();
// Be ready to parse more than a single message in a single TCP chunk.
while(true) {
ControlProtocol::Message* msg;
// Tell the parser to parse the buffer starting from the beginning of the latest
// detected message until the end of the data in the buffer.
msg = this->parser->Parse(this->buffer + this->msgStart, this->bufferDataLen - this->msgStart);
size_t parsed_len = parser->GetParsedLen();
// Message parsed.
if (msg) {
// Notify the reader.
this->reader->onControlProtocolMessage(this, msg, this->buffer + this->msgStart, parsed_len);
// Free the message.
delete msg;
// If there is no more space available in the buffer and that is because
// the latest parsed message filled it, then empty the full buffer.
if ((this->msgStart + parsed_len) == this->bufferSize) {
MS_DEBUG("no more space in the buffer, emptying the buffer data");
this->msgStart = 0;
this->bufferDataLen = 0;
}
// If there is still space in the buffer, set the beginning of the next
// parsing to the next position after the parsed message.
else {
this->msgStart += parsed_len;
}
// Reset the parser.
this->parser->Reset();
// If there is more data in the buffer after the parsed message
// then parse again. Otherwise break here and wait for more data.
if (this->bufferDataLen > this->msgStart) {
MS_DEBUG("there is more data after the parsed message, continue parsing");
continue;
}
else {
break;
}
}
// Parsing error. Close the connection.
else if (this->parser->HasError()) {
MS_ERROR("parsing error, closing the connection");
// Close the connection.
Close();
// Exit the parsing loop.
break;
}
// Message not finished.
else {
// Check if the buffer is full.
if (this->bufferDataLen == this->bufferSize) {
// First case: the uncomplete message does not begin at position 0 of
// the buffer, so move the message to the position 0.
if (this->msgStart != 0) {
MS_DEBUG("no more space in the buffer, moving parsed bytes to the beginning of the buffer and wait for more data");
std::memmove(this->buffer, this->buffer + this->msgStart, parsed_len);
this->msgStart = 0;
this->bufferDataLen = parsed_len;
}
// Second case: the uncomplete message begins at position 0 of the buffer.
// The message is too big, so close the connection.
else {
MS_ERROR("no more space in the buffer for the unfinished message being parsed, closing the connection");
// Close the socket.
Close();
}
}
// The buffer is not full.
else {
MS_DEBUG("message not finished yet, waiting for more data");
}
// Exit the parsing loop.
break;
}
} // while()
}
} // namespace ControlProtocol
#define MS_CLASS "ControlProtocol::TCPServer"
#include "ControlProtocol/TCPServer.h"
#include "Logger.h"
namespace ControlProtocol {
/* Instance methods. */
TCPServer::TCPServer(Listener* listener, ControlProtocol::TCPConnection::Reader* reader, const std::string &ip, MS_PORT port) :
::TCPServer::TCPServer(ip, port, 2048),
listener(listener),
reader(reader)
{
MS_TRACE();
}
void TCPServer::userOnTCPConnectionAlloc(::TCPConnection** connection) {
MS_TRACE();
// Allocate a new ControlProtocol::TCPConnection and pass it our reader.
*connection = new ControlProtocol::TCPConnection(this->reader, 65536);
}
void TCPServer::userOnNewTCPConnection(::TCPConnection* connection) {
MS_TRACE();
// Notify the listener.
this->listener->onControlProtocolNewTCPConnection(this, static_cast<ControlProtocol::TCPConnection*>(connection));
}
void TCPServer::userOnTCPConnectionClosed(::TCPConnection* connection, bool is_closed_by_peer) {
MS_TRACE();
// Notify the listener.
this->listener->onControlProtocolTCPConnectionClosed(this, static_cast<ControlProtocol::TCPConnection*>(connection), is_closed_by_peer);
}
void TCPServer::userOnTCPServerClosed() {
MS_TRACE();
}
} // namespace ControlProtocol
#define MS_CLASS "ControlProtocol::UnixStreamSocket"
#include "ControlProtocol/UnixStreamSocket.h"
#include "Logger.h"
#include <cstring> // std::memmove()
namespace ControlProtocol {
/* Instance methods. */
UnixStreamSocket::UnixStreamSocket(Listener* listener, int fd) :
::UnixStreamSocket::UnixStreamSocket(fd, 65536),
listener(listener)
{
MS_TRACE();
// Initiate a ControlProtocol::Parser.
this->parser = new ControlProtocol::Parser();
}
UnixStreamSocket::~UnixStreamSocket() {
MS_TRACE();
if (this->parser)
delete this->parser;
}
void UnixStreamSocket::userOnUnixStreamRead(const MS_BYTE* data, size_t len) {
MS_TRACE();
// Be ready to parse more than a single message in a single TCP chunk.
while(true) {
ControlProtocol::Message* msg;
// Tell the parser to parse the buffer starting from the beginning of the latest
// detected message until the end of the data in the buffer.
msg = this->parser->Parse(this->buffer + this->msgStart, this->bufferDataLen - this->msgStart);
size_t parsed_len = parser->GetParsedLen();
// Message parsed.
if (msg) {
// Notify the listener.
this->listener->onControlProtocolMessage(this, msg, this->buffer + this->msgStart, parsed_len);
// Free the message.
delete msg;
// If there is no more space available in the buffer and that is because
// the latest parsed message filled it, then empty the full buffer.
if ((this->msgStart + parsed_len) == this->bufferSize) {
MS_DEBUG("no more space in the buffer, emptying the buffer data");
this->msgStart = 0;
this->bufferDataLen = 0;
}
// If there is still space in the buffer, set the beginning of the next
// parsing to the next position after the parsed message.
else {
this->msgStart += parsed_len;
}
// Reset the parser.
this->parser->Reset();
// If there is more data in the buffer after the parsed message
// then parse again. Otherwise break here and wait for more data.
if (this->bufferDataLen > this->msgStart) {
MS_DEBUG("there is more data after the parsed message, continue parsing");
continue;
}
else {
break;
}
}
// Parsing error. Close the pipe.
else if (this->parser->HasError()) {
MS_ERROR("parsing error, closing the pipe");
// Close the pipe.
Close();
// Exit the parsing loop.
break;
}
// Message not finished.
else {
// Check if the buffer is full.
if (this->bufferDataLen == this->bufferSize) {
// First case: the uncomplete message does not begin at position 0 of
// the buffer, so move the message to the position 0.
if (this->msgStart != 0) {
MS_DEBUG("no more space in the buffer, moving parsed bytes to the beginning of the buffer and wait for more data");
std::memmove(this->buffer, this->buffer + this->msgStart, parsed_len);
this->msgStart = 0;
this->bufferDataLen = parsed_len;
}
// Second case: the uncomplete message begins at position 0 of the buffer.
// The message is too big, so close the pipe.
else {
MS_ERROR("no more space in the buffer for the unfinished message being parsed, closing the pipe");
// Close the socket.
Close();
}
}
// The buffer is not full.
else {
MS_DEBUG("message not finished yet, waiting for more data");
}
// Exit the parsing loop.
break;
}
} // while()
}
void UnixStreamSocket::userOnUnixStreamSocketClosed(bool is_closed_by_peer) {
MS_TRACE();
// Notify the listener.
this->listener->onControlProtocolUnixStreamSocketClosed(this, is_closed_by_peer);
}
} // namespace ControlProtocol
#!/usr/bin/env bash
ROOT_DIR="../../"
RAGEL_FILE="src/ControlProtocol/Parser.rl"
RAGEL_COMPILE_TYPE="-G2"
PRODUCTION=false
set -e
which ragel >/dev/null
if [ $? -ne 0 ] ; then
echo ">>> ERROR: ragel binary not found, cannot compile the Ragel grammar" >&2
exit 1
else
ragel -v
fi
cd $ROOT_DIR
cpp_file="${RAGEL_FILE%.rl}.cpp"
echo ">>> INFO: compiling $RAGEL_FILE:"
if [ "$PRODUCTION" == "true" ] ; then
show_ragel_lines="-L"
else
show_ragel_lines=""
fi
ragel $RAGEL_COMPILE_TYPE -C $RAGEL_FILE $show_ragel_lines -o $cpp_file
# Remove unused Ragel variables.
sed -i".delete_me" -E "s/.*static const int MessageParser_en_main.*//g" $cpp_file
echo ">>> DEBUG: Ragel's unused static variables removed from $cpp_file"
rm -f ${cpp_file}.delete_me
echo ">>> INFO: $cpp_file generated"
%%{
machine RequestAuthenticate;
action on_request_type_Authenticate {
this->msg = new ControlProtocol::RequestAuthenticate();
}
action on_auth_user {
static_cast<RequestAuthenticate*>(this->msg)->SetUser(PTR_TO_MARK, LEN_FROM_MARK);
}
action on_auth_passwd {
static_cast<RequestAuthenticate*>(this->msg)->SetPasswd(PTR_TO_MARK, LEN_FROM_MARK);
}
auth_user = token >mark %on_auth_user;
auth_passwd = token >mark %on_auth_passwd;
RequestAuthenticate = "Request" SP "Authenticate" CRLF %on_request_type_Authenticate
transaction CRLF
"user:" SP auth_user CRLF
"passwd:" SP auth_passwd CRLF
CRLF;
}%%
%%{
machine RequestCreateConference;
action on_request_type_CreateConference {
this->msg = new ControlProtocol::RequestCreateConference();
}
RequestCreateConference = "Request" SP "CreateConference" CRLF %on_request_type_CreateConference
transaction CRLF
CRLF;
}%%
%%{
machine RequestHello;
action on_request_type_Hello {
this->msg = new ControlProtocol::RequestHello();
}
RequestHello = "Request" SP "Hello" CRLF %on_request_type_Hello
transaction CRLF
CRLF;
}%%
#define MS_CLASS "ControlProtocol::RequestAuthenticate"
#include "ControlProtocol/messages/RequestAuthenticate.h"
#include "Logger.h"
namespace ControlProtocol {
/* Instance methods. */
RequestAuthenticate::RequestAuthenticate() :
Request(Type::Authenticate)
{
MS_DEBUG("kind: %d, type: %d", (int)this->kind, (int)this->type);
}
RequestAuthenticate::~RequestAuthenticate() {
MS_TRACE();
}
void RequestAuthenticate::SetUser(const char* str, size_t len) {
MS_TRACE();
this->user = std::string(str, len);
}
void RequestAuthenticate::SetPasswd(const char* str, size_t len) {
MS_TRACE();
this->passwd = std::string(str, len);
}
void RequestAuthenticate::Dump() {
MS_DEBUG("[Request Authenticate]");
MS_DEBUG("- transaction: %zu", (size_t)this->transaction);
MS_DEBUG("- user: %s", this->user.c_str());
MS_DEBUG("- passwd: %s", this->passwd.c_str());
MS_DEBUG("[/Request Authenticate]");
}
} // namespace ControlProtocol
#define MS_CLASS "ControlProtocol::RequestCreateConference"
#include "ControlProtocol/messages/RequestCreateConference.h"
#include "Logger.h"
namespace ControlProtocol {
/* Instance methods. */
RequestCreateConference::RequestCreateConference() : Request(Type::CreateConference) {
MS_DEBUG("kind: %d, type: %d", (int)this->kind, (int)this->type);
}
RequestCreateConference::~RequestCreateConference() {
MS_TRACE();
}
void RequestCreateConference::Dump() {
MS_DEBUG("[Request CreateConference]");
MS_DEBUG("- transaction: %zu", (size_t)this->transaction);
MS_DEBUG("[/Request CreateConference]");
}
} // namespace ControlProtocol
#define MS_CLASS "ControlProtocol::RequestHello"
#include "ControlProtocol/messages/RequestHello.h"
#include "Logger.h"
namespace ControlProtocol {
/* Instance methods. */
RequestHello::RequestHello() : Request(Type::Hello) {
MS_DEBUG("kind: %d, type: %d", (int)this->kind, (int)this->type);
}
RequestHello::~RequestHello() {
MS_TRACE();
}
void RequestHello::Dump() {
MS_DEBUG("[Request Hello]");
MS_DEBUG("- transaction: %zu", (size_t)this->transaction);
MS_DEBUG("[/Request Hello]");
}
} // namespace ControlProtocol
#define MS_CLASS "Daemon"
#include "Daemon.h"
#include "Settings.h"
#include "Version.h"
#include "MediaSoupError.h"
#include "Logger.h"
#include <string>
#include <cerrno>
#include <cstdlib> // std::_Exit()
#include <cstdio> // std::setbuf(), std::freopen(), std::fopen(), std::fscanf(), std::fprintf(), std::remove()
#include <csignal> // kill()
#include <unistd.h> // pipe(), fork(), close(), setsid(), getpid()
/* Static variables. */
int Daemon::statusPipe[2] {-1, -1};
bool Daemon::isDaemonized = false;
bool Daemon::hasWrittenPIDFile = false;
/* Static methods. */
void Daemon::Daemonize() {
MS_TRACE();
/**
* - ancestor process (running in foreground)
* \- intermediary process
* \- daemonized process (main process running in background)
*/
int ret;
int pid;
char status;
// Flush std file descriptors to avoid flushes after fork (same message
// appearing multiple times) and switch to unbuffered mode.
std::setbuf(stdout, 0);
std::setbuf(stderr, 0);
// Set the pipe for the daemonized process to send its status to the ancestor
// process (that waits for it in the foreground).
do {
ret = pipe(Daemon::statusPipe);
} while(ret < 0 && errno == EINTR);
if (ret < 0)
MS_THROW_ERROR("pipe() failed: %s", std::strerror(errno));
// NOTE: Don't need to update thread name after fork() calls. fork() copies
// the memory of the calling thread.
// First fork: don't be group leader.
if ((pid = fork()) < 0) {
MS_THROW_ERROR("first fork() failed: %s", std::strerror(errno));
}
else if (pid > 0) {
// When fork() returns a positive number, we are in the ancestor process
// and the return value is the PID of the newly created child process (the
// intermediary process).
// Ancestor process wait for the daemonized process to write into the pipe (or to die
// before) so it can exit with the proper exit status.
if (Daemon::WaitForDaemonizedStatus(&status)) {
if ((int)status == EXIT_SUCCESS) {
MS_NOTICE("%s running as daemon", Version::name.c_str());
std::_Exit(EXIT_SUCCESS);
}
else {
MS_EXIT_FAILURE("daemonized process failed to start (check Syslog)");
}
}
// The daemonized process died before writing its status on the pipe.
else {
MS_EXIT_FAILURE("daemonized process died before writing its status (check Syslog)");
}
}
// This is the intermediary process.
// We are now daemonized (even if this is not the definitive forked process).
Daemon::isDaemonized = true;
// Clean unused fds.
if (Daemon::statusPipe[0] != -1) {
close(Daemon::statusPipe[0]);
Daemon::statusPipe[0] = -1;
}
// Become session leader to drop the ctrl terminal.
if (setsid() < 0) {
MS_THROW_ERROR("setsid() failed: %s", std::strerror(errno));
}
// Fork again to drop group leadership.
if ((pid = fork()) < 0) {
MS_THROW_ERROR("second fork() failed: %s", std::strerror(errno));
}
else if (pid > 0) {
// Intermediary process just exits.
std::_Exit(EXIT_SUCCESS);
}
// This is the daemonized process.
// Create a PID file if requested.
if (! Settings::arguments.pidFile.empty()) {
if (! Daemon::WritePIDFile())
MS_THROW_ERROR("error writing the PID file '%s'", Settings::arguments.pidFile.c_str());
}
// Replace stdin, stdout & stderr with /dev/null.
if (std::freopen("/dev/null", "r", stdin) == nullptr) {
MS_ERROR("error replacing stdin with /dev/null: %s", std::strerror(errno));
}
if (std::freopen("/dev/null", "w", stdout) == nullptr) {
MS_ERROR("error replacing stdout with /dev/null: %s", std::strerror(errno));
}
if (std::freopen("/dev/null", "w", stderr) == nullptr) {
MS_ERROR("error replacing stderr with /dev/null: %s", std::strerror(errno));
}
// Close all the possible fds inherited from the ancestor process (all but
// the write side of the pipe as the daemonized process must use it).
for (int fd=3; fd<32; fd++) {
if (fd != Daemon::statusPipe[1])
close(fd);
}
// Enable Syslog logging.
Logger::EnableSyslog();
// First log in Syslog.
MS_NOTICE("%s running as daemon", Version::name.c_str());
}
void Daemon::SendOKStatusToAncestor() {
MS_TRACE();
MS_DEBUG("sending OK status to the ancestor process");
SendStatusToAncestor(EXIT_SUCCESS);
}
void Daemon::SendErrorStatusToAncestor() {
MS_TRACE();
MS_DEBUG("sending error status to the ancestor process");
SendStatusToAncestor(EXIT_FAILURE);
}
bool Daemon::IsDaemonized() {
MS_TRACE();
return Daemon::isDaemonized;
}
void Daemon::End() {
MS_TRACE();
// Delete PID file.
if (Daemon::hasWrittenPIDFile) {
int err;
err = std::remove(Settings::arguments.pidFile.c_str());
if (err)
MS_ERROR("cannot delete the PID file '%s': %s", Settings::arguments.pidFile.c_str(), std::strerror(errno));
}
}
bool Daemon::WritePIDFile() {
MS_TRACE();
FILE *pid_file;
const char* pidFile = Settings::arguments.pidFile.c_str();
unsigned int existing_pid = 0;
pid_t pid;
pid_file = std::fopen(pidFile, "r");
// PID file already exists. Check it.
if (pid_file) {
MS_DEBUG("a PID file '%s' already exists", pidFile);
if (std::fscanf(pid_file, "%9u", &existing_pid) < 0) {
MS_ERROR("could not parse existing PID file '%s'", pidFile);
std::fclose(pid_file);
return false;
}
fclose(pid_file);
if (existing_pid == 0) {
MS_ERROR("existing PID file '%s' does not contain a valid value", pidFile);
return false;
}
if (kill((pid_t)existing_pid, 0) == 0 || errno == EPERM) {
MS_ERROR("there is a running process with the same PID as in the existing PID file '%s'",
pidFile);
return false;
}
else {
MS_NOTICE("existing PID file '%s' contains an old PID, replacing its value", pidFile);
}
}
// Get our PID.
pid = getpid();
MS_DEBUG("PID of the daemonized process: %u", (unsigned int)pid);
// Write into the PID file.
pid_file = std::fopen(pidFile, "w");
if (! pid_file) {
MS_ERROR("cannot open PID file '%s' for writing: %s", pidFile, std::strerror(errno));
return false;
}
std::fprintf(pid_file, "%u\n", (unsigned int)pid);
std::fclose(pid_file);
Daemon::hasWrittenPIDFile = true;
MS_DEBUG("PID file '%s' created with our PID value", pidFile);
return true;
}
bool Daemon::WaitForDaemonizedStatus(char* status) {
MS_TRACE();
int ret;
MS_DEBUG("waiting for the daemonized process to write its status");
// Close the output side of the pipe.
if (Daemon::statusPipe[1] != -1) {
close(Daemon::statusPipe[1]);
Daemon::statusPipe[1] = -1;
}
// If the read side of the pipe is closed the daemonized process died even before
// sending status.
if (Daemon::statusPipe[0] == -1) {
return false;
}
do {
ret = read(Daemon::statusPipe[0], status, 1);
} while(ret < 0 && errno == EINTR);
// If a byte has been read return true and the ancestor process will inspect the
// status value.
return (ret == 1) ? true : false;
}
void Daemon::SendStatusToAncestor(char status) {
MS_TRACE();
int ret;
if (Daemon::statusPipe[1] == -1) {
MS_ERROR("cannot send status to ancestor process, pipe is closed");
return;
}
do {
ret = write(Daemon::statusPipe[1], &status, 1);
} while(ret < 0 && errno == EINTR);
if (ret != 1)
MS_ERROR("cannot send status to ancestor process: %s", std::strerror(errno));
close(Daemon::statusPipe[1]);
Daemon::statusPipe[1] = -1;
}
#define MS_CLASS "Dispatcher"
#include "Dispatcher.h"
#include "Settings.h"
#include "Daemon.h"
#include "Worker.h"
#include "Utils.h"
#include "LibUV.h"
#include "ControlProtocol/messages.h"
#include "MediaSoupError.h"
#include "Logger.h"
#include <string>
#include <csignal> // sigaction(), pthread_sigmask()
#include <cerrno>
/* Instance methods. */
Dispatcher::Dispatcher() {
MS_TRACE();
// Set the signals handler.
try {
this->signalsHandler = new SignalsHandler(this);
// Add signals to handle.
this->signalsHandler->AddSignal(SIGUSR1, "USR1");
this->signalsHandler->AddSignal(SIGINT, "INT");
this->signalsHandler->AddSignal(SIGTERM, "TERM");
}
catch (const MediaSoupError &error) {
MS_THROW_ERROR("error creating the SignalsHandler: %s", error.what());
}
MS_DEBUG("SignalsHandler ready");
// Create a ControlProtocol TCP server.
std::string ip = Settings::configuration.ControlProtocol.listenIP;
MS_PORT port = Settings::configuration.ControlProtocol.listenPort;
try {
this->controlProtocolTCPServer = new ControlProtocol::TCPServer(this, this, ip, port);
}
catch (const MediaSoupError &error) {
MS_THROW_ERROR("error creating a ControlProtocol TCP server in %s : %d: %s", ip.c_str(), port, error.what());
}
MS_DEBUG("ControlProtocol TCP server listening into %s : %d", this->controlProtocolTCPServer->GetLocalIP().c_str(), this->controlProtocolTCPServer->GetLocalPort());
// Create the ControlProtocol UnixStream sockets.
int num_workers = Worker::CountWorkers();
// Insert a nullptr value in position 0 of the vector of ControlProtocol::UnixStreamSocket*
// since the first entry will be in position 1.
this->controlProtocolUnixStreamSockets.push_back(nullptr);
for (int workerId=1; workerId <= num_workers; workerId++) {
int fd = Worker::GetControlProtocolRemoteSocket(workerId);
ControlProtocol::UnixStreamSocket* controlProtocolUnixStreamSocket;
try {
controlProtocolUnixStreamSocket = new ControlProtocol::UnixStreamSocket(this, fd);
// Attach the workerId as user data.
int* data = new int(workerId);
controlProtocolUnixStreamSocket->SetUserData((void*)data);
}
catch (const MediaSoupError &error) {
MS_THROW_ERROR("error creating a ControlProtocol Unix socket for Worker %d: %s", workerId, error.what());
}
// Add to the vector. Note that workerId 1 will be placed in position 1 of the vector.
this->controlProtocolUnixStreamSockets.push_back(controlProtocolUnixStreamSocket);
MS_DEBUG("ControlProtocol Unix socket for Worker #%d ready", workerId);
}
MS_DEBUG("Dispatcher running");
// Write the success status on the pipe if daemonized to tell the ancestor
// process that the daemonized process is properly running.
if (Settings::arguments.daemonize)
Daemon::SendOKStatusToAncestor();
// Run the loop.
LibUV::RunLoop();
MS_DEBUG("libuv loop ends");
}
Dispatcher::~Dispatcher() {
MS_TRACE();
}
void Dispatcher::Close() {
MS_TRACE();
if (this->closed) {
MS_ERROR("already closed");
return;
}
this->closed = true;
MS_DEBUG("closing all the services running in the Dispatcher");
// First block all the signals to not be interrupted while closing.
int err;
sigset_t signal_mask;
// Block all the signals.
sigfillset(&signal_mask);
err = pthread_sigmask(SIG_BLOCK, &signal_mask, nullptr);
if (err)
MS_ERROR("pthread_sigmask() failed: %s", std::strerror(errno));
// Close the SignalsHandler.
this->signalsHandler->Close();
// Close the ControlProtocol TCP server.
this->controlProtocolTCPServer->Close();
// Close the ControlProtocol UnixStream sockets.
int num_workers = Worker::CountWorkers();
for (int workerId=1; workerId <= num_workers; workerId++) {
this->controlProtocolUnixStreamSockets[workerId]->Close();
}
}
void Dispatcher::onSignal(SignalsHandler* signalsHandler, int signum) {
MS_TRACE();
switch(signum) {
// SIGUSR1 means configuration reload.
case SIGUSR1:
MS_NOTICE("signal USR1 received, reloading configuration");
if (Settings::ReloadConfigurationFile()) {
// Print new configuration.
Settings::PrintConfiguration();
}
break;
case SIGINT:
MS_NOTICE("signal INT received, exiting");
Close();
break;
case SIGTERM:
MS_NOTICE("signal TERM received, exiting");
Close();
break;
default:
MS_ERROR("received a signal (with signum %d) for which there is no handling code", signum);
}
}
void Dispatcher::onSignalsHandlerClosed(SignalsHandler* signalsHandler) {
MS_TRACE();
}
void Dispatcher::onControlProtocolNewTCPConnection(ControlProtocol::TCPServer* tcpServer, ControlProtocol::TCPConnection* connection) {
MS_TRACE();
MS_DEBUG("new ControlProtocol TCP connection:");
tcpServer->Dump();
connection->Dump();
}
void Dispatcher::onControlProtocolTCPConnectionClosed(ControlProtocol::TCPServer* tcpServer, ControlProtocol::TCPConnection* connection, bool is_closed_by_peer) {
MS_TRACE();
if (is_closed_by_peer)
MS_DEBUG("ControlProtocol TCP connection closed by peer:");
else
MS_DEBUG("ControlProtocol TCP connection closed locally:");
connection->Dump();
tcpServer->Dump();
}
void Dispatcher::onControlProtocolMessage(ControlProtocol::TCPConnection* connection, ControlProtocol::Message* msg, const MS_BYTE* raw, size_t len) {
MS_TRACE();
MS_DEBUG("ControlProtocol message received from TCP %s : %u", connection->GetPeerIP().c_str(), (unsigned int)connection->GetPeerPort());
// TODO: process the ControlProtocol::Message.
// TEST
bool relayToRandomWorker = true;
bool relayToAllWorkers = false;
bool replyOK = true;
if (relayToRandomWorker) {
int workerId = (int)Utils::Crypto::GetRandomUInt(1, (unsigned int)Worker::CountWorkers());
MS_INFO("relaying ControlProtocol message to Worker #%d ...", workerId);
ControlProtocol::UnixStreamSocket* controlProtocolUnixStreamSocket = controlProtocolUnixStreamSockets[workerId];
controlProtocolUnixStreamSocket->Write(raw, len);
}
if (relayToAllWorkers) {
int num_workers = Worker::CountWorkers();
for (int workerId=1; workerId <= num_workers; workerId++) {
ControlProtocol::UnixStreamSocket* controlProtocolUnixStreamSocket = controlProtocolUnixStreamSockets[workerId];
MS_INFO("relaying ControlProtocol message to Worker #%d ...", workerId);
controlProtocolUnixStreamSocket->Write(raw, len);
}
}
if (replyOK) {
MS_INFO("replying 'OK, message received' via TCP ...");
// TEST: Write(std::string &data)
std::string ok_reply_begin = "OK, message received with transaction ";
connection->Write(ok_reply_begin);
// TEST: Write(std::string &data)
std::string transaction_str = std::to_string(msg->GetTransaction());
connection->Write(transaction_str);
// TEST: Write(std::string &data)
std::string ok_reply_end = ":\n---------------------\n";
connection->Write(ok_reply_end);
// TEST: Write(const MS_BYTE* data, size_t len)
connection->Write(raw, len);
// TEST: Write(std::string &data)
std::string ok_reply_real_end = "---------------------\n";
connection->Write(ok_reply_real_end);
}
}
void Dispatcher::onControlProtocolMessage(ControlProtocol::UnixStreamSocket* unixSocket, ControlProtocol::Message* msg, const MS_BYTE* raw, size_t len) {
MS_TRACE();
// Get the workerId associated to this socket.
int workerId = *(int*)unixSocket->GetUserData();
// TMP
MS_INFO("ControlProtocol message received from Worker #%d", workerId);
// TMP send back to the worker (loop !!!)
unixSocket->Write((MS_BYTE*)raw, len);
// TODO: process the ControlProtocol::Message.
}
void Dispatcher::onControlProtocolUnixStreamSocketClosed(ControlProtocol::UnixStreamSocket* unixSocket, bool is_closed_by_peer) {
MS_TRACE();
// Get the workerId associated to this socket.
int* userData = (int*)unixSocket->GetUserData();
int workerId = *userData;
// Free the socket's user data and remove the socket from the map.
delete userData;
controlProtocolUnixStreamSockets[workerId] = nullptr;
// A Worker MUST NEVER close the socket. If it does it is due to a parsing error
// that should NEVER happen, so abort.
if (is_closed_by_peer)
MS_ABORT("ControlProtocol Unix socket for Worker #%d remotely closed", workerId);
else
MS_DEBUG("ControlProtocol Unix socket for Worker #%d locally closed", workerId);
}
#define MS_CLASS "LibSRTP"
#include "LibSRTP.h"
#include "MediaSoupError.h"
#include "Logger.h"
/* Static variables. */
std::vector<const char*> LibSRTP::errors = {
// From 0 (err_status_ok) to 24 (err_status_pfkey_err).
"nothing to report (err_status_ok)",
"unspecified failure (err_status_fail)",
"unsupported parameter (err_status_bad_param)",
"couldn't allocate memory (err_status_alloc_fail)",
"couldn't deallocate memory (err_status_dealloc_fail)",
"couldn't initialize (err_status_init_fail)",
"can’t process as much data as requested (err_status_terminus)",
"authentication failure (err_status_auth_fail)",
"cipher failure (err_status_cipher_fail)",
"replay check failed (bad index) (err_status_replay_fail)",
"replay check failed (index too old) (err_status_replay_old)",
"algorithm failed test routine (err_status_algo_fail)",
"unsupported operation (err_status_no_such_op)",
"no appropriate context found (err_status_no_ctx)",
"unable to perform desired validation (err_status_cant_check)",
"can’t use key any more (err_status_key_expired)",
"error in use of socket (err_status_socket_err)",
"error in use POSIX signals (err_status_signal_err)",
"nonce check failed (err_status_nonce_bad)",
"couldn’t read data (err_status_read_fail)",
"couldn’t write data (err_status_write_fail)",
"error parsing data (err_status_parse_err)",
"error encoding data (err_status_encode_err)",
"error while using semaphores (err_status_semaphore_err)",
"error while using pfkey (err_status_pfkey_err)"
};
/* Static methods. */
void LibSRTP::ClassInit() {
MS_TRACE();
err_status_t err;
MS_DEBUG("loaded libsrtp");
err = srtp_init();
if (LibSRTP::IsError(err))
MS_THROW_ERROR("srtp_init() failed: %s", LibSRTP::GetErrorString(err));
}
void LibSRTP::ClassDestroy() {
MS_TRACE();
err_status_t err;
MS_DEBUG("unloading libsrtp");
err = srtp_shutdown();
if (LibSRTP::IsError(err))
MS_CRIT("srtp_shutdown() failed: %s", LibSRTP::GetErrorString(err));
}
#define MS_CLASS "LibUV"
#include "LibUV.h"
#include "Logger.h"
/* Static variables. */
__thread uv_loop_t* LibUV::loop = nullptr;
/* Static methods. */
void LibUV::ClassInit() {
MS_TRACE();
// Print libuv version.
MS_DEBUG("loaded libuv version: %s", uv_version_string());
}
void LibUV::ThreadInit() {
MS_TRACE();
int err;
// This should never happen.
if (LibUV::loop)
MS_ABORT("LibUV::loop alread allocated in this thread");
LibUV::loop = new uv_loop_t;
err = uv_loop_init(LibUV::loop);
if (err)
MS_ABORT("uv_loop_init() failed: %s", uv_strerror(err));
}
void LibUV::ThreadDestroy() {
MS_TRACE();
// This should never happen.
if (! LibUV::loop)
MS_ABORT("LibUV::loop was not allocated in this thread");
uv_loop_close(LibUV::loop);
delete LibUV::loop;
}
void LibUV::RunLoop() {
MS_TRACE();
// This should never happen.
if (! LibUV::loop)
MS_ABORT("LibUV::loop was not allocated in this thread");
uv_run(LibUV::loop, UV_RUN_DEFAULT);
}
#define MS_CLASS "Logger"
#include "Logger.h"
#include "Version.h"
/* Static variables. */
__thread std::string* Logger::threadName = nullptr;
__thread const char* Logger::threadNamePtr = nullptr;
bool Logger::isSyslogEnabled = false;
/* Static methods. */
void Logger::ThreadInit(const std::string name) {
// Store the name for this thread in thread local storage.
if (Logger::threadName)
delete Logger::threadName;
// NOTE: this std::string pointer is never deallocated.
Logger::threadName = new std::string(name);
Logger::threadNamePtr = Logger::threadName->c_str();
MS_TRACE();
}
void Logger::EnableSyslog() {
MS_TRACE();
openlog(Version::command.c_str(), (LOG_PID), Settings::configuration.syslogFacility);
Logger::isSyslogEnabled = true;
}
#define MS_CLASS "MediaSoup"
#include "MediaSoup.h"
#include "Settings.h"
#include "Daemon.h"
#include "Dispatcher.h"
#include "Worker.h"
#include "LibUV.h"
#include "OpenSSL.h"
#include "LibSRTP.h"
#include "Utils.h"
#include "RTC/UDPSocket.h"
#include "RTC/TCPServer.h"
#include "RTC/DTLSHandler.h"
#include "RTC/SRTPSession.h"
#include "MediaSoupError.h"
#include "Logger.h"
#include <vector>
#include <map>
#include <string>
#include <csignal> // sigaction()
#include <cstdlib> // std::strtol()
#include <cerrno>
#include <cstdint> // uint8_t, etc
#include <ctime> // nanosleep()
#include <sys/resource.h> // setrlimit(), setrlimit()
#include <unistd.h> // setgid(), setuid(), initgroups()
#include <pwd.h>
#include <grp.h>
#include <uv.h>
#ifndef MS_RECOMMENDED_NOFILE
#define MS_RECOMMENDED_NOFILE 131072
#endif
/* Static methods. */
void MediaSoup::SetProcess() {
MS_TRACE();
#if defined(MS_LITTLE_ENDIAN)
MS_DEBUG("detected Little-Endian CPU");
#elif defined(MS_BIG_ENDIAN)
MS_DEBUG("detected Big-Endian CPU");
#endif
#if defined(INTPTR_MAX) && defined(INT32_MAX) && (INTPTR_MAX == INT32_MAX)
MS_DEBUG("detected 32 bits architecture");
#elif defined(INTPTR_MAX) && defined(INT64_MAX) && (INTPTR_MAX == INT64_MAX)
MS_DEBUG("detected 64 bits architecture");
#else
MS_NOTICE("cannot determine whether the architecture is 32 or 64 bits");
#endif
// NOTE: Some of these methods can exit if error if detected.
IgnoreSignals();
SetKernelLimits();
SetUserGroup();
}
void MediaSoup::Run() {
MS_TRACE();
// Init main thread stuff.
MediaSoup::ThreadInit();
// Init static data.
MediaSoup::ClassInit();
int err;
// A vector for holding the workerId value for each thread.
std::vector<int> worker_ids;
for(int workerId=1; workerId <= Settings::configuration.numWorkers; workerId++) {
worker_ids.push_back(workerId);
Worker::SetWorker(workerId, nullptr);
}
// A vector for holding all the worker threads and joining them later.
std::vector<uv_thread_t> worker_threads;
// Build the Worker threads.
for(int i = 0; i < Settings::configuration.numWorkers; i++) {
MS_DEBUG("running a thread for Worker #%d", worker_ids[i]);
uv_thread_t thread;
err = uv_thread_create(&thread, MediaSoup::RunWorkerThread, (void*)&worker_ids[i]);
if (err)
MS_THROW_ERROR("uv_thread_create() failed: %s", uv_strerror(err));
worker_threads.push_back(thread);
}
// Wait for all the workers to be running.
// Wait 300 rounds of 0.01 seconds each one (max 3 seconds).
MS_DEBUG("waiting for all the Workers to be running...");
bool all_workers_running = false;
struct timespec waiting;
waiting.tv_sec = 0;
waiting.tv_nsec = 10000000; // 10 ms.
for(int i=1; i<=300; i++) {
if (Worker::AreAllWorkersRunning()) {
all_workers_running = true;
break;
}
err = nanosleep(&waiting, nullptr);
if (err)
MS_THROW_ERROR("nanosleep() failed: %s", uv_strerror(err));
}
if (! all_workers_running)
MS_THROW_ERROR("some Worker(s) could not start or died");
MS_DEBUG("all the Workers running, let's run the Dispatcher");
try {
Dispatcher dispatcher;
}
catch (const MediaSoupError &error) {
MS_THROW_ERROR("%s", error.what());
}
MS_DEBUG("Dispatcher ends, waiting for Workers to end");
for (auto thread : worker_threads) {
err = uv_thread_join(&thread);
if (err)
MS_THROW_ERROR("uv_thread_join() failed: %s", uv_strerror(err));
}
MS_DEBUG("all the Workers have ended");
}
void MediaSoup::End() {
MS_TRACE();
// Tell the Daemon class to cleanup its resources if needed.
if (Daemon::IsDaemonized())
Daemon::End();
// Free static stuff.
MediaSoup::ClassDestroy();
// Free thread stuff.
MediaSoup::ThreadDestroy();
}
void MediaSoup::IgnoreSignals() {
MS_TRACE();
int err;
struct sigaction act;
// NOTE: Here we ignore also signals that will be later handled by the Dispatcher
// (as the libuv signal handler overrides it).
std::map<std::string, int> ignored_signals = {
{ "INT", SIGINT },
{ "TERM", SIGTERM },
{ "HUP", SIGHUP },
{ "ALRM", SIGALRM },
{ "USR1", SIGUSR2 },
{ "USR2", SIGUSR1 }
};
act.sa_handler = SIG_IGN;
act.sa_flags = 0;
err = sigfillset(&act.sa_mask);
if (err)
MS_EXIT_FAILURE("sigfillset() failed: %s", std::strerror(errno));
for(auto it = ignored_signals.begin(); it != ignored_signals.end(); ++it) {
std::string sig_name = it->first;
int sig_id = it->second;
err = sigaction(sig_id, &act, nullptr);
if (err)
MS_EXIT_FAILURE("sigaction() failed for signal %s: %s", sig_name.c_str(), std::strerror(errno));
}
}
void MediaSoup::SetKernelLimits() {
MS_TRACE();
struct rlimit current_limit;
struct rlimit new_limit;
rlim_t recommended_NOFILE = MS_RECOMMENDED_NOFILE;
int err;
// Get current NOFILE limits.
err = getrlimit(RLIMIT_NOFILE, &current_limit);
if (err) {
MS_EXIT_FAILURE("getrlimit(RLIMIT_NOFILE) failed: %s", std::strerror(errno));
return;
}
MS_DEBUG("getrlimit(RLIMIT_NOFILE) [soft:%llu, hard:%llu]", (unsigned long long)current_limit.rlim_cur, (unsigned long long)current_limit.rlim_max);
// If soft limit of "open files" is equal or bigger than recommended_NOFILE we are done.
if (current_limit.rlim_cur >= recommended_NOFILE)
goto end;
// If hard limit of "open files" is equal or bigger than recommended_NOFILE then we should
// be able to set the soft limit to recommended_NOFILE.
// NOTE: This is not true on OSX in which hard limit is infinity but it does
// not let the user chaning its soft limit.
if (current_limit.rlim_max >= recommended_NOFILE) {
new_limit.rlim_cur = recommended_NOFILE;
new_limit.rlim_max = current_limit.rlim_max;
err = setrlimit(RLIMIT_NOFILE, &new_limit);
if (err) {
if (errno == EINVAL) {
MS_DEBUG("setrlimit(RLIMIT_NOFILE) failed for limits [soft:%llu, hard:%llu]: %s", (unsigned long long)new_limit.rlim_cur, (unsigned long long)new_limit.rlim_max, std::strerror(errno));
}
else {
MS_WARN("setrlimit(RLIMIT_NOFILE) failed for limits [soft:%llu, hard:%llu]: %s", (unsigned long long)new_limit.rlim_cur, (unsigned long long)new_limit.rlim_max, std::strerror(errno));
}
}
}
// Otherwise try to set both hard and soft limits to recommended_NOFILE.
else {
new_limit.rlim_cur = recommended_NOFILE;
new_limit.rlim_max = recommended_NOFILE;
err = setrlimit(RLIMIT_NOFILE, &new_limit);
if (err)
MS_WARN("setrlimit(RLIMIT_NOFILE) failed for limits [soft:%llu, hard:%llu]: %s", (unsigned long long)new_limit.rlim_cur, (unsigned long long)new_limit.rlim_max, std::strerror(errno));
}
end:
// Get the resulting NOFILE limits.
err = getrlimit(RLIMIT_NOFILE, &current_limit);
if (err) {
MS_EXIT_FAILURE("getrlimit(RLIMIT_NOFILE) failed: %s", std::strerror(errno));
return;
}
// If the soft limit is equal or bigger than recommended_NOFILE then ok.
if (current_limit.rlim_cur >= recommended_NOFILE) {
MS_DEBUG("RLIMIT_NOFILE soft limit (max open files) set to %llu", (unsigned long long)current_limit.rlim_cur);
}
// Otherwise warn the user.
else {
MS_WARN("RLIMIT_recommended_NOFILE soft limit (max open files) set to %llu, less than the recommended value (%llu)", (unsigned long long)current_limit.rlim_cur, (unsigned long long)recommended_NOFILE);
}
}
void MediaSoup::SetUserGroup() {
MS_TRACE();
struct group *grp = nullptr;
struct passwd *pwd = nullptr;
// Set the group if requested.
if (! Settings::arguments.group.empty()) {
char *endptr;
const char* group = Settings::arguments.group.c_str();
gid_t g, gid;
// Allow passing a numeric string representing the user's gid.
g = std::strtol(group, &endptr, 10);
if (*endptr == '\0') {
gid = (gid_t)g;
grp = getgrgid(gid);
if (! grp)
MS_EXIT_FAILURE("cannot get information for group with gid '%d': %s", (int)gid, std::strerror(errno));
}
// Otherwise convert from name to gid.
else {
grp = getgrnam(group);
if (! grp) {
MS_EXIT_FAILURE("group '%s' does not exist", group);
}
gid = grp->gr_gid;
}
// Set gid as process gid.
MS_DEBUG("setting '%s' (%d) as process group", group, (int)gid);
if (setgid(gid) < 0)
MS_EXIT_FAILURE("cannot change gid to %s (%d): %s", group, (int)gid, std::strerror(errno));
}
// Set the user if requested.
if (! Settings::arguments.user.empty()) {
char *endptr;
const char* user = Settings::arguments.user.c_str();
uid_t u, uid;
// Allow passing a numeric string representing the group's uid.
u = std::strtol(user, &endptr, 10);
if (*endptr == '\0') {
uid = (uid_t)u;
pwd = getpwuid(uid);
if (! pwd)
MS_EXIT_FAILURE("cannot get information for user with uid '%d': %s", (int)uid, std::strerror(errno));
}
// Otherwise convert from name to uid.
else {
pwd = getpwnam(user);
if (! pwd) {
MS_EXIT_FAILURE("user '%s' does not exist", user);
}
uid = pwd->pw_uid;
}
// Set access to all the groups of which the user is member.
gid_t additional_gid = grp ? grp->gr_gid : pwd->pw_gid;
MS_DEBUG("setting supplementary groups for uid %d (using %d as additional gid)", (int)uid, (int)additional_gid);
if (initgroups(pwd->pw_name, additional_gid) < 0)
MS_EXIT_FAILURE("initgroups() for uid %d and gid %d failed: %s", (int)uid, (int)additional_gid, std::strerror(errno));
// Set uid as process uid.
MS_DEBUG("setting '%s' (%d) as process user", user, (int)uid);
if (setuid(uid) < 0)
MS_EXIT_FAILURE("cannot change uid to %s (%d): %s", user, (int)uid, std::strerror(errno));
}
}
void MediaSoup::ThreadInit() {
MS_TRACE();
// Set (again, don't worry) this thread as main thread.
Logger::ThreadInit("main");
// Load libuv stuff.
LibUV::ThreadInit();
// Load the crypto utils.
Utils::Crypto::ThreadInit();
}
void MediaSoup::ThreadDestroy() {
MS_TRACE();
LibUV::ThreadDestroy();
Utils::Crypto::ThreadDestroy();
}
void MediaSoup::ClassInit() {
MS_TRACE();
// Initialize static stuff.
LibUV::ClassInit();
OpenSSL::ClassInit();
LibSRTP::ClassInit();
RTC::UDPSocket::ClassInit();
RTC::TCPServer::ClassInit();
RTC::DTLSHandler::ClassInit();
RTC::SRTPSession::ClassInit();
}
void MediaSoup::ClassDestroy() {
MS_TRACE();
// Free static stuff.
RTC::DTLSHandler::ClassDestroy();
OpenSSL::ClassDestroy();
LibSRTP::ClassDestroy();
}
/* This method is called within a new thread and creates a Worker. */
void MediaSoup::RunWorkerThread(void* data) {
int workerId = *(int*)data;
// Init thread stuff.
Worker::ThreadInit(workerId);
try {
MS_DEBUG("initializing Worker #%d", workerId);
Worker worker(workerId);
MS_DEBUG("Worker #%d exits", workerId);
}
catch (const MediaSoupError &error) {
MS_CRIT("error happened in Worker #%d: %s | Worker ended", workerId, error.what());
Worker::ThreadDestroy();
throw(error);
}
Worker::ThreadDestroy();
}
#define MS_CLASS "OpenSSL"
#include "OpenSSL.h"
#include "MediaSoupError.h"
#include "Logger.h"
#include <openssl/err.h>
#include <openssl/engine.h> // ENGINE_cleanup()
/* Static attributes. */
// This array will store all of the mutex available for OpenSSL.
pthread_mutex_t* OpenSSL::mutexes = nullptr;
int OpenSSL::numMutexes = 0;
/* Static methods. */
void OpenSSL::ClassInit() {
MS_TRACE();
MS_DEBUG("loaded openssl version: %s", SSLeay_version(SSLEAY_VERSION));
// First initialize OpenSSL stuff.
SSL_load_error_strings();
SSL_library_init();
RAND_poll();
// Make OpenSSL thread-safe.
OpenSSL::mutexes = new pthread_mutex_t[CRYPTO_num_locks()];
if (! OpenSSL::mutexes)
MS_THROW_ERROR("allocation of mutexes failed");
OpenSSL::numMutexes = CRYPTO_num_locks();
for (int i=0; i<OpenSSL::numMutexes; i++) {
int err = pthread_mutex_init(&OpenSSL::mutexes[i], nullptr);
if (err)
MS_THROW_ERROR("pthread_mutex_init() failed with return code %d\n", err);
}
CRYPTO_THREADID_set_callback(OpenSSL::SetThreadId);
CRYPTO_set_locking_callback(OpenSSL::LockingFunction);
CRYPTO_set_dynlock_create_callback(OpenSSL::DynCreateFunction);
CRYPTO_set_dynlock_lock_callback(OpenSSL::DynLockFunction);
CRYPTO_set_dynlock_destroy_callback(OpenSSL::DynDestroyFunction);
}
void OpenSSL::ClassDestroy() {
MS_TRACE();
MS_DEBUG("unloading openssl");
// FAQ: https://www.openssl.org/support/faq.html#PROG13
// Thread-local cleanup functions.
ERR_remove_thread_state(nullptr);
// Application-global cleanup functions that are aware of usage (and
// therefore thread-safe).
ENGINE_cleanup();
// "Brutal" (thread-unsafe) Application-global cleanup functions.
ERR_free_strings();
EVP_cleanup(); // Removes all ciphers and digests.
CRYPTO_cleanup_all_ex_data();
// https://bugs.launchpad.net/percona-server/+bug/1341067.
sk_SSL_COMP_free(SSL_COMP_get_compression_methods());
// Free mutexes.
for (int i=0; i<OpenSSL::numMutexes; i++) {
int err = pthread_mutex_destroy(&OpenSSL::mutexes[i]);
if (err)
MS_ERROR("pthread_mutex_destroy() failed with return code %d\n", err);
}
if (OpenSSL::mutexes)
delete[] OpenSSL::mutexes;
// Reset callbacks.
CRYPTO_THREADID_set_callback(nullptr);
CRYPTO_set_locking_callback(nullptr);
CRYPTO_set_dynlock_create_callback(nullptr);
CRYPTO_set_dynlock_lock_callback(nullptr);
CRYPTO_set_dynlock_destroy_callback(nullptr);
}
void OpenSSL::SetThreadId(CRYPTO_THREADID* id) {
// MS_TRACE();
CRYPTO_THREADID_set_numeric(id, (unsigned long)pthread_self());
}
void OpenSSL::LockingFunction(int mode, int n, const char *file, int line) {
// MS_TRACE();
/**
* - mode: bitfield describing what should be done with the lock:
* CRYPTO_LOCK 0x01
* CRYPTO_UNLOCK 0x02
* CRYPTO_READ 0x04
* CRYPTO_WRITE 0x08
* - n: the number of the mutex.
* - file: source file calling this function.
* - line: line in the source file calling this function.
*/
// MS_DEBUG("[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)
pthread_mutex_lock(&OpenSSL::mutexes[n]);
else
pthread_mutex_unlock(&OpenSSL::mutexes[n]);
}
CRYPTO_dynlock_value* OpenSSL::DynCreateFunction(const char* file, int line) {
// MS_TRACE();
CRYPTO_dynlock_value* value = new CRYPTO_dynlock_value;
if (! value) {
MS_ABORT("new CRYPTO_dynlock_value failed");
return nullptr;
}
pthread_mutex_init(&value->mutex, nullptr);
return value;
}
void OpenSSL::DynLockFunction(int mode, CRYPTO_dynlock_value* v, const char* file, int line) {
// MS_TRACE();
if (mode & CRYPTO_LOCK) {
pthread_mutex_lock(&v->mutex);
} else {
pthread_mutex_unlock(&v->mutex);
}
}
void OpenSSL::DynDestroyFunction(CRYPTO_dynlock_value* v, const char* file, int line) {
// MS_TRACE();
pthread_mutex_destroy(&v->mutex);
delete v;
}
#define MS_CLASS "RTC::DTLSHandler"
#include "RTC/DTLSHandler.h"
#include "Settings.h"
#include "Version.h"
#include "Utils.h"
#include "MediaSoupError.h"
#include "Logger.h"
#include <cstdio> // std::sprintf(), std::fopen()
#include <cstring> // std::memcpy(), std::strcmp()
#include <ctime> // struct timeval
#include <algorithm> // std::transform()
#include <openssl/err.h>
#include <openssl/bn.h>
#include <openssl/evp.h>
#include <openssl/rsa.h>
#include <openssl/asn1.h>
#define MS_SSL_READ_BUFFER_SIZE 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.
#define MS_SRTP_MASTER_KEY_LENGTH 16
#define MS_SRTP_MASTER_SALT_LENGTH 14
#define MS_SRTP_MASTER_LENGTH (MS_SRTP_MASTER_KEY_LENGTH + MS_SRTP_MASTER_SALT_LENGTH)
#define LOG_OPENSSL_ERROR(desc) \
do { \
if (ERR_peek_error() == 0) \
MS_ERROR("OpenSSL error | " desc); \
else { \
unsigned long err; \
while ((err = ERR_get_error()) != 0) { \
MS_ERROR("OpenSSL error | " desc ": %s", ERR_error_string(err, nullptr)); \
} \
ERR_clear_error(); \
} \
} while(0)
/* Static methods for OpenSSL callbacks. */
static inline
int on_ssl_certificate_verify(int preverify_ok, X509_STORE_CTX* ctx) {
MS_TRACE();
// Always valid.
return 1;
}
static inline
void on_ssl_info(const SSL* ssl, int where, int ret) {
static_cast<RTC::DTLSHandler*>(SSL_get_ex_data(ssl, 0))->onSSLInfo(where, ret);
}
namespace RTC {
/* Static variables. */
X509* DTLSHandler::certificate = nullptr;
EVP_PKEY* DTLSHandler::privateKey = nullptr;
SSL_CTX* DTLSHandler::sslCtx = nullptr;
DTLSHandler::Fingerprints DTLSHandler::fingerprints {
{ RTC::FingerprintHash::SHA1, "" },
{ RTC::FingerprintHash::SHA224, "" },
{ RTC::FingerprintHash::SHA256, "" },
{ RTC::FingerprintHash::SHA384, "" },
{ RTC::FingerprintHash::SHA512, "" }
};
DTLSHandler::SRTPProfiles DTLSHandler::srtpProfiles = {
{ RTC::SRTPProfile::AES_CM_128_HMAC_SHA1_80, "SRTP_AES128_CM_SHA1_80" },
{ RTC::SRTPProfile::AES_CM_128_HMAC_SHA1_32, "SRTP_AES128_CM_SHA1_32" }
};
__thread MS_BYTE DTLSHandler::sslReadBuffer[MS_SSL_READ_BUFFER_SIZE];
/* Static methods. */
void DTLSHandler::ClassInit() {
MS_TRACE();
// Generate a X509 certificate and private key (unless PEM files are privided).
if (Settings::configuration.RTC.dtlsCertificateFile.empty())
GenerateCertificateAndPrivateKey();
else
ReadCertificateAndPrivateKeyFromFiles();
// Create a global SSL_CTX.
CreateSSL_CTX();
// Generate certificate fingerprints.
GenerateFingerprints();
}
void DTLSHandler::ClassDestroy() {
MS_TRACE();
if (DTLSHandler::privateKey)
EVP_PKEY_free(DTLSHandler::privateKey);
if (DTLSHandler::certificate)
X509_free(DTLSHandler::certificate);
if (DTLSHandler::sslCtx)
SSL_CTX_free(DTLSHandler::sslCtx);
}
const std::string& DTLSHandler::GetFingerprint(RTC::FingerprintHash hash) {
MS_TRACE();
// NOTE: Don't check if the given hash is supported (should give a compilation error).
return DTLSHandler::fingerprints.at(hash);
}
void DTLSHandler::GenerateCertificateAndPrivateKey() {
MS_TRACE();
int ret = 0;
BIGNUM* bne = nullptr;
RSA* rsa_key = nullptr;
int num_bits = 1024;
X509_NAME* cert_name = nullptr;
// Create a big number object.
bne = BN_new();
if (! bne) {
LOG_OPENSSL_ERROR("BN_new() failed");
goto error;
}
ret = BN_set_word(bne, RSA_F4); // RSA_F4 == 65537.
if (ret == 0) {
LOG_OPENSSL_ERROR("BN_set_word() failed");
goto error;
}
// Generate a RSA key.
rsa_key = RSA_new();
if (! rsa_key) {
LOG_OPENSSL_ERROR("RSA_new() failed");
goto error;
}
// This takes some time.
ret = RSA_generate_key_ex(rsa_key, num_bits, bne, nullptr);
if (ret == 0) {
LOG_OPENSSL_ERROR("RSA_generate_key_ex() failed");
goto error;
}
// Create a private key object (needed to hold the RSA key).
DTLSHandler::privateKey = EVP_PKEY_new();
if (! DTLSHandler::privateKey) {
LOG_OPENSSL_ERROR("EVP_PKEY_new() failed");
goto error;
}
ret = EVP_PKEY_assign_RSA(DTLSHandler::privateKey, rsa_key);
if (ret == 0) {
LOG_OPENSSL_ERROR("EVP_PKEY_assign_RSA() failed");
goto error;
}
// The RSA key now belongs to the private key, so don't clean it up separately.
rsa_key = nullptr;
// Create the X509 certificate.
DTLSHandler::certificate = X509_new();
if (! DTLSHandler::certificate) {
LOG_OPENSSL_ERROR("X509_new() failed");
goto error;
}
// Set version 3 (note that 0 means version 1).
X509_set_version(DTLSHandler::certificate, 2);
// Set serial number (avoid default 0).
ASN1_INTEGER_set(X509_get_serialNumber(DTLSHandler::certificate), (long)Utils::Crypto::GetRandomUInt(1000000, 9999999));
// Set valid period.
X509_gmtime_adj(X509_get_notBefore(DTLSHandler::certificate), -1*60*60*24*365*10); // - 10 years.
X509_gmtime_adj(X509_get_notAfter(DTLSHandler::certificate), 60*60*24*365*10); // 10 years.
// Set the public key for the certificate using the key.
ret = X509_set_pubkey(DTLSHandler::certificate, DTLSHandler::privateKey);
if (ret == 0) {
LOG_OPENSSL_ERROR("X509_set_pubkey() failed");
goto error;
}
// Set certificate fields.
cert_name = X509_get_subject_name(DTLSHandler::certificate);
if (! cert_name) {
LOG_OPENSSL_ERROR("X509_get_subject_name() failed");
goto error;
}
X509_NAME_add_entry_by_txt(cert_name, "O", MBSTRING_ASC, (unsigned char *)Version::GetNameAndVersion().c_str(), -1, -1, 0);
X509_NAME_add_entry_by_txt(cert_name, "CN", MBSTRING_ASC, (unsigned char *)Version::name.c_str(), -1, -1, 0);
// It is self signed so set the issuer name to be the same as the subject.
ret = X509_set_issuer_name(DTLSHandler::certificate, cert_name);
if (ret == 0) {
LOG_OPENSSL_ERROR("X509_set_issuer_name() failed");
goto error;
}
// Sign the certificate with its own private key.
ret = X509_sign(DTLSHandler::certificate, DTLSHandler::privateKey, EVP_sha1());
if (ret == 0) {
LOG_OPENSSL_ERROR("X509_sign() failed");
goto error;
}
// Free stuff and return.
BN_free(bne);
return;
error:
if (bne)
BN_free(bne);
if (rsa_key && ! DTLSHandler::privateKey)
RSA_free(rsa_key);
if (DTLSHandler::privateKey)
EVP_PKEY_free(DTLSHandler::privateKey); // NOTE: This also frees the RSA key.
if (DTLSHandler::certificate)
X509_free(DTLSHandler::certificate);
MS_THROW_ERROR("DTLS certificate and private key generation failed");
}
void DTLSHandler::ReadCertificateAndPrivateKeyFromFiles() {
MS_TRACE();
FILE* file = nullptr;
file = fopen(Settings::configuration.RTC.dtlsCertificateFile.c_str(), "r");
if (! file) {
MS_ERROR("error reading DTLS certificate file: %s", std::strerror(errno));
goto error;
}
DTLSHandler::certificate = PEM_read_X509(file, nullptr, nullptr, nullptr);
if (! DTLSHandler::certificate) {
LOG_OPENSSL_ERROR("PEM_read_X509() failed");
goto error;
}
fclose(file);
file = fopen(Settings::configuration.RTC.dtlsPrivateKeyFile.c_str(), "r");
if (! file) {
MS_ERROR("error reading DTLS private key file: %s", std::strerror(errno));
goto error;
}
DTLSHandler::privateKey = PEM_read_PrivateKey(file, nullptr, nullptr, nullptr);
if (! DTLSHandler::privateKey) {
LOG_OPENSSL_ERROR("PEM_read_PrivateKey() failed");
goto error;
}
fclose(file);
return;
error:
MS_THROW_ERROR("error reading DTLS certificate and private key PEM files");
}
void DTLSHandler::CreateSSL_CTX() {
MS_TRACE();
std::string ssl_srtp_profiles;
EC_KEY* ecdh = nullptr;
int ret;
/* Set the global DTLS context. */
// - Both DTLS 1.0 and 1.2 (requires OpenSSL >= 1.1.0).
#if (OPENSSL_VERSION_NUMBER >= 0x10100000L)
DTLSHandler::sslCtx = SSL_CTX_new(DTLS_method());
// - Just DTLS 1.0 (requires OpenSSL >= 1.0.1).
#elif (OPENSSL_VERSION_NUMBER >= 0x10001000L)
DTLSHandler::sslCtx = SSL_CTX_new(DTLSv1_method());
#else
#error "too old OpenSSL version"
#endif
if (! DTLSHandler::sslCtx) {
LOG_OPENSSL_ERROR("SSL_CTX_new() failed");
goto error;
}
ret = SSL_CTX_use_certificate(DTLSHandler::sslCtx, DTLSHandler::certificate);
if (ret == 0) {
LOG_OPENSSL_ERROR("SSL_CTX_use_certificate() failed");
goto error;
}
ret = SSL_CTX_use_PrivateKey(DTLSHandler::sslCtx, DTLSHandler::privateKey);
if (ret == 0) {
LOG_OPENSSL_ERROR("SSL_CTX_use_PrivateKey() failed");
goto error;
}
ret = SSL_CTX_check_private_key(DTLSHandler::sslCtx);
if (ret == 0) {
LOG_OPENSSL_ERROR("SSL_CTX_check_private_key() failed");
goto error;
}
// Set options.
SSL_CTX_set_options(DTLSHandler::sslCtx, SSL_OP_CIPHER_SERVER_PREFERENCE | SSL_OP_NO_TICKET | SSL_OP_SINGLE_ECDH_USE);
// Don't use sessions cache.
SSL_CTX_set_session_cache_mode(DTLSHandler::sslCtx, SSL_SESS_CACHE_OFF);
// Read always as much into the buffer as possible.
SSL_CTX_set_read_ahead(DTLSHandler::sslCtx, 1);
SSL_CTX_set_verify_depth(DTLSHandler::sslCtx, 4);
// Require certificate from peer.
SSL_CTX_set_verify(DTLSHandler::sslCtx, SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT, on_ssl_certificate_verify);
// Set SSL info callback.
SSL_CTX_set_info_callback(DTLSHandler::sslCtx, on_ssl_info);
// Set ciphers.
ret = SSL_CTX_set_cipher_list(DTLSHandler::sslCtx, "ALL:!ADH:!LOW:!EXP:!MD5:!aNULL:!eNULL:@STRENGTH");
if (ret == 0) {
LOG_OPENSSL_ERROR("SSL_CTX_set_cipher_list() failed");
goto error;
}
// Enable ECDH ciphers.
// DOC: http://en.wikibooks.org/wiki/OpenSSL/Diffie-Hellman_parameters
// NOTE: https://code.google.com/p/chromium/issues/detail?id=406458
// For OpenSSL >= 1.0.2:
#if (OPENSSL_VERSION_NUMBER >= 0x10002000L)
SSL_CTX_set_ecdh_auto(DTLSHandler::sslCtx, 1);
#else
ecdh = EC_KEY_new_by_curve_name(NID_X9_62_prime256v1);
if (! ecdh) {
LOG_OPENSSL_ERROR("EC_KEY_new_by_curve_name() failed");
goto error;
}
if (SSL_CTX_set_tmp_ecdh(DTLSHandler::sslCtx, ecdh) != 1) {
LOG_OPENSSL_ERROR("SSL_CTX_set_tmp_ecdh() failed");
goto error;
}
EC_KEY_free(ecdh);
ecdh = nullptr;
#endif
// Set the "use_srtp" DTLS extension.
for (auto it = DTLSHandler::srtpProfiles.begin(); it != DTLSHandler::srtpProfiles.end(); ++it) {
if (it != DTLSHandler::srtpProfiles.begin())
ssl_srtp_profiles += ":";
SrtpProfileMapEntry* profile_entry = &(*it);
ssl_srtp_profiles += profile_entry->name;
}
MS_DEBUG("setting SRTP profiles for DTLS: %s", ssl_srtp_profiles.c_str());
// NOTE: This function returns 0 on success.
ret = SSL_CTX_set_tlsext_use_srtp(DTLSHandler::sslCtx, ssl_srtp_profiles.c_str());
if (ret != 0) {
MS_ERROR("SSL_CTX_set_tlsext_use_srtp() failed when entering '%s'", ssl_srtp_profiles.c_str());
LOG_OPENSSL_ERROR("SSL_CTX_set_tlsext_use_srtp() failed");
goto error;
}
return;
error:
if (DTLSHandler::sslCtx) {
SSL_CTX_free(DTLSHandler::sslCtx);
DTLSHandler::sslCtx = nullptr;
}
if (ecdh)
EC_KEY_free(ecdh);
MS_THROW_ERROR("SSL context creation failed");
}
void DTLSHandler::GenerateFingerprints() {
MS_TRACE();
for (auto it = DTLSHandler::fingerprints.begin(); it != DTLSHandler::fingerprints.end(); ++it) {
RTC::FingerprintHash hash = it->first;
std::string hash_str;
unsigned char binary_fingerprint[EVP_MAX_MD_SIZE];
unsigned int size = 0;
char hex_fingerprint[(EVP_MAX_MD_SIZE * 3) + 1];
const EVP_MD* hash_function;
int ret;
switch(hash) {
case RTC::FingerprintHash::SHA1:
hash_function = EVP_sha1();
hash_str = "SHA-1";
break;
case RTC::FingerprintHash::SHA224:
hash_function = EVP_sha224();
hash_str = "SHA-224";
break;
case RTC::FingerprintHash::SHA256:
hash_function = EVP_sha256();
hash_str = "SHA-256";
break;
case RTC::FingerprintHash::SHA384:
hash_function = EVP_sha384();
hash_str = "SHA-384";
break;
case RTC::FingerprintHash::SHA512:
hash_function = EVP_sha512();
hash_str = "SHA-512";
break;
default:
MS_ABORT("unknown hash");
}
ret = X509_digest(DTLSHandler::certificate, hash_function, binary_fingerprint, &size);
if (ret == 0) {
MS_ERROR("X509_digest() failed");
MS_THROW_ERROR("Fingerprints generation failed");
}
// Convert to hexadecimal format (NOTE: %.2X uses uppercase letters).
for (unsigned int i = 0; i < size; i++) {
std::sprintf(hex_fingerprint + (i * 3), "%.2X:", binary_fingerprint[i]);
}
// NOTE: The -1 removes the last ":".
hex_fingerprint[(size * 3) - 1] = '\0';
MS_DEBUG("%-7s fingerprint: %s", hash_str.c_str(), hex_fingerprint);
// Store in the map.
DTLSHandler::fingerprints[hash].assign(hex_fingerprint);
}
}
/* Instance methods. */
DTLSHandler::DTLSHandler(Listener* listener) :
listener(listener)
{
MS_TRACE();
/* Set SSL. */
this->ssl = SSL_new(DTLSHandler::sslCtx);
if (! this->ssl) {
LOG_OPENSSL_ERROR("SSL_new() failed");
goto error;
}
// Set this as custom data.
SSL_set_ex_data(this->ssl, 0, static_cast<void*>(this));
this->sslBioFromNetwork = BIO_new(BIO_s_mem());
if (! this->sslBioFromNetwork) {
LOG_OPENSSL_ERROR("BIO_new() failed");
SSL_free(this->ssl);
goto error;
}
this->sslBioToNetwork = BIO_new(BIO_s_mem());
if (! this->sslBioToNetwork) {
LOG_OPENSSL_ERROR("BIO_new() failed");
BIO_free(this->sslBioFromNetwork);
SSL_free(this->ssl);
goto error;
}
SSL_set_bio(this->ssl, this->sslBioFromNetwork, this->sslBioToNetwork);
/* Set the DTLS timer. */
this->timer = new Timer(this);
return;
error:
// NOTE: At this point SSL_set_bio() was not called so we must free BIOs as
// well.
if (this->sslBioFromNetwork)
BIO_free(this->sslBioFromNetwork);
if (this->sslBioToNetwork)
BIO_free(this->sslBioToNetwork);
if (this->ssl)
SSL_free(this->ssl);
// NOTE: If this is not catched by the caller the program will abort, but
// this should never happen.
MS_THROW_ERROR("DTLSHandler instance creation failed");
}
DTLSHandler::~DTLSHandler() {
MS_TRACE();
if (this->ssl) {
SSL_free(this->ssl);
this->ssl = nullptr;
this->sslBioFromNetwork = nullptr;
this->sslBioToNetwork = nullptr;
}
}
void DTLSHandler::Run(RTC::DTLSRole role) {
MS_TRACE();
if (this->isRunning)
return;
this->isRunning = true;
this->role = role;
switch(this->role) {
case RTC::DTLSRole::SERVER:
SSL_set_accept_state(this->ssl);
SSL_do_handshake(this->ssl);
break;
case RTC::DTLSRole::CLIENT:
SSL_set_connect_state(this->ssl);
SSL_do_handshake(this->ssl);
SendPendingOutgoingDTLSData();
SetTimeout();
break;
case RTC::DTLSRole::NONE:
MS_ABORT("no valid DTLS role given");
break;
}
}
void DTLSHandler::SetRemoteFingerprint(RTC::FingerprintHash hash, std::string& fingerprint) {
MS_TRACE();
MS_ASSERT(hash != RTC::FingerprintHash::NONE, "no fingerprint hash provided");
this->remoteFingerprintHash = hash;
this->remoteFingerprint = fingerprint;
// Upcase given fingerprint.
std::transform(this->remoteFingerprint.begin(), this->remoteFingerprint.end(), this->remoteFingerprint.begin(), ::toupper);
// The remote fingerpring may have been set after DTLS handshake was done,
// so we may need to process it now.
if (this->isHandshakeDone && ! this->isConnected) {
MS_DEBUG("handshake already done, processing it right now");
ProcessHandshake();
}
}
void DTLSHandler::Reset() {
MS_TRACE();
int ret;
this->doReset = false;
if (! this->isRunning)
return;
if (this->isCheckingStatus) {
this->doReset = true;
return;
}
MS_DEBUG("resetting DTLS status");
// Stop the DTLS timer.
this->timer->Stop();
// Send close alert to the peer.
SSL_shutdown(this->ssl);
SendPendingOutgoingDTLSData();
this->role = RTC::DTLSRole::NONE;
this->isRunning = false;
this->isHandshakeDone = false;
this->isHandshakeDoneNow = false;
this->isConnected = false;
this->doClose = false;
this->isCheckingStatus = false;
// Reset SSL status.
// NOTE: For this to properly work, SSL_shutdown() must be called before.
// NOTE: This may fail if not enough DTLS handshake data has been received.
ret = SSL_clear(this->ssl);
if (ret == 0)
LOG_OPENSSL_ERROR("SSL_clear() failed");
}
void DTLSHandler::Close() {
MS_TRACE();
if (this->isCheckingStatus) {
this->doClose = true;
return;
}
if (this->isRunning) {
// Send close alert to the peer.
SSL_shutdown(this->ssl);
SendPendingOutgoingDTLSData();
}
this->timer->Close();
delete this;
}
void DTLSHandler::ProcessDTLSData(const MS_BYTE* data, size_t len) {
MS_TRACE();
int written;
int read;
if (! this->isRunning) {
MS_ERROR("cannot process data while not running");
return;
}
// Write the received DTLS data into the sslBioFromNetwork.
written = BIO_write(this->sslBioFromNetwork, (const void*)data, (int)len);
if (written != (int)len)
MS_WARN("OpenSSL BIO_write() wrote less (%zu bytes) than given data (%zu bytes)", (size_t)written, len);
// Must call SSL_read() to process received DTLS data.
read = SSL_read(this->ssl, (void*)DTLSHandler::sslReadBuffer, MS_SSL_READ_BUFFER_SIZE);
// Send data if it's ready.
SendPendingOutgoingDTLSData();
// Check SSL status and return if it is bad/closed.
if (! CheckStatus(read))
return;
// Set/update the DTLS timeout.
SetTimeout();
// Application data received. Notify to the listener.
if (read > 0) {
if (! this->isConnected) {
MS_NOTICE("ignoring application data received while DTLS not fully connected");
return;
}
this->listener->onDTLSApplicationData(this, (MS_BYTE*)DTLSHandler::sslReadBuffer, (size_t)read);
}
}
void DTLSHandler::SendApplicationData(const MS_BYTE* data, size_t len) {
MS_TRACE();
if (! this->isConnected) {
MS_ERROR("cannot send application data while DTLS is not connected");
return;
}
if (len == 0) {
MS_DEBUG("ignoring 0 length data");
return;
}
int written;
written = SSL_write(this->ssl, (const void*)data, (int)len);
if (written < 0) {
LOG_OPENSSL_ERROR("SSL_write() failed");
CheckStatus(written);
}
else if (written != (int)len) {
MS_ERROR("OpenSSL SSL_write() wrote less (%d bytes) than given data (%zu bytes)", written, len);
}
// Send data.
SendPendingOutgoingDTLSData();
}
void DTLSHandler::Dump() {
MS_TRACE();
MS_DEBUG("[role: %s | running: %s | handshake done: %s | connected: %s]",
(this->role == RTC::DTLSRole::SERVER ? "server" : (this->role == RTC::DTLSRole::CLIENT ? "client" : "none")),
this->isRunning ? "yes" : "no",
this->isHandshakeDone ? "yes" : "no",
this->isConnected ? "yes" : "no");
}
inline
bool DTLSHandler::CheckStatus(int return_code) {
MS_TRACE();
int err;
// Set a flag to avoid certain methods to be called while in this method.
this->isCheckingStatus = true;
err = SSL_get_error(this->ssl, return_code);
switch(err) {
case SSL_ERROR_NONE:
// MS_DEBUG("SSL status: SSL_ERROR_NONE");
break;
case SSL_ERROR_SSL:
// MS_NOTICE("SSL status: SSL_ERROR_SSL");
LOG_OPENSSL_ERROR("SSL status: SSL_ERROR_SSL");
break;
case SSL_ERROR_WANT_READ:
// MS_DEBUG("SSL status: SSL_ERROR_WANT_READ");
break;
case SSL_ERROR_WANT_WRITE:
MS_DEBUG("SSL status: SSL_ERROR_WANT_WRITE");
break;
case SSL_ERROR_WANT_X509_LOOKUP:
MS_NOTICE("SSL status: SSL_ERROR_WANT_X509_LOOKUP");
break;
case SSL_ERROR_SYSCALL:
// MS_WARN("SSL status: SSL_ERROR_SYSCALL");
LOG_OPENSSL_ERROR("SSL status: SSL_ERROR_SYSCALL");
break;
case SSL_ERROR_ZERO_RETURN:
// MS_DEBUG("SSL status: SSL_ERROR_ZERO_RETURN");
break;
case SSL_ERROR_WANT_CONNECT:
MS_WARN("SSL status: SSL_ERROR_WANT_CONNECT");
break;
case SSL_ERROR_WANT_ACCEPT:
MS_WARN("SSL status: SSL_ERROR_WANT_ACCEPT");
break;
}
// Check if the handshake (or re-handshake) has been done right now.
if (this->isHandshakeDoneNow) {
this->isHandshakeDoneNow = false;
this->isHandshakeDone = true;
// Stop the timer.
this->timer->Stop();
// Process the handshake.
ProcessHandshake();
}
// 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) {
bool was_connected = this->isConnected;
this->role = RTC::DTLSRole::NONE;
this->isRunning = false;
this->isHandshakeDone = false;
this->isHandshakeDoneNow = false;
this->isConnected = false;
if (was_connected) {
MS_DEBUG("DTLS connection disconnected");
// Notify to the listener.
this->listener->onDTLSDisconnected(this);
}
else {
MS_NOTICE("DTLS connection failed");
// Notify to the listener.
this->listener->onDTLSFailed(this);
}
// Set Reset flag.
this->doReset = true;
}
// Unset the safe flag.
this->isCheckingStatus = false;
// Check reset/close flags (note that they may have been set in user callbacks).
if (this->doClose) {
Close();
return false;
}
else if (this->doReset) {
Reset();
return false;
}
return true;
}
inline
void DTLSHandler::SendPendingOutgoingDTLSData() {
MS_TRACE();
if (BIO_eof(this->sslBioToNetwork))
return;
long read;
char* data = nullptr;
read = BIO_get_mem_data(this->sslBioToNetwork, &data);
MS_DEBUG("%ld bytes of DTLS data ready to sent to the peer", read);
// NOTE: The caller MUST NOT call Reset() or Close() in this callback.
this->listener->onOutgoingDTLSData(this, (MS_BYTE*)data, (size_t)read);
// Clear the BIO buffer.
// NOTE: the (void) avoids the -Wunused-value warning.
(void)BIO_reset(this->sslBioToNetwork);
}
inline
void DTLSHandler::SetTimeout() {
MS_TRACE();
long int ret;
struct timeval dtls_timeout;
MS_8BYTES timeout_ms;
// NOTE: If ret == 0 then ignore the value in dtls_timeout.
// 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);
if (ret == 0)
return;
timeout_ms = (dtls_timeout.tv_sec * (MS_8BYTES)1000) + (dtls_timeout.tv_usec / 1000);
if (timeout_ms == 0)
return;
else if (timeout_ms < 30000) {
MS_DEBUG("DTLS timer set in %llu ms", (unsigned long long)timeout_ms);
this->timer->Start(timeout_ms);
}
// NOTE: Don't start the timer again if the timeout is greater than 30 seconds.
else {
MS_DEBUG("DTLS timeout too high (%llu ms), resetting DTLS status", (unsigned long long)timeout_ms);
Reset();
}
}
inline
void DTLSHandler::ProcessHandshake() {
MS_TRACE();
MS_ASSERT(this->isHandshakeDone, "handshake not done yet");
// If the remote fingerprint is not yet set then do nothing (this method
// will be called when the fingerprint is set).
if (this->remoteFingerprintHash == RTC::FingerprintHash::NONE) {
MS_DEBUG("remote fingerprint not yet set, waiting for it");
return;
}
// Validate the remote fingerprint.
// TODO: uncomment!!!
// if (! CheckRemoteFingerprint()) {
// // Notify to the listener.
// this->listener->onDTLSFailed(this);
// // Reset DTLS.
// Reset();
// return;
// }
this->isConnected = true;
// Notify the listener.
this->listener->onDTLSConnected(this);
// Get the negotiated SRTP profile.
RTC::SRTPProfile srtp_profile;
srtp_profile = GetNegotiatedSRTPProfile();
if (srtp_profile != RTC::SRTPProfile::NONE) {
// Extract the SRTP keys (will notify the listener with them).
ExtractSRTPKeys(srtp_profile);
}
else {
MS_NOTICE("SRTP profile not negotiated");
}
}
inline
bool DTLSHandler::CheckRemoteFingerprint() {
MS_TRACE();
MS_ASSERT(this->remoteFingerprintHash != RTC::FingerprintHash::NONE, "remote fingerprint not set");
X509* certificate;
std::string hash_str;
unsigned char binary_fingerprint[EVP_MAX_MD_SIZE];
unsigned int size = 0;
char hex_fingerprint[(EVP_MAX_MD_SIZE * 3) + 1];
const EVP_MD* hash_function;
int ret;
certificate = SSL_get_peer_certificate(this->ssl);
if (! certificate) {
MS_ERROR("no certificate was provided by the peer");
return false;
}
switch(this->remoteFingerprintHash) {
case RTC::FingerprintHash::SHA1:
hash_function = EVP_sha1();
hash_str = "SHA-1";
break;
case RTC::FingerprintHash::SHA224:
hash_function = EVP_sha224();
hash_str = "SHA-224";
break;
case RTC::FingerprintHash::SHA256:
hash_function = EVP_sha256();
hash_str = "SHA-256";
break;
case RTC::FingerprintHash::SHA384:
hash_function = EVP_sha384();
hash_str = "SHA-384";
break;
case RTC::FingerprintHash::SHA512:
hash_function = EVP_sha512();
hash_str = "SHA-512";
break;
default:
MS_ABORT("unknown hash");
}
ret = X509_digest(certificate, hash_function, binary_fingerprint, &size);
if (ret == 0) {
MS_ERROR("X509_digest() failed");
X509_free(certificate);
return false;
}
X509_free(certificate);
// Convert to hexadecimal format.
for (unsigned int i = 0; i < size; i++) {
std::sprintf(hex_fingerprint + (i * 3), "%.2X:", binary_fingerprint[i]);
}
// NOTE: The -1 removes the last ":".
hex_fingerprint[(size * 3) - 1] = '\0';
if (this->remoteFingerprint.compare(hex_fingerprint) != 0) {
MS_NOTICE("fingerprint in the remote certificate (%s) does not match the announced one (%s)", hex_fingerprint, this->remoteFingerprint.c_str());
return false;
}
MS_DEBUG("valid remote %-7s fingerprint: %s", hash_str.c_str(), hex_fingerprint);
return true;
}
inline
RTC::SRTPProfile DTLSHandler::GetNegotiatedSRTPProfile() {
MS_TRACE();
RTC::SRTPProfile negotiated_srtp_profile = RTC::SRTPProfile::NONE;
// Ensure that the SRTP profile has been negotiated.
SRTP_PROTECTION_PROFILE* ssl_srtp_profile = SSL_get_selected_srtp_profile(this->ssl);
if (! ssl_srtp_profile) {
return negotiated_srtp_profile;
}
// Get the negotiated SRTP profile.
for (auto it = DTLSHandler::srtpProfiles.begin(); it != DTLSHandler::srtpProfiles.end(); ++it) {
SrtpProfileMapEntry* profile_entry = &(*it);
if (std::strcmp(ssl_srtp_profile->name, profile_entry->name) == 0) {
MS_DEBUG("chosen SRTP profile: %s", profile_entry->name);
negotiated_srtp_profile = profile_entry->profile;
}
}
MS_ASSERT(negotiated_srtp_profile != RTC::SRTPProfile::NONE, "chosen SRTP profile is not an available one");
return negotiated_srtp_profile;
}
inline
void DTLSHandler::ExtractSRTPKeys(RTC::SRTPProfile srtp_profile) {
MS_TRACE();
MS_BYTE srtp_material[MS_SRTP_MASTER_LENGTH * 2];
MS_BYTE* srtp_local_key;
MS_BYTE* srtp_local_salt;
MS_BYTE* srtp_remote_key;
MS_BYTE* srtp_remote_salt;
MS_BYTE srtp_local_master_key[MS_SRTP_MASTER_LENGTH];
MS_BYTE srtp_remote_master_key[MS_SRTP_MASTER_LENGTH];
int ret;
ret = SSL_export_keying_material(this->ssl, srtp_material, MS_SRTP_MASTER_LENGTH * 2, "EXTRACTOR-dtls_srtp", 19, nullptr, 0, 0);
MS_ASSERT(ret != 0, "SSL_export_keying_material() failed");
switch(this->role) {
case RTC::DTLSRole::SERVER:
srtp_remote_key = srtp_material;
srtp_local_key = srtp_remote_key + MS_SRTP_MASTER_KEY_LENGTH;
srtp_remote_salt = srtp_local_key + MS_SRTP_MASTER_KEY_LENGTH;
srtp_local_salt = srtp_remote_salt + MS_SRTP_MASTER_SALT_LENGTH;
break;
case RTC::DTLSRole::CLIENT:
srtp_local_key = srtp_material;
srtp_remote_key = srtp_local_key + MS_SRTP_MASTER_KEY_LENGTH;
srtp_local_salt = srtp_remote_key + MS_SRTP_MASTER_KEY_LENGTH;
srtp_remote_salt = srtp_local_salt + MS_SRTP_MASTER_SALT_LENGTH;
break;
case RTC::DTLSRole::NONE:
MS_ABORT("no DTLS role set");
break;
}
// Create the SRTP local master key.
std::memcpy(srtp_local_master_key, srtp_local_key, MS_SRTP_MASTER_KEY_LENGTH);
std::memcpy(srtp_local_master_key + MS_SRTP_MASTER_KEY_LENGTH, srtp_local_salt, MS_SRTP_MASTER_SALT_LENGTH);
// Create the SRTP remote master key.
std::memcpy(srtp_remote_master_key, srtp_remote_key, MS_SRTP_MASTER_KEY_LENGTH);
std::memcpy(srtp_remote_master_key + MS_SRTP_MASTER_KEY_LENGTH, srtp_remote_salt, MS_SRTP_MASTER_SALT_LENGTH);
// Notify the listener with the SRTP key material.
this->listener->onSRTPKeyMaterial(this, srtp_profile, srtp_local_master_key, MS_SRTP_MASTER_LENGTH, srtp_remote_master_key, MS_SRTP_MASTER_LENGTH);
}
inline
void DTLSHandler::onSSLInfo(int where, int ret) {
MS_TRACE();
int w = where & -SSL_ST_MASK;
const char* role;
if (w & SSL_ST_CONNECT) role = "client";
else if (w & SSL_ST_ACCEPT) role = "server";
else role = "undefined";
if (where & SSL_CB_LOOP) {
MS_DEBUG("role: %s | action: %s", role, SSL_state_string_long(this->ssl));
}
else if (where & SSL_CB_ALERT) {
const char* alert_type;
switch (*SSL_alert_type_string(ret)) {
case 'W': alert_type = "warning"; break;
case 'F': alert_type = "fatal"; break;
default: alert_type = "undefined";
}
if (where & SSL_CB_READ)
MS_DEBUG("received DTLS %s alert: %s", alert_type, SSL_alert_desc_string_long(ret));
else if (where & SSL_CB_WRITE)
MS_DEBUG("sending DTLS %s alert: %s", alert_type, SSL_alert_desc_string_long(ret));
else
MS_DEBUG("DTLS %s alert: %s", alert_type, SSL_alert_desc_string_long(ret));
}
else if (where & SSL_CB_EXIT) {
if (ret == 0)
MS_NOTICE("role: %s | failed in: %s", role, SSL_state_string_long(this->ssl));
else if (ret < 0)
MS_DEBUG("role: %s | waiting for: %s", role, SSL_state_string_long(this->ssl));
}
else if (where & SSL_CB_HANDSHAKE_START) {
MS_DEBUG("DTLS handshake start");
}
else if (where & SSL_CB_HANDSHAKE_DONE) {
MS_DEBUG("DTLS handshake done");
this->isHandshakeDoneNow = true;
}
// NOTE: checking SSL_get_shutdown(this->ssl) & SSL_RECEIVED_SHUTDOWN here upon
// receipt of a close alert does not work (the flag is set after this callback).
}
inline
void DTLSHandler::onTimer(Timer* timer) {
MS_TRACE();
DTLSv1_handle_timeout(this->ssl);
SendPendingOutgoingDTLSData();
SetTimeout();
}
} // namespace RTC
#define MS_CLASS "RTC::ICEServer"
#include "RTC/ICEServer.h"
#include "Utils.h"
#include "Logger.h"
namespace RTC {
/* Instance methods. */
ICEServer::ICEServer(Listener* listener) :
listener(listener)
{
MS_TRACE();
char local_username[16];
char local_password[16];
this->localUsername = std::string(Utils::Crypto::GetRandomHexString(local_username, 16), 16);
this->localPassword = std::string(Utils::Crypto::GetRandomHexString(local_password, 32), 32);
MS_DEBUG("local username: %s | local password: %s", this->localUsername.c_str(), this->localPassword.c_str());
// TODO: TMP for testing
this->localUsername = "7D5B3AA55DC2CE83";
this->localPassword = "75C96DDDFC38D194FEDF75986CF962A2D56F3B65F1F7";
}
void ICEServer::ProcessSTUNMessage(RTC::STUNMessage* msg, RTC::TransportSource* source) {
MS_TRACE();
// Must be a Binding method.
if (msg->GetMethod() != RTC::STUNMessage::Method::Binding) {
if (msg->GetClass() == RTC::STUNMessage::Class::Request) {
MS_DEBUG("unknown method %#.3x in STUN Request => 400", (unsigned int)msg->GetMethod());
// Reply 400.
RTC::STUNMessage* response = msg->CreateErrorResponse(400);
response->Serialize();
this->listener->onOutgoingSTUNMessage(this, response, source);
delete response;
}
else {
MS_DEBUG("ignoring STUN Indication or Response with unknown method %#.3x", (unsigned int)msg->GetMethod());
}
return;
}
// Must use FINGERPRINT (optional for ICE STUN indications).
if (! msg->HasFingerprint() && msg->GetClass() != RTC::STUNMessage::Class::Indication) {
if (msg->GetClass() == RTC::STUNMessage::Class::Request) {
MS_DEBUG("STUN Binding Request without FINGERPRINT => 400");
// Reply 400.
RTC::STUNMessage* response = msg->CreateErrorResponse(400);
response->Serialize();
this->listener->onOutgoingSTUNMessage(this, response, source);
delete response;
}
else {
MS_DEBUG("ignoring STUN Binding Response without FINGERPRINT");
}
return;
}
switch(msg->GetClass()) {
case RTC::STUNMessage::Class::Request: {
// USERNAME, MESSAGE-INTEGRITY and PRIORITY are required.
if (! msg->HasMessageIntegrity() || ! msg->GetPriority() || msg->GetUsername().empty()) {
MS_DEBUG("mising required attributes in STUN Binding Request => 400");
// Reply 400.
RTC::STUNMessage* response = msg->CreateErrorResponse(400);
response->Serialize();
this->listener->onOutgoingSTUNMessage(this, response, source);
delete response;
return;
}
// Check authentication.
switch(msg->CheckAuthentication(this->localUsername, this->localPassword)) {
case RTC::STUNMessage::Authentication::OK:
break;
case RTC::STUNMessage::Authentication::Unauthorized: {
MS_DEBUG("wrong authentication in STUN Binding Request => 401");
// Reply 401.
RTC::STUNMessage* response = msg->CreateErrorResponse(401);
response->Serialize();
this->listener->onOutgoingSTUNMessage(this, response, source);
delete response;
return;
}
case RTC::STUNMessage::Authentication::BadRequest: {
MS_DEBUG("cannot check authentication in STUN Binding Request => 400");
// Reply 400.
RTC::STUNMessage* response = msg->CreateErrorResponse(400);
response->Serialize();
this->listener->onOutgoingSTUNMessage(this, response, source);
delete response;
return;
}
}
// The remote peer must be ICE controlling.
if (msg->GetIceControlled()) {
MS_NOTICE("peer indicates ICE-CONTROLLED in STUN Binding Request => 487");
// Reply 487 (Role Conflict).
RTC::STUNMessage* response = msg->CreateErrorResponse(487);
response->Serialize();
this->listener->onOutgoingSTUNMessage(this, response, source);
delete response;
return;
}
MS_DEBUG("processing STUN Binding Request with Priority %u%s", (unsigned int)msg->GetPriority(), msg->HasUseCandidate() ? " and UseCandidate" : "");
// Create a success response.
RTC::STUNMessage* response = msg->CreateSuccessResponse();
// Add XOR-MAPPED-ADDRESS.
response->SetXorMappedAddress(source->GetRemoteAddress());
// Authenticate the response.
response->Authenticate(this->localPassword);
// Send back.
response->Serialize();
this->listener->onOutgoingSTUNMessage(this, response, source);
delete response;
// Notify the listener with the valid pair.
this->listener->onICEValidPair(this, source, msg->HasUseCandidate());
break;
}
case RTC::STUNMessage::Class::Indication: {
MS_DEBUG("STUN Binding Indication processed");
break;
}
case RTC::STUNMessage::Class::SuccessResponse: {
MS_DEBUG("STUN Binding Success Response processed");
break;
}
case RTC::STUNMessage::Class::ErrorResponse: {
MS_DEBUG("STUN Binding Error Response processed");
break;
}
}
}
void ICEServer::Close() {
MS_TRACE();
delete this;
}
} // namespace RTC
#define MS_CLASS "RTC::Peer"
#include "RTC/Peer.h"
#include "RTC/DTLSRole.h"
#include "MediaSoupError.h"
#include "Logger.h"
// TMP
#include "RTC/UDPSocket.h"
#include "RTC/TCPServer.h"
#include <string>
namespace RTC {
/* Instance methods. */
Peer::Peer(Listener* listener) :
listener(listener)
{
MS_TRACE();
// TMP
this->transport = RTC::Transport::NewWebRTC(this);
// Local DTLS role.
RTC::DTLSRole local_dtls_role = RTC::DTLSRole::SERVER;
// Chrome's fingerprint.
std::string remote_fingerprint = "74:24:E1:0A:30:48:FB:F2:72:6E:2C:70:FA:96:FD:06:81:AA:F8:1F:65:2E:D4:81:3E:93:0C:0F:E1:D0:FE:19";
this->transport->SetLocalDTLSRole(local_dtls_role);
this->transport->SetRemoteDTLSFingerprint(RTC::FingerprintHash::SHA256, remote_fingerprint);
try {
RTC::UDPSocket* socket = RTC::UDPSocket::New(AF_INET);
this->transport->AddUDPSocket(socket);
MS_NOTICE("---- TEST: transport listens in IPv4 UDP '%s' : %u", socket->GetLocalIP().c_str(), socket->GetLocalPort());
}
catch (const MediaSoupError &error) {
MS_ERROR("---- TEST: error adding IPv4 UDP to transport: %s", error.what());
}
try {
RTC::TCPServer* server = RTC::TCPServer::New(AF_INET);
this->transport->AddTCPServer(server);
MS_NOTICE("---- TEST: transport listens in IPv4 TCP '%s' : %u", server->GetLocalIP().c_str(), server->GetLocalPort());
}
catch (const MediaSoupError &error) {
MS_ERROR("---- TEST: error adding IPv4 TCP to transport: %s", error.what());
}
}
Peer::~Peer() {
MS_TRACE();
}
void Peer::SendRTPPacket(RTC::RTPPacket* packet) {
MS_TRACE();
// TMP
if (this->transport->IsReadyForMedia())
this->transport->SendRTPPacket(packet);
}
void Peer::SendRTCPPacket(RTC::RTCPPacket* packet) {
MS_TRACE();
// TMP
if (this->transport->IsReadyForMedia())
this->transport->SendRTCPPacket(packet);
}
void Peer::Close() {
MS_TRACE();
// TMP
if (this->transport)
this->transport->Close();
delete this;
}
void Peer::onRTPPacket(RTC::Transport* transport, RTC::RTPPacket* packet) {
MS_TRACE();
// MS_DEBUG("RTP packet received"); // TODO: TMP
// TMP
this->listener->onRTPPacket(this, packet);
}
void Peer::onRTCPPacket(RTC::Transport* transport, RTC::RTCPPacket* packet) {
MS_TRACE();
// MS_DEBUG("RTCP packet received"); // TODO: TMP
// TMP
this->listener->onRTCPPacket(this, packet);
}
} // namespace RTC
#define MS_CLASS "RTC::RTCPPacket"
#include "RTC/RTCPPacket.h"
#include "Logger.h"
namespace RTC {
/* Static methods. */
RTCPPacket* RTCPPacket::Parse(const MS_BYTE* data, size_t len) {
MS_TRACE();
if (! RTCPPacket::IsRTCP(data, len))
return nullptr;
// TODO: Do it.
// Get the header.
CommonHeader* header = (CommonHeader*)data;
return new RTCPPacket(header, data, len);
}
/* Instance methods. */
RTCPPacket::RTCPPacket(CommonHeader* header, const MS_BYTE* raw, size_t length) :
header(header),
raw((MS_BYTE*)raw),
length(length)
{
MS_TRACE();
}
RTCPPacket::~RTCPPacket() {
MS_TRACE();
}
} // namespace RTC
#define MS_CLASS "RTC::RTPPacket"
#include "RTC/RTPPacket.h"
#include "Utils.h"
#include "Logger.h"
#include <cstring> // std::memcmp(), std::memcpy()
namespace RTC {
/* Static methods. */
RTPPacket* RTPPacket::Parse(const MS_BYTE* data, size_t len) {
MS_TRACE();
if (! RTPPacket::IsRTP(data, len))
return nullptr;
// Get the header.
Header* header = (Header*)data;
// Inspect data after the minimum header size.
size_t pos = sizeof(Header);
// Check CSRC list.
size_t csrc_list_size = 0;
if (header->csrc_count) {
csrc_list_size = header->csrc_count * sizeof(header->ssrc);
// Packet size must be >= header size + CSRC list.
if (len < pos + csrc_list_size) {
MS_DEBUG("not enough space for the announced CSRC list | packet discarded");
return nullptr;
}
pos += csrc_list_size;
}
// Check header extension.
ExtensionHeader* extensionHeader = nullptr;
size_t extension_value_size = 0;
if (header->extension) {
// The extension header is at least 4 bytes.
if (len < pos + 4) {
MS_DEBUG("not enough space for the announced extension header | packet discarded");
return nullptr;
}
extensionHeader = (ExtensionHeader*)(data + pos);
// 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.
// extension_value_size = (size_t)(Utils::Byte::Get2Bytes(data, pos + 2) * 4);
extension_value_size = (size_t)(ntohs(extensionHeader->length) * 4);
// Packet size must be >= header size + CSRC list + header extension size.
if (len < pos + 4 + extension_value_size) {
MS_DEBUG("not enough space for the announced header extension value | packet discarded");
return nullptr;
}
pos += 4 + extension_value_size;
}
// Get payload.
MS_BYTE* payload = (MS_BYTE*)data + pos;
size_t payloadLength = len - pos;
MS_BYTE payloadPadding = 0;
MS_ASSERT(len >= pos, "payload has negative size");
// Check padding field.
if (header->padding) {
// Must be at least a single payload byte.
if (payloadLength == 0) {
MS_DEBUG("padding bit is set but no space for a padding byte | packet discarded");
return nullptr;
}
payloadPadding = data[len - 1];
if (payloadPadding == 0) {
MS_DEBUG("padding byte cannot be 0 packet discarded");
return nullptr;
}
if (payloadLength < (size_t)payloadPadding) {
MS_DEBUG("number of padding octets is greater than available space for payload | packet discarded");
return nullptr;
}
payloadLength -= (size_t)payloadPadding;
}
if (payloadLength == 0)
payload = nullptr;
MS_ASSERT(len == sizeof(Header) + csrc_list_size + (extensionHeader ? 4 + extension_value_size : 0) + payloadLength + (size_t)payloadPadding, "packet's computed length does not match received length");
return new RTPPacket(header, extensionHeader, payload, payloadLength, payloadPadding, data, len);
}
/* Instance methods. */
RTPPacket::RTPPacket(Header* header, ExtensionHeader* extensionHeader, const MS_BYTE* payload, size_t payloadLength, MS_BYTE payloadPadding, const MS_BYTE* raw, size_t length) :
header(header),
extensionHeader(extensionHeader),
payload((MS_BYTE*)payload),
payloadLength(payloadLength),
payloadPadding(payloadPadding),
raw((MS_BYTE*)raw),
length(length)
{
MS_TRACE();
if (this->header->csrc_count)
this->csrcList = (MS_BYTE*)raw + sizeof(Header);
}
RTPPacket::~RTPPacket() {
MS_TRACE();
if (this->isSerialized)
delete this->raw;
}
void RTPPacket::Serialize() {
MS_TRACE();
if (this->isSerialized)
delete this->raw;
// Set this->isSerialized so the destructor will free the buffer.
this->isSerialized = true;
// Some useful variables.
size_t extension_value_size = 0;
// First calculate the total required size for the entire message.
this->length = sizeof(Header); // Minimun header.
if (this->csrcList)
this->length += this->header->csrc_count * sizeof(header->ssrc);
if (this->extensionHeader) {
extension_value_size = (size_t)(ntohs(this->extensionHeader->length) * 4);
this->length += 4 + extension_value_size;
}
this->length += this->payloadLength;
this->length += (size_t)this->payloadPadding;
// Allocate it.
this->raw = new MS_BYTE[this->length];
// Add minimun header.
std::memcpy(this->raw, this->header, sizeof(Header));
size_t pos = sizeof(Header);
// Update the header pointer.
this->header = (Header*)(this->raw);
// Add CSRC list.
if (this->csrcList) {
std::memcpy(this->raw + pos, this->csrcList, this->header->csrc_count * sizeof(header->ssrc));
// Update the pointer.
this->csrcList = this->raw + pos;
pos += this->header->csrc_count * sizeof(header->ssrc);
}
// Add extension header.
if (this->extensionHeader) {
std::memcpy(this->raw + pos, this->extensionHeader, 4 + extension_value_size);
// Update the header extension pointer.
this->extensionHeader = (ExtensionHeader*)(this->raw + pos);
pos += 4 + extension_value_size;
}
// Add payload.
if (this->payload) {
std::memcpy(this->raw + pos, this->payload, this->payloadLength);
// Update the pointer.
this->payload = this->raw + pos;
pos += this->payloadLength;
}
// Add payload padding.
if (this->payloadPadding) {
this->raw[pos + (size_t)this->payloadPadding - 1] = this->payloadPadding;
pos += (size_t)this->payloadPadding;
}
MS_ASSERT(pos == this->length, "pos != this->length");
}
void RTPPacket::Dump() {
MS_TRACE();
if (! Logger::HasDebugLevel())
return;
MS_DEBUG("[RTPPacket]");
MS_DEBUG("- Padding: %s", this->header->padding ? "true" : "false");
MS_DEBUG("- Extension: %s", HasExtensionHeader() ? "true" : "false");
if (HasExtensionHeader()) {
MS_DEBUG("- Extension ID: %u", (unsigned int)GetExtensionHeaderId());
MS_DEBUG("- Extension length: %zu bytes", GetExtensionHeaderLength());
}
MS_DEBUG("- CSRC count: %u", (unsigned int)this->header->csrc_count); // TODO: method?
MS_DEBUG("- Marker: %s", HasMarker() ? "true" : "false");
MS_DEBUG("- Payload type: %u", (unsigned int)GetPayloadType());
MS_DEBUG("- Sequence number: %u", (unsigned int)GetSequenceNumber());
MS_DEBUG("- Timestamp: %lu", (unsigned long)GetTimestamp());
MS_DEBUG("- SSRC: %lu", (unsigned long)GetSSRC());
MS_DEBUG("- Payload size: %zu bytes", GetPayloadLength());
MS_DEBUG("[/RTPPacket]");
}
} // namespace RTC
#define MS_CLASS "RTC::Room"
#include "RTC/Room.h"
#include "MediaSoupError.h"
#include "Logger.h"
// TMP
#define NUM_PEERS 4
#define PAYLOAD_TYPE_AUDIO 111 // OPUS
#define PAYLOAD_TYPE_VIDEO 100 // VP8
#define SSRC_AUDIO_BASE 100000
#define SSRC_VIDEO_BASE 200000
namespace RTC {
/* Instance methods. */
Room::Room() {
MS_TRACE();
// TMP
for(int i = 1; i <= NUM_PEERS; i++) {
RTC::Peer* peer = new RTC::Peer(this);
int* data = new int(i);
peer->SetUserData((void*)data);
this->peers.push_back(peer);
}
}
Room::~Room() {
MS_TRACE();
}
void Room::Close() {
MS_TRACE();
for (auto peer : this->peers)
peer->Close();
delete this;
}
void Room::onRTPPacket(RTC::Peer* peer, RTC::RTPPacket* packet) {
MS_TRACE();
int peer_id = *(int*)peer->GetUserData();
MS_BYTE payload_type = packet->GetPayloadType();
MS_4BYTES original_ssrc = packet->GetSSRC();
MS_DEBUG("valid RTP packet received from Peer %d [ssrc: %llu | payload: %hu]",
peer_id, (unsigned long long)packet->GetSSRC(), (unsigned short)packet->GetPayloadType());
switch(payload_type) {
case PAYLOAD_TYPE_AUDIO:
case PAYLOAD_TYPE_VIDEO:
break;
default:
MS_ERROR("payload is not OPUS %d nor VP8 %d, packet ignored", PAYLOAD_TYPE_AUDIO, PAYLOAD_TYPE_VIDEO);
return;
}
// Deliver to all the peers.
// TODO: but this one? yes (TODO)
for (auto dst_peer : this->peers) {
// if (dst_peer == peer)
// continue;
int dst_peer_id = *(int*)dst_peer->GetUserData();
switch(payload_type) {
case PAYLOAD_TYPE_AUDIO:
packet->SetSSRC((MS_4BYTES)(SSRC_AUDIO_BASE + (peer_id * 10) + dst_peer_id));
break;
case PAYLOAD_TYPE_VIDEO:
packet->SetSSRC((MS_4BYTES)(SSRC_VIDEO_BASE + (peer_id * 10) + dst_peer_id));
break;
default:
MS_ABORT("no puede ser!!!");
return;
}
MS_DEBUG("sending RTP packet to Peer %d [ssrc: %llu | payload: %hu | size: %zu]",
dst_peer_id, (unsigned long long)packet->GetSSRC(), (unsigned short)packet->GetPayloadType(), packet->GetLength());
dst_peer->SendRTPPacket(packet);
// NOTE: recover the previous SSRC since other peers are going to
// send this same RTPPacket!
packet->SetSSRC(original_ssrc);
}
}
void Room::onRTCPPacket(RTC::Peer* peer, RTC::RTCPPacket* packet) {
MS_TRACE();
// TMP
// Ignore RTCP packets.
// for (auto dst_peer : this->peers) {
// dst_peer->SendRTCPPacket(packet);
// }
}
} // namespace RTC
#define MS_CLASS "RTC::SRTPSession"
#include "RTC/SRTPSession.h"
#include "MediaSoupError.h"
#include "Logger.h"
#include <cstring> // std::memset(), std::memcpy()
#include <srtp/srtp_priv.h> // TODO: This allows data->stream->ssrc, but it is not public. Wait ofr libsrtp new API.
#define MS_ENCRYPT_BUFFER_SIZE 65536
namespace RTC {
/* Static variables. */
__thread MS_BYTE SRTPSession::encryptBuffer[MS_ENCRYPT_BUFFER_SIZE];
/* Static methods. */
void SRTPSession::ClassInit() {
/* Set libsrtp event handler. */
err_status_t err;
err = srtp_install_event_handler((srtp_event_handler_func_t*)onSRTPEvent);
if (LibSRTP::IsError(err)) {
MS_THROW_ERROR("srtp_install_event_handler() failed: %s", LibSRTP::GetErrorString(err));
}
}
void SRTPSession::onSRTPEvent(srtp_event_data_t* data) {
MS_TRACE();
const char* event_desc = "";
switch(data->event) {
case event_ssrc_collision:
event_desc = "collision occurred";
break;
case event_key_soft_limit:
event_desc = "stream reached the soft key usage limit and will expire soon";
break;
case event_key_hard_limit:
event_desc = "stream reached the hard key usage limit and has expired";
break;
case event_packet_index_limit:
event_desc = "stream reached the hard packet limit (2^48 packets)";
break;
}
MS_NOTICE("SSRC %llu: %s", (unsigned long long)data->stream->ssrc, event_desc);
}
/* Instance methods. */
SRTPSession::SRTPSession(Type type, RTC::SRTPProfile profile, MS_BYTE* key, size_t key_len) {
MS_TRACE();
err_status_t err;
srtp_policy_t policy;
// Set all policy fields to 0.
std::memset(&policy, 0, sizeof(srtp_policy_t));
switch (profile) {
case RTC::SRTPProfile::AES_CM_128_HMAC_SHA1_80:
crypto_policy_set_aes_cm_128_hmac_sha1_80(&policy.rtp);
crypto_policy_set_aes_cm_128_hmac_sha1_80(&policy.rtcp);
break;
case RTC::SRTPProfile::AES_CM_128_HMAC_SHA1_32:
crypto_policy_set_aes_cm_128_hmac_sha1_32(&policy.rtp);
crypto_policy_set_aes_cm_128_hmac_sha1_80(&policy.rtcp); // NOTE: Must be 80 for RTCP!.
break;
default:
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");
switch(type) {
case Type::INBOUND:
policy.ssrc.type = ssrc_any_inbound;
break;
case Type::OUTBOUND:
policy.ssrc.type = ssrc_any_outbound;
break;
default:
MS_ABORT("unknown SRTPSession::Type");
}
policy.ssrc.value = 0;
policy.key = key;
policy.allow_repeat_tx = 0;
policy.window_size = 1024;
policy.next = nullptr; // No more policies.
// Set the SRTP session.
err = srtp_create(&this->session, &policy);
if (LibSRTP::IsError(err)) {
MS_THROW_ERROR("srtp_create() failed: %s", LibSRTP::GetErrorString(err));
}
}
SRTPSession::~SRTPSession() {
MS_TRACE();
if (this->session) {
err_status_t err;
err = srtp_dealloc(this->session);
if (LibSRTP::IsError(err)) {
MS_ABORT("srtp_dealloc() failed: %s", LibSRTP::GetErrorString(err));
}
}
}
// TODO: It must not memcpy it but instead the provided packet must already be
// allocated into a buffer.
bool SRTPSession::EncryptRTP(const MS_BYTE** data, size_t* len) {
MS_TRACE();
// Ensure that the resulting SRTP packet fits into the encrypt buffer.
if (*len + SRTP_MAX_TRAILER_LEN > MS_ENCRYPT_BUFFER_SIZE) {
MS_WARN("cannot encrypt RTP packet, size too big (%zu bytes)", *len);
this->lastError = err_status_fail;
return false;
}
std::memcpy(SRTPSession::encryptBuffer, *data, *len);
this->lastError = srtp_protect(this->session, (void*)SRTPSession::encryptBuffer, (int*)len);
if (LibSRTP::IsError(this->lastError)) {
MS_DEBUG("srtp_protect() failed: %s", LibSRTP::GetErrorString(this->lastError));
return false;
}
// Update the given data pointer.
*data = (const MS_BYTE*)SRTPSession::encryptBuffer;
return true;
}
bool SRTPSession::DecryptSRTP(const MS_BYTE* data, size_t* len) {
MS_TRACE();
this->lastError = srtp_unprotect(this->session, (void*)data, (int*)len);
if (LibSRTP::IsError(this->lastError)) {
MS_DEBUG("srtp_unprotect() failed: %s", LibSRTP::GetErrorString(this->lastError));
return false;
}
return true;
}
bool SRTPSession::EncryptRTCP(const MS_BYTE** data, size_t* len) {
MS_TRACE();
// Ensure that the resulting SRTCP packet fits into the encrypt buffer.
if (*len + SRTP_MAX_TRAILER_LEN > MS_ENCRYPT_BUFFER_SIZE) {
MS_WARN("cannot encrypt RTCP packet, size too big (%zu bytes)", *len);
this->lastError = err_status_fail;
return false;
}
std::memcpy(SRTPSession::encryptBuffer, *data, *len);
this->lastError = srtp_protect_rtcp(this->session, (void*)SRTPSession::encryptBuffer, (int*)len);
if (LibSRTP::IsError(this->lastError)) {
MS_DEBUG("srtp_protect_rtcp() failed: %s", LibSRTP::GetErrorString(this->lastError));
return false;
}
// Update the given data pointer.
*data = (const MS_BYTE*)SRTPSession::encryptBuffer;
return true;
}
bool SRTPSession::DecryptSRTCP(const MS_BYTE* data, size_t* len) {
MS_TRACE();
this->lastError = srtp_unprotect_rtcp(this->session, (void*)data, (int*)len);
if (LibSRTP::IsError(this->lastError)) {
MS_DEBUG("srtp_unprotect_rtcp() failed: %s", LibSRTP::GetErrorString(this->lastError));
return false;
}
return true;
}
void SRTPSession::Close() {
MS_TRACE();
delete this;
}
} // namespace RTC
#define MS_CLASS "RTC::STUNMessage"
#include "RTC/STUNMessage.h"
#include "Utils.h"
#include "Logger.h"
#include <cstdio> // std::snprintf()
#include <cstring> // std::memcmp(), std::memcpy()
namespace RTC {
/* Static variables. */
const MS_BYTE STUNMessage::magicCookie[] = {0x21, 0x12, 0xA4, 0x42};
/* Static methods. */
STUNMessage* STUNMessage::Parse(const MS_BYTE* data, size_t len) {
MS_TRACE();
if (! STUNMessage::IsSTUN(data, len))
return nullptr;
/*
The message type field is decomposed further into the following
structure:
0 1
2 3 4 5 6 7 8 9 0 1 2 3 4 5
+--+--+-+-+-+-+-+-+-+-+-+-+-+-+
|M |M |M|M|M|C|M|M|M|C|M|M|M|M|
|11|10|9|8|7|1|6|5|4|0|3|2|1|0|
+--+--+-+-+-+-+-+-+-+-+-+-+-+-+
Figure 3: Format of STUN Message Type Field
Here the bits in the message type field are shown as most significant
(M11) through least significant (M0). M11 through M0 represent a 12-
bit encoding of the method. C1 and C0 represent a 2-bit encoding of
the class.
*/
// Get type field.
MS_2BYTES msg_type = Utils::Byte::Get2Bytes(data, 0);
// Get length field.
MS_2BYTES msg_length = Utils::Byte::Get2Bytes(data, 2);
// 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)) {
MS_DEBUG("length field + 20 does not match total size (or it is not multiple of 4 bytes) | message discarded");
return nullptr;
}
// Get STUN method.
MS_2BYTES msg_method = (msg_type & 0x000f) | ((msg_type & 0x00e0)>>1) | ((msg_type & 0x3E00)>>2);
// Get STUN class.
MS_2BYTES msg_class = ((data[0] & 0x01) << 1) | ((data[1] & 0x10) >> 4);
// 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);
/*
STUN Attributes
After the STUN header are zero or more attributes. Each attribute
MUST be TLV encoded, with a 16-bit type, 16-bit length, and value.
Each STUN attribute MUST end on a 32-bit boundary. As mentioned
above, all fields in an attribute are transmitted most significant
bit first.
0 1 2 3
0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| Type | Length |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| Value (variable) ....
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
*/
// Start looking for attributes after STUN header (Byte #20).
size_t pos = 20;
// Flags (positions) for special MESSAGE-INTEGRITY and FINGERPRINT attributes.
bool has_message_integrity = false;
bool has_fingerprint = false;
size_t fingerprint_attr_pos; // Will point to the beginning of the attribute.
MS_4BYTES fingerprint; // Holds the value of the FINGERPRINT attribute.
// Ensure there are at least 4 remaining bytes (attribute with 0 length).
while (pos + 4 <= len) {
// Get the attribute type.
Attribute attr_type = (Attribute)Utils::Byte::Get2Bytes(data, pos);
// Get the attribute length.
MS_2BYTES attr_length = Utils::Byte::Get2Bytes(data, pos + 2);
// Ensure the attribute length is not greater than the remaining size.
if ((pos + 4 + attr_length) > len) {
MS_DEBUG("the attribute length exceeds the remaining size | message discarded");
delete msg;
return nullptr;
}
// FINGERPRINT must be the last attribute.
if (has_fingerprint) {
MS_DEBUG("attribute after FINGERPRINT is not allowed | message discarded");
delete msg;
return nullptr;
}
// After a MESSAGE-INTEGRITY attribute just FINGERPRINT is allowed.
if (has_message_integrity && attr_type != Attribute::Fingerprint) {
MS_DEBUG("attribute after MESSAGE_INTEGRITY other than FINGERPRINT is not allowed | message discarded");
delete msg;
return nullptr;
}
const MS_BYTE* attr_value_pos = data + pos + 4;
switch(attr_type) {
case Attribute::Username:
msg->SetUsername((const char*)attr_value_pos, (size_t)attr_length);
break;
case Attribute::Priority:
msg->SetPriority(Utils::Byte::Get4Bytes(attr_value_pos, 0));
break;
case Attribute::IceControlling:
msg->SetIceControlling(Utils::Byte::Get8Bytes(attr_value_pos, 0));
break;
case Attribute::IceControlled:
msg->SetIceControlled(Utils::Byte::Get8Bytes(attr_value_pos, 0));
break;
case Attribute::UseCandidate:
msg->SetUseCandidate();
break;
case Attribute::MessageIntegrity:
has_message_integrity = true;
msg->SetMessageIntegrity(attr_value_pos);
break;
case Attribute::Fingerprint:
has_fingerprint = true;
fingerprint_attr_pos = pos;
fingerprint = Utils::Byte::Get4Bytes(attr_value_pos, 0);
msg->SetFingerprint();
break;
case Attribute::ErrorCode: {
MS_BYTE error_class = Utils::Byte::Get1Byte(attr_value_pos, 2);
MS_BYTE error_number = Utils::Byte::Get1Byte(attr_value_pos, 3);
MS_2BYTES error_code = (MS_2BYTES)(error_class * 100 + error_number);
msg->SetErrorCode(error_code);
break;
}
default:
break;
}
// Set next attribute position.
pos = (size_t)Utils::Byte::PadTo4Bytes((MS_2BYTES)(pos + 4 + attr_length));
}
// Ensure current position matches the total length.
if (pos != len) {
MS_DEBUG("computed message size does not match total size | message discarded");
delete msg;
return nullptr;
}
// If it has FINGERPRINT attribute then verify it.
if (has_fingerprint) {
// Compute the CRC32 of the received message up to (but excluding) the
// FINGERPRINT attribute and XOR it with 0x5354554e.
MS_4BYTES computed_fingerprint = Utils::Crypto::CRC32(data, fingerprint_attr_pos) ^ 0x5354554e;
// Compare with the FINGERPRINT value in the message.
if (fingerprint != computed_fingerprint) {
MS_DEBUG("computed FINGERPRINT value does not match the value in the message | message discarded");
delete msg;
return nullptr;
}
}
return msg;
}
/* Instance methods. */
STUNMessage::STUNMessage(Class klass, Method method, const MS_BYTE* transactionId, const MS_BYTE* raw, size_t length) :
klass(klass),
method(method),
transactionId(transactionId),
raw((MS_BYTE*)raw),
length(length)
{
MS_TRACE();
}
STUNMessage::~STUNMessage() {
MS_TRACE();
if (this->isSerialized)
delete this->raw;
}
STUNMessage::Authentication STUNMessage::CheckAuthentication(const std::string &local_username, const std::string &local_password) {
MS_TRACE();
switch(this->klass) {
case Class::Request:
case Class::Indication: {
// Both USERNAME and MESSAGE-INTEGRITY must be present.
if (! this->messageIntegrity || this->username.empty())
return Authentication::BadRequest;
// Check that USERNAME attribute begins with our local username plus ":".
size_t local_username_len = local_username.length();
if (this->username.length() <= local_username_len ||
this->username.at(local_username_len) != ':' ||
(this->username.compare(0, local_username_len, local_username) != 0))
return Authentication::Unauthorized;
break;
}
// This method cannot check authentication in received responses (as we
// are ICE-Lite and don't generate requests).
case Class::SuccessResponse:
case Class::ErrorResponse: {
MS_ERROR("cannot check authentication for a STUN response");
return Authentication::BadRequest;
}
}
// If there is FINGERPRINT it must be discarded for MESSAGE-INTEGRITY calculation,
// so the header length field must be modified (and later restored).
if (this->hasFingerprint)
// Set the length: full length - header length (20) - FINGERPRINT length (8).
Utils::Byte::Set2Bytes(this->raw, 2, (MS_2BYTES)(this->length - 20 - 8));
// Calculate the HMAC-SHA1 of the message according to MESSAGE-INTEGRITY rules.
const MS_BYTE* computed_message_integrity = Utils::Crypto::HMAC_SHA1(local_password, this->raw, (this->messageIntegrity - 4) - this->raw);
Authentication result;
// Compare the computed HMAC-SHA1 with the MESSAGE-INTEGRITY in the message.
if (std::memcmp(this->messageIntegrity, computed_message_integrity, 20) == 0)
result = Authentication::OK;
else
result = Authentication::Unauthorized;
// Restore the header length field.
if (this->hasFingerprint)
Utils::Byte::Set2Bytes(this->raw, 2, (MS_2BYTES)(this->length - 20));
return result;
}
STUNMessage* STUNMessage::CreateSuccessResponse() {
MS_TRACE();
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);
}
STUNMessage* STUNMessage::CreateErrorResponse(MS_2BYTES errorCode) {
MS_TRACE();
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);
response->SetErrorCode(errorCode);
return response;
}
void STUNMessage::Authenticate(const std::string &password) {
// Just for Request, Indication and SuccessResponse messages.
if (this->klass == Class::ErrorResponse) {
MS_ERROR("cannot set password for ErrorResponse messages");
return;
}
this->password = password;
}
void STUNMessage::Serialize() {
MS_TRACE();
if (this->isSerialized)
delete this->raw;
// Set this->isSerialized so the destructor will free the buffer.
this->isSerialized = true;
// Some useful variables.
MS_2BYTES username_padded_len = 0;
MS_2BYTES xor_mapped_address_padded_len = 0;
bool add_xor_mapped_address = (this->xorMappedAddress && this->method == STUNMessage::Method::Binding && this->klass == Class::SuccessResponse);
bool add_error_code = (this->errorCode && this->klass == Class::ErrorResponse);
bool add_message_integrity = (this->klass != Class::ErrorResponse && ! this->password.empty());
bool add_fingerprint = true; // Do always.
// First calculate the total required size for the entire message.
this->length = 20; // Header.
if (! this->username.empty()) {
username_padded_len = Utils::Byte::PadTo4Bytes((MS_2BYTES)this->username.length());
this->length += 4 + username_padded_len;
}
if (this->priority)
this->length += 4 + 4;
if (this->iceControlling)
this->length += 4 + 8;
if (this->iceControlled)
this->length += 4 + 8;
if (this->hasUseCandidate)
this->length += 4;
if (add_xor_mapped_address) {
switch(this->xorMappedAddress->sa_family) {
case AF_INET:
xor_mapped_address_padded_len = 8;
this->length += 4 + 8;
break;
case AF_INET6:
xor_mapped_address_padded_len = 20;
this->length += 4 + 20;
break;
default:
MS_ERROR("invalid inet family in XOR-MAPPED-ADDRESS attribute");
add_xor_mapped_address = false;
break;
}
}
if (add_error_code)
this->length += 4 + 4;
if (add_message_integrity)
this->length += 4 + 20;
if (add_fingerprint)
this->length += 4 + 4;
// Allocate it.
this->raw = new MS_BYTE[this->length];
// Merge class and method fields into type.
MS_2BYTES type_field = ((MS_2BYTES)this->method & 0x0f80) << 2;
type_field |= ((MS_2BYTES)this->method & 0x0070) << 1;
type_field |= ((MS_2BYTES)this->method & 0x000f);
type_field |= ((MS_2BYTES)this->klass & 0x02) << 7;
type_field |= ((MS_2BYTES)this->klass & 0x01) << 4;
// Set type field.
Utils::Byte::Set2Bytes(this->raw, 0, type_field);
// Set length field.
Utils::Byte::Set2Bytes(this->raw, 2, (MS_2BYTES)this->length - 20);
// Set magic cookie.
std::memcpy(this->raw + 4, STUNMessage::magicCookie, 4);
// Set TransactionId field.
std::memcpy(this->raw + 8, this->transactionId, 12);
// Update the transaction ID pointer.
this->transactionId = this->raw + 8;
// Add atributes.
size_t pos = 20;
// Add USERNAME.
if (username_padded_len) {
Utils::Byte::Set2Bytes(this->raw, pos, (MS_2BYTES)Attribute::Username);
Utils::Byte::Set2Bytes(this->raw, pos + 2, (MS_2BYTES)this->username.length());
std::memcpy(this->raw + pos + 4, this->username.c_str(), this->username.length());
pos += 4 + username_padded_len;
}
// Add PRIORITY.
if (this->priority) {
Utils::Byte::Set2Bytes(this->raw, pos, (MS_2BYTES)Attribute::Priority);
Utils::Byte::Set2Bytes(this->raw, pos + 2, 4);
Utils::Byte::Set4Bytes(this->raw, pos + 4, this->priority);
pos += 4 + 4;
}
// Add ICE-CONTROLLING.
if (this->iceControlling) {
Utils::Byte::Set2Bytes(this->raw, pos, (MS_2BYTES)Attribute::IceControlling);
Utils::Byte::Set2Bytes(this->raw, pos + 2, 8);
Utils::Byte::Set8Bytes(this->raw, pos + 4, this->iceControlling);
pos += 4 + 8;
}
// Add ICE-CONTROLLED.
if (this->iceControlled) {
Utils::Byte::Set2Bytes(this->raw, pos, (MS_2BYTES)Attribute::IceControlled);
Utils::Byte::Set2Bytes(this->raw, pos + 2, 8);
Utils::Byte::Set8Bytes(this->raw, pos + 4, this->iceControlled);
pos += 4 + 8;
}
// Add USE-CANDIDATE.
if (this->hasUseCandidate) {
Utils::Byte::Set2Bytes(this->raw, pos, (MS_2BYTES)Attribute::UseCandidate);
Utils::Byte::Set2Bytes(this->raw, pos + 2, 0);
pos += 4;
}
// Add XOR-MAPPED-ADDRESS
if (add_xor_mapped_address) {
Utils::Byte::Set2Bytes(this->raw, pos, (MS_2BYTES)Attribute::XorMappedAddress);
Utils::Byte::Set2Bytes(this->raw, pos + 2, xor_mapped_address_padded_len);
MS_BYTE* attr_value = this->raw + pos + 4;
switch(this->xorMappedAddress->sa_family) {
case AF_INET: {
// Set first byte to 0.
attr_value[0] = 0;
// Set inet family.
attr_value[1] = 0x01;
// Set port and XOR it.
std::memcpy(attr_value + 2, &((const sockaddr_in*)(this->xorMappedAddress))->sin_port, 2);
attr_value[2] ^= STUNMessage::magicCookie[0];
attr_value[3] ^= STUNMessage::magicCookie[1];
// Set address and XOR it.
std::memcpy(attr_value + 4, &((const sockaddr_in*)this->xorMappedAddress)->sin_addr.s_addr, 4);
attr_value[4] ^= STUNMessage::magicCookie[0];
attr_value[5] ^= STUNMessage::magicCookie[1];
attr_value[6] ^= STUNMessage::magicCookie[2];
attr_value[7] ^= STUNMessage::magicCookie[3];
pos += 4 + 8;
break;
}
case AF_INET6: {
// Set first byte to 0.
attr_value[0] = 0;
// Set inet family.
attr_value[1] = 0x02;
// Set port and XOR it.
std::memcpy(attr_value + 2, &((const sockaddr_in6*)(this->xorMappedAddress))->sin6_port, 2);
attr_value[2] ^= STUNMessage::magicCookie[0];
attr_value[3] ^= STUNMessage::magicCookie[1];
// Set address and XOR it.
std::memcpy(attr_value + 4, &((const sockaddr_in6*)this->xorMappedAddress)->sin6_addr.s6_addr, 16);
attr_value[4] ^= STUNMessage::magicCookie[0];
attr_value[5] ^= STUNMessage::magicCookie[1];
attr_value[6] ^= STUNMessage::magicCookie[2];
attr_value[7] ^= STUNMessage::magicCookie[3];
attr_value[8] ^= this->transactionId[0];
attr_value[9] ^= this->transactionId[1];
attr_value[10] ^= this->transactionId[2];
attr_value[11] ^= this->transactionId[3];
attr_value[12] ^= this->transactionId[4];
attr_value[13] ^= this->transactionId[5];
attr_value[14] ^= this->transactionId[6];
attr_value[15] ^= this->transactionId[7];
attr_value[16] ^= this->transactionId[8];
attr_value[17] ^= this->transactionId[9];
attr_value[18] ^= this->transactionId[10];
attr_value[19] ^= this->transactionId[11];
pos += 4 + 20;
break;
}
}
}
// Add ERROR-CODE.
if (add_error_code) {
Utils::Byte::Set2Bytes(this->raw, pos, (MS_2BYTES)Attribute::ErrorCode);
Utils::Byte::Set2Bytes(this->raw, pos + 2, 4);
MS_BYTE code_class = (MS_BYTE)(this->errorCode / 100);
MS_BYTE code_number = (MS_BYTE)this->errorCode - (code_class * 100);
Utils::Byte::Set2Bytes(this->raw, pos + 4, 0);
Utils::Byte::Set1Byte(this->raw, pos + 6, code_class);
Utils::Byte::Set1Byte(this->raw, pos + 7, code_number);
pos += 4 + 4;
}
// Add MESSAGE-INTEGRITY.
if (add_message_integrity) {
// Ignore FINGERPRINT.
if (add_fingerprint)
Utils::Byte::Set2Bytes(this->raw, 2, (MS_2BYTES)(this->length - 20 - 8));
// Calculate the HMAC-SHA1 of the message according to MESSAGE-INTEGRITY rules.
const MS_BYTE* computed_message_integrity = Utils::Crypto::HMAC_SHA1(this->password, this->raw, pos);
Utils::Byte::Set2Bytes(this->raw, pos, (MS_2BYTES)Attribute::MessageIntegrity);
Utils::Byte::Set2Bytes(this->raw, pos + 2, 20);
std::memcpy(this->raw + pos + 4, computed_message_integrity, 20);
// Update the pointer.
this->messageIntegrity = this->raw + pos + 4;
pos += 4 + 20;
// Restore length field.
if (add_fingerprint)
Utils::Byte::Set2Bytes(this->raw, 2, (MS_2BYTES)(this->length - 20));
}
else {
// Unset the pointer (if it was set).
this->messageIntegrity = nullptr;
}
// Add FINGERPRINT.
if (add_fingerprint) {
// Compute the CRC32 of the message up to (but excluding) the FINGERPRINT
// attribute and XOR it with 0x5354554e.
MS_4BYTES computed_fingerprint = Utils::Crypto::CRC32(this->raw, pos) ^ 0x5354554e;
Utils::Byte::Set2Bytes(this->raw, pos, (MS_2BYTES)Attribute::Fingerprint);
Utils::Byte::Set2Bytes(this->raw, pos + 2, 4);
Utils::Byte::Set4Bytes(this->raw, pos + 4, computed_fingerprint);
pos += 4 + 4;
// Set flag.
this->hasFingerprint = true;
}
else {
this->hasFingerprint = false;
}
MS_ASSERT(pos == this->length, "pos != this->length");
}
void STUNMessage::Dump() {
MS_TRACE();
if (! Logger::HasDebugLevel())
return;
MS_DEBUG("[STUNMessage]");
std::string klass;
switch(this->klass) {
case Class::Request: klass = "Request"; break;
case Class::Indication: klass = "Indication"; break;
case Class::SuccessResponse: klass = "SuccessResponse"; break;
case Class::ErrorResponse: klass = "ErrorResponse"; break;
}
if (this->method == Method::Binding)
MS_DEBUG("- Binding %s", klass.c_str());
else
// This prints the unknown method number. Example: TURN Allocate => 0x003.
MS_DEBUG("- %s with unknown method %#.3x", klass.c_str(), (unsigned int)this->method);
MS_DEBUG("- Length (with header): %zu bytes", this->length);
char transaction_id[25];
for(int i=0; i<12; i++) {
// NOTE: n must be 3 because snprintf adds a \0 after printed chars.
std::snprintf(transaction_id+(i*2), 3, "%.2x", this->transactionId[i]);
}
MS_DEBUG("- TransactionId: %s", transaction_id);
if (this->errorCode)
MS_DEBUG("- ErrorCode: %u", (unsigned int)this->errorCode);
if (! this->username.empty())
MS_DEBUG("- Username: %s", this->username.c_str());
if (this->priority)
MS_DEBUG("- Priority: %llu", (unsigned long long)this->priority);
if (this->iceControlling)
MS_DEBUG("- IceControlling: %llu", (unsigned long long)this->iceControlling);
if (this->iceControlled)
MS_DEBUG("- IceControlled: %llu", (unsigned long long)this->iceControlled);
if (this->hasUseCandidate)
MS_DEBUG("- has UseCandidate");
if (this->xorMappedAddress) {
int family;
MS_PORT port;
std::string ip;
Utils::IP::GetAddressInfo(this->xorMappedAddress, &family, ip, &port);
MS_DEBUG("- XorMappedAddress: %s : %u", ip.c_str(), (unsigned int)port);
}
if (this->messageIntegrity) {
char message_integrity[41];
for(int i=0; i<20; i++) {
std::snprintf(message_integrity+(i*2), 3, "%.2x", this->messageIntegrity[i]);
}
MS_DEBUG("- MessageIntegrity: %s", message_integrity);
}
if (this->hasFingerprint)
MS_DEBUG("- has Fingerprint");
MS_DEBUG("[/STUNMessage]");
}
} // namespace RTC
#define MS_CLASS "RTC::Stream"
#include "RTC/Stream.h"
#include "Logger.h"
namespace RTC {
/* Instance methods. */
Stream::Stream() {
MS_TRACE();
}
Stream::~Stream() {
MS_TRACE();
}
void Stream::Close() {
MS_TRACE();
delete this;
}
} // namespace RTC
#define MS_CLASS "RTC::TCPConnection"
#include "RTC/TCPConnection.h"
#include "RTC/STUNMessage.h"
#include "RTC/DTLSHandler.h"
#include "RTC/RTPPacket.h"
#include "RTC/RTCPPacket.h"
#include "Utils.h"
#include "Logger.h"
#include <cstring> // std::memmove()
namespace RTC {
/* Instance methods. */
TCPConnection::TCPConnection(Reader* reader, size_t bufferSize) :
::TCPConnection(bufferSize),
reader(reader)
{
MS_TRACE();
}
TCPConnection::~TCPConnection() {
MS_TRACE();
}
void TCPConnection::userOnTCPConnectionRead(const MS_BYTE* data, size_t len) {
MS_TRACE();
MS_DEBUG("%zu bytes received [local: %s : %u | remote: %s : %u]", len,
GetLocalIP().c_str(), (unsigned int)GetLocalPort(), GetPeerIP().c_str(), (unsigned int)GetPeerPort());
/*
* Framing RFC 4571
*
* 0 1 2 3
* 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
* ---------------------------------------------------------------
* | LENGTH | STUN / DTLS / RTP / RTCP |
* ---------------------------------------------------------------
*
* A 16-bit unsigned integer LENGTH field, coded in network byte order
* (big-endian), begins the frame. If LENGTH is non-zero, an RTP or
* RTCP packet follows the LENGTH field. The value coded in the LENGTH
* field MUST equal the number of octets in the RTP or RTCP packet.
* Zero is a valid value for LENGTH, and it codes the null packet.
*/
// Be ready to parse more than a single frame in a single TCP chunk.
while(true) {
size_t data_len = this->bufferDataLen - this->frameStart;
size_t packet_len;
if (data_len >= 2)
packet_len = (size_t)Utils::Byte::Get2Bytes(this->buffer + this->frameStart, 0);
// We have packet_len bytes.
if (data_len >= 2 && data_len >= 2 + packet_len) {
const MS_BYTE* packet = this->buffer + this->frameStart + 2;
// Ignore if zero-length.
if (packet_len == 0) {
MS_DEBUG("ignoring 0 length received frame");
}
// Check if it's STUN.
else if (STUNMessage::IsSTUN(packet, packet_len)) {
this->reader->onSTUNDataRecv(this, packet, packet_len);
}
// Check if it's RTCP.
else if (RTCPPacket::IsRTCP(packet, packet_len)) {
this->reader->onRTCPDataRecv(this, packet, packet_len);
}
// Check if it's RTP.
else if (RTPPacket::IsRTP(packet, packet_len)) {
this->reader->onRTPDataRecv(this, packet, packet_len);
}
// Check if it's DTLS.
else if (DTLSHandler::IsDTLS(packet, packet_len)) {
this->reader->onDTLSDataRecv(this, packet, packet_len);
}
else {
MS_DEBUG("packet of unknown type received, closing the connection");
// Close the connection.
Close();
// Exit the parsing loop.
break;
}
// If there is no more space available in the buffer and that is because
// the latest parsed frame filled it, then empty the full buffer.
if ((this->frameStart + 2 + packet_len) == this->bufferSize) {
MS_DEBUG("no more space in the buffer, emptying the buffer data");
this->frameStart = 0;
this->bufferDataLen = 0;
}
// If there is still space in the buffer, set the beginning of the next
// frame to the next position after the parsed frame.
else {
this->frameStart += 2 + packet_len;
}
// If there is more data in the buffer after the parsed frame then
// parse again. Otherwise break here and wait for more data.
if (this->bufferDataLen > this->frameStart) {
MS_DEBUG("there is more data after the parsed frame, continue parsing");
continue;
}
else {
break;
}
}
// Incomplete packet.
else {
// Check if the buffer is full.
if (this->bufferDataLen == this->bufferSize) {
// First case: the uncomplete frame does not begin at position 0 of
// the buffer, so move the frame to the position 0.
if (this->frameStart != 0) {
MS_DEBUG("no more space in the buffer, moving parsed bytes to the beginning of the buffer and wait for more data");
std::memmove(this->buffer, this->buffer + this->frameStart, this->bufferSize - this->frameStart);
this->bufferDataLen = this->bufferSize - this->frameStart;
this->frameStart = 0;
}
// Second case: the uncomplete frame begins at position 0 of the buffer.
// The frame is too big, so close the connection.
else {
MS_ERROR("no more space in the buffer for the unfinished frame being parsed, closing the connection");
// Close the socket.
Close();
}
}
// The buffer is not full.
else {
MS_DEBUG("frame not finished yet, waiting for more data");
}
// Exit the parsing loop.
break;
}
} // while()
}
void TCPConnection::Send(const MS_BYTE* data, size_t len) {
MS_TRACE();
// Write according to Framing RFC 4571.
MS_BYTE frame_len[2];
Utils::Byte::Set2Bytes(frame_len, 0, len);
Write(frame_len, 2, data, len);
}
} // namespace RTC
#define MS_CLASS "RTC::TCPServer"
#include "RTC/TCPServer.h"
#include "RTC/STUNMessage.h"
#include "RTC/RTPPacket.h"
#include "RTC/DTLSHandler.h"
#include "Settings.h"
#include "Utils.h"
#include "LibUV.h"
#include "MediaSoupError.h"
#include "Logger.h"
#include <string>
#define MAX_BIND_ATTEMPTS 10
#define MAX_TCP_CONNECTIONS_PER_SERVER 10
/* Static methods for UV callbacks. */
static inline
void on_error_close(uv_handle_t* handle) {
delete handle;
}
namespace RTC {
/* Static variables. */
struct sockaddr_storage TCPServer::sockaddrStorageIPv4;
struct sockaddr_storage TCPServer::sockaddrStorageIPv6;
MS_PORT TCPServer::minPort;
MS_PORT TCPServer::maxPort;
TCPServer::AvailablePorts TCPServer::availableIPv4Ports;
TCPServer::AvailablePorts TCPServer::availableIPv6Ports;
/* Static methods. */
// NOTE: Must be called from MediaSoup::Init().
void TCPServer::ClassInit() {
MS_TRACE();
int err;
if (! Settings::configuration.RTC.listenIPv4.empty()) {
err = uv_ip4_addr(Settings::configuration.RTC.listenIPv4.c_str(), 0, (struct sockaddr_in*)&RTC::TCPServer::sockaddrStorageIPv4);
if (err)
MS_ABORT("uv_ipv4_addr() failed: %s", uv_strerror(err));
}
if (! Settings::configuration.RTC.listenIPv6.empty()) {
err = uv_ip6_addr(Settings::configuration.RTC.listenIPv6.c_str(), 0, (struct sockaddr_in6*)&RTC::TCPServer::sockaddrStorageIPv6);
if (err)
MS_ABORT("uv_ipv6_addr() failed: %s", uv_strerror(err));
}
TCPServer::minPort = Settings::configuration.RTC.minPort;
TCPServer::maxPort = Settings::configuration.RTC.maxPort;
MS_PORT i = RTC::TCPServer::minPort;
do {
RTC::TCPServer::availableIPv4Ports[i] = true;
RTC::TCPServer::availableIPv6Ports[i] = true;
} while(i++ != RTC::TCPServer::maxPort);
}
RTC::TCPServer* TCPServer::New(int address_family) {
MS_TRACE();
uv_tcp_t* uvHandles[1];
// NOTE: This call may throw a MediaSoupError exception if the address family is not available
// or there are no available ports.
RandomizePort(address_family, uvHandles, false);
return new RTC::TCPServer(uvHandles[0]);
}
void TCPServer::NewPair(int address_family, RTC::TCPServer* servers[]) {
MS_TRACE();
uv_tcp_t* uvHandles[2];
// NOTE: This call may throw a MediaSoupError exception if the address family is not available
// or there are no available ports.
RandomizePort(address_family, uvHandles, true);
servers[0] = new RTC::TCPServer(uvHandles[0]);
servers[1] = new RTC::TCPServer(uvHandles[1]);
}
/*
* By calling this method, two different workers (threads) can access to the
* static map of available ports. No problem since the map keys are not modified,
* and values are a MS_PORT (uint16_t) which is atomic.
*/
void TCPServer::RandomizePort(int address_family, uv_tcp_t* uvHandles[], bool pair) {
MS_TRACE();
if (address_family == AF_INET && ! Settings::configuration.RTC.hasIPv4)
MS_THROW_ERROR("IPv4 family not available for RTC");
else if (address_family == AF_INET6 && ! Settings::configuration.RTC.hasIPv6)
MS_THROW_ERROR("IPv6 family not available for RTC");
int err;
struct sockaddr_storage first_bind_addr;
struct sockaddr_storage second_bind_addr;
const char* listenIP;
MS_PORT random_first_port;
MS_PORT iterate_first_port;
MS_PORT iterate_second_port;
uint16_t attempt = 0;
uint16_t bindAttempt = 0;
int flags = 0;
AvailablePorts* available_ports;
switch (address_family) {
case AF_INET:
available_ports = &RTC::TCPServer::availableIPv4Ports;
first_bind_addr = RTC::TCPServer::sockaddrStorageIPv4;
second_bind_addr = RTC::TCPServer::sockaddrStorageIPv4;
listenIP = Settings::configuration.RTC.listenIPv4.c_str();
break;
case AF_INET6:
available_ports = &RTC::TCPServer::availableIPv6Ports;
first_bind_addr = RTC::TCPServer::sockaddrStorageIPv6;
second_bind_addr = RTC::TCPServer::sockaddrStorageIPv6;
listenIP = Settings::configuration.RTC.listenIPv6.c_str();
// Don't also bind into IPv4 when listening in IPv6.
flags |= UV_TCP_IPV6ONLY;
break;
default:
MS_THROW_ERROR("invalid address family given");
break;
}
// Choose a random first port to start from.
random_first_port = (MS_PORT)Utils::Crypto::GetRandomUInt((unsigned int)RTC::TCPServer::minPort, (unsigned int)RTC::TCPServer::maxPort);
// Make it even if pair is requested.
if (pair)
random_first_port &= ~1;
// Set iterate_xxxx_port.
iterate_first_port = random_first_port;
// Iterate the RTC TCP ports until get one (or two) available (or fail if not).
// Fail also after bind() fails N times in theorically available RTC TCP ports.
while(true) {
attempt++;
// Increase the iterate port(s) within the range of RTC TCP ports.
if (! pair) {
if (iterate_first_port < RTC::TCPServer::maxPort)
iterate_first_port += 1;
else
iterate_first_port = RTC::TCPServer::minPort;
}
else {
if (iterate_first_port < RTC::TCPServer::maxPort - 1)
iterate_first_port += 2;
else
iterate_first_port = RTC::TCPServer::minPort;
iterate_second_port = iterate_first_port + 1;
}
if (! pair)
MS_DEBUG("attempt: %u | trying port %u" , (unsigned int)attempt, (unsigned int)iterate_first_port);
else
MS_DEBUG("attempt: %u | trying ports %u and %u" , (unsigned int)attempt, (unsigned int)iterate_first_port, (unsigned int)iterate_second_port);
// Check whether the chosen port is available.
if (! (*available_ports)[iterate_first_port]) {
MS_DEBUG("attempt: %u | port %u is in use, try again", (unsigned int)attempt, (unsigned int)iterate_first_port);
// If we have tried all the ports in the range raise an error.
if (iterate_first_port == random_first_port) {
MS_THROW_ERROR("no more available ports for IP '%s'", listenIP);
}
continue;
}
// Check also the odd port (if requested).
if (pair && ! (*available_ports)[iterate_second_port]) {
MS_DEBUG("attempt: %u | odd port %u is in use, try again", (unsigned int)attempt, (unsigned int)iterate_second_port);
// If we have tried all the ports in the range raise an error.
if (iterate_first_port == random_first_port) {
MS_THROW_ERROR("no more available ports for IP '%s'", listenIP);
}
continue;
}
// Here we already have a theorically available one of two ports.
// Now let's check whether no other process is listening into them.
// Set the chosen port(s) into the sockaddr struct(s).
switch(address_family) {
case AF_INET:
((struct sockaddr_in*)&first_bind_addr)->sin_port = htons(iterate_first_port);
if (pair)
((struct sockaddr_in*)&second_bind_addr)->sin_port = htons(iterate_second_port);
break;
case AF_INET6:
((struct sockaddr_in6*)&first_bind_addr)->sin6_port = htons(iterate_first_port);
if (pair)
((struct sockaddr_in6*)&second_bind_addr)->sin6_port = htons(iterate_second_port);
break;
}
// Try to bind on the even address (it may be taken by other process).
bindAttempt++;
uvHandles[0] = new uv_tcp_t();
err = uv_tcp_init(LibUV::GetLoop(), uvHandles[0]);
if (err) {
delete uvHandles[0];
MS_THROW_ERROR("attempt: %u | uv_tcp_init() failed: %s", (unsigned int)attempt, uv_strerror(err));
}
err = uv_tcp_bind(uvHandles[0], (const struct sockaddr*)&first_bind_addr, flags);
if (err) {
MS_WARN("attempt: %u | uv_tcp_bind() failed for port %u: %s", (unsigned int)attempt, (unsigned int)iterate_first_port, uv_strerror(err));
uv_close((uv_handle_t*)uvHandles[0], (uv_close_cb)on_error_close);
// If bind() fails due to "too many open files" stop here.
if (err == UV_EMFILE) {
MS_THROW_ERROR("bind() fails due to many open files");
}
// If bind() fails for more that MAX_BIND_ATTEMPTS then raise an error.
if (bindAttempt > MAX_BIND_ATTEMPTS) {
MS_THROW_ERROR("bind() fails more than %u times for IP '%s'", MAX_BIND_ATTEMPTS, listenIP);
}
// If we have tried all the ports in the range raise an error.
if (iterate_first_port == random_first_port) {
MS_THROW_ERROR("no more available ports for IP '%s'", listenIP);
}
continue;
}
// If requested, try to bind also on the odd address.
if (pair) {
uvHandles[1] = new uv_tcp_t();
err = uv_tcp_init(LibUV::GetLoop(), uvHandles[1]);
if (err) {
uv_close((uv_handle_t*)uvHandles[0], (uv_close_cb)on_error_close);
delete uvHandles[1];
MS_THROW_ERROR("attempt: %u | uv_tcp_init() failed: %s", (unsigned int)attempt, uv_strerror(err));
}
err = uv_tcp_bind(uvHandles[1], (const struct sockaddr*)&second_bind_addr, flags);
if (err) {
MS_WARN("attempt: %u | uv_tcp_bind() failed for odd port %u: %s", (unsigned int)attempt, (unsigned int)iterate_second_port, uv_strerror(err));
uv_close((uv_handle_t*)uvHandles[0], (uv_close_cb)on_error_close);
uv_close((uv_handle_t*)uvHandles[1], (uv_close_cb)on_error_close);
// If bind() fails due to "too many open files" stop here.
if (err == UV_EMFILE) {
MS_THROW_ERROR("bind() fails due to many open files");
}
// If bind() fails for more that MAX_BIND_ATTEMPTS then raise an error.
if (bindAttempt > MAX_BIND_ATTEMPTS) {
MS_THROW_ERROR("bind() fails more than %u times for IP '%s'", MAX_BIND_ATTEMPTS, listenIP);
}
// If we have tried all the ports in the range raise an error.
if (iterate_first_port == random_first_port) {
MS_THROW_ERROR("no more available ports for IP '%s'", listenIP);
}
continue;
}
}
// Success!
// Set the port(s) as unavailable.
(*available_ports)[iterate_first_port] = false;
if (pair)
(*available_ports)[iterate_second_port] = false;
if (! pair)
MS_DEBUG("attempt: %u | available port for IP '%s': %u" , (unsigned int)attempt, listenIP, (unsigned int)iterate_first_port);
else
MS_DEBUG("attempt: %u | available ports for IP '%s': %u and %u" , (unsigned int)attempt, listenIP, (unsigned int)iterate_first_port, (unsigned int)iterate_second_port);
return;
};
}
/* Instance methods. */
TCPServer::TCPServer(uv_tcp_t* uvHandle) :
::TCPServer::TCPServer(uvHandle, 256)
{
MS_TRACE();
}
void TCPServer::userOnTCPConnectionAlloc(::TCPConnection** connection) {
MS_TRACE();
// Allocate a new RTC::TCPConnection for the TCPServer to handle it.
*connection = new RTC::TCPConnection(this->reader, 65536);
}
void TCPServer::userOnNewTCPConnection(::TCPConnection* connection) {
MS_TRACE();
// Allow just MAX_TCP_CONNECTIONS_PER_SERVER.
if (GetNumConnections() > MAX_TCP_CONNECTIONS_PER_SERVER)
connection->Close();
}
void TCPServer::userOnTCPConnectionClosed(::TCPConnection* connection, bool is_closed_by_peer) {
MS_TRACE();
// Notify the listener.
// NOTE: Don't do it if closing (since at this point the listener is already freed).
if (! IsClosing())
this->listener->onRTCTCPConnectionClosed(this, static_cast<RTC::TCPConnection*>(connection), is_closed_by_peer);
}
void TCPServer::userOnTCPServerClosed() {
MS_TRACE();
// Mark the port as available again.
if (this->localAddr.ss_family == AF_INET)
RTC::TCPServer::availableIPv4Ports[this->localPort] = true;
else if (this->localAddr.ss_family == AF_INET6)
RTC::TCPServer::availableIPv6Ports[this->localPort] = true;
}
} // namespace RTC
#define MS_CLASS "RTC::Transport"
#include "RTC/Transport.h"
#include "RTC/FingerprintHash.h"
#include "MediaSoupError.h"
#include "Logger.h"
#define TRANSPORT_UDP "UDP"
#define TRANSPORT_TCP "TCP"
#define TRANSPORT_NAME(source) (source->IsUDP() ? TRANSPORT_UDP : TRANSPORT_TCP)
namespace RTC {
/* Static variables. */
size_t Transport::maxSources = 8;
/* Static methods. */
Transport* Transport::NewWebRTC(Listener* listener) {
MS_TRACE();
return new Transport(listener, Flag::ICE | Flag::DTLS | Flag::SRTP);
}
/* Instance methods. */
Transport::Transport(Listener* listener, int flags) :
listener(listener),
flags(flags)
{
MS_TRACE();
if (HasFlagICE())
this->iceServer = new RTC::ICEServer(this);
if (HasFlagDTLS()) {
this->dtlsHandler = new RTC::DTLSHandler(this);
// If DTLS flag is given then ensure SRTP flag is set.
this->flags |= Flag::SRTP;
}
}
Transport::~Transport() {
MS_TRACE();
}
void Transport::AddUDPSocket(RTC::UDPSocket* socket) {
MS_TRACE();
socket->SetListener(this);
this->udpSockets.push_back(socket);
}
void Transport::AddTCPServer(RTC::TCPServer* server) {
MS_TRACE();
server->SetListeners(this, this);
this->tcpServers.push_back(server);
}
void Transport::Reset() {
MS_TRACE();
this->sendingSource = nullptr;
for (auto it = this->sources.begin(); it != this->sources.end(); ++it) {
RTC::TransportSource* source = &(*it);
source->Close();
}
this->sources.clear();
this->isIcePaired = false;
this->isIcePairedWithUseCandidate = false;
if (this->dtlsHandler && this->dtlsHandler->IsRunning())
this->dtlsHandler->Reset();
if (this->srtpRecvSession) {
this->srtpRecvSession->Close();
this->srtpRecvSession = nullptr;
}
if (this->srtpSendSession) {
this->srtpSendSession->Close();
this->srtpSendSession = nullptr;
}
}
void Transport::Close() {
MS_TRACE();
if (this->iceServer)
this->iceServer->Close();
if (this->dtlsHandler)
this->dtlsHandler->Close();
if (this->srtpRecvSession)
this->srtpRecvSession->Close();
if (this->srtpSendSession)
this->srtpSendSession->Close();
for (auto socket : this->udpSockets)
socket->Close();
for (auto server : this->tcpServers)
server->Close();
delete this;
}
void Transport::SetLocalDTLSRole(RTC::DTLSRole role) {
MS_TRACE();
if (! HasFlagDTLS()) {
MS_ERROR("no DTLS flag");
return;
}
// If no changes are being made return.
if (this->dtlsRole == role) {
MS_DEBUG("given DTLS role matches the current one, doing nothing");
return;
}
// Update local DTLS role.
this->dtlsRole = role;
// Otherwise, if the DTLS handler is running, reset it.
if (this->dtlsHandler->IsRunning())
this->dtlsHandler->Reset();
// If ready, run the DTLS handler.
if (this->dtlsRole != RTC::DTLSRole::NONE)
RunDTLSHandlerIfReady();
}
void Transport::SetRemoteDTLSFingerprint(RTC::FingerprintHash hash, std::string& fingerprint) {
MS_TRACE();
if (! HasFlagDTLS()) {
MS_ERROR("no DTLS flag");
return;
}
this->dtlsHandler->SetRemoteFingerprint(hash, fingerprint);
}
void Transport::SetLocalSRTPKey(RTC::SRTPProfile srtp_profile, MS_BYTE* srtp_local_key, size_t srtp_local_key_len) {
MS_TRACE();
if (! HasFlagSRTP()) {
MS_ERROR("transport without SRTP");
return;
}
// Close it if it was already set and update it.
if (this->srtpSendSession) {
this->srtpSendSession->Close();
this->srtpSendSession = nullptr;
}
try {
this->srtpSendSession = new RTC::SRTPSession(SRTPSession::Type::OUTBOUND, srtp_profile, srtp_local_key, srtp_local_key_len);
}
catch (const MediaSoupError &error) {
MS_ERROR("error creating SRTP sending session: %s", error.what());
}
}
void Transport::SetRemoteSRTPKey(RTC::SRTPProfile srtp_profile, MS_BYTE* srtp_remote_key, size_t srtp_remote_key_len) {
MS_TRACE();
if (! HasFlagSRTP()) {
MS_ERROR("transport without SRTP");
return;
}
// Close it if it was already set and update it.
if (this->srtpRecvSession) {
this->srtpRecvSession->Close();
this->srtpRecvSession = nullptr;
}
try {
this->srtpRecvSession = new RTC::SRTPSession(SRTPSession::Type::INBOUND, srtp_profile, srtp_remote_key, srtp_remote_key_len);
}
catch (const MediaSoupError &error) {
MS_ERROR("error creating SRTP receiving session: %s", error.what());
}
}
void Transport::SendRTPPacket(RTC::RTPPacket* packet) {
MS_TRACE();
if (! this->sendingSource) {
MS_WARN("no sending address set, cannot send RTP packet");
return;
}
const MS_BYTE* data = packet->GetRaw();
size_t len = packet->GetLength();
if (HasFlagSRTP()) {
if (! this->srtpSendSession) {
MS_WARN("SRTP sending session not set, cannot send RTP packet");
return;
}
if (! this->srtpSendSession->EncryptRTP(&data, &len)) {
MS_WARN("error encrypting RTP packet: %s", this->srtpSendSession->GetLastErrorDesc());
return;
}
MS_DEBUG("sending SRTP packet of %zu bytes", len);
}
else {
MS_DEBUG("sending RTP packet of %zu bytes", len);
}
this->sendingSource->Send(data, len);
}
void Transport::SendRTCPPacket(RTC::RTCPPacket* packet) {
MS_TRACE();
if (! this->sendingSource) {
MS_WARN("no sending address set, cannot send RTCP packet");
return;
}
const MS_BYTE* data = packet->GetRaw();
size_t len = packet->GetLength();
if (HasFlagSRTP()) {
if (! this->srtpSendSession) {
MS_WARN("SRTP sending session not set, cannot send RTCP packet");
return;
}
if (! this->srtpSendSession->EncryptRTCP(&data, &len)) {
MS_WARN("error encrypting RTCP packet: %s", this->srtpSendSession->GetLastErrorDesc());
return;
}
MS_DEBUG("sending SRTCP packet of %zu bytes", len);
}
else {
MS_DEBUG("sending RTCP packet of %zu bytes", len);
}
this->sendingSource->Send(data, len);
}
// TODO: do it
void Transport::Dump() {
MS_DEBUG("%zu valid sources:", this->sources.size());
for (auto it = this->sources.begin(); it != this->sources.end(); ++it) {
RTC::TransportSource* source = &(*it);
source->Dump();
}
if (this->sendingSource) {
MS_DEBUG("sending source:");
this->sendingSource->Dump();
}
if (this->dtlsHandler)
this->dtlsHandler->Dump();
}
inline
void Transport::RunDTLSHandlerIfReady() {
MS_TRACE();
if (! this->dtlsHandler->IsRunning() && this->sendingSource) {
switch(this->dtlsRole) {
// If we are DTLS server then run the DTLS handler upon first valid ICE pair.
case RTC::DTLSRole::SERVER:
if (this->isIcePaired) {
MS_DEBUG("running DTLS handler in server role");
this->dtlsHandler->Run(this->dtlsRole);
}
break;
// If we are DTLS client then wait for the first Binding with USE-CANDIDATE.
case RTC::DTLSRole::CLIENT:
if (this->isIcePairedWithUseCandidate) {
MS_DEBUG("running DTLS handler in client role");
this->dtlsHandler->Run(this->dtlsRole);
}
break;
case RTC::DTLSRole::NONE:
break;
}
}
}
inline
void Transport::onSTUNDataRecv(RTC::TransportSource* source, const MS_BYTE* data, size_t len) {
MS_TRACE();
if (! HasFlagICE()) {
MS_DEBUG("no ICE flag, ignoring STUN message received via %s", TRANSPORT_NAME(source));
return;
}
RTC::STUNMessage* msg = RTC::STUNMessage::Parse(data, len);
if (! msg) {
MS_DEBUG("ignoring wrong STUN message received via %s", TRANSPORT_NAME(source));
return;
}
MS_DEBUG("STUN message received via %s, passing it to the ICEServer", TRANSPORT_NAME(source));
// msg->Dump();
this->iceServer->ProcessSTUNMessage(msg, source);
delete msg;
}
inline
void Transport::onDTLSDataRecv(RTC::TransportSource* source, const MS_BYTE* data, size_t len) {
MS_TRACE();
if (! HasFlagDTLS()) {
MS_DEBUG("no DTLS flag, ignoring DTLS data received via %s", TRANSPORT_NAME(source));
return;
}
if (! IsValidSource(source)) {
MS_DEBUG("ignoring DTLS data coming from an invalid %s address", TRANSPORT_NAME(source));
return;
}
if (this->dtlsHandler->IsRunning()) {
MS_DEBUG("DTLS data received via %s, passing it to the DTLSHandler", TRANSPORT_NAME(source));
this->dtlsHandler->ProcessDTLSData(data, len);
}
else {
MS_DEBUG("no DTLSHandler running, ignoring DTLS data received via %s", TRANSPORT_NAME(source));
return;
}
}
inline
void Transport::onRTPDataRecv(RTC::TransportSource* source, const MS_BYTE* data, size_t len) {
MS_TRACE();
if (! IsValidSource(source)) {
MS_DEBUG("ignoring RTP packet coming from an invalid %s address", TRANSPORT_NAME(source));
return;
}
if (HasFlagSRTP()) {
if (! this->srtpRecvSession) {
MS_DEBUG("SRTP receiving session not set, ignoring received RTP packet via %s", TRANSPORT_NAME(source));
return;
}
if (! this->srtpRecvSession->DecryptSRTP(data, &len)) {
MS_WARN("error decrypting SRTP packet received via %s: %s", TRANSPORT_NAME(source), this->srtpRecvSession->GetLastErrorDesc());
return;
}
}
RTC::RTPPacket* packet = RTC::RTPPacket::Parse(data, len);
if (! packet) {
MS_NOTICE("data received via %s is not a valid RTP packet", TRANSPORT_NAME(source));
return;
}
// MS_DEBUG("valid RTP packet received via %s [ssrc: %llu | payload: %hu | size: %zu]",
// TRANSPORT_NAME(source), (unsigned long long)packet->GetSSRC(), (unsigned short)packet->GetPayloadType(), len);
// Pass the RTP packet to the listener.
this->listener->onRTPPacket(this, packet);
delete packet;
}
inline
void Transport::onRTCPDataRecv(RTC::TransportSource* source, const MS_BYTE* data, size_t len) {
MS_TRACE();
if (! IsValidSource(source)) {
MS_DEBUG("ignoring RTCP packet coming from an invalid %s address", TRANSPORT_NAME(source));
return;
}
if (HasFlagSRTP()) {
if (! this->srtpRecvSession) {
MS_DEBUG("SRTP receiving session not set, ignoring received RTCP packet via %s", TRANSPORT_NAME(source));
return;
}
if (! this->srtpRecvSession->DecryptSRTCP(data, &len)) {
MS_WARN("error decrypting SRTCP packet received via %s: %s", TRANSPORT_NAME(source), this->srtpRecvSession->GetLastErrorDesc());
return;
}
}
RTC::RTCPPacket* packet = RTC::RTCPPacket::Parse(data, len);
if (! packet) {
MS_NOTICE("data received via %s is not a valid RTCP packet", TRANSPORT_NAME(source));
return;
}
// MS_DEBUG("valid RTCP packet received via %s", TRANSPORT_NAME(source));
// Pass the RTP packet to the listener.
this->listener->onRTCPPacket(this, packet);
delete packet;
}
void Transport::onSTUNDataRecv(RTC::UDPSocket *socket, const MS_BYTE* data, size_t len, const struct sockaddr* remote_addr) {
MS_TRACE();
RTC::TransportSource source(socket, remote_addr);
onSTUNDataRecv(&source, data, len);
}
void Transport::onDTLSDataRecv(RTC::UDPSocket *socket, const MS_BYTE* data, size_t len, const struct sockaddr* remote_addr) {
MS_TRACE();
RTC::TransportSource source(socket, remote_addr);
onDTLSDataRecv(&source, data, len);
}
void Transport::onRTPDataRecv(RTC::UDPSocket *socket, const MS_BYTE* data, size_t len, const struct sockaddr* remote_addr) {
MS_TRACE();
RTC::TransportSource source(socket, remote_addr);
onRTPDataRecv(&source, data, len);
}
void Transport::onRTCPDataRecv(RTC::UDPSocket *socket, const MS_BYTE* data, size_t len, const struct sockaddr* remote_addr) {
MS_TRACE();
RTC::TransportSource source(socket, remote_addr);
onRTCPDataRecv(&source, data, len);
}
void Transport::onRTCTCPConnectionClosed(RTC::TCPServer* tcpServer, RTC::TCPConnection* connection, bool is_closed_by_peer) {
MS_TRACE();
RTC::TransportSource source(connection);
if (RemoveSource(&source)) {
MS_DEBUG("valid source %s:", is_closed_by_peer ? "closed by peer" : "locally closed");
source.Dump();
}
}
void Transport::onSTUNDataRecv(RTC::TCPConnection *connection, const MS_BYTE* data, size_t len) {
MS_TRACE();
RTC::TransportSource source(connection);
onSTUNDataRecv(&source, data, len);
}
void Transport::onDTLSDataRecv(RTC::TCPConnection *connection, const MS_BYTE* data, size_t len) {
MS_TRACE();
RTC::TransportSource source(connection);
onDTLSDataRecv(&source, data, len);
}
void Transport::onRTPDataRecv(RTC::TCPConnection *connection, const MS_BYTE* data, size_t len) {
MS_TRACE();
RTC::TransportSource source(connection);
onRTPDataRecv(&source, data, len);
}
void Transport::onRTCPDataRecv(RTC::TCPConnection *connection, const MS_BYTE* data, size_t len) {
MS_TRACE();
RTC::TransportSource source(connection);
onRTCPDataRecv(&source, data, len);
}
void Transport::onOutgoingSTUNMessage(RTC::ICEServer* iceServer, RTC::STUNMessage* msg, RTC::TransportSource* source) {
MS_TRACE();
MS_DEBUG("sending STUN message to:");
source->Dump();
// msg->Dump();
source->Send(msg->GetRaw(), msg->GetLength());
}
void Transport::onICEValidPair(RTC::ICEServer* iceServer, RTC::TransportSource* source, bool has_use_candidate) {
MS_TRACE();
this->isIcePaired = true;
if (has_use_candidate)
this->isIcePairedWithUseCandidate = true;
/*
* RFC 5245 section 11.2 "Receiving Media":
*
* ICE implementations MUST be prepared to receive media on each component
* on any candidates provided for that component.
*/
if (SetSendingSource(source)) {
MS_DEBUG("ICE paired");
Dump();
}
// If ready, run the DTLS handler.
if (HasFlagDTLS())
RunDTLSHandlerIfReady();
}
void Transport::onOutgoingDTLSData(RTC::DTLSHandler* dtlsHandler, const MS_BYTE* data, size_t len) {
MS_TRACE();
if (! this->sendingSource) {
MS_ERROR("no sending address set, cannot send DTLS packet");
return;
}
MS_DEBUG("sending DTLS data to to:");
this->sendingSource->Dump();
this->sendingSource->Send(data, len);
}
void Transport::onDTLSConnected(RTC::DTLSHandler* dtlsHandler) {
MS_TRACE();
MS_DEBUG("DTLS connected");
Dump();
}
void Transport::onDTLSDisconnected(RTC::DTLSHandler* dtlsHandler) {
MS_TRACE();
MS_DEBUG("DTLS disconnected");
Reset();
Dump();
}
void Transport::onDTLSFailed(RTC::DTLSHandler* dtlsHandler) {
MS_TRACE();
MS_NOTICE("DTLS failed");
Reset();
Dump();
}
void Transport::onSRTPKeyMaterial(RTC::DTLSHandler* dtlsHandler, RTC::SRTPProfile srtp_profile, MS_BYTE* srtp_local_key, size_t srtp_local_key_len, MS_BYTE* srtp_remote_key, size_t srtp_remote_key_len) {
MS_TRACE();
MS_DEBUG("got SRTP key material");
SetLocalSRTPKey(srtp_profile, srtp_local_key, srtp_local_key_len);
SetRemoteSRTPKey(srtp_profile, srtp_remote_key, srtp_remote_key_len);
}
void Transport::onDTLSApplicationData(RTC::DTLSHandler* dtlsHandler, const MS_BYTE* data, size_t len) {
MS_TRACE();
MS_DEBUG("DTLS application data received | size: %zu", len);
// TMP
MS_DEBUG("data: %s", std::string((char*)data, len).c_str());
// TMP
dtlsHandler->SendApplicationData(data, len);
}
} // namespace RTC
#define MS_CLASS "RTC::TransportSource"
#include "RTC/TransportSource.h"
#include "Logger.h"
namespace RTC {
/* Instance methods. */
void TransportSource::Dump() {
MS_TRACE();
if (! Logger::HasDebugLevel())
return;
switch(this->type) {
case Type::UDP: {
int remote_family;
std::string remote_ip;
MS_PORT remote_port;
Utils::IP::GetAddressInfo(GetRemoteAddress(), &remote_family, remote_ip, &remote_port);
MS_DEBUG("[UDP | local: %s : %u | remote: %s : %u]",
this->udpSocket->GetLocalIP().c_str(), (unsigned int)this->udpSocket->GetLocalPort(),
remote_ip.c_str(), remote_port);
break;
}
case Type::TCP: {
MS_DEBUG("[TCP | local: %s : %u | remote: %s : %u]",
this->tcpConnection->GetLocalIP().c_str(), (unsigned int)this->tcpConnection->GetLocalPort(),
this->tcpConnection->GetPeerIP().c_str(), (unsigned int)this->tcpConnection->GetPeerPort());
break;
}
}
}
} // namespace RTC
#define MS_CLASS "RTC::UDPSocket"
#include "RTC/UDPSocket.h"
#include "RTC/STUNMessage.h"
#include "RTC/DTLSHandler.h"
#include "RTC/RTPPacket.h"
#include "RTC/RTCPPacket.h"
#include "Settings.h"
#include "Utils.h"
#include "LibUV.h"
#include "MediaSoupError.h"
#include "Logger.h"
#include <string>
#define MAX_BIND_ATTEMPTS 10
/* Static methods for UV callbacks. */
static inline
void on_error_close(uv_handle_t* handle) {
delete handle;
}
namespace RTC {
/* Static variables. */
struct sockaddr_storage UDPSocket::sockaddrStorageIPv4;
struct sockaddr_storage UDPSocket::sockaddrStorageIPv6;
MS_PORT UDPSocket::minPort;
MS_PORT UDPSocket::maxPort;
UDPSocket::AvailablePorts UDPSocket::availableIPv4Ports;
UDPSocket::AvailablePorts UDPSocket::availableIPv6Ports;
/* Static methods. */
// NOTE: Must be called from MediaSoup::Init().
void UDPSocket::ClassInit() {
MS_TRACE();
int err;
if (Settings::configuration.RTC.hasIPv4) {
err = uv_ip4_addr(Settings::configuration.RTC.listenIPv4.c_str(), 0, (struct sockaddr_in*)&RTC::UDPSocket::sockaddrStorageIPv4);
if (err)
MS_ABORT("uv_ipv4_addr() failed: %s", uv_strerror(err));
}
if (Settings::configuration.RTC.hasIPv6) {
err = uv_ip6_addr(Settings::configuration.RTC.listenIPv6.c_str(), 0, (struct sockaddr_in6*)&RTC::UDPSocket::sockaddrStorageIPv6);
if (err)
MS_ABORT("uv_ipv6_addr() failed: %s", uv_strerror(err));
}
UDPSocket::minPort = Settings::configuration.RTC.minPort;
UDPSocket::maxPort = Settings::configuration.RTC.maxPort;
MS_PORT i = RTC::UDPSocket::minPort;
do {
RTC::UDPSocket::availableIPv4Ports[i] = true;
RTC::UDPSocket::availableIPv6Ports[i] = true;
} while(i++ != RTC::UDPSocket::maxPort);
}
RTC::UDPSocket* UDPSocket::New(int address_family) {
MS_TRACE();
uv_udp_t* uvHandles[1];
// NOTE: This call may throw a MediaSoupError exception if the address family is not available
// or there are no available ports.
RandomizePort(address_family, uvHandles, false);
return new RTC::UDPSocket(uvHandles[0]);
}
void UDPSocket::NewPair(int address_family, RTC::UDPSocket* sockets[]) {
MS_TRACE();
uv_udp_t* uvHandles[2];
// NOTE: This call may throw a MediaSoupError exception if the address family is not available
// or there are no available ports.
RandomizePort(address_family, uvHandles, true);
sockets[0] = new RTC::UDPSocket(uvHandles[0]);
sockets[1] = new RTC::UDPSocket(uvHandles[1]);
}
/*
* By calling this method, two different workers (threads) can access to the
* static map of available ports. No problem since the map keys are not modified,
* and values are a MS_PORT (uint16_t) which is atomic.
*/
void UDPSocket::RandomizePort(int address_family, uv_udp_t* uvHandles[], bool pair) {
MS_TRACE();
if (address_family == AF_INET && ! Settings::configuration.RTC.hasIPv4)
MS_THROW_ERROR("IPv4 family not available for RTC");
else if (address_family == AF_INET6 && ! Settings::configuration.RTC.hasIPv6)
MS_THROW_ERROR("IPv6 family not available for RTC");
int err;
struct sockaddr_storage first_bind_addr;
struct sockaddr_storage second_bind_addr;
const char* listenIP;
MS_PORT random_first_port;
MS_PORT iterate_first_port;
MS_PORT iterate_second_port;
uint16_t attempt = 0;
uint16_t bindAttempt = 0;
int flags = 0;
AvailablePorts* available_ports;
switch (address_family) {
case AF_INET:
available_ports = &RTC::UDPSocket::availableIPv4Ports;
first_bind_addr = RTC::UDPSocket::sockaddrStorageIPv4;
second_bind_addr = RTC::UDPSocket::sockaddrStorageIPv4;
listenIP = Settings::configuration.RTC.listenIPv4.c_str();
break;
case AF_INET6:
available_ports = &RTC::UDPSocket::availableIPv6Ports;
first_bind_addr = RTC::UDPSocket::sockaddrStorageIPv6;
second_bind_addr = RTC::UDPSocket::sockaddrStorageIPv6;
listenIP = Settings::configuration.RTC.listenIPv6.c_str();
// Don't also bind into IPv4 when listening in IPv6.
flags |= UV_UDP_IPV6ONLY;
break;
default:
MS_THROW_ERROR("invalid address family given");
break;
}
// Choose a random first port to start from.
random_first_port = (MS_PORT)Utils::Crypto::GetRandomUInt((unsigned int)RTC::UDPSocket::minPort, (unsigned int)RTC::UDPSocket::maxPort);
// Make it even if pair is requested.
if (pair)
random_first_port &= ~1;
// Set iterate_xxxx_port.
iterate_first_port = random_first_port;
// Iterate the RTC UDP ports until get one (or two) available (or fail if not).
// Fail also after bind() fails N times in theorically available RTC UDP ports.
while(true) {
attempt++;
// Increase the iterate port(s) within the range of RTC UDP ports.
if (! pair) {
if (iterate_first_port < RTC::UDPSocket::maxPort)
iterate_first_port += 1;
else
iterate_first_port = RTC::UDPSocket::minPort;
}
else {
if (iterate_first_port < RTC::UDPSocket::maxPort - 1)
iterate_first_port += 2;
else
iterate_first_port = RTC::UDPSocket::minPort;
iterate_second_port = iterate_first_port + 1;
}
if (! pair)
MS_DEBUG("attempt: %u | trying port %u" , (unsigned int)attempt, (unsigned int)iterate_first_port);
else
MS_DEBUG("attempt: %u | trying ports %u and %u" , (unsigned int)attempt, (unsigned int)iterate_first_port, (unsigned int)iterate_second_port);
// Check whether the chosen port is available.
if (! (*available_ports)[iterate_first_port]) {
MS_DEBUG("attempt: %u | port %u is in use, try again", (unsigned int)attempt, (unsigned int)iterate_first_port);
// If we have tried all the ports in the range raise an error.
if (iterate_first_port == random_first_port) {
MS_THROW_ERROR("no more available ports for IP '%s'", listenIP);
}
continue;
}
// Check also the odd port (if requested).
if (pair && ! (*available_ports)[iterate_second_port]) {
MS_DEBUG("attempt: %u | odd port %u is in use, try again", (unsigned int)attempt, (unsigned int)iterate_second_port);
// If we have tried all the ports in the range raise an error.
if (iterate_first_port == random_first_port) {
MS_THROW_ERROR("no more available ports for IP '%s'", listenIP);
}
continue;
}
// Here we already have a theorically available one of two ports.
// Now let's check whether no other process is listening into them.
// Set the chosen port(s) into the sockaddr struct(s).
switch(address_family) {
case AF_INET:
((struct sockaddr_in*)&first_bind_addr)->sin_port = htons(iterate_first_port);
if (pair)
((struct sockaddr_in*)&second_bind_addr)->sin_port = htons(iterate_second_port);
break;
case AF_INET6:
((struct sockaddr_in6*)&first_bind_addr)->sin6_port = htons(iterate_first_port);
if (pair)
((struct sockaddr_in6*)&second_bind_addr)->sin6_port = htons(iterate_second_port);
break;
}
// Try to bind on the even address (it may be taken by other process).
bindAttempt++;
uvHandles[0] = new uv_udp_t();
err = uv_udp_init(LibUV::GetLoop(), uvHandles[0]);
if (err) {
delete uvHandles[0];
MS_THROW_ERROR("attempt: %u | uv_udp_init() failed: %s", (unsigned int)attempt, uv_strerror(err));
}
err = uv_udp_bind(uvHandles[0], (const struct sockaddr*)&first_bind_addr, flags);
if (err) {
MS_WARN("attempt: %u | uv_udp_bind() failed for port %u: %s", (unsigned int)attempt, (unsigned int)iterate_first_port, uv_strerror(err));
uv_close((uv_handle_t*)uvHandles[0], (uv_close_cb)on_error_close);
// If bind() fails due to "too many open files" stop here.
if (err == UV_EMFILE) {
MS_THROW_ERROR("bind() fails due to many open files");
}
// If bind() fails for more that MAX_BIND_ATTEMPTS then raise an error.
if (bindAttempt > MAX_BIND_ATTEMPTS) {
MS_THROW_ERROR("bind() fails more than %u times for IP '%s'", MAX_BIND_ATTEMPTS, listenIP);
}
// If we have tried all the ports in the range raise an error.
if (iterate_first_port == random_first_port) {
MS_THROW_ERROR("no more available ports for IP '%s'", listenIP);
}
continue;
}
// If requested, try to bind also on the odd address.
if (pair) {
uvHandles[1] = new uv_udp_t();
err = uv_udp_init(LibUV::GetLoop(), uvHandles[1]);
if (err) {
uv_close((uv_handle_t*)uvHandles[0], (uv_close_cb)on_error_close);
delete uvHandles[1];
MS_THROW_ERROR("attempt: %u | uv_udp_init() failed: %s", (unsigned int)attempt, uv_strerror(err));
}
err = uv_udp_bind(uvHandles[1], (const struct sockaddr*)&second_bind_addr, flags);
if (err) {
MS_WARN("attempt: %u | uv_udp_bind() failed for odd port %u: %s", (unsigned int)attempt, (unsigned int)iterate_second_port, uv_strerror(err));
uv_close((uv_handle_t*)uvHandles[0], (uv_close_cb)on_error_close);
uv_close((uv_handle_t*)uvHandles[1], (uv_close_cb)on_error_close);
// If bind() fails due to "too many open files" stop here.
if (err == UV_EMFILE) {
MS_THROW_ERROR("bind() fails due to many open files");
}
// If bind() fails for more that MAX_BIND_ATTEMPTS then raise an error.
if (bindAttempt > MAX_BIND_ATTEMPTS) {
MS_THROW_ERROR("bind() fails more than %u times for IP '%s'", MAX_BIND_ATTEMPTS, listenIP);
}
// If we have tried all the ports in the range raise an error.
if (iterate_first_port == random_first_port) {
MS_THROW_ERROR("no more available ports for IP '%s'", listenIP);
}
continue;
}
}
// Success!
// Set the port(s) as unavailable.
(*available_ports)[iterate_first_port] = false;
if (pair)
(*available_ports)[iterate_second_port] = false;
if (! pair)
MS_DEBUG("attempt: %u | available port for IP '%s': %u" , (unsigned int)attempt, listenIP, (unsigned int)iterate_first_port);
else
MS_DEBUG("attempt: %u | available ports for IP '%s': %u and %u" , (unsigned int)attempt, listenIP, (unsigned int)iterate_first_port, (unsigned int)iterate_second_port);
return;
};
}
/* Instance methods. */
UDPSocket::UDPSocket(uv_udp_t* uvHandle) :
::UDPSocket::UDPSocket(uvHandle)
{
MS_TRACE();
}
void UDPSocket::userOnUDPDatagramRecv(const MS_BYTE* data, size_t len, const struct sockaddr* addr) {
MS_TRACE();
if (! this->listener) {
MS_ERROR("no listener set");
return;
}
if (Logger::HasDebugLevel()) {
int family;
MS_PORT port;
std::string ip;
Utils::IP::GetAddressInfo(addr, &family, ip, &port);
MS_DEBUG("%zu bytes datagram received [local: %s : %u | remote: %s : %u]", len, GetLocalIP().c_str(), (unsigned int)GetLocalPort(), ip.c_str(), (unsigned int)port);
}
// Check if it's STUN.
if (STUNMessage::IsSTUN(data, len)) {
this->listener->onSTUNDataRecv(this, data, len, addr);
return;
}
// Check if it's RTCP.
if (RTCPPacket::IsRTCP(data, len)) {
this->listener->onRTCPDataRecv(this, data, len, addr);
return;
}
// Check if it's RTP.
if (RTPPacket::IsRTP(data, len)) {
this->listener->onRTPDataRecv(this, data, len, addr);
return;
}
// Check if it's DTLS.
if (DTLSHandler::IsDTLS(data, len)) {
this->listener->onDTLSDataRecv(this, data, len, addr);
return;
}
MS_DEBUG("ignoring received datagram of unknown type");
}
void UDPSocket::userOnUDPSocketClosed() {
MS_TRACE();
// Mark the port as available again.
if (this->localAddr.ss_family == AF_INET)
RTC::UDPSocket::availableIPv4Ports[this->localPort] = true;
else if (this->localAddr.ss_family == AF_INET6)
RTC::UDPSocket::availableIPv6Ports[this->localPort] = true;
}
} // namespace RTC
#define MS_CLASS "Settings"
#include "Settings.h"
#include "Version.h"
#include "Utils.h"
#include "MediaSoupError.h"
#include "Logger.h"
#include <string>
#include <map>
#include <algorithm> // std::transform()
#include <cstdio> // std::fprintf()
#include <cstdlib> // std::_Exit()
#include <cerrno>
#include <unistd.h> // close()
#include <uv.h>
extern "C" {
#include <getopt.h>
#include <syslog.h>
}
/* Static variables. */
struct Settings::Arguments Settings::arguments;
struct Settings::Configuration Settings::configuration;
std::map<std::string, unsigned int> Settings::string2LogLevel = {
{ "debug", LOG_DEBUG },
{ "info", LOG_INFO },
{ "notice", LOG_NOTICE },
{ "warn", LOG_WARNING },
{ "error", LOG_ERR }
};
std::map<unsigned int, std::string> Settings::logLevel2String = {
{ LOG_DEBUG, "debug" },
{ LOG_INFO, "info" },
{ LOG_NOTICE, "notice" },
{ LOG_WARNING, "warn" },
{ LOG_ERR, "error" }
};
std::map<std::string, unsigned int> Settings::string2SyslogFacility = {
{ "user", LOG_USER },
{ "local0", LOG_LOCAL0 },
{ "local1", LOG_LOCAL1 },
{ "local2", LOG_LOCAL2 },
{ "local3", LOG_LOCAL3 },
{ "local4", LOG_LOCAL4 },
{ "local5", LOG_LOCAL5 },
{ "local6", LOG_LOCAL6 },
{ "local7", LOG_LOCAL7 }
};
std::map<unsigned int, std::string> Settings::syslogFacility2String = {
{ LOG_USER, "user" },
{ LOG_LOCAL0, "local0" },
{ LOG_LOCAL1, "local1" },
{ LOG_LOCAL2, "local2" },
{ LOG_LOCAL3, "local3" },
{ LOG_LOCAL4, "local4" },
{ LOG_LOCAL5, "local5" },
{ LOG_LOCAL6, "local6" },
{ LOG_LOCAL7, "local7" }
};
/* Static methods. */
void Settings::ReadArguments(int argc, char* argv[]) {
MS_TRACE();
/* Variables for getopt. */
int c;
int option_index = 0;
extern char *optarg;
extern int optind, opterr, optopt;
// For getopt_long().
// Begin with ":" so we get ':' error in case a valid option requires argument.
std::string short_options = ":c:dp:u:g:vh";
// For getopt_long().
struct option long_options[] = {
{ "configfile", required_argument, nullptr, 'c' },
{ "daemonize", no_argument, nullptr, 'd' },
{ "pidfile", required_argument, nullptr, 'p' },
{ "user", required_argument, nullptr, 'u' },
{ "group", required_argument, nullptr, 'g' },
{ "version", no_argument, nullptr, 'v' },
{ "help", no_argument, nullptr, 'h' },
{ 0, 0, 0, 0 }
};
// A map for associating short and long option names.
std::map<char, std::string> long_option_names = {
{ 'c', "configfile" },
{ 'd', "daemonize" },
{ 'p', "pidfile" },
{ 'u', "user" },
{ 'g', "group" },
{ 'v', "version" },
{ 'h', "help" }
};
/* Parse command line options. */
opterr = 0; // Don't allow getopt to print error messages.
while ((c = getopt_long(argc, argv, short_options.c_str(), long_options, &option_index)) != -1) {
switch(c) {
case 'c':
Settings::arguments.configFile = optarg;
break;
case 'd':
Settings::arguments.daemonize = true;
break;
case 'p':
Settings::arguments.pidFile = optarg;
break;
case 'u':
Settings::arguments.user = optarg;
break;
case 'g':
Settings::arguments.group = optarg;
break;
case 'v':
Settings::PrintVersion();
std::_Exit(EXIT_SUCCESS);
break;
case 'h':
Settings::PrintVersion();
Settings::PrintHelp(false);
std::_Exit(EXIT_SUCCESS);
break;
// Invalid option.
case '?':
if (isprint(optopt)) {
MS_ERROR("invalid option '-%c'", (char)optopt);
Settings::PrintHelp(true);
std::_Exit(EXIT_FAILURE);
}
else {
MS_ERROR("unknown long option given as argument");
Settings::PrintHelp(true);
std::_Exit(EXIT_FAILURE);
}
// Valid option, but it requires and argument that is not given.
case ':':
MS_ERROR("option '-%c' or '--%s' requires an argument", (char)optopt, long_option_names[(char)optopt].c_str());
Settings::PrintHelp(true);
std::_Exit(EXIT_FAILURE);
break;
// This should never happen.
default:
MS_ABORT("'default' should never happen");
}
}
// Ensure there are no more command line arguments after parsed options.
if (optind != argc)
MS_EXIT_FAILURE("there are remaining arguments after parsing command line options");
// Ensure that PID file is not given when in foreground mode.
if (! Settings::arguments.pidFile.empty() && ! Settings::arguments.daemonize)
MS_EXIT_FAILURE("PID file option requires daemon mode");
}
void Settings::PrintHelp(bool error) {
MS_TRACE();
std::string help;
help.append("\nUsage: ");
help.append(Version::command);
help.append(" [options]\n");
help.append("Options:\n");
help.append(" -c, --configfile FILE Path to the configuration file\n");
help.append(" -d, --daemonize Run in daemon mode\n");
help.append(" -p, --pidfile FILE Create a PID file (requires daemon mode)\n");
help.append(" -u, --user USER Run with the given system user\n");
help.append(" -g, --group GROUP Run with the given system group\n");
help.append(" -v, --version Show version\n");
help.append(" -h, --help Show this message\n");
if (error)
std::fprintf(stderr, "%s", help.c_str());
else
std::fprintf(stdout, "%s", help.c_str());
}
void Settings::PrintVersion() {
MS_TRACE();
std::fprintf(stdout, "%s\n", Version::GetNameAndVersion().c_str());
std::fprintf(stdout, "%s\n", Version::copyright.c_str());
}
void Settings::SetDefaultConfiguration() {
MS_TRACE();
SetDefaultNumWorkers();
SetDefaultRTClistenIP(AF_INET);
SetDefaultRTClistenIP(AF_INET6);
}
void Settings::ReadConfigurationFile() {
MS_TRACE();
if (Settings::arguments.configFile.empty())
return;
libconfig::Config* config;
try {
config = ParseConfigFile();
}
catch (const MediaSoupError &error) {
MS_EXIT_FAILURE("%s", error.what());
}
std::string str_value;
std::string str_value2;
int int_value;
int int_value2;
bool bool_value;
std::string empty_string;
try {
/* First level settings. */
if (config->lookupValue("logLevel", str_value))
SetLogLevel(str_value);
if (config->lookupValue("syslogFacility", str_value))
SetSyslogFacility(str_value);
if (config->lookupValue("numWorkers", int_value))
SetNumWorkers(int_value);
/* ControlProtocol section. */
if (config->lookupValue("ControlProtocol.listenIP", str_value))
SetControlProtocolListenIP(str_value);
if (config->lookupValue("ControlProtocol.listenPort", int_value))
SetControlProtocolListenPort(int_value);
/* RTC section. */
if (config->lookupValue("RTC.listenIPv4", str_value))
SetRTClistenIPv4(str_value);
else if ((config->lookupValue("RTC.listenIPv4", bool_value)) && bool_value == false)
SetRTClistenIPv4(empty_string);
if (config->lookupValue("RTC.listenIPv6", str_value))
SetRTClistenIPv6(str_value);
else if ((config->lookupValue("RTC.listenIPv6", bool_value)) && bool_value == false)
SetRTClistenIPv6(empty_string);
if (config->lookupValue("RTC.minPort", int_value) && config->lookupValue("RTC.maxPort", int_value2))
SetRTCports(int_value, int_value2);
if (config->lookupValue("RTC.dtlsCertificateFile", str_value) && config->lookupValue("RTC.dtlsPrivateKeyFile", str_value2))
SetDtlsCertificateAndPrivateKeyFiles(str_value, str_value2);
}
catch (const MediaSoupError &error) {
delete config;
MS_EXIT_FAILURE("error in configuration file: %s", error.what());
}
delete config;
}
bool Settings::ReloadConfigurationFile() {
MS_TRACE();
if (Settings::arguments.configFile.empty()) {
MS_ERROR("no configuration file was given in command line options");
return false;
}
libconfig::Config* config;
try {
config = ParseConfigFile();
}
catch (const MediaSoupError &error) {
MS_ERROR("%s", error.what());
return false;
}
std::string str_value;
// Just some configuration settings can be reloaded.
try {
/* First level settings. */
if (config->lookupValue("logLevel", str_value))
SetLogLevel(str_value);
else
Settings::configuration.logLevel = LOG_DEBUG;
}
catch (const MediaSoupError &error) {
MS_ERROR("error in configuration file: %s", error.what());
delete config;
return false;
}
delete config;
return true;
}
void Settings::PrintConfiguration() {
MS_TRACE();
MS_INFO("[configuration]");
MS_INFO("- logLevel: \"%s\"", Settings::logLevel2String[Settings::configuration.logLevel].c_str());
MS_INFO("- syslogFacility: \"%s\"", Settings::syslogFacility2String[Settings::configuration.syslogFacility].c_str());
MS_INFO("- numWorkers: %d", Settings::configuration.numWorkers);
MS_INFO("- ControlProtocol:");
MS_INFO(" - listenIP: \"%s\"", Settings::configuration.ControlProtocol.listenIP.c_str());
MS_INFO(" - listenPort: %d", Settings::configuration.ControlProtocol.listenPort);
MS_INFO("- RTC:");
if (Settings::configuration.RTC.hasIPv4)
MS_INFO(" - listenIPv4: \"%s\"", Settings::configuration.RTC.listenIPv4.c_str());
else
MS_INFO(" - listenIPv4: (unavailable)");
if (Settings::configuration.RTC.hasIPv6)
MS_INFO(" - listenIPv6: \"%s\"", Settings::configuration.RTC.listenIPv6.c_str());
else
MS_INFO(" - listenIPv6: (unavailable)");
MS_INFO(" - minPort: %d", Settings::configuration.RTC.minPort);
MS_INFO(" - maxPort: %d", Settings::configuration.RTC.maxPort);
if (! Settings::configuration.RTC.dtlsCertificateFile.empty()) {
MS_INFO(" - dtlsCertificateFile: \"%s\"", Settings::configuration.RTC.dtlsCertificateFile.c_str());
MS_INFO(" - dtlsPrivateKeyFile: \"%s\"", Settings::configuration.RTC.dtlsPrivateKeyFile.c_str());
}
MS_INFO("[/configuration]");
}
libconfig::Config* Settings::ParseConfigFile() {
MS_TRACE();
const char* config_file = Settings::arguments.configFile.c_str();
try {
Utils::File::CheckFile(config_file);
}
catch (const MediaSoupError &error) {
MS_THROW_ERROR("error reading configuration file: %s", error.what());
}
libconfig::Config* config = new libconfig::Config();
try {
config->readFile(config_file);
}
catch (const libconfig::ParseException &error) {
delete config;
MS_THROW_ERROR("parsing error in configuration file '%s': %s in line %d", config_file, error.getError(), error.getLine());
}
catch (const libconfig::FileIOException &error) {
delete config;
MS_THROW_ERROR("cannot read configuration file '%s'", config_file);
}
catch (const libconfig::ConfigException &error) {
delete config;
MS_THROW_ERROR("error reading configuration file '%s': %s", config_file, error.what());
}
return config;
}
void Settings::SetLogLevel(std::string &level) {
MS_TRACE();
// Downcase given level.
std::transform(level.begin(), level.end(), level.begin(), ::tolower);
if (Settings::string2LogLevel.find(level) == Settings::string2LogLevel.end())
MS_THROW_ERROR("invalid value '%s' for Logging.level", level.c_str());
Settings::configuration.logLevel = Settings::string2LogLevel[level];
}
void Settings::SetSyslogFacility(std::string &facility) {
MS_TRACE();
// Downcase given facility.
std::transform(facility.begin(), facility.end(), facility.begin(), ::tolower);
if (Settings::string2SyslogFacility.find(facility) == Settings::string2SyslogFacility.end())
MS_THROW_ERROR("invalid value '%s' for Logging.syslogFacility", facility.c_str());
Settings::configuration.syslogFacility = Settings::string2SyslogFacility[facility];
}
void Settings::SetNumWorkers(int numWorkers) {
MS_TRACE();
if (numWorkers < 0)
MS_THROW_ERROR("numWorkers must be greater or equal than 0");
// If 0 let the already set default value.
else if (numWorkers == 0)
return;
Settings::configuration.numWorkers = numWorkers;
}
void Settings::SetDefaultNumWorkers() {
MS_TRACE();
int err;
uv_cpu_info_t* cpus;
int num_cpus;
err = uv_cpu_info(&cpus, &num_cpus);
if (err)
MS_ABORT("uv_cpu_info() failed: %s", uv_strerror(err));
uv_free_cpu_info(cpus, num_cpus);
MS_DEBUG("auto-detected value for numWorkers: %d", num_cpus);
Settings::configuration.numWorkers = num_cpus;
}
void Settings::SetControlProtocolListenIP(const std::string &ip) {
MS_TRACE();
switch (Utils::IP::GetFamily(ip)) {
case AF_INET:
case AF_INET6:
Settings::configuration.ControlProtocol.listenIP = ip;
break;
default:
MS_THROW_ERROR("invalid value '%s' for ControlProtocol.listenIP", ip.c_str());
}
}
void Settings::SetControlProtocolListenPort(MS_PORT port) {
MS_TRACE();
Settings::configuration.ControlProtocol.listenPort = port;
}
void Settings::SetRTClistenIPv4(const std::string &ip) {
MS_TRACE();
if (ip.empty()) {
Settings::configuration.RTC.listenIPv4.clear();
Settings::configuration.RTC.hasIPv4 = false;
return;
}
switch (Utils::IP::GetFamily(ip)) {
case AF_INET:
if (ip == "0.0.0.0")
MS_THROW_ERROR("RTC.listenIPv4 cannot be '0.0.0.0'");
Settings::configuration.RTC.listenIPv4 = ip;
Settings::configuration.RTC.hasIPv4 = true;
break;
case AF_INET6:
MS_THROW_ERROR("invalid IPv6 '%s' for RTC.listenIPv4", ip.c_str());
default:
MS_THROW_ERROR("invalid value '%s' for RTC.listenIPv4", ip.c_str());
}
int _bind_err;
if (! IsBindableIP(ip, AF_INET, &_bind_err))
MS_THROW_ERROR("cannot bind on '%s' for RTC.listenIPv4: %s", ip.c_str(), std::strerror(_bind_err));
}
void Settings::SetRTClistenIPv6(const std::string &ip) {
MS_TRACE();
if (ip.empty()) {
Settings::configuration.RTC.listenIPv6.clear();
Settings::configuration.RTC.hasIPv6 = false;
return;
}
switch (Utils::IP::GetFamily(ip)) {
case AF_INET6:
if (ip == "::")
MS_THROW_ERROR("RTC.listenIPv6 cannot be '::'");
Settings::configuration.RTC.listenIPv6 = ip;
Settings::configuration.RTC.hasIPv6 = true;
break;
case AF_INET:
MS_THROW_ERROR("invalid IPv4 '%s' for RTC.listenIPv6", ip.c_str());
default:
MS_THROW_ERROR("invalid value '%s' for RTC.listenIPv6", ip.c_str());
}
int _bind_err;
if (! IsBindableIP(ip, AF_INET6, &_bind_err))
MS_THROW_ERROR("cannot bind on '%s' for RTC.listenIPv6: %s", ip.c_str(), std::strerror(_bind_err));
}
void Settings::SetDefaultRTClistenIP(int requested_family) {
MS_TRACE();
int err;
uv_interface_address_t* addresses;
int num_addresses;
std::string ipv4;
std::string ipv6;
int _bind_err;
err = uv_interface_addresses(&addresses, &num_addresses);
if (err)
MS_ABORT("uv_interface_addresses() failed: %s", uv_strerror(err));
for (int i=0; i<num_addresses; i++) {
uv_interface_address_t address = addresses[i];
// Ignore internal addresses.
if (address.is_internal)
continue;
int family;
MS_PORT port;
std::string ip;
Utils::IP::GetAddressInfo((struct sockaddr*)(&address.address.address4), &family, ip, &port);
if (family != requested_family)
continue;
switch(family) {
case AF_INET:
// Ignore if already got an IPv4.
if (! ipv4.empty())
continue;
// Check if it is bindable.
if (! IsBindableIP(ip, AF_INET, &_bind_err)) {
MS_DEBUG("ignoring '%s' for RTC.listenIPv4: %s", ip.c_str(), std::strerror(errno));
continue;
}
MS_DEBUG("auto-discovered '%s' for RTC.listenIPv4", ip.c_str());
ipv4 = ip;
break;
case AF_INET6:
// Ignore if already got an IPv6.
if (! ipv6.empty())
continue;
// Check if it is bindable.
if (! IsBindableIP(ip, AF_INET6, &_bind_err)) {
MS_DEBUG("ignoring '%s' for RTC.listenIPv6: %s", ip.c_str(), std::strerror(errno));
continue;
}
MS_DEBUG("auto-discovered '%s' for RTC.listenIPv6", ip.c_str());
ipv6 = ip;
break;
}
}
if (! ipv4.empty()) {
Settings::configuration.RTC.listenIPv4 = ipv4;
Settings::configuration.RTC.hasIPv4 = true;
}
if (! ipv6.empty()) {
Settings::configuration.RTC.listenIPv6 = ipv6;
Settings::configuration.RTC.hasIPv6 = true;
}
uv_free_interface_addresses(addresses, num_addresses);
}
bool Settings::IsBindableIP(const std::string &ip, int family, int* _bind_err) {
MS_TRACE();
struct sockaddr_storage bind_addr;
int bind_socket;
int err = 0;
bool bind_ok;
switch (family) {
case AF_INET:
err = uv_ip4_addr(ip.c_str(), 0, (struct sockaddr_in*)&bind_addr);
if (err)
MS_ABORT("uv_ipv4_addr() failed: %s", uv_strerror(err));
bind_socket = socket(AF_INET, SOCK_DGRAM, 0);
if (bind_socket == -1)
MS_ABORT("socket() failed: %s", std::strerror(errno));
err = bind(bind_socket, (const struct sockaddr*)&bind_addr, sizeof(struct sockaddr_in));
break;
case AF_INET6:
uv_ip6_addr(ip.c_str(), 0, (struct sockaddr_in6*)&bind_addr);
if (err)
MS_ABORT("uv_ipv6_addr() failed: %s", uv_strerror(err));
bind_socket = socket(AF_INET6, SOCK_DGRAM, 0);
if (bind_socket == -1)
MS_ABORT("socket() failed: %s", std::strerror(errno));
err = bind(bind_socket, (const struct sockaddr*)&bind_addr, sizeof(struct sockaddr_in6));
break;
default:
MS_ABORT("unknown family");
}
if (err == 0) {
bind_ok = true;
}
else {
bind_ok = false;
*_bind_err = errno;
}
err = close(bind_socket);
if (err)
MS_ABORT("close() failed: %s", std::strerror(errno));
return bind_ok;
}
void Settings::SetRTCports(MS_PORT minPort, MS_PORT maxPort) {
MS_TRACE();
if (minPort < 1024)
MS_THROW_ERROR("RTC.minPort must be greater or equal than 1024");
if (maxPort == 0)
MS_THROW_ERROR("RTC.maxPort can not be 0");
// Make minPort even.
minPort &= ~1;
// Make maxPort odd.
if (maxPort % 2 == 0)
maxPort--;
if ((maxPort - minPort) < 99)
MS_THROW_ERROR("RTC.maxPort must be at least 99 ports higher than RTC.minPort");
Settings::configuration.RTC.minPort = minPort;
Settings::configuration.RTC.maxPort = maxPort;
}
void Settings::SetDtlsCertificateAndPrivateKeyFiles(std::string& dtlsCertificateFile, std::string& dtlsPrivateKeyFile) {
MS_TRACE();
try {
Utils::File::CheckFile(dtlsCertificateFile.c_str());
}
catch (const MediaSoupError &error) {
MS_THROW_ERROR("RTC.dtlsCertificateFile: %s", error.what());
}
try {
Utils::File::CheckFile(dtlsPrivateKeyFile.c_str());
}
catch (const MediaSoupError &error) {
MS_THROW_ERROR("RTC.dtlsPrivateKeyFile: %s", error.what());
}
Settings::configuration.RTC.dtlsCertificateFile = dtlsCertificateFile;
Settings::configuration.RTC.dtlsPrivateKeyFile = dtlsPrivateKeyFile;
}
void Settings::ConfigurationPostCheck() {
MS_TRACE();
// RTC must have at least 'listenIPv4' or 'listenIPv6'.
if (! Settings::configuration.RTC.hasIPv4 && ! Settings::configuration.RTC.hasIPv6)
MS_EXIT_FAILURE("at least RTC.listenIPv4 or RTC.listenIPv6 must be enabled");
}
#define MS_CLASS "Utils::Crypto"
#include "Utils.h"
#include "Logger.h"
#include <openssl/sha.h>
namespace Utils {
/* Static variables. */
__thread unsigned int Crypto::seed;
__thread HMAC_CTX Crypto::hmacSha1Ctx;
__thread MS_BYTE Crypto::hmacSha1Buffer[20]; // SHA-1 result is 20 bytes long.
const MS_4BYTES Crypto::crc32Table[] = {
0x00000000, 0x77073096, 0xee0e612c, 0x990951ba, 0x076dc419, 0x706af48f,
0xe963a535, 0x9e6495a3, 0x0edb8832, 0x79dcb8a4, 0xe0d5e91e, 0x97d2d988,
0x09b64c2b, 0x7eb17cbd, 0xe7b82d07, 0x90bf1d91, 0x1db71064, 0x6ab020f2,
0xf3b97148, 0x84be41de, 0x1adad47d, 0x6ddde4eb, 0xf4d4b551, 0x83d385c7,
0x136c9856, 0x646ba8c0, 0xfd62f97a, 0x8a65c9ec, 0x14015c4f, 0x63066cd9,
0xfa0f3d63, 0x8d080df5, 0x3b6e20c8, 0x4c69105e, 0xd56041e4, 0xa2677172,
0x3c03e4d1, 0x4b04d447, 0xd20d85fd, 0xa50ab56b, 0x35b5a8fa, 0x42b2986c,
0xdbbbc9d6, 0xacbcf940, 0x32d86ce3, 0x45df5c75, 0xdcd60dcf, 0xabd13d59,
0x26d930ac, 0x51de003a, 0xc8d75180, 0xbfd06116, 0x21b4f4b5, 0x56b3c423,
0xcfba9599, 0xb8bda50f, 0x2802b89e, 0x5f058808, 0xc60cd9b2, 0xb10be924,
0x2f6f7c87, 0x58684c11, 0xc1611dab, 0xb6662d3d, 0x76dc4190, 0x01db7106,
0x98d220bc, 0xefd5102a, 0x71b18589, 0x06b6b51f, 0x9fbfe4a5, 0xe8b8d433,
0x7807c9a2, 0x0f00f934, 0x9609a88e, 0xe10e9818, 0x7f6a0dbb, 0x086d3d2d,
0x91646c97, 0xe6635c01, 0x6b6b51f4, 0x1c6c6162, 0x856530d8, 0xf262004e,
0x6c0695ed, 0x1b01a57b, 0x8208f4c1, 0xf50fc457, 0x65b0d9c6, 0x12b7e950,
0x8bbeb8ea, 0xfcb9887c, 0x62dd1ddf, 0x15da2d49, 0x8cd37cf3, 0xfbd44c65,
0x4db26158, 0x3ab551ce, 0xa3bc0074, 0xd4bb30e2, 0x4adfa541, 0x3dd895d7,
0xa4d1c46d, 0xd3d6f4fb, 0x4369e96a, 0x346ed9fc, 0xad678846, 0xda60b8d0,
0x44042d73, 0x33031de5, 0xaa0a4c5f, 0xdd0d7cc9, 0x5005713c, 0x270241aa,
0xbe0b1010, 0xc90c2086, 0x5768b525, 0x206f85b3, 0xb966d409, 0xce61e49f,
0x5edef90e, 0x29d9c998, 0xb0d09822, 0xc7d7a8b4, 0x59b33d17, 0x2eb40d81,
0xb7bd5c3b, 0xc0ba6cad, 0xedb88320, 0x9abfb3b6, 0x03b6e20c, 0x74b1d29a,
0xead54739, 0x9dd277af, 0x04db2615, 0x73dc1683, 0xe3630b12, 0x94643b84,
0x0d6d6a3e, 0x7a6a5aa8, 0xe40ecf0b, 0x9309ff9d, 0x0a00ae27, 0x7d079eb1,
0xf00f9344, 0x8708a3d2, 0x1e01f268, 0x6906c2fe, 0xf762575d, 0x806567cb,
0x196c3671, 0x6e6b06e7, 0xfed41b76, 0x89d32be0, 0x10da7a5a, 0x67dd4acc,
0xf9b9df6f, 0x8ebeeff9, 0x17b7be43, 0x60b08ed5, 0xd6d6a3e8, 0xa1d1937e,
0x38d8c2c4, 0x4fdff252, 0xd1bb67f1, 0xa6bc5767, 0x3fb506dd, 0x48b2364b,
0xd80d2bda, 0xaf0a1b4c, 0x36034af6, 0x41047a60, 0xdf60efc3, 0xa867df55,
0x316e8eef, 0x4669be79, 0xcb61b38c, 0xbc66831a, 0x256fd2a0, 0x5268e236,
0xcc0c7795, 0xbb0b4703, 0x220216b9, 0x5505262f, 0xc5ba3bbe, 0xb2bd0b28,
0x2bb45a92, 0x5cb36a04, 0xc2d7ffa7, 0xb5d0cf31, 0x2cd99e8b, 0x5bdeae1d,
0x9b64c2b0, 0xec63f226, 0x756aa39c, 0x026d930a, 0x9c0906a9, 0xeb0e363f,
0x72076785, 0x05005713, 0x95bf4a82, 0xe2b87a14, 0x7bb12bae, 0x0cb61b38,
0x92d28e9b, 0xe5d5be0d, 0x7cdcefb7, 0x0bdbdf21, 0x86d3d2d4, 0xf1d4e242,
0x68ddb3f8, 0x1fda836e, 0x81be16cd, 0xf6b9265b, 0x6fb077e1, 0x18b74777,
0x88085ae6, 0xff0f6a70, 0x66063bca, 0x11010b5c, 0x8f659eff, 0xf862ae69,
0x616bffd3, 0x166ccf45, 0xa00ae278, 0xd70dd2ee, 0x4e048354, 0x3903b3c2,
0xa7672661, 0xd06016f7, 0x4969474d, 0x3e6e77db, 0xaed16a4a, 0xd9d65adc,
0x40df0b66, 0x37d83bf0, 0xa9bcae53, 0xdebb9ec5, 0x47b2cf7f, 0x30b5ffe9,
0xbdbdf21c, 0xcabac28a, 0x53b39330, 0x24b4a3a6, 0xbad03605, 0xcdd70693,
0x54de5729, 0x23d967bf, 0xb3667a2e, 0xc4614ab8, 0x5d681b02, 0x2a6f2b94,
0xb40bbe37, 0xc30c8ea1, 0x5a05df1b, 0x2d02ef8d
};
/* Static methods. */
void Crypto::ThreadInit() {
MS_TRACE();
// Init the seed of each thread with a random number taken from the address
// of the seed variable itself (which is different for each thread).
Crypto::seed = (unsigned int)(unsigned long)&Crypto::seed;
// Create an OpenSSL HMAC_CTX context for HMAC SHA1 calculation.
HMAC_CTX_init(&Crypto::hmacSha1Ctx);
}
void Crypto::ThreadDestroy() {
MS_TRACE();
HMAC_CTX_cleanup(&Crypto::hmacSha1Ctx);
}
const MS_BYTE* Crypto::HMAC_SHA1(const std::string &key, const MS_BYTE* data, size_t len) {
MS_TRACE();
int ret;
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());
ret = HMAC_Update(&Crypto::hmacSha1Ctx, (const unsigned char*)data, (int)len);
MS_ASSERT(ret == 1, "OpenSSL HMAC_Update() failed with key '%s' and data length %zu bytes", key.c_str(), len);
unsigned int result_len;
ret = HMAC_Final(&Crypto::hmacSha1Ctx, (unsigned char *)Crypto::hmacSha1Buffer, &result_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);
return Crypto::hmacSha1Buffer;
}
} // namespace Utils
#define MS_CLASS "Utils::File"
#include "Utils.h"
#include "MediaSoupError.h"
#include "Logger.h"
#include <cerrno>
#include <unistd.h> // access(), R_OK
#include <sys/stat.h> // stat()
namespace Utils {
void Utils::File::CheckFile(const char* file) {
MS_TRACE();
struct stat file_stat;
int err;
// Ensure the given file exists.
err = stat(file, &file_stat);
if (err)
MS_THROW_ERROR("cannot read file '%s': %s", file, std::strerror(errno));
// Ensure it is a regular file.
if (! S_ISREG(file_stat.st_mode))
MS_THROW_ERROR("'%s' is not a regular file", file);
// Ensure it is readable.
err = access(file, R_OK);
if (err)
MS_THROW_ERROR("cannot read file '%s': %s", file, std::strerror(errno));
}
} // namespace Utils
#line 1 "src/Utils/IP.rl"
#define MS_CLASS "Utils::IP"
#include "Utils.h"
#include "Logger.h"
#include <uv.h>
namespace Utils {
int IP::GetFamily(const char *ip, size_t ip_len) {
MS_TRACE();
int ip_family = 0;
/**
* Ragel: machine definition
*/
#line 36 "src/Utils/IP.rl"
/**
* Ragel: %%write data
* This generates Ragel's static variables.
*/
#line 32 "src/Utils/IP.cpp"
static const int IPParser_start = 1;
#line 44 "src/Utils/IP.rl"
// Used by Ragel:
size_t cs;
const unsigned char* p;
const unsigned char* pe;
p = (const unsigned char*)ip;
pe = p + ip_len;
/**
* Ragel: %%write init
*/
#line 54 "src/Utils/IP.cpp"
{
cs = IPParser_start;
}
#line 57 "src/Utils/IP.rl"
/**
* Ragel: %%write exec
* This updates cs variable needed by Ragel.
*/
#line 66 "src/Utils/IP.cpp"
{
if ( p == pe )
goto _test_eof;
switch ( cs )
{
case 1:
switch( (*p) ) {
case 48u: goto st2;
case 49u: goto st76;
case 50u: goto st79;
case 58u: goto st83;
}
if ( (*p) < 65u ) {
if ( 51u <= (*p) && (*p) <= 57u )
goto st82;
} else if ( (*p) > 70u ) {
if ( 97u <= (*p) && (*p) <= 102u )
goto st85;
} else
goto st85;
goto st0;
st0:
cs = 0;
goto _out;
st2:
if ( ++p == pe )
goto _test_eof2;
case 2:
switch( (*p) ) {
case 46u: goto st3;
case 58u: goto st19;
}
if ( (*p) < 65u ) {
if ( 48u <= (*p) && (*p) <= 57u )
goto st16;
} else if ( (*p) > 70u ) {
if ( 97u <= (*p) && (*p) <= 102u )
goto st16;
} else
goto st16;
goto st0;
st3:
if ( ++p == pe )
goto _test_eof3;
case 3:
switch( (*p) ) {
case 48u: goto st4;
case 49u: goto st12;
case 50u: goto st14;
}
if ( 51u <= (*p) && (*p) <= 57u )
goto st13;
goto st0;
st4:
if ( ++p == pe )
goto _test_eof4;
case 4:
if ( (*p) == 46u )
goto st5;
goto st0;
st5:
if ( ++p == pe )
goto _test_eof5;
case 5:
switch( (*p) ) {
case 48u: goto st6;
case 49u: goto st8;
case 50u: goto st10;
}
if ( 51u <= (*p) && (*p) <= 57u )
goto st9;
goto st0;
st6:
if ( ++p == pe )
goto _test_eof6;
case 6:
if ( (*p) == 46u )
goto st7;
goto st0;
st7:
if ( ++p == pe )
goto _test_eof7;
case 7:
switch( (*p) ) {
case 48u: goto tr20;
case 49u: goto tr21;
case 50u: goto tr22;
}
if ( 51u <= (*p) && (*p) <= 57u )
goto tr23;
goto st0;
tr20:
#line 24 "src/Utils/IP.rl"
{
ip_family = AF_INET;
}
goto st86;
tr77:
#line 28 "src/Utils/IP.rl"
{
ip_family = AF_INET6;
}
goto st86;
st86:
if ( ++p == pe )
goto _test_eof86;
case 86:
#line 174 "src/Utils/IP.cpp"
goto st0;
tr21:
#line 24 "src/Utils/IP.rl"
{
ip_family = AF_INET;
}
goto st87;
st87:
if ( ++p == pe )
goto _test_eof87;
case 87:
#line 186 "src/Utils/IP.cpp"
if ( 48u <= (*p) && (*p) <= 57u )
goto tr23;
goto st0;
tr23:
#line 24 "src/Utils/IP.rl"
{
ip_family = AF_INET;
}
goto st88;
st88:
if ( ++p == pe )
goto _test_eof88;
case 88:
#line 200 "src/Utils/IP.cpp"
if ( 48u <= (*p) && (*p) <= 57u )
goto tr20;
goto st0;
tr22:
#line 24 "src/Utils/IP.rl"
{
ip_family = AF_INET;
}
goto st89;
st89:
if ( ++p == pe )
goto _test_eof89;
case 89:
#line 214 "src/Utils/IP.cpp"
if ( (*p) == 53u )
goto tr120;
if ( (*p) > 52u ) {
if ( 54u <= (*p) && (*p) <= 57u )
goto tr20;
} else if ( (*p) >= 48u )
goto tr23;
goto st0;
tr120:
#line 24 "src/Utils/IP.rl"
{
ip_family = AF_INET;
}
goto st90;
st90:
if ( ++p == pe )
goto _test_eof90;
case 90:
#line 233 "src/Utils/IP.cpp"
if ( 48u <= (*p) && (*p) <= 53u )
goto tr20;
goto st0;
st8:
if ( ++p == pe )
goto _test_eof8;
case 8:
if ( (*p) == 46u )
goto st7;
if ( 48u <= (*p) && (*p) <= 57u )
goto st9;
goto st0;
st9:
if ( ++p == pe )
goto _test_eof9;
case 9:
if ( (*p) == 46u )
goto st7;
if ( 48u <= (*p) && (*p) <= 57u )
goto st6;
goto st0;
st10:
if ( ++p == pe )
goto _test_eof10;
case 10:
switch( (*p) ) {
case 46u: goto st7;
case 53u: goto st11;
}
if ( (*p) > 52u ) {
if ( 54u <= (*p) && (*p) <= 57u )
goto st6;
} else if ( (*p) >= 48u )
goto st9;
goto st0;
st11:
if ( ++p == pe )
goto _test_eof11;
case 11:
if ( (*p) == 46u )
goto st7;
if ( 48u <= (*p) && (*p) <= 53u )
goto st6;
goto st0;
st12:
if ( ++p == pe )
goto _test_eof12;
case 12:
if ( (*p) == 46u )
goto st5;
if ( 48u <= (*p) && (*p) <= 57u )
goto st13;
goto st0;
st13:
if ( ++p == pe )
goto _test_eof13;
case 13:
if ( (*p) == 46u )
goto st5;
if ( 48u <= (*p) && (*p) <= 57u )
goto st4;
goto st0;
st14:
if ( ++p == pe )
goto _test_eof14;
case 14:
switch( (*p) ) {
case 46u: goto st5;
case 53u: goto st15;
}
if ( (*p) > 52u ) {
if ( 54u <= (*p) && (*p) <= 57u )
goto st4;
} else if ( (*p) >= 48u )
goto st13;
goto st0;
st15:
if ( ++p == pe )
goto _test_eof15;
case 15:
if ( (*p) == 46u )
goto st5;
if ( 48u <= (*p) && (*p) <= 53u )
goto st4;
goto st0;
st16:
if ( ++p == pe )
goto _test_eof16;
case 16:
if ( (*p) == 58u )
goto st19;
if ( (*p) < 65u ) {
if ( 48u <= (*p) && (*p) <= 57u )
goto st17;
} else if ( (*p) > 70u ) {
if ( 97u <= (*p) && (*p) <= 102u )
goto st17;
} else
goto st17;
goto st0;
st17:
if ( ++p == pe )
goto _test_eof17;
case 17:
if ( (*p) == 58u )
goto st19;
if ( (*p) < 65u ) {
if ( 48u <= (*p) && (*p) <= 57u )
goto st18;
} else if ( (*p) > 70u ) {
if ( 97u <= (*p) && (*p) <= 102u )
goto st18;
} else
goto st18;
goto st0;
st18:
if ( ++p == pe )
goto _test_eof18;
case 18:
if ( (*p) == 58u )
goto st19;
goto st0;
st19:
if ( ++p == pe )
goto _test_eof19;
case 19:
if ( (*p) == 58u )
goto tr29;
if ( (*p) < 65u ) {
if ( 48u <= (*p) && (*p) <= 57u )
goto st20;
} else if ( (*p) > 70u ) {
if ( 97u <= (*p) && (*p) <= 102u )
goto st20;
} else
goto st20;
goto st0;
st20:
if ( ++p == pe )
goto _test_eof20;
case 20:
if ( (*p) == 58u )
goto st24;
if ( (*p) < 65u ) {
if ( 48u <= (*p) && (*p) <= 57u )
goto st21;
} else if ( (*p) > 70u ) {
if ( 97u <= (*p) && (*p) <= 102u )
goto st21;
} else
goto st21;
goto st0;
st21:
if ( ++p == pe )
goto _test_eof21;
case 21:
if ( (*p) == 58u )
goto st24;
if ( (*p) < 65u ) {
if ( 48u <= (*p) && (*p) <= 57u )
goto st22;
} else if ( (*p) > 70u ) {
if ( 97u <= (*p) && (*p) <= 102u )
goto st22;
} else
goto st22;
goto st0;
st22:
if ( ++p == pe )
goto _test_eof22;
case 22:
if ( (*p) == 58u )
goto st24;
if ( (*p) < 65u ) {
if ( 48u <= (*p) && (*p) <= 57u )
goto st23;
} else if ( (*p) > 70u ) {
if ( 97u <= (*p) && (*p) <= 102u )
goto st23;
} else
goto st23;
goto st0;
st23:
if ( ++p == pe )
goto _test_eof23;
case 23:
if ( (*p) == 58u )
goto st24;
goto st0;
st24:
if ( ++p == pe )
goto _test_eof24;
case 24:
if ( (*p) == 58u )
goto tr35;
if ( (*p) < 65u ) {
if ( 48u <= (*p) && (*p) <= 57u )
goto st25;
} else if ( (*p) > 70u ) {
if ( 97u <= (*p) && (*p) <= 102u )
goto st25;
} else
goto st25;
goto st0;
st25:
if ( ++p == pe )
goto _test_eof25;
case 25:
if ( (*p) == 58u )
goto st29;
if ( (*p) < 65u ) {
if ( 48u <= (*p) && (*p) <= 57u )
goto st26;
} else if ( (*p) > 70u ) {
if ( 97u <= (*p) && (*p) <= 102u )
goto st26;
} else
goto st26;
goto st0;
st26:
if ( ++p == pe )
goto _test_eof26;
case 26:
if ( (*p) == 58u )
goto st29;
if ( (*p) < 65u ) {
if ( 48u <= (*p) && (*p) <= 57u )
goto st27;
} else if ( (*p) > 70u ) {
if ( 97u <= (*p) && (*p) <= 102u )
goto st27;
} else
goto st27;
goto st0;
st27:
if ( ++p == pe )
goto _test_eof27;
case 27:
if ( (*p) == 58u )
goto st29;
if ( (*p) < 65u ) {
if ( 48u <= (*p) && (*p) <= 57u )
goto st28;
} else if ( (*p) > 70u ) {
if ( 97u <= (*p) && (*p) <= 102u )
goto st28;
} else
goto st28;
goto st0;
st28:
if ( ++p == pe )
goto _test_eof28;
case 28:
if ( (*p) == 58u )
goto st29;
goto st0;
st29:
if ( ++p == pe )
goto _test_eof29;
case 29:
if ( (*p) == 58u )
goto tr41;
if ( (*p) < 65u ) {
if ( 48u <= (*p) && (*p) <= 57u )
goto st30;
} else if ( (*p) > 70u ) {
if ( 97u <= (*p) && (*p) <= 102u )
goto st30;
} else
goto st30;
goto st0;
st30:
if ( ++p == pe )
goto _test_eof30;
case 30:
if ( (*p) == 58u )
goto st34;
if ( (*p) < 65u ) {
if ( 48u <= (*p) && (*p) <= 57u )
goto st31;
} else if ( (*p) > 70u ) {
if ( 97u <= (*p) && (*p) <= 102u )
goto st31;
} else
goto st31;
goto st0;
st31:
if ( ++p == pe )
goto _test_eof31;
case 31:
if ( (*p) == 58u )
goto st34;
if ( (*p) < 65u ) {
if ( 48u <= (*p) && (*p) <= 57u )
goto st32;
} else if ( (*p) > 70u ) {
if ( 97u <= (*p) && (*p) <= 102u )
goto st32;
} else
goto st32;
goto st0;
st32:
if ( ++p == pe )
goto _test_eof32;
case 32:
if ( (*p) == 58u )
goto st34;
if ( (*p) < 65u ) {
if ( 48u <= (*p) && (*p) <= 57u )
goto st33;
} else if ( (*p) > 70u ) {
if ( 97u <= (*p) && (*p) <= 102u )
goto st33;
} else
goto st33;
goto st0;
st33:
if ( ++p == pe )
goto _test_eof33;
case 33:
if ( (*p) == 58u )
goto st34;
goto st0;
st34:
if ( ++p == pe )
goto _test_eof34;
case 34:
if ( (*p) == 58u )
goto tr47;
if ( (*p) < 65u ) {
if ( 48u <= (*p) && (*p) <= 57u )
goto st35;
} else if ( (*p) > 70u ) {
if ( 97u <= (*p) && (*p) <= 102u )
goto st35;
} else
goto st35;
goto st0;
st35:
if ( ++p == pe )
goto _test_eof35;
case 35:
if ( (*p) == 58u )
goto st39;
if ( (*p) < 65u ) {
if ( 48u <= (*p) && (*p) <= 57u )
goto st36;
} else if ( (*p) > 70u ) {
if ( 97u <= (*p) && (*p) <= 102u )
goto st36;
} else
goto st36;
goto st0;
st36:
if ( ++p == pe )
goto _test_eof36;
case 36:
if ( (*p) == 58u )
goto st39;
if ( (*p) < 65u ) {
if ( 48u <= (*p) && (*p) <= 57u )
goto st37;
} else if ( (*p) > 70u ) {
if ( 97u <= (*p) && (*p) <= 102u )
goto st37;
} else
goto st37;
goto st0;
st37:
if ( ++p == pe )
goto _test_eof37;
case 37:
if ( (*p) == 58u )
goto st39;
if ( (*p) < 65u ) {
if ( 48u <= (*p) && (*p) <= 57u )
goto st38;
} else if ( (*p) > 70u ) {
if ( 97u <= (*p) && (*p) <= 102u )
goto st38;
} else
goto st38;
goto st0;
st38:
if ( ++p == pe )
goto _test_eof38;
case 38:
if ( (*p) == 58u )
goto st39;
goto st0;
st39:
if ( ++p == pe )
goto _test_eof39;
case 39:
if ( (*p) == 58u )
goto tr53;
if ( (*p) < 65u ) {
if ( 48u <= (*p) && (*p) <= 57u )
goto st40;
} else if ( (*p) > 70u ) {
if ( 97u <= (*p) && (*p) <= 102u )
goto st40;
} else
goto st40;
goto st0;
st40:
if ( ++p == pe )
goto _test_eof40;
case 40:
if ( (*p) == 58u )
goto st44;
if ( (*p) < 65u ) {
if ( 48u <= (*p) && (*p) <= 57u )
goto st41;
} else if ( (*p) > 70u ) {
if ( 97u <= (*p) && (*p) <= 102u )
goto st41;
} else
goto st41;
goto st0;
st41:
if ( ++p == pe )
goto _test_eof41;
case 41:
if ( (*p) == 58u )
goto st44;
if ( (*p) < 65u ) {
if ( 48u <= (*p) && (*p) <= 57u )
goto st42;
} else if ( (*p) > 70u ) {
if ( 97u <= (*p) && (*p) <= 102u )
goto st42;
} else
goto st42;
goto st0;
st42:
if ( ++p == pe )
goto _test_eof42;
case 42:
if ( (*p) == 58u )
goto st44;
if ( (*p) < 65u ) {
if ( 48u <= (*p) && (*p) <= 57u )
goto st43;
} else if ( (*p) > 70u ) {
if ( 97u <= (*p) && (*p) <= 102u )
goto st43;
} else
goto st43;
goto st0;
st43:
if ( ++p == pe )
goto _test_eof43;
case 43:
if ( (*p) == 58u )
goto st44;
goto st0;
st44:
if ( ++p == pe )
goto _test_eof44;
case 44:
switch( (*p) ) {
case 48u: goto st45;
case 49u: goto st63;
case 50u: goto st66;
case 58u: goto tr62;
}
if ( (*p) < 65u ) {
if ( 51u <= (*p) && (*p) <= 57u )
goto st69;
} else if ( (*p) > 70u ) {
if ( 97u <= (*p) && (*p) <= 102u )
goto st70;
} else
goto st70;
goto st0;
st45:
if ( ++p == pe )
goto _test_eof45;
case 45:
switch( (*p) ) {
case 46u: goto st46;
case 58u: goto st62;
}
if ( (*p) < 65u ) {
if ( 48u <= (*p) && (*p) <= 57u )
goto st59;
} else if ( (*p) > 70u ) {
if ( 97u <= (*p) && (*p) <= 102u )
goto st59;
} else
goto st59;
goto st0;
st46:
if ( ++p == pe )
goto _test_eof46;
case 46:
switch( (*p) ) {
case 48u: goto st47;
case 49u: goto st55;
case 50u: goto st57;
}
if ( 51u <= (*p) && (*p) <= 57u )
goto st56;
goto st0;
st47:
if ( ++p == pe )
goto _test_eof47;
case 47:
if ( (*p) == 46u )
goto st48;
goto st0;
st48:
if ( ++p == pe )
goto _test_eof48;
case 48:
switch( (*p) ) {
case 48u: goto st49;
case 49u: goto st51;
case 50u: goto st53;
}
if ( 51u <= (*p) && (*p) <= 57u )
goto st52;
goto st0;
st49:
if ( ++p == pe )
goto _test_eof49;
case 49:
if ( (*p) == 46u )
goto st50;
goto st0;
st50:
if ( ++p == pe )
goto _test_eof50;
case 50:
switch( (*p) ) {
case 48u: goto tr77;
case 49u: goto tr78;
case 50u: goto tr79;
}
if ( 51u <= (*p) && (*p) <= 57u )
goto tr80;
goto st0;
tr78:
#line 28 "src/Utils/IP.rl"
{
ip_family = AF_INET6;
}
goto st91;
st91:
if ( ++p == pe )
goto _test_eof91;
case 91:
#line 787 "src/Utils/IP.cpp"
if ( 48u <= (*p) && (*p) <= 57u )
goto tr80;
goto st0;
tr80:
#line 28 "src/Utils/IP.rl"
{
ip_family = AF_INET6;
}
goto st92;
st92:
if ( ++p == pe )
goto _test_eof92;
case 92:
#line 801 "src/Utils/IP.cpp"
if ( 48u <= (*p) && (*p) <= 57u )
goto tr77;
goto st0;
tr79:
#line 28 "src/Utils/IP.rl"
{
ip_family = AF_INET6;
}
goto st93;
st93:
if ( ++p == pe )
goto _test_eof93;
case 93:
#line 815 "src/Utils/IP.cpp"
if ( (*p) == 53u )
goto tr121;
if ( (*p) > 52u ) {
if ( 54u <= (*p) && (*p) <= 57u )
goto tr77;
} else if ( (*p) >= 48u )
goto tr80;
goto st0;
tr121:
#line 28 "src/Utils/IP.rl"
{
ip_family = AF_INET6;
}
goto st94;
st94:
if ( ++p == pe )
goto _test_eof94;
case 94:
#line 834 "src/Utils/IP.cpp"
if ( 48u <= (*p) && (*p) <= 53u )
goto tr77;
goto st0;
st51:
if ( ++p == pe )
goto _test_eof51;
case 51:
if ( (*p) == 46u )
goto st50;
if ( 48u <= (*p) && (*p) <= 57u )
goto st52;
goto st0;
st52:
if ( ++p == pe )
goto _test_eof52;
case 52:
if ( (*p) == 46u )
goto st50;
if ( 48u <= (*p) && (*p) <= 57u )
goto st49;
goto st0;
st53:
if ( ++p == pe )
goto _test_eof53;
case 53:
switch( (*p) ) {
case 46u: goto st50;
case 53u: goto st54;
}
if ( (*p) > 52u ) {
if ( 54u <= (*p) && (*p) <= 57u )
goto st49;
} else if ( (*p) >= 48u )
goto st52;
goto st0;
st54:
if ( ++p == pe )
goto _test_eof54;
case 54:
if ( (*p) == 46u )
goto st50;
if ( 48u <= (*p) && (*p) <= 53u )
goto st49;
goto st0;
st55:
if ( ++p == pe )
goto _test_eof55;
case 55:
if ( (*p) == 46u )
goto st48;
if ( 48u <= (*p) && (*p) <= 57u )
goto st56;
goto st0;
st56:
if ( ++p == pe )
goto _test_eof56;
case 56:
if ( (*p) == 46u )
goto st48;
if ( 48u <= (*p) && (*p) <= 57u )
goto st47;
goto st0;
st57:
if ( ++p == pe )
goto _test_eof57;
case 57:
switch( (*p) ) {
case 46u: goto st48;
case 53u: goto st58;
}
if ( (*p) > 52u ) {
if ( 54u <= (*p) && (*p) <= 57u )
goto st47;
} else if ( (*p) >= 48u )
goto st56;
goto st0;
st58:
if ( ++p == pe )
goto _test_eof58;
case 58:
if ( (*p) == 46u )
goto st48;
if ( 48u <= (*p) && (*p) <= 53u )
goto st47;
goto st0;
st59:
if ( ++p == pe )
goto _test_eof59;
case 59:
if ( (*p) == 58u )
goto st62;
if ( (*p) < 65u ) {
if ( 48u <= (*p) && (*p) <= 57u )
goto st60;
} else if ( (*p) > 70u ) {
if ( 97u <= (*p) && (*p) <= 102u )
goto st60;
} else
goto st60;
goto st0;
st60:
if ( ++p == pe )
goto _test_eof60;
case 60:
if ( (*p) == 58u )
goto st62;
if ( (*p) < 65u ) {
if ( 48u <= (*p) && (*p) <= 57u )
goto st61;
} else if ( (*p) > 70u ) {
if ( 97u <= (*p) && (*p) <= 102u )
goto st61;
} else
goto st61;
goto st0;
st61:
if ( ++p == pe )
goto _test_eof61;
case 61:
if ( (*p) == 58u )
goto st62;
goto st0;
st62:
if ( ++p == pe )
goto _test_eof62;
case 62:
if ( (*p) == 58u )
goto tr77;
if ( (*p) < 65u ) {
if ( 48u <= (*p) && (*p) <= 57u )
goto tr85;
} else if ( (*p) > 70u ) {
if ( 97u <= (*p) && (*p) <= 102u )
goto tr85;
} else
goto tr85;
goto st0;
tr85:
#line 28 "src/Utils/IP.rl"
{
ip_family = AF_INET6;
}
goto st95;
st95:
if ( ++p == pe )
goto _test_eof95;
case 95:
#line 982 "src/Utils/IP.cpp"
if ( (*p) < 65u ) {
if ( 48u <= (*p) && (*p) <= 57u )
goto tr122;
} else if ( (*p) > 70u ) {
if ( 97u <= (*p) && (*p) <= 102u )
goto tr122;
} else
goto tr122;
goto st0;
tr122:
#line 28 "src/Utils/IP.rl"
{
ip_family = AF_INET6;
}
goto st96;
st96:
if ( ++p == pe )
goto _test_eof96;
case 96:
#line 1002 "src/Utils/IP.cpp"
if ( (*p) < 65u ) {
if ( 48u <= (*p) && (*p) <= 57u )
goto tr123;
} else if ( (*p) > 70u ) {
if ( 97u <= (*p) && (*p) <= 102u )
goto tr123;
} else
goto tr123;
goto st0;
tr123:
#line 28 "src/Utils/IP.rl"
{
ip_family = AF_INET6;
}
goto st97;
st97:
if ( ++p == pe )
goto _test_eof97;
case 97:
#line 1022 "src/Utils/IP.cpp"
if ( (*p) < 65u ) {
if ( 48u <= (*p) && (*p) <= 57u )
goto tr77;
} else if ( (*p) > 70u ) {
if ( 97u <= (*p) && (*p) <= 102u )
goto tr77;
} else
goto tr77;
goto st0;
st63:
if ( ++p == pe )
goto _test_eof63;
case 63:
switch( (*p) ) {
case 46u: goto st46;
case 58u: goto st62;
}
if ( (*p) < 65u ) {
if ( 48u <= (*p) && (*p) <= 57u )
goto st64;
} else if ( (*p) > 70u ) {
if ( 97u <= (*p) && (*p) <= 102u )
goto st59;
} else
goto st59;
goto st0;
st64:
if ( ++p == pe )
goto _test_eof64;
case 64:
switch( (*p) ) {
case 46u: goto st46;
case 58u: goto st62;
}
if ( (*p) < 65u ) {
if ( 48u <= (*p) && (*p) <= 57u )
goto st65;
} else if ( (*p) > 70u ) {
if ( 97u <= (*p) && (*p) <= 102u )
goto st60;
} else
goto st60;
goto st0;
st65:
if ( ++p == pe )
goto _test_eof65;
case 65:
switch( (*p) ) {
case 46u: goto st46;
case 58u: goto st62;
}
if ( (*p) < 65u ) {
if ( 48u <= (*p) && (*p) <= 57u )
goto st61;
} else if ( (*p) > 70u ) {
if ( 97u <= (*p) && (*p) <= 102u )
goto st61;
} else
goto st61;
goto st0;
st66:
if ( ++p == pe )
goto _test_eof66;
case 66:
switch( (*p) ) {
case 46u: goto st46;
case 53u: goto st67;
case 58u: goto st62;
}
if ( (*p) < 54u ) {
if ( 48u <= (*p) && (*p) <= 52u )
goto st64;
} else if ( (*p) > 57u ) {
if ( (*p) > 70u ) {
if ( 97u <= (*p) && (*p) <= 102u )
goto st59;
} else if ( (*p) >= 65u )
goto st59;
} else
goto st68;
goto st0;
st67:
if ( ++p == pe )
goto _test_eof67;
case 67:
switch( (*p) ) {
case 46u: goto st46;
case 58u: goto st62;
}
if ( (*p) < 54u ) {
if ( 48u <= (*p) && (*p) <= 53u )
goto st65;
} else if ( (*p) > 57u ) {
if ( (*p) > 70u ) {
if ( 97u <= (*p) && (*p) <= 102u )
goto st60;
} else if ( (*p) >= 65u )
goto st60;
} else
goto st60;
goto st0;
st68:
if ( ++p == pe )
goto _test_eof68;
case 68:
switch( (*p) ) {
case 46u: goto st46;
case 58u: goto st62;
}
if ( (*p) < 65u ) {
if ( 48u <= (*p) && (*p) <= 57u )
goto st60;
} else if ( (*p) > 70u ) {
if ( 97u <= (*p) && (*p) <= 102u )
goto st60;
} else
goto st60;
goto st0;
st69:
if ( ++p == pe )
goto _test_eof69;
case 69:
switch( (*p) ) {
case 46u: goto st46;
case 58u: goto st62;
}
if ( (*p) < 65u ) {
if ( 48u <= (*p) && (*p) <= 57u )
goto st68;
} else if ( (*p) > 70u ) {
if ( 97u <= (*p) && (*p) <= 102u )
goto st59;
} else
goto st59;
goto st0;
tr62:
#line 28 "src/Utils/IP.rl"
{
ip_family = AF_INET6;
}
goto st98;
st98:
if ( ++p == pe )
goto _test_eof98;
case 98:
#line 1168 "src/Utils/IP.cpp"
if ( (*p) < 65u ) {
if ( 48u <= (*p) && (*p) <= 57u )
goto tr85;
} else if ( (*p) > 70u ) {
if ( 97u <= (*p) && (*p) <= 102u )
goto tr85;
} else
goto tr85;
goto st0;
st70:
if ( ++p == pe )
goto _test_eof70;
case 70:
if ( (*p) == 58u )
goto st62;
if ( (*p) < 65u ) {
if ( 48u <= (*p) && (*p) <= 57u )
goto st59;
} else if ( (*p) > 70u ) {
if ( 97u <= (*p) && (*p) <= 102u )
goto st59;
} else
goto st59;
goto st0;
tr53:
#line 28 "src/Utils/IP.rl"
{
ip_family = AF_INET6;
}
goto st99;
st99:
if ( ++p == pe )
goto _test_eof99;
case 99:
#line 1203 "src/Utils/IP.cpp"
switch( (*p) ) {
case 48u: goto tr90;
case 49u: goto tr91;
case 50u: goto tr92;
}
if ( (*p) < 65u ) {
if ( 51u <= (*p) && (*p) <= 57u )
goto tr93;
} else if ( (*p) > 70u ) {
if ( 97u <= (*p) && (*p) <= 102u )
goto tr94;
} else
goto tr94;
goto st0;
tr90:
#line 28 "src/Utils/IP.rl"
{
ip_family = AF_INET6;
}
goto st100;
st100:
if ( ++p == pe )
goto _test_eof100;
case 100:
#line 1228 "src/Utils/IP.cpp"
switch( (*p) ) {
case 46u: goto st46;
case 58u: goto st71;
}
if ( (*p) < 65u ) {
if ( 48u <= (*p) && (*p) <= 57u )
goto tr124;
} else if ( (*p) > 70u ) {
if ( 97u <= (*p) && (*p) <= 102u )
goto tr124;
} else
goto tr124;
goto st0;
tr124:
#line 28 "src/Utils/IP.rl"
{
ip_family = AF_INET6;
}
goto st101;
st101:
if ( ++p == pe )
goto _test_eof101;
case 101:
#line 1252 "src/Utils/IP.cpp"
if ( (*p) == 58u )
goto st71;
if ( (*p) < 65u ) {
if ( 48u <= (*p) && (*p) <= 57u )
goto tr126;
} else if ( (*p) > 70u ) {
if ( 97u <= (*p) && (*p) <= 102u )
goto tr126;
} else
goto tr126;
goto st0;
tr126:
#line 28 "src/Utils/IP.rl"
{
ip_family = AF_INET6;
}
goto st102;
st102:
if ( ++p == pe )
goto _test_eof102;
case 102:
#line 1274 "src/Utils/IP.cpp"
if ( (*p) == 58u )
goto st71;
if ( (*p) < 65u ) {
if ( 48u <= (*p) && (*p) <= 57u )
goto tr127;
} else if ( (*p) > 70u ) {
if ( 97u <= (*p) && (*p) <= 102u )
goto tr127;
} else
goto tr127;
goto st0;
tr127:
#line 28 "src/Utils/IP.rl"
{
ip_family = AF_INET6;
}
goto st103;
st103:
if ( ++p == pe )
goto _test_eof103;
case 103:
#line 1296 "src/Utils/IP.cpp"
if ( (*p) == 58u )
goto st71;
goto st0;
st71:
if ( ++p == pe )
goto _test_eof71;
case 71:
if ( (*p) < 65u ) {
if ( 48u <= (*p) && (*p) <= 57u )
goto tr85;
} else if ( (*p) > 70u ) {
if ( 97u <= (*p) && (*p) <= 102u )
goto tr85;
} else
goto tr85;
goto st0;
tr91:
#line 28 "src/Utils/IP.rl"
{
ip_family = AF_INET6;
}
goto st104;
st104:
if ( ++p == pe )
goto _test_eof104;
case 104:
#line 1323 "src/Utils/IP.cpp"
switch( (*p) ) {
case 46u: goto st46;
case 58u: goto st71;
}
if ( (*p) < 65u ) {
if ( 48u <= (*p) && (*p) <= 57u )
goto tr128;
} else if ( (*p) > 70u ) {
if ( 97u <= (*p) && (*p) <= 102u )
goto tr124;
} else
goto tr124;
goto st0;
tr128:
#line 28 "src/Utils/IP.rl"
{
ip_family = AF_INET6;
}
goto st105;
st105:
if ( ++p == pe )
goto _test_eof105;
case 105:
#line 1347 "src/Utils/IP.cpp"
switch( (*p) ) {
case 46u: goto st46;
case 58u: goto st71;
}
if ( (*p) < 65u ) {
if ( 48u <= (*p) && (*p) <= 57u )
goto tr129;
} else if ( (*p) > 70u ) {
if ( 97u <= (*p) && (*p) <= 102u )
goto tr126;
} else
goto tr126;
goto st0;
tr129:
#line 28 "src/Utils/IP.rl"
{
ip_family = AF_INET6;
}
goto st106;
st106:
if ( ++p == pe )
goto _test_eof106;
case 106:
#line 1371 "src/Utils/IP.cpp"
switch( (*p) ) {
case 46u: goto st46;
case 58u: goto st71;
}
if ( (*p) < 65u ) {
if ( 48u <= (*p) && (*p) <= 57u )
goto tr127;
} else if ( (*p) > 70u ) {
if ( 97u <= (*p) && (*p) <= 102u )
goto tr127;
} else
goto tr127;
goto st0;
tr92:
#line 28 "src/Utils/IP.rl"
{
ip_family = AF_INET6;
}
goto st107;
st107:
if ( ++p == pe )
goto _test_eof107;
case 107:
#line 1395 "src/Utils/IP.cpp"
switch( (*p) ) {
case 46u: goto st46;
case 53u: goto tr130;
case 58u: goto st71;
}
if ( (*p) < 54u ) {
if ( 48u <= (*p) && (*p) <= 52u )
goto tr128;
} else if ( (*p) > 57u ) {
if ( (*p) > 70u ) {
if ( 97u <= (*p) && (*p) <= 102u )
goto tr124;
} else if ( (*p) >= 65u )
goto tr124;
} else
goto tr131;
goto st0;
tr130:
#line 28 "src/Utils/IP.rl"
{
ip_family = AF_INET6;
}
goto st108;
st108:
if ( ++p == pe )
goto _test_eof108;
case 108:
#line 1423 "src/Utils/IP.cpp"
switch( (*p) ) {
case 46u: goto st46;
case 58u: goto st71;
}
if ( (*p) < 54u ) {
if ( 48u <= (*p) && (*p) <= 53u )
goto tr129;
} else if ( (*p) > 57u ) {
if ( (*p) > 70u ) {
if ( 97u <= (*p) && (*p) <= 102u )
goto tr126;
} else if ( (*p) >= 65u )
goto tr126;
} else
goto tr126;
goto st0;
tr131:
#line 28 "src/Utils/IP.rl"
{
ip_family = AF_INET6;
}
goto st109;
st109:
if ( ++p == pe )
goto _test_eof109;
case 109:
#line 1450 "src/Utils/IP.cpp"
switch( (*p) ) {
case 46u: goto st46;
case 58u: goto st71;
}
if ( (*p) < 65u ) {
if ( 48u <= (*p) && (*p) <= 57u )
goto tr126;
} else if ( (*p) > 70u ) {
if ( 97u <= (*p) && (*p) <= 102u )
goto tr126;
} else
goto tr126;
goto st0;
tr93:
#line 28 "src/Utils/IP.rl"
{
ip_family = AF_INET6;
}
goto st110;
st110:
if ( ++p == pe )
goto _test_eof110;
case 110:
#line 1474 "src/Utils/IP.cpp"
switch( (*p) ) {
case 46u: goto st46;
case 58u: goto st71;
}
if ( (*p) < 65u ) {
if ( 48u <= (*p) && (*p) <= 57u )
goto tr131;
} else if ( (*p) > 70u ) {
if ( 97u <= (*p) && (*p) <= 102u )
goto tr124;
} else
goto tr124;
goto st0;
tr94:
#line 28 "src/Utils/IP.rl"
{
ip_family = AF_INET6;
}
goto st111;
st111:
if ( ++p == pe )
goto _test_eof111;
case 111:
#line 1498 "src/Utils/IP.cpp"
if ( (*p) == 58u )
goto st71;
if ( (*p) < 65u ) {
if ( 48u <= (*p) && (*p) <= 57u )
goto tr124;
} else if ( (*p) > 70u ) {
if ( 97u <= (*p) && (*p) <= 102u )
goto tr124;
} else
goto tr124;
goto st0;
tr47:
#line 28 "src/Utils/IP.rl"
{
ip_family = AF_INET6;
}
goto st112;
st112:
if ( ++p == pe )
goto _test_eof112;
case 112:
#line 1520 "src/Utils/IP.cpp"
switch( (*p) ) {
case 48u: goto tr95;
case 49u: goto tr96;
case 50u: goto tr97;
}
if ( (*p) < 65u ) {
if ( 51u <= (*p) && (*p) <= 57u )
goto tr98;
} else if ( (*p) > 70u ) {
if ( 97u <= (*p) && (*p) <= 102u )
goto tr99;
} else
goto tr99;
goto st0;
tr95:
#line 28 "src/Utils/IP.rl"
{
ip_family = AF_INET6;
}
goto st113;
st113:
if ( ++p == pe )
goto _test_eof113;
case 113:
#line 1545 "src/Utils/IP.cpp"
switch( (*p) ) {
case 46u: goto st46;
case 58u: goto st72;
}
if ( (*p) < 65u ) {
if ( 48u <= (*p) && (*p) <= 57u )
goto tr132;
} else if ( (*p) > 70u ) {
if ( 97u <= (*p) && (*p) <= 102u )
goto tr132;
} else
goto tr132;
goto st0;
tr132:
#line 28 "src/Utils/IP.rl"
{
ip_family = AF_INET6;
}
goto st114;
st114:
if ( ++p == pe )
goto _test_eof114;
case 114:
#line 1569 "src/Utils/IP.cpp"
if ( (*p) == 58u )
goto st72;
if ( (*p) < 65u ) {
if ( 48u <= (*p) && (*p) <= 57u )
goto tr134;
} else if ( (*p) > 70u ) {
if ( 97u <= (*p) && (*p) <= 102u )
goto tr134;
} else
goto tr134;
goto st0;
tr134:
#line 28 "src/Utils/IP.rl"
{
ip_family = AF_INET6;
}
goto st115;
st115:
if ( ++p == pe )
goto _test_eof115;
case 115:
#line 1591 "src/Utils/IP.cpp"
if ( (*p) == 58u )
goto st72;
if ( (*p) < 65u ) {
if ( 48u <= (*p) && (*p) <= 57u )
goto tr135;
} else if ( (*p) > 70u ) {
if ( 97u <= (*p) && (*p) <= 102u )
goto tr135;
} else
goto tr135;
goto st0;
tr135:
#line 28 "src/Utils/IP.rl"
{
ip_family = AF_INET6;
}
goto st116;
st116:
if ( ++p == pe )
goto _test_eof116;
case 116:
#line 1613 "src/Utils/IP.cpp"
if ( (*p) == 58u )
goto st72;
goto st0;
st72:
if ( ++p == pe )
goto _test_eof72;
case 72:
switch( (*p) ) {
case 48u: goto tr90;
case 49u: goto tr91;
case 50u: goto tr92;
}
if ( (*p) < 65u ) {
if ( 51u <= (*p) && (*p) <= 57u )
goto tr93;
} else if ( (*p) > 70u ) {
if ( 97u <= (*p) && (*p) <= 102u )
goto tr94;
} else
goto tr94;
goto st0;
tr96:
#line 28 "src/Utils/IP.rl"
{
ip_family = AF_INET6;
}
goto st117;
st117:
if ( ++p == pe )
goto _test_eof117;
case 117:
#line 1645 "src/Utils/IP.cpp"
switch( (*p) ) {
case 46u: goto st46;
case 58u: goto st72;
}
if ( (*p) < 65u ) {
if ( 48u <= (*p) && (*p) <= 57u )
goto tr136;
} else if ( (*p) > 70u ) {
if ( 97u <= (*p) && (*p) <= 102u )
goto tr132;
} else
goto tr132;
goto st0;
tr136:
#line 28 "src/Utils/IP.rl"
{
ip_family = AF_INET6;
}
goto st118;
st118:
if ( ++p == pe )
goto _test_eof118;
case 118:
#line 1669 "src/Utils/IP.cpp"
switch( (*p) ) {
case 46u: goto st46;
case 58u: goto st72;
}
if ( (*p) < 65u ) {
if ( 48u <= (*p) && (*p) <= 57u )
goto tr137;
} else if ( (*p) > 70u ) {
if ( 97u <= (*p) && (*p) <= 102u )
goto tr134;
} else
goto tr134;
goto st0;
tr137:
#line 28 "src/Utils/IP.rl"
{
ip_family = AF_INET6;
}
goto st119;
st119:
if ( ++p == pe )
goto _test_eof119;
case 119:
#line 1693 "src/Utils/IP.cpp"
switch( (*p) ) {
case 46u: goto st46;
case 58u: goto st72;
}
if ( (*p) < 65u ) {
if ( 48u <= (*p) && (*p) <= 57u )
goto tr135;
} else if ( (*p) > 70u ) {
if ( 97u <= (*p) && (*p) <= 102u )
goto tr135;
} else
goto tr135;
goto st0;
tr97:
#line 28 "src/Utils/IP.rl"
{
ip_family = AF_INET6;
}
goto st120;
st120:
if ( ++p == pe )
goto _test_eof120;
case 120:
#line 1717 "src/Utils/IP.cpp"
switch( (*p) ) {
case 46u: goto st46;
case 53u: goto tr138;
case 58u: goto st72;
}
if ( (*p) < 54u ) {
if ( 48u <= (*p) && (*p) <= 52u )
goto tr136;
} else if ( (*p) > 57u ) {
if ( (*p) > 70u ) {
if ( 97u <= (*p) && (*p) <= 102u )
goto tr132;
} else if ( (*p) >= 65u )
goto tr132;
} else
goto tr139;
goto st0;
tr138:
#line 28 "src/Utils/IP.rl"
{
ip_family = AF_INET6;
}
goto st121;
st121:
if ( ++p == pe )
goto _test_eof121;
case 121:
#line 1745 "src/Utils/IP.cpp"
switch( (*p) ) {
case 46u: goto st46;
case 58u: goto st72;
}
if ( (*p) < 54u ) {
if ( 48u <= (*p) && (*p) <= 53u )
goto tr137;
} else if ( (*p) > 57u ) {
if ( (*p) > 70u ) {
if ( 97u <= (*p) && (*p) <= 102u )
goto tr134;
} else if ( (*p) >= 65u )
goto tr134;
} else
goto tr134;
goto st0;
tr139:
#line 28 "src/Utils/IP.rl"
{
ip_family = AF_INET6;
}
goto st122;
st122:
if ( ++p == pe )
goto _test_eof122;
case 122:
#line 1772 "src/Utils/IP.cpp"
switch( (*p) ) {
case 46u: goto st46;
case 58u: goto st72;
}
if ( (*p) < 65u ) {
if ( 48u <= (*p) && (*p) <= 57u )
goto tr134;
} else if ( (*p) > 70u ) {
if ( 97u <= (*p) && (*p) <= 102u )
goto tr134;
} else
goto tr134;
goto st0;
tr98:
#line 28 "src/Utils/IP.rl"
{
ip_family = AF_INET6;
}
goto st123;
st123:
if ( ++p == pe )
goto _test_eof123;
case 123:
#line 1796 "src/Utils/IP.cpp"
switch( (*p) ) {
case 46u: goto st46;
case 58u: goto st72;
}
if ( (*p) < 65u ) {
if ( 48u <= (*p) && (*p) <= 57u )
goto tr139;
} else if ( (*p) > 70u ) {
if ( 97u <= (*p) && (*p) <= 102u )
goto tr132;
} else
goto tr132;
goto st0;
tr99:
#line 28 "src/Utils/IP.rl"
{
ip_family = AF_INET6;
}
goto st124;
st124:
if ( ++p == pe )
goto _test_eof124;
case 124:
#line 1820 "src/Utils/IP.cpp"
if ( (*p) == 58u )
goto st72;
if ( (*p) < 65u ) {
if ( 48u <= (*p) && (*p) <= 57u )
goto tr132;
} else if ( (*p) > 70u ) {
if ( 97u <= (*p) && (*p) <= 102u )
goto tr132;
} else
goto tr132;
goto st0;
tr41:
#line 28 "src/Utils/IP.rl"
{
ip_family = AF_INET6;
}
goto st125;
st125:
if ( ++p == pe )
goto _test_eof125;
case 125:
#line 1842 "src/Utils/IP.cpp"
switch( (*p) ) {
case 48u: goto tr100;
case 49u: goto tr101;
case 50u: goto tr102;
}
if ( (*p) < 65u ) {
if ( 51u <= (*p) && (*p) <= 57u )
goto tr103;
} else if ( (*p) > 70u ) {
if ( 97u <= (*p) && (*p) <= 102u )
goto tr104;
} else
goto tr104;
goto st0;
tr100:
#line 28 "src/Utils/IP.rl"
{
ip_family = AF_INET6;
}
goto st126;
st126:
if ( ++p == pe )
goto _test_eof126;
case 126:
#line 1867 "src/Utils/IP.cpp"
switch( (*p) ) {
case 46u: goto st46;
case 58u: goto st73;
}
if ( (*p) < 65u ) {
if ( 48u <= (*p) && (*p) <= 57u )
goto tr140;
} else if ( (*p) > 70u ) {
if ( 97u <= (*p) && (*p) <= 102u )
goto tr140;
} else
goto tr140;
goto st0;
tr140:
#line 28 "src/Utils/IP.rl"
{
ip_family = AF_INET6;
}
goto st127;
st127:
if ( ++p == pe )
goto _test_eof127;
case 127:
#line 1891 "src/Utils/IP.cpp"
if ( (*p) == 58u )
goto st73;
if ( (*p) < 65u ) {
if ( 48u <= (*p) && (*p) <= 57u )
goto tr142;
} else if ( (*p) > 70u ) {
if ( 97u <= (*p) && (*p) <= 102u )
goto tr142;
} else
goto tr142;
goto st0;
tr142:
#line 28 "src/Utils/IP.rl"
{
ip_family = AF_INET6;
}
goto st128;
st128:
if ( ++p == pe )
goto _test_eof128;
case 128:
#line 1913 "src/Utils/IP.cpp"
if ( (*p) == 58u )
goto st73;
if ( (*p) < 65u ) {
if ( 48u <= (*p) && (*p) <= 57u )
goto tr143;
} else if ( (*p) > 70u ) {
if ( 97u <= (*p) && (*p) <= 102u )
goto tr143;
} else
goto tr143;
goto st0;
tr143:
#line 28 "src/Utils/IP.rl"
{
ip_family = AF_INET6;
}
goto st129;
st129:
if ( ++p == pe )
goto _test_eof129;
case 129:
#line 1935 "src/Utils/IP.cpp"
if ( (*p) == 58u )
goto st73;
goto st0;
st73:
if ( ++p == pe )
goto _test_eof73;
case 73:
switch( (*p) ) {
case 48u: goto tr95;
case 49u: goto tr96;
case 50u: goto tr97;
}
if ( (*p) < 65u ) {
if ( 51u <= (*p) && (*p) <= 57u )
goto tr98;
} else if ( (*p) > 70u ) {
if ( 97u <= (*p) && (*p) <= 102u )
goto tr99;
} else
goto tr99;
goto st0;
tr101:
#line 28 "src/Utils/IP.rl"
{
ip_family = AF_INET6;
}
goto st130;
st130:
if ( ++p == pe )
goto _test_eof130;
case 130:
#line 1967 "src/Utils/IP.cpp"
switch( (*p) ) {
case 46u: goto st46;
case 58u: goto st73;
}
if ( (*p) < 65u ) {
if ( 48u <= (*p) && (*p) <= 57u )
goto tr144;
} else if ( (*p) > 70u ) {
if ( 97u <= (*p) && (*p) <= 102u )
goto tr140;
} else
goto tr140;
goto st0;
tr144:
#line 28 "src/Utils/IP.rl"
{
ip_family = AF_INET6;
}
goto st131;
st131:
if ( ++p == pe )
goto _test_eof131;
case 131:
#line 1991 "src/Utils/IP.cpp"
switch( (*p) ) {
case 46u: goto st46;
case 58u: goto st73;
}
if ( (*p) < 65u ) {
if ( 48u <= (*p) && (*p) <= 57u )
goto tr145;
} else if ( (*p) > 70u ) {
if ( 97u <= (*p) && (*p) <= 102u )
goto tr142;
} else
goto tr142;
goto st0;
tr145:
#line 28 "src/Utils/IP.rl"
{
ip_family = AF_INET6;
}
goto st132;
st132:
if ( ++p == pe )
goto _test_eof132;
case 132:
#line 2015 "src/Utils/IP.cpp"
switch( (*p) ) {
case 46u: goto st46;
case 58u: goto st73;
}
if ( (*p) < 65u ) {
if ( 48u <= (*p) && (*p) <= 57u )
goto tr143;
} else if ( (*p) > 70u ) {
if ( 97u <= (*p) && (*p) <= 102u )
goto tr143;
} else
goto tr143;
goto st0;
tr102:
#line 28 "src/Utils/IP.rl"
{
ip_family = AF_INET6;
}
goto st133;
st133:
if ( ++p == pe )
goto _test_eof133;
case 133:
#line 2039 "src/Utils/IP.cpp"
switch( (*p) ) {
case 46u: goto st46;
case 53u: goto tr146;
case 58u: goto st73;
}
if ( (*p) < 54u ) {
if ( 48u <= (*p) && (*p) <= 52u )
goto tr144;
} else if ( (*p) > 57u ) {
if ( (*p) > 70u ) {
if ( 97u <= (*p) && (*p) <= 102u )
goto tr140;
} else if ( (*p) >= 65u )
goto tr140;
} else
goto tr147;
goto st0;
tr146:
#line 28 "src/Utils/IP.rl"
{
ip_family = AF_INET6;
}
goto st134;
st134:
if ( ++p == pe )
goto _test_eof134;
case 134:
#line 2067 "src/Utils/IP.cpp"
switch( (*p) ) {
case 46u: goto st46;
case 58u: goto st73;
}
if ( (*p) < 54u ) {
if ( 48u <= (*p) && (*p) <= 53u )
goto tr145;
} else if ( (*p) > 57u ) {
if ( (*p) > 70u ) {
if ( 97u <= (*p) && (*p) <= 102u )
goto tr142;
} else if ( (*p) >= 65u )
goto tr142;
} else
goto tr142;
goto st0;
tr147:
#line 28 "src/Utils/IP.rl"
{
ip_family = AF_INET6;
}
goto st135;
st135:
if ( ++p == pe )
goto _test_eof135;
case 135:
#line 2094 "src/Utils/IP.cpp"
switch( (*p) ) {
case 46u: goto st46;
case 58u: goto st73;
}
if ( (*p) < 65u ) {
if ( 48u <= (*p) && (*p) <= 57u )
goto tr142;
} else if ( (*p) > 70u ) {
if ( 97u <= (*p) && (*p) <= 102u )
goto tr142;
} else
goto tr142;
goto st0;
tr103:
#line 28 "src/Utils/IP.rl"
{
ip_family = AF_INET6;
}
goto st136;
st136:
if ( ++p == pe )
goto _test_eof136;
case 136:
#line 2118 "src/Utils/IP.cpp"
switch( (*p) ) {
case 46u: goto st46;
case 58u: goto st73;
}
if ( (*p) < 65u ) {
if ( 48u <= (*p) && (*p) <= 57u )
goto tr147;
} else if ( (*p) > 70u ) {
if ( 97u <= (*p) && (*p) <= 102u )
goto tr140;
} else
goto tr140;
goto st0;
tr104:
#line 28 "src/Utils/IP.rl"
{
ip_family = AF_INET6;
}
goto st137;
st137:
if ( ++p == pe )
goto _test_eof137;
case 137:
#line 2142 "src/Utils/IP.cpp"
if ( (*p) == 58u )
goto st73;
if ( (*p) < 65u ) {
if ( 48u <= (*p) && (*p) <= 57u )
goto tr140;
} else if ( (*p) > 70u ) {
if ( 97u <= (*p) && (*p) <= 102u )
goto tr140;
} else
goto tr140;
goto st0;
tr35:
#line 28 "src/Utils/IP.rl"
{
ip_family = AF_INET6;
}
goto st138;
st138:
if ( ++p == pe )
goto _test_eof138;
case 138:
#line 2164 "src/Utils/IP.cpp"
switch( (*p) ) {
case 48u: goto tr105;
case 49u: goto tr106;
case 50u: goto tr107;
}
if ( (*p) < 65u ) {
if ( 51u <= (*p) && (*p) <= 57u )
goto tr108;
} else if ( (*p) > 70u ) {
if ( 97u <= (*p) && (*p) <= 102u )
goto tr109;
} else
goto tr109;
goto st0;
tr105:
#line 28 "src/Utils/IP.rl"
{
ip_family = AF_INET6;
}
goto st139;
st139:
if ( ++p == pe )
goto _test_eof139;
case 139:
#line 2189 "src/Utils/IP.cpp"
switch( (*p) ) {
case 46u: goto st46;
case 58u: goto st74;
}
if ( (*p) < 65u ) {
if ( 48u <= (*p) && (*p) <= 57u )
goto tr148;
} else if ( (*p) > 70u ) {
if ( 97u <= (*p) && (*p) <= 102u )
goto tr148;
} else
goto tr148;
goto st0;
tr148:
#line 28 "src/Utils/IP.rl"
{
ip_family = AF_INET6;
}
goto st140;
st140:
if ( ++p == pe )
goto _test_eof140;
case 140:
#line 2213 "src/Utils/IP.cpp"
if ( (*p) == 58u )
goto st74;
if ( (*p) < 65u ) {
if ( 48u <= (*p) && (*p) <= 57u )
goto tr150;
} else if ( (*p) > 70u ) {
if ( 97u <= (*p) && (*p) <= 102u )
goto tr150;
} else
goto tr150;
goto st0;
tr150:
#line 28 "src/Utils/IP.rl"
{
ip_family = AF_INET6;
}
goto st141;
st141:
if ( ++p == pe )
goto _test_eof141;
case 141:
#line 2235 "src/Utils/IP.cpp"
if ( (*p) == 58u )
goto st74;
if ( (*p) < 65u ) {
if ( 48u <= (*p) && (*p) <= 57u )
goto tr151;
} else if ( (*p) > 70u ) {
if ( 97u <= (*p) && (*p) <= 102u )
goto tr151;
} else
goto tr151;
goto st0;
tr151:
#line 28 "src/Utils/IP.rl"
{
ip_family = AF_INET6;
}
goto st142;
st142:
if ( ++p == pe )
goto _test_eof142;
case 142:
#line 2257 "src/Utils/IP.cpp"
if ( (*p) == 58u )
goto st74;
goto st0;
st74:
if ( ++p == pe )
goto _test_eof74;
case 74:
switch( (*p) ) {
case 48u: goto tr100;
case 49u: goto tr101;
case 50u: goto tr102;
}
if ( (*p) < 65u ) {
if ( 51u <= (*p) && (*p) <= 57u )
goto tr103;
} else if ( (*p) > 70u ) {
if ( 97u <= (*p) && (*p) <= 102u )
goto tr104;
} else
goto tr104;
goto st0;
tr106:
#line 28 "src/Utils/IP.rl"
{
ip_family = AF_INET6;
}
goto st143;
st143:
if ( ++p == pe )
goto _test_eof143;
case 143:
#line 2289 "src/Utils/IP.cpp"
switch( (*p) ) {
case 46u: goto st46;
case 58u: goto st74;
}
if ( (*p) < 65u ) {
if ( 48u <= (*p) && (*p) <= 57u )
goto tr152;
} else if ( (*p) > 70u ) {
if ( 97u <= (*p) && (*p) <= 102u )
goto tr148;
} else
goto tr148;
goto st0;
tr152:
#line 28 "src/Utils/IP.rl"
{
ip_family = AF_INET6;
}
goto st144;
st144:
if ( ++p == pe )
goto _test_eof144;
case 144:
#line 2313 "src/Utils/IP.cpp"
switch( (*p) ) {
case 46u: goto st46;
case 58u: goto st74;
}
if ( (*p) < 65u ) {
if ( 48u <= (*p) && (*p) <= 57u )
goto tr153;
} else if ( (*p) > 70u ) {
if ( 97u <= (*p) && (*p) <= 102u )
goto tr150;
} else
goto tr150;
goto st0;
tr153:
#line 28 "src/Utils/IP.rl"
{
ip_family = AF_INET6;
}
goto st145;
st145:
if ( ++p == pe )
goto _test_eof145;
case 145:
#line 2337 "src/Utils/IP.cpp"
switch( (*p) ) {
case 46u: goto st46;
case 58u: goto st74;
}
if ( (*p) < 65u ) {
if ( 48u <= (*p) && (*p) <= 57u )
goto tr151;
} else if ( (*p) > 70u ) {
if ( 97u <= (*p) && (*p) <= 102u )
goto tr151;
} else
goto tr151;
goto st0;
tr107:
#line 28 "src/Utils/IP.rl"
{
ip_family = AF_INET6;
}
goto st146;
st146:
if ( ++p == pe )
goto _test_eof146;
case 146:
#line 2361 "src/Utils/IP.cpp"
switch( (*p) ) {
case 46u: goto st46;
case 53u: goto tr154;
case 58u: goto st74;
}
if ( (*p) < 54u ) {
if ( 48u <= (*p) && (*p) <= 52u )
goto tr152;
} else if ( (*p) > 57u ) {
if ( (*p) > 70u ) {
if ( 97u <= (*p) && (*p) <= 102u )
goto tr148;
} else if ( (*p) >= 65u )
goto tr148;
} else
goto tr155;
goto st0;
tr154:
#line 28 "src/Utils/IP.rl"
{
ip_family = AF_INET6;
}
goto st147;
st147:
if ( ++p == pe )
goto _test_eof147;
case 147:
#line 2389 "src/Utils/IP.cpp"
switch( (*p) ) {
case 46u: goto st46;
case 58u: goto st74;
}
if ( (*p) < 54u ) {
if ( 48u <= (*p) && (*p) <= 53u )
goto tr153;
} else if ( (*p) > 57u ) {
if ( (*p) > 70u ) {
if ( 97u <= (*p) && (*p) <= 102u )
goto tr150;
} else if ( (*p) >= 65u )
goto tr150;
} else
goto tr150;
goto st0;
tr155:
#line 28 "src/Utils/IP.rl"
{
ip_family = AF_INET6;
}
goto st148;
st148:
if ( ++p == pe )
goto _test_eof148;
case 148:
#line 2416 "src/Utils/IP.cpp"
switch( (*p) ) {
case 46u: goto st46;
case 58u: goto st74;
}
if ( (*p) < 65u ) {
if ( 48u <= (*p) && (*p) <= 57u )
goto tr150;
} else if ( (*p) > 70u ) {
if ( 97u <= (*p) && (*p) <= 102u )
goto tr150;
} else
goto tr150;
goto st0;
tr108:
#line 28 "src/Utils/IP.rl"
{
ip_family = AF_INET6;
}
goto st149;
st149:
if ( ++p == pe )
goto _test_eof149;
case 149:
#line 2440 "src/Utils/IP.cpp"
switch( (*p) ) {
case 46u: goto st46;
case 58u: goto st74;
}
if ( (*p) < 65u ) {
if ( 48u <= (*p) && (*p) <= 57u )
goto tr155;
} else if ( (*p) > 70u ) {
if ( 97u <= (*p) && (*p) <= 102u )
goto tr148;
} else
goto tr148;
goto st0;
tr109:
#line 28 "src/Utils/IP.rl"
{
ip_family = AF_INET6;
}
goto st150;
st150:
if ( ++p == pe )
goto _test_eof150;
case 150:
#line 2464 "src/Utils/IP.cpp"
if ( (*p) == 58u )
goto st74;
if ( (*p) < 65u ) {
if ( 48u <= (*p) && (*p) <= 57u )
goto tr148;
} else if ( (*p) > 70u ) {
if ( 97u <= (*p) && (*p) <= 102u )
goto tr148;
} else
goto tr148;
goto st0;
tr29:
#line 28 "src/Utils/IP.rl"
{
ip_family = AF_INET6;
}
goto st151;
st151:
if ( ++p == pe )
goto _test_eof151;
case 151:
#line 2486 "src/Utils/IP.cpp"
switch( (*p) ) {
case 48u: goto tr115;
case 49u: goto tr116;
case 50u: goto tr117;
}
if ( (*p) < 65u ) {
if ( 51u <= (*p) && (*p) <= 57u )
goto tr118;
} else if ( (*p) > 70u ) {
if ( 97u <= (*p) && (*p) <= 102u )
goto tr119;
} else
goto tr119;
goto st0;
tr115:
#line 28 "src/Utils/IP.rl"
{
ip_family = AF_INET6;
}
goto st152;
st152:
if ( ++p == pe )
goto _test_eof152;
case 152:
#line 2511 "src/Utils/IP.cpp"
switch( (*p) ) {
case 46u: goto st46;
case 58u: goto st75;
}
if ( (*p) < 65u ) {
if ( 48u <= (*p) && (*p) <= 57u )
goto tr156;
} else if ( (*p) > 70u ) {
if ( 97u <= (*p) && (*p) <= 102u )
goto tr156;
} else
goto tr156;
goto st0;
tr156:
#line 28 "src/Utils/IP.rl"
{
ip_family = AF_INET6;
}
goto st153;
st153:
if ( ++p == pe )
goto _test_eof153;
case 153:
#line 2535 "src/Utils/IP.cpp"
if ( (*p) == 58u )
goto st75;
if ( (*p) < 65u ) {
if ( 48u <= (*p) && (*p) <= 57u )
goto tr158;
} else if ( (*p) > 70u ) {
if ( 97u <= (*p) && (*p) <= 102u )
goto tr158;
} else
goto tr158;
goto st0;
tr158:
#line 28 "src/Utils/IP.rl"
{
ip_family = AF_INET6;
}
goto st154;
st154:
if ( ++p == pe )
goto _test_eof154;
case 154:
#line 2557 "src/Utils/IP.cpp"
if ( (*p) == 58u )
goto st75;
if ( (*p) < 65u ) {
if ( 48u <= (*p) && (*p) <= 57u )
goto tr159;
} else if ( (*p) > 70u ) {
if ( 97u <= (*p) && (*p) <= 102u )
goto tr159;
} else
goto tr159;
goto st0;
tr159:
#line 28 "src/Utils/IP.rl"
{
ip_family = AF_INET6;
}
goto st155;
st155:
if ( ++p == pe )
goto _test_eof155;
case 155:
#line 2579 "src/Utils/IP.cpp"
if ( (*p) == 58u )
goto st75;
goto st0;
st75:
if ( ++p == pe )
goto _test_eof75;
case 75:
switch( (*p) ) {
case 48u: goto tr105;
case 49u: goto tr106;
case 50u: goto tr107;
}
if ( (*p) < 65u ) {
if ( 51u <= (*p) && (*p) <= 57u )
goto tr108;
} else if ( (*p) > 70u ) {
if ( 97u <= (*p) && (*p) <= 102u )
goto tr109;
} else
goto tr109;
goto st0;
tr116:
#line 28 "src/Utils/IP.rl"
{
ip_family = AF_INET6;
}
goto st156;
st156:
if ( ++p == pe )
goto _test_eof156;
case 156:
#line 2611 "src/Utils/IP.cpp"
switch( (*p) ) {
case 46u: goto st46;
case 58u: goto st75;
}
if ( (*p) < 65u ) {
if ( 48u <= (*p) && (*p) <= 57u )
goto tr160;
} else if ( (*p) > 70u ) {
if ( 97u <= (*p) && (*p) <= 102u )
goto tr156;
} else
goto tr156;
goto st0;
tr160:
#line 28 "src/Utils/IP.rl"
{
ip_family = AF_INET6;
}
goto st157;
st157:
if ( ++p == pe )
goto _test_eof157;
case 157:
#line 2635 "src/Utils/IP.cpp"
switch( (*p) ) {
case 46u: goto st46;
case 58u: goto st75;
}
if ( (*p) < 65u ) {
if ( 48u <= (*p) && (*p) <= 57u )
goto tr161;
} else if ( (*p) > 70u ) {
if ( 97u <= (*p) && (*p) <= 102u )
goto tr158;
} else
goto tr158;
goto st0;
tr161:
#line 28 "src/Utils/IP.rl"
{
ip_family = AF_INET6;
}
goto st158;
st158:
if ( ++p == pe )
goto _test_eof158;
case 158:
#line 2659 "src/Utils/IP.cpp"
switch( (*p) ) {
case 46u: goto st46;
case 58u: goto st75;
}
if ( (*p) < 65u ) {
if ( 48u <= (*p) && (*p) <= 57u )
goto tr159;
} else if ( (*p) > 70u ) {
if ( 97u <= (*p) && (*p) <= 102u )
goto tr159;
} else
goto tr159;
goto st0;
tr117:
#line 28 "src/Utils/IP.rl"
{
ip_family = AF_INET6;
}
goto st159;
st159:
if ( ++p == pe )
goto _test_eof159;
case 159:
#line 2683 "src/Utils/IP.cpp"
switch( (*p) ) {
case 46u: goto st46;
case 53u: goto tr162;
case 58u: goto st75;
}
if ( (*p) < 54u ) {
if ( 48u <= (*p) && (*p) <= 52u )
goto tr160;
} else if ( (*p) > 57u ) {
if ( (*p) > 70u ) {
if ( 97u <= (*p) && (*p) <= 102u )
goto tr156;
} else if ( (*p) >= 65u )
goto tr156;
} else
goto tr163;
goto st0;
tr162:
#line 28 "src/Utils/IP.rl"
{
ip_family = AF_INET6;
}
goto st160;
st160:
if ( ++p == pe )
goto _test_eof160;
case 160:
#line 2711 "src/Utils/IP.cpp"
switch( (*p) ) {
case 46u: goto st46;
case 58u: goto st75;
}
if ( (*p) < 54u ) {
if ( 48u <= (*p) && (*p) <= 53u )
goto tr161;
} else if ( (*p) > 57u ) {
if ( (*p) > 70u ) {
if ( 97u <= (*p) && (*p) <= 102u )
goto tr158;
} else if ( (*p) >= 65u )
goto tr158;
} else
goto tr158;
goto st0;
tr163:
#line 28 "src/Utils/IP.rl"
{
ip_family = AF_INET6;
}
goto st161;
st161:
if ( ++p == pe )
goto _test_eof161;
case 161:
#line 2738 "src/Utils/IP.cpp"
switch( (*p) ) {
case 46u: goto st46;
case 58u: goto st75;
}
if ( (*p) < 65u ) {
if ( 48u <= (*p) && (*p) <= 57u )
goto tr158;
} else if ( (*p) > 70u ) {
if ( 97u <= (*p) && (*p) <= 102u )
goto tr158;
} else
goto tr158;
goto st0;
tr118:
#line 28 "src/Utils/IP.rl"
{
ip_family = AF_INET6;
}
goto st162;
st162:
if ( ++p == pe )
goto _test_eof162;
case 162:
#line 2762 "src/Utils/IP.cpp"
switch( (*p) ) {
case 46u: goto st46;
case 58u: goto st75;
}
if ( (*p) < 65u ) {
if ( 48u <= (*p) && (*p) <= 57u )
goto tr163;
} else if ( (*p) > 70u ) {
if ( 97u <= (*p) && (*p) <= 102u )
goto tr156;
} else
goto tr156;
goto st0;
tr119:
#line 28 "src/Utils/IP.rl"
{
ip_family = AF_INET6;
}
goto st163;
st163:
if ( ++p == pe )
goto _test_eof163;
case 163:
#line 2786 "src/Utils/IP.cpp"
if ( (*p) == 58u )
goto st75;
if ( (*p) < 65u ) {
if ( 48u <= (*p) && (*p) <= 57u )
goto tr156;
} else if ( (*p) > 70u ) {
if ( 97u <= (*p) && (*p) <= 102u )
goto tr156;
} else
goto tr156;
goto st0;
st76:
if ( ++p == pe )
goto _test_eof76;
case 76:
switch( (*p) ) {
case 46u: goto st3;
case 58u: goto st19;
}
if ( (*p) < 65u ) {
if ( 48u <= (*p) && (*p) <= 57u )
goto st77;
} else if ( (*p) > 70u ) {
if ( 97u <= (*p) && (*p) <= 102u )
goto st16;
} else
goto st16;
goto st0;
st77:
if ( ++p == pe )
goto _test_eof77;
case 77:
switch( (*p) ) {
case 46u: goto st3;
case 58u: goto st19;
}
if ( (*p) < 65u ) {
if ( 48u <= (*p) && (*p) <= 57u )
goto st78;
} else if ( (*p) > 70u ) {
if ( 97u <= (*p) && (*p) <= 102u )
goto st17;
} else
goto st17;
goto st0;
st78:
if ( ++p == pe )
goto _test_eof78;
case 78:
switch( (*p) ) {
case 46u: goto st3;
case 58u: goto st19;
}
if ( (*p) < 65u ) {
if ( 48u <= (*p) && (*p) <= 57u )
goto st18;
} else if ( (*p) > 70u ) {
if ( 97u <= (*p) && (*p) <= 102u )
goto st18;
} else
goto st18;
goto st0;
st79:
if ( ++p == pe )
goto _test_eof79;
case 79:
switch( (*p) ) {
case 46u: goto st3;
case 53u: goto st80;
case 58u: goto st19;
}
if ( (*p) < 54u ) {
if ( 48u <= (*p) && (*p) <= 52u )
goto st77;
} else if ( (*p) > 57u ) {
if ( (*p) > 70u ) {
if ( 97u <= (*p) && (*p) <= 102u )
goto st16;
} else if ( (*p) >= 65u )
goto st16;
} else
goto st81;
goto st0;
st80:
if ( ++p == pe )
goto _test_eof80;
case 80:
switch( (*p) ) {
case 46u: goto st3;
case 58u: goto st19;
}
if ( (*p) < 54u ) {
if ( 48u <= (*p) && (*p) <= 53u )
goto st78;
} else if ( (*p) > 57u ) {
if ( (*p) > 70u ) {
if ( 97u <= (*p) && (*p) <= 102u )
goto st17;
} else if ( (*p) >= 65u )
goto st17;
} else
goto st17;
goto st0;
st81:
if ( ++p == pe )
goto _test_eof81;
case 81:
switch( (*p) ) {
case 46u: goto st3;
case 58u: goto st19;
}
if ( (*p) < 65u ) {
if ( 48u <= (*p) && (*p) <= 57u )
goto st17;
} else if ( (*p) > 70u ) {
if ( 97u <= (*p) && (*p) <= 102u )
goto st17;
} else
goto st17;
goto st0;
st82:
if ( ++p == pe )
goto _test_eof82;
case 82:
switch( (*p) ) {
case 46u: goto st3;
case 58u: goto st19;
}
if ( (*p) < 65u ) {
if ( 48u <= (*p) && (*p) <= 57u )
goto st81;
} else if ( (*p) > 70u ) {
if ( 97u <= (*p) && (*p) <= 102u )
goto st16;
} else
goto st16;
goto st0;
st83:
if ( ++p == pe )
goto _test_eof83;
case 83:
if ( (*p) == 58u )
goto tr114;
goto st0;
tr114:
#line 28 "src/Utils/IP.rl"
{
ip_family = AF_INET6;
}
goto st164;
st164:
if ( ++p == pe )
goto _test_eof164;
case 164:
#line 2941 "src/Utils/IP.cpp"
switch( (*p) ) {
case 48u: goto tr164;
case 49u: goto tr165;
case 50u: goto tr166;
}
if ( (*p) < 65u ) {
if ( 51u <= (*p) && (*p) <= 57u )
goto tr167;
} else if ( (*p) > 70u ) {
if ( 97u <= (*p) && (*p) <= 102u )
goto tr168;
} else
goto tr168;
goto st0;
tr164:
#line 28 "src/Utils/IP.rl"
{
ip_family = AF_INET6;
}
goto st165;
st165:
if ( ++p == pe )
goto _test_eof165;
case 165:
#line 2966 "src/Utils/IP.cpp"
switch( (*p) ) {
case 46u: goto st46;
case 58u: goto st84;
}
if ( (*p) < 65u ) {
if ( 48u <= (*p) && (*p) <= 57u )
goto tr169;
} else if ( (*p) > 70u ) {
if ( 97u <= (*p) && (*p) <= 102u )
goto tr169;
} else
goto tr169;
goto st0;
tr169:
#line 28 "src/Utils/IP.rl"
{
ip_family = AF_INET6;
}
goto st166;
st166:
if ( ++p == pe )
goto _test_eof166;
case 166:
#line 2990 "src/Utils/IP.cpp"
if ( (*p) == 58u )
goto st84;
if ( (*p) < 65u ) {
if ( 48u <= (*p) && (*p) <= 57u )
goto tr171;
} else if ( (*p) > 70u ) {
if ( 97u <= (*p) && (*p) <= 102u )
goto tr171;
} else
goto tr171;
goto st0;
tr171:
#line 28 "src/Utils/IP.rl"
{
ip_family = AF_INET6;
}
goto st167;
st167:
if ( ++p == pe )
goto _test_eof167;
case 167:
#line 3012 "src/Utils/IP.cpp"
if ( (*p) == 58u )
goto st84;
if ( (*p) < 65u ) {
if ( 48u <= (*p) && (*p) <= 57u )
goto tr172;
} else if ( (*p) > 70u ) {
if ( 97u <= (*p) && (*p) <= 102u )
goto tr172;
} else
goto tr172;
goto st0;
tr172:
#line 28 "src/Utils/IP.rl"
{
ip_family = AF_INET6;
}
goto st168;
st168:
if ( ++p == pe )
goto _test_eof168;
case 168:
#line 3034 "src/Utils/IP.cpp"
if ( (*p) == 58u )
goto st84;
goto st0;
st84:
if ( ++p == pe )
goto _test_eof84;
case 84:
switch( (*p) ) {
case 48u: goto tr115;
case 49u: goto tr116;
case 50u: goto tr117;
}
if ( (*p) < 65u ) {
if ( 51u <= (*p) && (*p) <= 57u )
goto tr118;
} else if ( (*p) > 70u ) {
if ( 97u <= (*p) && (*p) <= 102u )
goto tr119;
} else
goto tr119;
goto st0;
tr165:
#line 28 "src/Utils/IP.rl"
{
ip_family = AF_INET6;
}
goto st169;
st169:
if ( ++p == pe )
goto _test_eof169;
case 169:
#line 3066 "src/Utils/IP.cpp"
switch( (*p) ) {
case 46u: goto st46;
case 58u: goto st84;
}
if ( (*p) < 65u ) {
if ( 48u <= (*p) && (*p) <= 57u )
goto tr173;
} else if ( (*p) > 70u ) {
if ( 97u <= (*p) && (*p) <= 102u )
goto tr169;
} else
goto tr169;
goto st0;
tr173:
#line 28 "src/Utils/IP.rl"
{
ip_family = AF_INET6;
}
goto st170;
st170:
if ( ++p == pe )
goto _test_eof170;
case 170:
#line 3090 "src/Utils/IP.cpp"
switch( (*p) ) {
case 46u: goto st46;
case 58u: goto st84;
}
if ( (*p) < 65u ) {
if ( 48u <= (*p) && (*p) <= 57u )
goto tr174;
} else if ( (*p) > 70u ) {
if ( 97u <= (*p) && (*p) <= 102u )
goto tr171;
} else
goto tr171;
goto st0;
tr174:
#line 28 "src/Utils/IP.rl"
{
ip_family = AF_INET6;
}
goto st171;
st171:
if ( ++p == pe )
goto _test_eof171;
case 171:
#line 3114 "src/Utils/IP.cpp"
switch( (*p) ) {
case 46u: goto st46;
case 58u: goto st84;
}
if ( (*p) < 65u ) {
if ( 48u <= (*p) && (*p) <= 57u )
goto tr172;
} else if ( (*p) > 70u ) {
if ( 97u <= (*p) && (*p) <= 102u )
goto tr172;
} else
goto tr172;
goto st0;
tr166:
#line 28 "src/Utils/IP.rl"
{
ip_family = AF_INET6;
}
goto st172;
st172:
if ( ++p == pe )
goto _test_eof172;
case 172:
#line 3138 "src/Utils/IP.cpp"
switch( (*p) ) {
case 46u: goto st46;
case 53u: goto tr175;
case 58u: goto st84;
}
if ( (*p) < 54u ) {
if ( 48u <= (*p) && (*p) <= 52u )
goto tr173;
} else if ( (*p) > 57u ) {
if ( (*p) > 70u ) {
if ( 97u <= (*p) && (*p) <= 102u )
goto tr169;
} else if ( (*p) >= 65u )
goto tr169;
} else
goto tr176;
goto st0;
tr175:
#line 28 "src/Utils/IP.rl"
{
ip_family = AF_INET6;
}
goto st173;
st173:
if ( ++p == pe )
goto _test_eof173;
case 173:
#line 3166 "src/Utils/IP.cpp"
switch( (*p) ) {
case 46u: goto st46;
case 58u: goto st84;
}
if ( (*p) < 54u ) {
if ( 48u <= (*p) && (*p) <= 53u )
goto tr174;
} else if ( (*p) > 57u ) {
if ( (*p) > 70u ) {
if ( 97u <= (*p) && (*p) <= 102u )
goto tr171;
} else if ( (*p) >= 65u )
goto tr171;
} else
goto tr171;
goto st0;
tr176:
#line 28 "src/Utils/IP.rl"
{
ip_family = AF_INET6;
}
goto st174;
st174:
if ( ++p == pe )
goto _test_eof174;
case 174:
#line 3193 "src/Utils/IP.cpp"
switch( (*p) ) {
case 46u: goto st46;
case 58u: goto st84;
}
if ( (*p) < 65u ) {
if ( 48u <= (*p) && (*p) <= 57u )
goto tr171;
} else if ( (*p) > 70u ) {
if ( 97u <= (*p) && (*p) <= 102u )
goto tr171;
} else
goto tr171;
goto st0;
tr167:
#line 28 "src/Utils/IP.rl"
{
ip_family = AF_INET6;
}
goto st175;
st175:
if ( ++p == pe )
goto _test_eof175;
case 175:
#line 3217 "src/Utils/IP.cpp"
switch( (*p) ) {
case 46u: goto st46;
case 58u: goto st84;
}
if ( (*p) < 65u ) {
if ( 48u <= (*p) && (*p) <= 57u )
goto tr176;
} else if ( (*p) > 70u ) {
if ( 97u <= (*p) && (*p) <= 102u )
goto tr169;
} else
goto tr169;
goto st0;
tr168:
#line 28 "src/Utils/IP.rl"
{
ip_family = AF_INET6;
}
goto st176;
st176:
if ( ++p == pe )
goto _test_eof176;
case 176:
#line 3241 "src/Utils/IP.cpp"
if ( (*p) == 58u )
goto st84;
if ( (*p) < 65u ) {
if ( 48u <= (*p) && (*p) <= 57u )
goto tr169;
} else if ( (*p) > 70u ) {
if ( 97u <= (*p) && (*p) <= 102u )
goto tr169;
} else
goto tr169;
goto st0;
st85:
if ( ++p == pe )
goto _test_eof85;
case 85:
if ( (*p) == 58u )
goto st19;
if ( (*p) < 65u ) {
if ( 48u <= (*p) && (*p) <= 57u )
goto st16;
} else if ( (*p) > 70u ) {
if ( 97u <= (*p) && (*p) <= 102u )
goto st16;
} else
goto st16;
goto st0;
}
_test_eof2: cs = 2; goto _test_eof;
_test_eof3: cs = 3; goto _test_eof;
_test_eof4: cs = 4; goto _test_eof;
_test_eof5: cs = 5; goto _test_eof;
_test_eof6: cs = 6; goto _test_eof;
_test_eof7: cs = 7; goto _test_eof;
_test_eof86: cs = 86; goto _test_eof;
_test_eof87: cs = 87; goto _test_eof;
_test_eof88: cs = 88; goto _test_eof;
_test_eof89: cs = 89; goto _test_eof;
_test_eof90: cs = 90; goto _test_eof;
_test_eof8: cs = 8; goto _test_eof;
_test_eof9: cs = 9; goto _test_eof;
_test_eof10: cs = 10; goto _test_eof;
_test_eof11: cs = 11; goto _test_eof;
_test_eof12: cs = 12; goto _test_eof;
_test_eof13: cs = 13; goto _test_eof;
_test_eof14: cs = 14; goto _test_eof;
_test_eof15: cs = 15; goto _test_eof;
_test_eof16: cs = 16; goto _test_eof;
_test_eof17: cs = 17; goto _test_eof;
_test_eof18: cs = 18; goto _test_eof;
_test_eof19: cs = 19; goto _test_eof;
_test_eof20: cs = 20; goto _test_eof;
_test_eof21: cs = 21; goto _test_eof;
_test_eof22: cs = 22; goto _test_eof;
_test_eof23: cs = 23; goto _test_eof;
_test_eof24: cs = 24; goto _test_eof;
_test_eof25: cs = 25; goto _test_eof;
_test_eof26: cs = 26; goto _test_eof;
_test_eof27: cs = 27; goto _test_eof;
_test_eof28: cs = 28; goto _test_eof;
_test_eof29: cs = 29; goto _test_eof;
_test_eof30: cs = 30; goto _test_eof;
_test_eof31: cs = 31; goto _test_eof;
_test_eof32: cs = 32; goto _test_eof;
_test_eof33: cs = 33; goto _test_eof;
_test_eof34: cs = 34; goto _test_eof;
_test_eof35: cs = 35; goto _test_eof;
_test_eof36: cs = 36; goto _test_eof;
_test_eof37: cs = 37; goto _test_eof;
_test_eof38: cs = 38; goto _test_eof;
_test_eof39: cs = 39; goto _test_eof;
_test_eof40: cs = 40; goto _test_eof;
_test_eof41: cs = 41; goto _test_eof;
_test_eof42: cs = 42; goto _test_eof;
_test_eof43: cs = 43; goto _test_eof;
_test_eof44: cs = 44; goto _test_eof;
_test_eof45: cs = 45; goto _test_eof;
_test_eof46: cs = 46; goto _test_eof;
_test_eof47: cs = 47; goto _test_eof;
_test_eof48: cs = 48; goto _test_eof;
_test_eof49: cs = 49; goto _test_eof;
_test_eof50: cs = 50; goto _test_eof;
_test_eof91: cs = 91; goto _test_eof;
_test_eof92: cs = 92; goto _test_eof;
_test_eof93: cs = 93; goto _test_eof;
_test_eof94: cs = 94; goto _test_eof;
_test_eof51: cs = 51; goto _test_eof;
_test_eof52: cs = 52; goto _test_eof;
_test_eof53: cs = 53; goto _test_eof;
_test_eof54: cs = 54; goto _test_eof;
_test_eof55: cs = 55; goto _test_eof;
_test_eof56: cs = 56; goto _test_eof;
_test_eof57: cs = 57; goto _test_eof;
_test_eof58: cs = 58; goto _test_eof;
_test_eof59: cs = 59; goto _test_eof;
_test_eof60: cs = 60; goto _test_eof;
_test_eof61: cs = 61; goto _test_eof;
_test_eof62: cs = 62; goto _test_eof;
_test_eof95: cs = 95; goto _test_eof;
_test_eof96: cs = 96; goto _test_eof;
_test_eof97: cs = 97; goto _test_eof;
_test_eof63: cs = 63; goto _test_eof;
_test_eof64: cs = 64; goto _test_eof;
_test_eof65: cs = 65; goto _test_eof;
_test_eof66: cs = 66; goto _test_eof;
_test_eof67: cs = 67; goto _test_eof;
_test_eof68: cs = 68; goto _test_eof;
_test_eof69: cs = 69; goto _test_eof;
_test_eof98: cs = 98; goto _test_eof;
_test_eof70: cs = 70; goto _test_eof;
_test_eof99: cs = 99; goto _test_eof;
_test_eof100: cs = 100; goto _test_eof;
_test_eof101: cs = 101; goto _test_eof;
_test_eof102: cs = 102; goto _test_eof;
_test_eof103: cs = 103; goto _test_eof;
_test_eof71: cs = 71; goto _test_eof;
_test_eof104: cs = 104; goto _test_eof;
_test_eof105: cs = 105; goto _test_eof;
_test_eof106: cs = 106; goto _test_eof;
_test_eof107: cs = 107; goto _test_eof;
_test_eof108: cs = 108; goto _test_eof;
_test_eof109: cs = 109; goto _test_eof;
_test_eof110: cs = 110; goto _test_eof;
_test_eof111: cs = 111; goto _test_eof;
_test_eof112: cs = 112; goto _test_eof;
_test_eof113: cs = 113; goto _test_eof;
_test_eof114: cs = 114; goto _test_eof;
_test_eof115: cs = 115; goto _test_eof;
_test_eof116: cs = 116; goto _test_eof;
_test_eof72: cs = 72; goto _test_eof;
_test_eof117: cs = 117; goto _test_eof;
_test_eof118: cs = 118; goto _test_eof;
_test_eof119: cs = 119; goto _test_eof;
_test_eof120: cs = 120; goto _test_eof;
_test_eof121: cs = 121; goto _test_eof;
_test_eof122: cs = 122; goto _test_eof;
_test_eof123: cs = 123; goto _test_eof;
_test_eof124: cs = 124; goto _test_eof;
_test_eof125: cs = 125; goto _test_eof;
_test_eof126: cs = 126; goto _test_eof;
_test_eof127: cs = 127; goto _test_eof;
_test_eof128: cs = 128; goto _test_eof;
_test_eof129: cs = 129; goto _test_eof;
_test_eof73: cs = 73; goto _test_eof;
_test_eof130: cs = 130; goto _test_eof;
_test_eof131: cs = 131; goto _test_eof;
_test_eof132: cs = 132; goto _test_eof;
_test_eof133: cs = 133; goto _test_eof;
_test_eof134: cs = 134; goto _test_eof;
_test_eof135: cs = 135; goto _test_eof;
_test_eof136: cs = 136; goto _test_eof;
_test_eof137: cs = 137; goto _test_eof;
_test_eof138: cs = 138; goto _test_eof;
_test_eof139: cs = 139; goto _test_eof;
_test_eof140: cs = 140; goto _test_eof;
_test_eof141: cs = 141; goto _test_eof;
_test_eof142: cs = 142; goto _test_eof;
_test_eof74: cs = 74; goto _test_eof;
_test_eof143: cs = 143; goto _test_eof;
_test_eof144: cs = 144; goto _test_eof;
_test_eof145: cs = 145; goto _test_eof;
_test_eof146: cs = 146; goto _test_eof;
_test_eof147: cs = 147; goto _test_eof;
_test_eof148: cs = 148; goto _test_eof;
_test_eof149: cs = 149; goto _test_eof;
_test_eof150: cs = 150; goto _test_eof;
_test_eof151: cs = 151; goto _test_eof;
_test_eof152: cs = 152; goto _test_eof;
_test_eof153: cs = 153; goto _test_eof;
_test_eof154: cs = 154; goto _test_eof;
_test_eof155: cs = 155; goto _test_eof;
_test_eof75: cs = 75; goto _test_eof;
_test_eof156: cs = 156; goto _test_eof;
_test_eof157: cs = 157; goto _test_eof;
_test_eof158: cs = 158; goto _test_eof;
_test_eof159: cs = 159; goto _test_eof;
_test_eof160: cs = 160; goto _test_eof;
_test_eof161: cs = 161; goto _test_eof;
_test_eof162: cs = 162; goto _test_eof;
_test_eof163: cs = 163; goto _test_eof;
_test_eof76: cs = 76; goto _test_eof;
_test_eof77: cs = 77; goto _test_eof;
_test_eof78: cs = 78; goto _test_eof;
_test_eof79: cs = 79; goto _test_eof;
_test_eof80: cs = 80; goto _test_eof;
_test_eof81: cs = 81; goto _test_eof;
_test_eof82: cs = 82; goto _test_eof;
_test_eof83: cs = 83; goto _test_eof;
_test_eof164: cs = 164; goto _test_eof;
_test_eof165: cs = 165; goto _test_eof;
_test_eof166: cs = 166; goto _test_eof;
_test_eof167: cs = 167; goto _test_eof;
_test_eof168: cs = 168; goto _test_eof;
_test_eof84: cs = 84; goto _test_eof;
_test_eof169: cs = 169; goto _test_eof;
_test_eof170: cs = 170; goto _test_eof;
_test_eof171: cs = 171; goto _test_eof;
_test_eof172: cs = 172; goto _test_eof;
_test_eof173: cs = 173; goto _test_eof;
_test_eof174: cs = 174; goto _test_eof;
_test_eof175: cs = 175; goto _test_eof;
_test_eof176: cs = 176; goto _test_eof;
_test_eof85: cs = 85; goto _test_eof;
_test_eof: {}
_out: {}
}
#line 63 "src/Utils/IP.rl"
// Ensure that the parsing has consumed all the given length.
if(ip_len == (size_t)(p - (const unsigned char*)ip))
return ip_family;
else
return AF_UNSPEC;
}
void IP::GetAddressInfo(const struct sockaddr* addr, int* family, std::string &ip, MS_PORT* port) {
MS_TRACE();
char _ip[INET6_ADDRSTRLEN+1];
int err;
switch(addr->sa_family) {
case AF_INET:
err = uv_inet_ntop(AF_INET, &((struct sockaddr_in*)addr)->sin_addr, _ip, INET_ADDRSTRLEN);
if (err)
MS_ABORT("uv_inet_ntop() failed: %s", uv_strerror(err));
*port = (MS_PORT)ntohs(((struct sockaddr_in*)addr)->sin_port);
break;
case AF_INET6:
err = uv_inet_ntop(AF_INET6, &((struct sockaddr_in6*)addr)->sin6_addr, _ip, INET6_ADDRSTRLEN);
if (err)
MS_ABORT("uv_inet_ntop() failed: %s", uv_strerror(err));
*port = (MS_PORT)ntohs(((struct sockaddr_in6*)addr)->sin6_port);
break;
default:
MS_ABORT("unknown network family: %d", (int)addr->sa_family);
}
*family = addr->sa_family;
ip.assign(_ip);
}
} // namespace Utils
#define MS_CLASS "Utils::IP"
#include "Utils.h"
#include "Logger.h"
#include <uv.h>
namespace Utils {
int IP::GetFamily(const char *ip, size_t ip_len) {
MS_TRACE();
int ip_family = 0;
/**
* Ragel: machine definition
*/
%%{
machine IPParser;
alphtype unsigned char;
action on_ipv4 {
ip_family = AF_INET;
}
action on_ipv6 {
ip_family = AF_INET6;
}
include core_grammar "../core_grammar.rl";
main := IPv4address @on_ipv4 |
IPv6address @on_ipv6;
}%%
/**
* Ragel: %%write data
* This generates Ragel's static variables.
*/
%%write data;
// Used by Ragel:
size_t cs;
const unsigned char* p;
const unsigned char* pe;
p = (const unsigned char*)ip;
pe = p + ip_len;
/**
* Ragel: %%write init
*/
%%write init;
/**
* Ragel: %%write exec
* This updates cs variable needed by Ragel.
*/
%%write exec;
// Ensure that the parsing has consumed all the given length.
if(ip_len == (size_t)(p - (const unsigned char*)ip))
return ip_family;
else
return AF_UNSPEC;
}
void IP::GetAddressInfo(const struct sockaddr* addr, int* family, std::string &ip, MS_PORT* port) {
MS_TRACE();
char _ip[INET6_ADDRSTRLEN+1];
int err;
switch(addr->sa_family) {
case AF_INET:
err = uv_inet_ntop(AF_INET, &((struct sockaddr_in*)addr)->sin_addr, _ip, INET_ADDRSTRLEN);
if (err)
MS_ABORT("uv_inet_ntop() failed: %s", uv_strerror(err));
*port = (MS_PORT)ntohs(((struct sockaddr_in*)addr)->sin_port);
break;
case AF_INET6:
err = uv_inet_ntop(AF_INET6, &((struct sockaddr_in6*)addr)->sin6_addr, _ip, INET6_ADDRSTRLEN);
if (err)
MS_ABORT("uv_inet_ntop() failed: %s", uv_strerror(err));
*port = (MS_PORT)ntohs(((struct sockaddr_in6*)addr)->sin6_port);
break;
default:
MS_ABORT("unknown network family: %d", (int)addr->sa_family);
}
*family = addr->sa_family;
ip.assign(_ip);
}
} // namespace Utils
#define MS_CLASS "Utils::Socket"
#include "Utils.h"
#include "MediaSoupError.h"
#include "Logger.h"
#include <cerrno>
#include <fcntl.h>
namespace Utils {
void Socket::BuildSocketPair(int family, int type, int* fds) {
MS_TRACE();
// Old Linux/BSD kernels and OSX don't support setting SOCK_NONBLOCK and/or
// SOCK_CLOEXEC during socket creation. In those cases use fcntl().
#if defined(SOCK_NONBLOCK)
type |= SOCK_NONBLOCK;
#endif
#if defined(SOCK_CLOEXEC)
type |= SOCK_CLOEXEC;
#endif
// Create a pair of connected sockets.
if (socketpair(family, type, 0, fds))
MS_THROW_ERROR("socketpair() failed: %s", std::strerror(errno));
#if !defined(SOCK_NONBLOCK)
if (! (SetNonBlock(fds[0]) && SetNonBlock(fds[1])))
MS_THROW_ERROR("error setting sockets as non-blocking");
#endif
#if !defined(SOCK_CLOEXEC)
if (! (SetCloExec(fds[0]) && SetCloExec(fds[1])))
MS_THROW_ERROR("error setting sockets as close-exec");
#endif
}
bool Socket::SetNonBlock(int fd) {
MS_TRACE();
int flags;
int ret;
flags = fcntl(fd, F_GETFL);
if (flags == -1) {
MS_ERROR("fcntl() failed when getting flags");
return false;
}
ret = fcntl(fd, F_SETFL, flags | O_NONBLOCK);
if (ret == -1) {
MS_ERROR("fcntl() failed when setting O_NONBLOCK: %s", std::strerror(errno));
return false;
}
return true;
}
bool Socket::SetCloExec(int fd) {
MS_TRACE();
int flags;
int ret;
flags = fcntl(fd, F_GETFD);
if (flags == -1) {
MS_ERROR("fcntl() failed when getting flags");
return false;
}
ret = fcntl(fd, F_SETFD, flags | FD_CLOEXEC);
if (ret == -1) {
MS_ERROR("fcntl() failed when setting FD_CLOEXEC: %s", std::strerror(errno));
return false;
}
return true;
}
} // namespace Utils
#!/usr/bin/env bash
ROOT_DIR="../../"
RAGEL_FILE="src/Utils/IP.rl"
RAGEL_COMPILE_TYPE="-G2"
PRODUCTION=false
set -e
which ragel >/dev/null
if [ $? -ne 0 ] ; then
echo ">>> ERROR: ragel binary not found, cannot compile the Ragel grammar" >&2
exit 1
else
ragel -v
fi
cd $ROOT_DIR
cpp_file="${RAGEL_FILE%.rl}.cpp"
echo ">>> INFO: compiling $RAGEL_FILE:"
if [ "$PRODUCTION" == "true" ] ; then
show_ragel_lines="-L"
else
show_ragel_lines=""
fi
ragel $RAGEL_COMPILE_TYPE -C $RAGEL_FILE $show_ragel_lines -o $cpp_file
# Remove unused Ragel variables.
sed -i".delete_me" -E "s/.*static const int IPParser_(en_main|first_final|error).*//g" $cpp_file
echo ">>> DEBUG: Ragel's unused static variables removed from $cpp_file"
rm -f ${cpp_file}.delete_me
echo ">>> INFO: $cpp_file generated"
#define MS_CLASS "Version"
#include "Version.h"
#include "Logger.h"
/* Static variables. */
const int Version::versionMajor = 0;
const int Version::versionMinor = 0;
const int Version::versionTiny = 1;
const std::string Version::name = "MediaSoup";
const std::string Version::command = "mediasoup";
const std::string Version::copyright = "Copyright (c) 2014 Iñaki Baz Castillo | https://github.com/ibc";
/* Static methods .*/
const std::string Version::GetVersion() {
MS_TRACE();
std::string version;
version.append(std::to_string(Version::versionMajor));
version.append(".");
version.append(std::to_string(Version::versionMinor));
version.append(".");
version.append(std::to_string(Version::versionTiny));
return version;
}
const std::string Version::GetNameAndVersion() {
MS_TRACE();
std::string name_and_version;
name_and_version.append(Version::name);
name_and_version.append(" v");
name_and_version.append(Version::GetVersion());
return name_and_version;
}
#define MS_CLASS "Worker"
#include "Worker.h"
#include "Utils.h"
#include "LibUV.h"
#include "ControlProtocol/messages.h"
#include "MediaSoupError.h"
#include "Logger.h"
#include <string>
#include <csignal> // sigaction(), pthread_sigmask()
#include <cerrno>
/* Static variables. */
Worker::Workers Worker::workers;
int Worker::numWorkers = 0;
std::atomic<int> Worker::numWorkersRunning {0};
/* Static methods. */
void Worker::ThreadInit(int workerId) {
Logger::ThreadInit("worker #" + std::to_string(workerId));
MS_TRACE();
LibUV::ThreadInit();
Utils::Crypto::ThreadInit();
}
void Worker::ThreadDestroy() {
MS_TRACE();
LibUV::ThreadDestroy();
Utils::Crypto::ThreadDestroy();
}
void Worker::SetWorker(int workerId, Worker* worker) {
MS_TRACE();
// Main thread calls this method with nullptr as worker. In that case the
// workerId entry MUST NOT already exit.
if (! worker) {
if (Worker::workers.find(workerId) != Worker::workers.end())
MS_ABORT("entry with key %d already in the map", workerId);
Worker::workers[workerId] = nullptr;
}
// Each Worker (in its own thread) calls this method to insert itself in
// the map. In that case the key MUST exist.
else {
if (Worker::workers.find(workerId) == Worker::workers.end())
MS_ABORT("entry with key %d not present in the map", workerId);
Worker::workers[workerId] = worker;
}
}
int Worker::CountWorkers() {
MS_TRACE();
if (! Worker::numWorkers) {
Worker::numWorkers = workers.size();
}
return Worker::numWorkers;
}
bool Worker::AreAllWorkersRunning() {
MS_TRACE();
if (Worker::numWorkersRunning.load(std::memory_order_relaxed) == Worker::CountWorkers())
return true;
else
return false;
}
int Worker::GetControlProtocolRemoteSocket(int workerId) {
MS_TRACE();
Workers::iterator it = Worker::workers.find(workerId);
// Ensure it does exist in the map of Workers.
if (it == Worker::workers.end())
MS_ABORT("Worker with workerId %d not present in the map", workerId);
Worker* worker = it->second;
return worker->GetControlProtocolRemoteSocket();
}
/* Instance methods. */
Worker::Worker(int workerId) :
workerId(workerId)
{
MS_TRACE();
// Block signals that must just be delivered to Dispatcher thread.
BlockSignals();
// Add this worker to the map.
// NOTE: This is thread-safe given that I don't alter the map (but just
// the values of already allocated entries in the map).
Worker::SetWorker(this->workerId, this);
// Build a pair of connected UnixSocket in stream mode.
int fds[2] {-1,-1};
try {
Utils::Socket::BuildSocketPair(AF_UNIX, SOCK_STREAM, fds);
}
catch (const MediaSoupError &error) {
MS_THROW_ERROR("error building a socket pair for the ControlProtocol Unix socket: %s", error.what());
}
// Store the first paired socket for Dispatcher's usage.
this->controlProtocolRemoteSocket = fds[0];
try {
this->controlProtocolUnixStreamSocket = new ControlProtocol::UnixStreamSocket(this, fds[1]);
}
catch (const MediaSoupError &error) {
MS_THROW_ERROR("error creating a ControlProtocol Unix socket for Dispatcher: %s", error.what());
}
MS_DEBUG("ControlProtocol Unix socket for Dispatcher ready");
// TODO: TMP
if (this->workerId == 1) {
try {
this->room = new RTC::Room();
}
catch (const MediaSoupError &error) {
MS_ERROR("---- TEST: error creating a RTC Room: %s", error.what());
}
}
MS_DEBUG("Worker #%d running", this->workerId);
// Increase the static variable numWorkersRunning.
Worker::numWorkersRunning++;
// Run the loop.
LibUV::RunLoop();
MS_DEBUG("libuv loop ends");
}
Worker::~Worker() {
MS_TRACE();
}
void Worker::Close() {
MS_TRACE();
// TMP: close RTC::Room.
if (this->room)
this->room->Close();
}
int Worker::GetControlProtocolRemoteSocket() {
return this->controlProtocolRemoteSocket;
}
void Worker::BlockSignals() {
MS_TRACE();
int err;
sigset_t signal_mask;
sigemptyset(&signal_mask);
// Block some signals to ensure that they are just delivered to the Dispatcher thread.
sigaddset(&signal_mask, SIGUSR1);
sigaddset(&signal_mask, SIGINT);
sigaddset(&signal_mask, SIGTERM);
err = pthread_sigmask(SIG_BLOCK, &signal_mask, nullptr);
if (err)
MS_ABORT("pthread_sigmask() failed: %s", std::strerror(errno));
}
void Worker::onControlProtocolMessage(ControlProtocol::UnixStreamSocket* unixSocket, ControlProtocol::Message* msg, const MS_BYTE* raw, size_t len) {
MS_TRACE();
MS_DEBUG("ControlProtocol message received from Dispatcher");
msg->Dump();
// TMP
bool sendBackToDispatcher = false;
if (sendBackToDispatcher) {
MS_INFO("sending msg back to Dispatcher...");
unixSocket->Write(raw, len);
}
// TODO: process the ControlProtocol::Message.
}
void Worker::onControlProtocolUnixStreamSocketClosed(ControlProtocol::UnixStreamSocket* unixSocket, bool is_closed_by_peer) {
MS_TRACE();
if (is_closed_by_peer)
MS_DEBUG("ControlProtocol Unix socket for Dispatcher remotely closed");
else
MS_DEBUG("ControlProtocol Unix socket for Dispatcher locally closed");
// Call Close() to terminate all the active handles.
Close();
}
%%{
machine core_grammar;
CRLF = "\r\n";
SP = 0x20; # Space.
DIGIT = "0".."9";
ALPHA = "a".."z" | "A".."Z";
alphanum = ALPHA | DIGIT;
HEXDIG = DIGIT | "A"i | "B"i | "C"i | "D"i | "E"i | "F"i;
VCHAR = 0x21..0x7E; # Visible (printing) characters.
POS_DIGIT = "1".."9";
integer = POS_DIGIT DIGIT*;
# Max unsigned long (in 32 bits) is +4.294.967.295, so just allow 9 digits.
ULONG = DIGIT{1,9};
decimal_uchar = DIGIT | ( 0x31..0x39 DIGIT ) | ( "1" DIGIT{2} ) | ( "2" 0x30..0x34 DIGIT ) |
( "25" 0x30..0x35 ); # 0-255.
token = ( 0x21 | 0x23..0x27 | 0x2A..0x2B | 0x2D..0x2E | 0x30..0x39 | 0x41..0x5A |
0x5E..0x7E )+;
byte_string = ( 0x01..0x09 | 0x0B..0x0C | 0x0E..0xFF )+; # Any byte except NULL, CR or LF.
non_ws_string = ( VCHAR | 0x80..0xFF )+; # String of visible characters.
text = byte_string;
IPv4address = decimal_uchar "." decimal_uchar "." decimal_uchar "." decimal_uchar;
h16 = HEXDIG{1,4};
ls32 = ( h16 ":" h16 ) | IPv4address;
IPv6address = ( ( h16 ":" ){6} ls32 ) |
( "::" ( h16 ":" ){5} ls32 ) |
( h16? "::" ( h16 ":" ){4} ls32 ) |
( ( ( h16 ":" )? h16 )? "::" ( h16 ":" ){3} ls32 ) |
( ( ( h16 ":" ){,2} h16 )? "::" ( h16 ":" ){2} ls32 ) |
( ( ( h16 ":" ){,3} h16 )? "::" h16 ":" ls32 ) |
( ( ( h16 ":" ){,4} h16 )? "::" ls32 ) |
( ( ( h16 ":" ){,5} h16 )? "::" h16 ) |
( ( ( h16 ":" ){,6} h16 )? "::" );
port = DIGIT{1,4} |
"1".."5" DIGIT{4} |
"6" "0".."4" DIGIT{3} |
"6" "5" "0".."4" DIGIT{2} |
"6" "5" "5" "0".."2" DIGIT |
"6" "5" "5" "3" "0".."5";
domainlabel = alphanum | ( alphanum ( alphanum | "-" | "_" )* alphanum );
toplabel = ALPHA | ( ALPHA ( alphanum | "-" | "_" )* alphanum );
# TODO: Probably relax it and allow "anything".
FQDN = ( domainlabel "." )* toplabel "."?;
IPv4address_multicast = IPv4address "/" decimal_uchar ( "/" integer )?;
IPv6address_multicast = IPv6address ( "/" integer )?;
unicast_address = IPv4address | IPv6address | FQDN; # NOTE: let's remove non_ws_string.
multicast_address = IPv4address_multicast | IPv6address_multicast | FQDN; # NOTE: let's remove non_ws_string.
}%%
#define MS_CLASS "SignalsHandler"
#include "handles/SignalsHandler.h"
#include "LibUV.h"
#include "MediaSoupError.h"
#include "Logger.h"
/* Static methods for UV callbacks. */
static inline
void on_signal(uv_signal_t* handle, int signum) {
static_cast<SignalsHandler*>(handle->data)->onUvSignal(signum);
}
static inline
void on_close(uv_handle_t* handle) {
delete handle;
}
/* Instance methods. */
SignalsHandler::SignalsHandler(Listener* listener) :
listener(listener)
{
MS_TRACE();
}
void SignalsHandler::AddSignal(int signum, std::string name) {
MS_TRACE();
int err;
uv_signal_t* uvHandle = new uv_signal_t;
uvHandle->data = (void*)this;
err = uv_signal_init(LibUV::GetLoop(), uvHandle);
if (err) {
delete uvHandle;
MS_THROW_ERROR("uv_signal_init() failed for signal %s: %s", name.c_str(), uv_strerror(err));
}
err = uv_signal_start(uvHandle, (uv_signal_cb)on_signal, signum);
if (err)
MS_THROW_ERROR("uv_signal_start() failed for signal %s: %s", name.c_str(), uv_strerror(err));
// Enter the UV handle into the vector.
this->uvHandles.push_back(uvHandle);
MS_DEBUG("signal %s added", name.c_str());
}
void SignalsHandler::Close() {
MS_TRACE();
for (auto uvHandle : uvHandles) {
uv_close((uv_handle_t*)uvHandle, (uv_close_cb)on_close);
}
// Notify the listener.
this->listener->onSignalsHandlerClosed(this);
// And delete this.
delete this;
}
inline
void SignalsHandler::onUvSignal(int signum) {
MS_TRACE();
// Notify the listener.
this->listener->onSignal(this, signum);
}
#define MS_CLASS "TCPConnection"
#include "handles/TCPConnection.h"
#include "Utils.h"
#include "LibUV.h"
#include "MediaSoupError.h"
#include "Logger.h"
#include <cstring> // std::memcpy()
#include <cstdlib> // std::malloc(), std::free()
#define RETURN_IF_CLOSING() \
if (this->isClosing) { \
MS_DEBUG("in closing state, doing nothing"); \
return; \
}
/* Static methods for UV callbacks. */
static inline
void on_alloc(uv_handle_t* handle, size_t suggested_size, uv_buf_t* buf) {
static_cast<TCPConnection*>(handle->data)->onUvReadAlloc(suggested_size, buf);
}
static inline
void on_read(uv_stream_t* handle, ssize_t nread, const uv_buf_t* buf) {
static_cast<TCPConnection*>(handle->data)->onUvRead(nread, buf);
}
static inline
void on_write(uv_write_t* req, int status) {
TCPConnection::UvWriteData* write_data = static_cast<TCPConnection::UvWriteData*>(req->data);
TCPConnection* connection = write_data->connection;
// Delete the UvWriteData struct (which includes the uv_req_t and the store char[]).
std::free(write_data);
// Just notify the TCPConnection when error.
if (status)
connection->onUvWriteError(status);
}
static inline
void on_shutdown(uv_shutdown_t* req, int status) {
static_cast<TCPConnection*>(req->data)->onUvShutdown(req, status);
}
static inline
void on_close(uv_handle_t* handle) {
static_cast<TCPConnection*>(handle->data)->onUvClosed();
}
/* Instance methods. */
TCPConnection::TCPConnection(size_t bufferSize) :
bufferSize(bufferSize)
{
MS_TRACE();
this->uvHandle = new uv_tcp_t;
this->uvHandle->data = (void*)this;
// NOTE: Don't allocate the buffer here. Instead wait for the first uv_alloc_cb().
}
TCPConnection::~TCPConnection() {
MS_TRACE();
if (this->uvHandle)
delete this->uvHandle;
if (this->buffer)
delete[] this->buffer;
}
void TCPConnection::Setup(Listener* listener, const std::string &localIP, MS_PORT localPort) {
MS_TRACE();
int err;
// Set the UV handle.
err = uv_tcp_init(LibUV::GetLoop(), this->uvHandle);
if (err) {
delete this->uvHandle;
this->uvHandle = nullptr;
MS_THROW_ERROR("uv_tcp_init() failed: %s", uv_strerror(err));
}
// Set the listener.
this->listener = listener;
// Set the local address.
this->localIP = localIP;
this->localPort = localPort;
}
void TCPConnection::Start() {
MS_TRACE();
RETURN_IF_CLOSING();
int err;
err = uv_read_start((uv_stream_t*)this->uvHandle, (uv_alloc_cb)on_alloc, (uv_read_cb)on_read);
if (err)
MS_THROW_ERROR("uv_read_start() failed: %s", uv_strerror(err));
// Get the peer address.
if (! SetPeerAddress())
MS_THROW_ERROR("error setting peer IP and port");
}
void TCPConnection::Write(const MS_BYTE* data, size_t len) {
MS_TRACE();
RETURN_IF_CLOSING();
if (len == 0) {
MS_DEBUG("ignoring 0 length data");
return;
}
uv_buf_t buffer;
int written;
int err;
// First try uv_try_write(). In case it can not directly write all the given
// data then build a uv_req_t and use uv_write().
buffer = uv_buf_init((char*)data, len);
written = uv_try_write((uv_stream_t*)this->uvHandle, &buffer, 1);
// All the data was written. Done.
if (written == (int)len) {
return;
}
// Cannot write any data at first time. Use uv_write().
else if (written == UV_EAGAIN || written == UV_ENOSYS) {
// Set written to 0 so pending_len can be properly calculated.
written = 0;
}
// Error. Should not happen.
else if (written < 0) {
MS_NOTICE("uv_try_write() failed: %s | closing the connection", uv_strerror(written));
Close();
return;
}
// TMP: remove this.
MS_DEBUG("could just write %zu bytes (%zu given) at first time, using uv_write() now", (size_t)written, len);
size_t pending_len = len - written;
// Allocate a special UvWriteData struct pointer.
UvWriteData* write_data = (UvWriteData*)std::malloc(sizeof(UvWriteData) + pending_len);
write_data->connection = this;
std::memcpy(write_data->store, data + written, pending_len);
write_data->req.data = (void*)write_data;
buffer = uv_buf_init((char*)write_data->store, pending_len);
err = uv_write(&write_data->req, (uv_stream_t*)this->uvHandle, &buffer, 1, (uv_write_cb)on_write);
if (err)
MS_ABORT("uv_write() failed: %s", uv_strerror(err));
}
void TCPConnection::Write(const MS_BYTE* data1, size_t len1, const MS_BYTE* data2, size_t len2) {
MS_TRACE();
RETURN_IF_CLOSING();
if (len1 == 0 && len2 == 0) {
MS_DEBUG("ignoring 0 length data1 and data2");
return;
}
size_t total_len = len1 + len2;
uv_buf_t buffers[2];
int written;
int err;
// First try uv_try_write(). In case it can not directly write all the given
// data then build a uv_req_t and use uv_write().
buffers[0] = uv_buf_init((char*)data1, len1);
buffers[1] = uv_buf_init((char*)data2, len2);
written = uv_try_write((uv_stream_t*)this->uvHandle, buffers, 2);
// All the data was written. Done.
if (written == (int)total_len) {
return;
}
// Cannot write any data at first time. Use uv_write().
else if (written == UV_EAGAIN || written == UV_ENOSYS) {
// Set written to 0 so pending_len can be properly calculated.
written = 0;
}
// Error. Should not happen.
else if (written < 0) {
MS_NOTICE("uv_try_write() failed: %s | closing the connection", uv_strerror(written));
Close();
return;
}
// TMP: remove this.
MS_DEBUG("could just write %zu bytes (%zu given) at first time, using uv_write() now", (size_t)written, total_len);
size_t pending_len = total_len - written;
// Allocate a special UvWriteData struct pointer.
UvWriteData* write_data = (UvWriteData*)std::malloc(sizeof(UvWriteData) + pending_len);
write_data->connection = this;
// If the first buffer was not entirely written then splice it.
if ((size_t)written < len1) {
std::memcpy(write_data->store, data1 + (size_t)written, len1 - (size_t)written);
std::memcpy(write_data->store + (len1 - (size_t)written), data2, len2);
}
// Otherwise just take the pending data in the second buffer.
else {
std::memcpy(write_data->store, data2 + ((size_t)written - len1), len2 - ((size_t)written - len1));
}
write_data->req.data = (void*)write_data;
uv_buf_t buffer = uv_buf_init((char*)write_data->store, pending_len);
err = uv_write(&write_data->req, (uv_stream_t*)this->uvHandle, &buffer, 1, (uv_write_cb)on_write);
if (err)
MS_ABORT("uv_write() failed: %s", uv_strerror(err));
}
void TCPConnection::Close() {
MS_TRACE();
RETURN_IF_CLOSING();
int err;
this->isClosing = true;
// Don't read more.
err = uv_read_stop((uv_stream_t*)this->uvHandle);
if (err)
MS_ABORT("uv_read_stop() failed: %s", uv_strerror(err));
// If there is no error and the peer didn't close its connection side then close gracefully.
if (! this->hasError && ! this->isClosedByPeer) {
// Use uv_shutdown() so pending data to be written will be sent to the peer
// before closing.
uv_shutdown_t* req = new uv_shutdown_t;
req->data = (void*)this;
err = uv_shutdown(req, (uv_stream_t*)this->uvHandle, (uv_shutdown_cb)on_shutdown);
if (err)
MS_ABORT("uv_shutdown() failed: %s", uv_strerror(err));
}
// Otherwise directly close the socket.
else {
uv_close((uv_handle_t*)this->uvHandle, (uv_close_cb)on_close);
}
}
void TCPConnection::Dump() {
MS_DEBUG("[TCP | local address: %s : %u | peer address: %s : %u | status: %s]",
this->localIP.c_str(), (unsigned int)this->localPort,
this->peerIP.c_str(), (unsigned int)this->peerPort,
(! this->isClosing) ? "open" : "closed");
}
bool TCPConnection::SetPeerAddress() {
MS_TRACE();
int err;
int len = sizeof(this->peerAddr);
err = uv_tcp_getpeername(this->uvHandle, (struct sockaddr*)&this->peerAddr, &len);
if (err) {
MS_ERROR("uv_tcp_getpeername() failed: %s", uv_strerror(err));
return false;
}
int family;
Utils::IP::GetAddressInfo((const struct sockaddr*)&this->peerAddr, &family, this->peerIP, &this->peerPort);
return true;
}
inline
void TCPConnection::onUvReadAlloc(size_t suggested_size, uv_buf_t* buf) {
MS_TRACE();
// If this is the first call to onUvReadAlloc() then allocate the receiving buffer now.
if (! this->buffer)
this->buffer = new MS_BYTE[this->bufferSize];
// Tell UV to write after the last data byte in the buffer.
buf->base = (char *)(this->buffer + this->bufferDataLen);
// Give UV all the remaining space in the buffer.
if (this->bufferSize > this->bufferDataLen) {
buf->len = this->bufferSize - this->bufferDataLen;
MS_DEBUG("available space in the buffer: %zu", buf->len);
}
else {
buf->len = 0;
MS_WARN("no available space in the buffer");
}
}
inline
void TCPConnection::onUvRead(ssize_t nread, const uv_buf_t* buf) {
MS_TRACE();
RETURN_IF_CLOSING();
if (nread == 0)
return;
// Data received.
if (nread > 0) {
// Update the buffer data length.
this->bufferDataLen += (size_t)nread;
// Notify the subclass.
userOnTCPConnectionRead((MS_BYTE*)buf->base, nread);
}
// Client disconneted.
else if (nread == UV_EOF || nread == UV_ECONNRESET) {
MS_DEBUG("connection closed by client | closing server side");
this->isClosedByPeer = true;
// Close server side of the connection.
Close();
}
// Some error.
else {
MS_NOTICE("read error: %s | closing the connection", uv_strerror(nread));
this->hasError = true;
// Close server side of the connection.
// NOTE: calling uv_read_stop() upon EOF is a MUST.
Close();
}
}
inline
void TCPConnection::onUvWriteError(int error) {
MS_TRACE();
if (this->isClosing)
return;
if (error == UV_EPIPE || error == UV_ENOTCONN) {
MS_DEBUG("write error: %s | closing the connection", uv_strerror(error));
}
else {
MS_NOTICE("write error: %s | closing the connection", uv_strerror(error));
this->hasError = true;
}
Close();
}
inline
void TCPConnection::onUvShutdown(uv_shutdown_t* req, int status) {
MS_TRACE();
delete req;
if (status == UV_EPIPE || status == UV_ENOTCONN || status == UV_ECANCELED)
MS_DEBUG("shutdown error: %s", uv_strerror(status));
else if (status)
MS_NOTICE("shutdown error: %s", uv_strerror(status));
// Now do close the handle.
uv_close((uv_handle_t*)this->uvHandle, (uv_close_cb)on_close);
}
inline
void TCPConnection::onUvClosed() {
MS_TRACE();
// Notify the listener.
this->listener->onTCPConnectionClosed(this, this->isClosedByPeer);
// And delete this.
delete this;
}
#define MS_CLASS "TCPServer"
#include "handles/TCPServer.h"
#include "Utils.h"
#include "LibUV.h"
#include "MediaSoupError.h"
#include "Logger.h"
#define RETURN_IF_CLOSING() \
if (this->isClosing) { \
MS_DEBUG("in closing state, doing nothing"); \
return; \
}
/* Static methods for UV callbacks. */
static inline
void on_connection(uv_stream_t* handle, int status) {
static_cast<TCPServer*>(handle->data)->onUvConnection(status);
}
static inline
void on_close(uv_handle_t* handle) {
static_cast<TCPServer*>(handle->data)->onUvClosed();
}
static inline
void on_error_close(uv_handle_t* handle) {
delete handle;
}
/* Instance methods. */
TCPServer::TCPServer(const std::string &ip, MS_PORT port, int backlog) {
MS_TRACE();
int err;
int flags = 0;
this->uvHandle = new uv_tcp_t;
this->uvHandle->data = (void*)this;
err = uv_tcp_init(LibUV::GetLoop(), this->uvHandle);
if (err) {
delete this->uvHandle;
this->uvHandle = nullptr;
MS_THROW_ERROR("uv_tcp_init() failed: %s", uv_strerror(err));
}
struct sockaddr_storage bind_addr;
switch (Utils::IP::GetFamily(ip)) {
case AF_INET:
err = uv_ip4_addr(ip.c_str(), (int)port, (struct sockaddr_in*)&bind_addr);
if (err)
MS_ABORT("uv_ipv4_addr() failed: %s", uv_strerror(err));
break;
case AF_INET6:
err = uv_ip6_addr(ip.c_str(), (int)port, (struct sockaddr_in6*)&bind_addr);
if (err)
MS_ABORT("uv_ipv6_addr() failed: %s", uv_strerror(err));
// Don't also bind into IPv4 when listening in IPv6.
flags |= UV_TCP_IPV6ONLY;
break;
default:
uv_close((uv_handle_t*)this->uvHandle, (uv_close_cb)on_error_close);
MS_THROW_ERROR("invalid binding IP '%s'", ip.c_str());
break;
}
err = uv_tcp_bind(this->uvHandle, (const struct sockaddr*)&bind_addr, flags);
if (err) {
uv_close((uv_handle_t*)this->uvHandle, (uv_close_cb)on_error_close);
MS_THROW_ERROR("uv_tcp_bind() failed: %s", uv_strerror(err));
}
err = uv_listen((uv_stream_t*)this->uvHandle, backlog, (uv_connection_cb)on_connection);
if (err) {
uv_close((uv_handle_t*)this->uvHandle, (uv_close_cb)on_error_close);
MS_THROW_ERROR("uv_listen() failed: %s", uv_strerror(err));
}
// Set local address.
if (! SetLocalAddress()) {
uv_close((uv_handle_t*)this->uvHandle, (uv_close_cb)on_error_close);
MS_THROW_ERROR("error setting local IP and port");
}
}
TCPServer::TCPServer(uv_tcp_t* uvHandle, int backlog) :
uvHandle(uvHandle)
{
MS_TRACE();
int err;
this->uvHandle->data = (void*)this;
err = uv_listen((uv_stream_t*)this->uvHandle, backlog, (uv_connection_cb)on_connection);
if (err) {
uv_close((uv_handle_t*)this->uvHandle, (uv_close_cb)on_error_close);
MS_THROW_ERROR("uv_listen() failed: %s", uv_strerror(err));
}
// Set local address.
if (! SetLocalAddress()) {
uv_close((uv_handle_t*)this->uvHandle, (uv_close_cb)on_error_close);
MS_THROW_ERROR("error setting local IP and port");
}
}
TCPServer::~TCPServer() {
MS_TRACE();
if (this->uvHandle)
delete this->uvHandle;
}
const struct sockaddr* TCPServer::GetLocalAddress() {
MS_TRACE();
return (const struct sockaddr*)&this->localAddr;
}
const std::string& TCPServer::GetLocalIP() {
MS_TRACE();
return this->localIP;
}
MS_PORT TCPServer::GetLocalPort() {
MS_TRACE();
return this->localPort;
}
void TCPServer::Close() {
MS_TRACE();
RETURN_IF_CLOSING();
this->isClosing = true;
// If there are no connections then close now.
if (this->connections.empty()) {
uv_close((uv_handle_t*)this->uvHandle, (uv_close_cb)on_close);
}
// Otherwise close all the connections (but not the TCP server).
else {
MS_DEBUG("closing %zu active connections", this->connections.size());
for(auto it = this->connections.begin(); it != this->connections.end(); ++it) {
TCPConnection* connection = *it;
connection->Close();
}
}
}
void TCPServer::Dump() {
MS_DEBUG("[TCP | local address: %s : %u | status: %s | num connections: %zu]",
this->localIP.c_str(), (unsigned int)this->localPort,
(! this->isClosing) ? "open" : "closed",
this->connections.size());
}
bool TCPServer::SetLocalAddress() {
MS_TRACE();
int err;
int len = sizeof(this->localAddr);
err = uv_tcp_getsockname(this->uvHandle, (struct sockaddr*)&this->localAddr, &len);
if (err) {
MS_ERROR("uv_tcp_getsockname() failed: %s", uv_strerror(err));
return false;
}
int family;
Utils::IP::GetAddressInfo((const struct sockaddr*)&this->localAddr, &family, this->localIP, &this->localPort);
return true;
}
inline
void TCPServer::onUvConnection(int status) {
MS_TRACE();
RETURN_IF_CLOSING();
int err;
if (status) {
MS_ERROR("error while receiving a new TCP connection: %s", uv_strerror(status));
return;
}
// Notify the subclass so it provides an allocated derived class of TCPConnection.
TCPConnection* connection = nullptr;
userOnTCPConnectionAlloc(&connection);
MS_ASSERT(connection != nullptr, "TCPConnection pointer was not allocated by the user");
try {
connection->Setup(this, this->localIP, this->localPort);
}
catch (const MediaSoupError &error) {
delete connection;
return;
}
// Accept the connection.
err = uv_accept((uv_stream_t*)this->uvHandle, (uv_stream_t*)connection->GetUvHandle());
if (err)
MS_ABORT("uv_accept() failed: %s", uv_strerror(err));
// Insert the TCPConnection in the set.
this->connections.insert(connection);
// Start receiving data.
try {
connection->Start();
}
catch (const MediaSoupError &error) {
MS_ERROR("cannot run the TCP connection: %s | closing the connection", error.what());
connection->Close();
// NOTE: Don't return here so the user won't be notified about a "onclose" for a TCP connection
// for which there was not a previous "onnew" event.
}
MS_DEBUG("new TCP connection:");
connection->Dump();
// Notify the subclass.
userOnNewTCPConnection(connection);
}
inline
void TCPServer::onUvClosed() {
MS_TRACE();
// Motify the subclass.
userOnTCPServerClosed();
// And delete this.
delete this;
}
inline
void TCPServer::onTCPConnectionClosed(TCPConnection* connection, bool is_closed_by_peer) {
MS_TRACE();
MS_DEBUG("TCP connection closed:");
connection->Dump();
// Remove the TCPConnection from the set.
this->connections.erase(connection);
// Notify the subclass.
userOnTCPConnectionClosed(connection, is_closed_by_peer);
// Check if the server is closing connections and if this is the last
// connection then close the server now.
if (this->isClosing && this->connections.empty()) {
MS_DEBUG("last active connection closed");
uv_close((uv_handle_t*)this->uvHandle, (uv_close_cb)on_close);
}
}
#define MS_CLASS "Timer"
#include "handles/Timer.h"
#include "MediaSoupError.h"
#include "LibUV.h"
#include "Logger.h"
/* Static methods for UV callbacks. */
static inline
void on_timer(uv_timer_t* handle) {
static_cast<Timer*>(handle->data)->onUvTimer();
}
static inline
void on_close(uv_handle_t* handle) {
delete handle;
}
/* Instance methods. */
Timer::Timer(Listener* listener) :
listener(listener)
{
MS_TRACE();
int err;
this->uvHandle = new uv_timer_t;
uvHandle->data = (void*)this;
err = uv_timer_init(LibUV::GetLoop(), this->uvHandle);
if (err) {
delete this->uvHandle;
this->uvHandle = nullptr;
MS_THROW_ERROR("uv_timer_init() failed: %s", uv_strerror(err));
}
}
void Timer::Start(MS_8BYTES timeout) {
MS_TRACE();
int err;
err = uv_timer_start(this->uvHandle, (uv_timer_cb)on_timer, (uint64_t)timeout, 0);
if (err)
MS_THROW_ERROR("uv_timer_start() failed: %s", uv_strerror(err));
}
void Timer::Stop() {
MS_TRACE();
int err;
err = uv_timer_stop(this->uvHandle);
if (err)
MS_THROW_ERROR("uv_timer_stop() failed: %s", uv_strerror(err));
}
void Timer::Close() {
MS_TRACE();
uv_close((uv_handle_t*)this->uvHandle, (uv_close_cb)on_close);
// Delete this.
delete this;
}
inline
void Timer::onUvTimer() {
MS_TRACE();
// Notify the listener.
this->listener->onTimer(this);
}
#define MS_CLASS "UDPSocket"
#include "handles/UDPSocket.h"
#include "Utils.h"
#include "LibUV.h"
#include "MediaSoupError.h"
#include "Logger.h"
#define MS_READ_BUFFER_SIZE 65536
#define RETURN_IF_CLOSING() \
if (this->isClosing) { \
MS_DEBUG("in closing state, doing nothing"); \
return; \
}
/* Static methods for UV callbacks. */
static inline
void on_alloc(uv_handle_t* handle, size_t suggested_size, uv_buf_t* buf) {
static_cast<UDPSocket*>(handle->data)->onUvRecvAlloc(suggested_size, buf);
}
static inline
void on_recv(uv_udp_t* handle, ssize_t nread, const uv_buf_t* buf, const struct sockaddr* addr, unsigned int flags) {
static_cast<UDPSocket*>(handle->data)->onUvRecv(nread, buf, addr, flags);
}
static inline
void on_send(uv_udp_send_t* req, int status) {
UDPSocket::UvSendData* send_data = static_cast<UDPSocket::UvSendData*>(req->data);
UDPSocket* socket = send_data->socket;
// Delete the UvSendData struct (which includes the uv_req_t and the store char[]).
std::free(send_data);
// Just notify the UDPSocket when error.
if (status)
socket->onUvSendError(status);
}
static inline
void on_close(uv_handle_t* handle) {
static_cast<UDPSocket*>(handle->data)->onUvClosed();
}
static inline
void on_error_close(uv_handle_t* handle) {
delete handle;
}
/* Static variables. */
__thread MS_BYTE UDPSocket::readBuffer[MS_READ_BUFFER_SIZE];
/* Instance methods. */
UDPSocket::UDPSocket(const std::string &ip, MS_PORT port) {
MS_TRACE();
int err;
int flags = 0;
this->uvHandle = new uv_udp_t;
this->uvHandle->data = (void*)this;
err = uv_udp_init(LibUV::GetLoop(), this->uvHandle);
if (err) {
delete this->uvHandle;
this->uvHandle = nullptr;
MS_THROW_ERROR("uv_udp_init() failed: %s", uv_strerror(err));
}
struct sockaddr_storage bind_addr;
switch (Utils::IP::GetFamily(ip)) {
case AF_INET:
err = uv_ip4_addr(ip.c_str(), (int)port, (struct sockaddr_in*)&bind_addr);
if (err)
MS_ABORT("uv_ipv4_addr() failed: %s", uv_strerror(err));
break;
case AF_INET6:
err = uv_ip6_addr(ip.c_str(), (int)port, (struct sockaddr_in6*)&bind_addr);
if (err)
MS_ABORT("uv_ipv6_addr() failed: %s", uv_strerror(err));
// Don't also bind into IPv4 when listening in IPv6.
flags |= UV_UDP_IPV6ONLY;
break;
default:
uv_close((uv_handle_t*)this->uvHandle, (uv_close_cb)on_error_close);
MS_THROW_ERROR("invalid binding IP '%s'", ip.c_str());
break;
}
err = uv_udp_bind(this->uvHandle, (const struct sockaddr*)&bind_addr, flags);
if (err) {
uv_close((uv_handle_t*)this->uvHandle, (uv_close_cb)on_error_close);
MS_THROW_ERROR("uv_udp_bind() failed: %s", uv_strerror(err));
}
err = uv_udp_recv_start(this->uvHandle, (uv_alloc_cb)on_alloc, (uv_udp_recv_cb)on_recv);
if (err) {
uv_close((uv_handle_t*)this->uvHandle, (uv_close_cb)on_error_close);
MS_THROW_ERROR("uv_udp_recv_start() failed: %s", uv_strerror(err));
}
// Set local address.
if (! SetLocalAddress()) {
uv_close((uv_handle_t*)this->uvHandle, (uv_close_cb)on_error_close);
MS_THROW_ERROR("error setting local IP and port");
}
}
UDPSocket::UDPSocket(uv_udp_t* uvHandle) :
uvHandle(uvHandle)
{
MS_TRACE();
int err;
this->uvHandle->data = (void*)this;
err = uv_udp_recv_start(this->uvHandle, (uv_alloc_cb)on_alloc, (uv_udp_recv_cb)on_recv);
if (err) {
uv_close((uv_handle_t*)this->uvHandle, (uv_close_cb)on_error_close);
MS_THROW_ERROR("uv_udp_recv_start() failed: %s", uv_strerror(err));
}
// Set local address.
if (! SetLocalAddress()) {
uv_close((uv_handle_t*)this->uvHandle, (uv_close_cb)on_error_close);
MS_THROW_ERROR("error setting local IP and port");
}
}
UDPSocket::~UDPSocket() {
MS_TRACE();
if (this->uvHandle)
delete this->uvHandle;
}
void UDPSocket::Send(const MS_BYTE* data, size_t len, const struct sockaddr* addr) {
MS_TRACE();
RETURN_IF_CLOSING();
if (len == 0) {
MS_DEBUG("ignoring 0 length data");
return;
}
uv_buf_t buffer;
int sent;
int err;
// First try uv_udp_try_send(). In case it can not directly send the datagram
// then build a uv_req_t and use uv_udp_send().
buffer = uv_buf_init((char*)data, len);
sent = uv_udp_try_send(this->uvHandle, &buffer, 1, addr);
// Entire datagram was sent. Done.
if (sent == (int)len) {
return;
}
else if (sent >= 0) {
MS_WARN("datagram truncated (just %d of %zu bytes were sent)", sent, len);
return;
}
// Error,
else if (sent != UV_EAGAIN) {
MS_ERROR("uv_udp_try_send() failed: %s", uv_strerror(sent));
return;
}
// Otherwise UV_EAGAIN was returned so cannot send data at first time. Use uv_udp_send().
// TMP: remove this.
MS_DEBUG("could not send the datagram at first time, using uv_udp_send() now");
// Allocate a special UvSendData struct pointer.
UvSendData* send_data = (UvSendData*)std::malloc(sizeof(UvSendData) + len);
send_data->socket = this;
std::memcpy(send_data->store, data, len);
send_data->req.data = (void*)send_data;
buffer = uv_buf_init((char*)send_data->store, len);
err = uv_udp_send(&send_data->req, this->uvHandle, &buffer, 1, addr, (uv_udp_send_cb)on_send);
if (err) {
// NOTE: uv_udp_send() returns error if a wrong INET family is given
// (IPv6 destination on a IPv4 binded socket), so be ready.
MS_ERROR("uv_udp_send() failed: %s", uv_strerror(err));
// Delete the UvSendData struct (which includes the uv_req_t and the store char[]).
std::free(send_data);
}
}
void UDPSocket::Send(const MS_BYTE* data, size_t len, const std::string &ip, MS_PORT port) {
MS_TRACE();
RETURN_IF_CLOSING();
int err;
if (len == 0) {
MS_DEBUG("ignoring 0 length data");
return;
}
struct sockaddr_storage addr;
switch (Utils::IP::GetFamily(ip)) {
case AF_INET:
err = uv_ip4_addr(ip.c_str(), (int)port, (struct sockaddr_in*)&addr);
if (err)
MS_ABORT("uv_ipv4_addr() failed: %s", uv_strerror(err));
break;
case AF_INET6:
err = uv_ip6_addr(ip.c_str(), (int)port, (struct sockaddr_in6*)&addr);
if (err)
MS_ABORT("uv_ipv6_addr() failed: %s", uv_strerror(err));
break;
default:
MS_ERROR("invalid destination IP '%s'", ip.c_str());
return;
}
Send(data, len, (struct sockaddr*)&addr);
}
void UDPSocket::Close() {
MS_TRACE();
RETURN_IF_CLOSING();
int err;
this->isClosing = true;
// Don't read more.
err = uv_udp_recv_stop(this->uvHandle);
if (err)
MS_ABORT("uv_udp_recv_stop() failed: %s", uv_strerror(err));
uv_close((uv_handle_t*)this->uvHandle, (uv_close_cb)on_close);
}
void UDPSocket::Dump() {
MS_DEBUG("[UDP | local address: %s : %u | status: %s]",
this->localIP.c_str(), (unsigned int)this->localPort,
(! this->isClosing) ? "open" : "closed");
}
bool UDPSocket::SetLocalAddress() {
MS_TRACE();
int err;
int len = sizeof(this->localAddr);
err = uv_udp_getsockname(this->uvHandle, (struct sockaddr*)&this->localAddr, &len);
if (err) {
MS_ERROR("uv_udp_getsockname() failed: %s", uv_strerror(err));
return false;
}
int family;
Utils::IP::GetAddressInfo((const struct sockaddr*)&this->localAddr, &family, this->localIP, &this->localPort);
return true;
}
inline
void UDPSocket::onUvRecvAlloc(size_t suggested_size, uv_buf_t* buf) {
MS_TRACE();
// Tell UV to write into the per thread buffer.
buf->base = (char *)UDPSocket::readBuffer;
// Give UV all the buffer space.
buf->len = MS_READ_BUFFER_SIZE;
}
inline
void UDPSocket::onUvRecv(ssize_t nread, const uv_buf_t* buf, const struct sockaddr* addr, unsigned int flags) {
MS_TRACE();
RETURN_IF_CLOSING();
// NOTE: libuv calls twice to alloc & recv when a datagram is received, the
// second one with nread = 0 and addr = NULL. Ignore it.
if (nread == 0)
return;
// Check flags.
if (flags & UV_UDP_PARTIAL) {
MS_ERROR("received datagram was truncated due to insufficient buffer, ignoring it");
return;
}
// Data received.
if (nread > 0) {
// Notify the subclass.
userOnUDPDatagramRecv((MS_BYTE*)buf->base, nread, addr);
}
// Some error.
else {
MS_NOTICE("read error: %s", uv_strerror(nread));
}
}
inline
void UDPSocket::onUvSendError(int error) {
MS_TRACE();
if (this->isClosing)
return;
MS_NOTICE("send error: %s", uv_strerror(error));
}
inline
void UDPSocket::onUvClosed() {
MS_TRACE();
// Notify the subclass.
userOnUDPSocketClosed();
// And delete this.
delete this;
}
#define MS_CLASS "UnixStreamSocket"
#include "handles/UnixStreamSocket.h"
#include "LibUV.h"
#include "MediaSoupError.h"
#include "Logger.h"
#include <cstring> // std::memcpy()
#include <cstdlib> // std::malloc(), std::free()
#define RETURN_IF_CLOSING() \
if (this->isClosing) { \
MS_DEBUG("in closing state, doing nothing"); \
return; \
}
/* Static methods for UV callbacks. */
static inline
void on_alloc(uv_handle_t* handle, size_t suggested_size, uv_buf_t* buf) {
static_cast<UnixStreamSocket*>(handle->data)->onUvReadAlloc(suggested_size, buf);
}
static inline
void on_read(uv_stream_t* handle, ssize_t nread, const uv_buf_t* buf) {
static_cast<UnixStreamSocket*>(handle->data)->onUvRead(nread, buf);
}
static inline
void on_write(uv_write_t* req, int status) {
UnixStreamSocket::UvWriteData* write_data = static_cast<UnixStreamSocket::UvWriteData*>(req->data);
UnixStreamSocket* socket = write_data->socket;
// Delete the UvWriteData struct (which includes the uv_req_t and the store char[]).
std::free(write_data);
// Just notify the UnixStreamSocket when error.
if (status)
socket->onUvWriteError(status);
}
static inline
void on_shutdown(uv_shutdown_t* req, int status) {
static_cast<UnixStreamSocket*>(req->data)->onUvShutdown(req, status);
}
static inline
void on_close(uv_handle_t* handle) {
static_cast<UnixStreamSocket*>(handle->data)->onUvClosed();
}
static inline
void on_error_close(uv_handle_t* handle) {
delete handle;
}
/* Instance methods. */
UnixStreamSocket::UnixStreamSocket(int fd, size_t bufferSize) :
bufferSize(bufferSize)
{
MS_TRACE();
int err;
this->uvHandle = new uv_pipe_t;
this->uvHandle->data = (void*)this;
err = uv_pipe_init(LibUV::GetLoop(), this->uvHandle, 0);
if (err) {
delete this->uvHandle;
this->uvHandle = nullptr;
MS_THROW_ERROR("uv_pipe_init() failed: %s", uv_strerror(err));
}
err = uv_pipe_open(this->uvHandle, fd);
if (err) {
uv_close((uv_handle_t*)this->uvHandle, (uv_close_cb)on_error_close);
MS_THROW_ERROR("uv_pipe_open() failed: %s", uv_strerror(err));
}
// Start reading.
err = uv_read_start((uv_stream_t*)this->uvHandle, (uv_alloc_cb)on_alloc, (uv_read_cb)on_read);
if (err) {
uv_close((uv_handle_t*)this->uvHandle, (uv_close_cb)on_error_close);
MS_THROW_ERROR("uv_read_start() failed: %s", uv_strerror(err));
}
// NOTE: Don't allocate the buffer here. Instead wait for the first uv_alloc_cb().
}
UnixStreamSocket::~UnixStreamSocket() {
MS_TRACE();
if (this->uvHandle)
delete this->uvHandle;
if (this->buffer)
delete[] this->buffer;
}
void UnixStreamSocket::Write(const MS_BYTE* data, size_t len) {
MS_TRACE();
RETURN_IF_CLOSING();
if (len == 0) {
MS_DEBUG("ignoring 0 length data");
return;
}
uv_buf_t buffer;
int written;
int err;
// First try uv_try_write(). In case it can not directly send all the given data
// then build a uv_req_t and use uv_write().
buffer = uv_buf_init((char*)data, len);
written = uv_try_write((uv_stream_t*)this->uvHandle, &buffer, 1);
// All the data was written. Done.
if (written == (int)len) {
return;
}
// Cannot write any data at first time. Use uv_write().
else if (written == UV_EAGAIN || written == UV_ENOSYS) {
// Set written to 0 so pending_len can be properly calculated.
written = 0;
}
// Error. Should not happen.
else if (written < 0) {
MS_NOTICE("uv_try_write() failed: %s | closing the connection", uv_strerror(written));
Close();
return;
}
// TMP: remove this.
MS_DEBUG("could just write %zu bytes (%zu given) at first time, using uv_write() now", (size_t)written, len);
size_t pending_len = len - written;
// Allocate a special UvWriteData struct pointer.
UvWriteData* write_data = (UvWriteData*)std::malloc(sizeof(UvWriteData) + pending_len);
write_data->socket = this;
std::memcpy(write_data->store, data + written, pending_len);
write_data->req.data = (void*)write_data;
buffer = uv_buf_init((char*)write_data->store, pending_len);
err = uv_write(&write_data->req, (uv_stream_t*)this->uvHandle, &buffer, 1, (uv_write_cb)on_write);
if (err)
MS_ABORT("uv_write() failed: %s", uv_strerror(err));
}
void UnixStreamSocket::Close() {
MS_TRACE();
RETURN_IF_CLOSING();
int err;
this->isClosing = true;
// Don't read more.
err = uv_read_stop((uv_stream_t*)this->uvHandle);
if (err)
MS_ABORT("uv_read_stop() failed: %s", uv_strerror(err));
// If there is no error and the peer didn't close its pipe side then close gracefully.
if (! this->hasError && ! this->isClosedByPeer) {
// Use uv_shutdown() so pending data to be written will be sent to the peer before closing.
uv_shutdown_t* req = new uv_shutdown_t;
req->data = (void*)this;
err = uv_shutdown(req, (uv_stream_t*)this->uvHandle, (uv_shutdown_cb)on_shutdown);
if (err)
MS_ABORT("uv_shutdown() failed: %s", uv_strerror(err));
}
// Otherwise directly close the socket.
else {
uv_close((uv_handle_t*)this->uvHandle, (uv_close_cb)on_close);
}
}
void UnixStreamSocket::Dump() {
MS_DEBUG("[status: %s]", (! this->isClosing) ? "open" : "closed");
}
inline
void UnixStreamSocket::onUvReadAlloc(size_t suggested_size, uv_buf_t* buf) {
MS_TRACE();
// If this is the first call to onUvReadAlloc() then allocate the receiving buffer now.
if (! this->buffer)
this->buffer = new MS_BYTE[this->bufferSize];
// Tell UV to write after the last data byte in the buffer.
buf->base = (char *)(this->buffer + this->bufferDataLen);
// Give UV all the remaining space in the buffer.
if (this->bufferSize > this->bufferDataLen) {
buf->len = this->bufferSize - this->bufferDataLen;
MS_DEBUG("available space in the buffer: %zu", buf->len);
}
else {
buf->len = 0;
MS_WARN("no available space in the buffer");
}
}
inline
void UnixStreamSocket::onUvRead(ssize_t nread, const uv_buf_t* buf) {
MS_TRACE();
if (nread == 0)
return;
// Data received.
if (nread > 0) {
// Update the buffer data length.
this->bufferDataLen += (size_t)nread;
// Notify the subclass.
userOnUnixStreamRead((MS_BYTE*)buf->base, nread);
}
// Peer disconneted.
else if (nread == UV_EOF || nread == UV_ECONNRESET) {
MS_DEBUG("pipe closed by peer | closing local side");
this->isClosedByPeer = true;
// Close local side of the pipe.
Close();
}
// Some error.
else {
MS_NOTICE("read error: %s | closing the pipe", uv_strerror(nread));
this->hasError = true;
// Close the socket.
// NOTE: calling uv_read_stop() upon EOF is a MUST.
Close();
}
}
inline
void UnixStreamSocket::onUvWriteError(int error) {
MS_TRACE();
if (this->isClosing)
return;
if (error == UV_EPIPE || error == UV_ENOTCONN) {
MS_DEBUG("write error: %s | closing the pipe", uv_strerror(error));
}
else {
MS_NOTICE("write error: %s | closing the pipe", uv_strerror(error));
this->hasError = true;
}
Close();
}
inline
void UnixStreamSocket::onUvShutdown(uv_shutdown_t* req, int status) {
MS_TRACE();
delete req;
if (status == UV_EPIPE || status == UV_ENOTCONN || status == UV_ECANCELED)
MS_DEBUG("shutdown error: %s", uv_strerror(status));
else if (status)
MS_NOTICE("shutdown error: %s", uv_strerror(status));
// Now do close the handle.
uv_close((uv_handle_t*)this->uvHandle, (uv_close_cb)on_close);
}
inline
void UnixStreamSocket::onUvClosed() {
MS_TRACE();
// Notify the subclass.
userOnUnixStreamSocketClosed(this->isClosedByPeer);
// And delete this.
delete this;
}
#define MS_CLASS "main"
#include "MediaSoup.h"
#include "Settings.h"
#include "Version.h"
#include "Daemon.h"
#include "MediaSoupError.h"
#include "Logger.h"
#include <string>
#include <cstdlib> // std::_Exit()
int main(int argc, char* argv[]) {
// Set this thread as main thread.
Logger::ThreadInit("main");
// Read command line arguments.
Settings::ReadArguments(argc, argv);
MS_NOTICE("starting %s", Version::GetNameAndVersion().c_str());
// Set default settings.
Settings::SetDefaultConfiguration();
// Read configuration file (if given).
if (! Settings::arguments.configFile.empty()) {
MS_INFO("reading configuration file '%s'", Settings::arguments.configFile.c_str());
Settings::ReadConfigurationFile();
}
// Print configuration.
Settings::PrintConfiguration();
// Verify final configuration.
Settings::ConfigurationPostCheck();
// Set process stuff.
MediaSoup::SetProcess();
try {
// Daemonize if requested.
if (Settings::arguments.daemonize) {
MS_NOTICE("daemonizing %s", Version::name.c_str());
Daemon::Daemonize();
}
// Run MediaSoup.
MediaSoup::Run();
// End.
MediaSoup::End();
MS_EXIT_SUCCESS("%s ends", Version::name.c_str());
}
catch (const MediaSoupError &error) {
// End.
MediaSoup::End();
// If this is the daemonized process don't log FAILURE EXIT as the
// ancestor process will do it.
if (Daemon::IsDaemonized()) {
MS_CRIT("%s", error.what());
// Notify the ancestor process that the daemonized process failed.
Daemon::SendErrorStatusToAncestor();
// And silently die.
std::_Exit(EXIT_FAILURE);
}
// Otherwise this is the ancestor process so log FAILURE EXIT.
else {
MS_EXIT_FAILURE("%s", error.what());
}
}
}
Markdown 格式
0% 或
您添加了 0 人 到此讨论。请谨慎行事。
请先完成此评论的编辑!
请 注册 或者 后发表评论