You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

505 lines
16 KiB

​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
  1. /*
  2. * libjingle
  3. * Copyright 2004--2005, Google Inc.
  4. *
  5. * Redistribution and use in source and binary forms, with or without
  6. * modification, are permitted provided that the following conditions are met:
  7. *
  8. * 1. Redistributions of source code must retain the above copyright notice,
  9. * this list of conditions and the following disclaimer.
  10. * 2. Redistributions in binary form must reproduce the above copyright notice,
  11. * this list of conditions and the following disclaimer in the documentation
  12. * and/or other materials provided with the distribution.
  13. * 3. The name of the author may not be used to endorse or promote products
  14. * derived from this software without specific prior written permission.
  15. *
  16. * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
  17. * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
  18. * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
  19. * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  20. * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
  21. * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
  22. * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
  23. * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
  24. * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
  25. * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  26. */
  27. #include "talk/base/natsocketfactory.h"
  28. #include "talk/base/logging.h"
  29. #include "talk/base/natserver.h"
  30. #include "talk/base/virtualsocketserver.h"
  31. namespace talk_base {
  32. // Packs the given socketaddress into the buffer in buf, in the quasi-STUN
  33. // format that the natserver uses.
  34. // Returns 0 if an invalid address is passed.
  35. size_t PackAddressForNAT(char* buf, size_t buf_size,
  36. const SocketAddress& remote_addr) {
  37. const IPAddress& ip = remote_addr.ipaddr();
  38. int family = ip.family();
  39. buf[0] = 0;
  40. buf[1] = family;
  41. // Writes the port.
  42. *(reinterpret_cast<uint16*>(&buf[2])) = HostToNetwork16(remote_addr.port());
  43. if (family == AF_INET) {
  44. ASSERT(buf_size >= kNATEncodedIPv4AddressSize);
  45. in_addr v4addr = ip.ipv4_address();
  46. std::memcpy(&buf[4], &v4addr, kNATEncodedIPv4AddressSize - 4);
  47. return kNATEncodedIPv4AddressSize;
  48. } else if (family == AF_INET6) {
  49. ASSERT(buf_size >= kNATEncodedIPv6AddressSize);
  50. in6_addr v6addr = ip.ipv6_address();
  51. std::memcpy(&buf[4], &v6addr, kNATEncodedIPv6AddressSize - 4);
  52. return kNATEncodedIPv6AddressSize;
  53. }
  54. return 0U;
  55. }
  56. // Decodes the remote address from a packet that has been encoded with the nat's
  57. // quasi-STUN format. Returns the length of the address (i.e., the offset into
  58. // data where the original packet starts).
  59. size_t UnpackAddressFromNAT(const char* buf, size_t buf_size,
  60. SocketAddress* remote_addr) {
  61. ASSERT(buf_size >= 8);
  62. ASSERT(buf[0] == 0);
  63. int family = buf[1];
  64. uint16 port = NetworkToHost16(*(reinterpret_cast<const uint16*>(&buf[2])));
  65. if (family == AF_INET) {
  66. const in_addr* v4addr = reinterpret_cast<const in_addr*>(&buf[4]);
  67. *remote_addr = SocketAddress(IPAddress(*v4addr), port);
  68. return kNATEncodedIPv4AddressSize;
  69. } else if (family == AF_INET6) {
  70. ASSERT(buf_size >= 20);
  71. const in6_addr* v6addr = reinterpret_cast<const in6_addr*>(&buf[4]);
  72. *remote_addr = SocketAddress(IPAddress(*v6addr), port);
  73. return kNATEncodedIPv6AddressSize;
  74. }
  75. return 0U;
  76. }
  77. // NATSocket
  78. class NATSocket : public AsyncSocket, public sigslot::has_slots<> {
  79. public:
  80. explicit NATSocket(NATInternalSocketFactory* sf, int family, int type)
  81. : sf_(sf), family_(family), type_(type), async_(true), connected_(false),
  82. socket_(NULL), buf_(NULL), size_(0) {
  83. }
  84. virtual ~NATSocket() {
  85. delete socket_;
  86. delete[] buf_;
  87. }
  88. virtual SocketAddress GetLocalAddress() const {
  89. return (socket_) ? socket_->GetLocalAddress() : SocketAddress();
  90. }
  91. virtual SocketAddress GetRemoteAddress() const {
  92. return remote_addr_; // will be NIL if not connected
  93. }
  94. virtual int Bind(const SocketAddress& addr) {
  95. if (socket_) { // already bound, bubble up error
  96. return -1;
  97. }
  98. int result;
  99. socket_ = sf_->CreateInternalSocket(family_, type_, addr, &server_addr_);
  100. result = (socket_) ? socket_->Bind(addr) : -1;
  101. if (result >= 0) {
  102. socket_->SignalConnectEvent.connect(this, &NATSocket::OnConnectEvent);
  103. socket_->SignalReadEvent.connect(this, &NATSocket::OnReadEvent);
  104. socket_->SignalWriteEvent.connect(this, &NATSocket::OnWriteEvent);
  105. socket_->SignalCloseEvent.connect(this, &NATSocket::OnCloseEvent);
  106. } else {
  107. server_addr_.Clear();
  108. delete socket_;
  109. socket_ = NULL;
  110. }
  111. return result;
  112. }
  113. virtual int Connect(const SocketAddress& addr) {
  114. if (!socket_) { // socket must be bound, for now
  115. return -1;
  116. }
  117. int result = 0;
  118. if (type_ == SOCK_STREAM) {
  119. result = socket_->Connect(server_addr_.IsNil() ? addr : server_addr_);
  120. } else {
  121. connected_ = true;
  122. }
  123. if (result >= 0) {
  124. remote_addr_ = addr;
  125. }
  126. return result;
  127. }
  128. virtual int Send(const void* data, size_t size) {
  129. ASSERT(connected_);
  130. return SendTo(data, size, remote_addr_);
  131. }
  132. virtual int SendTo(const void* data, size_t size, const SocketAddress& addr) {
  133. ASSERT(!connected_ || addr == remote_addr_);
  134. if (server_addr_.IsNil() || type_ == SOCK_STREAM) {
  135. return socket_->SendTo(data, size, addr);
  136. }
  137. // This array will be too large for IPv4 packets, but only by 12 bytes.
  138. scoped_array<char> buf(new char[size + kNATEncodedIPv6AddressSize]);
  139. size_t addrlength = PackAddressForNAT(buf.get(),
  140. size + kNATEncodedIPv6AddressSize,
  141. addr);
  142. size_t encoded_size = size + addrlength;
  143. std::memcpy(buf.get() + addrlength, data, size);
  144. int result = socket_->SendTo(buf.get(), encoded_size, server_addr_);
  145. if (result >= 0) {
  146. ASSERT(result == static_cast<int>(encoded_size));
  147. result = result - static_cast<int>(addrlength);
  148. }
  149. return result;
  150. }
  151. virtual int Recv(void* data, size_t size) {
  152. SocketAddress addr;
  153. return RecvFrom(data, size, &addr);
  154. }
  155. virtual int RecvFrom(void* data, size_t size, SocketAddress *out_addr) {
  156. if (server_addr_.IsNil() || type_ == SOCK_STREAM) {
  157. return socket_->RecvFrom(data, size, out_addr);
  158. }
  159. // Make sure we have enough room to read the requested amount plus the
  160. // largest possible header address.
  161. SocketAddress remote_addr;
  162. Grow(size + kNATEncodedIPv6AddressSize);
  163. // Read the packet from the socket.
  164. int result = socket_->RecvFrom(buf_, size_, &remote_addr);
  165. if (result >= 0) {
  166. ASSERT(remote_addr == server_addr_);
  167. // TODO: we need better framing so we know how many bytes we can
  168. // return before we need to read the next address. For UDP, this will be
  169. // fine as long as the reader always reads everything in the packet.
  170. ASSERT((size_t)result < size_);
  171. // Decode the wire packet into the actual results.
  172. SocketAddress real_remote_addr;
  173. size_t addrlength =
  174. UnpackAddressFromNAT(buf_, result, &real_remote_addr);
  175. std::memcpy(data, buf_ + addrlength, result - addrlength);
  176. // Make sure this packet should be delivered before returning it.
  177. if (!connected_ || (real_remote_addr == remote_addr_)) {
  178. if (out_addr)
  179. *out_addr = real_remote_addr;
  180. result = result - static_cast<int>(addrlength);
  181. } else {
  182. LOG(LS_ERROR) << "Dropping packet from unknown remote address: "
  183. << real_remote_addr.ToString();
  184. result = 0; // Tell the caller we didn't read anything
  185. }
  186. }
  187. return result;
  188. }
  189. virtual int Close() {
  190. int result = 0;
  191. if (socket_) {
  192. result = socket_->Close();
  193. if (result >= 0) {
  194. connected_ = false;
  195. remote_addr_ = SocketAddress();
  196. delete socket_;
  197. socket_ = NULL;
  198. }
  199. }
  200. return result;
  201. }
  202. virtual int Listen(int backlog) {
  203. return socket_->Listen(backlog);
  204. }
  205. virtual AsyncSocket* Accept(SocketAddress *paddr) {
  206. return socket_->Accept(paddr);
  207. }
  208. virtual int GetError() const {
  209. return socket_->GetError();
  210. }
  211. virtual void SetError(int error) {
  212. socket_->SetError(error);
  213. }
  214. virtual ConnState GetState() const {
  215. return connected_ ? CS_CONNECTED : CS_CLOSED;
  216. }
  217. virtual int EstimateMTU(uint16* mtu) {
  218. return socket_->EstimateMTU(mtu);
  219. }
  220. virtual int GetOption(Option opt, int* value) {
  221. return socket_->GetOption(opt, value);
  222. }
  223. virtual int SetOption(Option opt, int value) {
  224. return socket_->SetOption(opt, value);
  225. }
  226. void OnConnectEvent(AsyncSocket* socket) {
  227. // If we're NATed, we need to send a request with the real addr to use.
  228. ASSERT(socket == socket_);
  229. if (server_addr_.IsNil()) {
  230. connected_ = true;
  231. SignalConnectEvent(this);
  232. } else {
  233. SendConnectRequest();
  234. }
  235. }
  236. void OnReadEvent(AsyncSocket* socket) {
  237. // If we're NATed, we need to process the connect reply.
  238. ASSERT(socket == socket_);
  239. if (type_ == SOCK_STREAM && !server_addr_.IsNil() && !connected_) {
  240. HandleConnectReply();
  241. } else {
  242. SignalReadEvent(this);
  243. }
  244. }
  245. void OnWriteEvent(AsyncSocket* socket) {
  246. ASSERT(socket == socket_);
  247. SignalWriteEvent(this);
  248. }
  249. void OnCloseEvent(AsyncSocket* socket, int error) {
  250. ASSERT(socket == socket_);
  251. SignalCloseEvent(this, error);
  252. }
  253. private:
  254. // Makes sure the buffer is at least the given size.
  255. void Grow(size_t new_size) {
  256. if (size_ < new_size) {
  257. delete[] buf_;
  258. size_ = new_size;
  259. buf_ = new char[size_];
  260. }
  261. }
  262. // Sends the destination address to the server to tell it to connect.
  263. void SendConnectRequest() {
  264. char buf[256];
  265. size_t length = PackAddressForNAT(buf, ARRAY_SIZE(buf), remote_addr_);
  266. socket_->Send(buf, length);
  267. }
  268. // Handles the byte sent back from the server and fires the appropriate event.
  269. void HandleConnectReply() {
  270. char code;
  271. socket_->Recv(&code, sizeof(code));
  272. if (code == 0) {
  273. SignalConnectEvent(this);
  274. } else {
  275. Close();
  276. SignalCloseEvent(this, code);
  277. }
  278. }
  279. NATInternalSocketFactory* sf_;
  280. int family_;
  281. int type_;
  282. bool async_;
  283. bool connected_;
  284. SocketAddress remote_addr_;
  285. SocketAddress server_addr_; // address of the NAT server
  286. AsyncSocket* socket_;
  287. char* buf_;
  288. size_t size_;
  289. };
  290. // NATSocketFactory
  291. NATSocketFactory::NATSocketFactory(SocketFactory* factory,
  292. const SocketAddress& nat_addr)
  293. : factory_(factory), nat_addr_(nat_addr) {
  294. }
  295. Socket* NATSocketFactory::CreateSocket(int type) {
  296. return CreateSocket(AF_INET, type);
  297. }
  298. Socket* NATSocketFactory::CreateSocket(int family, int type) {
  299. return new NATSocket(this, family, type);
  300. }
  301. AsyncSocket* NATSocketFactory::CreateAsyncSocket(int type) {
  302. return CreateAsyncSocket(AF_INET, type);
  303. }
  304. AsyncSocket* NATSocketFactory::CreateAsyncSocket(int family, int type) {
  305. return new NATSocket(this, family, type);
  306. }
  307. AsyncSocket* NATSocketFactory::CreateInternalSocket(int family, int type,
  308. const SocketAddress& local_addr, SocketAddress* nat_addr) {
  309. *nat_addr = nat_addr_;
  310. return factory_->CreateAsyncSocket(family, type);
  311. }
  312. // NATSocketServer
  313. NATSocketServer::NATSocketServer(SocketServer* server)
  314. : server_(server), msg_queue_(NULL) {
  315. }
  316. NATSocketServer::Translator* NATSocketServer::GetTranslator(
  317. const SocketAddress& ext_ip) {
  318. return nats_.Get(ext_ip);
  319. }
  320. NATSocketServer::Translator* NATSocketServer::AddTranslator(
  321. const SocketAddress& ext_ip, const SocketAddress& int_ip, NATType type) {
  322. // Fail if a translator already exists with this extternal address.
  323. if (nats_.Get(ext_ip))
  324. return NULL;
  325. return nats_.Add(ext_ip, new Translator(this, type, int_ip, server_, ext_ip));
  326. }
  327. void NATSocketServer::RemoveTranslator(
  328. const SocketAddress& ext_ip) {
  329. nats_.Remove(ext_ip);
  330. }
  331. Socket* NATSocketServer::CreateSocket(int type) {
  332. return CreateSocket(AF_INET, type);
  333. }
  334. Socket* NATSocketServer::CreateSocket(int family, int type) {
  335. return new NATSocket(this, family, type);
  336. }
  337. AsyncSocket* NATSocketServer::CreateAsyncSocket(int type) {
  338. return CreateAsyncSocket(AF_INET, type);
  339. }
  340. AsyncSocket* NATSocketServer::CreateAsyncSocket(int family, int type) {
  341. return new NATSocket(this, family, type);
  342. }
  343. AsyncSocket* NATSocketServer::CreateInternalSocket(int family, int type,
  344. const SocketAddress& local_addr, SocketAddress* nat_addr) {
  345. AsyncSocket* socket = NULL;
  346. Translator* nat = nats_.FindClient(local_addr);
  347. if (nat) {
  348. socket = nat->internal_factory()->CreateAsyncSocket(family, type);
  349. *nat_addr = (type == SOCK_STREAM) ?
  350. nat->internal_tcp_address() : nat->internal_address();
  351. } else {
  352. socket = server_->CreateAsyncSocket(family, type);
  353. }
  354. return socket;
  355. }
  356. // NATSocketServer::Translator
  357. NATSocketServer::Translator::Translator(
  358. NATSocketServer* server, NATType type, const SocketAddress& int_ip,
  359. SocketFactory* ext_factory, const SocketAddress& ext_ip)
  360. : server_(server) {
  361. // Create a new private network, and a NATServer running on the private
  362. // network that bridges to the external network. Also tell the private
  363. // network to use the same message queue as us.
  364. VirtualSocketServer* internal_server = new VirtualSocketServer(server_);
  365. internal_server->SetMessageQueue(server_->queue());
  366. internal_factory_.reset(internal_server);
  367. nat_server_.reset(new NATServer(type, internal_server, int_ip,
  368. ext_factory, ext_ip));
  369. }
  370. NATSocketServer::Translator* NATSocketServer::Translator::GetTranslator(
  371. const SocketAddress& ext_ip) {
  372. return nats_.Get(ext_ip);
  373. }
  374. NATSocketServer::Translator* NATSocketServer::Translator::AddTranslator(
  375. const SocketAddress& ext_ip, const SocketAddress& int_ip, NATType type) {
  376. // Fail if a translator already exists with this extternal address.
  377. if (nats_.Get(ext_ip))
  378. return NULL;
  379. AddClient(ext_ip);
  380. return nats_.Add(ext_ip,
  381. new Translator(server_, type, int_ip, server_, ext_ip));
  382. }
  383. void NATSocketServer::Translator::RemoveTranslator(
  384. const SocketAddress& ext_ip) {
  385. nats_.Remove(ext_ip);
  386. RemoveClient(ext_ip);
  387. }
  388. bool NATSocketServer::Translator::AddClient(
  389. const SocketAddress& int_ip) {
  390. // Fail if a client already exists with this internal address.
  391. if (clients_.find(int_ip) != clients_.end())
  392. return false;
  393. clients_.insert(int_ip);
  394. return true;
  395. }
  396. void NATSocketServer::Translator::RemoveClient(
  397. const SocketAddress& int_ip) {
  398. std::set<SocketAddress>::iterator it = clients_.find(int_ip);
  399. if (it != clients_.end()) {
  400. clients_.erase(it);
  401. }
  402. }
  403. NATSocketServer::Translator* NATSocketServer::Translator::FindClient(
  404. const SocketAddress& int_ip) {
  405. // See if we have the requested IP, or any of our children do.
  406. return (clients_.find(int_ip) != clients_.end()) ?
  407. this : nats_.FindClient(int_ip);
  408. }
  409. // NATSocketServer::TranslatorMap
  410. NATSocketServer::TranslatorMap::~TranslatorMap() {
  411. for (TranslatorMap::iterator it = begin(); it != end(); ++it) {
  412. delete it->second;
  413. }
  414. }
  415. NATSocketServer::Translator* NATSocketServer::TranslatorMap::Get(
  416. const SocketAddress& ext_ip) {
  417. TranslatorMap::iterator it = find(ext_ip);
  418. return (it != end()) ? it->second : NULL;
  419. }
  420. NATSocketServer::Translator* NATSocketServer::TranslatorMap::Add(
  421. const SocketAddress& ext_ip, Translator* nat) {
  422. (*this)[ext_ip] = nat;
  423. return nat;
  424. }
  425. void NATSocketServer::TranslatorMap::Remove(
  426. const SocketAddress& ext_ip) {
  427. TranslatorMap::iterator it = find(ext_ip);
  428. if (it != end()) {
  429. delete it->second;
  430. erase(it);
  431. }
  432. }
  433. NATSocketServer::Translator* NATSocketServer::TranslatorMap::FindClient(
  434. const SocketAddress& int_ip) {
  435. Translator* nat = NULL;
  436. for (TranslatorMap::iterator it = begin(); it != end() && !nat; ++it) {
  437. nat = it->second->FindClient(int_ip);
  438. }
  439. return nat;
  440. }
  441. } // namespace talk_base