summaryrefslogtreecommitdiffstats
path: root/kopete/protocols/jabber/jingle/libjingle/talk/p2p/base/tcpport.cpp
blob: a2d2adc645da86cc0fb5f6c4e9c703c186d4638b (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
/*
 * libjingle
 * Copyright 2004--2005, Google Inc.
 *
 * Redistribution and use in source and binary forms, with or without 
 * modification, are permitted provided that the following conditions are met:
 *
 *  1. Redistributions of source code must retain the above copyright notice, 
 *     this list of conditions and the following disclaimer.
 *  2. Redistributions in binary form must reproduce the above copyright notice,
 *     this list of conditions and the following disclaimer in the documentation
 *     and/or other materials provided with the distribution.
 *  3. The name of the author may not be used to endorse or promote products 
 *     derived from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
 * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF 
 * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
 * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
 * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
 * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR 
 * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF 
 * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

#if defined(_MSC_VER) && _MSC_VER < 1300
#pragma warning(disable:4786)
#endif
#include "talk/p2p/base/tcpport.h"
#include "talk/base/logging.h"
#ifdef WIN32
#include "talk/base/winfirewall.h"
#endif // WIN32
#include <iostream>
#include <cassert>

#if defined(_MSC_VER) && _MSC_VER < 1300
namespace std {
  using ::strerror;
}
#endif

#ifdef POSIX
extern "C" {
#include <errno.h>
}
#endif // POSIX

namespace cricket {

#ifdef WIN32
static WinFirewall win_firewall;
#endif  // WIN32

TCPPort::TCPPort(Thread* thread, SocketFactory* factory, Network* network,
                 const SocketAddress& address)
    : Port(thread, LOCAL_PORT_TYPE, factory, network), error_(0) {
  incoming_only_ = (address.port() != 0);
  socket_ = thread->socketserver()->CreateAsyncSocket(SOCK_STREAM);
  socket_->SignalReadEvent.connect(this, &TCPPort::OnAcceptEvent);
  if (socket_->Bind(address) < 0)
    LOG(INFO) << "bind: " << std::strerror(socket_->GetError());
}

TCPPort::~TCPPort() {
  delete socket_;
}

Connection* TCPPort::CreateConnection(const Candidate& address, CandidateOrigin origin) {
  // We only support TCP protocols
  if ((address.protocol() != "tcp") && (address.protocol() != "ssltcp"))
    return 0;

  // We can't accept TCP connections incoming on other ports
  if (origin == ORIGIN_OTHER_PORT)
    return 0;

  // Check if we are allowed to make outgoing TCP connections
  if (incoming_only_ && (origin == ORIGIN_MESSAGE))
    return 0;

  // We don't know how to act as an ssl server yet
  if ((address.protocol() == "ssltcp") && (origin == ORIGIN_THIS_PORT))
    return 0;

  TCPConnection* conn = 0;
  if (AsyncTCPSocket * socket = GetIncoming(address.address(), true)) {
    socket->SignalReadPacket.disconnect(this);
    conn = new TCPConnection(this, address, socket);
  } else {
    conn = new TCPConnection(this, address);
  }
  AddConnection(conn);
  return conn;
}

void TCPPort::PrepareAddress() {
  assert(socket_);

  bool allow_listen = true;
#ifdef WIN32
  if (win_firewall.Initialize()) {
    char module_path[MAX_PATH + 1] = { 0 };
    ::GetModuleFileNameA(NULL, module_path, MAX_PATH);
    if (win_firewall.Enabled() && !win_firewall.Authorized(module_path)) {
      allow_listen = false;
    }
  }
#endif // WIN32
  if (allow_listen) {
    if (socket_->Listen(5) < 0)
      LOG(INFO) << "listen: " << std::strerror(socket_->GetError());
  } else {
    LOG(INFO) << "not listening due to firewall restrictions";
  }
  // Note: We still add the address, since otherwise the remote side won't recognize
  // our incoming TCP connections.
  add_address(socket_->GetLocalAddress(), "tcp");
}

int TCPPort::SendTo(const void* data, size_t size, const SocketAddress& addr, bool payload) {
  AsyncTCPSocket * socket = 0;

  if (TCPConnection * conn = static_cast<TCPConnection*>(GetConnection(addr))) {
    socket = conn->socket();
  } else {
    socket = GetIncoming(addr);
  }
  if (!socket) {
    LOG(INFO) << "Unknown destination for SendTo: " << addr.ToString();
    return -1; // TODO: Set error_
  }

  //LOG(INFO) << "TCPPort::SendTo(" << size << ", " << addr.ToString() << ")";

  int sent = socket->Send(data, size);
  if (sent < 0)
    error_ = socket->GetError();
  return sent;
}

int TCPPort::SetOption(Socket::Option opt, int value) {
  return socket_->SetOption(opt, value);
}

int TCPPort::GetError() {
  assert(socket_);
  return error_;
}

void TCPPort::OnAcceptEvent(AsyncSocket* socket) {
  assert(socket == socket_);

  Incoming incoming;
  AsyncSocket * newsocket = static_cast<AsyncSocket *>(socket->Accept(&incoming.addr));
  if (!newsocket) {
    // TODO: Do something better like forwarding the error to the user.
    LOG(INFO) << "accept: " << socket_->GetError() << " " <<  std::strerror(socket_->GetError());
    return;
  }
  incoming.socket = new AsyncTCPSocket(newsocket);
  incoming.socket->SignalReadPacket.connect(this, &TCPPort::OnReadPacket);

  LOG(INFO) << "accepted incoming connection from " << incoming.addr.ToString();
  incoming_.push_back(incoming);

  // Prime a read event in case data is waiting
  newsocket->SignalReadEvent(newsocket);
}

AsyncTCPSocket * TCPPort::GetIncoming(const SocketAddress& addr, bool remove) {
  AsyncTCPSocket * socket = 0;
  for (std::list<Incoming>::iterator it = incoming_.begin(); it != incoming_.end(); ++it) {
    if (it->addr == addr) {
      socket = it->socket;
      if (remove)
        incoming_.erase(it);
      break;
    }
  }
  return socket;
}

void TCPPort::OnReadPacket(const char* data, size_t size, const SocketAddress& remote_addr,
      AsyncPacketSocket* socket) {
  Port::OnReadPacket(data, size, remote_addr);
}

TCPConnection::TCPConnection(TCPPort* port, const Candidate& candidate, AsyncTCPSocket* socket)
    : Connection(port, 0, candidate), socket_(socket), error_(0) {
  bool outgoing = (socket_ == 0);
  if (outgoing) {
    socket_ = static_cast<AsyncTCPSocket *>(port->CreatePacketSocket(
                (candidate.protocol() == "ssltcp") ? PROTO_SSLTCP : PROTO_TCP));
  }
  socket_->SignalReadPacket.connect(this, &TCPConnection::OnReadPacket);
  socket_->SignalClose.connect(this, &TCPConnection::OnClose);
  if (outgoing) {
    connected_ = false;
    socket_->SignalConnect.connect(this, &TCPConnection::OnConnect);
    socket_->Connect(candidate.address());
    LOG(INFO) << "Connecting to " << candidate.address().ToString();
  }
}

TCPConnection::~TCPConnection() {
}

int TCPConnection::Send(const void* data, size_t size) {
  if (write_state() != STATE_WRITABLE)
    return 0;

  int sent = socket_->Send(data, size);
  if (sent < 0) {
    error_ = socket_->GetError();
  } else {
    sent_total_bytes_ += sent;
  }
  return sent;
}

int TCPConnection::GetError() {
  return error_;
}

TCPPort* TCPConnection::tcpport() {
  return static_cast<TCPPort*>(port_);
}

void TCPConnection::OnConnect(AsyncTCPSocket* socket) {
  assert(socket == socket_);
  LOG(INFO) << "tcp connected to " << socket->GetRemoteAddress().ToString();
  set_connected(true);
}

void TCPConnection::OnClose(AsyncTCPSocket* socket, int error) {
  assert(socket == socket_);
  LOG(INFO) << "tcp closed with error: " << error;
  set_connected(false);
}

void TCPConnection::OnReadPacket(const char* data, size_t size, const SocketAddress& remote_addr,
      AsyncPacketSocket* socket) {
  assert(socket == socket_);
  Connection::OnReadPacket(data, size);
}

} // namespace cricket