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