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