]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/inspsocket.cpp
1de46e31684213f63e4c0e119837adf56c0663ab
[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                                 sockaddr* s = new sockaddr[2];
183 #ifdef IPV6
184                                 if (v6)
185                                 {
186                                         in6_addr n;
187                                         if (inet_pton(AF_INET6, IP.c_str(), &n) > 0)
188                                         {
189                                                 memcpy(&((sockaddr_in6*)s)->sin6_addr, &n, sizeof(n));
190                                                 ((sockaddr_in6*)s)->sin6_port = 0;
191                                                 ((sockaddr_in6*)s)->sin6_family = AF_INET6;
192                                                 size = sizeof(sockaddr_in6);
193                                         }
194                                         else
195                                         {
196                                                 delete[] s;
197                                                 j++;
198                                                 continue;
199                                         }
200                                 }
201                                 else
202 #endif
203                                 {
204                                         in_addr n;
205                                         if (inet_aton(IP.c_str(), &n) > 0)
206                                         {
207                                                 ((sockaddr_in*)s)->sin_addr = n;
208                                                 ((sockaddr_in*)s)->sin_port = 0;
209                                                 ((sockaddr_in*)s)->sin_family = AF_INET;
210                                         }
211                                         else
212                                         {
213                                                 delete[] s;
214                                                 j++;
215                                                 continue;
216                                         }
217                                 }
218
219                                 if (bind(this->fd, s, size) < 0)
220                                 {
221                                         this->state = I_ERROR;
222                                         this->OnError(I_ERR_BIND);
223                                         this->fd = -1;
224                                         delete[] s;
225                                         return false;
226                                 }
227
228                                 delete[] s;
229                                 return true;
230                         }
231                 }
232                 j++;
233         }
234         return true;
235 }
236
237 bool InspSocket::DoConnect()
238 {
239         sockaddr* addr = new sockaddr[2];
240         socklen_t size = sizeof(sockaddr_in);
241 #ifdef IPV6
242         bool v6 = false;
243         if ((!*this->host) || strchr(this->host, ':'))
244                 v6 = true;
245
246         if (v6)
247         {
248                 this->fd = socket(AF_INET6, SOCK_STREAM, 0);
249                 if ((this->fd > -1) && ((strstr(this->IP,"::ffff:") != (char*)&this->IP) && (strstr(this->IP,"::FFFF:") != (char*)&this->IP)))
250                 {
251                         if (!this->BindAddr(this->cbindip))
252                         {
253                                 delete[] addr;
254                                 return false;
255                         }
256                 }
257         }
258         else
259 #endif
260         {
261                 this->fd = socket(AF_INET, SOCK_STREAM, 0);
262                 if (this->fd > -1)
263                 {
264                         if (!this->BindAddr(this->cbindip))
265                         {
266                                 delete[] addr;
267                                 return false;
268                         }
269                 }
270         }
271
272         if (this->fd == -1)
273         {
274                 this->state = I_ERROR;
275                 this->OnError(I_ERR_SOCKET);
276                 delete[] addr;
277                 return false;
278         }
279
280 #ifdef IPV6
281         if (v6)
282         {
283                 in6_addr addy;
284                 if (inet_pton(AF_INET6, this->host, &addy) > 0)
285                 {
286                         ((sockaddr_in6*)addr)->sin6_family = AF_INET6;
287                         memcpy(&((sockaddr_in6*)addr)->sin6_addr, &addy, sizeof(addy));
288                         ((sockaddr_in6*)addr)->sin6_port = htons(this->port);
289                         size = sizeof(sockaddr_in6);
290                 }
291         }
292         else
293 #endif
294         {
295                 in_addr addy;
296                 if (inet_aton(this->host, &addy) > 0)
297                 {
298                         ((sockaddr_in*)addr)->sin_family = AF_INET;
299                         ((sockaddr_in*)addr)->sin_addr = addy;
300                         ((sockaddr_in*)addr)->sin_port = htons(this->port);
301                 }
302         }
303 #ifndef WIN32
304         int flags = fcntl(this->fd, F_GETFL, 0);
305         fcntl(this->fd, F_SETFL, flags | O_NONBLOCK);
306 #else
307         unsigned long flags = 0;
308         ioctlsocket(this->fd, FIONBIO, &flags);
309 #endif
310         if (connect(this->fd, (sockaddr*)addr, size) == -1)
311         {
312                 if (errno != EINPROGRESS)
313                 {
314                         this->OnError(I_ERR_CONNECT);
315                         this->Close();
316                         this->state = I_ERROR;
317                         return false;
318                 }
319
320                 this->Timeout = new SocketTimeout(this->GetFd(), this->Instance, this, timeout_val, this->Instance->Time());
321                 this->Instance->Timers->AddTimer(this->Timeout);
322         }
323 #ifdef WIN32
324         /* Set nonblocking mode after the connect() call */
325         flags = 0;
326         ioctlsocket(this->fd, FIONBIO, &flags);
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                 shutdown(this->fd,2);
365                 if (close(this->fd) != -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 #ifndef WIN32
478                                 int result = write(this->fd,outbuffer[0].c_str(),outbuffer[0].length());
479 #else
480                                 int result = send(this->fd,outbuffer[0].c_str(),outbuffer[0].length(), 0);
481 #endif
482                                 if (result > 0)
483                                 {
484                                         if ((unsigned int)result >= outbuffer[0].length())
485                                         {
486                                                 /* The whole block was written (usually a line)
487                                                  * Pop the block off the front of the queue,
488                                                  * dont set errno, because we are clear of errors
489                                                  * and want to try and write the next block too.
490                                                  */
491                                                 outbuffer.pop_front();
492                                         }
493                                         else
494                                         {
495                                                 std::string temp = outbuffer[0].substr(result);
496                                                 outbuffer[0] = temp;
497                                                 /* We didnt get the whole line out. arses.
498                                                  * Try again next time, i guess. Set errno,
499                                                  * because we shouldnt be writing any more now,
500                                                  * until the socketengine says its safe to do so.
501                                                  */
502                                                 errno = EAGAIN;
503                                         }
504                                 }
505                                 else if ((result == -1) && (errno != EAGAIN))
506                                 {
507                                         this->OnError(I_ERR_WRITE);
508                                         this->state = I_ERROR;
509                                         this->Instance->SE->DelFd(this);
510                                         this->Close();
511                                         return true;
512                                 }
513                         }
514                 }
515         }
516
517         if ((errno == EAGAIN) && (fd > -1))
518         {
519                 this->Instance->SE->WantWrite(this);
520         }
521
522         return (fd < 0);
523 }
524
525 void SocketTimeout::Tick(time_t now)
526 {
527         if (ServerInstance->SE->GetRef(this->sfd) != this->sock)
528                 return;
529
530         if (this->sock->state == I_CONNECTING)
531         {
532                 // for non-listening sockets, the timeout can occur
533                 // which causes termination of the connection after
534                 // the given number of seconds without a successful
535                 // connection.
536                 this->sock->OnTimeout();
537                 this->sock->OnError(I_ERR_TIMEOUT);
538                 this->sock->timeout = true;
539
540                 /* NOTE: We must set this AFTER DelFd, as we added
541                  * this socket whilst writeable. This means that we
542                  * must DELETE the socket whilst writeable too!
543                  */
544                 this->sock->state = I_ERROR;
545
546                 if (ServerInstance->SocketCull.find(this->sock) == ServerInstance->SocketCull.end())
547                         ServerInstance->SocketCull[this->sock] = this->sock;
548         }
549
550         this->sock->Timeout = NULL;
551 }
552
553 bool InspSocket::Poll()
554 {
555 #ifdef WINDOWS
556         if(Instance->SE->GetRef(this->fd) != this)
557                 return false;
558         int incoming = -1;
559 #else
560         if (this->Instance->SE->GetRef(this->fd) != this)
561                 return false;
562
563         int incoming = -1;
564
565         if ((fd < 0) || (fd > MAX_DESCRIPTORS))
566                 return false;
567 #endif
568         switch (this->state)
569         {
570                 case I_CONNECTING:
571                         /* Our socket was in write-state, so delete it and re-add it
572                          * in read-state.
573                          */
574 #ifndef WINDOWS
575                         if (this->fd > -1)
576                         {
577                                 this->Instance->SE->DelFd(this);
578                                 this->SetState(I_CONNECTED);
579                                 if (!this->Instance->SE->AddFd(this))
580                                         return false;
581                         }
582 #else
583                         this->SetState(I_CONNECTED);
584 #endif
585                         Instance->Log(DEBUG,"Inspsocket I_CONNECTING state");
586                         if (Instance->Config->GetIOHook(this))
587                         {
588                                 Instance->Log(DEBUG,"Hook for raw connect");
589                                 try
590                                 {
591                                         Instance->Config->GetIOHook(this)->OnRawSocketConnect(this->fd);
592                                 }
593                                 catch (CoreException& modexcept)
594                                 {
595                                         Instance->Log(DEBUG,"%s threw an exception: %s", modexcept.GetSource(), modexcept.GetReason());
596                                 }
597                         }
598                         return this->OnConnected();
599                 break;
600                 case I_LISTENING:
601                 {
602                         sockaddr* client = new sockaddr[2];
603                         length = sizeof (sockaddr_in);
604                         std::string recvip;
605 #ifdef IPV6
606                         if ((!*this->host) || strchr(this->host, ':'))
607                                 length = sizeof(sockaddr_in6);
608 #endif
609                         incoming = _accept (this->fd, client, &length);
610 #ifdef IPV6
611                         if ((!*this->host) || strchr(this->host, ':'))
612                         {
613                                 char buf[1024];
614                                 recvip = inet_ntop(AF_INET6, &((sockaddr_in6*)client)->sin6_addr, buf, sizeof(buf));
615                         }
616                         else
617 #endif
618                         recvip = inet_ntoa(((sockaddr_in*)client)->sin_addr);
619                         this->OnIncomingConnection(incoming, (char*)recvip.c_str());
620
621                         if (this->IsIOHooked)
622                         {
623                                 try
624                                 {
625                                         Instance->Config->GetIOHook(this)->OnRawSocketAccept(incoming, recvip.c_str(), this->port);
626                                 }
627                                 catch (CoreException& modexcept)
628                                 {
629                                         Instance->Log(DEBUG,"%s threw an exception: %s", modexcept.GetSource(), modexcept.GetReason());
630                                 }
631                         }
632
633                         this->SetQueues(incoming);
634
635                         delete[] client;
636                         return true;
637                 }
638                 break;
639                 case I_CONNECTED:
640                         /* Process the read event */
641                         return this->OnDataReady();
642                 break;
643                 default:
644                 break;
645         }
646         return true;
647 }
648
649 void InspSocket::SetState(InspSocketState s)
650 {
651         this->state = s;
652 }
653
654 InspSocketState InspSocket::GetState()
655 {
656         return this->state;
657 }
658
659 int InspSocket::GetFd()
660 {
661         return this->fd;
662 }
663
664 bool InspSocket::OnConnected() { return true; }
665 void InspSocket::OnError(InspSocketError e) { return; }
666 int InspSocket::OnDisconnect() { return 0; }
667 int InspSocket::OnIncomingConnection(int newfd, char* ip) { return 0; }
668 bool InspSocket::OnDataReady() { return true; }
669 bool InspSocket::OnWriteReady() { return true; }
670 void InspSocket::OnTimeout() { return; }
671 void InspSocket::OnClose() { return; }
672
673 InspSocket::~InspSocket()
674 {
675         this->Close();
676         if (Timeout)
677         {
678                 Instance->Timers->DelTimer(Timeout);
679                 Timeout = NULL;
680         }
681 }
682
683 void InspSocket::HandleEvent(EventType et, int errornum)
684 {
685         switch (et)
686         {
687                 case EVENT_ERROR:
688                         switch (errornum)
689                         {
690                                 case ETIMEDOUT:
691                                         this->OnError(I_ERR_TIMEOUT);
692                                 break;
693                                 case ECONNREFUSED:
694                                 case 0:
695                                         this->OnError(this->state == I_CONNECTING ? I_ERR_CONNECT : I_ERR_WRITE);
696                                 break;
697                                 case EADDRINUSE:
698                                         this->OnError(I_ERR_BIND);
699                                 break;
700                                 case EPIPE:
701                                 case EIO:
702                                         this->OnError(I_ERR_WRITE);
703                                 break;
704                         }
705                         if (this->Instance->SocketCull.find(this) == this->Instance->SocketCull.end())
706                                 this->Instance->SocketCull[this] = this;
707                         return;
708                 break;
709                 case EVENT_READ:
710                         if (!this->Poll())
711                         {
712                                 if (this->Instance->SocketCull.find(this) == this->Instance->SocketCull.end())
713                                         this->Instance->SocketCull[this] = this;
714                                 return;
715                         }
716                 break;
717                 case EVENT_WRITE:
718                         if (this->WaitingForWriteEvent)
719                         {
720                                 this->WaitingForWriteEvent = false;
721                                 if (!this->OnWriteReady())
722                                 {
723                                         if (this->Instance->SocketCull.find(this) == this->Instance->SocketCull.end())
724                                                 this->Instance->SocketCull[this] = this;
725                                         return;
726                                 }
727                         }
728                         if (this->state == I_CONNECTING)
729                         {
730                                 /* This might look wrong as if we should be actually calling
731                                  * with EVENT_WRITE, but trust me it is correct. There are some
732                                  * writeability-state things in the read code, because of how
733                                  * InspSocket used to work regarding write buffering in previous
734                                  * versions of InspIRCd. - Brain
735                                  */
736                                 this->HandleEvent(EVENT_READ);
737                                 return;
738                         }
739                         else
740                         {
741                                 if (this->FlushWriteBuffer())
742                                 {
743                                         if (this->Instance->SocketCull.find(this) == this->Instance->SocketCull.end())
744                                                 this->Instance->SocketCull[this] = this;
745                                         return;
746                                 }
747                         }
748                 break;
749         }
750 }
751