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