1/*
2 *  Copyright 2004 The WebRTC Project Authors. All rights reserved.
3 *
4 *  Use of this source code is governed by a BSD-style license
5 *  that can be found in the LICENSE file in the root of the source
6 *  tree. An additional intellectual property rights grant can be found
7 *  in the file PATENTS.  All contributing project authors may
8 *  be found in the AUTHORS file in the root of the source tree.
9 */
10
11#ifndef WEBRTC_BASE_PHYSICALSOCKETSERVER_H__
12#define WEBRTC_BASE_PHYSICALSOCKETSERVER_H__
13
14#include <vector>
15
16#include "webrtc/base/asyncfile.h"
17#include "webrtc/base/nethelpers.h"
18#include "webrtc/base/scoped_ptr.h"
19#include "webrtc/base/socketserver.h"
20#include "webrtc/base/criticalsection.h"
21
22#if defined(WEBRTC_POSIX)
23typedef int SOCKET;
24#endif // WEBRTC_POSIX
25
26namespace rtc {
27
28// Event constants for the Dispatcher class.
29enum DispatcherEvent {
30  DE_READ    = 0x0001,
31  DE_WRITE   = 0x0002,
32  DE_CONNECT = 0x0004,
33  DE_CLOSE   = 0x0008,
34  DE_ACCEPT  = 0x0010,
35};
36
37class Signaler;
38#if defined(WEBRTC_POSIX)
39class PosixSignalDispatcher;
40#endif
41
42class Dispatcher {
43 public:
44  virtual ~Dispatcher() {}
45  virtual uint32_t GetRequestedEvents() = 0;
46  virtual void OnPreEvent(uint32_t ff) = 0;
47  virtual void OnEvent(uint32_t ff, int err) = 0;
48#if defined(WEBRTC_WIN)
49  virtual WSAEVENT GetWSAEvent() = 0;
50  virtual SOCKET GetSocket() = 0;
51  virtual bool CheckSignalClose() = 0;
52#elif defined(WEBRTC_POSIX)
53  virtual int GetDescriptor() = 0;
54  virtual bool IsDescriptorClosed() = 0;
55#endif
56};
57
58// A socket server that provides the real sockets of the underlying OS.
59class PhysicalSocketServer : public SocketServer {
60 public:
61  PhysicalSocketServer();
62  ~PhysicalSocketServer() override;
63
64  // SocketFactory:
65  Socket* CreateSocket(int type) override;
66  Socket* CreateSocket(int family, int type) override;
67
68  AsyncSocket* CreateAsyncSocket(int type) override;
69  AsyncSocket* CreateAsyncSocket(int family, int type) override;
70
71  // Internal Factory for Accept
72  AsyncSocket* WrapSocket(SOCKET s);
73
74  // SocketServer:
75  bool Wait(int cms, bool process_io) override;
76  void WakeUp() override;
77
78  void Add(Dispatcher* dispatcher);
79  void Remove(Dispatcher* dispatcher);
80
81#if defined(WEBRTC_POSIX)
82  AsyncFile* CreateFile(int fd);
83
84  // Sets the function to be executed in response to the specified POSIX signal.
85  // The function is executed from inside Wait() using the "self-pipe trick"--
86  // regardless of which thread receives the signal--and hence can safely
87  // manipulate user-level data structures.
88  // "handler" may be SIG_IGN, SIG_DFL, or a user-specified function, just like
89  // with signal(2).
90  // Only one PhysicalSocketServer should have user-level signal handlers.
91  // Dispatching signals on multiple PhysicalSocketServers is not reliable.
92  // The signal mask is not modified. It is the caller's responsibily to
93  // maintain it as desired.
94  virtual bool SetPosixSignalHandler(int signum, void (*handler)(int));
95
96 protected:
97  Dispatcher* signal_dispatcher();
98#endif
99
100 private:
101  typedef std::vector<Dispatcher*> DispatcherList;
102  typedef std::vector<size_t*> IteratorList;
103
104#if defined(WEBRTC_POSIX)
105  static bool InstallSignal(int signum, void (*handler)(int));
106
107  scoped_ptr<PosixSignalDispatcher> signal_dispatcher_;
108#endif
109  DispatcherList dispatchers_;
110  IteratorList iterators_;
111  Signaler* signal_wakeup_;
112  CriticalSection crit_;
113  bool fWait_;
114#if defined(WEBRTC_WIN)
115  WSAEVENT socket_ev_;
116#endif
117};
118
119class PhysicalSocket : public AsyncSocket, public sigslot::has_slots<> {
120 public:
121  PhysicalSocket(PhysicalSocketServer* ss, SOCKET s = INVALID_SOCKET);
122  ~PhysicalSocket() override;
123
124  // Creates the underlying OS socket (same as the "socket" function).
125  virtual bool Create(int family, int type);
126
127  SocketAddress GetLocalAddress() const override;
128  SocketAddress GetRemoteAddress() const override;
129
130  int Bind(const SocketAddress& bind_addr) override;
131  int Connect(const SocketAddress& addr) override;
132
133  int GetError() const override;
134  void SetError(int error) override;
135
136  ConnState GetState() const override;
137
138  int GetOption(Option opt, int* value) override;
139  int SetOption(Option opt, int value) override;
140
141  int Send(const void* pv, size_t cb) override;
142  int SendTo(const void* buffer,
143             size_t length,
144             const SocketAddress& addr) override;
145
146  int Recv(void* buffer, size_t length) override;
147  int RecvFrom(void* buffer, size_t length, SocketAddress* out_addr) override;
148
149  int Listen(int backlog) override;
150  AsyncSocket* Accept(SocketAddress* out_addr) override;
151
152  int Close() override;
153
154  int EstimateMTU(uint16_t* mtu) override;
155
156  SocketServer* socketserver() { return ss_; }
157
158 protected:
159  int DoConnect(const SocketAddress& connect_addr);
160
161  // Make virtual so ::accept can be overwritten in tests.
162  virtual SOCKET DoAccept(SOCKET socket, sockaddr* addr, socklen_t* addrlen);
163
164  void OnResolveResult(AsyncResolverInterface* resolver);
165
166  void UpdateLastError();
167  void MaybeRemapSendError();
168
169  static int TranslateOption(Option opt, int* slevel, int* sopt);
170
171  PhysicalSocketServer* ss_;
172  SOCKET s_;
173  uint8_t enabled_events_;
174  bool udp_;
175  mutable CriticalSection crit_;
176  int error_ GUARDED_BY(crit_);
177  ConnState state_;
178  AsyncResolver* resolver_;
179
180#if !defined(NDEBUG)
181  std::string dbg_addr_;
182#endif
183};
184
185class SocketDispatcher : public Dispatcher, public PhysicalSocket {
186 public:
187  explicit SocketDispatcher(PhysicalSocketServer *ss);
188  SocketDispatcher(SOCKET s, PhysicalSocketServer *ss);
189  ~SocketDispatcher() override;
190
191  bool Initialize();
192
193  virtual bool Create(int type);
194  bool Create(int family, int type) override;
195
196#if defined(WEBRTC_WIN)
197  WSAEVENT GetWSAEvent() override;
198  SOCKET GetSocket() override;
199  bool CheckSignalClose() override;
200#elif defined(WEBRTC_POSIX)
201  int GetDescriptor() override;
202  bool IsDescriptorClosed() override;
203#endif
204
205  uint32_t GetRequestedEvents() override;
206  void OnPreEvent(uint32_t ff) override;
207  void OnEvent(uint32_t ff, int err) override;
208
209  int Close() override;
210
211#if defined(WEBRTC_WIN)
212 private:
213  static int next_id_;
214  int id_;
215  bool signal_close_;
216  int signal_err_;
217#endif // WEBRTC_WIN
218};
219
220} // namespace rtc
221
222#endif // WEBRTC_BASE_PHYSICALSOCKETSERVER_H__
223