]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/inspsocket.cpp
1a88afaca5309887c2c21e0b9b7e2c53a8b2363c
[user/henk/code/inspircd.git] / src / inspsocket.cpp
1 /*       +------------------------------------+
2  *       | Inspire Internet Relay Chat Daemon |
3  *       +------------------------------------+
4  *
5  *  InspIRCd: (C) 2002-2008 InspIRCd Development Team
6  * See: http://www.inspircd.org/wiki/index.php/Credits
7  *
8  * This program is free but copyrighted software; see
9  *            the file COPYING for details.
10  *
11  * ---------------------------------------------------
12  */
13
14 /* $Core */
15
16 #include "socket.h"
17 #include "inspstring.h"
18 #include "socketengine.h"
19 #include "inspircd.h"
20
21 bool BufferedSocket::Readable()
22 {
23         return (this->state != I_CONNECTING);
24 }
25
26 BufferedSocket::BufferedSocket(InspIRCd* SI)
27 {
28         this->Timeout = NULL;
29         this->state = I_DISCONNECTED;
30         this->fd = -1;
31         this->Instance = SI;
32 }
33
34 BufferedSocket::BufferedSocket(InspIRCd* SI, int newfd, const char* ip)
35 {
36         this->Timeout = NULL;
37         this->fd = newfd;
38         this->state = I_CONNECTED;
39         strlcpy(this->IP,ip,MAXBUF);
40         this->Instance = SI;
41         if (this->fd > -1)
42                 this->Instance->SE->AddFd(this);
43 }
44
45 BufferedSocket::BufferedSocket(InspIRCd* SI, const std::string &ipaddr, int aport, unsigned long maxtime, const std::string &connectbindip)
46 {
47         this->cbindip = connectbindip;
48         this->fd = -1;
49         this->Instance = SI;
50         strlcpy(host,ipaddr.c_str(),MAXBUF);
51         this->Timeout = NULL;
52
53         strlcpy(this->host,ipaddr.c_str(),MAXBUF);
54         this->port = aport;
55
56         bool ipvalid = true;
57 #ifdef IPV6
58         if (strchr(host,':'))
59         {
60                 in6_addr n;
61                 if (inet_pton(AF_INET6, host, &n) < 1)
62                         ipvalid = false;
63         }
64         else
65 #endif
66         {
67                 in_addr n;
68                 if (inet_aton(host,&n) < 1)
69                         ipvalid = false;
70         }
71         if (!ipvalid)
72         {
73                 this->Instance->Logs->Log("SOCKET", DEBUG,"BUG: Hostname passed to BufferedSocket, rather than an IP address!");
74                 this->OnError(I_ERR_CONNECT);
75                 this->Close();
76                 this->fd = -1;
77                 this->state = I_ERROR;
78                 return;
79         }
80         else
81         {
82                 strlcpy(this->IP,host,MAXBUF);
83                 timeout_val = maxtime;
84                 if (!this->DoConnect())
85                 {
86                         this->OnError(I_ERR_CONNECT);
87                         this->Close();
88                         this->fd = -1;
89                         this->state = I_ERROR;
90                         return;
91                 }
92         }
93 }
94
95 void BufferedSocket::WantWrite()
96 {
97         this->Instance->SE->WantWrite(this);
98 }
99
100 void BufferedSocket::SetQueues(int nfd)
101 {
102         // attempt to increase socket sendq and recvq as high as its possible
103         int sendbuf = 32768;
104         int recvbuf = 32768;
105         if(setsockopt(nfd,SOL_SOCKET,SO_SNDBUF,(const char *)&sendbuf,sizeof(sendbuf)) || setsockopt(nfd,SOL_SOCKET,SO_RCVBUF,(const char *)&recvbuf,sizeof(sendbuf)))
106         {
107                 //this->Instance->Log(DEFAULT, "Could not increase SO_SNDBUF/SO_RCVBUF for socket %u", GetFd());
108                 ; // 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.
109         }
110 }
111
112 /* Most irc servers require you to specify the ip you want to bind to.
113  * If you dont specify an IP, they rather dumbly bind to the first IP
114  * of the box (e.g. INADDR_ANY). In InspIRCd, we scan thought the IP
115  * addresses we've bound server ports to, and we try and bind our outbound
116  * connections to the first usable non-loopback and non-any IP we find.
117  * This is easier to configure when you have a lot of links and a lot
118  * of servers to configure.
119  */
120 bool BufferedSocket::BindAddr(const std::string &ip)
121 {
122         ConfigReader Conf(this->Instance);
123         socklen_t size = sizeof(sockaddr_in);
124 #ifdef IPV6
125         bool v6 = false;
126         /* Are we looking for a binding to fit an ipv6 host? */
127         if ((ip.empty()) || (ip.find(':') != std::string::npos))
128                 v6 = true;
129 #endif
130         int j = 0;
131         while (j < Conf.Enumerate("bind") || (!ip.empty()))
132         {
133                 std::string sIP = ip.empty() ? Conf.ReadValue("bind","address",j) : ip;
134                 if (!ip.empty() || Conf.ReadValue("bind","type",j) == "servers")
135                 {
136                         if (!ip.empty() || ((sIP != "*") && (sIP != "127.0.0.1") && (!sIP.empty()) && (sIP != "::1")))
137                         {
138                                 /* The [2] is required because we may write a sockaddr_in6 here, and sockaddr_in6 is larger than sockaddr, where sockaddr_in4 is not. */
139                                 sockaddr* s = new sockaddr[2];
140 #ifdef IPV6
141                                 if (v6)
142                                 {
143                                         in6_addr n;
144                                         if (inet_pton(AF_INET6, sIP.c_str(), &n) > 0)
145                                         {
146                                                 memcpy(&((sockaddr_in6*)s)->sin6_addr, &n, sizeof(sockaddr_in6));
147                                                 ((sockaddr_in6*)s)->sin6_port = 0;
148                                                 ((sockaddr_in6*)s)->sin6_family = AF_INET6;
149                                                 size = sizeof(sockaddr_in6);
150                                         }
151                                         else
152                                         {
153                                                 delete[] s;
154                                                 j++;
155                                                 continue;
156                                         }
157                                 }
158                                 else
159 #endif
160                                 {
161                                         in_addr n;
162                                         if (inet_aton(sIP.c_str(), &n) > 0)
163                                         {
164                                                 ((sockaddr_in*)s)->sin_addr = n;
165                                                 ((sockaddr_in*)s)->sin_port = 0;
166                                                 ((sockaddr_in*)s)->sin_family = AF_INET;
167                                         }
168                                         else
169                                         {
170                                                 delete[] s;
171                                                 j++;
172                                                 continue;
173                                         }
174                                 }
175
176                                 if (Instance->SE->Bind(this->fd, s, size) < 0)
177                                 {
178                                         this->state = I_ERROR;
179                                         this->OnError(I_ERR_BIND);
180                                         this->fd = -1;
181                                         delete[] s;
182                                         return false;
183                                 }
184
185                                 delete[] s;
186                                 return true;
187                         }
188                 }
189                 j++;
190         }
191         Instance->Logs->Log("SOCKET", DEBUG,"nothing in the config to bind()!");
192         return true;
193 }
194
195 bool BufferedSocket::DoConnect()
196 {
197         /* The [2] is required because we may write a sockaddr_in6 here, and sockaddr_in6 is larger than sockaddr, where sockaddr_in4 is not. */
198         sockaddr* addr = new sockaddr[2];
199         socklen_t size = sizeof(sockaddr_in);
200 #ifdef IPV6
201         bool v6 = false;
202         if ((!*this->host) || strchr(this->host, ':'))
203                 v6 = true;
204
205         if (v6)
206         {
207                 this->fd = socket(AF_INET6, SOCK_STREAM, 0);
208                 if ((this->fd > -1) && ((strstr(this->IP,"::ffff:") != (char*)&this->IP) && (strstr(this->IP,"::FFFF:") != (char*)&this->IP)))
209                 {
210                         if (!this->BindAddr(this->cbindip))
211                         {
212                                 delete[] addr;
213                                 return false;
214                         }
215                 }
216         }
217         else
218 #endif
219         {
220                 this->fd = socket(AF_INET, SOCK_STREAM, 0);
221                 if (this->fd > -1)
222                 {
223                         if (!this->BindAddr(this->cbindip))
224                         {
225                                 delete[] addr;
226                                 return false;
227                         }
228                 }
229         }
230
231         if (this->fd == -1)
232         {
233                 this->state = I_ERROR;
234                 this->OnError(I_ERR_SOCKET);
235                 delete[] addr;
236                 return false;
237         }
238
239 #ifdef IPV6
240         if (v6)
241         {
242                 in6_addr addy;
243                 if (inet_pton(AF_INET6, this->host, &addy) > 0)
244                 {
245                         ((sockaddr_in6*)addr)->sin6_family = AF_INET6;
246                         memcpy(&((sockaddr_in6*)addr)->sin6_addr, &addy, sizeof(addy));
247                         ((sockaddr_in6*)addr)->sin6_port = htons(this->port);
248                         size = sizeof(sockaddr_in6);
249                 }
250         }
251         else
252 #endif
253         {
254                 in_addr addy;
255                 if (inet_aton(this->host, &addy) > 0)
256                 {
257                         ((sockaddr_in*)addr)->sin_family = AF_INET;
258                         ((sockaddr_in*)addr)->sin_addr = addy;
259                         ((sockaddr_in*)addr)->sin_port = htons(this->port);
260                 }
261         }
262
263         Instance->SE->NonBlocking(this->fd);
264
265         if (Instance->SE->Connect(this, (sockaddr*)addr, size) == -1)
266         {
267                 if (errno != EINPROGRESS)
268                 {
269                         this->OnError(I_ERR_CONNECT);
270                         this->Close();
271                         this->state = I_ERROR;
272                         return false;
273                 }
274
275                 this->Timeout = new SocketTimeout(this->GetFd(), this->Instance, this, timeout_val, this->Instance->Time());
276                 this->Instance->Timers->AddTimer(this->Timeout);
277         }
278
279         this->state = I_CONNECTING;
280         if (this->fd > -1)
281         {
282                 if (!this->Instance->SE->AddFd(this))
283                 {
284                         this->OnError(I_ERR_NOMOREFDS);
285                         this->Close();
286                         this->state = I_ERROR;
287                         return false;
288                 }
289                 this->SetQueues(this->fd);
290         }
291
292         Instance->Logs->Log("SOCKET", DEBUG,"BufferedSocket::DoConnect success");
293         return true;
294 }
295
296
297 void BufferedSocket::Close()
298 {
299         /* Save this, so we dont lose it,
300          * otherise on failure, error messages
301          * might be inaccurate.
302          */
303         int save = errno;
304         if (this->fd > -1)
305         {
306                 if (this->GetIOHook())
307                 {
308                         try
309                         {
310                                 this->GetIOHook()->OnRawSocketClose(this->fd);
311                         }
312                         catch (CoreException& modexcept)
313                         {
314                                 Instance->Logs->Log("SOCKET", DEFAULT,"%s threw an exception: %s", modexcept.GetSource(), modexcept.GetReason());
315                         }
316                 }
317                 Instance->SE->Shutdown(this, 2);
318                 if (Instance->SE->Close(this) != -1)
319                         this->OnClose();
320
321                 if (Instance->SocketCull.find(this) == Instance->SocketCull.end())
322                         Instance->SocketCull[this] = this;
323         }
324         errno = save;
325 }
326
327 std::string BufferedSocket::GetIP()
328 {
329         return this->IP;
330 }
331
332 const char* BufferedSocket::Read()
333 {
334         if (!Instance->SE->BoundsCheckFd(this))
335                 return NULL;
336
337         int n = 0;
338         char* ReadBuffer = Instance->GetReadBuffer();
339
340         if (this->GetIOHook())
341         {
342                 int result2 = 0;
343                 int MOD_RESULT = 0;
344                 try
345                 {
346                         MOD_RESULT = this->GetIOHook()->OnRawSocketRead(this->fd, ReadBuffer, Instance->Config->NetBufferSize, result2);
347                 }
348                 catch (CoreException& modexcept)
349                 {
350                         Instance->Logs->Log("SOCKET", DEFAULT,"%s threw an exception: %s", modexcept.GetSource(), modexcept.GetReason());
351                 }
352                 if (MOD_RESULT < 0)
353                 {
354                         n = -1;
355                         errno = EAGAIN;
356                 }
357                 else
358                 {
359                         n = result2;
360                 }
361         }
362         else
363         {
364                 n = recv(this->fd, ReadBuffer, Instance->Config->NetBufferSize, 0);
365         }
366
367         /*
368          * This used to do some silly bounds checking instead of just passing bufsize - 1 to recv.
369          * Not only does that make absolutely no sense, but it could potentially result in a read buffer's worth
370          * of data being thrown into the bit bucket for no good reason, which is just *stupid*.. do things correctly now.
371          * --w00t (july 2, 2008)
372          */
373         if (n > 0)
374         {
375                 ReadBuffer[n] = 0;
376                 return ReadBuffer;
377         }
378         else
379         {
380                 int err = errno;
381                 if (err == EAGAIN)
382                         return "";
383                 else
384                         return NULL;
385         }
386 }
387
388 /*
389  * This function formerly tried to flush write buffer each call.
390  * While admirable in attempting to get the data out to wherever
391  * it is going, on a full socket, it's just going to syscall write() and
392  * EAGAIN constantly, instead of waiting in the SE to know if it can write
393  * which will chew a bit of CPU.
394  *
395  * So, now this function returns void (take note) and just adds to the sendq.
396  *
397  * It'll get written at a determinate point when the socketengine tells us it can write.
398  *              -- w00t (april 1, 2008)
399  */
400 void BufferedSocket::Write(const std::string &data)
401 {
402         /* Append the data to the back of the queue ready for writing */
403         outbuffer.push_back(data);
404
405         /* Mark ourselves as wanting write */
406         this->Instance->SE->WantWrite(this);
407 }
408
409 bool BufferedSocket::FlushWriteBuffer()
410 {
411         errno = 0;
412         if ((this->fd > -1) && (this->state == I_CONNECTED))
413         {
414                 if (this->GetIOHook())
415                 {
416                         while (outbuffer.size() && (errno != EAGAIN))
417                         {
418                                 try
419                                 {
420                                         /* XXX: The lack of buffering here is NOT a bug, modules implementing this interface have to
421                                          * implement their own buffering mechanisms
422                                          */
423                                         this->GetIOHook()->OnRawSocketWrite(this->fd, outbuffer[0].c_str(), outbuffer[0].length());
424                                         outbuffer.pop_front();
425                                 }
426                                 catch (CoreException& modexcept)
427                                 {
428                                         Instance->Logs->Log("SOCKET", DEBUG,"%s threw an exception: %s", modexcept.GetSource(), modexcept.GetReason());
429                                         return true;
430                                 }
431                         }
432                 }
433                 else
434                 {
435                         /* If we have multiple lines, try to send them all,
436                          * not just the first one -- Brain
437                          */
438                         while (outbuffer.size() && (errno != EAGAIN))
439                         {
440                                 /* Send a line */
441                                 int result = Instance->SE->Send(this, outbuffer[0].c_str(), outbuffer[0].length(), 0);
442
443                                 if (result > 0)
444                                 {
445                                         if ((unsigned int)result >= outbuffer[0].length())
446                                         {
447                                                 /* The whole block was written (usually a line)
448                                                  * Pop the block off the front of the queue,
449                                                  * dont set errno, because we are clear of errors
450                                                  * and want to try and write the next block too.
451                                                  */
452                                                 outbuffer.pop_front();
453                                         }
454                                         else
455                                         {
456                                                 std::string temp = outbuffer[0].substr(result);
457                                                 outbuffer[0] = temp;
458                                                 /* We didnt get the whole line out. arses.
459                                                  * Try again next time, i guess. Set errno,
460                                                  * because we shouldnt be writing any more now,
461                                                  * until the socketengine says its safe to do so.
462                                                  */
463                                                 errno = EAGAIN;
464                                         }
465                                 }
466                                 else if (result == 0)
467                                 {
468                                         this->Instance->SE->DelFd(this);
469                                         this->Close();
470                                         return true;
471                                 }
472                                 else if ((result == -1) && (errno != EAGAIN))
473                                 {
474                                         this->OnError(I_ERR_WRITE);
475                                         this->state = I_ERROR;
476                                         this->Instance->SE->DelFd(this);
477                                         this->Close();
478                                         return true;
479                                 }
480                         }
481                 }
482         }
483
484         if ((errno == EAGAIN) && (fd > -1))
485         {
486                 this->Instance->SE->WantWrite(this);
487         }
488
489         return (fd < 0);
490 }
491
492 void SocketTimeout::Tick(time_t)
493 {
494         ServerInstance->Logs->Log("SOCKET", DEBUG,"SocketTimeout::Tick");
495
496         if (ServerInstance->SE->GetRef(this->sfd) != this->sock)
497                 return;
498
499         if (this->sock->state == I_CONNECTING)
500         {
501                 // for connecting sockets, the timeout can occur
502                 // which causes termination of the connection after
503                 // the given number of seconds without a successful
504                 // connection.
505                 this->sock->OnTimeout();
506                 this->sock->OnError(I_ERR_TIMEOUT);
507                 this->sock->timeout = true;
508
509                 /* NOTE: We must set this AFTER DelFd, as we added
510                  * this socket whilst writeable. This means that we
511                  * must DELETE the socket whilst writeable too!
512                  */
513                 this->sock->state = I_ERROR;
514
515                 if (ServerInstance->SocketCull.find(this->sock) == ServerInstance->SocketCull.end())
516                         ServerInstance->SocketCull[this->sock] = this->sock;
517         }
518
519         this->sock->Timeout = NULL;
520 }
521
522 bool BufferedSocket::Poll()
523 {
524 #ifndef WINDOWS
525         if (!Instance->SE->BoundsCheckFd(this))
526                 return false;
527 #endif
528
529         if (Instance->SE->GetRef(this->fd) != this)
530                 return false;
531
532         switch (this->state)
533         {
534                 case I_CONNECTING:
535                         /* Our socket was in write-state, so delete it and re-add it
536                          * in read-state.
537                          */
538 #ifndef WINDOWS
539                         if (this->fd > -1)
540                         {
541                                 this->Instance->SE->DelFd(this);
542                                 if (!this->Instance->SE->AddFd(this))
543                                         return false;
544                         }
545 #endif
546                         this->SetState(I_CONNECTED);
547
548                         if (this->GetIOHook())
549                         {
550                                 Instance->Logs->Log("SOCKET",DEBUG,"Hook for raw connect");
551                                 try
552                                 {
553                                         this->GetIOHook()->OnRawSocketConnect(this->fd);
554                                 }
555                                 catch (CoreException& modexcept)
556                                 {
557                                         Instance->Logs->Log("SOCKET",DEBUG,"%s threw an exception: %s", modexcept.GetSource(), modexcept.GetReason());
558                                 }
559                         }
560                         return this->OnConnected();
561                 break;
562                 case I_CONNECTED:
563                         /* Process the read event */
564                         return this->OnDataReady();
565                 break;
566                 default:
567                 break;
568         }
569         return true;
570 }
571
572 void BufferedSocket::SetState(BufferedSocketState s)
573 {
574         this->state = s;
575 }
576
577 BufferedSocketState BufferedSocket::GetState()
578 {
579         return this->state;
580 }
581
582 bool BufferedSocket::OnConnected() { return true; }
583 void BufferedSocket::OnError(BufferedSocketError) { return; }
584 int BufferedSocket::OnDisconnect() { return 0; }
585 bool BufferedSocket::OnDataReady() { return true; }
586 bool BufferedSocket::OnWriteReady()
587 {
588         // Default behaviour: just try write some.
589         return !this->FlushWriteBuffer();
590 }
591 void BufferedSocket::OnTimeout() { return; }
592 void BufferedSocket::OnClose() { return; }
593
594 BufferedSocket::~BufferedSocket()
595 {
596         this->Close();
597         if (Timeout)
598         {
599                 Instance->Timers->DelTimer(Timeout);
600                 Timeout = NULL;
601         }
602 }
603
604 void BufferedSocket::HandleEvent(EventType et, int errornum)
605 {
606         switch (et)
607         {
608                 case EVENT_ERROR:
609                         switch (errornum)
610                         {
611                                 case ETIMEDOUT:
612                                         this->OnError(I_ERR_TIMEOUT);
613                                 break;
614                                 case ECONNREFUSED:
615                                 case 0:
616                                         this->OnError(this->state == I_CONNECTING ? I_ERR_CONNECT : I_ERR_WRITE);
617                                 break;
618                                 case EADDRINUSE:
619                                         this->OnError(I_ERR_BIND);
620                                 break;
621                                 case EPIPE:
622                                 case EIO:
623                                         this->OnError(I_ERR_WRITE);
624                                 break;
625                         }
626                         if (this->Instance->SocketCull.find(this) == this->Instance->SocketCull.end())
627                                 this->Instance->SocketCull[this] = this;
628                         return;
629                 break;
630                 case EVENT_READ:
631                         if (!this->Poll())
632                         {
633                                 if (this->Instance->SocketCull.find(this) == this->Instance->SocketCull.end())
634                                         this->Instance->SocketCull[this] = this;
635                                 return;
636                         }
637                 break;
638                 case EVENT_WRITE:
639                         if (this->state == I_CONNECTING)
640                         {
641                                 /* This might look wrong as if we should be actually calling
642                                  * with EVENT_WRITE, but trust me it is correct. There are some
643                                  * writeability-state things in the read code, because of how
644                                  * BufferedSocket used to work regarding write buffering in previous
645                                  * versions of InspIRCd. - Brain
646                                  */
647                                 this->HandleEvent(EVENT_READ);
648                                 return;
649                         }
650                         else
651                         {
652                                 if (!this->OnWriteReady())
653                                 {
654                                         if (this->Instance->SocketCull.find(this) == this->Instance->SocketCull.end())
655                                                 this->Instance->SocketCull[this] = this;
656                                         return;
657                                 }
658                         }
659                 break;
660         }
661 }
662