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