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