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
28#include "talk/base/proxyserver.h"
29
30#include <algorithm>
31#include "talk/base/socketfactory.h"
32
33namespace talk_base {
34
35// ProxyServer
36ProxyServer::ProxyServer(
37    SocketFactory* int_factory, const SocketAddress& int_addr,
38    SocketFactory* ext_factory, const SocketAddress& ext_ip)
39    : ext_factory_(ext_factory), ext_ip_(ext_ip.ipaddr(), 0),  // strip off port
40      server_socket_(int_factory->CreateAsyncSocket(int_addr.family(),
41                                                    SOCK_STREAM)) {
42  ASSERT(server_socket_.get() != NULL);
43  ASSERT(int_addr.family() == AF_INET || int_addr.family() == AF_INET6);
44  server_socket_->Bind(int_addr);
45  server_socket_->Listen(5);
46  server_socket_->SignalReadEvent.connect(this, &ProxyServer::OnAcceptEvent);
47}
48
49ProxyServer::~ProxyServer() {
50  for (BindingList::iterator it = bindings_.begin();
51       it != bindings_.end(); ++it) {
52    delete (*it);
53  }
54}
55
56void ProxyServer::OnAcceptEvent(AsyncSocket* socket) {
57  ASSERT(socket != NULL && socket == server_socket_.get());
58  AsyncSocket* int_socket = socket->Accept(NULL);
59  AsyncProxyServerSocket* wrapped_socket = WrapSocket(int_socket);
60  AsyncSocket* ext_socket = ext_factory_->CreateAsyncSocket(ext_ip_.family(),
61                                                            SOCK_STREAM);
62  if (ext_socket) {
63    ext_socket->Bind(ext_ip_);
64    bindings_.push_back(new ProxyBinding(wrapped_socket, ext_socket));
65  } else {
66    LOG(LS_ERROR) << "Unable to create external socket on proxy accept event";
67  }
68}
69
70void ProxyServer::OnBindingDestroyed(ProxyBinding* binding) {
71  BindingList::iterator it =
72      std::find(bindings_.begin(), bindings_.end(), binding);
73  delete (*it);
74  bindings_.erase(it);
75}
76
77// ProxyBinding
78ProxyBinding::ProxyBinding(AsyncProxyServerSocket* int_socket,
79                           AsyncSocket* ext_socket)
80    : int_socket_(int_socket), ext_socket_(ext_socket), connected_(false),
81      out_buffer_(kBufferSize), in_buffer_(kBufferSize) {
82  int_socket_->SignalConnectRequest.connect(this,
83                                            &ProxyBinding::OnConnectRequest);
84  int_socket_->SignalReadEvent.connect(this, &ProxyBinding::OnInternalRead);
85  int_socket_->SignalWriteEvent.connect(this, &ProxyBinding::OnInternalWrite);
86  int_socket_->SignalCloseEvent.connect(this, &ProxyBinding::OnInternalClose);
87  ext_socket_->SignalConnectEvent.connect(this,
88                                          &ProxyBinding::OnExternalConnect);
89  ext_socket_->SignalReadEvent.connect(this, &ProxyBinding::OnExternalRead);
90  ext_socket_->SignalWriteEvent.connect(this, &ProxyBinding::OnExternalWrite);
91  ext_socket_->SignalCloseEvent.connect(this, &ProxyBinding::OnExternalClose);
92}
93
94void ProxyBinding::OnConnectRequest(AsyncProxyServerSocket* socket,
95                                   const SocketAddress& addr) {
96  ASSERT(!connected_ && ext_socket_.get() != NULL);
97  ext_socket_->Connect(addr);
98  // TODO: handle errors here
99}
100
101void ProxyBinding::OnInternalRead(AsyncSocket* socket) {
102  Read(int_socket_.get(), &out_buffer_);
103  Write(ext_socket_.get(), &out_buffer_);
104}
105
106void ProxyBinding::OnInternalWrite(AsyncSocket* socket) {
107  Write(int_socket_.get(), &in_buffer_);
108}
109
110void ProxyBinding::OnInternalClose(AsyncSocket* socket, int err) {
111  Destroy();
112}
113
114void ProxyBinding::OnExternalConnect(AsyncSocket* socket) {
115  ASSERT(socket != NULL);
116  connected_ = true;
117  int_socket_->SendConnectResult(0, socket->GetRemoteAddress());
118}
119
120void ProxyBinding::OnExternalRead(AsyncSocket* socket) {
121  Read(ext_socket_.get(), &in_buffer_);
122  Write(int_socket_.get(), &in_buffer_);
123}
124
125void ProxyBinding::OnExternalWrite(AsyncSocket* socket) {
126  Write(ext_socket_.get(), &out_buffer_);
127}
128
129void ProxyBinding::OnExternalClose(AsyncSocket* socket, int err) {
130  if (!connected_) {
131    int_socket_->SendConnectResult(err, SocketAddress());
132  }
133  Destroy();
134}
135
136void ProxyBinding::Read(AsyncSocket* socket, FifoBuffer* buffer) {
137  // Only read if the buffer is empty.
138  ASSERT(socket != NULL);
139  size_t size;
140  int read;
141  if (buffer->GetBuffered(&size) && size == 0) {
142    void* p = buffer->GetWriteBuffer(&size);
143    read = socket->Recv(p, size);
144    buffer->ConsumeWriteBuffer(_max(read, 0));
145  }
146}
147
148void ProxyBinding::Write(AsyncSocket* socket, FifoBuffer* buffer) {
149  ASSERT(socket != NULL);
150  size_t size;
151  int written;
152  const void* p = buffer->GetReadData(&size);
153  written = socket->Send(p, size);
154  buffer->ConsumeReadData(_max(written, 0));
155}
156
157void ProxyBinding::Destroy() {
158  SignalDestroyed(this);
159}
160
161}  // namespace talk_base
162