提交 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_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
差异被折叠。
#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 "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));
}
差异被折叠。
差异被折叠。
差异被折叠。
差异被折叠。
差异被折叠。
差异被折叠。
差异被折叠。
差异被折叠。
差异被折叠。
差异被折叠。
差异被折叠。
差异被折叠。
差异被折叠。
差异被折叠。
差异被折叠。
差异被折叠。
差异被折叠。
差异被折叠。
差异被折叠。
差异被折叠。
差异被折叠。
差异被折叠。
差异被折叠。
差异被折叠。
差异被折叠。
差异被折叠。
差异被折叠。
差异被折叠。
差异被折叠。
差异被折叠。
差异被折叠。
差异被折叠。
差异被折叠。
差异被折叠。
差异被折叠。
Markdown 格式
0% 或
您添加了 0 人 到此讨论。请谨慎行事。
请先完成此评论的编辑!
请 注册 或者 后发表评论