Fix clang style warnings in webrtc/base

Mostly this consists of marking functions with override when
applicable, and moving function bodies from .h to .cc files.

Not inlining virtual functions with simple bodies such as

  { return false; }

strikes me as probably losing more in readability than we gain in
binary size and compilation time, but I guess it's just like any other
case where enabling a generally good warning forces us to write
slightly worse code in a couple of places.

BUG=163
R=kjellander@webrtc.org, tommi@webrtc.org

Review URL: https://webrtc-codereview.appspot.com/47429004

Cr-Commit-Position: refs/heads/master@{#8656}
git-svn-id: http://webrtc.googlecode.com/svn/trunk@8656 4adac7df-926f-26a2-2b94-8c16560cd09d
This commit is contained in:
kwiberg@webrtc.org
2015-03-09 22:21:53 +00:00
parent 2989204130
commit 67186fe00c
111 changed files with 1610 additions and 1061 deletions

View File

@@ -23,6 +23,7 @@ base/sha1.c
base/sha1.h base/sha1.h
Governed by http://sigslot.sourceforge.net/#license (Public domain): Governed by http://sigslot.sourceforge.net/#license (Public domain):
base/sigslot.cc
base/sigslot.h base/sigslot.h
Governed by http://www.freedesktop.org/wiki/Software/systemd (LGPL 2.1+): Governed by http://www.freedesktop.org/wiki/Software/systemd (LGPL 2.1+):

View File

@@ -111,6 +111,7 @@ static_library("rtc_base_approved") {
"exp_filter.h", "exp_filter.h",
"md5.cc", "md5.cc",
"md5.h", "md5.h",
"md5digest.cc",
"md5digest.h", "md5digest.h",
"platform_file.cc", "platform_file.cc",
"platform_file.h", "platform_file.h",
@@ -158,6 +159,7 @@ static_library("rtc_base") {
"asyncfile.h", "asyncfile.h",
"asynchttprequest.cc", "asynchttprequest.cc",
"asynchttprequest.h", "asynchttprequest.h",
"asyncpacketsocket.cc",
"asyncpacketsocket.h", "asyncpacketsocket.h",
"asyncsocket.cc", "asyncsocket.cc",
"asyncsocket.h", "asyncsocket.h",
@@ -180,6 +182,7 @@ static_library("rtc_base") {
"crc32.cc", "crc32.cc",
"crc32.h", "crc32.h",
"criticalsection.h", "criticalsection.h",
"cryptstring.cc",
"cryptstring.h", "cryptstring.h",
"diskcache.cc", "diskcache.cc",
"diskcache.h", "diskcache.h",
@@ -235,9 +238,11 @@ static_library("rtc_base") {
"scoped_ptr.h", "scoped_ptr.h",
"sha1.cc", "sha1.cc",
"sha1.h", "sha1.h",
"sha1digest.cc",
"sha1digest.h", "sha1digest.h",
"signalthread.cc", "signalthread.cc",
"signalthread.h", "signalthread.h",
"sigslot.cc",
"sigslot.h", "sigslot.h",
"sigslotrepeater.h", "sigslotrepeater.h",
"socket.h", "socket.h",
@@ -317,6 +322,7 @@ static_library("rtc_base") {
"asyncinvoker.cc", "asyncinvoker.cc",
"asyncinvoker.h", "asyncinvoker.h",
"asyncinvoker-inl.h", "asyncinvoker-inl.h",
"asyncresolverinterface.cc",
"asyncresolverinterface.h", "asyncresolverinterface.h",
"atomicops.h", "atomicops.h",
"bandwidthsmoother.cc", "bandwidthsmoother.cc",
@@ -324,6 +330,7 @@ static_library("rtc_base") {
"basictypes.h", "basictypes.h",
"bind.h", "bind.h",
"bind.h.pump", "bind.h.pump",
"buffer.cc",
"buffer.h", "buffer.h",
"callback.h", "callback.h",
"callback.h.pump", "callback.h.pump",
@@ -438,12 +445,6 @@ static_library("rtc_base") {
} }
} # !build_with_chromium } # !build_with_chromium
if (is_clang) {
# Suppress warnings from the Chrome Clang plugins.
# See http://code.google.com/p/webrtc/issues/detail?id=163 for details.
configs -= [ "//build/config/clang:find_bad_constructs" ]
}
# TODO(henrike): issue 3307, make rtc_base build with the Chromium default # TODO(henrike): issue 3307, make rtc_base build with the Chromium default
# compiler settings. # compiler settings.
configs -= [ "//build/config/compiler:chromium_code" ] configs -= [ "//build/config/compiler:chromium_code" ]

View File

@@ -31,7 +31,7 @@ class FirewallManager;
class AsyncHttpRequest : public SignalThread { class AsyncHttpRequest : public SignalThread {
public: public:
explicit AsyncHttpRequest(const std::string &user_agent); explicit AsyncHttpRequest(const std::string &user_agent);
~AsyncHttpRequest(); ~AsyncHttpRequest() override;
// If start_delay is less than or equal to zero, this starts immediately. // If start_delay is less than or equal to zero, this starts immediately.
// Start_delay defaults to zero. // Start_delay defaults to zero.
@@ -75,11 +75,11 @@ class AsyncHttpRequest : public SignalThread {
protected: protected:
void set_error(HttpErrorType error) { error_ = error; } void set_error(HttpErrorType error) { error_ = error; }
virtual void OnWorkStart(); void OnWorkStart() override;
virtual void OnWorkStop(); void OnWorkStop() override;
void OnComplete(HttpClient* client, HttpErrorType error); void OnComplete(HttpClient* client, HttpErrorType error);
virtual void OnMessage(Message* message); void OnMessage(Message* message) override;
virtual void DoWork(); void DoWork() override;
private: private:
void LaunchRequest(); void LaunchRequest();

View File

@@ -33,7 +33,7 @@ class AsyncClosure : public RefCountInterface {
// thread if needed. Should be called from the target thread. // thread if needed. Should be called from the target thread.
virtual void Execute() = 0; virtual void Execute() = 0;
protected: protected:
virtual ~AsyncClosure() {} ~AsyncClosure() override {}
}; };
// Simple closure that doesn't trigger a callback for the calling thread. // Simple closure that doesn't trigger a callback for the calling thread.
@@ -55,7 +55,7 @@ class FireAndForgetAsyncClosure : public AsyncClosure {
class NotifyingAsyncClosureBase : public AsyncClosure, class NotifyingAsyncClosureBase : public AsyncClosure,
public sigslot::has_slots<> { public sigslot::has_slots<> {
public: public:
virtual ~NotifyingAsyncClosureBase() { disconnect_all(); } ~NotifyingAsyncClosureBase() override;
protected: protected:
NotifyingAsyncClosureBase(AsyncInvoker* invoker, Thread* calling_thread); NotifyingAsyncClosureBase(AsyncInvoker* invoker, Thread* calling_thread);

View File

@@ -71,6 +71,10 @@ NotifyingAsyncClosureBase::NotifyingAsyncClosureBase(AsyncInvoker* invoker,
this, &NotifyingAsyncClosureBase::CancelCallback); this, &NotifyingAsyncClosureBase::CancelCallback);
} }
NotifyingAsyncClosureBase::~NotifyingAsyncClosureBase() {
disconnect_all();
}
void NotifyingAsyncClosureBase::TriggerCallback() { void NotifyingAsyncClosureBase::TriggerCallback() {
CritScope cs(&crit_); CritScope cs(&crit_);
if (!CallbackCanceled() && !callback_.empty()) { if (!CallbackCanceled() && !callback_.empty()) {

View File

@@ -69,7 +69,7 @@ namespace rtc {
class AsyncInvoker : public MessageHandler { class AsyncInvoker : public MessageHandler {
public: public:
AsyncInvoker(); AsyncInvoker();
virtual ~AsyncInvoker(); ~AsyncInvoker() override;
// Call |functor| asynchronously on |thread|, with no callback upon // Call |functor| asynchronously on |thread|, with no callback upon
// completion. Returns immediately. // completion. Returns immediately.
@@ -120,7 +120,7 @@ class AsyncInvoker : public MessageHandler {
sigslot::signal0<> SignalInvokerDestroyed; sigslot::signal0<> SignalInvokerDestroyed;
private: private:
virtual void OnMessage(Message* msg); void OnMessage(Message* msg) override;
void DoInvoke(Thread* thread, const scoped_refptr<AsyncClosure>& closure, void DoInvoke(Thread* thread, const scoped_refptr<AsyncClosure>& closure,
uint32 id); uint32 id);

View File

@@ -0,0 +1,29 @@
/*
* Copyright 2015 The WebRTC Project Authors. All rights reserved.
*
* Use of this source code is governed by a BSD-style license
* that can be found in the LICENSE file in the root of the source
* tree. An additional intellectual property rights grant can be found
* in the file PATENTS. All contributing project authors may
* be found in the AUTHORS file in the root of the source tree.
*/
#include "webrtc/base/asyncpacketsocket.h"
namespace rtc {
PacketTimeUpdateParams::PacketTimeUpdateParams()
: rtp_sendtime_extension_id(-1),
srtp_auth_tag_len(-1),
srtp_packet_index(-1) {
}
PacketTimeUpdateParams::~PacketTimeUpdateParams() = default;
AsyncPacketSocket::AsyncPacketSocket() {
}
AsyncPacketSocket::~AsyncPacketSocket() {
}
}; // namespace rtc

View File

@@ -22,10 +22,8 @@ namespace rtc {
// extension, including the information needed to update the authentication tag // extension, including the information needed to update the authentication tag
// after changing the value. // after changing the value.
struct PacketTimeUpdateParams { struct PacketTimeUpdateParams {
PacketTimeUpdateParams() PacketTimeUpdateParams();
: rtp_sendtime_extension_id(-1), srtp_auth_tag_len(-1), ~PacketTimeUpdateParams();
srtp_packet_index(-1) {
}
int rtp_sendtime_extension_id; // extension header id present in packet. int rtp_sendtime_extension_id; // extension header id present in packet.
std::vector<char> srtp_auth_key; // Authentication key. std::vector<char> srtp_auth_key; // Authentication key.
@@ -75,8 +73,8 @@ class AsyncPacketSocket : public sigslot::has_slots<> {
STATE_CONNECTED STATE_CONNECTED
}; };
AsyncPacketSocket() { } AsyncPacketSocket();
virtual ~AsyncPacketSocket() { } ~AsyncPacketSocket() override;
// Returns current local address. Address may be set to NULL if the // Returns current local address. Address may be set to NULL if the
// socket is not bound yet (GetState() returns STATE_BINDING). // socket is not bound yet (GetState() returns STATE_BINDING).

View File

@@ -0,0 +1,20 @@
/*
* Copyright 2015 The WebRTC Project Authors. All rights reserved.
*
* Use of this source code is governed by a BSD-style license
* that can be found in the LICENSE file in the root of the source
* tree. An additional intellectual property rights grant can be found
* in the file PATENTS. All contributing project authors may
* be found in the AUTHORS file in the root of the source tree.
*/
#include "webrtc/base/asyncresolverinterface.h"
namespace rtc {
AsyncResolverInterface::AsyncResolverInterface() {
}
AsyncResolverInterface::~AsyncResolverInterface() = default;
}; // namespace rtc

View File

@@ -19,8 +19,8 @@ namespace rtc {
// This interface defines the methods to resolve the address asynchronously. // This interface defines the methods to resolve the address asynchronously.
class AsyncResolverInterface { class AsyncResolverInterface {
public: public:
AsyncResolverInterface() {} AsyncResolverInterface();
virtual ~AsyncResolverInterface() {} virtual ~AsyncResolverInterface();
// Start address resolve process. // Start address resolve process.
virtual void Start(const SocketAddress& addr) = 0; virtual void Start(const SocketAddress& addr) = 0;

View File

@@ -32,13 +32,96 @@ void AsyncSocketAdapter::Attach(AsyncSocket* socket) {
if (socket_) { if (socket_) {
socket_->SignalConnectEvent.connect(this, socket_->SignalConnectEvent.connect(this,
&AsyncSocketAdapter::OnConnectEvent); &AsyncSocketAdapter::OnConnectEvent);
socket_->SignalReadEvent.connect(this, socket_->SignalReadEvent.connect(this, &AsyncSocketAdapter::OnReadEvent);
&AsyncSocketAdapter::OnReadEvent); socket_->SignalWriteEvent.connect(this, &AsyncSocketAdapter::OnWriteEvent);
socket_->SignalWriteEvent.connect(this, socket_->SignalCloseEvent.connect(this, &AsyncSocketAdapter::OnCloseEvent);
&AsyncSocketAdapter::OnWriteEvent);
socket_->SignalCloseEvent.connect(this,
&AsyncSocketAdapter::OnCloseEvent);
} }
} }
SocketAddress AsyncSocketAdapter::GetLocalAddress() const {
return socket_->GetLocalAddress();
}
SocketAddress AsyncSocketAdapter::GetRemoteAddress() const {
return socket_->GetRemoteAddress();
}
int AsyncSocketAdapter::Bind(const SocketAddress& addr) {
return socket_->Bind(addr);
}
int AsyncSocketAdapter::Connect(const SocketAddress& addr) {
return socket_->Connect(addr);
}
int AsyncSocketAdapter::Send(const void* pv, size_t cb) {
return socket_->Send(pv, cb);
}
int AsyncSocketAdapter::SendTo(const void* pv,
size_t cb,
const SocketAddress& addr) {
return socket_->SendTo(pv, cb, addr);
}
int AsyncSocketAdapter::Recv(void* pv, size_t cb) {
return socket_->Recv(pv, cb);
}
int AsyncSocketAdapter::RecvFrom(void* pv, size_t cb, SocketAddress* paddr) {
return socket_->RecvFrom(pv, cb, paddr);
}
int AsyncSocketAdapter::Listen(int backlog) {
return socket_->Listen(backlog);
}
AsyncSocket* AsyncSocketAdapter::Accept(SocketAddress* paddr) {
return socket_->Accept(paddr);
}
int AsyncSocketAdapter::Close() {
return socket_->Close();
}
int AsyncSocketAdapter::GetError() const {
return socket_->GetError();
}
void AsyncSocketAdapter::SetError(int error) {
return socket_->SetError(error);
}
AsyncSocket::ConnState AsyncSocketAdapter::GetState() const {
return socket_->GetState();
}
int AsyncSocketAdapter::EstimateMTU(uint16* mtu) {
return socket_->EstimateMTU(mtu);
}
int AsyncSocketAdapter::GetOption(Option opt, int* value) {
return socket_->GetOption(opt, value);
}
int AsyncSocketAdapter::SetOption(Option opt, int value) {
return socket_->SetOption(opt, value);
}
void AsyncSocketAdapter::OnConnectEvent(AsyncSocket* socket) {
SignalConnectEvent(this);
}
void AsyncSocketAdapter::OnReadEvent(AsyncSocket* socket) {
SignalReadEvent(this);
}
void AsyncSocketAdapter::OnWriteEvent(AsyncSocket* socket) {
SignalWriteEvent(this);
}
void AsyncSocketAdapter::OnCloseEvent(AsyncSocket* socket, int err) {
SignalCloseEvent(this, err);
}
} // namespace rtc } // namespace rtc

View File

@@ -23,9 +23,9 @@ namespace rtc {
class AsyncSocket : public Socket { class AsyncSocket : public Socket {
public: public:
AsyncSocket(); AsyncSocket();
virtual ~AsyncSocket(); ~AsyncSocket() override;
virtual AsyncSocket* Accept(SocketAddress* paddr) = 0; AsyncSocket* Accept(SocketAddress* paddr) override = 0;
// SignalReadEvent and SignalWriteEvent use multi_threaded_local to allow // SignalReadEvent and SignalWriteEvent use multi_threaded_local to allow
// access concurrently from different thread. // access concurrently from different thread.
@@ -48,73 +48,31 @@ class AsyncSocketAdapter : public AsyncSocket, public sigslot::has_slots<> {
// that will be called during the detached period (usually GetState()), to // that will be called during the detached period (usually GetState()), to
// avoid dereferencing a null pointer. // avoid dereferencing a null pointer.
explicit AsyncSocketAdapter(AsyncSocket* socket); explicit AsyncSocketAdapter(AsyncSocket* socket);
virtual ~AsyncSocketAdapter(); ~AsyncSocketAdapter() override;
void Attach(AsyncSocket* socket); void Attach(AsyncSocket* socket);
virtual SocketAddress GetLocalAddress() const { SocketAddress GetLocalAddress() const override;
return socket_->GetLocalAddress(); SocketAddress GetRemoteAddress() const override;
} int Bind(const SocketAddress& addr) override;
virtual SocketAddress GetRemoteAddress() const { int Connect(const SocketAddress& addr) override;
return socket_->GetRemoteAddress(); int Send(const void* pv, size_t cb) override;
} int SendTo(const void* pv, size_t cb, const SocketAddress& addr) override;
virtual int Bind(const SocketAddress& addr) { int Recv(void* pv, size_t cb) override;
return socket_->Bind(addr); int RecvFrom(void* pv, size_t cb, SocketAddress* paddr) override;
} int Listen(int backlog) override;
virtual int Connect(const SocketAddress& addr) { AsyncSocket* Accept(SocketAddress* paddr) override;
return socket_->Connect(addr); int Close() override;
} int GetError() const override;
virtual int Send(const void* pv, size_t cb) { void SetError(int error) override;
return socket_->Send(pv, cb); ConnState GetState() const override;
} int EstimateMTU(uint16* mtu) override;
virtual int SendTo(const void* pv, size_t cb, const SocketAddress& addr) { int GetOption(Option opt, int* value) override;
return socket_->SendTo(pv, cb, addr); int SetOption(Option opt, int value) override;
}
virtual int Recv(void* pv, size_t cb) {
return socket_->Recv(pv, cb);
}
virtual int RecvFrom(void* pv, size_t cb, SocketAddress* paddr) {
return socket_->RecvFrom(pv, cb, paddr);
}
virtual int Listen(int backlog) {
return socket_->Listen(backlog);
}
virtual AsyncSocket* Accept(SocketAddress* paddr) {
return socket_->Accept(paddr);
}
virtual int Close() {
return socket_->Close();
}
virtual int GetError() const {
return socket_->GetError();
}
virtual void SetError(int error) {
return socket_->SetError(error);
}
virtual ConnState GetState() const {
return socket_->GetState();
}
virtual int EstimateMTU(uint16* mtu) {
return socket_->EstimateMTU(mtu);
}
virtual int GetOption(Option opt, int* value) {
return socket_->GetOption(opt, value);
}
virtual int SetOption(Option opt, int value) {
return socket_->SetOption(opt, value);
}
protected: protected:
virtual void OnConnectEvent(AsyncSocket* socket) { virtual void OnConnectEvent(AsyncSocket* socket);
SignalConnectEvent(this); virtual void OnReadEvent(AsyncSocket* socket);
} virtual void OnWriteEvent(AsyncSocket* socket);
virtual void OnReadEvent(AsyncSocket* socket) { virtual void OnCloseEvent(AsyncSocket* socket, int err);
SignalReadEvent(this);
}
virtual void OnWriteEvent(AsyncSocket* socket) {
SignalWriteEvent(this);
}
virtual void OnCloseEvent(AsyncSocket* socket, int err) {
SignalCloseEvent(this, err);
}
AsyncSocket* socket_; AsyncSocket* socket_;
}; };

View File

@@ -23,26 +23,28 @@ namespace rtc {
class AsyncTCPSocketBase : public AsyncPacketSocket { class AsyncTCPSocketBase : public AsyncPacketSocket {
public: public:
AsyncTCPSocketBase(AsyncSocket* socket, bool listen, size_t max_packet_size); AsyncTCPSocketBase(AsyncSocket* socket, bool listen, size_t max_packet_size);
virtual ~AsyncTCPSocketBase(); ~AsyncTCPSocketBase() override;
// Pure virtual methods to send and recv data. // Pure virtual methods to send and recv data.
virtual int Send(const void *pv, size_t cb, int Send(const void *pv, size_t cb,
const rtc::PacketOptions& options) = 0; const rtc::PacketOptions& options) override = 0;
virtual void ProcessInput(char* data, size_t* len) = 0; virtual void ProcessInput(char* data, size_t* len) = 0;
// Signals incoming connection. // Signals incoming connection.
virtual void HandleIncomingConnection(AsyncSocket* socket) = 0; virtual void HandleIncomingConnection(AsyncSocket* socket) = 0;
virtual SocketAddress GetLocalAddress() const; SocketAddress GetLocalAddress() const override;
virtual SocketAddress GetRemoteAddress() const; SocketAddress GetRemoteAddress() const override;
virtual int SendTo(const void *pv, size_t cb, const SocketAddress& addr, int SendTo(const void* pv,
const rtc::PacketOptions& options); size_t cb,
virtual int Close(); const SocketAddress& addr,
const rtc::PacketOptions& options) override;
int Close() override;
virtual State GetState() const; State GetState() const override;
virtual int GetOption(Socket::Option opt, int* value); int GetOption(Socket::Option opt, int* value) override;
virtual int SetOption(Socket::Option opt, int value); int SetOption(Socket::Option opt, int value) override;
virtual int GetError() const; int GetError() const override;
virtual void SetError(int error); void SetError(int error) override;
protected: protected:
// Binds and connects |socket| and creates AsyncTCPSocket for // Binds and connects |socket| and creates AsyncTCPSocket for
@@ -84,12 +86,13 @@ class AsyncTCPSocket : public AsyncTCPSocketBase {
const SocketAddress& bind_address, const SocketAddress& bind_address,
const SocketAddress& remote_address); const SocketAddress& remote_address);
AsyncTCPSocket(AsyncSocket* socket, bool listen); AsyncTCPSocket(AsyncSocket* socket, bool listen);
virtual ~AsyncTCPSocket() {} ~AsyncTCPSocket() override {}
virtual int Send(const void* pv, size_t cb, int Send(const void* pv,
const rtc::PacketOptions& options); size_t cb,
virtual void ProcessInput(char* data, size_t* len); const rtc::PacketOptions& options) override;
virtual void HandleIncomingConnection(AsyncSocket* socket); void ProcessInput(char* data, size_t* len) override;
void HandleIncomingConnection(AsyncSocket* socket) override;
private: private:
DISALLOW_EVIL_CONSTRUCTORS(AsyncTCPSocket); DISALLOW_EVIL_CONSTRUCTORS(AsyncTCPSocket);

View File

@@ -31,21 +31,24 @@ class AsyncUDPSocket : public AsyncPacketSocket {
static AsyncUDPSocket* Create(SocketFactory* factory, static AsyncUDPSocket* Create(SocketFactory* factory,
const SocketAddress& bind_address); const SocketAddress& bind_address);
explicit AsyncUDPSocket(AsyncSocket* socket); explicit AsyncUDPSocket(AsyncSocket* socket);
virtual ~AsyncUDPSocket(); ~AsyncUDPSocket() override;
virtual SocketAddress GetLocalAddress() const; SocketAddress GetLocalAddress() const override;
virtual SocketAddress GetRemoteAddress() const; SocketAddress GetRemoteAddress() const override;
virtual int Send(const void *pv, size_t cb, int Send(const void* pv,
const rtc::PacketOptions& options); size_t cb,
virtual int SendTo(const void *pv, size_t cb, const SocketAddress& addr, const rtc::PacketOptions& options) override;
const rtc::PacketOptions& options); int SendTo(const void* pv,
virtual int Close(); size_t cb,
const SocketAddress& addr,
const rtc::PacketOptions& options) override;
int Close() override;
virtual State GetState() const; State GetState() const override;
virtual int GetOption(Socket::Option opt, int* value); int GetOption(Socket::Option opt, int* value) override;
virtual int SetOption(Socket::Option opt, int value); int SetOption(Socket::Option opt, int value) override;
virtual int GetError() const; int GetError() const override;
virtual void SetError(int error); void SetError(int error) override;
private: private:
// Called when the underlying socket is ready to be read from. // Called when the underlying socket is ready to be read from.

View File

@@ -32,6 +32,12 @@ AutoDetectProxy::AutoDetectProxy(const std::string& user_agent)
: agent_(user_agent), resolver_(NULL), socket_(NULL), next_(0) { : agent_(user_agent), resolver_(NULL), socket_(NULL), next_(0) {
} }
bool AutoDetectProxy::GetProxyForUrl(const char* agent,
const char* url,
rtc::ProxyInfo* proxy) {
return GetProxySettingsForUrl(agent, url, proxy, true);
}
AutoDetectProxy::~AutoDetectProxy() { AutoDetectProxy::~AutoDetectProxy() {
if (resolver_) { if (resolver_) {
resolver_->Destroy(false); resolver_->Destroy(false);

View File

@@ -50,20 +50,19 @@ class AutoDetectProxy : public SignalThread {
} }
// Default implementation of GetProxySettingsForUrl. Override for special // Default implementation of GetProxySettingsForUrl. Override for special
// implementation. // implementation.
virtual bool GetProxyForUrl(const char* agent, const char* url, virtual bool GetProxyForUrl(const char* agent,
rtc::ProxyInfo* proxy) { const char* url,
return GetProxySettingsForUrl(agent, url, proxy, true); rtc::ProxyInfo* proxy);
}
enum { MSG_TIMEOUT = SignalThread::ST_MSG_FIRST_AVAILABLE, enum { MSG_TIMEOUT = SignalThread::ST_MSG_FIRST_AVAILABLE,
MSG_UNRESOLVABLE, MSG_UNRESOLVABLE,
ADP_MSG_FIRST_AVAILABLE}; ADP_MSG_FIRST_AVAILABLE};
protected: protected:
virtual ~AutoDetectProxy(); ~AutoDetectProxy() override;
// SignalThread Interface // SignalThread Interface
virtual void DoWork(); void DoWork() override;
virtual void OnMessage(Message *msg); void OnMessage(Message* msg) override;
void Next(); void Next();
void Complete(ProxyType type); void Complete(ProxyType type);

View File

@@ -29,6 +29,8 @@ BandwidthSmoother::BandwidthSmoother(int initial_bandwidth_guess,
std::min(1.0, std::max(0.0, min_sample_count_percent))) { std::min(1.0, std::max(0.0, min_sample_count_percent))) {
} }
BandwidthSmoother::~BandwidthSmoother() = default;
// Samples a new bandwidth measurement // Samples a new bandwidth measurement
// returns true if the bandwidth estimation changed // returns true if the bandwidth estimation changed
bool BandwidthSmoother::Sample(uint32 sample_time, int bandwidth) { bool BandwidthSmoother::Sample(uint32 sample_time, int bandwidth) {

View File

@@ -35,6 +35,7 @@ class BandwidthSmoother {
double percent_increase, double percent_increase,
size_t samples_count_to_average, size_t samples_count_to_average,
double min_sample_count_percent); double min_sample_count_percent);
~BandwidthSmoother();
// Samples a new bandwidth measurement. // Samples a new bandwidth measurement.
// bandwidth is expected to be non-negative. // bandwidth is expected to be non-negative.

View File

@@ -37,6 +37,7 @@
'exp_filter.h', 'exp_filter.h',
'md5.cc', 'md5.cc',
'md5.h', 'md5.h',
'md5digest.cc',
'md5digest.h', 'md5digest.h',
'platform_file.cc', 'platform_file.cc',
'platform_file.h', 'platform_file.h',
@@ -75,7 +76,9 @@
'asyncinvoker.cc', 'asyncinvoker.cc',
'asyncinvoker.h', 'asyncinvoker.h',
'asyncinvoker-inl.h', 'asyncinvoker-inl.h',
'asyncpacketsocket.cc',
'asyncpacketsocket.h', 'asyncpacketsocket.h',
'asyncresolverinterface.cc',
'asyncresolverinterface.h', 'asyncresolverinterface.h',
'asyncsocket.cc', 'asyncsocket.cc',
'asyncsocket.h', 'asyncsocket.h',
@@ -94,6 +97,7 @@
'basictypes.h', 'basictypes.h',
'bind.h', 'bind.h',
'bind.h.pump', 'bind.h.pump',
'buffer.cc',
'buffer.h', 'buffer.h',
'bytebuffer.cc', 'bytebuffer.cc',
'bytebuffer.h', 'bytebuffer.h',
@@ -108,6 +112,7 @@
'crc32.cc', 'crc32.cc',
'crc32.h', 'crc32.h',
'criticalsection.h', 'criticalsection.h',
'cryptstring.cc',
'cryptstring.h', 'cryptstring.h',
'dbus.cc', 'dbus.cc',
'dbus.h', 'dbus.h',
@@ -226,11 +231,13 @@
'sec_buffer.h', 'sec_buffer.h',
'sha1.cc', 'sha1.cc',
'sha1.h', 'sha1.h',
'sha1digest.cc',
'sha1digest.h', 'sha1digest.h',
'sharedexclusivelock.cc', 'sharedexclusivelock.cc',
'sharedexclusivelock.h', 'sharedexclusivelock.h',
'signalthread.cc', 'signalthread.cc',
'signalthread.h', 'signalthread.h',
'sigslot.cc',
'sigslot.h', 'sigslot.h',
'sigslotrepeater.h', 'sigslotrepeater.h',
'socket.h', 'socket.h',
@@ -350,6 +357,7 @@
'asyncinvoker.cc', 'asyncinvoker.cc',
'asyncinvoker.h', 'asyncinvoker.h',
'asyncinvoker-inl.h', 'asyncinvoker-inl.h',
'asyncresolverinterface.cc',
'asyncresolverinterface.h', 'asyncresolverinterface.h',
'atomicops.h', 'atomicops.h',
'bandwidthsmoother.cc', 'bandwidthsmoother.cc',
@@ -357,6 +365,7 @@
'basictypes.h', 'basictypes.h',
'bind.h', 'bind.h',
'bind.h.pump', 'bind.h.pump',
'buffer.cc',
'buffer.h', 'buffer.h',
'callback.h', 'callback.h',
'callback.h.pump', 'callback.h.pump',

33
webrtc/base/buffer.cc Normal file
View File

@@ -0,0 +1,33 @@
/*
* Copyright 2015 The WebRTC Project Authors. All rights reserved.
*
* Use of this source code is governed by a BSD-style license
* that can be found in the LICENSE file in the root of the source
* tree. An additional intellectual property rights grant can be found
* in the file PATENTS. All contributing project authors may
* be found in the AUTHORS file in the root of the source tree.
*/
#include "webrtc/base/buffer.h"
namespace rtc {
Buffer::Buffer() {
Construct(NULL, 0, 0);
}
Buffer::Buffer(const void* data, size_t length) {
Construct(data, length, length);
}
Buffer::Buffer(const void* data, size_t length, size_t capacity) {
Construct(data, length, capacity);
}
Buffer::Buffer(const Buffer& buf) {
Construct(buf.data(), buf.length(), buf.length());
}
Buffer::~Buffer() = default;
}; // namespace rtc

View File

@@ -22,18 +22,11 @@ namespace rtc {
// Unlike std::string/vector, does not initialize data when expanding capacity. // Unlike std::string/vector, does not initialize data when expanding capacity.
class Buffer { class Buffer {
public: public:
Buffer() { Buffer();
Construct(NULL, 0, 0); Buffer(const void* data, size_t length);
} Buffer(const void* data, size_t length, size_t capacity);
Buffer(const void* data, size_t length) { Buffer(const Buffer& buf);
Construct(data, length, length); ~Buffer();
}
Buffer(const void* data, size_t length, size_t capacity) {
Construct(data, length, capacity);
}
Buffer(const Buffer& buf) {
Construct(buf.data(), buf.length(), buf.length());
}
const char* data() const { return data_.get(); } const char* data() const { return data_.get(); }
char* data() { return data_.get(); } char* data() { return data_.get(); }

View File

@@ -95,7 +95,7 @@ class CpuMonitor
: public rtc::MessageHandler, public sigslot::has_slots<> { : public rtc::MessageHandler, public sigslot::has_slots<> {
public: public:
explicit CpuMonitor(Thread* thread); explicit CpuMonitor(Thread* thread);
virtual ~CpuMonitor(); ~CpuMonitor() override;
void set_thread(Thread* thread); void set_thread(Thread* thread);
bool Start(int period_ms); bool Start(int period_ms);
@@ -105,7 +105,7 @@ class CpuMonitor
protected: protected:
// Override virtual method of parent MessageHandler. // Override virtual method of parent MessageHandler.
virtual void OnMessage(rtc::Message* msg); void OnMessage(rtc::Message* msg) override;
// Clear the monitor thread and stop sending it messages if the thread goes // Clear the monitor thread and stop sending it messages if the thread goes
// away before our lifetime. // away before our lifetime.
void OnMessageQueueDestroyed() { monitor_thread_ = NULL; } void OnMessageQueueDestroyed() { monitor_thread_ = NULL; }

View File

@@ -0,0 +1,75 @@
/*
* Copyright 2015 The WebRTC Project Authors. All rights reserved.
*
* Use of this source code is governed by a BSD-style license
* that can be found in the LICENSE file in the root of the source
* tree. An additional intellectual property rights grant can be found
* in the file PATENTS. All contributing project authors may
* be found in the AUTHORS file in the root of the source tree.
*/
#include "webrtc/base/cryptstring.h"
namespace rtc {
size_t EmptyCryptStringImpl::GetLength() const {
return 0;
}
void EmptyCryptStringImpl::CopyTo(char* dest, bool nullterminate) const {
if (nullterminate) {
*dest = '\0';
}
}
std::string EmptyCryptStringImpl::UrlEncode() const {
return "";
}
CryptStringImpl* EmptyCryptStringImpl::Copy() const {
return new EmptyCryptStringImpl();
}
void EmptyCryptStringImpl::CopyRawTo(std::vector<unsigned char>* dest) const {
dest->clear();
}
CryptString::CryptString() : impl_(new EmptyCryptStringImpl()) {
}
CryptString::CryptString(const CryptString& other)
: impl_(other.impl_->Copy()) {
}
CryptString::CryptString(const CryptStringImpl& impl) : impl_(impl.Copy()) {
}
CryptString::~CryptString() = default;
size_t InsecureCryptStringImpl::GetLength() const {
return password_.size();
}
void InsecureCryptStringImpl::CopyTo(char* dest, bool nullterminate) const {
memcpy(dest, password_.data(), password_.size());
if (nullterminate)
dest[password_.size()] = 0;
}
std::string InsecureCryptStringImpl::UrlEncode() const {
return password_;
}
CryptStringImpl* InsecureCryptStringImpl::Copy() const {
InsecureCryptStringImpl* copy = new InsecureCryptStringImpl;
copy->password() = password_;
return copy;
}
void InsecureCryptStringImpl::CopyRawTo(
std::vector<unsigned char>* dest) const {
dest->resize(password_.size());
memcpy(&dest->front(), password_.data(), password_.size());
}
}; // namespace rtc

View File

@@ -33,27 +33,22 @@ public:
class EmptyCryptStringImpl : public CryptStringImpl { class EmptyCryptStringImpl : public CryptStringImpl {
public: public:
virtual ~EmptyCryptStringImpl() {} ~EmptyCryptStringImpl() override {}
virtual size_t GetLength() const { return 0; } size_t GetLength() const override;
virtual void CopyTo(char * dest, bool nullterminate) const { void CopyTo(char* dest, bool nullterminate) const override;
if (nullterminate) { std::string UrlEncode() const override;
*dest = '\0'; CryptStringImpl* Copy() const override;
} void CopyRawTo(std::vector<unsigned char>* dest) const override;
}
virtual std::string UrlEncode() const { return ""; }
virtual CryptStringImpl * Copy() const { return new EmptyCryptStringImpl(); }
virtual void CopyRawTo(std::vector<unsigned char> * dest) const {
dest->clear();
}
}; };
class CryptString { class CryptString {
public: public:
CryptString() : impl_(new EmptyCryptStringImpl()) {} CryptString();
size_t GetLength() const { return impl_->GetLength(); } size_t GetLength() const { return impl_->GetLength(); }
void CopyTo(char * dest, bool nullterminate) const { impl_->CopyTo(dest, nullterminate); } void CopyTo(char * dest, bool nullterminate) const { impl_->CopyTo(dest, nullterminate); }
CryptString(const CryptString & other) : impl_(other.impl_->Copy()) {} CryptString(const CryptString& other);
explicit CryptString(const CryptStringImpl & impl) : impl_(impl.Copy()) {} explicit CryptString(const CryptStringImpl& impl);
~CryptString();
CryptString & operator=(const CryptString & other) { CryptString & operator=(const CryptString & other) {
if (this != &other) { if (this != &other) {
impl_.reset(other.impl_->Copy()); impl_.reset(other.impl_->Copy());
@@ -158,22 +153,13 @@ class InsecureCryptStringImpl : public CryptStringImpl {
std::string& password() { return password_; } std::string& password() { return password_; }
const std::string& password() const { return password_; } const std::string& password() const { return password_; }
virtual ~InsecureCryptStringImpl() {} ~InsecureCryptStringImpl() override = default;
virtual size_t GetLength() const { return password_.size(); } size_t GetLength() const override;
virtual void CopyTo(char * dest, bool nullterminate) const { void CopyTo(char* dest, bool nullterminate) const override;
memcpy(dest, password_.data(), password_.size()); std::string UrlEncode() const override;
if (nullterminate) dest[password_.size()] = 0; CryptStringImpl* Copy() const override;
} void CopyRawTo(std::vector<unsigned char>* dest) const override;
virtual std::string UrlEncode() const { return password_; }
virtual CryptStringImpl * Copy() const {
InsecureCryptStringImpl * copy = new InsecureCryptStringImpl;
copy->password() = password_;
return copy;
}
virtual void CopyRawTo(std::vector<unsigned char> * dest) const {
dest->resize(password_.size());
memcpy(&dest->front(), password_.data(), password_.size());
}
private: private:
std::string password_; std::string password_;
}; };

View File

@@ -43,7 +43,7 @@ public:
StreamInterface* stream) StreamInterface* stream)
: StreamAdapterInterface(stream), cache_(cache), id_(id), index_(index) : StreamAdapterInterface(stream), cache_(cache), id_(id), index_(index)
{ } { }
virtual ~DiskCacheAdapter() { ~DiskCacheAdapter() override {
Close(); Close();
cache_->ReleaseResource(id_, index_); cache_->ReleaseResource(id_, index_);
} }

View File

@@ -148,6 +148,10 @@ FilesystemInterface *Filesystem::EnsureDefaultFilesystem() {
return default_filesystem_; return default_filesystem_;
} }
DirectoryIterator* FilesystemInterface::IterateDirectory() {
return new DirectoryIterator();
}
bool FilesystemInterface::CopyFolder(const Pathname &old_path, bool FilesystemInterface::CopyFolder(const Pathname &old_path,
const Pathname &new_path) { const Pathname &new_path) {
bool success = true; bool success = true;
@@ -208,6 +212,10 @@ bool FilesystemInterface::DeleteFolderContents(const Pathname &folder) {
return success; return success;
} }
bool FilesystemInterface::DeleteFolderAndContents(const Pathname& folder) {
return DeleteFolderContents(folder) && DeleteEmptyFolder(folder);
}
bool FilesystemInterface::CleanAppTempFolder() { bool FilesystemInterface::CleanAppTempFolder() {
Pathname path; Pathname path;
if (!GetAppTempFolder(&path)) if (!GetAppTempFolder(&path))

View File

@@ -95,9 +95,7 @@ class FilesystemInterface {
// Returns a DirectoryIterator for a given pathname. // Returns a DirectoryIterator for a given pathname.
// TODO: Do fancy abstracted stuff // TODO: Do fancy abstracted stuff
virtual DirectoryIterator *IterateDirectory() { virtual DirectoryIterator* IterateDirectory();
return new DirectoryIterator();
}
// Opens a file. Returns an open StreamInterface if function succeeds. // Opens a file. Returns an open StreamInterface if function succeeds.
// Otherwise, returns NULL. // Otherwise, returns NULL.
@@ -133,9 +131,7 @@ class FilesystemInterface {
// This deletes the contents of a folder, recursively, and then deletes // This deletes the contents of a folder, recursively, and then deletes
// the folder itself. // the folder itself.
virtual bool DeleteFolderAndContents(const Pathname &folder) { virtual bool DeleteFolderAndContents(const Pathname& folder);
return DeleteFolderContents(folder) && DeleteEmptyFolder(folder);
}
// This will delete whatever is located at path, be it a file or a folder. // This will delete whatever is located at path, be it a file or a folder.
// If it is a folder, it will delete it recursively by calling // If it is a folder, it will delete it recursively by calling

View File

@@ -25,7 +25,7 @@ class FirewallSocket : public AsyncSocketAdapter {
: AsyncSocketAdapter(socket), server_(server), type_(type) { : AsyncSocketAdapter(socket), server_(server), type_(type) {
} }
virtual int Connect(const SocketAddress& addr) { int Connect(const SocketAddress& addr) override {
if (type_ == SOCK_STREAM) { if (type_ == SOCK_STREAM) {
if (!server_->Check(FP_TCP, GetLocalAddress(), addr)) { if (!server_->Check(FP_TCP, GetLocalAddress(), addr)) {
LOG(LS_VERBOSE) << "FirewallSocket outbound TCP connection from " LOG(LS_VERBOSE) << "FirewallSocket outbound TCP connection from "
@@ -38,10 +38,10 @@ class FirewallSocket : public AsyncSocketAdapter {
} }
return AsyncSocketAdapter::Connect(addr); return AsyncSocketAdapter::Connect(addr);
} }
virtual int Send(const void* pv, size_t cb) { int Send(const void* pv, size_t cb) override {
return SendTo(pv, cb, GetRemoteAddress()); return SendTo(pv, cb, GetRemoteAddress());
} }
virtual int SendTo(const void* pv, size_t cb, const SocketAddress& addr) { int SendTo(const void* pv, size_t cb, const SocketAddress& addr) override {
if (type_ == SOCK_DGRAM) { if (type_ == SOCK_DGRAM) {
if (!server_->Check(FP_UDP, GetLocalAddress(), addr)) { if (!server_->Check(FP_UDP, GetLocalAddress(), addr)) {
LOG(LS_VERBOSE) << "FirewallSocket outbound UDP packet from " LOG(LS_VERBOSE) << "FirewallSocket outbound UDP packet from "
@@ -52,11 +52,11 @@ class FirewallSocket : public AsyncSocketAdapter {
} }
return AsyncSocketAdapter::SendTo(pv, cb, addr); return AsyncSocketAdapter::SendTo(pv, cb, addr);
} }
virtual int Recv(void* pv, size_t cb) { int Recv(void* pv, size_t cb) override {
SocketAddress addr; SocketAddress addr;
return RecvFrom(pv, cb, &addr); return RecvFrom(pv, cb, &addr);
} }
virtual int RecvFrom(void* pv, size_t cb, SocketAddress* paddr) { int RecvFrom(void* pv, size_t cb, SocketAddress* paddr) override {
if (type_ == SOCK_DGRAM) { if (type_ == SOCK_DGRAM) {
while (true) { while (true) {
int res = AsyncSocketAdapter::RecvFrom(pv, cb, paddr); int res = AsyncSocketAdapter::RecvFrom(pv, cb, paddr);
@@ -72,7 +72,7 @@ class FirewallSocket : public AsyncSocketAdapter {
return AsyncSocketAdapter::RecvFrom(pv, cb, paddr); return AsyncSocketAdapter::RecvFrom(pv, cb, paddr);
} }
virtual int Listen(int backlog) { int Listen(int backlog) override {
if (!server_->tcp_listen_enabled()) { if (!server_->tcp_listen_enabled()) {
LOG(LS_VERBOSE) << "FirewallSocket listen attempt denied"; LOG(LS_VERBOSE) << "FirewallSocket listen attempt denied";
return -1; return -1;
@@ -80,7 +80,7 @@ class FirewallSocket : public AsyncSocketAdapter {
return AsyncSocketAdapter::Listen(backlog); return AsyncSocketAdapter::Listen(backlog);
} }
virtual AsyncSocket* Accept(SocketAddress* paddr) { AsyncSocket* Accept(SocketAddress* paddr) override {
SocketAddress addr; SocketAddress addr;
while (AsyncSocket* sock = AsyncSocketAdapter::Accept(&addr)) { while (AsyncSocket* sock = AsyncSocketAdapter::Accept(&addr)) {
if (server_->Check(FP_TCP, addr, GetLocalAddress())) { if (server_->Check(FP_TCP, addr, GetLocalAddress())) {
@@ -190,6 +190,18 @@ AsyncSocket* FirewallSocketServer::CreateAsyncSocket(int family, int type) {
return WrapSocket(server_->CreateAsyncSocket(family, type), type); return WrapSocket(server_->CreateAsyncSocket(family, type), type);
} }
void FirewallSocketServer::SetMessageQueue(MessageQueue* queue) {
server_->SetMessageQueue(queue);
}
bool FirewallSocketServer::Wait(int cms, bool process_io) {
return server_->Wait(cms, process_io);
}
void FirewallSocketServer::WakeUp() {
return server_->WakeUp();
}
AsyncSocket* FirewallSocketServer::WrapSocket(AsyncSocket* sock, int type) { AsyncSocket* FirewallSocketServer::WrapSocket(AsyncSocket* sock, int type) {
if (!sock || if (!sock ||
(type == SOCK_STREAM && !tcp_sockets_enabled_) || (type == SOCK_STREAM && !tcp_sockets_enabled_) ||

View File

@@ -29,7 +29,7 @@ class FirewallSocketServer : public SocketServer {
FirewallSocketServer(SocketServer * server, FirewallSocketServer(SocketServer * server,
FirewallManager * manager = NULL, FirewallManager * manager = NULL,
bool should_delete_server = false); bool should_delete_server = false);
virtual ~FirewallSocketServer(); ~FirewallSocketServer() override;
SocketServer* socketserver() const { return server_; } SocketServer* socketserver() const { return server_; }
void set_socketserver(SocketServer* server) { void set_socketserver(SocketServer* server) {
@@ -58,21 +58,15 @@ class FirewallSocketServer : public SocketServer {
bool Check(FirewallProtocol p, bool Check(FirewallProtocol p,
const SocketAddress& src, const SocketAddress& dst); const SocketAddress& src, const SocketAddress& dst);
virtual Socket* CreateSocket(int type); Socket* CreateSocket(int type) override;
virtual Socket* CreateSocket(int family, int type); Socket* CreateSocket(int family, int type) override;
virtual AsyncSocket* CreateAsyncSocket(int type); AsyncSocket* CreateAsyncSocket(int type) override;
virtual AsyncSocket* CreateAsyncSocket(int family, int type); AsyncSocket* CreateAsyncSocket(int family, int type) override;
virtual void SetMessageQueue(MessageQueue* queue) { void SetMessageQueue(MessageQueue* queue) override;
server_->SetMessageQueue(queue); bool Wait(int cms, bool process_io) override;
} void WakeUp() override;
virtual bool Wait(int cms, bool process_io) {
return server_->Wait(cms, process_io);
}
virtual void WakeUp() {
return server_->WakeUp();
}
Socket * WrapSocket(Socket * sock, int type); Socket * WrapSocket(Socket * sock, int type);
AsyncSocket * WrapSocket(AsyncSocket * sock, int type); AsyncSocket * WrapSocket(AsyncSocket * sock, int type);

View File

@@ -51,11 +51,9 @@ class RandomGenerator {
class SecureRandomGenerator : public RandomGenerator { class SecureRandomGenerator : public RandomGenerator {
public: public:
SecureRandomGenerator() {} SecureRandomGenerator() {}
~SecureRandomGenerator() {} ~SecureRandomGenerator() override {}
virtual bool Init(const void* seed, size_t len) { bool Init(const void* seed, size_t len) override { return true; }
return true; bool Generate(void* buf, size_t len) override {
}
virtual bool Generate(void* buf, size_t len) {
return (RAND_bytes(reinterpret_cast<unsigned char*>(buf), len) > 0); return (RAND_bytes(reinterpret_cast<unsigned char*>(buf), len) > 0);
} }
}; };
@@ -65,11 +63,9 @@ class SecureRandomGenerator : public RandomGenerator {
class SecureRandomGenerator : public RandomGenerator { class SecureRandomGenerator : public RandomGenerator {
public: public:
SecureRandomGenerator() {} SecureRandomGenerator() {}
~SecureRandomGenerator() {} ~SecureRandomGenerator() override {}
virtual bool Init(const void* seed, size_t len) { bool Init(const void* seed, size_t len) override { return true; }
return true; bool Generate(void* buf, size_t len) override {
}
virtual bool Generate(void* buf, size_t len) {
return (PK11_GenerateRandom(reinterpret_cast<unsigned char*>(buf), return (PK11_GenerateRandom(reinterpret_cast<unsigned char*>(buf),
static_cast<int>(len)) == SECSuccess); static_cast<int>(len)) == SECSuccess);
} }
@@ -153,12 +149,10 @@ class TestRandomGenerator : public RandomGenerator {
public: public:
TestRandomGenerator() : seed_(7) { TestRandomGenerator() : seed_(7) {
} }
~TestRandomGenerator() { ~TestRandomGenerator() override {
} }
virtual bool Init(const void* seed, size_t len) { bool Init(const void* seed, size_t len) override { return true; }
return true; bool Generate(void* buf, size_t len) override {
}
virtual bool Generate(void* buf, size_t len) {
for (size_t i = 0; i < len; ++i) { for (size_t i = 0; i < len; ++i) {
static_cast<uint8*>(buf)[i] = static_cast<uint8>(GetRandom()); static_cast<uint8*>(buf)[i] = static_cast<uint8>(GetRandom());
} }

View File

@@ -234,7 +234,7 @@ public:
BlockingMemoryStream(char* buffer, size_t size) BlockingMemoryStream(char* buffer, size_t size)
: ExternalMemoryStream(buffer, size) { } : ExternalMemoryStream(buffer, size) { }
virtual StreamResult DoReserve(size_t size, int* error) { StreamResult DoReserve(size_t size, int* error) override {
return (buffer_length_ >= size) ? SR_SUCCESS : SR_BLOCK; return (buffer_length_ >= size) ? SR_SUCCESS : SR_BLOCK;
} }
}; };
@@ -243,7 +243,7 @@ class HttpBase::DocumentStream : public StreamInterface {
public: public:
DocumentStream(HttpBase* base) : base_(base), error_(HE_DEFAULT) { } DocumentStream(HttpBase* base) : base_(base), error_(HE_DEFAULT) { }
virtual StreamState GetState() const { StreamState GetState() const override {
if (NULL == base_) if (NULL == base_)
return SS_CLOSED; return SS_CLOSED;
if (HM_RECV == base_->mode_) if (HM_RECV == base_->mode_)
@@ -251,8 +251,10 @@ public:
return SS_OPENING; return SS_OPENING;
} }
virtual StreamResult Read(void* buffer, size_t buffer_len, StreamResult Read(void* buffer,
size_t* read, int* error) { size_t buffer_len,
size_t* read,
int* error) override {
if (!base_) { if (!base_) {
if (error) *error = error_; if (error) *error = error_;
return (HE_NONE == error_) ? SR_EOS : SR_ERROR; return (HE_NONE == error_) ? SR_EOS : SR_ERROR;
@@ -309,13 +311,15 @@ public:
return result; return result;
} }
virtual StreamResult Write(const void* data, size_t data_len, StreamResult Write(const void* data,
size_t* written, int* error) { size_t data_len,
size_t* written,
int* error) override {
if (error) *error = -1; if (error) *error = -1;
return SR_ERROR; return SR_ERROR;
} }
virtual void Close() { void Close() override {
if (base_) { if (base_) {
HttpBase* base = Disconnect(HE_NONE); HttpBase* base = Disconnect(HE_NONE);
if (HM_RECV == base->mode_ && base->http_stream_) { if (HM_RECV == base->mode_ && base->http_stream_) {
@@ -326,7 +330,7 @@ public:
} }
} }
virtual bool GetAvailable(size_t* size) const { bool GetAvailable(size_t* size) const override {
if (!base_ || HM_RECV != base_->mode_) if (!base_ || HM_RECV != base_->mode_)
return false; return false;
size_t data_size = base_->GetDataRemaining(); size_t data_size = base_->GetDataRemaining();

View File

@@ -94,7 +94,7 @@ class HttpBase
{ {
public: public:
HttpBase(); HttpBase();
virtual ~HttpBase(); ~HttpBase() override;
void notify(IHttpNotify* notify) { notify_ = notify; } void notify(IHttpNotify* notify) { notify_ = notify; }
bool attach(StreamInterface* stream); bool attach(StreamInterface* stream);
@@ -145,16 +145,22 @@ protected:
void OnDocumentEvent(StreamInterface* stream, int events, int error); void OnDocumentEvent(StreamInterface* stream, int events, int error);
// HttpParser Interface // HttpParser Interface
virtual ProcessResult ProcessLeader(const char* line, size_t len, ProcessResult ProcessLeader(const char* line,
HttpError* error); size_t len,
virtual ProcessResult ProcessHeader(const char* name, size_t nlen, HttpError* error) override;
const char* value, size_t vlen, ProcessResult ProcessHeader(const char* name,
HttpError* error); size_t nlen,
virtual ProcessResult ProcessHeaderComplete(bool chunked, size_t& data_size, const char* value,
HttpError* error); size_t vlen,
virtual ProcessResult ProcessData(const char* data, size_t len, size_t& read, HttpError* error) override;
HttpError* error); ProcessResult ProcessHeaderComplete(bool chunked,
virtual void OnComplete(HttpError err); size_t& data_size,
HttpError* error) override;
ProcessResult ProcessData(const char* data,
size_t len,
size_t& read,
HttpError* error) override;
void OnComplete(HttpError err) override;
private: private:
class DocumentStream; class DocumentStream;

View File

@@ -62,7 +62,7 @@ public:
// be freed by the caller. Otherwise, an internal object is allocated. // be freed by the caller. Otherwise, an internal object is allocated.
HttpClient(const std::string& agent, StreamPool* pool, HttpClient(const std::string& agent, StreamPool* pool,
HttpTransaction* transaction = NULL); HttpTransaction* transaction = NULL);
virtual ~HttpClient(); ~HttpClient() override;
void set_pool(StreamPool* pool) { pool_ = pool; } void set_pool(StreamPool* pool) { pool_ = pool; }
@@ -161,9 +161,9 @@ protected:
void OnResolveResult(AsyncResolverInterface* resolver); void OnResolveResult(AsyncResolverInterface* resolver);
// IHttpNotify Interface // IHttpNotify Interface
virtual HttpError onHttpHeaderComplete(bool chunked, size_t& data_size); HttpError onHttpHeaderComplete(bool chunked, size_t& data_size) override;
virtual void onHttpComplete(HttpMode mode, HttpError err); void onHttpComplete(HttpMode mode, HttpError err) override;
virtual void onHttpClosed(HttpError err); void onHttpClosed(HttpError err) override;
private: private:
enum CacheState { CS_READY, CS_WRITING, CS_READING, CS_VALIDATING }; enum CacheState { CS_READY, CS_WRITING, CS_READING, CS_VALIDATING };

View File

@@ -401,6 +401,11 @@ std::string HttpAddress(const SocketAddress& address, bool secure) {
// HttpData // HttpData
////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////
HttpData::HttpData() : version(HVER_1_1) {
}
HttpData::~HttpData() = default;
void void
HttpData::clear(bool release_document) { HttpData::clear(bool release_document) {
// Clear headers first, since releasing a document may have far-reaching // Clear headers first, since releasing a document may have far-reaching

View File

@@ -283,7 +283,7 @@ struct HttpData {
HttpVersion version; HttpVersion version;
scoped_ptr<StreamInterface> document; scoped_ptr<StreamInterface> document;
HttpData() : version(HVER_1_1) { } HttpData();
enum HeaderCombine { HC_YES, HC_NO, HC_AUTO, HC_REPLACE, HC_NEW }; enum HeaderCombine { HC_YES, HC_NO, HC_AUTO, HC_REPLACE, HC_NEW };
void changeHeader(const std::string& name, const std::string& value, void changeHeader(const std::string& name, const std::string& value,
@@ -368,7 +368,7 @@ struct HttpData {
virtual HttpError parseLeader(const char* line, size_t len) = 0; virtual HttpError parseLeader(const char* line, size_t len) = 0;
protected: protected:
virtual ~HttpData() { } virtual ~HttpData();
void clear(bool release_document); void clear(bool release_document);
void copy(const HttpData& src); void copy(const HttpData& src);
@@ -385,8 +385,8 @@ struct HttpRequestData : public HttpData {
void clear(bool release_document); void clear(bool release_document);
void copy(const HttpRequestData& src); void copy(const HttpRequestData& src);
virtual size_t formatLeader(char* buffer, size_t size) const; size_t formatLeader(char* buffer, size_t size) const override;
virtual HttpError parseLeader(const char* line, size_t len); HttpError parseLeader(const char* line, size_t len) override;
bool getAbsoluteUri(std::string* uri) const; bool getAbsoluteUri(std::string* uri) const;
bool getRelativeUri(std::string* host, std::string* path) const; bool getRelativeUri(std::string* host, std::string* path) const;
@@ -408,8 +408,8 @@ struct HttpResponseData : public HttpData {
uint32 scode = HC_MOVED_TEMPORARILY); uint32 scode = HC_MOVED_TEMPORARILY);
void set_error(uint32 scode); void set_error(uint32 scode);
virtual size_t formatLeader(char* buffer, size_t size) const; size_t formatLeader(char* buffer, size_t size) const override;
virtual HttpError parseLeader(const char* line, size_t len); HttpError parseLeader(const char* line, size_t len) override;
}; };
struct HttpTransaction { struct HttpTransaction {

View File

@@ -54,6 +54,8 @@ HttpRequest::HttpRequest(const std::string &user_agent)
client_(user_agent.c_str(), NULL), error_(HE_NONE) { client_(user_agent.c_str(), NULL), error_(HE_NONE) {
} }
HttpRequest::~HttpRequest() = default;
void HttpRequest::Send() { void HttpRequest::Send() {
// TODO: Rewrite this to use the thread's native socket server, and a more // TODO: Rewrite this to use the thread's native socket server, and a more
// natural flow? // natural flow?

View File

@@ -30,6 +30,7 @@ class MemoryStream;
class HttpRequest { class HttpRequest {
public: public:
HttpRequest(const std::string &user_agent); HttpRequest(const std::string &user_agent);
~HttpRequest();
void Send(); void Send();

View File

@@ -80,7 +80,7 @@ private:
class Connection : private IHttpNotify { class Connection : private IHttpNotify {
public: public:
Connection(int connection_id, HttpServer* server); Connection(int connection_id, HttpServer* server);
virtual ~Connection(); ~Connection() override;
void BeginProcess(StreamInterface* stream); void BeginProcess(StreamInterface* stream);
StreamInterface* EndProcess(); StreamInterface* EndProcess();
@@ -89,9 +89,9 @@ private:
void InitiateClose(bool force); void InitiateClose(bool force);
// IHttpNotify Interface // IHttpNotify Interface
virtual HttpError onHttpHeaderComplete(bool chunked, size_t& data_size); HttpError onHttpHeaderComplete(bool chunked, size_t& data_size) override;
virtual void onHttpComplete(HttpMode mode, HttpError err); void onHttpComplete(HttpMode mode, HttpError err) override;
virtual void onHttpClosed(HttpError err); void onHttpClosed(HttpError err) override;
int connection_id_; int connection_id_;
HttpServer* server_; HttpServer* server_;
@@ -116,7 +116,7 @@ private:
class HttpListenServer : public HttpServer, public sigslot::has_slots<> { class HttpListenServer : public HttpServer, public sigslot::has_slots<> {
public: public:
HttpListenServer(); HttpListenServer();
virtual ~HttpListenServer(); ~HttpListenServer() override;
int Listen(const SocketAddress& address); int Listen(const SocketAddress& address);
bool GetAddress(SocketAddress* address) const; bool GetAddress(SocketAddress* address) const;

View File

@@ -28,29 +28,30 @@ class MacBaseSocketServer;
class MacAsyncSocket : public AsyncSocket, public sigslot::has_slots<> { class MacAsyncSocket : public AsyncSocket, public sigslot::has_slots<> {
public: public:
MacAsyncSocket(MacBaseSocketServer* ss, int family); MacAsyncSocket(MacBaseSocketServer* ss, int family);
virtual ~MacAsyncSocket(); ~MacAsyncSocket() override;
bool valid() const { return source_ != NULL; } bool valid() const { return source_ != NULL; }
// Socket interface // Socket interface
virtual SocketAddress GetLocalAddress() const; SocketAddress GetLocalAddress() const override;
virtual SocketAddress GetRemoteAddress() const; SocketAddress GetRemoteAddress() const override;
virtual int Bind(const SocketAddress& addr); int Bind(const SocketAddress& addr) override;
virtual int Connect(const SocketAddress& addr); int Connect(const SocketAddress& addr) override;
virtual int Send(const void* buffer, size_t length); int Send(const void* buffer, size_t length) override;
virtual int SendTo(const void* buffer, size_t length, int SendTo(const void* buffer,
const SocketAddress& addr); size_t length,
virtual int Recv(void* buffer, size_t length); const SocketAddress& addr) override;
virtual int RecvFrom(void* buffer, size_t length, SocketAddress* out_addr); int Recv(void* buffer, size_t length) override;
virtual int Listen(int backlog); int RecvFrom(void* buffer, size_t length, SocketAddress* out_addr) override;
virtual MacAsyncSocket* Accept(SocketAddress* out_addr); int Listen(int backlog) override;
virtual int Close(); MacAsyncSocket* Accept(SocketAddress* out_addr) override;
virtual int GetError() const; int Close() override;
virtual void SetError(int error); int GetError() const override;
virtual ConnState GetState() const; void SetError(int error) override;
virtual int EstimateMTU(uint16* mtu); ConnState GetState() const override;
virtual int GetOption(Option opt, int* value); int EstimateMTU(uint16* mtu) override;
virtual int SetOption(Option opt, int value); int GetOption(Option opt, int* value) override;
int SetOption(Option opt, int value) override;
// For the MacBaseSocketServer to disable callbacks when process_io is false. // For the MacBaseSocketServer to disable callbacks when process_io is false.
void EnableCallbacks(); void EnableCallbacks();

View File

@@ -29,10 +29,10 @@ namespace rtc {
class MacCocoaSocketServer : public MacBaseSocketServer { class MacCocoaSocketServer : public MacBaseSocketServer {
public: public:
explicit MacCocoaSocketServer(); explicit MacCocoaSocketServer();
virtual ~MacCocoaSocketServer(); ~MacCocoaSocketServer() override;
virtual bool Wait(int cms, bool process_io); bool Wait(int cms, bool process_io) override;
virtual void WakeUp(); void WakeUp() override;
private: private:
MacCocoaSocketServerHelperRtc* helper_; MacCocoaSocketServerHelperRtc* helper_;

View File

@@ -29,6 +29,14 @@ MacBaseSocketServer::MacBaseSocketServer() {
MacBaseSocketServer::~MacBaseSocketServer() { MacBaseSocketServer::~MacBaseSocketServer() {
} }
Socket* MacBaseSocketServer::CreateSocket(int type) {
return NULL;
}
Socket* MacBaseSocketServer::CreateSocket(int family, int type) {
return NULL;
}
AsyncSocket* MacBaseSocketServer::CreateAsyncSocket(int type) { AsyncSocket* MacBaseSocketServer::CreateAsyncSocket(int type) {
return CreateAsyncSocket(AF_INET, type); return CreateAsyncSocket(AF_INET, type);
} }

View File

@@ -26,23 +26,23 @@ class MacAsyncSocket;
class MacBaseSocketServer : public PhysicalSocketServer { class MacBaseSocketServer : public PhysicalSocketServer {
public: public:
MacBaseSocketServer(); MacBaseSocketServer();
virtual ~MacBaseSocketServer(); ~MacBaseSocketServer() override;
// SocketServer Interface // SocketServer Interface
virtual Socket* CreateSocket(int type) { return NULL; } Socket* CreateSocket(int type) override;
virtual Socket* CreateSocket(int family, int type) { return NULL; } Socket* CreateSocket(int family, int type) override;
virtual AsyncSocket* CreateAsyncSocket(int type); AsyncSocket* CreateAsyncSocket(int type) override;
virtual AsyncSocket* CreateAsyncSocket(int family, int type); AsyncSocket* CreateAsyncSocket(int family, int type) override;
virtual bool Wait(int cms, bool process_io) = 0; bool Wait(int cms, bool process_io) override = 0;
virtual void WakeUp() = 0; void WakeUp() override = 0;
void RegisterSocket(MacAsyncSocket* socket); void RegisterSocket(MacAsyncSocket* socket);
void UnregisterSocket(MacAsyncSocket* socket); void UnregisterSocket(MacAsyncSocket* socket);
// PhysicalSocketServer Overrides // PhysicalSocketServer Overrides
virtual bool SetPosixSignalHandler(int signum, void (*handler)(int)); bool SetPosixSignalHandler(int signum, void (*handler)(int)) override;
protected: protected:
void EnableSocketCallbacks(bool enable); void EnableSocketCallbacks(bool enable);
@@ -65,11 +65,11 @@ class MacBaseSocketServer : public PhysicalSocketServer {
class MacCFSocketServer : public MacBaseSocketServer { class MacCFSocketServer : public MacBaseSocketServer {
public: public:
MacCFSocketServer(); MacCFSocketServer();
virtual ~MacCFSocketServer(); ~MacCFSocketServer() override;
// SocketServer Interface // SocketServer Interface
virtual bool Wait(int cms, bool process_io); bool Wait(int cms, bool process_io) override;
virtual void WakeUp(); void WakeUp() override;
void OnWakeUpCallback(); void OnWakeUpCallback();
private: private:

View File

@@ -17,14 +17,15 @@ namespace rtc {
class MacWindowPicker : public WindowPicker { class MacWindowPicker : public WindowPicker {
public: public:
MacWindowPicker(); MacWindowPicker();
~MacWindowPicker(); ~MacWindowPicker() override;
virtual bool Init(); bool Init() override;
virtual bool IsVisible(const WindowId& id); bool IsVisible(const WindowId& id) override;
virtual bool MoveToFront(const WindowId& id); bool MoveToFront(const WindowId& id) override;
virtual bool GetWindowList(WindowDescriptionList* descriptions); bool GetWindowList(WindowDescriptionList* descriptions) override;
virtual bool GetDesktopList(DesktopDescriptionList* descriptions); bool GetDesktopList(DesktopDescriptionList* descriptions) override;
virtual bool GetDesktopDimensions(const DesktopId& id, int* width, bool GetDesktopDimensions(const DesktopId& id,
int* height); int* width,
int* height) override;
private: private:
void* lib_handle_; void* lib_handle_;

32
webrtc/base/md5digest.cc Normal file
View File

@@ -0,0 +1,32 @@
/*
* Copyright 2015 The WebRTC Project Authors. All rights reserved.
*
* Use of this source code is governed by a BSD-style license
* that can be found in the LICENSE file in the root of the source
* tree. An additional intellectual property rights grant can be found
* in the file PATENTS. All contributing project authors may
* be found in the AUTHORS file in the root of the source tree.
*/
#include "webrtc/base/md5digest.h"
namespace rtc {
size_t Md5Digest::Size() const {
return kSize;
}
void Md5Digest::Update(const void* buf, size_t len) {
MD5Update(&ctx_, static_cast<const uint8*>(buf), len);
}
size_t Md5Digest::Finish(void* buf, size_t len) {
if (len < kSize) {
return 0;
}
MD5Final(&ctx_, static_cast<uint8*>(buf));
MD5Init(&ctx_); // Reset for next use.
return kSize;
}
}; // namespace rtc

View File

@@ -23,20 +23,10 @@ class Md5Digest : public MessageDigest {
Md5Digest() { Md5Digest() {
MD5Init(&ctx_); MD5Init(&ctx_);
} }
virtual size_t Size() const { size_t Size() const override;
return kSize; void Update(const void* buf, size_t len) override;
} size_t Finish(void* buf, size_t len) override;
virtual void Update(const void* buf, size_t len) {
MD5Update(&ctx_, static_cast<const uint8*>(buf), len);
}
virtual size_t Finish(void* buf, size_t len) {
if (len < kSize) {
return 0;
}
MD5Final(&ctx_, static_cast<uint8*>(buf));
MD5Init(&ctx_); // Reset for next use.
return kSize;
}
private: private:
MD5_CTX ctx_; MD5_CTX ctx_;
}; };

View File

@@ -297,6 +297,20 @@ void MessageQueue::Post(MessageHandler *phandler, uint32 id,
ss_->WakeUp(); ss_->WakeUp();
} }
void MessageQueue::PostDelayed(int cmsDelay,
MessageHandler* phandler,
uint32 id,
MessageData* pdata) {
return DoDelayPost(cmsDelay, TimeAfter(cmsDelay), phandler, id, pdata);
}
void MessageQueue::PostAt(uint32 tstamp,
MessageHandler* phandler,
uint32 id,
MessageData* pdata) {
return DoDelayPost(TimeUntil(tstamp), tstamp, phandler, id, pdata);
}
void MessageQueue::DoDelayPost(int cmsDelay, uint32 tstamp, void MessageQueue::DoDelayPost(int cmsDelay, uint32 tstamp,
MessageHandler *phandler, uint32 id, MessageData* pdata) { MessageHandler *phandler, uint32 id, MessageData* pdata) {
if (fStop_) if (fStop_)

View File

@@ -192,14 +192,14 @@ class MessageQueue {
virtual bool Peek(Message *pmsg, int cmsWait = 0); virtual bool Peek(Message *pmsg, int cmsWait = 0);
virtual void Post(MessageHandler *phandler, uint32 id = 0, virtual void Post(MessageHandler *phandler, uint32 id = 0,
MessageData *pdata = NULL, bool time_sensitive = false); MessageData *pdata = NULL, bool time_sensitive = false);
virtual void PostDelayed(int cmsDelay, MessageHandler *phandler, virtual void PostDelayed(int cmsDelay,
uint32 id = 0, MessageData *pdata = NULL) { MessageHandler* phandler,
return DoDelayPost(cmsDelay, TimeAfter(cmsDelay), phandler, id, pdata); uint32 id = 0,
} MessageData* pdata = NULL);
virtual void PostAt(uint32 tstamp, MessageHandler *phandler, virtual void PostAt(uint32 tstamp,
uint32 id = 0, MessageData *pdata = NULL) { MessageHandler* phandler,
return DoDelayPost(TimeUntil(tstamp), tstamp, phandler, id, pdata); uint32 id = 0,
} MessageData* pdata = NULL);
virtual void Clear(MessageHandler *phandler, uint32 id = MQID_ANY, virtual void Clear(MessageHandler *phandler, uint32 id = MQID_ANY,
MessageList* removed = NULL); MessageList* removed = NULL);
virtual void Dispatch(Message *pmsg); virtual void Dispatch(Message *pmsg);

View File

@@ -27,7 +27,7 @@ namespace rtc {
class MultipartStream : public StreamInterface, public sigslot::has_slots<> { class MultipartStream : public StreamInterface, public sigslot::has_slots<> {
public: public:
MultipartStream(const std::string& type, const std::string& boundary); MultipartStream(const std::string& type, const std::string& boundary);
virtual ~MultipartStream(); ~MultipartStream() override;
void GetContentType(std::string* content_type); void GetContentType(std::string* content_type);
@@ -48,16 +48,20 @@ class MultipartStream : public StreamInterface, public sigslot::has_slots<> {
size_t GetEndPartSize() const; size_t GetEndPartSize() const;
// StreamInterface // StreamInterface
virtual StreamState GetState() const; StreamState GetState() const override;
virtual StreamResult Read(void* buffer, size_t buffer_len, StreamResult Read(void* buffer,
size_t* read, int* error); size_t buffer_len,
virtual StreamResult Write(const void* data, size_t data_len, size_t* read,
size_t* written, int* error); int* error) override;
virtual void Close(); StreamResult Write(const void* data,
virtual bool SetPosition(size_t position); size_t data_len,
virtual bool GetPosition(size_t* position) const; size_t* written,
virtual bool GetSize(size_t* size) const; int* error) override;
virtual bool GetAvailable(size_t* size) const; void Close() override;
bool SetPosition(size_t position) override;
bool GetPosition(size_t* position) const override;
bool GetSize(size_t* size) const override;
bool GetAvailable(size_t* size) const override;
private: private:
typedef std::vector<StreamInterface*> PartList; typedef std::vector<StreamInterface*> PartList;

View File

@@ -54,7 +54,7 @@ class NATServer : public sigslot::has_slots<> {
NATServer( NATServer(
NATType type, SocketFactory* internal, const SocketAddress& internal_addr, NATType type, SocketFactory* internal, const SocketAddress& internal_addr,
SocketFactory* external, const SocketAddress& external_ip); SocketFactory* external, const SocketAddress& external_ip);
~NATServer(); ~NATServer() override;
SocketAddress internal_address() const { SocketAddress internal_address() const {
return server_socket_->GetLocalAddress(); return server_socket_->GetLocalAddress();

View File

@@ -72,20 +72,20 @@ class NATSocket : public AsyncSocket, public sigslot::has_slots<> {
socket_(NULL), buf_(NULL), size_(0) { socket_(NULL), buf_(NULL), size_(0) {
} }
virtual ~NATSocket() { ~NATSocket() override {
delete socket_; delete socket_;
delete[] buf_; delete[] buf_;
} }
virtual SocketAddress GetLocalAddress() const { SocketAddress GetLocalAddress() const override {
return (socket_) ? socket_->GetLocalAddress() : SocketAddress(); return (socket_) ? socket_->GetLocalAddress() : SocketAddress();
} }
virtual SocketAddress GetRemoteAddress() const { SocketAddress GetRemoteAddress() const override {
return remote_addr_; // will be NIL if not connected return remote_addr_; // will be NIL if not connected
} }
virtual int Bind(const SocketAddress& addr) { int Bind(const SocketAddress& addr) override {
if (socket_) { // already bound, bubble up error if (socket_) { // already bound, bubble up error
return -1; return -1;
} }
@@ -107,7 +107,7 @@ class NATSocket : public AsyncSocket, public sigslot::has_slots<> {
return result; return result;
} }
virtual int Connect(const SocketAddress& addr) { int Connect(const SocketAddress& addr) override {
if (!socket_) { // socket must be bound, for now if (!socket_) { // socket must be bound, for now
return -1; return -1;
} }
@@ -126,12 +126,14 @@ class NATSocket : public AsyncSocket, public sigslot::has_slots<> {
return result; return result;
} }
virtual int Send(const void* data, size_t size) { int Send(const void* data, size_t size) override {
ASSERT(connected_); ASSERT(connected_);
return SendTo(data, size, remote_addr_); return SendTo(data, size, remote_addr_);
} }
virtual int SendTo(const void* data, size_t size, const SocketAddress& addr) { int SendTo(const void* data,
size_t size,
const SocketAddress& addr) override {
ASSERT(!connected_ || addr == remote_addr_); ASSERT(!connected_ || addr == remote_addr_);
if (server_addr_.IsNil() || type_ == SOCK_STREAM) { if (server_addr_.IsNil() || type_ == SOCK_STREAM) {
return socket_->SendTo(data, size, addr); return socket_->SendTo(data, size, addr);
@@ -151,12 +153,12 @@ class NATSocket : public AsyncSocket, public sigslot::has_slots<> {
return result; return result;
} }
virtual int Recv(void* data, size_t size) { int Recv(void* data, size_t size) override {
SocketAddress addr; SocketAddress addr;
return RecvFrom(data, size, &addr); return RecvFrom(data, size, &addr);
} }
virtual int RecvFrom(void* data, size_t size, SocketAddress *out_addr) { int RecvFrom(void* data, size_t size, SocketAddress* out_addr) override {
if (server_addr_.IsNil() || type_ == SOCK_STREAM) { if (server_addr_.IsNil() || type_ == SOCK_STREAM) {
return socket_->RecvFrom(data, size, out_addr); return socket_->RecvFrom(data, size, out_addr);
} }
@@ -196,7 +198,7 @@ class NATSocket : public AsyncSocket, public sigslot::has_slots<> {
return result; return result;
} }
virtual int Close() { int Close() override {
int result = 0; int result = 0;
if (socket_) { if (socket_) {
result = socket_->Close(); result = socket_->Close();
@@ -210,28 +212,20 @@ class NATSocket : public AsyncSocket, public sigslot::has_slots<> {
return result; return result;
} }
virtual int Listen(int backlog) { int Listen(int backlog) override { return socket_->Listen(backlog); }
return socket_->Listen(backlog); AsyncSocket* Accept(SocketAddress* paddr) override {
}
virtual AsyncSocket* Accept(SocketAddress *paddr) {
return socket_->Accept(paddr); return socket_->Accept(paddr);
} }
virtual int GetError() const { int GetError() const override { return socket_->GetError(); }
return socket_->GetError(); void SetError(int error) override { socket_->SetError(error); }
} ConnState GetState() const override {
virtual void SetError(int error) {
socket_->SetError(error);
}
virtual ConnState GetState() const {
return connected_ ? CS_CONNECTED : CS_CLOSED; return connected_ ? CS_CONNECTED : CS_CLOSED;
} }
virtual int EstimateMTU(uint16* mtu) { int EstimateMTU(uint16* mtu) override { return socket_->EstimateMTU(mtu); }
return socket_->EstimateMTU(mtu); int GetOption(Option opt, int* value) override {
}
virtual int GetOption(Option opt, int* value) {
return socket_->GetOption(opt, value); return socket_->GetOption(opt, value);
} }
virtual int SetOption(Option opt, int value) { int SetOption(Option opt, int value) override {
return socket_->SetOption(opt, value); return socket_->SetOption(opt, value);
} }
@@ -371,6 +365,19 @@ AsyncSocket* NATSocketServer::CreateAsyncSocket(int family, int type) {
return new NATSocket(this, family, type); return new NATSocket(this, family, type);
} }
void NATSocketServer::SetMessageQueue(MessageQueue* queue) {
msg_queue_ = queue;
server_->SetMessageQueue(queue);
}
bool NATSocketServer::Wait(int cms, bool process_io) {
return server_->Wait(cms, process_io);
}
void NATSocketServer::WakeUp() {
server_->WakeUp();
}
AsyncSocket* NATSocketServer::CreateInternalSocket(int family, int type, AsyncSocket* NATSocketServer::CreateInternalSocket(int family, int type,
const SocketAddress& local_addr, SocketAddress* nat_addr) { const SocketAddress& local_addr, SocketAddress* nat_addr) {
AsyncSocket* socket = NULL; AsyncSocket* socket = NULL;
@@ -400,6 +407,7 @@ NATSocketServer::Translator::Translator(
ext_factory, ext_ip)); ext_factory, ext_ip));
} }
NATSocketServer::Translator::~Translator() = default;
NATSocketServer::Translator* NATSocketServer::Translator::GetTranslator( NATSocketServer::Translator* NATSocketServer::Translator::GetTranslator(
const SocketAddress& ext_ip) { const SocketAddress& ext_ip) {

View File

@@ -40,14 +40,16 @@ class NATSocketFactory : public SocketFactory, public NATInternalSocketFactory {
NATSocketFactory(SocketFactory* factory, const SocketAddress& nat_addr); NATSocketFactory(SocketFactory* factory, const SocketAddress& nat_addr);
// SocketFactory implementation // SocketFactory implementation
virtual Socket* CreateSocket(int type); Socket* CreateSocket(int type) override;
virtual Socket* CreateSocket(int family, int type); Socket* CreateSocket(int family, int type) override;
virtual AsyncSocket* CreateAsyncSocket(int type); AsyncSocket* CreateAsyncSocket(int type) override;
virtual AsyncSocket* CreateAsyncSocket(int family, int type); AsyncSocket* CreateAsyncSocket(int family, int type) override;
// NATInternalSocketFactory implementation // NATInternalSocketFactory implementation
virtual AsyncSocket* CreateInternalSocket(int family, int type, AsyncSocket* CreateInternalSocket(int family,
const SocketAddress& local_addr, SocketAddress* nat_addr); int type,
const SocketAddress& local_addr,
SocketAddress* nat_addr) override;
private: private:
SocketFactory* factory_; SocketFactory* factory_;
@@ -89,6 +91,7 @@ class NATSocketServer : public SocketServer, public NATInternalSocketFactory {
Translator(NATSocketServer* server, NATType type, Translator(NATSocketServer* server, NATType type,
const SocketAddress& int_addr, SocketFactory* ext_factory, const SocketAddress& int_addr, SocketFactory* ext_factory,
const SocketAddress& ext_addr); const SocketAddress& ext_addr);
~Translator();
SocketFactory* internal_factory() { return internal_factory_.get(); } SocketFactory* internal_factory() { return internal_factory_.get(); }
SocketAddress internal_address() const { SocketAddress internal_address() const {
@@ -128,26 +131,21 @@ class NATSocketServer : public SocketServer, public NATInternalSocketFactory {
void RemoveTranslator(const SocketAddress& ext_ip); void RemoveTranslator(const SocketAddress& ext_ip);
// SocketServer implementation // SocketServer implementation
virtual Socket* CreateSocket(int type); Socket* CreateSocket(int type) override;
virtual Socket* CreateSocket(int family, int type); Socket* CreateSocket(int family, int type) override;
virtual AsyncSocket* CreateAsyncSocket(int type); AsyncSocket* CreateAsyncSocket(int type) override;
virtual AsyncSocket* CreateAsyncSocket(int family, int type); AsyncSocket* CreateAsyncSocket(int family, int type) override;
virtual void SetMessageQueue(MessageQueue* queue) { void SetMessageQueue(MessageQueue* queue) override;
msg_queue_ = queue; bool Wait(int cms, bool process_io) override;
server_->SetMessageQueue(queue); void WakeUp() override;
}
virtual bool Wait(int cms, bool process_io) {
return server_->Wait(cms, process_io);
}
virtual void WakeUp() {
server_->WakeUp();
}
// NATInternalSocketFactory implementation // NATInternalSocketFactory implementation
virtual AsyncSocket* CreateInternalSocket(int family, int type, AsyncSocket* CreateInternalSocket(int family,
const SocketAddress& local_addr, SocketAddress* nat_addr); int type,
const SocketAddress& local_addr,
SocketAddress* nat_addr) override;
private: private:
SocketServer* server_; SocketServer* server_;

View File

@@ -16,30 +16,30 @@ namespace rtc {
class SymmetricNAT : public NAT { class SymmetricNAT : public NAT {
public: public:
bool IsSymmetric() { return true; } bool IsSymmetric() override { return true; }
bool FiltersIP() { return true; } bool FiltersIP() override { return true; }
bool FiltersPort() { return true; } bool FiltersPort() override { return true; }
}; };
class OpenConeNAT : public NAT { class OpenConeNAT : public NAT {
public: public:
bool IsSymmetric() { return false; } bool IsSymmetric() override { return false; }
bool FiltersIP() { return false; } bool FiltersIP() override { return false; }
bool FiltersPort() { return false; } bool FiltersPort() override { return false; }
}; };
class AddressRestrictedNAT : public NAT { class AddressRestrictedNAT : public NAT {
public: public:
bool IsSymmetric() { return false; } bool IsSymmetric() override { return false; }
bool FiltersIP() { return true; } bool FiltersIP() override { return true; }
bool FiltersPort() { return false; } bool FiltersPort() override { return false; }
}; };
class PortRestrictedNAT : public NAT { class PortRestrictedNAT : public NAT {
public: public:
bool IsSymmetric() { return false; } bool IsSymmetric() override { return false; }
bool FiltersIP() { return true; } bool FiltersIP() override { return true; }
bool FiltersPort() { return true; } bool FiltersPort() override { return true; }
}; };
NAT* NAT::Create(NATType type) { NAT* NAT::Create(NATType type) {

View File

@@ -60,6 +60,8 @@ int ResolveHostname(const std::string& hostname, int family,
AsyncResolver::AsyncResolver() : error_(-1) { AsyncResolver::AsyncResolver() : error_(-1) {
} }
AsyncResolver::~AsyncResolver() = default;
void AsyncResolver::Start(const SocketAddress& addr) { void AsyncResolver::Start(const SocketAddress& addr) {
addr_ = addr; addr_ = addr;
// SignalThred Start will kickoff the resolve process. // SignalThred Start will kickoff the resolve process.
@@ -80,6 +82,14 @@ bool AsyncResolver::GetResolvedAddress(int family, SocketAddress* addr) const {
return false; return false;
} }
int AsyncResolver::GetError() const {
return error_;
}
void AsyncResolver::Destroy(bool wait) {
SignalThread::Destroy(wait);
}
void AsyncResolver::DoWork() { void AsyncResolver::DoWork() {
error_ = ResolveHostname(addr_.hostname().c_str(), addr_.family(), error_ = ResolveHostname(addr_.hostname().c_str(), addr_.family(),
&addresses_); &addresses_);

View File

@@ -34,19 +34,19 @@ class AsyncResolverTest;
class AsyncResolver : public SignalThread, public AsyncResolverInterface { class AsyncResolver : public SignalThread, public AsyncResolverInterface {
public: public:
AsyncResolver(); AsyncResolver();
virtual ~AsyncResolver() {} ~AsyncResolver() override;
virtual void Start(const SocketAddress& addr); void Start(const SocketAddress& addr) override;
virtual bool GetResolvedAddress(int family, SocketAddress* addr) const; bool GetResolvedAddress(int family, SocketAddress* addr) const override;
virtual int GetError() const { return error_; } int GetError() const override;
virtual void Destroy(bool wait) { SignalThread::Destroy(wait); } void Destroy(bool wait) override;
const std::vector<IPAddress>& addresses() const { return addresses_; } const std::vector<IPAddress>& addresses() const { return addresses_; }
void set_error(int error) { error_ = error; } void set_error(int error) { error_ = error; }
protected: protected:
virtual void DoWork(); void DoWork() override;
virtual void OnWorkDone(); void OnWorkDone() override;
private: private:
SocketAddress addr_; SocketAddress addr_;

View File

@@ -708,6 +708,8 @@ Network::Network(const std::string& name, const std::string& desc,
ignored_(false), type_(type), preference_(0) { ignored_(false), type_(type), preference_(0) {
} }
Network::~Network() = default;
// Sets the addresses of this network. Returns true if the address set changed. // Sets the addresses of this network. Returns true if the address set changed.
// Change detection is short circuited if the changed argument is true. // Change detection is short circuited if the changed argument is true.
bool Network::SetIPs(const std::vector<InterfaceAddress>& ips, bool changed) { bool Network::SetIPs(const std::vector<InterfaceAddress>& ips, bool changed) {

View File

@@ -103,10 +103,10 @@ class NetworkManager {
class NetworkManagerBase : public NetworkManager { class NetworkManagerBase : public NetworkManager {
public: public:
NetworkManagerBase(); NetworkManagerBase();
virtual ~NetworkManagerBase(); ~NetworkManagerBase() override;
virtual void GetNetworks(std::vector<Network*>* networks) const; void GetNetworks(std::vector<Network*>* networks) const override;
virtual void GetAnyAddressNetworks(NetworkList* networks); void GetAnyAddressNetworks(NetworkList* networks) override;
bool ipv6_enabled() const { return ipv6_enabled_; } bool ipv6_enabled() const { return ipv6_enabled_; }
void set_ipv6_enabled(bool enabled) { ipv6_enabled_ = enabled; } void set_ipv6_enabled(bool enabled) { ipv6_enabled_ = enabled; }
@@ -147,16 +147,16 @@ class BasicNetworkManager : public NetworkManagerBase,
public MessageHandler { public MessageHandler {
public: public:
BasicNetworkManager(); BasicNetworkManager();
virtual ~BasicNetworkManager(); ~BasicNetworkManager() override;
virtual void StartUpdating(); void StartUpdating() override;
virtual void StopUpdating(); void StopUpdating() override;
// Logs the available networks. // Logs the available networks.
virtual void DumpNetworks(bool include_ignored); void DumpNetworks(bool include_ignored) override;
// MessageHandler interface. // MessageHandler interface.
virtual void OnMessage(Message* msg); void OnMessage(Message* msg) override;
bool started() { return start_count_ > 0; } bool started() { return start_count_ > 0; }
// Sets the network ignore list, which is empty by default. Any network on the // Sets the network ignore list, which is empty by default. Any network on the
@@ -219,6 +219,7 @@ class Network {
Network(const std::string& name, const std::string& description, Network(const std::string& name, const std::string& description,
const IPAddress& prefix, int prefix_length, AdapterType type); const IPAddress& prefix, int prefix_length, AdapterType type);
~Network();
// Returns the name of the interface this network is associated wtih. // Returns the name of the interface this network is associated wtih.
const std::string& name() const { return name_; } const std::string& name() const { return name_; }

View File

@@ -117,6 +117,10 @@ NSSCertificate::NSSCertificate(CERTCertificate* cert, SSLCertChain* chain)
chain_.reset(chain->Copy()); chain_.reset(chain->Copy());
} }
NSSCertificate::~NSSCertificate() {
if (certificate_)
CERT_DestroyCertificate(certificate_);
}
NSSCertificate *NSSCertificate::FromPEMString(const std::string &pem_string) { NSSCertificate *NSSCertificate::FromPEMString(const std::string &pem_string) {
std::string der; std::string der;
@@ -329,6 +333,9 @@ bool NSSCertificate::GetDigestObject(const std::string &algorithm,
return true; return true;
} }
NSSIdentity::NSSIdentity(NSSKeyPair* keypair, NSSCertificate* cert)
: keypair_(keypair), certificate_(cert) {
}
NSSIdentity* NSSIdentity::GenerateInternal(const SSLIdentityParams& params) { NSSIdentity* NSSIdentity::GenerateInternal(const SSLIdentityParams& params) {
std::string subject_name_string = "CN=" + params.common_name; std::string subject_name_string = "CN=" + params.common_name;
@@ -495,6 +502,10 @@ SSLIdentity* NSSIdentity::FromPEMStrings(const std::string& private_key,
return new NSSIdentity(keypair.release(), cert.release()); return new NSSIdentity(keypair.release(), cert.release());
} }
NSSIdentity::~NSSIdentity() {
LOG(LS_INFO) << "Destroying NSS identity";
}
NSSIdentity *NSSIdentity::GetReference() const { NSSIdentity *NSSIdentity::GetReference() const {
NSSKeyPair *keypair = keypair_->GetReference(); NSSKeyPair *keypair = keypair_->GetReference();
if (!keypair) if (!keypair)

View File

@@ -53,25 +53,22 @@ class NSSCertificate : public SSLCertificate {
// and the constructor makes a copy. // and the constructor makes a copy.
explicit NSSCertificate(CERTCertificate* cert); explicit NSSCertificate(CERTCertificate* cert);
explicit NSSCertificate(CERTCertList* cert_list); explicit NSSCertificate(CERTCertList* cert_list);
virtual ~NSSCertificate() { ~NSSCertificate() override;
if (certificate_)
CERT_DestroyCertificate(certificate_);
}
virtual NSSCertificate* GetReference() const; NSSCertificate* GetReference() const override;
virtual std::string ToPEMString() const; std::string ToPEMString() const override;
virtual void ToDER(Buffer* der_buffer) const; void ToDER(Buffer* der_buffer) const override;
virtual bool GetSignatureDigestAlgorithm(std::string* algorithm) const; bool GetSignatureDigestAlgorithm(std::string* algorithm) const override;
virtual bool ComputeDigest(const std::string& algorithm, bool ComputeDigest(const std::string& algorithm,
unsigned char* digest, unsigned char* digest,
size_t size, size_t size,
size_t* length) const; size_t* length) const override;
virtual bool GetChain(SSLCertChain** chain) const; bool GetChain(SSLCertChain** chain) const override;
CERTCertificate* certificate() { return certificate_; } CERTCertificate* certificate() { return certificate_; }
@@ -104,18 +101,15 @@ class NSSIdentity : public SSLIdentity {
static NSSIdentity* GenerateForTest(const SSLIdentityParams& params); static NSSIdentity* GenerateForTest(const SSLIdentityParams& params);
static SSLIdentity* FromPEMStrings(const std::string& private_key, static SSLIdentity* FromPEMStrings(const std::string& private_key,
const std::string& certificate); const std::string& certificate);
virtual ~NSSIdentity() { ~NSSIdentity() override;
LOG(LS_INFO) << "Destroying NSS identity";
}
virtual NSSIdentity* GetReference() const; NSSIdentity* GetReference() const override;
virtual NSSCertificate& certificate() const; NSSCertificate& certificate() const override;
NSSKeyPair* keypair() const { return keypair_.get(); } NSSKeyPair* keypair() const { return keypair_.get(); }
private: private:
NSSIdentity(NSSKeyPair* keypair, NSSCertificate* cert) : NSSIdentity(NSSKeyPair* keypair, NSSCertificate* cert);
keypair_(keypair), certificate_(cert) {}
static NSSIdentity* GenerateInternal(const SSLIdentityParams& params); static NSSIdentity* GenerateInternal(const SSLIdentityParams& params);

View File

@@ -614,6 +614,11 @@ void NSSStreamAdapter::Cleanup() {
Thread::Current()->Clear(this, MSG_DTLS_TIMEOUT); Thread::Current()->Clear(this, MSG_DTLS_TIMEOUT);
} }
bool NSSStreamAdapter::GetDigestLength(const std::string& algorithm,
size_t* length) {
return NSSCertificate::GetDigestLength(algorithm, length);
}
StreamResult NSSStreamAdapter::Read(void* data, size_t data_len, StreamResult NSSStreamAdapter::Read(void* data, size_t data_len,
size_t* read, int* error) { size_t* read, int* error) {
// SSL_CONNECTED sanity check. // SSL_CONNECTED sanity check.

View File

@@ -52,28 +52,32 @@ class NSSContext {
class NSSStreamAdapter : public SSLStreamAdapterHelper { class NSSStreamAdapter : public SSLStreamAdapterHelper {
public: public:
explicit NSSStreamAdapter(StreamInterface* stream); explicit NSSStreamAdapter(StreamInterface* stream);
virtual ~NSSStreamAdapter(); ~NSSStreamAdapter() override;
bool Init(); bool Init();
virtual StreamResult Read(void* data, size_t data_len, StreamResult Read(void* data,
size_t* read, int* error); size_t data_len,
virtual StreamResult Write(const void* data, size_t data_len, size_t* read,
size_t* written, int* error); int* error) override;
void OnMessage(Message *msg); StreamResult Write(const void* data,
size_t data_len,
size_t* written,
int* error) override;
void OnMessage(Message* msg) override;
virtual bool GetSslCipher(std::string* cipher); bool GetSslCipher(std::string* cipher) override;
// Key Extractor interface // Key Extractor interface
virtual bool ExportKeyingMaterial(const std::string& label, bool ExportKeyingMaterial(const std::string& label,
const uint8* context, const uint8* context,
size_t context_len, size_t context_len,
bool use_context, bool use_context,
uint8* result, uint8* result,
size_t result_len); size_t result_len) override;
// DTLS-SRTP interface // DTLS-SRTP interface
virtual bool SetDtlsSrtpCiphers(const std::vector<std::string>& ciphers); bool SetDtlsSrtpCiphers(const std::vector<std::string>& ciphers) override;
virtual bool GetDtlsSrtpCipher(std::string* cipher); bool GetDtlsSrtpCipher(std::string* cipher) override;
// Capabilities interfaces // Capabilities interfaces
static bool HaveDtls(); static bool HaveDtls();
@@ -83,14 +87,12 @@ class NSSStreamAdapter : public SSLStreamAdapterHelper {
protected: protected:
// Override SSLStreamAdapter // Override SSLStreamAdapter
virtual void OnEvent(StreamInterface* stream, int events, int err); void OnEvent(StreamInterface* stream, int events, int err) override;
// Override SSLStreamAdapterHelper // Override SSLStreamAdapterHelper
virtual int BeginSSL(); int BeginSSL() override;
virtual void Cleanup(); void Cleanup() override;
virtual bool GetDigestLength(const std::string& algorithm, size_t* length) { bool GetDigestLength(const std::string& algorithm, size_t* length) override;
return NSSCertificate::GetDigestLength(algorithm, length);
}
private: private:
int ContinueSSL(); int ContinueSSL();

View File

@@ -31,24 +31,24 @@ public:
static bool CleanupSSL(); static bool CleanupSSL();
OpenSSLAdapter(AsyncSocket* socket); OpenSSLAdapter(AsyncSocket* socket);
virtual ~OpenSSLAdapter(); ~OpenSSLAdapter() override;
virtual void SetMode(SSLMode mode); void SetMode(SSLMode mode) override;
virtual int StartSSL(const char* hostname, bool restartable); int StartSSL(const char* hostname, bool restartable) override;
virtual int Send(const void* pv, size_t cb); int Send(const void* pv, size_t cb) override;
virtual int SendTo(const void* pv, size_t cb, const SocketAddress& addr); int SendTo(const void* pv, size_t cb, const SocketAddress& addr) override;
virtual int Recv(void* pv, size_t cb); int Recv(void* pv, size_t cb) override;
virtual int RecvFrom(void* pv, size_t cb, SocketAddress* paddr); int RecvFrom(void* pv, size_t cb, SocketAddress* paddr) override;
virtual int Close(); int Close() override;
// Note that the socket returns ST_CONNECTING while SSL is being negotiated. // Note that the socket returns ST_CONNECTING while SSL is being negotiated.
virtual ConnState GetState() const; ConnState GetState() const override;
protected: protected:
virtual void OnConnectEvent(AsyncSocket* socket); void OnConnectEvent(AsyncSocket* socket) override;
virtual void OnReadEvent(AsyncSocket* socket); void OnReadEvent(AsyncSocket* socket) override;
virtual void OnWriteEvent(AsyncSocket* socket); void OnWriteEvent(AsyncSocket* socket) override;
virtual void OnCloseEvent(AsyncSocket* socket, int err); void OnCloseEvent(AsyncSocket* socket, int err) override;
private: private:
enum SSLState { enum SSLState {
@@ -62,7 +62,7 @@ private:
void Error(const char* context, int err, bool signal = true); void Error(const char* context, int err, bool signal = true);
void Cleanup(); void Cleanup();
virtual void OnMessage(Message* msg); void OnMessage(Message* msg) override;
static bool VerifyServerName(SSL* ssl, const char* host, static bool VerifyServerName(SSL* ssl, const char* host,
bool ignore_bad_cert); bool ignore_bad_cert);

View File

@@ -22,13 +22,13 @@ class OpenSSLDigest : public MessageDigest {
public: public:
// Creates an OpenSSLDigest with |algorithm| as the hash algorithm. // Creates an OpenSSLDigest with |algorithm| as the hash algorithm.
explicit OpenSSLDigest(const std::string& algorithm); explicit OpenSSLDigest(const std::string& algorithm);
~OpenSSLDigest(); ~OpenSSLDigest() override;
// Returns the digest output size (e.g. 16 bytes for MD5). // Returns the digest output size (e.g. 16 bytes for MD5).
virtual size_t Size() const; size_t Size() const override;
// Updates the digest with |len| bytes from |buf|. // Updates the digest with |len| bytes from |buf|.
virtual void Update(const void* buf, size_t len); void Update(const void* buf, size_t len) override;
// Outputs the digest value to |buf| with length |len|. // Outputs the digest value to |buf| with length |len|.
virtual size_t Finish(void* buf, size_t len); size_t Finish(void* buf, size_t len) override;
// Helper function to look up a digest's EVP by name. // Helper function to look up a digest's EVP by name.
static bool GetDigestEVP(const std::string &algorithm, static bool GetDigestEVP(const std::string &algorithm,

View File

@@ -151,6 +151,11 @@ OpenSSLKeyPair::~OpenSSLKeyPair() {
EVP_PKEY_free(pkey_); EVP_PKEY_free(pkey_);
} }
OpenSSLKeyPair* OpenSSLKeyPair::GetReference() {
AddReference();
return new OpenSSLKeyPair(pkey_);
}
void OpenSSLKeyPair::AddReference() { void OpenSSLKeyPair::AddReference() {
CRYPTO_add(&pkey_->references, 1, CRYPTO_LOCK_EVP_PKEY); CRYPTO_add(&pkey_->references, 1, CRYPTO_LOCK_EVP_PKEY);
} }
@@ -218,6 +223,13 @@ bool OpenSSLCertificate::GetSignatureDigestAlgorithm(
EVP_get_digestbyobj(x509_->sig_alg->algorithm), algorithm); EVP_get_digestbyobj(x509_->sig_alg->algorithm), algorithm);
} }
bool OpenSSLCertificate::GetChain(SSLCertChain** chain) const {
// Chains are not yet supported when using OpenSSL.
// OpenSSLStreamAdapter::SSLVerifyCallback currently requires the remote
// certificate to be self-signed.
return false;
}
bool OpenSSLCertificate::ComputeDigest(const std::string& algorithm, bool OpenSSLCertificate::ComputeDigest(const std::string& algorithm,
unsigned char* digest, unsigned char* digest,
size_t size, size_t size,
@@ -250,6 +262,10 @@ OpenSSLCertificate::~OpenSSLCertificate() {
X509_free(x509_); X509_free(x509_);
} }
OpenSSLCertificate* OpenSSLCertificate::GetReference() const {
return new OpenSSLCertificate(x509_);
}
std::string OpenSSLCertificate::ToPEMString() const { std::string OpenSSLCertificate::ToPEMString() const {
BIO* bio = BIO_new(BIO_s_mem()); BIO* bio = BIO_new(BIO_s_mem());
if (!bio) { if (!bio) {
@@ -291,6 +307,15 @@ void OpenSSLCertificate::AddReference() const {
CRYPTO_add(&x509_->references, 1, CRYPTO_LOCK_X509); CRYPTO_add(&x509_->references, 1, CRYPTO_LOCK_X509);
} }
OpenSSLIdentity::OpenSSLIdentity(OpenSSLKeyPair* key_pair,
OpenSSLCertificate* certificate)
: key_pair_(key_pair), certificate_(certificate) {
ASSERT(key_pair != NULL);
ASSERT(certificate != NULL);
}
OpenSSLIdentity::~OpenSSLIdentity() = default;
OpenSSLIdentity* OpenSSLIdentity::GenerateInternal( OpenSSLIdentity* OpenSSLIdentity::GenerateInternal(
const SSLIdentityParams& params) { const SSLIdentityParams& params) {
OpenSSLKeyPair *key_pair = OpenSSLKeyPair::Generate(); OpenSSLKeyPair *key_pair = OpenSSLKeyPair::Generate();
@@ -347,6 +372,15 @@ SSLIdentity* OpenSSLIdentity::FromPEMStrings(
cert.release()); cert.release());
} }
const OpenSSLCertificate& OpenSSLIdentity::certificate() const {
return *certificate_;
}
OpenSSLIdentity* OpenSSLIdentity::GetReference() const {
return new OpenSSLIdentity(key_pair_->GetReference(),
certificate_->GetReference());
}
bool OpenSSLIdentity::ConfigureIdentity(SSL_CTX* ctx) { bool OpenSSLIdentity::ConfigureIdentity(SSL_CTX* ctx) {
// 1 is the documented success return code. // 1 is the documented success return code.
if (SSL_CTX_use_certificate(ctx, certificate_->x509()) != 1 || if (SSL_CTX_use_certificate(ctx, certificate_->x509()) != 1 ||

View File

@@ -36,10 +36,7 @@ class OpenSSLKeyPair {
virtual ~OpenSSLKeyPair(); virtual ~OpenSSLKeyPair();
virtual OpenSSLKeyPair* GetReference() { virtual OpenSSLKeyPair* GetReference();
AddReference();
return new OpenSSLKeyPair(pkey_);
}
EVP_PKEY* pkey() const { return pkey_; } EVP_PKEY* pkey() const { return pkey_; }
@@ -64,23 +61,21 @@ class OpenSSLCertificate : public SSLCertificate {
const SSLIdentityParams& params); const SSLIdentityParams& params);
static OpenSSLCertificate* FromPEMString(const std::string& pem_string); static OpenSSLCertificate* FromPEMString(const std::string& pem_string);
virtual ~OpenSSLCertificate(); ~OpenSSLCertificate() override;
virtual OpenSSLCertificate* GetReference() const { OpenSSLCertificate* GetReference() const override;
return new OpenSSLCertificate(x509_);
}
X509* x509() const { return x509_; } X509* x509() const { return x509_; }
virtual std::string ToPEMString() const; std::string ToPEMString() const override;
virtual void ToDER(Buffer* der_buffer) const; void ToDER(Buffer* der_buffer) const override;
// Compute the digest of the certificate given algorithm // Compute the digest of the certificate given algorithm
virtual bool ComputeDigest(const std::string& algorithm, bool ComputeDigest(const std::string& algorithm,
unsigned char* digest, unsigned char* digest,
size_t size, size_t size,
size_t* length) const; size_t* length) const override;
// Compute the digest of a certificate as an X509 * // Compute the digest of a certificate as an X509 *
static bool ComputeDigest(const X509* x509, static bool ComputeDigest(const X509* x509,
@@ -89,14 +84,8 @@ class OpenSSLCertificate : public SSLCertificate {
size_t size, size_t size,
size_t* length); size_t* length);
virtual bool GetSignatureDigestAlgorithm(std::string* algorithm) const; bool GetSignatureDigestAlgorithm(std::string* algorithm) const override;
bool GetChain(SSLCertChain** chain) const override;
virtual bool GetChain(SSLCertChain** chain) const {
// Chains are not yet supported when using OpenSSL.
// OpenSSLStreamAdapter::SSLVerifyCallback currently requires the remote
// certificate to be self-signed.
return false;
}
private: private:
void AddReference() const; void AddReference() const;
@@ -114,27 +103,16 @@ class OpenSSLIdentity : public SSLIdentity {
static OpenSSLIdentity* GenerateForTest(const SSLIdentityParams& params); static OpenSSLIdentity* GenerateForTest(const SSLIdentityParams& params);
static SSLIdentity* FromPEMStrings(const std::string& private_key, static SSLIdentity* FromPEMStrings(const std::string& private_key,
const std::string& certificate); const std::string& certificate);
virtual ~OpenSSLIdentity() { } ~OpenSSLIdentity() override;
virtual const OpenSSLCertificate& certificate() const { const OpenSSLCertificate& certificate() const override;
return *certificate_; OpenSSLIdentity* GetReference() const override;
}
virtual OpenSSLIdentity* GetReference() const {
return new OpenSSLIdentity(key_pair_->GetReference(),
certificate_->GetReference());
}
// Configure an SSL context object to use our key and certificate. // Configure an SSL context object to use our key and certificate.
bool ConfigureIdentity(SSL_CTX* ctx); bool ConfigureIdentity(SSL_CTX* ctx);
private: private:
OpenSSLIdentity(OpenSSLKeyPair* key_pair, OpenSSLIdentity(OpenSSLKeyPair* key_pair, OpenSSLCertificate* certificate);
OpenSSLCertificate* certificate)
: key_pair_(key_pair), certificate_(certificate) {
ASSERT(key_pair != NULL);
ASSERT(certificate != NULL);
}
static OpenSSLIdentity* GenerateInternal(const SSLIdentityParams& params); static OpenSSLIdentity* GenerateInternal(const SSLIdentityParams& params);

View File

@@ -59,48 +59,51 @@ class OpenSSLIdentity;
class OpenSSLStreamAdapter : public SSLStreamAdapter { class OpenSSLStreamAdapter : public SSLStreamAdapter {
public: public:
explicit OpenSSLStreamAdapter(StreamInterface* stream); explicit OpenSSLStreamAdapter(StreamInterface* stream);
virtual ~OpenSSLStreamAdapter(); ~OpenSSLStreamAdapter() override;
virtual void SetIdentity(SSLIdentity* identity); void SetIdentity(SSLIdentity* identity) override;
// Default argument is for compatibility // Default argument is for compatibility
virtual void SetServerRole(SSLRole role = SSL_SERVER); void SetServerRole(SSLRole role = SSL_SERVER) override;
virtual bool SetPeerCertificateDigest(const std::string& digest_alg, bool SetPeerCertificateDigest(const std::string& digest_alg,
const unsigned char* digest_val, const unsigned char* digest_val,
size_t digest_len); size_t digest_len) override;
virtual bool GetPeerCertificate(SSLCertificate** cert) const; bool GetPeerCertificate(SSLCertificate** cert) const override;
virtual int StartSSLWithServer(const char* server_name); int StartSSLWithServer(const char* server_name) override;
virtual int StartSSLWithPeer(); int StartSSLWithPeer() override;
virtual void SetMode(SSLMode mode); void SetMode(SSLMode mode) override;
virtual StreamResult Read(void* data, size_t data_len, StreamResult Read(void* data,
size_t* read, int* error); size_t data_len,
virtual StreamResult Write(const void* data, size_t data_len, size_t* read,
size_t* written, int* error); int* error) override;
virtual void Close(); StreamResult Write(const void* data,
virtual StreamState GetState() const; size_t data_len,
size_t* written,
int* error) override;
void Close() override;
StreamState GetState() const override;
#ifndef OPENSSL_IS_BORINGSSL #ifndef OPENSSL_IS_BORINGSSL
// Return the RFC (5246, 3268, etc.) cipher name for an OpenSSL cipher. // Return the RFC (5246, 3268, etc.) cipher name for an OpenSSL cipher.
static const char* GetRfcSslCipherName(const SSL_CIPHER* cipher); static const char* GetRfcSslCipherName(const SSL_CIPHER* cipher);
#endif #endif
virtual bool GetSslCipher(std::string* cipher); bool GetSslCipher(std::string* cipher) override;
// Key Extractor interface // Key Extractor interface
virtual bool ExportKeyingMaterial(const std::string& label, bool ExportKeyingMaterial(const std::string& label,
const uint8* context, const uint8* context,
size_t context_len, size_t context_len,
bool use_context, bool use_context,
uint8* result, uint8* result,
size_t result_len); size_t result_len) override;
// DTLS-SRTP interface // DTLS-SRTP interface
virtual bool SetDtlsSrtpCiphers(const std::vector<std::string>& ciphers); bool SetDtlsSrtpCiphers(const std::vector<std::string>& ciphers) override;
virtual bool GetDtlsSrtpCipher(std::string* cipher); bool GetDtlsSrtpCipher(std::string* cipher) override;
// Capabilities interfaces // Capabilities interfaces
static bool HaveDtls(); static bool HaveDtls();
@@ -109,7 +112,7 @@ class OpenSSLStreamAdapter : public SSLStreamAdapter {
static std::string GetDefaultSslCipher(); static std::string GetDefaultSslCipher();
protected: protected:
virtual void OnEvent(StreamInterface* stream, int events, int err); void OnEvent(StreamInterface* stream, int events, int err) override;
private: private:
enum SSLState { enum SSLState {
@@ -149,7 +152,7 @@ class OpenSSLStreamAdapter : public SSLStreamAdapter {
void Cleanup(); void Cleanup();
// Override MessageHandler // Override MessageHandler
virtual void OnMessage(Message* msg); void OnMessage(Message* msg) override;
// Flush the input buffers by reading left bytes (for DTLS) // Flush the input buffers by reading left bytes (for DTLS)
void FlushInput(unsigned int left); void FlushInput(unsigned int left);

View File

@@ -21,6 +21,8 @@ namespace rtc {
OptionsFile::OptionsFile(const std::string &path) : path_(path) { OptionsFile::OptionsFile(const std::string &path) : path_(path) {
} }
OptionsFile::~OptionsFile() = default;
bool OptionsFile::Load() { bool OptionsFile::Load() {
options_.clear(); options_.clear();
// Open file. // Open file.

View File

@@ -22,6 +22,7 @@ namespace rtc {
class OptionsFile { class OptionsFile {
public: public:
OptionsFile(const std::string &path); OptionsFile(const std::string &path);
~OptionsFile();
// Loads the file from disk, overwriting the in-memory values. // Loads the file from disk, overwriting the in-memory values.
bool Load(); bool Load();

View File

@@ -120,7 +120,7 @@ class PhysicalSocket : public AsyncSocket, public sigslot::has_slots<> {
} }
} }
virtual ~PhysicalSocket() { ~PhysicalSocket() override {
Close(); Close();
} }
@@ -135,7 +135,7 @@ class PhysicalSocket : public AsyncSocket, public sigslot::has_slots<> {
return s_ != INVALID_SOCKET; return s_ != INVALID_SOCKET;
} }
SocketAddress GetLocalAddress() const { SocketAddress GetLocalAddress() const override {
sockaddr_storage addr_storage = {0}; sockaddr_storage addr_storage = {0};
socklen_t addrlen = sizeof(addr_storage); socklen_t addrlen = sizeof(addr_storage);
sockaddr* addr = reinterpret_cast<sockaddr*>(&addr_storage); sockaddr* addr = reinterpret_cast<sockaddr*>(&addr_storage);
@@ -150,7 +150,7 @@ class PhysicalSocket : public AsyncSocket, public sigslot::has_slots<> {
return address; return address;
} }
SocketAddress GetRemoteAddress() const { SocketAddress GetRemoteAddress() const override {
sockaddr_storage addr_storage = {0}; sockaddr_storage addr_storage = {0};
socklen_t addrlen = sizeof(addr_storage); socklen_t addrlen = sizeof(addr_storage);
sockaddr* addr = reinterpret_cast<sockaddr*>(&addr_storage); sockaddr* addr = reinterpret_cast<sockaddr*>(&addr_storage);
@@ -165,7 +165,7 @@ class PhysicalSocket : public AsyncSocket, public sigslot::has_slots<> {
return address; return address;
} }
int Bind(const SocketAddress& bind_addr) { int Bind(const SocketAddress& bind_addr) override {
sockaddr_storage addr_storage; sockaddr_storage addr_storage;
size_t len = bind_addr.ToSockAddrStorage(&addr_storage); size_t len = bind_addr.ToSockAddrStorage(&addr_storage);
sockaddr* addr = reinterpret_cast<sockaddr*>(&addr_storage); sockaddr* addr = reinterpret_cast<sockaddr*>(&addr_storage);
@@ -180,7 +180,7 @@ class PhysicalSocket : public AsyncSocket, public sigslot::has_slots<> {
return err; return err;
} }
int Connect(const SocketAddress& addr) { int Connect(const SocketAddress& addr) override {
// TODO: Implicit creation is required to reconnect... // TODO: Implicit creation is required to reconnect...
// ...but should we make it more explicit? // ...but should we make it more explicit?
if (state_ != CS_CLOSED) { if (state_ != CS_CLOSED) {
@@ -222,21 +222,19 @@ class PhysicalSocket : public AsyncSocket, public sigslot::has_slots<> {
return 0; return 0;
} }
int GetError() const { int GetError() const override {
CritScope cs(&crit_); CritScope cs(&crit_);
return error_; return error_;
} }
void SetError(int error) { void SetError(int error) override {
CritScope cs(&crit_); CritScope cs(&crit_);
error_ = error; error_ = error;
} }
ConnState GetState() const { ConnState GetState() const override { return state_; }
return state_;
}
int GetOption(Option opt, int* value) { int GetOption(Option opt, int* value) override {
int slevel; int slevel;
int sopt; int sopt;
if (TranslateOption(opt, &slevel, &sopt) == -1) if (TranslateOption(opt, &slevel, &sopt) == -1)
@@ -251,7 +249,7 @@ class PhysicalSocket : public AsyncSocket, public sigslot::has_slots<> {
return ret; return ret;
} }
int SetOption(Option opt, int value) { int SetOption(Option opt, int value) override {
int slevel; int slevel;
int sopt; int sopt;
if (TranslateOption(opt, &slevel, &sopt) == -1) if (TranslateOption(opt, &slevel, &sopt) == -1)
@@ -264,7 +262,7 @@ class PhysicalSocket : public AsyncSocket, public sigslot::has_slots<> {
return ::setsockopt(s_, slevel, sopt, (SockOptArg)&value, sizeof(value)); return ::setsockopt(s_, slevel, sopt, (SockOptArg)&value, sizeof(value));
} }
int Send(const void *pv, size_t cb) { int Send(const void* pv, size_t cb) override {
int sent = ::send(s_, reinterpret_cast<const char *>(pv), (int)cb, int sent = ::send(s_, reinterpret_cast<const char *>(pv), (int)cb,
#if defined(WEBRTC_LINUX) && !defined(WEBRTC_ANDROID) #if defined(WEBRTC_LINUX) && !defined(WEBRTC_ANDROID)
// Suppress SIGPIPE. Without this, attempting to send on a socket whose // Suppress SIGPIPE. Without this, attempting to send on a socket whose
@@ -287,7 +285,9 @@ class PhysicalSocket : public AsyncSocket, public sigslot::has_slots<> {
return sent; return sent;
} }
int SendTo(const void* buffer, size_t length, const SocketAddress& addr) { int SendTo(const void* buffer,
size_t length,
const SocketAddress& addr) override {
sockaddr_storage saddr; sockaddr_storage saddr;
size_t len = addr.ToSockAddrStorage(&saddr); size_t len = addr.ToSockAddrStorage(&saddr);
int sent = ::sendto( int sent = ::sendto(
@@ -309,7 +309,7 @@ class PhysicalSocket : public AsyncSocket, public sigslot::has_slots<> {
return sent; return sent;
} }
int Recv(void* buffer, size_t length) { int Recv(void* buffer, size_t length) override {
int received = ::recv(s_, static_cast<char*>(buffer), int received = ::recv(s_, static_cast<char*>(buffer),
static_cast<int>(length), 0); static_cast<int>(length), 0);
if ((received == 0) && (length != 0)) { if ((received == 0) && (length != 0)) {
@@ -335,7 +335,7 @@ class PhysicalSocket : public AsyncSocket, public sigslot::has_slots<> {
return received; return received;
} }
int RecvFrom(void* buffer, size_t length, SocketAddress *out_addr) { int RecvFrom(void* buffer, size_t length, SocketAddress* out_addr) override {
sockaddr_storage addr_storage; sockaddr_storage addr_storage;
socklen_t addr_len = sizeof(addr_storage); socklen_t addr_len = sizeof(addr_storage);
sockaddr* addr = reinterpret_cast<sockaddr*>(&addr_storage); sockaddr* addr = reinterpret_cast<sockaddr*>(&addr_storage);
@@ -355,7 +355,7 @@ class PhysicalSocket : public AsyncSocket, public sigslot::has_slots<> {
return received; return received;
} }
int Listen(int backlog) { int Listen(int backlog) override {
int err = ::listen(s_, backlog); int err = ::listen(s_, backlog);
UpdateLastError(); UpdateLastError();
if (err == 0) { if (err == 0) {
@@ -369,7 +369,7 @@ class PhysicalSocket : public AsyncSocket, public sigslot::has_slots<> {
return err; return err;
} }
AsyncSocket* Accept(SocketAddress *out_addr) { AsyncSocket* Accept(SocketAddress* out_addr) override {
sockaddr_storage addr_storage; sockaddr_storage addr_storage;
socklen_t addr_len = sizeof(addr_storage); socklen_t addr_len = sizeof(addr_storage);
sockaddr* addr = reinterpret_cast<sockaddr*>(&addr_storage); sockaddr* addr = reinterpret_cast<sockaddr*>(&addr_storage);
@@ -383,7 +383,7 @@ class PhysicalSocket : public AsyncSocket, public sigslot::has_slots<> {
return ss_->WrapSocket(s); return ss_->WrapSocket(s);
} }
int Close() { int Close() override {
if (s_ == INVALID_SOCKET) if (s_ == INVALID_SOCKET)
return 0; return 0;
int err = ::closesocket(s_); int err = ::closesocket(s_);
@@ -398,7 +398,7 @@ class PhysicalSocket : public AsyncSocket, public sigslot::has_slots<> {
return err; return err;
} }
int EstimateMTU(uint16* mtu) { int EstimateMTU(uint16* mtu) override {
SocketAddress addr = GetRemoteAddress(); SocketAddress addr = GetRemoteAddress();
if (addr.IsAny()) { if (addr.IsAny()) {
SetError(ENOTCONN); SetError(ENOTCONN);
@@ -563,7 +563,7 @@ class EventDispatcher : public Dispatcher {
ss_->Add(this); ss_->Add(this);
} }
virtual ~EventDispatcher() { ~EventDispatcher() override {
ss_->Remove(this); ss_->Remove(this);
close(afd_[0]); close(afd_[0]);
close(afd_[1]); close(afd_[1]);
@@ -579,11 +579,9 @@ class EventDispatcher : public Dispatcher {
} }
} }
virtual uint32 GetRequestedEvents() { uint32 GetRequestedEvents() override { return DE_READ; }
return DE_READ;
}
virtual void OnPreEvent(uint32 ff) { void OnPreEvent(uint32 ff) override {
// It is not possible to perfectly emulate an auto-resetting event with // It is not possible to perfectly emulate an auto-resetting event with
// pipes. This simulates it by resetting before the event is handled. // pipes. This simulates it by resetting before the event is handled.
@@ -595,17 +593,11 @@ class EventDispatcher : public Dispatcher {
} }
} }
virtual void OnEvent(uint32 ff, int err) { void OnEvent(uint32 ff, int err) override { ASSERT(false); }
ASSERT(false);
}
virtual int GetDescriptor() { int GetDescriptor() override { return afd_[0]; }
return afd_[0];
}
virtual bool IsDescriptorClosed() { bool IsDescriptorClosed() override { return false; }
return false;
}
private: private:
PhysicalSocketServer *ss_; PhysicalSocketServer *ss_;
@@ -735,15 +727,13 @@ class PosixSignalDispatcher : public Dispatcher {
owner_->Add(this); owner_->Add(this);
} }
virtual ~PosixSignalDispatcher() { ~PosixSignalDispatcher() override {
owner_->Remove(this); owner_->Remove(this);
} }
virtual uint32 GetRequestedEvents() { uint32 GetRequestedEvents() override { return DE_READ; }
return DE_READ;
}
virtual void OnPreEvent(uint32 ff) { void OnPreEvent(uint32 ff) override {
// Events might get grouped if signals come very fast, so we read out up to // Events might get grouped if signals come very fast, so we read out up to
// 16 bytes to make sure we keep the pipe empty. // 16 bytes to make sure we keep the pipe empty.
uint8 b[16]; uint8 b[16];
@@ -755,7 +745,7 @@ class PosixSignalDispatcher : public Dispatcher {
} }
} }
virtual void OnEvent(uint32 ff, int err) { void OnEvent(uint32 ff, int err) override {
for (int signum = 0; signum < PosixSignalHandler::kNumPosixSignals; for (int signum = 0; signum < PosixSignalHandler::kNumPosixSignals;
++signum) { ++signum) {
if (PosixSignalHandler::Instance()->IsSignalSet(signum)) { if (PosixSignalHandler::Instance()->IsSignalSet(signum)) {
@@ -774,13 +764,11 @@ class PosixSignalDispatcher : public Dispatcher {
} }
} }
virtual int GetDescriptor() { int GetDescriptor() override {
return PosixSignalHandler::Instance()->GetDescriptor(); return PosixSignalHandler::Instance()->GetDescriptor();
} }
virtual bool IsDescriptorClosed() { bool IsDescriptorClosed() override { return false; }
return false;
}
void SetHandler(int signum, void (*handler)(int)) { void SetHandler(int signum, void (*handler)(int)) {
handlers_[signum] = handler; handlers_[signum] = handler;
@@ -809,7 +797,7 @@ class SocketDispatcher : public Dispatcher, public PhysicalSocket {
SocketDispatcher(SOCKET s, PhysicalSocketServer *ss) : PhysicalSocket(ss, s) { SocketDispatcher(SOCKET s, PhysicalSocketServer *ss) : PhysicalSocket(ss, s) {
} }
virtual ~SocketDispatcher() { ~SocketDispatcher() override {
Close(); Close();
} }
@@ -823,7 +811,7 @@ class SocketDispatcher : public Dispatcher, public PhysicalSocket {
return Create(AF_INET, type); return Create(AF_INET, type);
} }
virtual bool Create(int family, int type) { bool Create(int family, int type) override {
// Change the socket to be non-blocking. // Change the socket to be non-blocking.
if (!PhysicalSocket::Create(family, type)) if (!PhysicalSocket::Create(family, type))
return false; return false;
@@ -831,11 +819,9 @@ class SocketDispatcher : public Dispatcher, public PhysicalSocket {
return Initialize(); return Initialize();
} }
virtual int GetDescriptor() { int GetDescriptor() override { return s_; }
return s_;
}
virtual bool IsDescriptorClosed() { bool IsDescriptorClosed() override {
// We don't have a reliable way of distinguishing end-of-stream // We don't have a reliable way of distinguishing end-of-stream
// from readability. So test on each readable call. Is this // from readability. So test on each readable call. Is this
// inefficient? Probably. // inefficient? Probably.
@@ -870,18 +856,16 @@ class SocketDispatcher : public Dispatcher, public PhysicalSocket {
} }
} }
virtual uint32 GetRequestedEvents() { uint32 GetRequestedEvents() override { return enabled_events_; }
return enabled_events_;
}
virtual void OnPreEvent(uint32 ff) { void OnPreEvent(uint32 ff) override {
if ((ff & DE_CONNECT) != 0) if ((ff & DE_CONNECT) != 0)
state_ = CS_CONNECTED; state_ = CS_CONNECTED;
if ((ff & DE_CLOSE) != 0) if ((ff & DE_CLOSE) != 0)
state_ = CS_CLOSED; state_ = CS_CLOSED;
} }
virtual void OnEvent(uint32 ff, int err) { void OnEvent(uint32 ff, int err) override {
// Make sure we deliver connect/accept first. Otherwise, consumers may see // Make sure we deliver connect/accept first. Otherwise, consumers may see
// something like a READ followed by a CONNECT, which would be odd. // something like a READ followed by a CONNECT, which would be odd.
if ((ff & DE_CONNECT) != 0) { if ((ff & DE_CONNECT) != 0) {
@@ -907,7 +891,7 @@ class SocketDispatcher : public Dispatcher, public PhysicalSocket {
} }
} }
virtual int Close() { int Close() override {
if (s_ == INVALID_SOCKET) if (s_ == INVALID_SOCKET)
return 0; return 0;
@@ -926,28 +910,21 @@ class FileDispatcher: public Dispatcher, public AsyncFile {
fcntl(fd_, F_SETFL, fcntl(fd_, F_GETFL, 0) | O_NONBLOCK); fcntl(fd_, F_SETFL, fcntl(fd_, F_GETFL, 0) | O_NONBLOCK);
} }
virtual ~FileDispatcher() { ~FileDispatcher() override {
ss_->Remove(this); ss_->Remove(this);
} }
SocketServer* socketserver() { return ss_; } SocketServer* socketserver() { return ss_; }
virtual int GetDescriptor() { int GetDescriptor() override { return fd_; }
return fd_;
}
virtual bool IsDescriptorClosed() { bool IsDescriptorClosed() override { return false; }
return false;
}
virtual uint32 GetRequestedEvents() { uint32 GetRequestedEvents() override { return flags_; }
return flags_;
}
virtual void OnPreEvent(uint32 ff) { void OnPreEvent(uint32 ff) override {}
}
virtual void OnEvent(uint32 ff, int err) { void OnEvent(uint32 ff, int err) override {
if ((ff & DE_READ) != 0) if ((ff & DE_READ) != 0)
SignalReadEvent(this); SignalReadEvent(this);
if ((ff & DE_WRITE) != 0) if ((ff & DE_WRITE) != 0)
@@ -956,19 +933,15 @@ class FileDispatcher: public Dispatcher, public AsyncFile {
SignalCloseEvent(this, err); SignalCloseEvent(this, err);
} }
virtual bool readable() { bool readable() override { return (flags_ & DE_READ) != 0; }
return (flags_ & DE_READ) != 0;
}
virtual void set_readable(bool value) { void set_readable(bool value) override {
flags_ = value ? (flags_ | DE_READ) : (flags_ & ~DE_READ); flags_ = value ? (flags_ | DE_READ) : (flags_ & ~DE_READ);
} }
virtual bool writable() { bool writable() override { return (flags_ & DE_WRITE) != 0; }
return (flags_ & DE_WRITE) != 0;
}
virtual void set_writable(bool value) { void set_writable(bool value) override {
flags_ = value ? (flags_ | DE_WRITE) : (flags_ & ~DE_WRITE); flags_ = value ? (flags_ | DE_WRITE) : (flags_ & ~DE_WRITE);
} }
@@ -1179,9 +1152,9 @@ class Signaler : public EventDispatcher {
Signaler(PhysicalSocketServer* ss, bool* pf) Signaler(PhysicalSocketServer* ss, bool* pf)
: EventDispatcher(ss), pf_(pf) { : EventDispatcher(ss), pf_(pf) {
} }
virtual ~Signaler() { } ~Signaler() override { }
void OnEvent(uint32 ff, int err) { void OnEvent(uint32 ff, int err) override {
if (pf_) if (pf_)
*pf_ = false; *pf_ = false;
} }

View File

@@ -58,21 +58,21 @@ class Dispatcher {
class PhysicalSocketServer : public SocketServer { class PhysicalSocketServer : public SocketServer {
public: public:
PhysicalSocketServer(); PhysicalSocketServer();
virtual ~PhysicalSocketServer(); ~PhysicalSocketServer() override;
// SocketFactory: // SocketFactory:
virtual Socket* CreateSocket(int type); Socket* CreateSocket(int type) override;
virtual Socket* CreateSocket(int family, int type); Socket* CreateSocket(int family, int type) override;
virtual AsyncSocket* CreateAsyncSocket(int type); AsyncSocket* CreateAsyncSocket(int type) override;
virtual AsyncSocket* CreateAsyncSocket(int family, int type); AsyncSocket* CreateAsyncSocket(int family, int type) override;
// Internal Factory for Accept // Internal Factory for Accept
AsyncSocket* WrapSocket(SOCKET s); AsyncSocket* WrapSocket(SOCKET s);
// SocketServer: // SocketServer:
virtual bool Wait(int cms, bool process_io); bool Wait(int cms, bool process_io) override;
virtual void WakeUp(); void WakeUp() override;
void Add(Dispatcher* dispatcher); void Add(Dispatcher* dispatcher);
void Remove(Dispatcher* dispatcher); void Remove(Dispatcher* dispatcher);

View File

@@ -86,11 +86,16 @@ double ProfilerEvent::standard_deviation() const {
return sqrt(sum_of_squared_differences_ / (event_count_ - 1.0)); return sqrt(sum_of_squared_differences_ / (event_count_ - 1.0));
} }
Profiler::~Profiler() = default;
Profiler* Profiler::Instance() { Profiler* Profiler::Instance() {
LIBJINGLE_DEFINE_STATIC_LOCAL(Profiler, instance, ()); LIBJINGLE_DEFINE_STATIC_LOCAL(Profiler, instance, ());
return &instance; return &instance;
} }
Profiler::Profiler() {
}
void Profiler::StartEvent(const std::string& event_name) { void Profiler::StartEvent(const std::string& event_name) {
lock_.LockShared(); lock_.LockShared();
EventMap::iterator it = events_.find(event_name); EventMap::iterator it = events_.find(event_name);

View File

@@ -115,6 +115,7 @@ class ProfilerEvent {
// macros, defined above, rather than directly calling Profiler methods. // macros, defined above, rather than directly calling Profiler methods.
class Profiler { class Profiler {
public: public:
~Profiler();
void StartEvent(const std::string& event_name); void StartEvent(const std::string& event_name);
void StopEvent(const std::string& event_name); void StopEvent(const std::string& event_name);
void ReportToLog(const char* file, int line, LoggingSeverity severity_to_use, void ReportToLog(const char* file, int line, LoggingSeverity severity_to_use,
@@ -127,7 +128,7 @@ class Profiler {
static Profiler* Instance(); static Profiler* Instance();
private: private:
Profiler() {} Profiler();
typedef std::map<std::string, ProfilerEvent> EventMap; typedef std::map<std::string, ProfilerEvent> EventMap;
EventMap events_; EventMap events_;

View File

@@ -17,4 +17,8 @@ const char * ProxyToString(ProxyType proxy) {
return PROXY_NAMES[proxy]; return PROXY_NAMES[proxy];
} }
ProxyInfo::ProxyInfo() : type(PROXY_NONE), autodetect(false) {
}
ProxyInfo::~ProxyInfo() = default;
} // namespace rtc } // namespace rtc

View File

@@ -34,7 +34,8 @@ struct ProxyInfo {
std::string username; std::string username;
CryptString password; CryptString password;
ProxyInfo() : type(PROXY_NONE), autodetect(false) { } ProxyInfo();
~ProxyInfo();
}; };
} // namespace rtc } // namespace rtc

View File

@@ -74,6 +74,8 @@ ProxyBinding::ProxyBinding(AsyncProxyServerSocket* int_socket,
ext_socket_->SignalCloseEvent.connect(this, &ProxyBinding::OnExternalClose); ext_socket_->SignalCloseEvent.connect(this, &ProxyBinding::OnExternalClose);
} }
ProxyBinding::~ProxyBinding() = default;
void ProxyBinding::OnConnectRequest(AsyncProxyServerSocket* socket, void ProxyBinding::OnConnectRequest(AsyncProxyServerSocket* socket,
const SocketAddress& addr) { const SocketAddress& addr) {
ASSERT(!connected_ && ext_socket_.get() != NULL); ASSERT(!connected_ && ext_socket_.get() != NULL);
@@ -141,4 +143,8 @@ void ProxyBinding::Destroy() {
SignalDestroyed(this); SignalDestroyed(this);
} }
AsyncProxyServerSocket* SocksProxyServer::WrapSocket(AsyncSocket* socket) {
return new AsyncSocksProxyServerSocket(socket);
}
} // namespace rtc } // namespace rtc

View File

@@ -31,6 +31,7 @@ class SocketFactory;
class ProxyBinding : public sigslot::has_slots<> { class ProxyBinding : public sigslot::has_slots<> {
public: public:
ProxyBinding(AsyncProxyServerSocket* in_socket, AsyncSocket* out_socket); ProxyBinding(AsyncProxyServerSocket* in_socket, AsyncSocket* out_socket);
~ProxyBinding() override;
sigslot::signal1<ProxyBinding*> SignalDestroyed; sigslot::signal1<ProxyBinding*> SignalDestroyed;
private: private:
@@ -61,7 +62,7 @@ class ProxyServer : public sigslot::has_slots<> {
public: public:
ProxyServer(SocketFactory* int_factory, const SocketAddress& int_addr, ProxyServer(SocketFactory* int_factory, const SocketAddress& int_addr,
SocketFactory* ext_factory, const SocketAddress& ext_ip); SocketFactory* ext_factory, const SocketAddress& ext_ip);
virtual ~ProxyServer(); ~ProxyServer() override;
protected: protected:
void OnAcceptEvent(AsyncSocket* socket); void OnAcceptEvent(AsyncSocket* socket);
@@ -85,9 +86,7 @@ class SocksProxyServer : public ProxyServer {
: ProxyServer(int_factory, int_addr, ext_factory, ext_ip) { : ProxyServer(int_factory, int_addr, ext_factory, ext_ip) {
} }
protected: protected:
AsyncProxyServerSocket* WrapSocket(AsyncSocket* socket) { AsyncProxyServerSocket* WrapSocket(AsyncSocket* socket) override;
return new AsyncSocksProxyServerSocket(socket);
}
DISALLOW_EVIL_CONSTRUCTORS(SocksProxyServer); DISALLOW_EVIL_CONSTRUCTORS(SocksProxyServer);
}; };

32
webrtc/base/sha1digest.cc Normal file
View File

@@ -0,0 +1,32 @@
/*
* Copyright 2015 The WebRTC Project Authors. All rights reserved.
*
* Use of this source code is governed by a BSD-style license
* that can be found in the LICENSE file in the root of the source
* tree. An additional intellectual property rights grant can be found
* in the file PATENTS. All contributing project authors may
* be found in the AUTHORS file in the root of the source tree.
*/
#include "webrtc/base/sha1digest.h"
namespace rtc {
size_t Sha1Digest::Size() const {
return kSize;
}
void Sha1Digest::Update(const void* buf, size_t len) {
SHA1Update(&ctx_, static_cast<const uint8*>(buf), len);
}
size_t Sha1Digest::Finish(void* buf, size_t len) {
if (len < kSize) {
return 0;
}
SHA1Final(&ctx_, static_cast<uint8*>(buf));
SHA1Init(&ctx_); // Reset for next use.
return kSize;
}
} // namespace rtc

View File

@@ -23,20 +23,9 @@ class Sha1Digest : public MessageDigest {
Sha1Digest() { Sha1Digest() {
SHA1Init(&ctx_); SHA1Init(&ctx_);
} }
virtual size_t Size() const { size_t Size() const override;
return kSize; void Update(const void* buf, size_t len) override;
} size_t Finish(void* buf, size_t len) override;
virtual void Update(const void* buf, size_t len) {
SHA1Update(&ctx_, static_cast<const uint8*>(buf), len);
}
virtual size_t Finish(void* buf, size_t len) {
if (len < kSize) {
return 0;
}
SHA1Final(&ctx_, static_cast<uint8*>(buf));
SHA1Init(&ctx_); // Reset for next use.
return kSize;
}
private: private:
SHA1_CTX ctx_; SHA1_CTX ctx_;

View File

@@ -131,6 +131,14 @@ void SignalThread::OnMessage(Message *msg) {
} }
} }
SignalThread::Worker::~Worker() {
Stop();
}
void SignalThread::Worker::Run() {
parent_->Run();
}
void SignalThread::Run() { void SignalThread::Run() {
DoWork(); DoWork();
{ {

View File

@@ -69,7 +69,7 @@ class SignalThread
enum { ST_MSG_WORKER_DONE, ST_MSG_FIRST_AVAILABLE }; enum { ST_MSG_WORKER_DONE, ST_MSG_FIRST_AVAILABLE };
protected: protected:
virtual ~SignalThread(); ~SignalThread() override;
Thread* worker() { return &worker_; } Thread* worker() { return &worker_; }
@@ -92,7 +92,7 @@ class SignalThread
// Context: Any Thread. If subclass overrides, be sure to call the base // Context: Any Thread. If subclass overrides, be sure to call the base
// implementation. Do not use (message_id < ST_MSG_FIRST_AVAILABLE) // implementation. Do not use (message_id < ST_MSG_FIRST_AVAILABLE)
virtual void OnMessage(Message *msg); void OnMessage(Message* msg) override;
private: private:
enum State { enum State {
@@ -106,8 +106,8 @@ class SignalThread
class Worker : public Thread { class Worker : public Thread {
public: public:
explicit Worker(SignalThread* parent) : parent_(parent) {} explicit Worker(SignalThread* parent) : parent_(parent) {}
virtual ~Worker() { Stop(); } ~Worker() override;
virtual void Run() { parent_->Run(); } void Run() override;
private: private:
SignalThread* parent_; SignalThread* parent_;

54
webrtc/base/sigslot.cc Normal file
View File

@@ -0,0 +1,54 @@
// sigslot.h: Signal/Slot classes
//
// Written by Sarah Thompson (sarah@telergy.com) 2002.
//
// License: Public domain. You are free to use this code however you like, with
// the proviso that the author takes on no responsibility or liability for any
// use.
#include "webrtc/base/sigslot.h"
namespace sigslot {
#ifdef _SIGSLOT_HAS_POSIX_THREADS
multi_threaded_global::multi_threaded_global() {
pthread_mutex_init(get_mutex(), NULL);
}
multi_threaded_global::multi_threaded_global(const multi_threaded_global&) {
}
multi_threaded_global::~multi_threaded_global() = default;
void multi_threaded_global::lock() {
pthread_mutex_lock(get_mutex());
}
void multi_threaded_global::unlock() {
pthread_mutex_unlock(get_mutex());
}
multi_threaded_local::multi_threaded_local() {
pthread_mutex_init(&m_mutex, NULL);
}
multi_threaded_local::multi_threaded_local(const multi_threaded_local&) {
pthread_mutex_init(&m_mutex, NULL);
}
multi_threaded_local::~multi_threaded_local() {
pthread_mutex_destroy(&m_mutex);
}
void multi_threaded_local::lock() {
pthread_mutex_lock(&m_mutex);
}
void multi_threaded_local::unlock() {
pthread_mutex_unlock(&m_mutex);
}
#endif // _SIGSLOT_HAS_POSIX_THREADS
}; // namespace sigslot

View File

@@ -128,20 +128,11 @@ namespace sigslot {
; ;
} }
virtual ~single_threaded() virtual ~single_threaded() {}
{
;
}
virtual void lock() virtual void lock() {}
{
;
}
virtual void unlock() virtual void unlock() {}
{
;
}
}; };
#ifdef _SIGSLOT_HAS_WIN32_THREADS #ifdef _SIGSLOT_HAS_WIN32_THREADS
@@ -226,30 +217,11 @@ namespace sigslot {
class multi_threaded_global class multi_threaded_global
{ {
public: public:
multi_threaded_global() multi_threaded_global();
{ multi_threaded_global(const multi_threaded_global&);
pthread_mutex_init(get_mutex(), NULL); virtual ~multi_threaded_global();
} virtual void lock();
virtual void unlock();
multi_threaded_global(const multi_threaded_global&)
{
;
}
virtual ~multi_threaded_global()
{
;
}
virtual void lock()
{
pthread_mutex_lock(get_mutex());
}
virtual void unlock()
{
pthread_mutex_unlock(get_mutex());
}
private: private:
pthread_mutex_t* get_mutex() pthread_mutex_t* get_mutex()
@@ -262,30 +234,11 @@ namespace sigslot {
class multi_threaded_local class multi_threaded_local
{ {
public: public:
multi_threaded_local() multi_threaded_local();
{ multi_threaded_local(const multi_threaded_local&);
pthread_mutex_init(&m_mutex, NULL); virtual ~multi_threaded_local();
} virtual void lock();
virtual void unlock();
multi_threaded_local(const multi_threaded_local&)
{
pthread_mutex_init(&m_mutex, NULL);
}
virtual ~multi_threaded_local()
{
pthread_mutex_destroy(&m_mutex);
}
virtual void lock()
{
pthread_mutex_lock(&m_mutex);
}
virtual void unlock()
{
pthread_mutex_unlock(&m_mutex);
}
private: private:
pthread_mutex_t m_mutex; pthread_mutex_t m_mutex;

View File

@@ -117,6 +117,13 @@ void BufferedReadAdapter::OnReadEvent(AsyncSocket * socket) {
ProcessInput(buffer_, &data_len_); ProcessInput(buffer_, &data_len_);
} }
AsyncProxyServerSocket::AsyncProxyServerSocket(AsyncSocket* socket,
size_t buffer_size)
: BufferedReadAdapter(socket, buffer_size) {
}
AsyncProxyServerSocket::~AsyncProxyServerSocket() = default;
/////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////
// This is a SSL v2 CLIENT_HELLO message. // This is a SSL v2 CLIENT_HELLO message.
@@ -507,6 +514,8 @@ AsyncSocksProxySocket::AsyncSocksProxySocket(AsyncSocket* socket,
user_(username), pass_(password) { user_(username), pass_(password) {
} }
AsyncSocksProxySocket::~AsyncSocksProxySocket() = default;
int AsyncSocksProxySocket::Connect(const SocketAddress& addr) { int AsyncSocksProxySocket::Connect(const SocketAddress& addr) {
int ret; int ret;
dest_ = addr; dest_ = addr;

View File

@@ -31,10 +31,10 @@ class ByteBuffer;
class BufferedReadAdapter : public AsyncSocketAdapter { class BufferedReadAdapter : public AsyncSocketAdapter {
public: public:
BufferedReadAdapter(AsyncSocket* socket, size_t buffer_size); BufferedReadAdapter(AsyncSocket* socket, size_t buffer_size);
virtual ~BufferedReadAdapter(); ~BufferedReadAdapter() override;
virtual int Send(const void* pv, size_t cb); int Send(const void* pv, size_t cb) override;
virtual int Recv(void* pv, size_t cb); int Recv(void* pv, size_t cb) override;
protected: protected:
int DirectSend(const void* pv, size_t cb) { int DirectSend(const void* pv, size_t cb) {
@@ -44,7 +44,7 @@ class BufferedReadAdapter : public AsyncSocketAdapter {
void BufferInput(bool on = true); void BufferInput(bool on = true);
virtual void ProcessInput(char* data, size_t* len) = 0; virtual void ProcessInput(char* data, size_t* len) = 0;
virtual void OnReadEvent(AsyncSocket * socket); void OnReadEvent(AsyncSocket* socket) override;
private: private:
char * buffer_; char * buffer_;
@@ -58,8 +58,8 @@ class BufferedReadAdapter : public AsyncSocketAdapter {
// Interface for implementing proxy server sockets. // Interface for implementing proxy server sockets.
class AsyncProxyServerSocket : public BufferedReadAdapter { class AsyncProxyServerSocket : public BufferedReadAdapter {
public: public:
AsyncProxyServerSocket(AsyncSocket* socket, size_t buffer_size) AsyncProxyServerSocket(AsyncSocket* socket, size_t buffer_size);
: BufferedReadAdapter(socket, buffer_size) {} ~AsyncProxyServerSocket() override;
sigslot::signal2<AsyncProxyServerSocket*, sigslot::signal2<AsyncProxyServerSocket*,
const SocketAddress&> SignalConnectRequest; const SocketAddress&> SignalConnectRequest;
virtual void SendConnectResult(int err, const SocketAddress& addr) = 0; virtual void SendConnectResult(int err, const SocketAddress& addr) = 0;
@@ -73,11 +73,11 @@ class AsyncSSLSocket : public BufferedReadAdapter {
public: public:
explicit AsyncSSLSocket(AsyncSocket* socket); explicit AsyncSSLSocket(AsyncSocket* socket);
virtual int Connect(const SocketAddress& addr); int Connect(const SocketAddress& addr) override;
protected: protected:
virtual void OnConnectEvent(AsyncSocket* socket); void OnConnectEvent(AsyncSocket* socket) override;
virtual void ProcessInput(char* data, size_t* len); void ProcessInput(char* data, size_t* len) override;
DISALLOW_EVIL_CONSTRUCTORS(AsyncSSLSocket); DISALLOW_EVIL_CONSTRUCTORS(AsyncSSLSocket);
}; };
@@ -88,7 +88,7 @@ class AsyncSSLServerSocket : public BufferedReadAdapter {
explicit AsyncSSLServerSocket(AsyncSocket* socket); explicit AsyncSSLServerSocket(AsyncSocket* socket);
protected: protected:
virtual void ProcessInput(char* data, size_t* len); void ProcessInput(char* data, size_t* len) override;
DISALLOW_EVIL_CONSTRUCTORS(AsyncSSLServerSocket); DISALLOW_EVIL_CONSTRUCTORS(AsyncSSLServerSocket);
}; };
@@ -100,22 +100,22 @@ class AsyncHttpsProxySocket : public BufferedReadAdapter {
AsyncHttpsProxySocket(AsyncSocket* socket, const std::string& user_agent, AsyncHttpsProxySocket(AsyncSocket* socket, const std::string& user_agent,
const SocketAddress& proxy, const SocketAddress& proxy,
const std::string& username, const CryptString& password); const std::string& username, const CryptString& password);
virtual ~AsyncHttpsProxySocket(); ~AsyncHttpsProxySocket() override;
// If connect is forced, the adapter will always issue an HTTP CONNECT to the // If connect is forced, the adapter will always issue an HTTP CONNECT to the
// target address. Otherwise, it will connect only if the destination port // target address. Otherwise, it will connect only if the destination port
// is not port 80. // is not port 80.
void SetForceConnect(bool force) { force_connect_ = force; } void SetForceConnect(bool force) { force_connect_ = force; }
virtual int Connect(const SocketAddress& addr); int Connect(const SocketAddress& addr) override;
virtual SocketAddress GetRemoteAddress() const; SocketAddress GetRemoteAddress() const override;
virtual int Close(); int Close() override;
virtual ConnState GetState() const; ConnState GetState() const override;
protected: protected:
virtual void OnConnectEvent(AsyncSocket* socket); void OnConnectEvent(AsyncSocket* socket) override;
virtual void OnCloseEvent(AsyncSocket* socket, int err); void OnCloseEvent(AsyncSocket* socket, int err) override;
virtual void ProcessInput(char* data, size_t* len); void ProcessInput(char* data, size_t* len) override;
bool ShouldIssueConnect() const; bool ShouldIssueConnect() const;
void SendRequest(); void SendRequest();
@@ -159,15 +159,16 @@ class AsyncSocksProxySocket : public BufferedReadAdapter {
public: public:
AsyncSocksProxySocket(AsyncSocket* socket, const SocketAddress& proxy, AsyncSocksProxySocket(AsyncSocket* socket, const SocketAddress& proxy,
const std::string& username, const CryptString& password); const std::string& username, const CryptString& password);
~AsyncSocksProxySocket() override;
virtual int Connect(const SocketAddress& addr); int Connect(const SocketAddress& addr) override;
virtual SocketAddress GetRemoteAddress() const; SocketAddress GetRemoteAddress() const override;
virtual int Close(); int Close() override;
virtual ConnState GetState() const; ConnState GetState() const override;
protected: protected:
virtual void OnConnectEvent(AsyncSocket* socket); void OnConnectEvent(AsyncSocket* socket) override;
virtual void ProcessInput(char* data, size_t* len); void ProcessInput(char* data, size_t* len) override;
void SendHello(); void SendHello();
void SendConnect(); void SendConnect();
@@ -191,7 +192,7 @@ class AsyncSocksProxyServerSocket : public AsyncProxyServerSocket {
explicit AsyncSocksProxyServerSocket(AsyncSocket* socket); explicit AsyncSocksProxyServerSocket(AsyncSocket* socket);
private: private:
virtual void ProcessInput(char* data, size_t* len); void ProcessInput(char* data, size_t* len) override;
void DirectSend(const ByteBuffer& buf); void DirectSend(const ByteBuffer& buf);
void HandleHello(ByteBuffer* request); void HandleHello(ByteBuffer* request);
@@ -199,7 +200,7 @@ class AsyncSocksProxyServerSocket : public AsyncProxyServerSocket {
void HandleAuth(ByteBuffer* request); void HandleAuth(ByteBuffer* request);
void SendAuthReply(uint8 result); void SendAuthReply(uint8 result);
void HandleConnect(ByteBuffer* request); void HandleConnect(ByteBuffer* request);
virtual void SendConnectResult(int result, const SocketAddress& addr); void SendConnectResult(int result, const SocketAddress& addr) override;
void Error(int error); void Error(int error);
@@ -219,15 +220,15 @@ class LoggingSocketAdapter : public AsyncSocketAdapter {
LoggingSocketAdapter(AsyncSocket* socket, LoggingSeverity level, LoggingSocketAdapter(AsyncSocket* socket, LoggingSeverity level,
const char * label, bool hex_mode = false); const char * label, bool hex_mode = false);
virtual int Send(const void *pv, size_t cb); int Send(const void* pv, size_t cb) override;
virtual int SendTo(const void *pv, size_t cb, const SocketAddress& addr); int SendTo(const void* pv, size_t cb, const SocketAddress& addr) override;
virtual int Recv(void *pv, size_t cb); int Recv(void* pv, size_t cb) override;
virtual int RecvFrom(void *pv, size_t cb, SocketAddress *paddr); int RecvFrom(void* pv, size_t cb, SocketAddress* paddr) override;
virtual int Close(); int Close() override;
protected: protected:
virtual void OnConnectEvent(AsyncSocket * socket); void OnConnectEvent(AsyncSocket* socket) override;
virtual void OnCloseEvent(AsyncSocket * socket, int err); void OnCloseEvent(AsyncSocket* socket, int err) override;
private: private:
LoggingSeverity level_; LoggingSeverity level_;

View File

@@ -46,12 +46,12 @@ public:
class StreamCache : public StreamPool, public sigslot::has_slots<> { class StreamCache : public StreamPool, public sigslot::has_slots<> {
public: public:
StreamCache(StreamPool* pool); StreamCache(StreamPool* pool);
virtual ~StreamCache(); ~StreamCache() override;
// StreamPool Interface // StreamPool Interface
virtual StreamInterface* RequestConnectedStream(const SocketAddress& remote, StreamInterface* RequestConnectedStream(const SocketAddress& remote,
int* err); int* err) override;
virtual void ReturnConnectedStream(StreamInterface* stream); void ReturnConnectedStream(StreamInterface* stream) override;
private: private:
typedef std::pair<SocketAddress, StreamInterface*> ConnectedStream; typedef std::pair<SocketAddress, StreamInterface*> ConnectedStream;
@@ -75,12 +75,12 @@ private:
class NewSocketPool : public StreamPool { class NewSocketPool : public StreamPool {
public: public:
NewSocketPool(SocketFactory* factory); NewSocketPool(SocketFactory* factory);
virtual ~NewSocketPool(); ~NewSocketPool() override;
// StreamPool Interface // StreamPool Interface
virtual StreamInterface* RequestConnectedStream(const SocketAddress& remote, StreamInterface* RequestConnectedStream(const SocketAddress& remote,
int* err); int* err) override;
virtual void ReturnConnectedStream(StreamInterface* stream); void ReturnConnectedStream(StreamInterface* stream) override;
private: private:
SocketFactory* factory_; SocketFactory* factory_;
@@ -95,12 +95,12 @@ private:
class ReuseSocketPool : public StreamPool, public sigslot::has_slots<> { class ReuseSocketPool : public StreamPool, public sigslot::has_slots<> {
public: public:
ReuseSocketPool(SocketFactory* factory); ReuseSocketPool(SocketFactory* factory);
virtual ~ReuseSocketPool(); ~ReuseSocketPool() override;
// StreamPool Interface // StreamPool Interface
virtual StreamInterface* RequestConnectedStream(const SocketAddress& remote, StreamInterface* RequestConnectedStream(const SocketAddress& remote,
int* err); int* err) override;
virtual void ReturnConnectedStream(StreamInterface* stream); void ReturnConnectedStream(StreamInterface* stream) override;
private: private:
void OnStreamEvent(StreamInterface* stream, int events, int err); void OnStreamEvent(StreamInterface* stream, int events, int err);
@@ -120,12 +120,12 @@ class LoggingPoolAdapter : public StreamPool {
public: public:
LoggingPoolAdapter(StreamPool* pool, LoggingSeverity level, LoggingPoolAdapter(StreamPool* pool, LoggingSeverity level,
const std::string& label, bool binary_mode); const std::string& label, bool binary_mode);
virtual ~LoggingPoolAdapter(); ~LoggingPoolAdapter() override;
// StreamPool Interface // StreamPool Interface
virtual StreamInterface* RequestConnectedStream(const SocketAddress& remote, StreamInterface* RequestConnectedStream(const SocketAddress& remote,
int* err); int* err) override;
virtual void ReturnConnectedStream(StreamInterface* stream); void ReturnConnectedStream(StreamInterface* stream) override;
private: private:
StreamPool* pool_; StreamPool* pool_;

View File

@@ -22,22 +22,26 @@ namespace rtc {
class SocketStream : public StreamInterface, public sigslot::has_slots<> { class SocketStream : public StreamInterface, public sigslot::has_slots<> {
public: public:
explicit SocketStream(AsyncSocket* socket); explicit SocketStream(AsyncSocket* socket);
virtual ~SocketStream(); ~SocketStream() override;
void Attach(AsyncSocket* socket); void Attach(AsyncSocket* socket);
AsyncSocket* Detach(); AsyncSocket* Detach();
AsyncSocket* GetSocket() { return socket_; } AsyncSocket* GetSocket() { return socket_; }
virtual StreamState GetState() const; StreamState GetState() const override;
virtual StreamResult Read(void* buffer, size_t buffer_len, StreamResult Read(void* buffer,
size_t* read, int* error); size_t buffer_len,
size_t* read,
int* error) override;
virtual StreamResult Write(const void* data, size_t data_len, StreamResult Write(const void* data,
size_t* written, int* error); size_t data_len,
size_t* written,
int* error) override;
virtual void Close(); void Close() override;
private: private:
void OnConnectEvent(AsyncSocket* socket); void OnConnectEvent(AsyncSocket* socket);

View File

@@ -88,6 +88,20 @@ std::string SSLIdentity::DerToPem(const std::string& pem_type,
return result.str(); return result.str();
} }
SSLCertChain::SSLCertChain(const std::vector<SSLCertificate*>& certs) {
ASSERT(!certs.empty());
certs_.resize(certs.size());
std::transform(certs.begin(), certs.end(), certs_.begin(), DupCert);
}
SSLCertChain::SSLCertChain(const SSLCertificate* cert) {
certs_.push_back(cert->GetReference());
}
SSLCertChain::~SSLCertChain() {
std::for_each(certs_.begin(), certs_.end(), DeleteCert);
}
#if SSL_USE_SCHANNEL #if SSL_USE_SCHANNEL
SSLCertificate* SSLCertificate::FromPEMString(const std::string& pem_string) { SSLCertificate* SSLCertificate::FromPEMString(const std::string& pem_string) {

View File

@@ -77,18 +77,9 @@ class SSLCertChain {
public: public:
// These constructors copy the provided SSLCertificate(s), so the caller // These constructors copy the provided SSLCertificate(s), so the caller
// retains ownership. // retains ownership.
explicit SSLCertChain(const std::vector<SSLCertificate*>& certs) { explicit SSLCertChain(const std::vector<SSLCertificate*>& certs);
ASSERT(!certs.empty()); explicit SSLCertChain(const SSLCertificate* cert);
certs_.resize(certs.size()); ~SSLCertChain();
std::transform(certs.begin(), certs.end(), certs_.begin(), DupCert);
}
explicit SSLCertChain(const SSLCertificate* cert) {
certs_.push_back(cert->GetReference());
}
~SSLCertChain() {
std::for_each(certs_.begin(), certs_.end(), DeleteCert);
}
// Vector access methods. // Vector access methods.
size_t GetSize() const { return certs_.size(); } size_t GetSize() const { return certs_.size(); }

View File

@@ -31,11 +31,11 @@ class ProxySocketAdapter : public AsyncSocketAdapter {
: AsyncSocketAdapter(NULL), factory_(factory), family_(family), : AsyncSocketAdapter(NULL), factory_(factory), family_(family),
type_(type), detect_(NULL) { type_(type), detect_(NULL) {
} }
virtual ~ProxySocketAdapter() { ~ProxySocketAdapter() override {
Close(); Close();
} }
virtual int Connect(const SocketAddress& addr) { int Connect(const SocketAddress& addr) override {
ASSERT(NULL == detect_); ASSERT(NULL == detect_);
ASSERT(NULL == socket_); ASSERT(NULL == socket_);
remote_ = addr; remote_ = addr;
@@ -51,13 +51,13 @@ class ProxySocketAdapter : public AsyncSocketAdapter {
detect_->Start(); detect_->Start();
return SOCKET_ERROR; return SOCKET_ERROR;
} }
virtual int GetError() const { int GetError() const override {
if (socket_) { if (socket_) {
return socket_->GetError(); return socket_->GetError();
} }
return detect_ ? EWOULDBLOCK : EADDRNOTAVAIL; return detect_ ? EWOULDBLOCK : EADDRNOTAVAIL;
} }
virtual int Close() { int Close() override {
if (socket_) { if (socket_) {
return socket_->Close(); return socket_->Close();
} }
@@ -67,7 +67,7 @@ class ProxySocketAdapter : public AsyncSocketAdapter {
} }
return 0; return 0;
} }
virtual ConnState GetState() const { ConnState GetState() const override {
if (socket_) { if (socket_) {
return socket_->GetState(); return socket_->GetState();
} }
@@ -99,6 +99,19 @@ private:
// SslSocketFactory // SslSocketFactory
/////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////
SslSocketFactory::SslSocketFactory(SocketFactory* factory,
const std::string& user_agent)
: factory_(factory),
agent_(user_agent),
autodetect_proxy_(true),
force_connect_(false),
logging_level_(LS_VERBOSE),
binary_mode_(false),
ignore_bad_cert_(false) {
}
SslSocketFactory::~SslSocketFactory() = default;
Socket* SslSocketFactory::CreateSocket(int type) { Socket* SslSocketFactory::CreateSocket(int type) {
return CreateSocket(AF_INET, type); return CreateSocket(AF_INET, type);
} }

View File

@@ -22,11 +22,8 @@ namespace rtc {
class SslSocketFactory : public SocketFactory { class SslSocketFactory : public SocketFactory {
public: public:
SslSocketFactory(SocketFactory* factory, const std::string& user_agent) SslSocketFactory(SocketFactory* factory, const std::string& user_agent);
: factory_(factory), agent_(user_agent), autodetect_proxy_(true), ~SslSocketFactory() override;
force_connect_(false), logging_level_(LS_VERBOSE), binary_mode_(false),
ignore_bad_cert_(false) {
}
void SetAutoDetectProxy() { void SetAutoDetectProxy() {
autodetect_proxy_ = true; autodetect_proxy_ = true;
@@ -54,11 +51,11 @@ class SslSocketFactory : public SocketFactory {
} }
// SocketFactory Interface // SocketFactory Interface
virtual Socket* CreateSocket(int type); Socket* CreateSocket(int type) override;
virtual Socket* CreateSocket(int family, int type); Socket* CreateSocket(int family, int type) override;
virtual AsyncSocket* CreateAsyncSocket(int type); AsyncSocket* CreateAsyncSocket(int type) override;
virtual AsyncSocket* CreateAsyncSocket(int family, int type); AsyncSocket* CreateAsyncSocket(int family, int type) override;
private: private:
friend class ProxySocketAdapter; friend class ProxySocketAdapter;

View File

@@ -45,6 +45,28 @@ SSLStreamAdapter* SSLStreamAdapter::Create(StreamInterface* stream) {
#endif #endif
} }
bool SSLStreamAdapter::GetSslCipher(std::string* cipher) {
return false;
}
bool SSLStreamAdapter::ExportKeyingMaterial(const std::string& label,
const uint8* context,
size_t context_len,
bool use_context,
uint8* result,
size_t result_len) {
return false; // Default is unsupported
}
bool SSLStreamAdapter::SetDtlsSrtpCiphers(
const std::vector<std::string>& ciphers) {
return false;
}
bool SSLStreamAdapter::GetDtlsSrtpCipher(std::string* cipher) {
return false;
}
// Note: this matches the logic above with SCHANNEL dominating // Note: this matches the logic above with SCHANNEL dominating
#if SSL_USE_SCHANNEL #if SSL_USE_SCHANNEL
bool SSLStreamAdapter::HaveDtls() { return false; } bool SSLStreamAdapter::HaveDtls() { return false; }

View File

@@ -121,9 +121,7 @@ class SSLStreamAdapter : public StreamAdapterInterface {
// Retrieves the name of the cipher suite used for the connection // Retrieves the name of the cipher suite used for the connection
// (e.g. "TLS_RSA_WITH_AES_128_CBC_SHA"). // (e.g. "TLS_RSA_WITH_AES_128_CBC_SHA").
virtual bool GetSslCipher(std::string* cipher) { virtual bool GetSslCipher(std::string* cipher);
return false;
}
// Key Exporter interface from RFC 5705 // Key Exporter interface from RFC 5705
// Arguments are: // Arguments are:
@@ -142,19 +140,11 @@ class SSLStreamAdapter : public StreamAdapterInterface {
size_t context_len, size_t context_len,
bool use_context, bool use_context,
uint8* result, uint8* result,
size_t result_len) { size_t result_len);
return false; // Default is unsupported
}
// DTLS-SRTP interface // DTLS-SRTP interface
virtual bool SetDtlsSrtpCiphers(const std::vector<std::string>& ciphers) { virtual bool SetDtlsSrtpCiphers(const std::vector<std::string>& ciphers);
return false; virtual bool GetDtlsSrtpCipher(std::string* cipher);
}
virtual bool GetDtlsSrtpCipher(std::string* cipher) {
return false;
}
// Capabilities testing // Capabilities testing
static bool HaveDtls(); static bool HaveDtls();

View File

@@ -23,6 +23,16 @@
namespace rtc { namespace rtc {
SSLStreamAdapterHelper::SSLStreamAdapterHelper(StreamInterface* stream)
: SSLStreamAdapter(stream),
state_(SSL_NONE),
role_(SSL_CLIENT),
ssl_error_code_(0), // Not meaningful yet
ssl_mode_(SSL_MODE_TLS) {
}
SSLStreamAdapterHelper::~SSLStreamAdapterHelper() = default;
void SSLStreamAdapterHelper::SetIdentity(SSLIdentity* identity) { void SSLStreamAdapterHelper::SetIdentity(SSLIdentity* identity) {
ASSERT(identity_.get() == NULL); ASSERT(identity_.get() == NULL);
identity_.reset(identity); identity_.reset(identity);

View File

@@ -26,28 +26,23 @@ namespace rtc {
// (NSS and OpenSSL) // (NSS and OpenSSL)
class SSLStreamAdapterHelper : public SSLStreamAdapter { class SSLStreamAdapterHelper : public SSLStreamAdapter {
public: public:
explicit SSLStreamAdapterHelper(StreamInterface* stream) explicit SSLStreamAdapterHelper(StreamInterface* stream);
: SSLStreamAdapter(stream), ~SSLStreamAdapterHelper() override;
state_(SSL_NONE),
role_(SSL_CLIENT),
ssl_error_code_(0), // Not meaningful yet
ssl_mode_(SSL_MODE_TLS) {}
// Overrides of SSLStreamAdapter // Overrides of SSLStreamAdapter
virtual void SetIdentity(SSLIdentity* identity); void SetIdentity(SSLIdentity* identity) override;
virtual void SetServerRole(SSLRole role = SSL_SERVER); void SetServerRole(SSLRole role = SSL_SERVER) override;
virtual void SetMode(SSLMode mode); void SetMode(SSLMode mode) override;
virtual int StartSSLWithServer(const char* server_name); int StartSSLWithServer(const char* server_name) override;
virtual int StartSSLWithPeer(); int StartSSLWithPeer() override;
virtual bool SetPeerCertificateDigest(const std::string& digest_alg, bool SetPeerCertificateDigest(const std::string& digest_alg,
const unsigned char* digest_val, const unsigned char* digest_val,
size_t digest_len); size_t digest_len) override;
virtual bool GetPeerCertificate(SSLCertificate** cert) const; bool GetPeerCertificate(SSLCertificate** cert) const override;
virtual StreamState GetState() const; StreamState GetState() const override;
virtual void Close(); void Close() override;
protected: protected:
// Internal helper methods // Internal helper methods

View File

@@ -101,6 +101,42 @@ void StreamInterface::PostEvent(int events, int err) {
PostEvent(Thread::Current(), events, err); PostEvent(Thread::Current(), events, err);
} }
const void* StreamInterface::GetReadData(size_t* data_len) {
return NULL;
}
void* StreamInterface::GetWriteBuffer(size_t* buf_len) {
return NULL;
}
bool StreamInterface::SetPosition(size_t position) {
return false;
}
bool StreamInterface::GetPosition(size_t* position) const {
return false;
}
bool StreamInterface::GetSize(size_t* size) const {
return false;
}
bool StreamInterface::GetAvailable(size_t* size) const {
return false;
}
bool StreamInterface::GetWriteRemaining(size_t* size) const {
return false;
}
bool StreamInterface::Flush() {
return false;
}
bool StreamInterface::ReserveSize(size_t size) {
return true;
}
StreamInterface::StreamInterface() { StreamInterface::StreamInterface() {
} }
@@ -123,6 +159,53 @@ StreamAdapterInterface::StreamAdapterInterface(StreamInterface* stream,
stream_->SignalEvent.connect(this, &StreamAdapterInterface::OnEvent); stream_->SignalEvent.connect(this, &StreamAdapterInterface::OnEvent);
} }
StreamState StreamAdapterInterface::GetState() const {
return stream_->GetState();
}
StreamResult StreamAdapterInterface::Read(void* buffer,
size_t buffer_len,
size_t* read,
int* error) {
return stream_->Read(buffer, buffer_len, read, error);
}
StreamResult StreamAdapterInterface::Write(const void* data,
size_t data_len,
size_t* written,
int* error) {
return stream_->Write(data, data_len, written, error);
}
void StreamAdapterInterface::Close() {
stream_->Close();
}
bool StreamAdapterInterface::SetPosition(size_t position) {
return stream_->SetPosition(position);
}
bool StreamAdapterInterface::GetPosition(size_t* position) const {
return stream_->GetPosition(position);
}
bool StreamAdapterInterface::GetSize(size_t* size) const {
return stream_->GetSize(size);
}
bool StreamAdapterInterface::GetAvailable(size_t* size) const {
return stream_->GetAvailable(size);
}
bool StreamAdapterInterface::GetWriteRemaining(size_t* size) const {
return stream_->GetWriteRemaining(size);
}
bool StreamAdapterInterface::ReserveSize(size_t size) {
return stream_->ReserveSize(size);
}
bool StreamAdapterInterface::Flush() {
return stream_->Flush();
}
void StreamAdapterInterface::Attach(StreamInterface* stream, bool owned) { void StreamAdapterInterface::Attach(StreamInterface* stream, bool owned) {
if (NULL != stream_) if (NULL != stream_)
stream_->SignalEvent.disconnect(this); stream_->SignalEvent.disconnect(this);
@@ -147,6 +230,12 @@ StreamAdapterInterface::~StreamAdapterInterface() {
delete stream_; delete stream_;
} }
void StreamAdapterInterface::OnEvent(StreamInterface* stream,
int events,
int err) {
SignalEvent(this, events, err);
}
/////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////
// StreamTap // StreamTap
/////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////
@@ -157,6 +246,8 @@ StreamTap::StreamTap(StreamInterface* stream, StreamInterface* tap)
AttachTap(tap); AttachTap(tap);
} }
StreamTap::~StreamTap() = default;
void StreamTap::AttachTap(StreamInterface* tap) { void StreamTap::AttachTap(StreamInterface* tap) {
tap_.reset(tap); tap_.reset(tap);
} }
@@ -609,6 +700,13 @@ StreamResult CircularFileStream::Write(const void* data, size_t data_len,
return result; return result;
} }
AsyncWriteStream::AsyncWriteStream(StreamInterface* stream,
rtc::Thread* write_thread)
: stream_(stream),
write_thread_(write_thread),
state_(stream ? stream->GetState() : SS_CLOSED) {
}
AsyncWriteStream::~AsyncWriteStream() { AsyncWriteStream::~AsyncWriteStream() {
write_thread_->Clear(this, 0, NULL); write_thread_->Clear(this, 0, NULL);
ClearBufferAndWrite(); ClearBufferAndWrite();
@@ -617,6 +715,10 @@ AsyncWriteStream::~AsyncWriteStream() {
stream_.reset(); stream_.reset();
} }
StreamState AsyncWriteStream::GetState() const {
return state_;
}
// This is needed by some stream writers, such as RtpDumpWriter. // This is needed by some stream writers, such as RtpDumpWriter.
bool AsyncWriteStream::GetPosition(size_t* position) const { bool AsyncWriteStream::GetPosition(size_t* position) const {
CritScope cs(&crit_stream_); CritScope cs(&crit_stream_);

View File

@@ -63,7 +63,7 @@ class StreamInterface : public MessageHandler {
MSG_POST_EVENT = 0xF1F1, MSG_MAX = MSG_POST_EVENT MSG_POST_EVENT = 0xF1F1, MSG_MAX = MSG_POST_EVENT
}; };
virtual ~StreamInterface(); ~StreamInterface() override;
virtual StreamState GetState() const = 0; virtual StreamState GetState() const = 0;
@@ -130,7 +130,7 @@ class StreamInterface : public MessageHandler {
// does not require a matching call to ConsumeReadData if the data is not // does not require a matching call to ConsumeReadData if the data is not
// processed. Read and ConsumeReadData invalidate the buffer returned by // processed. Read and ConsumeReadData invalidate the buffer returned by
// GetReadData. // GetReadData.
virtual const void* GetReadData(size_t* data_len) { return NULL; } virtual const void* GetReadData(size_t* data_len);
virtual void ConsumeReadData(size_t used) {} virtual void ConsumeReadData(size_t used) {}
// GetWriteBuffer returns a pointer to a buffer which is owned by the stream. // GetWriteBuffer returns a pointer to a buffer which is owned by the stream.
@@ -144,7 +144,7 @@ class StreamInterface : public MessageHandler {
// amount of buffer is not yet available, return NULL and Signal SE_WRITE // amount of buffer is not yet available, return NULL and Signal SE_WRITE
// when it is available. If the requested amount is too large, return an // when it is available. If the requested amount is too large, return an
// error. // error.
virtual void* GetWriteBuffer(size_t* buf_len) { return NULL; } virtual void* GetWriteBuffer(size_t* buf_len);
virtual void ConsumeWriteBuffer(size_t used) {} virtual void ConsumeWriteBuffer(size_t used) {}
// Write data_len bytes found in data, circumventing any throttling which // Write data_len bytes found in data, circumventing any throttling which
@@ -165,33 +165,33 @@ class StreamInterface : public MessageHandler {
// Seek to a byte offset from the beginning of the stream. Returns false if // Seek to a byte offset from the beginning of the stream. Returns false if
// the stream does not support seeking, or cannot seek to the specified // the stream does not support seeking, or cannot seek to the specified
// position. // position.
virtual bool SetPosition(size_t position) { return false; } virtual bool SetPosition(size_t position);
// Get the byte offset of the current position from the start of the stream. // Get the byte offset of the current position from the start of the stream.
// Returns false if the position is not known. // Returns false if the position is not known.
virtual bool GetPosition(size_t* position) const { return false; } virtual bool GetPosition(size_t* position) const;
// Get the byte length of the entire stream. Returns false if the length // Get the byte length of the entire stream. Returns false if the length
// is not known. // is not known.
virtual bool GetSize(size_t* size) const { return false; } virtual bool GetSize(size_t* size) const;
// Return the number of Read()-able bytes remaining before end-of-stream. // Return the number of Read()-able bytes remaining before end-of-stream.
// Returns false if not known. // Returns false if not known.
virtual bool GetAvailable(size_t* size) const { return false; } virtual bool GetAvailable(size_t* size) const;
// Return the number of Write()-able bytes remaining before end-of-stream. // Return the number of Write()-able bytes remaining before end-of-stream.
// Returns false if not known. // Returns false if not known.
virtual bool GetWriteRemaining(size_t* size) const { return false; } virtual bool GetWriteRemaining(size_t* size) const;
// Return true if flush is successful. // Return true if flush is successful.
virtual bool Flush() { return false; } virtual bool Flush();
// Communicates the amount of data which will be written to the stream. The // Communicates the amount of data which will be written to the stream. The
// stream may choose to preallocate memory to accomodate this data. The // stream may choose to preallocate memory to accomodate this data. The
// stream may return false to indicate that there is not enough room (ie, // stream may return false to indicate that there is not enough room (ie,
// Write will return SR_EOS/SR_ERROR at some point). Note that calling this // Write will return SR_EOS/SR_ERROR at some point). Note that calling this
// function should not affect the existing state of data in the stream. // function should not affect the existing state of data in the stream.
virtual bool ReserveSize(size_t size) { return true; } virtual bool ReserveSize(size_t size);
// //
// CONVENIENCE METHODS // CONVENIENCE METHODS
@@ -225,7 +225,7 @@ class StreamInterface : public MessageHandler {
StreamInterface(); StreamInterface();
// MessageHandler Interface // MessageHandler Interface
virtual void OnMessage(Message* msg); void OnMessage(Message* msg) override;
private: private:
DISALLOW_EVIL_CONSTRUCTORS(StreamInterface); DISALLOW_EVIL_CONSTRUCTORS(StreamInterface);
@@ -245,20 +245,16 @@ class StreamAdapterInterface : public StreamInterface,
explicit StreamAdapterInterface(StreamInterface* stream, bool owned = true); explicit StreamAdapterInterface(StreamInterface* stream, bool owned = true);
// Core Stream Interface // Core Stream Interface
virtual StreamState GetState() const { StreamState GetState() const override;
return stream_->GetState(); StreamResult Read(void* buffer,
} size_t buffer_len,
virtual StreamResult Read(void* buffer, size_t buffer_len, size_t* read,
size_t* read, int* error) { int* error) override;
return stream_->Read(buffer, buffer_len, read, error); StreamResult Write(const void* data,
} size_t data_len,
virtual StreamResult Write(const void* data, size_t data_len, size_t* written,
size_t* written, int* error) { int* error) override;
return stream_->Write(data, data_len, written, error); void Close() override;
}
virtual void Close() {
stream_->Close();
}
// Optional Stream Interface // Optional Stream Interface
/* Note: Many stream adapters were implemented prior to this Read/Write /* Note: Many stream adapters were implemented prior to this Read/Write
@@ -287,39 +283,23 @@ class StreamAdapterInterface : public StreamInterface,
} }
*/ */
virtual bool SetPosition(size_t position) { bool SetPosition(size_t position) override;
return stream_->SetPosition(position); bool GetPosition(size_t* position) const override;
} bool GetSize(size_t* size) const override;
virtual bool GetPosition(size_t* position) const { bool GetAvailable(size_t* size) const override;
return stream_->GetPosition(position); bool GetWriteRemaining(size_t* size) const override;
} bool ReserveSize(size_t size) override;
virtual bool GetSize(size_t* size) const { bool Flush() override;
return stream_->GetSize(size);
}
virtual bool GetAvailable(size_t* size) const {
return stream_->GetAvailable(size);
}
virtual bool GetWriteRemaining(size_t* size) const {
return stream_->GetWriteRemaining(size);
}
virtual bool ReserveSize(size_t size) {
return stream_->ReserveSize(size);
}
virtual bool Flush() {
return stream_->Flush();
}
void Attach(StreamInterface* stream, bool owned = true); void Attach(StreamInterface* stream, bool owned = true);
StreamInterface* Detach(); StreamInterface* Detach();
protected: protected:
virtual ~StreamAdapterInterface(); ~StreamAdapterInterface() override;
// Note that the adapter presents itself as the origin of the stream events, // Note that the adapter presents itself as the origin of the stream events,
// since users of the adapter may not recognize the adapted object. // since users of the adapter may not recognize the adapted object.
virtual void OnEvent(StreamInterface* stream, int events, int err) { virtual void OnEvent(StreamInterface* stream, int events, int err);
SignalEvent(this, events, err);
}
StreamInterface* stream() { return stream_; } StreamInterface* stream() { return stream_; }
private: private:
@@ -337,16 +317,21 @@ class StreamAdapterInterface : public StreamInterface,
class StreamTap : public StreamAdapterInterface { class StreamTap : public StreamAdapterInterface {
public: public:
explicit StreamTap(StreamInterface* stream, StreamInterface* tap); explicit StreamTap(StreamInterface* stream, StreamInterface* tap);
~StreamTap() override;
void AttachTap(StreamInterface* tap); void AttachTap(StreamInterface* tap);
StreamInterface* DetachTap(); StreamInterface* DetachTap();
StreamResult GetTapResult(int* error); StreamResult GetTapResult(int* error);
// StreamAdapterInterface Interface // StreamAdapterInterface Interface
virtual StreamResult Read(void* buffer, size_t buffer_len, StreamResult Read(void* buffer,
size_t* read, int* error); size_t buffer_len,
virtual StreamResult Write(const void* data, size_t data_len, size_t* read,
size_t* written, int* error); int* error) override;
StreamResult Write(const void* data,
size_t data_len,
size_t* written,
int* error) override;
private: private:
scoped_ptr<StreamInterface> tap_; scoped_ptr<StreamInterface> tap_;
@@ -371,12 +356,14 @@ class StreamSegment : public StreamAdapterInterface {
explicit StreamSegment(StreamInterface* stream, size_t length); explicit StreamSegment(StreamInterface* stream, size_t length);
// StreamAdapterInterface Interface // StreamAdapterInterface Interface
virtual StreamResult Read(void* buffer, size_t buffer_len, StreamResult Read(void* buffer,
size_t* read, int* error); size_t buffer_len,
virtual bool SetPosition(size_t position); size_t* read,
virtual bool GetPosition(size_t* position) const; int* error) override;
virtual bool GetSize(size_t* size) const; bool SetPosition(size_t position) override;
virtual bool GetAvailable(size_t* size) const; bool GetPosition(size_t* position) const override;
bool GetSize(size_t* size) const override;
bool GetAvailable(size_t* size) const override;
private: private:
size_t start_, pos_, length_; size_t start_, pos_, length_;
@@ -390,15 +377,19 @@ class StreamSegment : public StreamAdapterInterface {
class NullStream : public StreamInterface { class NullStream : public StreamInterface {
public: public:
NullStream(); NullStream();
virtual ~NullStream(); ~NullStream() override;
// StreamInterface Interface // StreamInterface Interface
virtual StreamState GetState() const; StreamState GetState() const override;
virtual StreamResult Read(void* buffer, size_t buffer_len, StreamResult Read(void* buffer,
size_t* read, int* error); size_t buffer_len,
virtual StreamResult Write(const void* data, size_t data_len, size_t* read,
size_t* written, int* error); int* error) override;
virtual void Close(); StreamResult Write(const void* data,
size_t data_len,
size_t* written,
int* error) override;
void Close() override;
}; };
/////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////
@@ -409,7 +400,7 @@ class NullStream : public StreamInterface {
class FileStream : public StreamInterface { class FileStream : public StreamInterface {
public: public:
FileStream(); FileStream();
virtual ~FileStream(); ~FileStream() override;
// The semantics of filename and mode are the same as stdio's fopen // The semantics of filename and mode are the same as stdio's fopen
virtual bool Open(const std::string& filename, const char* mode, int* error); virtual bool Open(const std::string& filename, const char* mode, int* error);
@@ -420,19 +411,23 @@ class FileStream : public StreamInterface {
// buffering causes writes to block until the bytes on disk are updated. // buffering causes writes to block until the bytes on disk are updated.
virtual bool DisableBuffering(); virtual bool DisableBuffering();
virtual StreamState GetState() const; StreamState GetState() const override;
virtual StreamResult Read(void* buffer, size_t buffer_len, StreamResult Read(void* buffer,
size_t* read, int* error); size_t buffer_len,
virtual StreamResult Write(const void* data, size_t data_len, size_t* read,
size_t* written, int* error); int* error) override;
virtual void Close(); StreamResult Write(const void* data,
virtual bool SetPosition(size_t position); size_t data_len,
virtual bool GetPosition(size_t* position) const; size_t* written,
virtual bool GetSize(size_t* size) const; int* error) override;
virtual bool GetAvailable(size_t* size) const; void Close() override;
virtual bool ReserveSize(size_t size); bool SetPosition(size_t position) override;
bool GetPosition(size_t* position) const override;
bool GetSize(size_t* size) const override;
bool GetAvailable(size_t* size) const override;
bool ReserveSize(size_t size) override;
virtual bool Flush(); bool Flush() override;
#if defined(WEBRTC_POSIX) && !defined(__native_client__) #if defined(WEBRTC_POSIX) && !defined(__native_client__)
// Tries to aquire an exclusive lock on the file. // Tries to aquire an exclusive lock on the file.
@@ -460,11 +455,15 @@ class CircularFileStream : public FileStream {
public: public:
explicit CircularFileStream(size_t max_size); explicit CircularFileStream(size_t max_size);
virtual bool Open(const std::string& filename, const char* mode, int* error); bool Open(const std::string& filename, const char* mode, int* error) override;
virtual StreamResult Read(void* buffer, size_t buffer_len, StreamResult Read(void* buffer,
size_t* read, int* error); size_t buffer_len,
virtual StreamResult Write(const void* data, size_t data_len, size_t* read,
size_t* written, int* error); int* error) override;
StreamResult Write(const void* data,
size_t data_len,
size_t* written,
int* error) override;
private: private:
enum ReadSegment { enum ReadSegment {
@@ -487,28 +486,27 @@ class CircularFileStream : public FileStream {
class AsyncWriteStream : public StreamInterface { class AsyncWriteStream : public StreamInterface {
public: public:
// Takes ownership of the stream, but not the thread. // Takes ownership of the stream, but not the thread.
AsyncWriteStream(StreamInterface* stream, rtc::Thread* write_thread) AsyncWriteStream(StreamInterface* stream, rtc::Thread* write_thread);
: stream_(stream), ~AsyncWriteStream() override;
write_thread_(write_thread),
state_(stream ? stream->GetState() : SS_CLOSED) {
}
virtual ~AsyncWriteStream();
// StreamInterface Interface // StreamInterface Interface
virtual StreamState GetState() const { return state_; } StreamState GetState() const override;
// This is needed by some stream writers, such as RtpDumpWriter. // This is needed by some stream writers, such as RtpDumpWriter.
virtual bool GetPosition(size_t* position) const; bool GetPosition(size_t* position) const override;
virtual StreamResult Read(void* buffer, size_t buffer_len, StreamResult Read(void* buffer,
size_t* read, int* error); size_t buffer_len,
virtual StreamResult Write(const void* data, size_t data_len, size_t* read,
size_t* written, int* error); int* error) override;
virtual void Close(); StreamResult Write(const void* data,
virtual bool Flush(); size_t data_len,
size_t* written,
int* error) override;
void Close() override;
bool Flush() override;
protected: protected:
// From MessageHandler // From MessageHandler
virtual void OnMessage(rtc::Message* pmsg); void OnMessage(rtc::Message* pmsg) override;
virtual void ClearBufferAndWrite(); virtual void ClearBufferAndWrite();
private: private:
@@ -530,13 +528,16 @@ class AsyncWriteStream : public StreamInterface {
class POpenStream : public FileStream { class POpenStream : public FileStream {
public: public:
POpenStream() : wait_status_(-1) {} POpenStream() : wait_status_(-1) {}
virtual ~POpenStream(); ~POpenStream() override;
virtual bool Open(const std::string& subcommand, const char* mode, bool Open(const std::string& subcommand,
int* error); const char* mode,
int* error) override;
// Same as Open(). shflag is ignored. // Same as Open(). shflag is ignored.
virtual bool OpenShare(const std::string& subcommand, const char* mode, bool OpenShare(const std::string& subcommand,
int shflag, int* error); const char* mode,
int shflag,
int* error) override;
// Returns the wait status from the last Close() of an Open()'ed stream, or // Returns the wait status from the last Close() of an Open()'ed stream, or
// -1 if no Open()+Close() has been done on this object. Meaning of the number // -1 if no Open()+Close() has been done on this object. Meaning of the number
@@ -544,7 +545,7 @@ class POpenStream : public FileStream {
int GetWaitStatus() const { return wait_status_; } int GetWaitStatus() const { return wait_status_; }
protected: protected:
virtual void DoClose(); void DoClose() override;
private: private:
int wait_status_; int wait_status_;
@@ -560,17 +561,21 @@ class POpenStream : public FileStream {
class MemoryStreamBase : public StreamInterface { class MemoryStreamBase : public StreamInterface {
public: public:
virtual StreamState GetState() const; StreamState GetState() const override;
virtual StreamResult Read(void* buffer, size_t bytes, size_t* bytes_read, StreamResult Read(void* buffer,
int* error); size_t bytes,
virtual StreamResult Write(const void* buffer, size_t bytes, size_t* bytes_read,
size_t* bytes_written, int* error); int* error) override;
virtual void Close(); StreamResult Write(const void* buffer,
virtual bool SetPosition(size_t position); size_t bytes,
virtual bool GetPosition(size_t* position) const; size_t* bytes_written,
virtual bool GetSize(size_t* size) const; int* error) override;
virtual bool GetAvailable(size_t* size) const; void Close() override;
virtual bool ReserveSize(size_t size); bool SetPosition(size_t position) override;
bool GetPosition(size_t* position) const override;
bool GetSize(size_t* size) const override;
bool GetAvailable(size_t* size) const override;
bool ReserveSize(size_t size) override;
char* GetBuffer() { return buffer_; } char* GetBuffer() { return buffer_; }
const char* GetBuffer() const { return buffer_; } const char* GetBuffer() const { return buffer_; }
@@ -597,12 +602,12 @@ class MemoryStream : public MemoryStreamBase {
MemoryStream(); MemoryStream();
explicit MemoryStream(const char* data); // Calls SetData(data, strlen(data)) explicit MemoryStream(const char* data); // Calls SetData(data, strlen(data))
MemoryStream(const void* data, size_t length); // Calls SetData(data, length) MemoryStream(const void* data, size_t length); // Calls SetData(data, length)
virtual ~MemoryStream(); ~MemoryStream() override;
void SetData(const void* data, size_t length); void SetData(const void* data, size_t length);
protected: protected:
virtual StreamResult DoReserve(size_t size, int* error); StreamResult DoReserve(size_t size, int* error) override;
// Memory Streams are aligned for efficiency. // Memory Streams are aligned for efficiency.
static const int kAlignment = 16; static const int kAlignment = 16;
char* buffer_alloc_; char* buffer_alloc_;
@@ -615,7 +620,7 @@ class ExternalMemoryStream : public MemoryStreamBase {
public: public:
ExternalMemoryStream(); ExternalMemoryStream();
ExternalMemoryStream(void* data, size_t length); ExternalMemoryStream(void* data, size_t length);
virtual ~ExternalMemoryStream(); ~ExternalMemoryStream() override;
void SetData(void* data, size_t length); void SetData(void* data, size_t length);
}; };
@@ -630,7 +635,7 @@ class FifoBuffer : public StreamInterface {
explicit FifoBuffer(size_t length); explicit FifoBuffer(size_t length);
// Creates a FIFO buffer with the specified capacity and owner // Creates a FIFO buffer with the specified capacity and owner
FifoBuffer(size_t length, Thread* owner); FifoBuffer(size_t length, Thread* owner);
virtual ~FifoBuffer(); ~FifoBuffer() override;
// Gets the amount of data currently readable from the buffer. // Gets the amount of data currently readable from the buffer.
bool GetBuffered(size_t* data_len) const; bool GetBuffered(size_t* data_len) const;
// Resizes the buffer to the specified capacity. Fails if data_length_ > size // Resizes the buffer to the specified capacity. Fails if data_length_ > size
@@ -651,17 +656,21 @@ class FifoBuffer : public StreamInterface {
size_t* bytes_written); size_t* bytes_written);
// StreamInterface methods // StreamInterface methods
virtual StreamState GetState() const; StreamState GetState() const override;
virtual StreamResult Read(void* buffer, size_t bytes, StreamResult Read(void* buffer,
size_t* bytes_read, int* error); size_t bytes,
virtual StreamResult Write(const void* buffer, size_t bytes, size_t* bytes_read,
size_t* bytes_written, int* error); int* error) override;
virtual void Close(); StreamResult Write(const void* buffer,
virtual const void* GetReadData(size_t* data_len); size_t bytes,
virtual void ConsumeReadData(size_t used); size_t* bytes_written,
virtual void* GetWriteBuffer(size_t* buf_len); int* error) override;
virtual void ConsumeWriteBuffer(size_t used); void Close() override;
virtual bool GetWriteRemaining(size_t* size) const; const void* GetReadData(size_t* data_len) override;
void ConsumeReadData(size_t used) override;
void* GetWriteBuffer(size_t* buf_len) override;
void ConsumeWriteBuffer(size_t used) override;
bool GetWriteRemaining(size_t* size) const override;
private: private:
// Helper method that implements ReadOffset. Caller must acquire a lock // Helper method that implements ReadOffset. Caller must acquire a lock
@@ -693,14 +702,18 @@ class LoggingAdapter : public StreamAdapterInterface {
void set_label(const std::string& label); void set_label(const std::string& label);
virtual StreamResult Read(void* buffer, size_t buffer_len, StreamResult Read(void* buffer,
size_t* read, int* error); size_t buffer_len,
virtual StreamResult Write(const void* data, size_t data_len, size_t* read,
size_t* written, int* error); int* error) override;
virtual void Close(); StreamResult Write(const void* data,
size_t data_len,
size_t* written,
int* error) override;
void Close() override;
protected: protected:
virtual void OnEvent(StreamInterface* stream, int events, int err); void OnEvent(StreamInterface* stream, int events, int err) override;
private: private:
LoggingSeverity level_; LoggingSeverity level_;
@@ -720,17 +733,21 @@ class StringStream : public StreamInterface {
explicit StringStream(std::string& str); explicit StringStream(std::string& str);
explicit StringStream(const std::string& str); explicit StringStream(const std::string& str);
virtual StreamState GetState() const; StreamState GetState() const override;
virtual StreamResult Read(void* buffer, size_t buffer_len, StreamResult Read(void* buffer,
size_t* read, int* error); size_t buffer_len,
virtual StreamResult Write(const void* data, size_t data_len, size_t* read,
size_t* written, int* error); int* error) override;
virtual void Close(); StreamResult Write(const void* data,
virtual bool SetPosition(size_t position); size_t data_len,
virtual bool GetPosition(size_t* position) const; size_t* written,
virtual bool GetSize(size_t* size) const; int* error) override;
virtual bool GetAvailable(size_t* size) const; void Close() override;
virtual bool ReserveSize(size_t size); bool SetPosition(size_t position) override;
bool GetPosition(size_t* position) const override;
bool GetSize(size_t* size) const override;
bool GetAvailable(size_t* size) const override;
bool ReserveSize(size_t size) override;
private: private:
std::string& str_; std::string& str_;
@@ -760,7 +777,7 @@ class StreamReference : public StreamAdapterInterface {
explicit StreamReference(StreamInterface* stream); explicit StreamReference(StreamInterface* stream);
StreamInterface* GetStream() { return stream(); } StreamInterface* GetStream() { return stream(); }
StreamInterface* NewReference(); StreamInterface* NewReference();
virtual ~StreamReference(); ~StreamReference() override;
private: private:
class StreamRefCount { class StreamRefCount {

View File

@@ -461,6 +461,11 @@ static void GetProperty(io_service_t port, CFStringRef name,
} }
#endif #endif
SystemInfo::GpuInfo::GpuInfo() : vendor_id(0), device_id(0) {
}
SystemInfo::GpuInfo::~GpuInfo() = default;
// Fills a struct with information on the graphics adapater and returns true // Fills a struct with information on the graphics adapater and returns true
// iff successful. // iff successful.
bool SystemInfo::GetGpuInfo(GpuInfo *info) { bool SystemInfo::GetGpuInfo(GpuInfo *info) {

View File

@@ -52,7 +52,8 @@ class SystemInfo {
// The gpu identifier // The gpu identifier
struct GpuInfo { struct GpuInfo {
GpuInfo() : vendor_id(0), device_id(0) {} GpuInfo();
~GpuInfo();
std::string device_name; std::string device_name;
std::string description; std::string description;
int vendor_id; int vendor_id;

View File

@@ -224,6 +224,10 @@ void Task::Stop() {
TaskParent::OnStopped(this); TaskParent::OnStopped(this);
} }
int Task::ProcessResponse() {
return STATE_DONE;
}
void Task::set_timeout_seconds(const int timeout_seconds) { void Task::set_timeout_seconds(const int timeout_seconds) {
timeout_seconds_ = timeout_seconds; timeout_seconds_ = timeout_seconds;
ResetTimeout(); ResetTimeout();
@@ -269,4 +273,9 @@ void Task::ResumeTimeout() {
} }
} }
int Task::OnTimeout() {
// by default, we are finished after timing out
return STATE_DONE;
}
} // namespace rtc } // namespace rtc

View File

@@ -93,7 +93,7 @@ namespace rtc {
class Task : public TaskParent { class Task : public TaskParent {
public: public:
Task(TaskParent *parent); Task(TaskParent *parent);
virtual ~Task(); ~Task() override;
int32 unique_id() { return unique_id_; } int32 unique_id() { return unique_id_; }
@@ -140,7 +140,7 @@ class Task : public TaskParent {
virtual int Process(int state); virtual int Process(int state);
virtual void Stop(); virtual void Stop();
virtual int ProcessStart() = 0; virtual int ProcessStart() = 0;
virtual int ProcessResponse() { return STATE_DONE; } virtual int ProcessResponse();
void ResetTimeout(); void ResetTimeout();
void ClearTimeout(); void ClearTimeout();
@@ -149,10 +149,7 @@ class Task : public TaskParent {
void ResumeTimeout(); void ResumeTimeout();
protected: protected:
virtual int OnTimeout() { virtual int OnTimeout();
// by default, we are finished after timing out
return STATE_DONE;
}
private: private:
void Done(); void Done();

View File

@@ -34,6 +34,8 @@ TaskParent::TaskParent(TaskRunner *derived_instance)
Initialize(); Initialize();
} }
TaskParent::~TaskParent() = default;
// Does common initialization of member variables // Does common initialization of member variables
void TaskParent::Initialize() { void TaskParent::Initialize() {
children_.reset(new ChildSet()); children_.reset(new ChildSet());

Some files were not shown because too many files have changed in this diff Show More