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 #include "rtc_base/nat_socket_factory.h"
12
13 #include "rtc_base/arraysize.h"
14 #include "rtc_base/checks.h"
15 #include "rtc_base/logging.h"
16 #include "rtc_base/nat_server.h"
17 #include "rtc_base/virtual_socket_server.h"
18
19 namespace rtc {
20
21 // Packs the given socketaddress into the buffer in buf, in the quasi-STUN
22 // format that the natserver uses.
23 // Returns 0 if an invalid address is passed.
PackAddressForNAT(char * buf,size_t buf_size,const SocketAddress & remote_addr)24 size_t PackAddressForNAT(char* buf,
25 size_t buf_size,
26 const SocketAddress& remote_addr) {
27 const IPAddress& ip = remote_addr.ipaddr();
28 int family = ip.family();
29 buf[0] = 0;
30 buf[1] = family;
31 // Writes the port.
32 *(reinterpret_cast<uint16_t*>(&buf[2])) = HostToNetwork16(remote_addr.port());
33 if (family == AF_INET) {
34 RTC_DCHECK(buf_size >= kNATEncodedIPv4AddressSize);
35 in_addr v4addr = ip.ipv4_address();
36 memcpy(&buf[4], &v4addr, kNATEncodedIPv4AddressSize - 4);
37 return kNATEncodedIPv4AddressSize;
38 } else if (family == AF_INET6) {
39 RTC_DCHECK(buf_size >= kNATEncodedIPv6AddressSize);
40 in6_addr v6addr = ip.ipv6_address();
41 memcpy(&buf[4], &v6addr, kNATEncodedIPv6AddressSize - 4);
42 return kNATEncodedIPv6AddressSize;
43 }
44 return 0U;
45 }
46
47 // Decodes the remote address from a packet that has been encoded with the nat's
48 // quasi-STUN format. Returns the length of the address (i.e., the offset into
49 // data where the original packet starts).
UnpackAddressFromNAT(const char * buf,size_t buf_size,SocketAddress * remote_addr)50 size_t UnpackAddressFromNAT(const char* buf,
51 size_t buf_size,
52 SocketAddress* remote_addr) {
53 RTC_DCHECK(buf_size >= 8);
54 RTC_DCHECK(buf[0] == 0);
55 int family = buf[1];
56 uint16_t port =
57 NetworkToHost16(*(reinterpret_cast<const uint16_t*>(&buf[2])));
58 if (family == AF_INET) {
59 const in_addr* v4addr = reinterpret_cast<const in_addr*>(&buf[4]);
60 *remote_addr = SocketAddress(IPAddress(*v4addr), port);
61 return kNATEncodedIPv4AddressSize;
62 } else if (family == AF_INET6) {
63 RTC_DCHECK(buf_size >= 20);
64 const in6_addr* v6addr = reinterpret_cast<const in6_addr*>(&buf[4]);
65 *remote_addr = SocketAddress(IPAddress(*v6addr), port);
66 return kNATEncodedIPv6AddressSize;
67 }
68 return 0U;
69 }
70
71 // NATSocket
72 class NATSocket : public AsyncSocket, public sigslot::has_slots<> {
73 public:
NATSocket(NATInternalSocketFactory * sf,int family,int type)74 explicit NATSocket(NATInternalSocketFactory* sf, int family, int type)
75 : sf_(sf),
76 family_(family),
77 type_(type),
78 connected_(false),
79 socket_(nullptr),
80 buf_(nullptr),
81 size_(0) {}
82
~NATSocket()83 ~NATSocket() override {
84 delete socket_;
85 delete[] buf_;
86 }
87
GetLocalAddress() const88 SocketAddress GetLocalAddress() const override {
89 return (socket_) ? socket_->GetLocalAddress() : SocketAddress();
90 }
91
GetRemoteAddress() const92 SocketAddress GetRemoteAddress() const override {
93 return remote_addr_; // will be NIL if not connected
94 }
95
Bind(const SocketAddress & addr)96 int Bind(const SocketAddress& addr) override {
97 if (socket_) { // already bound, bubble up error
98 return -1;
99 }
100
101 return BindInternal(addr);
102 }
103
Connect(const SocketAddress & addr)104 int Connect(const SocketAddress& addr) override {
105 int result = 0;
106 // If we're not already bound (meaning |socket_| is null), bind to ANY
107 // address.
108 if (!socket_) {
109 result = BindInternal(SocketAddress(GetAnyIP(family_), 0));
110 if (result < 0) {
111 return result;
112 }
113 }
114
115 if (type_ == SOCK_STREAM) {
116 result = socket_->Connect(server_addr_.IsNil() ? addr : server_addr_);
117 } else {
118 connected_ = true;
119 }
120
121 if (result >= 0) {
122 remote_addr_ = addr;
123 }
124
125 return result;
126 }
127
Send(const void * data,size_t size)128 int Send(const void* data, size_t size) override {
129 RTC_DCHECK(connected_);
130 return SendTo(data, size, remote_addr_);
131 }
132
SendTo(const void * data,size_t size,const SocketAddress & addr)133 int SendTo(const void* data,
134 size_t size,
135 const SocketAddress& addr) override {
136 RTC_DCHECK(!connected_ || addr == remote_addr_);
137 if (server_addr_.IsNil() || type_ == SOCK_STREAM) {
138 return socket_->SendTo(data, size, addr);
139 }
140 // This array will be too large for IPv4 packets, but only by 12 bytes.
141 std::unique_ptr<char[]> buf(new char[size + kNATEncodedIPv6AddressSize]);
142 size_t addrlength =
143 PackAddressForNAT(buf.get(), size + kNATEncodedIPv6AddressSize, addr);
144 size_t encoded_size = size + addrlength;
145 memcpy(buf.get() + addrlength, data, size);
146 int result = socket_->SendTo(buf.get(), encoded_size, server_addr_);
147 if (result >= 0) {
148 RTC_DCHECK(result == static_cast<int>(encoded_size));
149 result = result - static_cast<int>(addrlength);
150 }
151 return result;
152 }
153
Recv(void * data,size_t size,int64_t * timestamp)154 int Recv(void* data, size_t size, int64_t* timestamp) override {
155 SocketAddress addr;
156 return RecvFrom(data, size, &addr, timestamp);
157 }
158
RecvFrom(void * data,size_t size,SocketAddress * out_addr,int64_t * timestamp)159 int RecvFrom(void* data,
160 size_t size,
161 SocketAddress* out_addr,
162 int64_t* timestamp) override {
163 if (server_addr_.IsNil() || type_ == SOCK_STREAM) {
164 return socket_->RecvFrom(data, size, out_addr, timestamp);
165 }
166 // Make sure we have enough room to read the requested amount plus the
167 // largest possible header address.
168 SocketAddress remote_addr;
169 Grow(size + kNATEncodedIPv6AddressSize);
170
171 // Read the packet from the socket.
172 int result = socket_->RecvFrom(buf_, size_, &remote_addr, timestamp);
173 if (result >= 0) {
174 RTC_DCHECK(remote_addr == server_addr_);
175
176 // TODO: we need better framing so we know how many bytes we can
177 // return before we need to read the next address. For UDP, this will be
178 // fine as long as the reader always reads everything in the packet.
179 RTC_DCHECK((size_t)result < size_);
180
181 // Decode the wire packet into the actual results.
182 SocketAddress real_remote_addr;
183 size_t addrlength = UnpackAddressFromNAT(buf_, result, &real_remote_addr);
184 memcpy(data, buf_ + addrlength, result - addrlength);
185
186 // Make sure this packet should be delivered before returning it.
187 if (!connected_ || (real_remote_addr == remote_addr_)) {
188 if (out_addr)
189 *out_addr = real_remote_addr;
190 result = result - static_cast<int>(addrlength);
191 } else {
192 RTC_LOG(LS_ERROR) << "Dropping packet from unknown remote address: "
193 << real_remote_addr.ToString();
194 result = 0; // Tell the caller we didn't read anything
195 }
196 }
197
198 return result;
199 }
200
Close()201 int Close() override {
202 int result = 0;
203 if (socket_) {
204 result = socket_->Close();
205 if (result >= 0) {
206 connected_ = false;
207 remote_addr_ = SocketAddress();
208 delete socket_;
209 socket_ = nullptr;
210 }
211 }
212 return result;
213 }
214
Listen(int backlog)215 int Listen(int backlog) override { return socket_->Listen(backlog); }
Accept(SocketAddress * paddr)216 AsyncSocket* Accept(SocketAddress* paddr) override {
217 return socket_->Accept(paddr);
218 }
GetError() const219 int GetError() const override {
220 return socket_ ? socket_->GetError() : error_;
221 }
SetError(int error)222 void SetError(int error) override {
223 if (socket_) {
224 socket_->SetError(error);
225 } else {
226 error_ = error;
227 }
228 }
GetState() const229 ConnState GetState() const override {
230 return connected_ ? CS_CONNECTED : CS_CLOSED;
231 }
GetOption(Option opt,int * value)232 int GetOption(Option opt, int* value) override {
233 return socket_->GetOption(opt, value);
234 }
SetOption(Option opt,int value)235 int SetOption(Option opt, int value) override {
236 return socket_->SetOption(opt, value);
237 }
238
OnConnectEvent(AsyncSocket * socket)239 void OnConnectEvent(AsyncSocket* socket) {
240 // If we're NATed, we need to send a message with the real addr to use.
241 RTC_DCHECK(socket == socket_);
242 if (server_addr_.IsNil()) {
243 connected_ = true;
244 SignalConnectEvent(this);
245 } else {
246 SendConnectRequest();
247 }
248 }
OnReadEvent(AsyncSocket * socket)249 void OnReadEvent(AsyncSocket* socket) {
250 // If we're NATed, we need to process the connect reply.
251 RTC_DCHECK(socket == socket_);
252 if (type_ == SOCK_STREAM && !server_addr_.IsNil() && !connected_) {
253 HandleConnectReply();
254 } else {
255 SignalReadEvent(this);
256 }
257 }
OnWriteEvent(AsyncSocket * socket)258 void OnWriteEvent(AsyncSocket* socket) {
259 RTC_DCHECK(socket == socket_);
260 SignalWriteEvent(this);
261 }
OnCloseEvent(AsyncSocket * socket,int error)262 void OnCloseEvent(AsyncSocket* socket, int error) {
263 RTC_DCHECK(socket == socket_);
264 SignalCloseEvent(this, error);
265 }
266
267 private:
BindInternal(const SocketAddress & addr)268 int BindInternal(const SocketAddress& addr) {
269 RTC_DCHECK(!socket_);
270
271 int result;
272 socket_ = sf_->CreateInternalSocket(family_, type_, addr, &server_addr_);
273 result = (socket_) ? socket_->Bind(addr) : -1;
274 if (result >= 0) {
275 socket_->SignalConnectEvent.connect(this, &NATSocket::OnConnectEvent);
276 socket_->SignalReadEvent.connect(this, &NATSocket::OnReadEvent);
277 socket_->SignalWriteEvent.connect(this, &NATSocket::OnWriteEvent);
278 socket_->SignalCloseEvent.connect(this, &NATSocket::OnCloseEvent);
279 } else {
280 server_addr_.Clear();
281 delete socket_;
282 socket_ = nullptr;
283 }
284
285 return result;
286 }
287
288 // Makes sure the buffer is at least the given size.
Grow(size_t new_size)289 void Grow(size_t new_size) {
290 if (size_ < new_size) {
291 delete[] buf_;
292 size_ = new_size;
293 buf_ = new char[size_];
294 }
295 }
296
297 // Sends the destination address to the server to tell it to connect.
SendConnectRequest()298 void SendConnectRequest() {
299 char buf[kNATEncodedIPv6AddressSize];
300 size_t length = PackAddressForNAT(buf, arraysize(buf), remote_addr_);
301 socket_->Send(buf, length);
302 }
303
304 // Handles the byte sent back from the server and fires the appropriate event.
HandleConnectReply()305 void HandleConnectReply() {
306 char code;
307 socket_->Recv(&code, sizeof(code), nullptr);
308 if (code == 0) {
309 connected_ = true;
310 SignalConnectEvent(this);
311 } else {
312 Close();
313 SignalCloseEvent(this, code);
314 }
315 }
316
317 NATInternalSocketFactory* sf_;
318 int family_;
319 int type_;
320 bool connected_;
321 SocketAddress remote_addr_;
322 SocketAddress server_addr_; // address of the NAT server
323 AsyncSocket* socket_;
324 // Need to hold error in case it occurs before the socket is created.
325 int error_ = 0;
326 char* buf_;
327 size_t size_;
328 };
329
330 // NATSocketFactory
NATSocketFactory(SocketFactory * factory,const SocketAddress & nat_udp_addr,const SocketAddress & nat_tcp_addr)331 NATSocketFactory::NATSocketFactory(SocketFactory* factory,
332 const SocketAddress& nat_udp_addr,
333 const SocketAddress& nat_tcp_addr)
334 : factory_(factory),
335 nat_udp_addr_(nat_udp_addr),
336 nat_tcp_addr_(nat_tcp_addr) {}
337
CreateSocket(int family,int type)338 Socket* NATSocketFactory::CreateSocket(int family, int type) {
339 return new NATSocket(this, family, type);
340 }
341
CreateAsyncSocket(int family,int type)342 AsyncSocket* NATSocketFactory::CreateAsyncSocket(int family, int type) {
343 return new NATSocket(this, family, type);
344 }
345
CreateInternalSocket(int family,int type,const SocketAddress & local_addr,SocketAddress * nat_addr)346 AsyncSocket* NATSocketFactory::CreateInternalSocket(
347 int family,
348 int type,
349 const SocketAddress& local_addr,
350 SocketAddress* nat_addr) {
351 if (type == SOCK_STREAM) {
352 *nat_addr = nat_tcp_addr_;
353 } else {
354 *nat_addr = nat_udp_addr_;
355 }
356 return factory_->CreateAsyncSocket(family, type);
357 }
358
359 // NATSocketServer
NATSocketServer(SocketServer * server)360 NATSocketServer::NATSocketServer(SocketServer* server)
361 : server_(server), msg_queue_(nullptr) {}
362
GetTranslator(const SocketAddress & ext_ip)363 NATSocketServer::Translator* NATSocketServer::GetTranslator(
364 const SocketAddress& ext_ip) {
365 return nats_.Get(ext_ip);
366 }
367
AddTranslator(const SocketAddress & ext_ip,const SocketAddress & int_ip,NATType type)368 NATSocketServer::Translator* NATSocketServer::AddTranslator(
369 const SocketAddress& ext_ip,
370 const SocketAddress& int_ip,
371 NATType type) {
372 // Fail if a translator already exists with this extternal address.
373 if (nats_.Get(ext_ip))
374 return nullptr;
375
376 return nats_.Add(ext_ip, new Translator(this, type, int_ip, server_, ext_ip));
377 }
378
RemoveTranslator(const SocketAddress & ext_ip)379 void NATSocketServer::RemoveTranslator(const SocketAddress& ext_ip) {
380 nats_.Remove(ext_ip);
381 }
382
CreateSocket(int family,int type)383 Socket* NATSocketServer::CreateSocket(int family, int type) {
384 return new NATSocket(this, family, type);
385 }
386
CreateAsyncSocket(int family,int type)387 AsyncSocket* NATSocketServer::CreateAsyncSocket(int family, int type) {
388 return new NATSocket(this, family, type);
389 }
390
SetMessageQueue(Thread * queue)391 void NATSocketServer::SetMessageQueue(Thread* queue) {
392 msg_queue_ = queue;
393 server_->SetMessageQueue(queue);
394 }
395
Wait(int cms,bool process_io)396 bool NATSocketServer::Wait(int cms, bool process_io) {
397 return server_->Wait(cms, process_io);
398 }
399
WakeUp()400 void NATSocketServer::WakeUp() {
401 server_->WakeUp();
402 }
403
CreateInternalSocket(int family,int type,const SocketAddress & local_addr,SocketAddress * nat_addr)404 AsyncSocket* NATSocketServer::CreateInternalSocket(
405 int family,
406 int type,
407 const SocketAddress& local_addr,
408 SocketAddress* nat_addr) {
409 AsyncSocket* socket = nullptr;
410 Translator* nat = nats_.FindClient(local_addr);
411 if (nat) {
412 socket = nat->internal_factory()->CreateAsyncSocket(family, type);
413 *nat_addr = (type == SOCK_STREAM) ? nat->internal_tcp_address()
414 : nat->internal_udp_address();
415 } else {
416 socket = server_->CreateAsyncSocket(family, type);
417 }
418 return socket;
419 }
420
421 // NATSocketServer::Translator
Translator(NATSocketServer * server,NATType type,const SocketAddress & int_ip,SocketFactory * ext_factory,const SocketAddress & ext_ip)422 NATSocketServer::Translator::Translator(NATSocketServer* server,
423 NATType type,
424 const SocketAddress& int_ip,
425 SocketFactory* ext_factory,
426 const SocketAddress& ext_ip)
427 : server_(server) {
428 // Create a new private network, and a NATServer running on the private
429 // network that bridges to the external network. Also tell the private
430 // network to use the same message queue as us.
431 VirtualSocketServer* internal_server = new VirtualSocketServer();
432 internal_server->SetMessageQueue(server_->queue());
433 internal_factory_.reset(internal_server);
434 nat_server_.reset(new NATServer(type, internal_server, int_ip, int_ip,
435 ext_factory, ext_ip));
436 }
437
438 NATSocketServer::Translator::~Translator() = default;
439
GetTranslator(const SocketAddress & ext_ip)440 NATSocketServer::Translator* NATSocketServer::Translator::GetTranslator(
441 const SocketAddress& ext_ip) {
442 return nats_.Get(ext_ip);
443 }
444
AddTranslator(const SocketAddress & ext_ip,const SocketAddress & int_ip,NATType type)445 NATSocketServer::Translator* NATSocketServer::Translator::AddTranslator(
446 const SocketAddress& ext_ip,
447 const SocketAddress& int_ip,
448 NATType type) {
449 // Fail if a translator already exists with this extternal address.
450 if (nats_.Get(ext_ip))
451 return nullptr;
452
453 AddClient(ext_ip);
454 return nats_.Add(ext_ip,
455 new Translator(server_, type, int_ip, server_, ext_ip));
456 }
RemoveTranslator(const SocketAddress & ext_ip)457 void NATSocketServer::Translator::RemoveTranslator(
458 const SocketAddress& ext_ip) {
459 nats_.Remove(ext_ip);
460 RemoveClient(ext_ip);
461 }
462
AddClient(const SocketAddress & int_ip)463 bool NATSocketServer::Translator::AddClient(const SocketAddress& int_ip) {
464 // Fail if a client already exists with this internal address.
465 if (clients_.find(int_ip) != clients_.end())
466 return false;
467
468 clients_.insert(int_ip);
469 return true;
470 }
471
RemoveClient(const SocketAddress & int_ip)472 void NATSocketServer::Translator::RemoveClient(const SocketAddress& int_ip) {
473 std::set<SocketAddress>::iterator it = clients_.find(int_ip);
474 if (it != clients_.end()) {
475 clients_.erase(it);
476 }
477 }
478
FindClient(const SocketAddress & int_ip)479 NATSocketServer::Translator* NATSocketServer::Translator::FindClient(
480 const SocketAddress& int_ip) {
481 // See if we have the requested IP, or any of our children do.
482 return (clients_.find(int_ip) != clients_.end()) ? this
483 : nats_.FindClient(int_ip);
484 }
485
486 // NATSocketServer::TranslatorMap
~TranslatorMap()487 NATSocketServer::TranslatorMap::~TranslatorMap() {
488 for (TranslatorMap::iterator it = begin(); it != end(); ++it) {
489 delete it->second;
490 }
491 }
492
Get(const SocketAddress & ext_ip)493 NATSocketServer::Translator* NATSocketServer::TranslatorMap::Get(
494 const SocketAddress& ext_ip) {
495 TranslatorMap::iterator it = find(ext_ip);
496 return (it != end()) ? it->second : nullptr;
497 }
498
Add(const SocketAddress & ext_ip,Translator * nat)499 NATSocketServer::Translator* NATSocketServer::TranslatorMap::Add(
500 const SocketAddress& ext_ip,
501 Translator* nat) {
502 (*this)[ext_ip] = nat;
503 return nat;
504 }
505
Remove(const SocketAddress & ext_ip)506 void NATSocketServer::TranslatorMap::Remove(const SocketAddress& ext_ip) {
507 TranslatorMap::iterator it = find(ext_ip);
508 if (it != end()) {
509 delete it->second;
510 erase(it);
511 }
512 }
513
FindClient(const SocketAddress & int_ip)514 NATSocketServer::Translator* NATSocketServer::TranslatorMap::FindClient(
515 const SocketAddress& int_ip) {
516 Translator* nat = nullptr;
517 for (TranslatorMap::iterator it = begin(); it != end() && !nat; ++it) {
518 nat = it->second->FindClient(int_ip);
519 }
520 return nat;
521 }
522
523 } // namespace rtc
524