1/*
2 * libjingle
3 * Copyright 2011, 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
28#include "talk/p2p/base/basicpacketsocketfactory.h"
29
30#include "talk/p2p/base/asyncstuntcpsocket.h"
31#include "talk/p2p/base/stun.h"
32#include "webrtc/base/asynctcpsocket.h"
33#include "webrtc/base/asyncudpsocket.h"
34#include "webrtc/base/logging.h"
35#include "webrtc/base/nethelpers.h"
36#include "webrtc/base/physicalsocketserver.h"
37#include "webrtc/base/scoped_ptr.h"
38#include "webrtc/base/socketadapters.h"
39#include "webrtc/base/ssladapter.h"
40#include "webrtc/base/thread.h"
41
42namespace rtc {
43
44BasicPacketSocketFactory::BasicPacketSocketFactory()
45    : thread_(Thread::Current()),
46      socket_factory_(NULL) {
47}
48
49BasicPacketSocketFactory::BasicPacketSocketFactory(Thread* thread)
50    : thread_(thread),
51      socket_factory_(NULL) {
52}
53
54BasicPacketSocketFactory::BasicPacketSocketFactory(
55    SocketFactory* socket_factory)
56    : thread_(NULL),
57      socket_factory_(socket_factory) {
58}
59
60BasicPacketSocketFactory::~BasicPacketSocketFactory() {
61}
62
63AsyncPacketSocket* BasicPacketSocketFactory::CreateUdpSocket(
64    const SocketAddress& address, int min_port, int max_port) {
65  // UDP sockets are simple.
66  rtc::AsyncSocket* socket =
67      socket_factory()->CreateAsyncSocket(
68          address.family(), SOCK_DGRAM);
69  if (!socket) {
70    return NULL;
71  }
72  if (BindSocket(socket, address, min_port, max_port) < 0) {
73    LOG(LS_ERROR) << "UDP bind failed with error "
74                    << socket->GetError();
75    delete socket;
76    return NULL;
77  }
78  return new rtc::AsyncUDPSocket(socket);
79}
80
81AsyncPacketSocket* BasicPacketSocketFactory::CreateServerTcpSocket(
82    const SocketAddress& local_address, int min_port, int max_port, int opts) {
83
84  // Fail if TLS is required.
85  if (opts & PacketSocketFactory::OPT_TLS) {
86    LOG(LS_ERROR) << "TLS support currently is not available.";
87    return NULL;
88  }
89
90  rtc::AsyncSocket* socket =
91      socket_factory()->CreateAsyncSocket(local_address.family(),
92                                          SOCK_STREAM);
93  if (!socket) {
94    return NULL;
95  }
96
97  if (BindSocket(socket, local_address, min_port, max_port) < 0) {
98    LOG(LS_ERROR) << "TCP bind failed with error "
99                  << socket->GetError();
100    delete socket;
101    return NULL;
102  }
103
104  // If using SSLTCP, wrap the TCP socket in a pseudo-SSL socket.
105  if (opts & PacketSocketFactory::OPT_SSLTCP) {
106    ASSERT(!(opts & PacketSocketFactory::OPT_TLS));
107    socket = new rtc::AsyncSSLSocket(socket);
108  }
109
110  // Set TCP_NODELAY (via OPT_NODELAY) for improved performance.
111  // See http://go/gtalktcpnodelayexperiment
112  socket->SetOption(rtc::Socket::OPT_NODELAY, 1);
113
114  if (opts & PacketSocketFactory::OPT_STUN)
115    return new cricket::AsyncStunTCPSocket(socket, true);
116
117  return new rtc::AsyncTCPSocket(socket, true);
118}
119
120AsyncPacketSocket* BasicPacketSocketFactory::CreateClientTcpSocket(
121    const SocketAddress& local_address, const SocketAddress& remote_address,
122    const ProxyInfo& proxy_info, const std::string& user_agent, int opts) {
123
124  rtc::AsyncSocket* socket =
125      socket_factory()->CreateAsyncSocket(local_address.family(), SOCK_STREAM);
126  if (!socket) {
127    return NULL;
128  }
129
130  if (BindSocket(socket, local_address, 0, 0) < 0) {
131    LOG(LS_ERROR) << "TCP bind failed with error "
132                  << socket->GetError();
133    delete socket;
134    return NULL;
135  }
136
137  // If using a proxy, wrap the socket in a proxy socket.
138  if (proxy_info.type == rtc::PROXY_SOCKS5) {
139    socket = new rtc::AsyncSocksProxySocket(
140        socket, proxy_info.address, proxy_info.username, proxy_info.password);
141  } else if (proxy_info.type == rtc::PROXY_HTTPS) {
142    socket = new rtc::AsyncHttpsProxySocket(
143        socket, user_agent, proxy_info.address,
144        proxy_info.username, proxy_info.password);
145  }
146
147  // If using TLS, wrap the socket in an SSL adapter.
148  if (opts & PacketSocketFactory::OPT_TLS) {
149    ASSERT(!(opts & PacketSocketFactory::OPT_SSLTCP));
150
151    rtc::SSLAdapter* ssl_adapter = rtc::SSLAdapter::Create(socket);
152    if (!ssl_adapter) {
153      return NULL;
154    }
155
156    socket = ssl_adapter;
157
158    if (ssl_adapter->StartSSL(remote_address.hostname().c_str(), false) != 0) {
159      delete ssl_adapter;
160      return NULL;
161    }
162
163  // If using SSLTCP, wrap the TCP socket in a pseudo-SSL socket.
164  } else if (opts & PacketSocketFactory::OPT_SSLTCP) {
165    ASSERT(!(opts & PacketSocketFactory::OPT_TLS));
166    socket = new rtc::AsyncSSLSocket(socket);
167  }
168
169  if (socket->Connect(remote_address) < 0) {
170    LOG(LS_ERROR) << "TCP connect failed with error "
171                  << socket->GetError();
172    delete socket;
173    return NULL;
174  }
175
176  // Finally, wrap that socket in a TCP or STUN TCP packet socket.
177  AsyncPacketSocket* tcp_socket;
178  if (opts & PacketSocketFactory::OPT_STUN) {
179    tcp_socket = new cricket::AsyncStunTCPSocket(socket, false);
180  } else {
181    tcp_socket = new rtc::AsyncTCPSocket(socket, false);
182  }
183
184  // Set TCP_NODELAY (via OPT_NODELAY) for improved performance.
185  // See http://go/gtalktcpnodelayexperiment
186  tcp_socket->SetOption(rtc::Socket::OPT_NODELAY, 1);
187
188  return tcp_socket;
189}
190
191AsyncResolverInterface* BasicPacketSocketFactory::CreateAsyncResolver() {
192  return new rtc::AsyncResolver();
193}
194
195int BasicPacketSocketFactory::BindSocket(
196    AsyncSocket* socket, const SocketAddress& local_address,
197    int min_port, int max_port) {
198  int ret = -1;
199  if (min_port == 0 && max_port == 0) {
200    // If there's no port range, let the OS pick a port for us.
201    ret = socket->Bind(local_address);
202  } else {
203    // Otherwise, try to find a port in the provided range.
204    for (int port = min_port; ret < 0 && port <= max_port; ++port) {
205      ret = socket->Bind(rtc::SocketAddress(local_address.ipaddr(),
206                                                  port));
207    }
208  }
209  return ret;
210}
211
212SocketFactory* BasicPacketSocketFactory::socket_factory() {
213  if (thread_) {
214    ASSERT(thread_ == Thread::Current());
215    return thread_->socketserver();
216  } else {
217    return socket_factory_;
218  }
219}
220
221}  // namespace rtc
222