summaryrefslogtreecommitdiff
path: root/src/inspsocket.cpp
blob: e42990a748615c4f02238d6e7480560f0fb7297c (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
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
/*       +------------------------------------+
 *       | Inspire Internet Relay Chat Daemon |
 *       +------------------------------------+
 *
 *  InspIRCd: (C) 2002-2009 InspIRCd Development Team
 * See: http://wiki.inspircd.org/Credits
 *
 * This program is free but copyrighted software; see
 *            the file COPYING for details.
 *
 * ---------------------------------------------------
 */

/* $Core */

#include "socket.h"
#include "inspstring.h"
#include "socketengine.h"
#include "inspircd.h"

bool BufferedSocket::Readable()
{
	return (this->state != I_CONNECTING);
}

BufferedSocket::BufferedSocket(InspIRCd* SI)
{
	this->Timeout = NULL;
	this->state = I_DISCONNECTED;
	this->fd = -1;
	this->ServerInstance = SI;
}

BufferedSocket::BufferedSocket(InspIRCd* SI, int newfd, const char* ip)
{
	this->Timeout = NULL;
	this->fd = newfd;
	this->state = I_CONNECTED;
	strlcpy(this->IP,ip,MAXBUF);
	this->ServerInstance = SI;
	if (this->fd > -1)
		this->ServerInstance->SE->AddFd(this);
}

BufferedSocket::BufferedSocket(InspIRCd* SI, const std::string &ipaddr, int aport, unsigned long maxtime, const std::string &connectbindip)
{
	this->cbindip = connectbindip;
	this->fd = -1;
	this->ServerInstance = SI;
	strlcpy(host,ipaddr.c_str(),MAXBUF);
	this->Timeout = NULL;

	strlcpy(this->host,ipaddr.c_str(),MAXBUF);
	this->port = aport;

	irc::sockets::sockaddrs testaddr;
	if (!irc::sockets::aptosa(host, aport, &testaddr))
	{
		this->ServerInstance->Logs->Log("SOCKET", DEBUG,"BUG: Hostname passed to BufferedSocket, rather than an IP address!");
		this->OnError(I_ERR_CONNECT);
		this->Close();
		this->fd = -1;
		this->state = I_ERROR;
		return;
	}
	else
	{
		strlcpy(this->IP,host,MAXBUF);
		if (!this->DoConnect(maxtime))
		{
			this->OnError(I_ERR_CONNECT);
			this->Close();
			this->fd = -1;
			this->state = I_ERROR;
			return;
		}
	}
}

void BufferedSocket::SetQueues()
{
	// attempt to increase socket sendq and recvq as high as its possible
	int sendbuf = 32768;
	int recvbuf = 32768;
	if(setsockopt(this->fd,SOL_SOCKET,SO_SNDBUF,(const char *)&sendbuf,sizeof(sendbuf)) || setsockopt(this->fd,SOL_SOCKET,SO_RCVBUF,(const char *)&recvbuf,sizeof(sendbuf)))
	{
		//this->ServerInstance->Log(DEFAULT, "Could not increase SO_SNDBUF/SO_RCVBUF for socket %u", GetFd());
		; // do nothing. I'm a little sick of people trying to interpret this message as a result of why their incorrect setups don't work.
	}
}

bool BufferedSocket::DoBindMagic(const std::string &current_ip, bool v6)
{
	irc::sockets::sockaddrs s;
	if (!irc::sockets::aptosa(current_ip.c_str(), 0, &s))
	{
		errno = EADDRNOTAVAIL;
		return false;
	}

	if (ServerInstance->SE->Bind(this->fd, &s.sa, sizeof(s)) < 0)
	{
		this->state = I_ERROR;
		this->OnError(I_ERR_BIND);
		return false;
	}

	return true;
}

/* Most irc servers require you to specify the ip you want to bind to.
 * If you dont specify an IP, they rather dumbly bind to the first IP
 * of the box (e.g. INADDR_ANY). In InspIRCd, we scan thought the IP
 * addresses we've bound server ports to, and we try and bind our outbound
 * connections to the first usable non-loopback and non-any IP we find.
 * This is easier to configure when you have a lot of links and a lot
 * of servers to configure.
 */
bool BufferedSocket::BindAddr(const std::string &ip_to_bind)
{
	ConfigReader Conf(this->ServerInstance);
	bool v6 = false;

	// Case one: If they provided an IP, try bind it
	if (!ip_to_bind.empty())
	{
#ifdef IPV6
		// Check whether or not they are binding to an IPv6 IP..
		if (ip_to_bind.find(':') != std::string::npos)
			v6 = true;
#endif
		// And if it fails, don't do anything.
		return this->DoBindMagic(ip_to_bind, v6);
	}

	for (int j = 0; j < Conf.Enumerate("bind"); j++)
	{
		// We only want to try bind to a server ip.
		if (Conf.ReadValue("bind","type",j) != "servers")
			continue;

		// set current IP to the <bind> tag
		std::string current_ip = Conf.ReadValue("bind","address",j);

#ifdef IPV6
		// Check whether this <bind> is for an ipv6 address
		if (current_ip.find(':') != std::string::npos)
			v6 = true;
		else
			v6 = false;
#endif

		// Make sure IP is nothing local
		if (current_ip == "*" || current_ip == "127.0.0.1" || current_ip.empty() || current_ip == "::1")
			continue;

		// Try bind, don't fail if it doesn't bind though.
		if (this->DoBindMagic(current_ip, v6))
			return true;
	}

	// NOTE: You may wonder WTF we are returning *true* here, but that is because there were no custom binds setup, and so we have nothing to do
	// (remember, outgoing connections without binding are perfectly ok).
	ServerInstance->Logs->Log("SOCKET", DEBUG,"nothing in the config to bind()!");
	return true;
}

bool BufferedSocket::DoConnect(unsigned long maxtime)
{
	irc::sockets::sockaddrs addr;
	irc::sockets::aptosa(this->host, this->port, &addr);

	this->fd = socket(addr.sa.sa_family, SOCK_STREAM, 0);

	if (this->fd == -1)
	{
		this->state = I_ERROR;
		this->OnError(I_ERR_SOCKET);
		return false;
	}

	if (!this->BindAddr(this->cbindip))
	{
		this->Close();
		this->fd = -1;
		return false;
	}

	ServerInstance->SE->NonBlocking(this->fd);

	if (ServerInstance->SE->Connect(this, &addr.sa, sa_size(addr)) == -1)
	{
		if (errno != EINPROGRESS)
		{
			this->OnError(I_ERR_CONNECT);
			this->Close();
			this->state = I_ERROR;
			return false;
		}

		this->Timeout = new SocketTimeout(this->GetFd(), this->ServerInstance, this, maxtime, this->ServerInstance->Time());
		this->ServerInstance->Timers->AddTimer(this->Timeout);
	}

	this->state = I_CONNECTING;
	if (this->fd > -1)
	{
		if (!this->ServerInstance->SE->AddFd(this))
		{
			this->OnError(I_ERR_NOMOREFDS);
			this->Close();
			this->state = I_ERROR;
			return false;
		}
		this->SetQueues();
	}

	ServerInstance->Logs->Log("SOCKET", DEBUG,"BufferedSocket::DoConnect success");
	return true;
}


void BufferedSocket::Close()
{
	/* Save this, so we dont lose it,
	 * otherise on failure, error messages
	 * might be inaccurate.
	 */
	int save = errno;
	if (this->fd > -1)
	{
		if (this->GetIOHook())
		{
			try
			{
				this->GetIOHook()->OnRawSocketClose(this->fd);
			}
			catch (CoreException& modexcept)
			{
				ServerInstance->Logs->Log("SOCKET", DEFAULT,"%s threw an exception: %s", modexcept.GetSource(), modexcept.GetReason());
			}
		}
		ServerInstance->SE->Shutdown(this, 2);
		if (ServerInstance->SE->Close(this) != -1)
			this->OnClose();

		if (ServerInstance->SocketCull.find(this) == ServerInstance->SocketCull.end())
			ServerInstance->SocketCull[this] = this;
	}
	errno = save;
}

std::string BufferedSocket::GetIP()
{
	return this->IP;
}

const char* BufferedSocket::Read()
{
	if (!ServerInstance->SE->BoundsCheckFd(this))
		return NULL;

	int n = 0;
	char* ReadBuffer = ServerInstance->GetReadBuffer();

	if (this->GetIOHook())
	{
		int result2 = 0;
		int MOD_RESULT = 0;
		try
		{
			MOD_RESULT = this->GetIOHook()->OnRawSocketRead(this->fd, ReadBuffer, ServerInstance->Config->NetBufferSize, result2);
		}
		catch (CoreException& modexcept)
		{
			ServerInstance->Logs->Log("SOCKET", DEFAULT,"%s threw an exception: %s", modexcept.GetSource(), modexcept.GetReason());
		}
		if (MOD_RESULT < 0)
		{
			n = -1;
			errno = EAGAIN;
		}
		else
		{
			n = result2;
		}
	}
	else
	{
		n = recv(this->fd, ReadBuffer, ServerInstance->Config->NetBufferSize, 0);
	}

	/*
	 * This used to do some silly bounds checking instead of just passing bufsize - 1 to recv.
	 * Not only does that make absolutely no sense, but it could potentially result in a read buffer's worth
	 * of data being thrown into the bit bucket for no good reason, which is just *stupid*.. do things correctly now.
	 * --w00t (july 2, 2008)
	 */
	if (n > 0)
	{
		ReadBuffer[n] = 0;
		return ReadBuffer;
	}
	else
	{
		int err = errno;
		if (err == EAGAIN)
			return "";
		else
			return NULL;
	}
}

/*
 * This function formerly tried to flush write buffer each call.
 * While admirable in attempting to get the data out to wherever
 * it is going, on a full socket, it's just going to syscall write() and
 * EAGAIN constantly, instead of waiting in the SE to know if it can write
 * which will chew a bit of CPU.
 *
 * So, now this function returns void (take note) and just adds to the sendq.
 *
 * It'll get written at a determinate point when the socketengine tells us it can write.
 *		-- w00t (april 1, 2008)
 */
void BufferedSocket::Write(const std::string &data)
{
	/* Append the data to the back of the queue ready for writing */
	outbuffer.push_back(data);

	/* Mark ourselves as wanting write */
	this->ServerInstance->SE->WantWrite(this);
}

bool BufferedSocket::FlushWriteBuffer()
{
	errno = 0;
	if ((this->fd > -1) && (this->state == I_CONNECTED))
	{
		if (this->GetIOHook())
		{
			while (outbuffer.size() && (errno != EAGAIN))
			{
				try
				{
					/* XXX: The lack of buffering here is NOT a bug, modules implementing this interface have to
					 * implement their own buffering mechanisms
					 */
					this->GetIOHook()->OnRawSocketWrite(this->fd, outbuffer[0].c_str(), outbuffer[0].length());
					outbuffer.pop_front();
				}
				catch (CoreException& modexcept)
				{
					ServerInstance->Logs->Log("SOCKET", DEBUG,"%s threw an exception: %s", modexcept.GetSource(), modexcept.GetReason());
					return true;
				}
			}
		}
		else
		{
			/* If we have multiple lines, try to send them all,
			 * not just the first one -- Brain
			 */
			while (outbuffer.size() && (errno != EAGAIN))
			{
				/* Send a line */
				int result = ServerInstance->SE->Send(this, outbuffer[0].c_str(), outbuffer[0].length(), 0);

				if (result > 0)
				{
					if ((unsigned int)result >= outbuffer[0].length())
					{
						/* The whole block was written (usually a line)
						 * Pop the block off the front of the queue,
						 * dont set errno, because we are clear of errors
						 * and want to try and write the next block too.
						 */
						outbuffer.pop_front();
					}
					else
					{
						std::string temp = outbuffer[0].substr(result);
						outbuffer[0] = temp;
						/* We didnt get the whole line out. arses.
						 * Try again next time, i guess. Set errno,
						 * because we shouldnt be writing any more now,
						 * until the socketengine says its safe to do so.
						 */
						errno = EAGAIN;
					}
				}
				else if (result == 0)
				{
					this->ServerInstance->SE->DelFd(this);
					this->Close();
					return true;
				}
				else if ((result == -1) && (errno != EAGAIN))
				{
					this->OnError(I_ERR_WRITE);
					this->state = I_ERROR;
					this->ServerInstance->SE->DelFd(this);
					this->Close();
					return true;
				}
			}
		}
	}

	if ((errno == EAGAIN) && (fd > -1))
	{
		this->ServerInstance->SE->WantWrite(this);
	}

	return (fd < 0);
}

void SocketTimeout::Tick(time_t)
{
	ServerInstance->Logs->Log("SOCKET", DEBUG,"SocketTimeout::Tick");

	if (ServerInstance->SE->GetRef(this->sfd) != this->sock)
		return;

	if (this->sock->state == I_CONNECTING)
	{
		// for connecting sockets, the timeout can occur
		// which causes termination of the connection after
		// the given number of seconds without a successful
		// connection.
		this->sock->OnTimeout();
		this->sock->OnError(I_ERR_TIMEOUT);

		/* NOTE: We must set this AFTER DelFd, as we added
		 * this socket whilst writeable. This means that we
		 * must DELETE the socket whilst writeable too!
		 */
		this->sock->state = I_ERROR;

		if (ServerInstance->SocketCull.find(this->sock) == ServerInstance->SocketCull.end())
			ServerInstance->SocketCull[this->sock] = this->sock;
	}

	this->sock->Timeout = NULL;
}

bool BufferedSocket::InternalMarkConnected()
{
	/* Our socket was in write-state, so delete it and re-add it
	 * in read-state.
	 */
	this->SetState(I_CONNECTED);

	if (this->GetIOHook())
	{
		ServerInstance->Logs->Log("SOCKET",DEBUG,"Hook for raw connect");
		try
		{
			this->GetIOHook()->OnRawSocketConnect(this->fd);
		}
		catch (CoreException& modexcept)
		{
			ServerInstance->Logs->Log("SOCKET",DEBUG,"%s threw an exception: %s", modexcept.GetSource(), modexcept.GetReason());
			return false;
		}
	}
	return this->OnConnected();
}

void BufferedSocket::SetState(BufferedSocketState s)
{
	this->state = s;
}

BufferedSocketState BufferedSocket::GetState()
{
	return this->state;
}

bool BufferedSocket::OnConnected() { return true; }
void BufferedSocket::OnError(BufferedSocketError) { return; }
int BufferedSocket::OnDisconnect() { return 0; }
bool BufferedSocket::OnDataReady() { return true; }
bool BufferedSocket::OnWriteReady()
{
	// Default behaviour: just try write some.
	return !this->FlushWriteBuffer();
}
void BufferedSocket::OnTimeout() { return; }
void BufferedSocket::OnClose() { return; }

BufferedSocket::~BufferedSocket()
{
	this->Close();
	if (Timeout)
	{
		ServerInstance->Timers->DelTimer(Timeout);
		Timeout = NULL;
	}
}

void BufferedSocket::HandleEvent(EventType et, int errornum)
{
	switch (et)
	{
		case EVENT_ERROR:
		{
			switch (errornum)
			{
				case ETIMEDOUT:
					this->OnError(I_ERR_TIMEOUT);
					break;
				case ECONNREFUSED:
				case 0:
					this->OnError(this->state == I_CONNECTING ? I_ERR_CONNECT : I_ERR_WRITE);
					break;
				case EADDRINUSE:
					this->OnError(I_ERR_BIND);
					break;
				case EPIPE:
				case EIO:
					this->OnError(I_ERR_WRITE);
					break;
			}

			if (this->ServerInstance->SocketCull.find(this) == this->ServerInstance->SocketCull.end())
				this->ServerInstance->SocketCull[this] = this;
			return;
			break;
		}
		case EVENT_READ:
		{
			if (!this->OnDataReady())
			{
				if (this->ServerInstance->SocketCull.find(this) == this->ServerInstance->SocketCull.end())
					this->ServerInstance->SocketCull[this] = this;
				return;
			}
			break;
		}
		case EVENT_WRITE:
		{
			if (this->state == I_CONNECTING)
			{
				if (!this->InternalMarkConnected())
				{
					if (this->ServerInstance->SocketCull.find(this) == this->ServerInstance->SocketCull.end())
						this->ServerInstance->SocketCull[this] = this;
					return;
				}
				return;
			}
			else
			{
				if (!this->OnWriteReady())
				{
					if (this->ServerInstance->SocketCull.find(this) == this->ServerInstance->SocketCull.end())
						this->ServerInstance->SocketCull[this] = this;
					return;
				}
			}
			break;
		}
	}
}