summaryrefslogtreecommitdiff
path: root/src/sockets.cpp
blob: 6aadb780239597ebb609feb2aa0f54c16aa9a6d3 (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
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
/*
 *
 * (C) 2003-2012 Anope Team
 * Contact us at team@anope.org
 *
 * Please read COPYING and README for further details.
 *
 * Based on the original code of Epona by Lara.
 * Based on the original code of Services by Andy Church.
 *
 */

#include "services.h"
#include "sockets.h"
#include "socketengine.h"
#include "logger.h"

#ifndef _WIN32
#include <arpa/inet.h>
#include <errno.h>
#include <fcntl.h>
#endif

static const Anope::string SocketFlagStrings[] = {
	"SF_DEAD", "SF_WRITABLE", "SF_CONNECTING", "SF_CONNECTED", "SF_ACCEPTING", "SF_ACCEPTED", ""
};
template<> const Anope::string* Flags<SocketFlag>::flags_strings = SocketFlagStrings;

std::map<int, Socket *> SocketEngine::Sockets;

uint32_t TotalRead = 0;
uint32_t TotalWritten = 0;

SocketIO NormalSocketIO;

sockaddrs::sockaddrs(const Anope::string &address)
{
	this->clear();
	if (!address.empty())
		this->pton(address.find(':') != Anope::string::npos ? AF_INET6 : AF_INET, address);
}

void sockaddrs::clear()
{
	memset(this, 0, sizeof(*this));
}

size_t sockaddrs::size() const
{
	switch (sa.sa_family)
	{
		case AF_INET:
			return sizeof(sa4);
		case AF_INET6:
			return sizeof(sa6);
		default:
			break;
	}

	return 0;
}

int sockaddrs::port() const
{
	switch (sa.sa_family)
	{
		case AF_INET:
			return ntohs(sa4.sin_port);
		case AF_INET6:
			return ntohs(sa6.sin6_port);
		default:
			break;
	}

	return -1;
}

Anope::string sockaddrs::addr() const
{
	char address[INET6_ADDRSTRLEN + 1] = "";

	switch (sa.sa_family)
	{
		case AF_INET:
			if (!inet_ntop(AF_INET, &sa4.sin_addr, address, sizeof(address)))
				throw SocketException(Anope::LastError());
			return address;
		case AF_INET6:
			if (!inet_ntop(AF_INET6, &sa6.sin6_addr, address, sizeof(address)))
				throw SocketException(Anope::LastError());
			return address;
		default:
			break;
	}

	return address;
}

bool sockaddrs::operator()() const
{
	return this->sa.sa_family != 0;
}

bool sockaddrs::operator==(const sockaddrs &other) const
{
	if (sa.sa_family != other.sa.sa_family)
		return false;
	switch (sa.sa_family)
	{
		case AF_INET:
			return (sa4.sin_port == other.sa4.sin_port) && (sa4.sin_addr.s_addr == other.sa4.sin_addr.s_addr);
		case AF_INET6:
			return (sa6.sin6_port == other.sa6.sin6_port) && !memcmp(sa6.sin6_addr.s6_addr, other.sa6.sin6_addr.s6_addr, 16);
		default:
			return !memcmp(this, &other, sizeof(*this));
	}

	return false;
}

void sockaddrs::pton(int type, const Anope::string &address, int pport)
{
	switch (type)
	{
		case AF_INET:
		{
			int i = inet_pton(type, address.c_str(), &sa4.sin_addr);
			if (i == 0)
				throw SocketException("Invalid IP");
			else if (i <= -1)
				throw SocketException("Invalid IP: "  + Anope::LastError());
			sa4.sin_family = type;
			sa4.sin_port = htons(pport);
			return;
		}
		case AF_INET6:
		{
			int i = inet_pton(type, address.c_str(), &sa6.sin6_addr);
			if (i == 0)
				throw SocketException("Invalid IP");
			else if (i <= -1)
				throw SocketException("Invalid IP: " + Anope::LastError());
			sa6.sin6_family = type;
			sa6.sin6_port = htons(pport);
			return;
		}
		default:
			break;
	}

	throw CoreException("Invalid socket type");
}

void sockaddrs::ntop(int type, const void *src)
{
	switch (type)
	{
		case AF_INET:
			sa4.sin_addr = *reinterpret_cast<const in_addr *>(src);
			sa4.sin_family = type;
			return;
		case AF_INET6:
			sa6.sin6_addr = *reinterpret_cast<const in6_addr *>(src);
			sa6.sin6_family = type;
			return;
		default:
			break;
	}

	throw CoreException("Invalid socket type");
}

cidr::cidr(const Anope::string &ip)
{
	bool ipv6 = ip.find(':') != Anope::string::npos;
	size_t sl = ip.find_last_of('/');

	if (sl == Anope::string::npos)
	{
		this->cidr_ip = ip;
		this->cidr_len = ipv6 ? 128 : 32;
		this->addr.pton(ipv6 ? AF_INET6 : AF_INET, ip);
	}
	else
	{
		Anope::string real_ip = ip.substr(0, sl);
		Anope::string cidr_range = ip.substr(sl + 1);
		if (!cidr_range.is_pos_number_only())
			throw SocketException("Invalid CIDR range");

		this->cidr_ip = real_ip;
		this->cidr_len = convertTo<unsigned int>(cidr_range);
		this->addr.pton(ipv6 ? AF_INET6 : AF_INET, real_ip);
	}
}

cidr::cidr(const Anope::string &ip, unsigned char len)
{
	bool ipv6 = ip.find(':') != Anope::string::npos;
	this->addr.pton(ipv6 ? AF_INET6 : AF_INET, ip);
	this->cidr_ip = ip;
	this->cidr_len = len;
}

Anope::string cidr::mask() const
{
	return Anope::printf("%s/%d", this->cidr_ip.c_str(), this->cidr_len);
}

bool cidr::match(sockaddrs &other)
{
	if (this->addr.sa.sa_family != other.sa.sa_family)
		return false;

	unsigned char *ip, *their_ip, byte;

	switch (this->addr.sa.sa_family)
	{
		case AF_INET:
			ip = reinterpret_cast<unsigned char *>(&this->addr.sa4.sin_addr);
			byte = this->cidr_len / 8;
			their_ip = reinterpret_cast<unsigned char *>(&other.sa4.sin_addr);
			break;
		case AF_INET6:
			ip = reinterpret_cast<unsigned char *>(&this->addr.sa6.sin6_addr);
			byte = this->cidr_len / 8;
			their_ip = reinterpret_cast<unsigned char *>(&other.sa6.sin6_addr);
			break;
		default:
			throw SocketException("Invalid address type");
	}

	if (memcmp(ip, their_ip, byte))
		return false;

	ip += byte;
	their_ip += byte;
	byte = this->cidr_len % 8;
	if ((*ip & byte) != (*their_ip & byte))
		return false;

	return true;
}

bool cidr::operator<(const cidr &other) const
{
	if (this->addr.sa.sa_family != other.addr.sa.sa_family)
		return this->addr.sa.sa_family < other.addr.sa.sa_family;
	
	switch (this->addr.sa.sa_family)
	{
		case AF_INET:
		{
			unsigned int m = 0xFFFFFFFFU >> (32 - this->cidr_len);

			return (this->addr.sa4.sin_addr.s_addr & m) < (other.addr.sa4.sin_addr.s_addr & m);
		}
		case AF_INET6:
		{
			int i = memcmp(&this->addr.sa6.sin6_addr.s6_addr, &other.addr.sa6.sin6_addr.s6_addr, this->cidr_len / 8);
			if (i || this->cidr_len >= 128)
				return i < 0;

			// Now all thats left is to compare 'remainig' bits at offset this->cidr_len / 8
			int remaining = this->cidr_len % 8;
			unsigned char m = 0xFF << (8 - remaining);

			return (this->addr.sa6.sin6_addr.s6_addr[this->cidr_len / 8] & m) < (other.addr.sa6.sin6_addr.s6_addr[this->cidr_len / 8] & m);
		}
		default:
			throw CoreException("Unknown AFTYPE for cidr");
	}
}

bool cidr::operator==(const cidr &other) const
{
	return !(*this < other) && !(other < *this);
}

bool cidr::operator!=(const cidr &other) const
{
	return !(*this == other);
}

size_t cidr::hash::operator()(const cidr &s) const
{
	switch (s.addr.sa.sa_family)
	{
		case AF_INET:
		{
			unsigned int m = 0xFFFFFFFFU >> (32 - s.cidr_len);
			return s.addr.sa4.sin_addr.s_addr & m;
		}
		case AF_INET6:
		{
			size_t h = 0;

			for (int i = 0; i < s.cidr_len / 8; ++i)
				h ^= (s.addr.sa6.sin6_addr.s6_addr[i] << ((i * 8) % sizeof(size_t)));

			int remaining = s.cidr_len % 8;
			unsigned char m = 0xFF << (8 - remaining);

			h ^= s.addr.sa6.sin6_addr.s6_addr[s.cidr_len / 8] & m;

			return h;
		}
		default:
			throw CoreException("Unknown AFTYPE for cidr");
	}
}

int SocketIO::Recv(Socket *s, char *buf, size_t sz)
{
	size_t i = recv(s->GetFD(), buf, sz, 0);
	TotalRead += i;
	return i;
}

int SocketIO::Send(Socket *s, const char *buf, size_t sz)
{
	size_t i = send(s->GetFD(), buf, sz, 0);
	TotalWritten += i;
	return i;
}

int SocketIO::Send(Socket *s, const Anope::string &buf)
{
	return this->Send(s, buf.c_str(), buf.length());
}

ClientSocket *SocketIO::Accept(ListenSocket *s)
{
	sockaddrs conaddr;

	socklen_t size = sizeof(conaddr);
	int newsock = accept(s->GetFD(), &conaddr.sa, &size);

	if (newsock >= 0)
	{
		ClientSocket *ns = s->OnAccept(newsock, conaddr);
		ns->SetFlag(SF_ACCEPTED);
		ns->OnAccept();
		return ns;
	}
	else
		throw SocketException("Unable to accept connection: " + Anope::LastError());
}

SocketFlag SocketIO::FinishAccept(ClientSocket *cs)
{
	return SF_ACCEPTED;
}

void SocketIO::Bind(Socket *s, const Anope::string &ip, int port)
{
	s->bindaddr.pton(s->IsIPv6() ? AF_INET6 : AF_INET, ip, port);
	if (bind(s->GetFD(), &s->bindaddr.sa, s->bindaddr.size()) == -1)
		throw SocketException("Unable to bind to address: " + Anope::LastError());
}

void SocketIO::Connect(ConnectionSocket *s, const Anope::string &target, int port)
{
	s->UnsetFlag(SF_CONNECTING);
	s->UnsetFlag(SF_CONNECTED);
	s->conaddr.pton(s->IsIPv6() ? AF_INET6 : AF_INET, target, port);
	int c = connect(s->GetFD(), &s->conaddr.sa, s->conaddr.size());
	if (c == -1)
	{
		if (Anope::LastErrorCode() != EINPROGRESS)
			s->OnError(Anope::LastError());
		else
		{
			SocketEngine::Change(s, true, SF_WRITABLE);
			s->SetFlag(SF_CONNECTING);
		}
	}
	else
	{
		s->SetFlag(SF_CONNECTED);
		s->OnConnect();
	}
}

SocketFlag SocketIO::FinishConnect(ConnectionSocket *s)
{
	if (s->HasFlag(SF_CONNECTED))
		return SF_CONNECTED;
	else if (!s->HasFlag(SF_CONNECTING))
		throw SocketException("SocketIO::FinishConnect called for a socket not connected nor connecting?");

	int optval = 0;
	socklen_t optlen = sizeof(optval);
	if (!getsockopt(s->GetFD(), SOL_SOCKET, SO_ERROR, reinterpret_cast<char *>(&optval), &optlen) && !optval)
	{
		s->SetFlag(SF_CONNECTED);
		s->UnsetFlag(SF_CONNECTING);
		s->OnConnect();
		return SF_CONNECTED;
	}
	else
	{
		errno = optval;
		s->OnError(optval ? Anope::LastError() : "");
		return SF_DEAD;
	}
}

Socket::Socket()
{
	throw CoreException("Socket::Socket() ?");
}

Socket::Socket(int s, bool i, int type)
{
	this->io = &NormalSocketIO;
	this->ipv6 = i;
	if (s == -1)
		this->sock = socket(this->ipv6 ? AF_INET6 : AF_INET, type, 0);
	else
		this->sock = s;
	this->SetNonBlocking();
	SocketEngine::Sockets[this->sock] = this;
	SocketEngine::Change(this, true, SF_READABLE);
}

Socket::~Socket()
{
	SocketEngine::Change(this, false, SF_READABLE);
	SocketEngine::Change(this, false, SF_WRITABLE);
	anope_close(this->sock);
	this->io->Destroy();
	SocketEngine::Sockets.erase(this->sock);
}

int Socket::GetFD() const
{
	return sock;
}

bool Socket::IsIPv6() const
{
	return ipv6;
}

bool Socket::SetBlocking()
{
	int flags = fcntl(this->GetFD(), F_GETFL, 0);
	return !fcntl(this->GetFD(), F_SETFL, flags & ~O_NONBLOCK);
}

bool Socket::SetNonBlocking()
{
	int flags = fcntl(this->GetFD(), F_GETFL, 0);
	return !fcntl(this->GetFD(), F_SETFL, flags | O_NONBLOCK);
}

void Socket::Bind(const Anope::string &ip, int port)
{
	this->io->Bind(this, ip, port);
}

bool Socket::Process()
{
	return true;
}

bool Socket::ProcessRead()
{
	return true;
}

bool Socket::ProcessWrite()
{
	return true;
}

void Socket::ProcessError()
{
}

ListenSocket::ListenSocket(const Anope::string &bindip, int port, bool i)
{
	this->SetNonBlocking();

	const char op = 1;
	setsockopt(this->GetFD(), SOL_SOCKET, SO_REUSEADDR, &op, sizeof(op));

	this->bindaddr.pton(i ? AF_INET6 : AF_INET, bindip, port);
	this->io->Bind(this, bindip, port);

	if (listen(sock, SOMAXCONN) == -1)
		throw SocketException("Unable to listen: " + Anope::LastError());
}

ListenSocket::~ListenSocket()
{
}

bool ListenSocket::ProcessRead()
{
	try
	{
		this->io->Accept(this);
	}
	catch (const SocketException &ex)
	{
		Log() << ex.GetReason();
	}
	return true;
}