]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/inspsocket.cpp
f76543562152235cade8d2cce675ca4e2d3e49f6
[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         setsockopt(nfd,SOL_SOCKET,SO_SNDBUF,(const char *)&sendbuf,sizeof(sendbuf));
153         setsockopt(nfd,SOL_SOCKET,SO_RCVBUF,(const char *)&recvbuf,sizeof(sendbuf));
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         this->state = I_CONNECTING;
324         if (this->fd > -1)
325         {
326                 if (!this->Instance->SE->AddFd(this))
327                 {
328                         this->OnError(I_ERR_NOMOREFDS);
329                         this->Close();
330                         this->state = I_ERROR;
331                         return false;
332                 }
333                 this->SetQueues(this->fd);
334         }
335         return true;
336 }
337
338
339 void InspSocket::Close()
340 {
341         /* Save this, so we dont lose it,
342          * otherise on failure, error messages
343          * might be inaccurate.
344          */
345         int save = errno;
346         if (this->fd > -1)
347         {
348                 if (this->IsIOHooked && Instance->Config->GetIOHook(this))
349                 {
350                         try
351                         {
352                                 Instance->Config->GetIOHook(this)->OnRawSocketClose(this->fd);
353                         }
354                         catch (CoreException& modexcept)
355                         {
356                                 Instance->Log(DEFAULT,"%s threw an exception: %s", modexcept.GetSource(), modexcept.GetReason());
357                         }
358                 }
359                 this->OnClose();
360                 shutdown(this->fd,2);
361                 close(this->fd);
362         }
363         errno = save;
364 }
365
366 std::string InspSocket::GetIP()
367 {
368         return this->IP;
369 }
370
371 char* InspSocket::Read()
372 {
373 #ifdef WINDOWS
374         if ((fd < 0) || (m_internalFd > MAX_DESCRIPTORS))
375 #else
376         if ((fd < 0) || (fd > MAX_DESCRIPTORS))
377 #endif
378                 return NULL;
379
380         int n = 0;
381
382         if (this->IsIOHooked)
383         {
384                 int result2 = 0;
385                 int MOD_RESULT = 0;
386                 try
387                 {
388                         MOD_RESULT = Instance->Config->GetIOHook(this)->OnRawSocketRead(this->fd,this->ibuf,sizeof(this->ibuf),result2);
389                 }
390                 catch (CoreException& modexcept)
391                 {
392                         Instance->Log(DEFAULT,"%s threw an exception: %s", modexcept.GetSource(), modexcept.GetReason());
393                 }
394                 if (MOD_RESULT < 0)
395                 {
396                         n = -1;
397                         errno = EAGAIN;
398                 }
399                 else
400                 {
401                         n = result2;
402                 }
403         }
404         else
405         {
406                 n = recv(this->fd,this->ibuf,sizeof(this->ibuf),0);
407         }
408
409         if ((n > 0) && (n <= (int)sizeof(this->ibuf)))
410         {
411                 ibuf[n] = 0;
412                 return ibuf;
413         }
414         else
415         {
416                 int err = errno;
417                 if (err == EAGAIN)
418                         return "";
419                 else
420                         return NULL;
421         }
422 }
423
424 void InspSocket::MarkAsClosed()
425 {
426 }
427
428 // There are two possible outcomes to this function.
429 // It will either write all of the data, or an undefined amount.
430 // If an undefined amount is written the connection has failed
431 // and should be aborted.
432 int InspSocket::Write(const std::string &data)
433 {
434         /* Try and append the data to the back of the queue, and send it on its way
435          */
436         outbuffer.push_back(data);
437         this->Instance->SE->WantWrite(this);
438         return (!this->FlushWriteBuffer());
439 }
440
441 bool InspSocket::FlushWriteBuffer()
442 {
443         errno = 0;
444         if ((this->fd > -1) && (this->state == I_CONNECTED))
445         {
446                 if (this->IsIOHooked)
447                 {
448                         while (outbuffer.size() && (errno != EAGAIN))
449                         {
450                                 try
451                                 {
452                                         /* XXX: The lack of buffering here is NOT a bug, modules implementing this interface have to
453                                          * implement their own buffering mechanisms
454                                          */
455                                         Instance->Config->GetIOHook(this)->OnRawSocketWrite(this->fd, outbuffer[0].c_str(), outbuffer[0].length());
456                                         outbuffer.pop_front();
457                                 }
458                                 catch (CoreException& modexcept)
459                                 {
460                                         Instance->Log(DEBUG,"%s threw an exception: %s", modexcept.GetSource(), modexcept.GetReason());
461                                         return true;
462                                 }
463                         }
464                 }
465                 else
466                 {
467                         /* If we have multiple lines, try to send them all,
468                          * not just the first one -- Brain
469                          */
470                         while (outbuffer.size() && (errno != EAGAIN))
471                         {
472                                 /* Send a line */
473 #ifndef WIN32
474                                 int result = write(this->fd,outbuffer[0].c_str(),outbuffer[0].length());
475 #else
476                                 int result = send(this->fd,outbuffer[0].c_str(),outbuffer[0].length(), 0);
477 #endif
478                                 if (result > 0)
479                                 {
480                                         if ((unsigned int)result >= outbuffer[0].length())
481                                         {
482                                                 /* The whole block was written (usually a line)
483                                                  * Pop the block off the front of the queue,
484                                                  * dont set errno, because we are clear of errors
485                                                  * and want to try and write the next block too.
486                                                  */
487                                                 outbuffer.pop_front();
488                                         }
489                                         else
490                                         {
491                                                 std::string temp = outbuffer[0].substr(result);
492                                                 outbuffer[0] = temp;
493                                                 /* We didnt get the whole line out. arses.
494                                                  * Try again next time, i guess. Set errno,
495                                                  * because we shouldnt be writing any more now,
496                                                  * until the socketengine says its safe to do so.
497                                                  */
498                                                 errno = EAGAIN;
499                                         }
500                                 }
501                                 else if ((result == -1) && (errno != EAGAIN))
502                                 {
503                                         this->OnError(I_ERR_WRITE);
504                                         this->state = I_ERROR;
505                                         this->Instance->SE->DelFd(this);
506                                         this->Close();
507                                         return true;
508                                 }
509                         }
510                 }
511         }
512
513         if ((errno == EAGAIN) && (fd > -1))
514         {
515                 this->Instance->SE->WantWrite(this);
516         }
517
518         return (fd < 0);
519 }
520
521 void SocketTimeout::Tick(time_t now)
522 {
523         if (ServerInstance->SE->GetRef(this->sfd) != this->sock)
524                 return;
525
526         if (this->sock->state == I_CONNECTING)
527         {
528                 // for non-listening sockets, the timeout can occur
529                 // which causes termination of the connection after
530                 // the given number of seconds without a successful
531                 // connection.
532                 this->sock->OnTimeout();
533                 this->sock->OnError(I_ERR_TIMEOUT);
534                 this->sock->timeout = true;
535
536                 /* NOTE: We must set this AFTER DelFd, as we added
537                  * this socket whilst writeable. This means that we
538                  * must DELETE the socket whilst writeable too!
539                  */
540                 this->sock->state = I_ERROR;
541
542                 if (ServerInstance->SocketCull.find(this->sock) == ServerInstance->SocketCull.end())
543                         ServerInstance->SocketCull[this->sock] = this->sock;
544         }
545
546         this->sock->Timeout = NULL;
547 }
548
549 bool InspSocket::Poll()
550 {
551 #ifdef WINDOWS
552         if(Instance->SE->GetRef(this->fd) != this)
553                 return false;
554         int incoming = -1;
555 #else
556         if (this->Instance->SE->GetRef(this->fd) != this)
557                 return false;
558
559         int incoming = -1;
560
561         if ((fd < 0) || (fd > MAX_DESCRIPTORS))
562                 return false;
563 #endif
564         switch (this->state)
565         {
566                 case I_CONNECTING:
567                         /* Our socket was in write-state, so delete it and re-add it
568                          * in read-state.
569                          */
570 #ifndef WINDOWS
571                         if (this->fd > -1)
572                         {
573                                 this->Instance->SE->DelFd(this);
574                                 this->SetState(I_CONNECTED);
575                                 if (!this->Instance->SE->AddFd(this))
576                                         return false;
577                         }
578 #else
579                         this->SetState(I_CONNECTED);
580 #endif
581                         if (Instance->Config->GetIOHook(this))
582                         {
583                                 try
584                                 {
585                                         Instance->Config->GetIOHook(this)->OnRawSocketConnect(this->fd);
586                                 }
587                                 catch (CoreException& modexcept)
588                                 {
589                                         Instance->Log(DEBUG,"%s threw an exception: %s", modexcept.GetSource(), modexcept.GetReason());
590                                 }
591                         }
592                         return this->OnConnected();
593                 break;
594                 case I_LISTENING:
595                 {
596                         sockaddr* client = new sockaddr[2];
597                         length = sizeof (sockaddr_in);
598                         std::string recvip;
599 #ifdef IPV6
600                         if ((!*this->host) || strchr(this->host, ':'))
601                                 length = sizeof(sockaddr_in6);
602 #endif
603                         incoming = _accept (this->fd, client, &length);
604 #ifdef IPV6
605                         if ((!*this->host) || strchr(this->host, ':'))
606                         {
607                                 char buf[1024];
608                                 recvip = inet_ntop(AF_INET6, &((sockaddr_in6*)client)->sin6_addr, buf, sizeof(buf));
609                         }
610                         else
611 #endif
612                         recvip = inet_ntoa(((sockaddr_in*)client)->sin_addr);
613                         this->OnIncomingConnection(incoming, (char*)recvip.c_str());
614
615                         if (this->IsIOHooked)
616                         {
617                                 try
618                                 {
619                                         Instance->Config->GetIOHook(this)->OnRawSocketAccept(incoming, recvip.c_str(), this->port);
620                                 }
621                                 catch (CoreException& modexcept)
622                                 {
623                                         Instance->Log(DEBUG,"%s threw an exception: %s", modexcept.GetSource(), modexcept.GetReason());
624                                 }
625                         }
626
627                         this->SetQueues(incoming);
628
629                         delete[] client;
630                         return true;
631                 }
632                 break;
633                 case I_CONNECTED:
634                         /* Process the read event */
635                         return this->OnDataReady();
636                 break;
637                 default:
638                 break;
639         }
640         return true;
641 }
642
643 void InspSocket::SetState(InspSocketState s)
644 {
645         this->state = s;
646 }
647
648 InspSocketState InspSocket::GetState()
649 {
650         return this->state;
651 }
652
653 int InspSocket::GetFd()
654 {
655         return this->fd;
656 }
657
658 bool InspSocket::OnConnected() { return true; }
659 void InspSocket::OnError(InspSocketError e) { return; }
660 int InspSocket::OnDisconnect() { return 0; }
661 int InspSocket::OnIncomingConnection(int newfd, char* ip) { return 0; }
662 bool InspSocket::OnDataReady() { return true; }
663 bool InspSocket::OnWriteReady() { return true; }
664 void InspSocket::OnTimeout() { return; }
665 void InspSocket::OnClose() { return; }
666
667 InspSocket::~InspSocket()
668 {
669         this->Close();
670         if (Timeout)
671         {
672                 Instance->Timers->DelTimer(Timeout);
673                 Timeout = NULL;
674         }
675 }
676
677 void InspSocket::HandleEvent(EventType et, int errornum)
678 {
679         switch (et)
680         {
681                 case EVENT_ERROR:
682                         switch (errornum)
683                         {
684                                 case ETIMEDOUT:
685                                         this->OnError(I_ERR_TIMEOUT);
686                                 break;
687                                 case ECONNREFUSED:
688                                 case 0:
689                                         this->OnError(this->state == I_CONNECTING ? I_ERR_CONNECT : I_ERR_WRITE);
690                                 break;
691                                 case EADDRINUSE:
692                                         this->OnError(I_ERR_BIND);
693                                 break;
694                                 case EPIPE:
695                                 case EIO:
696                                         this->OnError(I_ERR_WRITE);
697                                 break;
698                         }
699                         if (this->Instance->SocketCull.find(this) == this->Instance->SocketCull.end())
700                                 this->Instance->SocketCull[this] = this;
701                         return;
702                 break;
703                 case EVENT_READ:
704                         if (!this->Poll())
705                         {
706                                 if (this->Instance->SocketCull.find(this) == this->Instance->SocketCull.end())
707                                         this->Instance->SocketCull[this] = this;
708                                 return;
709                         }
710                 break;
711                 case EVENT_WRITE:
712                         if (this->WaitingForWriteEvent)
713                         {
714                                 this->WaitingForWriteEvent = false;
715                                 if (!this->OnWriteReady())
716                                 {
717                                         if (this->Instance->SocketCull.find(this) == this->Instance->SocketCull.end())
718                                                 this->Instance->SocketCull[this] = this;
719                                         return;
720                                 }
721                         }
722                         if (this->state == I_CONNECTING)
723                         {
724                                 /* This might look wrong as if we should be actually calling
725                                  * with EVENT_WRITE, but trust me it is correct. There are some
726                                  * writeability-state things in the read code, because of how
727                                  * InspSocket used to work regarding write buffering in previous
728                                  * versions of InspIRCd. - Brain
729                                  */
730                                 this->HandleEvent(EVENT_READ);
731                                 return;
732                         }
733                         else
734                         {
735                                 if (this->FlushWriteBuffer())
736                                 {
737                                         if (this->Instance->SocketCull.find(this) == this->Instance->SocketCull.end())
738                                                 this->Instance->SocketCull[this] = this;
739                                         return;
740                                 }
741                         }
742                 break;
743         }
744 }
745