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