added port window and port range options
[anytun.git] / Sockets / TcpSocket.cpp
blob960ac35da782e816f16b7d31f9609f96392f2bda
1 /** \file TcpSocket.cpp
2 ** \date 2004-02-13
3 ** \author grymse@alhem.net
4 **/
5 /*
6 Copyright (C) 2004-2007 Anders Hedstrom
8 This library is made available under the terms of the GNU GPL.
10 If you would like to use this library in a closed-source application,
11 a separate license agreement is available. For information about
12 the closed-source license agreement for the C++ sockets library,
13 please visit http://www.alhem.net/Sockets/license.html and/or
14 email license@alhem.net.
16 This program is free software; you can redistribute it and/or
17 modify it under the terms of the GNU General Public License
18 as published by the Free Software Foundation; either version 2
19 of the License, or (at your option) any later version.
21 This program is distributed in the hope that it will be useful,
22 but WITHOUT ANY WARRANTY; without even the implied warranty of
23 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
24 GNU General Public License for more details.
26 You should have received a copy of the GNU General Public License
27 along with this program; if not, write to the Free Software
28 Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
30 #ifdef _WIN32
31 #ifdef _MSC_VER
32 #pragma warning(disable:4786)
33 #endif
34 #include <stdlib.h>
35 #else
36 #include <errno.h>
37 #endif
38 #include "ISocketHandler.h"
39 #include <fcntl.h>
40 #include <assert.h>
41 #include <stdarg.h>
42 #ifdef HAVE_OPENSSL
43 #include <openssl/rand.h>
44 #include <openssl/err.h>
45 #endif
47 #include "TcpSocket.h"
48 #include "Utility.h"
49 #include "Ipv4Address.h"
50 #include "Ipv6Address.h"
51 #include "Mutex.h"
52 #include "IFile.h"
54 #ifdef SOCKETS_NAMESPACE
55 namespace SOCKETS_NAMESPACE {
56 #endif
59 #ifdef _DEBUG
60 #define DEB(x) x
61 #else
62 #define DEB(x)
63 #endif
66 // statics
67 #ifdef HAVE_OPENSSL
68 SSLInitializer TcpSocket::m_ssl_init;
69 #endif
72 // thanks, q
73 #ifdef _MSC_VER
74 #pragma warning(disable:4355)
75 #endif
76 TcpSocket::TcpSocket(ISocketHandler& h) : StreamSocket(h)
77 ,ibuf(TCP_BUFSIZE_READ)
78 ,m_b_input_buffer_disabled(false)
79 ,m_bytes_sent(0)
80 ,m_bytes_received(0)
81 ,m_skip_c(false)
82 #ifdef SOCKETS_DYNAMIC_TEMP
83 ,m_buf(new char[TCP_BUFSIZE_READ + 1])
84 #endif
85 ,m_obuf_top(NULL)
86 ,m_transfer_limit(0)
87 ,m_output_length(0)
88 #ifdef HAVE_OPENSSL
89 ,m_ssl_ctx(NULL)
90 ,m_ssl(NULL)
91 ,m_sbio(NULL)
92 #endif
93 #ifdef ENABLE_SOCKS4
94 ,m_socks4_state(0)
95 #endif
96 #ifdef ENABLE_RESOLVER
97 ,m_resolver_id(0)
98 #endif
99 #ifdef ENABLE_RECONNECT
100 ,m_b_reconnect(false)
101 ,m_b_is_reconnect(false)
102 #endif
105 #ifdef _MSC_VER
106 #pragma warning(default:4355)
107 #endif
110 #ifdef _MSC_VER
111 #pragma warning(disable:4355)
112 #endif
113 TcpSocket::TcpSocket(ISocketHandler& h,size_t isize,size_t osize) : StreamSocket(h)
114 ,ibuf(isize)
115 ,m_b_input_buffer_disabled(false)
116 ,m_bytes_sent(0)
117 ,m_bytes_received(0)
118 ,m_skip_c(false)
119 #ifdef SOCKETS_DYNAMIC_TEMP
120 ,m_buf(new char[TCP_BUFSIZE_READ + 1])
121 #endif
122 ,m_obuf_top(NULL)
123 ,m_transfer_limit(0)
124 ,m_output_length(0)
125 #ifdef HAVE_OPENSSL
126 ,m_ssl_ctx(NULL)
127 ,m_ssl(NULL)
128 ,m_sbio(NULL)
129 #endif
130 #ifdef ENABLE_SOCKS4
131 ,m_socks4_state(0)
132 #endif
133 #ifdef ENABLE_RESOLVER
134 ,m_resolver_id(0)
135 #endif
136 #ifdef ENABLE_RECONNECT
137 ,m_b_reconnect(false)
138 ,m_b_is_reconnect(false)
139 #endif
142 #ifdef _MSC_VER
143 #pragma warning(default:4355)
144 #endif
147 TcpSocket::~TcpSocket()
149 #ifdef SOCKETS_DYNAMIC_TEMP
150 delete[] m_buf;
151 #endif
152 // %! empty m_obuf
153 #ifdef HAVE_OPENSSL
154 if (m_ssl)
156 SSL_free(m_ssl);
158 #endif
162 bool TcpSocket::Open(ipaddr_t ip,port_t port,bool skip_socks)
164 Ipv4Address ad(ip, port);
165 Ipv4Address local;
166 return Open(ad, local, skip_socks);
170 #ifdef ENABLE_IPV6
171 #ifdef IPPROTO_IPV6
172 bool TcpSocket::Open(in6_addr ip,port_t port,bool skip_socks)
174 Ipv6Address ad(ip, port);
175 return Open(ad, skip_socks);
177 #endif
178 #endif
181 bool TcpSocket::Open(SocketAddress& ad,bool skip_socks)
183 Ipv4Address bind_ad("0.0.0.0", 0);
184 return Open(ad, bind_ad, skip_socks);
188 bool TcpSocket::Open(SocketAddress& ad,SocketAddress& bind_ad,bool skip_socks)
190 if (!ad.IsValid())
192 Handler().LogError(this, "Open", 0, "Invalid SocketAddress", LOG_LEVEL_FATAL);
193 SetCloseAndDelete();
194 return false;
196 if (Handler().GetCount() >= FD_SETSIZE)
198 Handler().LogError(this, "Open", 0, "no space left in fd_set", LOG_LEVEL_FATAL);
199 SetCloseAndDelete();
200 return false;
202 SetConnecting(false);
203 #ifdef ENABLE_SOCKS4
204 SetSocks4(false);
205 #endif
206 // check for pooling
207 #ifdef ENABLE_POOL
208 if (Handler().PoolEnabled())
210 ISocketHandler::PoolSocket *pools = Handler().FindConnection(SOCK_STREAM, "tcp", ad);
211 if (pools)
213 CopyConnection( pools );
214 delete pools;
216 SetIsClient();
217 SetCallOnConnect(); // ISocketHandler must call OnConnect
218 Handler().LogError(this, "SetCallOnConnect", 0, "Found pooled connection", LOG_LEVEL_INFO);
219 return true;
222 #endif
223 // if not, create new connection
224 SOCKET s = CreateSocket(ad.GetFamily(), SOCK_STREAM, "tcp");
225 if (s == INVALID_SOCKET)
227 return false;
229 // socket must be nonblocking for async connect
230 if (!SetNonblocking(true, s))
232 SetCloseAndDelete();
233 closesocket(s);
234 return false;
236 #ifdef ENABLE_POOL
237 SetIsClient(); // client because we connect
238 #endif
239 SetClientRemoteAddress(ad);
240 int n = 0;
241 if (bind_ad.GetPort() != 0)
243 bind(s, bind_ad, bind_ad);
245 #ifdef ENABLE_SOCKS4
246 if (!skip_socks && GetSocks4Host() && GetSocks4Port())
248 Ipv4Address sa(GetSocks4Host(), GetSocks4Port());
250 std::string sockshost;
251 Utility::l2ip(GetSocks4Host(), sockshost);
252 Handler().LogError(this, "Open", 0, "Connecting to socks4 server @ " + sockshost + ":" +
253 Utility::l2string(GetSocks4Port()), LOG_LEVEL_INFO);
255 SetSocks4();
256 n = connect(s, sa, sa);
257 SetRemoteAddress(sa);
259 else
260 #endif
262 n = connect(s, ad, ad);
263 SetRemoteAddress(ad);
265 if (n == -1)
267 // check error code that means a connect is in progress
268 #ifdef _WIN32
269 if (Errno == WSAEWOULDBLOCK)
270 #else
271 if (Errno == EINPROGRESS)
272 #endif
274 Attach(s);
275 SetConnecting( true ); // this flag will control fd_set's
277 else
278 #ifdef ENABLE_SOCKS4
279 if (Socks4() && Handler().Socks4TryDirect() ) // retry
281 closesocket(s);
282 return Open(ad, true);
284 else
285 #endif
286 #ifdef ENABLE_RECONNECT
287 if (Reconnect())
289 Handler().LogError(this, "connect: failed, reconnect pending", Errno, StrError(Errno), LOG_LEVEL_INFO);
290 Attach(s);
291 SetConnecting( true ); // this flag will control fd_set's
293 else
294 #endif
296 Handler().LogError(this, "connect: failed", Errno, StrError(Errno), LOG_LEVEL_FATAL);
297 SetCloseAndDelete();
298 closesocket(s);
299 return false;
302 else
304 Attach(s);
305 SetCallOnConnect(); // ISocketHandler must call OnConnect
308 // 'true' means connected or connecting(not yet connected)
309 // 'false' means something failed
310 return true; //!Connecting();
314 bool TcpSocket::Open(const std::string &host,port_t port)
316 #ifdef ENABLE_IPV6
317 #ifdef IPPROTO_IPV6
318 if (IsIpv6())
320 #ifdef ENABLE_RESOLVER
321 if (!Handler().ResolverEnabled() || Utility::isipv6(host) )
323 #endif
324 in6_addr a;
325 if (!Utility::u2ip(host, a))
327 SetCloseAndDelete();
328 return false;
330 Ipv6Address ad(a, port);
331 Ipv6Address local;
332 return Open(ad, local);
333 #ifdef ENABLE_RESOLVER
335 m_resolver_id = Resolve6(host, port);
336 return true;
337 #endif
339 #endif
340 #endif
341 #ifdef ENABLE_RESOLVER
342 if (!Handler().ResolverEnabled() || Utility::isipv4(host) )
344 #endif
345 ipaddr_t l;
346 if (!Utility::u2ip(host,l))
348 SetCloseAndDelete();
349 return false;
351 Ipv4Address ad(l, port);
352 Ipv4Address local;
353 return Open(ad, local);
354 #ifdef ENABLE_RESOLVER
356 // resolve using async resolver thread
357 m_resolver_id = Resolve(host, port);
358 return true;
359 #endif
363 #ifdef ENABLE_RESOLVER
364 void TcpSocket::OnResolved(int id,ipaddr_t a,port_t port)
366 DEB( fprintf(stderr, "TcpSocket::OnResolved id %d addr %x port %d\n", id, a, port);)
367 if (id == m_resolver_id)
369 if (a && port)
371 Ipv4Address ad(a, port);
372 Ipv4Address local;
373 if (Open(ad, local))
375 if (!Handler().Valid(this))
377 Handler().Add(this);
381 else
383 Handler().LogError(this, "OnResolved", 0, "Resolver failed", LOG_LEVEL_FATAL);
384 SetCloseAndDelete();
387 else
389 Handler().LogError(this, "OnResolved", id, "Resolver returned wrong job id", LOG_LEVEL_FATAL);
390 SetCloseAndDelete();
395 #ifdef ENABLE_IPV6
396 void TcpSocket::OnResolved(int id,in6_addr& a,port_t port)
398 if (id == m_resolver_id)
400 Ipv6Address ad(a, port);
401 if (ad.IsValid())
403 Ipv6Address local;
404 if (Open(ad, local))
406 if (!Handler().Valid(this))
408 Handler().Add(this);
413 else
415 Handler().LogError(this, "OnResolved", id, "Resolver returned wrong job id", LOG_LEVEL_FATAL);
416 SetCloseAndDelete();
419 #endif
420 #endif
423 void TcpSocket::OnRead()
425 int n = 0;
426 #ifdef SOCKETS_DYNAMIC_TEMP
427 char *buf = m_buf;
428 #else
429 char buf[TCP_BUFSIZE_READ];
430 #endif
431 #ifdef HAVE_OPENSSL
432 if (IsSSL())
434 if (!Ready())
435 return;
436 n = SSL_read(m_ssl, buf, TCP_BUFSIZE_READ);
437 if (n == -1)
439 n = SSL_get_error(m_ssl, n);
440 switch (n)
442 case SSL_ERROR_NONE:
443 case SSL_ERROR_WANT_READ:
444 case SSL_ERROR_WANT_WRITE:
445 break;
446 case SSL_ERROR_ZERO_RETURN:
447 DEB( fprintf(stderr, "SSL_read() returns zero - closing socket\n");)
448 OnDisconnect();
449 SetCloseAndDelete(true);
450 SetFlushBeforeClose(false);
451 #ifdef ENABLE_POOL
452 SetLost();
453 #endif
454 break;
455 default:
456 DEB( fprintf(stderr, "SSL read problem, errcode = %d\n",n);)
457 OnDisconnect();
458 SetCloseAndDelete(true);
459 SetFlushBeforeClose(false);
460 #ifdef ENABLE_POOL
461 SetLost();
462 #endif
464 return;
466 else
467 if (!n)
469 OnDisconnect();
470 SetCloseAndDelete(true);
471 SetFlushBeforeClose(false);
472 #ifdef ENABLE_POOL
473 SetLost();
474 #endif
475 SetShutdown(SHUT_WR);
476 return;
478 else
479 if (n > 0 && n <= TCP_BUFSIZE_READ)
481 m_bytes_received += n;
482 if (GetTrafficMonitor())
484 GetTrafficMonitor() -> fwrite(buf, 1, n);
486 if (!m_b_input_buffer_disabled && !ibuf.Write(buf,n))
488 Handler().LogError(this, "OnRead(ssl)", 0, "ibuf overflow", LOG_LEVEL_WARNING);
491 else
493 Handler().LogError(this, "OnRead(ssl)", n, "abnormal value from SSL_read", LOG_LEVEL_ERROR);
496 else
497 #endif // HAVE_OPENSSL
499 n = recv(GetSocket(), buf, TCP_BUFSIZE_READ, MSG_NOSIGNAL);
500 if (n == -1)
502 Handler().LogError(this, "read", Errno, StrError(Errno), LOG_LEVEL_FATAL);
503 OnDisconnect();
504 SetCloseAndDelete(true);
505 SetFlushBeforeClose(false);
506 #ifdef ENABLE_POOL
507 SetLost();
508 #endif
509 return;
511 else
512 if (!n)
514 OnDisconnect();
515 SetCloseAndDelete(true);
516 SetFlushBeforeClose(false);
517 #ifdef ENABLE_POOL
518 SetLost();
519 #endif
520 SetShutdown(SHUT_WR);
521 return;
523 else
524 if (n > 0 && n <= TCP_BUFSIZE_READ)
526 m_bytes_received += n;
527 if (GetTrafficMonitor())
529 GetTrafficMonitor() -> fwrite(buf, 1, n);
531 if (!m_b_input_buffer_disabled && !ibuf.Write(buf,n))
533 Handler().LogError(this, "OnRead", 0, "ibuf overflow", LOG_LEVEL_WARNING);
536 else
538 Handler().LogError(this, "OnRead", n, "abnormal value from recv", LOG_LEVEL_ERROR);
542 OnRead( buf, n );
546 void TcpSocket::OnRead( char *buf, size_t n )
548 // unbuffered
549 if (n > 0 && n <= TCP_BUFSIZE_READ)
551 if (LineProtocol())
553 buf[n] = 0;
554 size_t i = 0;
555 if (m_skip_c && (buf[i] == 13 || buf[i] == 10) && buf[i] != m_c)
557 m_skip_c = false;
558 i++;
560 size_t x = i;
561 for (; i < n && LineProtocol(); i++)
563 while ((buf[i] == 13 || buf[i] == 10) && LineProtocol())
565 char c = buf[i];
566 buf[i] = 0;
567 if (buf[x])
569 m_line += (buf + x);
571 OnLine( m_line );
572 i++;
573 m_skip_c = true;
574 m_c = c;
575 if (i < n && (buf[i] == 13 || buf[i] == 10) && buf[i] != c)
577 m_skip_c = false;
578 i++;
580 x = i;
581 m_line = "";
583 if (!LineProtocol())
585 break;
588 if (!LineProtocol())
590 if (i < n)
592 OnRawData(buf + i, n - i);
595 else
596 if (buf[x])
598 m_line += (buf + x);
601 else
603 OnRawData(buf, n);
606 if (m_b_input_buffer_disabled)
608 return;
610 // further processing: socks4
611 #ifdef ENABLE_SOCKS4
612 if (Socks4())
614 bool need_more = false;
615 while (GetInputLength() && !need_more && !CloseAndDelete())
617 need_more = OnSocks4Read();
620 #endif
624 void TcpSocket::OnWriteComplete()
629 void TcpSocket::OnWrite()
631 if (Connecting())
633 int err = SoError();
635 // don't reset connecting flag on error here, we want the OnConnectFailed timeout later on
636 if (!err) // ok
638 Set(!IsDisableRead(), false);
639 SetConnecting(false);
640 SetCallOnConnect();
641 return;
643 Handler().LogError(this, "tcp: connect failed", err, StrError(err), LOG_LEVEL_FATAL);
644 Set(false, false); // no more monitoring because connection failed
646 // failed
647 #ifdef ENABLE_SOCKS4
648 if (Socks4())
650 // %! leave 'Connecting' flag set?
651 OnSocks4ConnectFailed();
652 return;
654 #endif
655 if (GetConnectionRetry() == -1 ||
656 (GetConnectionRetry() && GetConnectionRetries() < GetConnectionRetry()) )
658 // even though the connection failed at once, only retry after
659 // the connection timeout.
660 // should we even try to connect again, when CheckConnect returns
661 // false it's because of a connection error - not a timeout...
662 return;
664 SetConnecting(false);
665 SetCloseAndDelete( true );
666 /// \todo state reason why connect failed
667 OnConnectFailed();
668 return;
670 // try send next block in buffer
671 // if full block is sent, repeat
672 // if all blocks are sent, reset m_wfds
674 bool repeat = false;
675 size_t sz = m_transfer_limit ? GetOutputLength() : 0;
678 output_l::iterator it = m_obuf.begin();
679 OUTPUT *p = *it;
680 repeat = false;
681 int n = TryWrite(p -> Buf(), p -> Len());
682 if (n > 0)
684 size_t left = p -> Remove(n);
685 m_output_length -= n;
686 if (!left)
688 delete p;
689 m_obuf.erase(it);
690 if (!m_obuf.size())
692 m_obuf_top = NULL;
693 OnWriteComplete();
695 else
697 repeat = true;
701 } while (repeat);
703 if (m_transfer_limit && sz > m_transfer_limit && GetOutputLength() < m_transfer_limit)
705 OnTransferLimit();
708 // check output buffer set, set/reset m_wfds accordingly
710 bool br;
711 bool bw;
712 bool bx;
713 Handler().Get(GetSocket(), br, bw, bx);
714 if (m_obuf.size())
715 Set(br, true);
716 else
717 Set(br, false);
722 int TcpSocket::TryWrite(const char *buf, size_t len)
724 int n = 0;
725 #ifdef HAVE_OPENSSL
726 if (IsSSL())
728 n = SSL_write(m_ssl, buf, (int)len);
729 if (n == -1)
731 int errnr = SSL_get_error(m_ssl, n);
732 if ( errnr != SSL_ERROR_WANT_READ && errnr != SSL_ERROR_WANT_WRITE )
734 OnDisconnect();
735 SetCloseAndDelete(true);
736 SetFlushBeforeClose(false);
737 #ifdef ENABLE_POOL
738 SetLost();
739 #endif
740 const char *errbuf = ERR_error_string(errnr, NULL);
741 Handler().LogError(this, "OnWrite/SSL_write", errnr, errbuf, LOG_LEVEL_FATAL);
743 return 0;
745 else
746 if (!n)
748 OnDisconnect();
749 SetCloseAndDelete(true);
750 SetFlushBeforeClose(false);
751 #ifdef ENABLE_POOL
752 SetLost();
753 #endif
754 DEB( int errnr = SSL_get_error(m_ssl, n);
755 const char *errbuf = ERR_error_string(errnr, NULL);
756 fprintf(stderr, "SSL_write() returns 0: %d : %s\n",errnr, errbuf);)
759 else
760 #endif // HAVE_OPENSSL
762 n = send(GetSocket(), buf, (int)len, MSG_NOSIGNAL);
763 if (n == -1)
765 // normal error codes:
766 // WSAEWOULDBLOCK
767 // EAGAIN or EWOULDBLOCK
768 #ifdef _WIN32
769 if (Errno != WSAEWOULDBLOCK)
770 #else
771 if (Errno != EWOULDBLOCK)
772 #endif
774 Handler().LogError(this, "send", Errno, StrError(Errno), LOG_LEVEL_FATAL);
775 OnDisconnect();
776 SetCloseAndDelete(true);
777 SetFlushBeforeClose(false);
778 #ifdef ENABLE_POOL
779 SetLost();
780 #endif
782 return 0;
785 if (n > 0)
787 m_bytes_sent += n;
788 if (GetTrafficMonitor())
790 GetTrafficMonitor() -> fwrite(buf, 1, n);
793 return n;
797 void TcpSocket::Buffer(const char *buf, size_t len)
799 size_t ptr = 0;
800 m_output_length += len;
801 while (ptr < len)
803 // buf/len => pbuf/sz
804 size_t space = 0;
805 if (m_obuf_top && (space = m_obuf_top -> Space()) > 0)
807 const char *pbuf = buf + ptr;
808 size_t sz = len - ptr;
809 if (space >= sz)
811 m_obuf_top -> Add(pbuf, sz);
812 ptr += sz;
814 else
816 m_obuf_top -> Add(pbuf, space);
817 ptr += space;
820 else
822 m_obuf_top = new OUTPUT;
823 m_obuf.push_back( m_obuf_top );
829 void TcpSocket::Send(const std::string &str,int i)
831 SendBuf(str.c_str(),str.size(),i);
835 void TcpSocket::SendBuf(const char *buf,size_t len,int)
837 if (!Ready() && !Connecting())
839 Handler().LogError(this, "SendBuf", -1, "Attempt to write to a non-ready socket" ); // warning
840 if (GetSocket() == INVALID_SOCKET)
841 Handler().LogError(this, "SendBuf", 0, " * GetSocket() == INVALID_SOCKET", LOG_LEVEL_INFO);
842 if (Connecting())
843 Handler().LogError(this, "SendBuf", 0, " * Connecting()", LOG_LEVEL_INFO);
844 if (CloseAndDelete())
845 Handler().LogError(this, "SendBuf", 0, " * CloseAndDelete()", LOG_LEVEL_INFO);
846 return;
848 if (!IsConnected())
850 Handler().LogError(this, "SendBuf", -1, "Attempt to write to a non-connected socket, will be sent on connect" ); // warning
851 Buffer(buf, len);
852 return;
854 if (m_obuf_top)
856 Buffer(buf, len);
857 return;
859 int n = TryWrite(buf, len);
860 if (n >= 0 && n < (int)len)
862 Buffer(buf + n, len - n);
864 // if ( data in buffer || !IsConnected )
865 // {
866 // add to buffer
867 // }
868 // else
869 // try_send
870 // if any data is unsent, buffer it and set m_wfds
872 // check output buffer set, set/reset m_wfds accordingly
874 bool br;
875 bool bw;
876 bool bx;
877 Handler().Get(GetSocket(), br, bw, bx);
878 if (m_obuf.size())
879 Set(br, true);
880 else
881 Set(br, false);
886 void TcpSocket::OnLine(const std::string& )
891 #ifdef _MSC_VER
892 #pragma warning(disable:4355)
893 #endif
894 TcpSocket::TcpSocket(const TcpSocket& s)
895 :StreamSocket(s)
896 ,ibuf(0)
899 #ifdef _MSC_VER
900 #pragma warning(default:4355)
901 #endif
904 #ifdef ENABLE_SOCKS4
905 void TcpSocket::OnSocks4Connect()
907 char request[1000];
908 memset(request, 0, sizeof(request));
909 request[0] = 4; // socks v4
910 request[1] = 1; // command code: CONNECT
912 std::auto_ptr<SocketAddress> ad = GetClientRemoteAddress();
913 if (ad.get())
915 struct sockaddr *p0 = (struct sockaddr *)*ad;
916 struct sockaddr_in *p = (struct sockaddr_in *)p0;
917 if (p -> sin_family == AF_INET)
919 memcpy(request + 2, &p -> sin_port, 2); // nwbo is ok here
920 memcpy(request + 4, &p -> sin_addr, sizeof(struct in_addr));
922 else
924 /// \todo warn
927 else
929 /// \todo warn
932 strcpy(request + 8, GetSocks4Userid().c_str());
933 size_t length = GetSocks4Userid().size() + 8 + 1;
934 SendBuf(request, length);
935 m_socks4_state = 0;
939 void TcpSocket::OnSocks4ConnectFailed()
941 Handler().LogError(this,"OnSocks4ConnectFailed",0,"connection to socks4 server failed, trying direct connection",LOG_LEVEL_WARNING);
942 if (!Handler().Socks4TryDirect())
944 SetConnecting(false);
945 SetCloseAndDelete();
946 OnConnectFailed(); // just in case
948 else
950 SetRetryClientConnect();
955 bool TcpSocket::OnSocks4Read()
957 switch (m_socks4_state)
959 case 0:
960 ibuf.Read(&m_socks4_vn, 1);
961 m_socks4_state = 1;
962 break;
963 case 1:
964 ibuf.Read(&m_socks4_cd, 1);
965 m_socks4_state = 2;
966 break;
967 case 2:
968 if (GetInputLength() > 1)
970 ibuf.Read( (char *)&m_socks4_dstport, 2);
971 m_socks4_state = 3;
973 else
975 return true;
977 break;
978 case 3:
979 if (GetInputLength() > 3)
981 ibuf.Read( (char *)&m_socks4_dstip, 4);
982 SetSocks4(false);
984 switch (m_socks4_cd)
986 case 90:
987 OnConnect();
988 Handler().LogError(this, "OnSocks4Read", 0, "Connection established", LOG_LEVEL_INFO);
989 break;
990 case 91:
991 case 92:
992 case 93:
993 Handler().LogError(this,"OnSocks4Read",m_socks4_cd,"socks4 server reports connect failed",LOG_LEVEL_FATAL);
994 SetConnecting(false);
995 SetCloseAndDelete();
996 OnConnectFailed();
997 break;
998 default:
999 Handler().LogError(this,"OnSocks4Read",m_socks4_cd,"socks4 server unrecognized response",LOG_LEVEL_FATAL);
1000 SetCloseAndDelete();
1001 break;
1004 else
1006 return true;
1008 break;
1010 return false;
1012 #endif
1015 void TcpSocket::Sendf(const char *format, ...)
1017 va_list ap;
1018 va_start(ap, format);
1019 char slask[5000]; // vsprintf / vsnprintf temporary
1020 #ifdef _WIN32
1021 vsprintf(slask, format, ap);
1022 #else
1023 vsnprintf(slask, 5000, format, ap);
1024 #endif
1025 va_end(ap);
1026 Send( slask );
1030 #ifdef HAVE_OPENSSL
1031 void TcpSocket::OnSSLConnect()
1033 SetNonblocking(true);
1035 if (m_ssl_ctx)
1037 DEB( fprintf(stderr, "SSL Context already initialized - closing socket\n");)
1038 SetCloseAndDelete(true);
1039 return;
1041 InitSSLClient();
1043 if (m_ssl_ctx)
1045 /* Connect the SSL socket */
1046 m_ssl = SSL_new(m_ssl_ctx);
1047 if (!m_ssl)
1049 DEB( fprintf(stderr, " m_ssl is NULL\n");)
1050 SetCloseAndDelete(true);
1051 return;
1053 SSL_set_mode(m_ssl, SSL_MODE_AUTO_RETRY);
1054 m_sbio = BIO_new_socket((int)GetSocket(), BIO_NOCLOSE);
1055 if (!m_sbio)
1057 DEB( fprintf(stderr, " m_sbio is NULL\n");)
1058 SetCloseAndDelete(true);
1059 return;
1061 SSL_set_bio(m_ssl, m_sbio, m_sbio);
1062 if (!SSLNegotiate())
1064 SetSSLNegotiate();
1067 else
1069 SetCloseAndDelete();
1074 void TcpSocket::OnSSLAccept()
1076 SetNonblocking(true);
1078 if (m_ssl_ctx)
1080 DEB( fprintf(stderr, "SSL Context already initialized - closing socket\n");)
1081 SetCloseAndDelete(true);
1082 return;
1084 InitSSLServer();
1085 SetSSLServer();
1087 if (m_ssl_ctx)
1089 m_ssl = SSL_new(m_ssl_ctx);
1090 if (!m_ssl)
1092 DEB( fprintf(stderr, " m_ssl is NULL\n");)
1093 SetCloseAndDelete(true);
1094 return;
1096 SSL_set_mode(m_ssl, SSL_MODE_AUTO_RETRY);
1097 m_sbio = BIO_new_socket((int)GetSocket(), BIO_NOCLOSE);
1098 if (!m_sbio)
1100 DEB( fprintf(stderr, " m_sbio is NULL\n");)
1101 SetCloseAndDelete(true);
1102 return;
1104 SSL_set_bio(m_ssl, m_sbio, m_sbio);
1105 // if (!SSLNegotiate())
1107 SetSSLNegotiate();
1113 bool TcpSocket::SSLNegotiate()
1115 if (!IsSSLServer()) // client
1117 int r = SSL_connect(m_ssl);
1118 if (r > 0)
1120 SetSSLNegotiate(false);
1121 /// \todo: resurrect certificate check... client
1122 // CheckCertificateChain( "");//ServerHOST);
1123 SetNonblocking(false);
1126 SetConnected();
1127 if (GetOutputLength())
1129 OnWrite();
1132 #ifdef ENABLE_RECONNECT
1133 if (IsReconnect())
1134 OnReconnect();
1135 else
1136 #endif
1138 OnConnect();
1140 Handler().LogError(this, "SSLNegotiate/SSL_connect", 0, "Connection established", LOG_LEVEL_INFO);
1141 return true;
1143 else
1144 if (!r)
1146 Handler().LogError(this, "SSLNegotiate/SSL_connect", 0, "Connection failed", LOG_LEVEL_INFO);
1147 SetSSLNegotiate(false);
1148 SetCloseAndDelete();
1149 OnSSLConnectFailed();
1151 else
1153 r = SSL_get_error(m_ssl, r);
1154 if (r != SSL_ERROR_WANT_READ && r != SSL_ERROR_WANT_WRITE)
1156 Handler().LogError(this, "SSLNegotiate/SSL_connect", -1, "Connection failed", LOG_LEVEL_INFO);
1157 DEB( fprintf(stderr, "SSL_connect() failed - closing socket, return code: %d\n",r);)
1158 SetSSLNegotiate(false);
1159 SetCloseAndDelete(true);
1160 OnSSLConnectFailed();
1164 else // server
1166 int r = SSL_accept(m_ssl);
1167 if (r > 0)
1169 SetSSLNegotiate(false);
1170 /// \todo: resurrect certificate check... server
1171 // CheckCertificateChain( "");//ClientHOST);
1172 SetNonblocking(false);
1175 SetConnected();
1176 if (GetOutputLength())
1178 OnWrite();
1181 OnAccept();
1182 Handler().LogError(this, "SSLNegotiate/SSL_accept", 0, "Connection established", LOG_LEVEL_INFO);
1183 return true;
1185 else
1186 if (!r)
1188 Handler().LogError(this, "SSLNegotiate/SSL_accept", 0, "Connection failed", LOG_LEVEL_INFO);
1189 SetSSLNegotiate(false);
1190 SetCloseAndDelete();
1191 OnSSLAcceptFailed();
1193 else
1195 r = SSL_get_error(m_ssl, r);
1196 if (r != SSL_ERROR_WANT_READ && r != SSL_ERROR_WANT_WRITE)
1198 Handler().LogError(this, "SSLNegotiate/SSL_accept", -1, "Connection failed", LOG_LEVEL_INFO);
1199 DEB( fprintf(stderr, "SSL_accept() failed - closing socket, return code: %d\n",r);)
1200 SetSSLNegotiate(false);
1201 SetCloseAndDelete(true);
1202 OnSSLAcceptFailed();
1206 return false;
1210 void TcpSocket::InitSSLClient()
1212 InitializeContext("", SSLv23_method());
1216 void TcpSocket::InitSSLServer()
1218 Handler().LogError(this, "InitSSLServer", 0, "You MUST implement your own InitSSLServer method", LOG_LEVEL_FATAL);
1219 SetCloseAndDelete();
1223 void TcpSocket::InitializeContext(const std::string& context, SSL_METHOD *meth_in)
1225 /* Create our context*/
1226 static std::map<std::string, SSL_CTX *> client_contexts;
1227 if (client_contexts.find(context) == client_contexts.end())
1229 SSL_METHOD *meth = meth_in ? meth_in : SSLv3_method();
1230 m_ssl_ctx = client_contexts[context] = SSL_CTX_new(meth);
1231 SSL_CTX_set_mode(m_ssl_ctx, SSL_MODE_AUTO_RETRY);
1233 else
1235 m_ssl_ctx = client_contexts[context];
1240 void TcpSocket::InitializeContext(const std::string& context,const std::string& keyfile,const std::string& password,SSL_METHOD *meth_in)
1242 /* Create our context*/
1243 static std::map<std::string, SSL_CTX *> server_contexts;
1244 if (server_contexts.find(context) == server_contexts.end())
1246 SSL_METHOD *meth = meth_in ? meth_in : SSLv3_method();
1247 m_ssl_ctx = server_contexts[context] = SSL_CTX_new(meth);
1248 SSL_CTX_set_mode(m_ssl_ctx, SSL_MODE_AUTO_RETRY);
1249 // session id
1250 if (context.size())
1251 SSL_CTX_set_session_id_context(m_ssl_ctx, (const unsigned char *)context.c_str(), (unsigned int)context.size());
1252 else
1253 SSL_CTX_set_session_id_context(m_ssl_ctx, (const unsigned char *)"--empty--", 9);
1255 else
1257 m_ssl_ctx = server_contexts[context];
1260 /* Load our keys and certificates*/
1261 if (!(SSL_CTX_use_certificate_file(m_ssl_ctx, keyfile.c_str(), SSL_FILETYPE_PEM)))
1263 Handler().LogError(this, "TcpSocket InitializeContext", 0, "Couldn't read certificate file " + keyfile, LOG_LEVEL_FATAL);
1266 m_password = password;
1267 SSL_CTX_set_default_passwd_cb(m_ssl_ctx, SSL_password_cb);
1268 SSL_CTX_set_default_passwd_cb_userdata(m_ssl_ctx, this);
1269 if (!(SSL_CTX_use_PrivateKey_file(m_ssl_ctx, keyfile.c_str(), SSL_FILETYPE_PEM)))
1271 Handler().LogError(this, "TcpSocket InitializeContext", 0, "Couldn't read private key file " + keyfile, LOG_LEVEL_FATAL);
1276 void TcpSocket::InitializeContext(const std::string& context,const std::string& certfile,const std::string& keyfile,const std::string& password,SSL_METHOD *meth_in)
1278 /* Create our context*/
1279 static std::map<std::string, SSL_CTX *> server_contexts;
1280 if (server_contexts.find(context) == server_contexts.end())
1282 SSL_METHOD *meth = meth_in ? meth_in : SSLv3_method();
1283 m_ssl_ctx = server_contexts[context] = SSL_CTX_new(meth);
1284 SSL_CTX_set_mode(m_ssl_ctx, SSL_MODE_AUTO_RETRY);
1285 // session id
1286 if (context.size())
1287 SSL_CTX_set_session_id_context(m_ssl_ctx, (const unsigned char *)context.c_str(), (unsigned int)context.size());
1288 else
1289 SSL_CTX_set_session_id_context(m_ssl_ctx, (const unsigned char *)"--empty--", 9);
1291 else
1293 m_ssl_ctx = server_contexts[context];
1296 /* Load our keys and certificates*/
1297 if (!(SSL_CTX_use_certificate_file(m_ssl_ctx, certfile.c_str(), SSL_FILETYPE_PEM)))
1299 Handler().LogError(this, "TcpSocket InitializeContext", 0, "Couldn't read certificate file " + keyfile, LOG_LEVEL_FATAL);
1302 m_password = password;
1303 SSL_CTX_set_default_passwd_cb(m_ssl_ctx, SSL_password_cb);
1304 SSL_CTX_set_default_passwd_cb_userdata(m_ssl_ctx, this);
1305 if (!(SSL_CTX_use_PrivateKey_file(m_ssl_ctx, keyfile.c_str(), SSL_FILETYPE_PEM)))
1307 Handler().LogError(this, "TcpSocket InitializeContext", 0, "Couldn't read private key file " + keyfile, LOG_LEVEL_FATAL);
1312 int TcpSocket::SSL_password_cb(char *buf,int num,int rwflag,void *userdata)
1314 Socket *p0 = static_cast<Socket *>(userdata);
1315 TcpSocket *p = dynamic_cast<TcpSocket *>(p0);
1316 std::string pw = p ? p -> GetPassword() : "";
1317 if ( (size_t)num < pw.size() + 1)
1319 return 0;
1321 strcpy(buf,pw.c_str());
1322 return (int)pw.size();
1324 #endif // HAVE_OPENSSL
1327 int TcpSocket::Close()
1329 if (GetSocket() == INVALID_SOCKET) // this could happen
1331 Handler().LogError(this, "Socket::Close", 0, "file descriptor invalid", LOG_LEVEL_WARNING);
1332 return 0;
1334 int n;
1335 SetNonblocking(true);
1336 if (IsConnected() && !(GetShutdown() & SHUT_WR))
1338 if (shutdown(GetSocket(), SHUT_WR) == -1)
1340 // failed...
1341 Handler().LogError(this, "shutdown", Errno, StrError(Errno), LOG_LEVEL_ERROR);
1345 char tmp[1000];
1346 if ((n = recv(GetSocket(),tmp,1000,0)) >= 0)
1348 if (n)
1350 Handler().LogError(this, "read() after shutdown", n, "bytes read", LOG_LEVEL_WARNING);
1353 #ifdef HAVE_OPENSSL
1354 if (IsSSL() && m_ssl)
1355 SSL_shutdown(m_ssl);
1356 if (m_ssl)
1358 SSL_free(m_ssl);
1359 m_ssl = NULL;
1361 #endif
1362 return Socket::Close();
1366 #ifdef HAVE_OPENSSL
1367 SSL_CTX *TcpSocket::GetSslContext()
1369 if (!m_ssl_ctx)
1370 Handler().LogError(this, "GetSslContext", 0, "SSL Context is NULL; check InitSSLServer/InitSSLClient", LOG_LEVEL_WARNING);
1371 return m_ssl_ctx;
1374 SSL *TcpSocket::GetSsl()
1376 if (!m_ssl)
1377 Handler().LogError(this, "GetSsl", 0, "SSL is NULL; check InitSSLServer/InitSSLClient", LOG_LEVEL_WARNING);
1378 return m_ssl;
1380 #endif
1383 #ifdef ENABLE_RECONNECT
1384 void TcpSocket::SetReconnect(bool x)
1386 m_b_reconnect = x;
1388 #endif
1391 void TcpSocket::OnRawData(const char *buf_in,size_t len)
1396 size_t TcpSocket::GetInputLength()
1398 return ibuf.GetLength();
1402 size_t TcpSocket::GetOutputLength()
1404 return m_output_length;
1408 uint64_t TcpSocket::GetBytesReceived(bool clear)
1410 uint64_t z = m_bytes_received;
1411 if (clear)
1412 m_bytes_received = 0;
1413 return z;
1417 uint64_t TcpSocket::GetBytesSent(bool clear)
1419 uint64_t z = m_bytes_sent;
1420 if (clear)
1421 m_bytes_sent = 0;
1422 return z;
1426 #ifdef ENABLE_RECONNECT
1427 bool TcpSocket::Reconnect()
1429 return m_b_reconnect;
1433 void TcpSocket::SetIsReconnect(bool x)
1435 m_b_is_reconnect = x;
1439 bool TcpSocket::IsReconnect()
1441 return m_b_is_reconnect;
1443 #endif
1446 #ifdef HAVE_OPENSSL
1447 const std::string& TcpSocket::GetPassword()
1449 return m_password;
1451 #endif
1454 void TcpSocket::DisableInputBuffer(bool x)
1456 m_b_input_buffer_disabled = x;
1460 void TcpSocket::OnOptions(int family,int type,int protocol,SOCKET s)
1462 DEB( fprintf(stderr, "Socket::OnOptions()\n");)
1463 #ifdef SO_NOSIGPIPE
1464 SetSoNosigpipe(true);
1465 #endif
1466 SetSoReuseaddr(true);
1467 SetSoKeepalive(true);
1471 void TcpSocket::SetLineProtocol(bool x)
1473 StreamSocket::SetLineProtocol(x);
1474 DisableInputBuffer(x);
1478 bool TcpSocket::SetTcpNodelay(bool x)
1480 #ifdef TCP_NODELAY
1481 int optval = x ? 1 : 0;
1482 if (setsockopt(GetSocket(), IPPROTO_TCP, TCP_NODELAY, (char *)&optval, sizeof(optval)) == -1)
1484 Handler().LogError(this, "setsockopt(IPPROTO_TCP, TCP_NODELAY)", Errno, StrError(Errno), LOG_LEVEL_FATAL);
1485 return false;
1487 return true;
1488 #else
1489 Handler().LogError(this, "socket option not available", 0, "TCP_NODELAY", LOG_LEVEL_INFO);
1490 return false;
1491 #endif
1495 TcpSocket::CircularBuffer::CircularBuffer(size_t size)
1496 :buf(new char[2 * size])
1497 ,m_max(size)
1498 ,m_q(0)
1499 ,m_b(0)
1500 ,m_t(0)
1501 ,m_count(0)
1506 TcpSocket::CircularBuffer::~CircularBuffer()
1508 delete[] buf;
1512 bool TcpSocket::CircularBuffer::Write(const char *s,size_t l)
1514 if (m_q + l > m_max)
1516 return false; // overflow
1518 m_count += (unsigned long)l;
1519 if (m_t + l > m_max) // block crosses circular border
1521 size_t l1 = m_max - m_t; // size left until circular border crossing
1522 // always copy full block to buffer(buf) + top pointer(m_t)
1523 // because we have doubled the buffer size for performance reasons
1524 memcpy(buf + m_t, s, l);
1525 memcpy(buf, s + l1, l - l1);
1526 m_t = l - l1;
1527 m_q += l;
1529 else
1531 memcpy(buf + m_t, s, l);
1532 memcpy(buf + m_max + m_t, s, l);
1533 m_t += l;
1534 if (m_t >= m_max)
1535 m_t -= m_max;
1536 m_q += l;
1538 return true;
1542 bool TcpSocket::CircularBuffer::Read(char *s,size_t l)
1544 if (l > m_q)
1546 return false; // not enough chars
1548 if (m_b + l > m_max) // block crosses circular border
1550 size_t l1 = m_max - m_b;
1551 if (s)
1553 memcpy(s, buf + m_b, l1);
1554 memcpy(s + l1, buf, l - l1);
1556 m_b = l - l1;
1557 m_q -= l;
1559 else
1561 if (s)
1563 memcpy(s, buf + m_b, l);
1565 m_b += l;
1566 if (m_b >= m_max)
1567 m_b -= m_max;
1568 m_q -= l;
1570 if (!m_q)
1572 m_b = m_t = 0;
1574 return true;
1578 bool TcpSocket::CircularBuffer::Remove(size_t l)
1580 return Read(NULL, l);
1584 size_t TcpSocket::CircularBuffer::GetLength()
1586 return m_q;
1590 const char *TcpSocket::CircularBuffer::GetStart()
1592 return buf + m_b;
1596 size_t TcpSocket::CircularBuffer::GetL()
1598 return (m_b + m_q > m_max) ? m_max - m_b : m_q;
1602 size_t TcpSocket::CircularBuffer::Space()
1604 return m_max - m_q;
1608 unsigned long TcpSocket::CircularBuffer::ByteCounter(bool clear)
1610 if (clear)
1612 unsigned long x = m_count;
1613 m_count = 0;
1614 return x;
1616 return m_count;
1620 std::string TcpSocket::CircularBuffer::ReadString(size_t l)
1622 char *sz = new char[l + 1];
1623 if (!Read(sz, l)) // failed, debug printout in Read() method
1625 delete[] sz;
1626 return "";
1628 sz[l] = 0;
1629 std::string tmp = sz;
1630 delete[] sz;
1631 return tmp;
1635 void TcpSocket::OnConnectTimeout()
1637 Handler().LogError(this, "connect", -1, "connect timeout", LOG_LEVEL_FATAL);
1638 #ifdef ENABLE_SOCKS4
1639 if (Socks4())
1641 OnSocks4ConnectFailed();
1642 // retry direct connection
1644 else
1645 #endif
1646 if (GetConnectionRetry() == -1 ||
1647 (GetConnectionRetry() && GetConnectionRetries() < GetConnectionRetry()) )
1649 IncreaseConnectionRetries();
1650 // ask socket via OnConnectRetry callback if we should continue trying
1651 if (OnConnectRetry())
1653 SetRetryClientConnect();
1655 else
1657 SetCloseAndDelete( true );
1658 /// \todo state reason why connect failed
1659 OnConnectFailed();
1662 else
1664 SetCloseAndDelete(true);
1665 /// \todo state reason why connect failed
1666 OnConnectFailed();
1669 SetConnecting(false);
1673 #ifdef _WIN32
1674 void TcpSocket::OnException()
1676 if (Connecting())
1678 #ifdef ENABLE_SOCKS4
1679 if (Socks4())
1680 OnSocks4ConnectFailed();
1681 else
1682 #endif
1683 if (GetConnectionRetry() == -1 ||
1684 (GetConnectionRetry() &&
1685 GetConnectionRetries() < GetConnectionRetry() ))
1687 // even though the connection failed at once, only retry after
1688 // the connection timeout
1689 // should we even try to connect again, when CheckConnect returns
1690 // false it's because of a connection error - not a timeout...
1692 else
1694 SetConnecting(false); // tnx snibbe
1695 SetCloseAndDelete();
1696 OnConnectFailed();
1698 return;
1700 // %! exception doesn't always mean something bad happened, this code should be reworked
1701 // errno valid here?
1702 int err = SoError();
1703 Handler().LogError(this, "exception on select", err, StrError(err), LOG_LEVEL_FATAL);
1704 SetCloseAndDelete();
1706 #endif // _WIN32
1709 int TcpSocket::Protocol()
1711 return IPPROTO_TCP;
1715 void TcpSocket::SetTransferLimit(size_t sz)
1717 m_transfer_limit = sz;
1721 void TcpSocket::OnTransferLimit()
1726 #ifdef SOCKETS_NAMESPACE
1728 #endif