summaryrefslogtreecommitdiff
path: root/node/TcpSocket.cpp
blob: b21cbd5e81644a940268344f8a6336c293ce1c09 (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
/*
 * ZeroTier One - Global Peer to Peer Ethernet
 * Copyright (C) 2011-2014  ZeroTier Networks LLC
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 *
 * --
 *
 * ZeroTier may be used and distributed under the terms of the GPLv3, which
 * are available at: http://www.gnu.org/licenses/gpl-3.0.html
 *
 * If you would like to embed ZeroTier into a commercial application or
 * redistribute it in a modified binary form, please contact ZeroTier Networks
 * LLC. Start here: http://www.zerotier.com/
 */

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <fcntl.h>
#include <time.h>
#include <errno.h>
#include <sys/types.h>

#include "Constants.hpp"
#include "TcpSocket.hpp"
#include "SocketManager.hpp"

#ifdef __WINDOWS__
#include <WinSock2.h>
#include <WS2tcpip.h>
#include <Windows.h>
#else
#include <unistd.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <signal.h>
#endif

#define ZT_TCP_MAX_SENDQ_LENGTH (ZT_SOCKET_MAX_MESSAGE_LEN * 8)

namespace ZeroTier {

TcpSocket::~TcpSocket()
{
#ifdef __WINDOWS__
	::closesocket(_sock);
#else
	::close(_sock);
#endif
	if (_outbuf)
		::free(_outbuf);
	//printf("!!! TCP SOCKET DESTROYED @%.16llx to %s\r\n",(unsigned long long)this,_remote.toString().c_str());
}

bool TcpSocket::send(const InetAddress &to,const void *msg,unsigned int msglen)
{
	if (msglen > ZT_SOCKET_MAX_MESSAGE_LEN)
		return false; // message too big
	if (!msglen)
		return true; // sanity check

	Mutex::Lock _l(_writeLock);
	bool writeInProgress = ((_outptr != 0)||(_connecting));

	// Ensure that _outbuf is large enough
	unsigned int newptr = _outptr + 5 + msglen;
	if (newptr > _outbufsize) {
		unsigned int newbufsize = _outbufsize;
		while (newbufsize < newptr)
			newbufsize += ZT_SOCKET_MAX_MESSAGE_LEN;
		if (newbufsize > ZT_TCP_MAX_SENDQ_LENGTH)
			return false; // cannot send, outbuf full
		unsigned char *newbuf = (unsigned char *)::malloc(newbufsize);
		if (!newbuf)
			return false; // cannot send, no memory
		_outbufsize = newbufsize;
		if (_outbuf) {
			memcpy(newbuf,_outbuf,_outptr);
			::free(_outbuf);
		}
		_outbuf = newbuf;
	}

	_outbuf[_outptr++] = 0x17; // look like TLS data
	_outbuf[_outptr++] = 0x03;
	_outbuf[_outptr++] = 0x03; // look like TLS 1.2
	_outbuf[_outptr++] = (unsigned char)((msglen >> 8) & 0xff);
	_outbuf[_outptr++] = (unsigned char)(msglen & 0xff);
	for(unsigned int i=0;i<msglen;++i)
		_outbuf[_outptr++] = ((const unsigned char *)msg)[i];

	if (!writeInProgress) {
		// If no output was enqueued before this, try to send() it and then
		// start a queued write if any remains after that.

		int n = (int)::send(_sock,(const char *)_outbuf,_outptr,0);
		if (n > 0)
			memmove(_outbuf,_outbuf + (unsigned int)n,_outptr -= (unsigned int)n);

		if (_outptr) {
			_sm->startNotifyWrite(this);
			_sm->whack();
		}
	} // else just leave in _outbuf[] to get written when stream is available for write

	return true;
}

bool TcpSocket::notifyAvailableForRead(const SharedPtr<Socket> &self,SocketManager *sm)
{
	unsigned char buf[65536];

	// will not be called concurrently since only SocketManager::poll() calls this

	int n = (int)::recv(_sock,(char *)buf,sizeof(buf),0);
	if (n <= 0)
		return false; // read error, stream probably closed

	unsigned int p = _inptr,pl = 0;
	for(int k=0;k<n;++k) {
		_inbuf[p++] = buf[k];
		if (p >= (int)sizeof(_inbuf))
			return false; // read overrun, packet too large or invalid

		if ((!pl)&&(p >= 5)) {
			if (_inbuf[0] == 0x17) {
				// fake TLS data frame, next two bytes are TLS version and are ignored
				pl = (((unsigned int)_inbuf[3] << 8) | (unsigned int)_inbuf[4]) + 5;
			} else return false; // in the future we may support fake TLS handshakes
		}

		if ((pl)&&(p >= pl)) {
			Buffer<ZT_SOCKET_MAX_MESSAGE_LEN> data(_inbuf + 5,pl - 5);
			memmove(_inbuf,_inbuf + pl,p -= pl);
			try {
				sm->handleReceivedPacket(self,_remote,data);
			} catch ( ... ) {} // handlers should not throw
			pl = 0;
		}
	}
	_inptr = p;

	return true;
}

bool TcpSocket::notifyAvailableForWrite(const SharedPtr<Socket> &self,SocketManager *sm)
{
	Mutex::Lock _l(_writeLock);

	if (_connecting)
		_connecting = false;

	if (_outptr) {
		int n = (int)::send(_sock,(const char *)_outbuf,_outptr,0);
#ifdef __WINDOWS__
		if (n == SOCKET_ERROR) {
			switch(WSAGetLastError()) {
				case WSAEINTR:
				case WSAEWOULDBLOCK:
					break;
				default:
					return false;
			}
#else
		if (n <= 0) {
			switch(errno) {
#ifdef EAGAIN
				case EAGAIN:
#endif
#if defined(EWOULDBLOCK) && ( !defined(EAGAIN) || (EWOULDBLOCK != EAGAIN) )
				case EWOULDBLOCK:
#endif
#ifdef EINTR
				case EINTR:
#endif
					break;
				default:
					return false;
			}
#endif
		} else memmove(_outbuf,_outbuf + (unsigned int)n,_outptr -= (unsigned int)n);
	}

	if (!_outptr)
		sm->stopNotifyWrite(this);

	return true;
}

} // namespace ZeroTier