]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/inspsocket.cpp
Ive tidied up the mode count stuff, but i still cant duplicate negative invisible...
[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         setsockopt(nfd,SOL_SOCKET,SO_SNDBUF,(const char *)&sendbuf,sizeof(sendbuf));
153         setsockopt(nfd,SOL_SOCKET,SO_RCVBUF,(const char *)&recvbuf,sizeof(sendbuf));
154 }
155
156 /* Most irc servers require you to specify the ip you want to bind to.
157  * If you dont specify an IP, they rather dumbly bind to the first IP
158  * of the box (e.g. INADDR_ANY). In InspIRCd, we scan thought the IP
159  * addresses we've bound server ports to, and we try and bind our outbound
160  * connections to the first usable non-loopback and non-any IP we find.
161  * This is easier to configure when you have a lot of links and a lot
162  * of servers to configure.
163  */
164 bool InspSocket::BindAddr(const std::string &ip)
165 {
166         ConfigReader Conf(this->Instance);
167         socklen_t size = sizeof(sockaddr_in);
168 #ifdef IPV6
169         bool v6 = false;
170         /* Are we looking for a binding to fit an ipv6 host? */
171         if ((ip.empty()) || (ip.find(':') != std::string::npos))
172                 v6 = true;
173 #endif
174         int j = 0;
175         while (j < Conf.Enumerate("bind") || (!ip.empty()))
176         {
177                 std::string IP = ip.empty() ? Conf.ReadValue("bind","address",j) : ip;
178                 if (!ip.empty() || Conf.ReadValue("bind","type",j) == "servers")
179                 {
180                         if (!ip.empty() || ((IP != "*") && (IP != "127.0.0.1") && (!IP.empty()) && (IP != "::1")))
181                         {
182                                 sockaddr* s = new sockaddr[2];
183 #ifdef IPV6
184                                 if (v6)
185                                 {
186                                         in6_addr n;
187                                         if (inet_pton(AF_INET6, IP.c_str(), &n) > 0)
188                                         {
189                                                 memcpy(&((sockaddr_in6*)s)->sin6_addr, &n, sizeof(n));
190                                                 ((sockaddr_in6*)s)->sin6_port = 0;
191                                                 ((sockaddr_in6*)s)->sin6_family = AF_INET6;
192                                                 size = sizeof(sockaddr_in6);
193                                         }
194                                         else
195                                         {
196                                                 delete[] s;
197                                                 j++;
198                                                 continue;
199                                         }
200                                 }
201                                 else
202 #endif
203                                 {
204                                         in_addr n;
205                                         if (inet_aton(IP.c_str(), &n) > 0)
206                                         {
207                                                 ((sockaddr_in*)s)->sin_addr = n;
208                                                 ((sockaddr_in*)s)->sin_port = 0;
209                                                 ((sockaddr_in*)s)->sin_family = AF_INET;
210                                         }
211                                         else
212                                         {
213                                                 delete[] s;
214                                                 j++;
215                                                 continue;
216                                         }
217                                 }
218
219                                 if (bind(this->fd, s, size) < 0)
220                                 {
221                                         this->state = I_ERROR;
222                                         this->OnError(I_ERR_BIND);
223                                         this->fd = -1;
224                                         delete[] s;
225                                         return false;
226                                 }
227
228                                 delete[] s;
229                                 return true;
230                         }
231                 }
232                 j++;
233         }
234         return true;
235 }
236
237 bool InspSocket::DoConnect()
238 {
239         sockaddr* addr = new sockaddr[2];
240         socklen_t size = sizeof(sockaddr_in);
241 #ifdef IPV6
242         bool v6 = false;
243         if ((!*this->host) || strchr(this->host, ':'))
244                 v6 = true;
245
246         if (v6)
247         {
248                 this->fd = socket(AF_INET6, SOCK_STREAM, 0);
249                 if ((this->fd > -1) && ((strstr(this->IP,"::ffff:") != (char*)&this->IP) && (strstr(this->IP,"::FFFF:") != (char*)&this->IP)))
250                 {
251                         if (!this->BindAddr(this->cbindip))
252                         {
253                                 delete[] addr;
254                                 return false;
255                         }
256                 }
257         }
258         else
259 #endif
260         {
261                 this->fd = socket(AF_INET, SOCK_STREAM, 0);
262                 if (this->fd > -1)
263                 {
264                         if (!this->BindAddr(this->cbindip))
265                         {
266                                 delete[] addr;
267                                 return false;
268                         }
269                 }
270         }
271
272         if (this->fd == -1)
273         {
274                 this->state = I_ERROR;
275                 this->OnError(I_ERR_SOCKET);
276                 delete[] addr;
277                 return false;
278         }
279
280 #ifdef IPV6
281         if (v6)
282         {
283                 in6_addr addy;
284                 if (inet_pton(AF_INET6, this->host, &addy) > 0)
285                 {
286                         ((sockaddr_in6*)addr)->sin6_family = AF_INET6;
287                         memcpy(&((sockaddr_in6*)addr)->sin6_addr, &addy, sizeof(addy));
288                         ((sockaddr_in6*)addr)->sin6_port = htons(this->port);
289                         size = sizeof(sockaddr_in6);
290                 }
291         }
292         else
293 #endif
294         {
295                 in_addr addy;
296                 if (inet_aton(this->host, &addy) > 0)
297                 {
298                         ((sockaddr_in*)addr)->sin_family = AF_INET;
299                         ((sockaddr_in*)addr)->sin_addr = addy;
300                         ((sockaddr_in*)addr)->sin_port = htons(this->port);
301                 }
302         }
303 #ifndef WIN32
304         int flags = fcntl(this->fd, F_GETFL, 0);
305         fcntl(this->fd, F_SETFL, flags | O_NONBLOCK);
306 #else
307         unsigned long flags = 0;
308         ioctlsocket(this->fd, FIONBIO, &flags);
309 #endif
310         if (connect(this->fd, (sockaddr*)addr, size) == -1)
311         {
312                 if (errno != EINPROGRESS)
313                 {
314                         this->OnError(I_ERR_CONNECT);
315                         this->Close();
316                         this->state = I_ERROR;
317                         return false;
318                 }
319
320                 this->Timeout = new SocketTimeout(this->GetFd(), this->Instance, this, timeout_val, this->Instance->Time());
321                 this->Instance->Timers->AddTimer(this->Timeout);
322         }
323         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                 shutdown(this->fd,2);
360                 if (close(this->fd) != -1)
361                         this->OnClose();
362
363                 if (Instance->SocketCull.find(this) == Instance->SocketCull.end())
364                         Instance->SocketCull[this] = this;
365         }
366         errno = save;
367 }
368
369 std::string InspSocket::GetIP()
370 {
371         return this->IP;
372 }
373
374 char* InspSocket::Read()
375 {
376 #ifdef WINDOWS
377         if ((fd < 0) || (m_internalFd > MAX_DESCRIPTORS))
378 #else
379         if ((fd < 0) || (fd > MAX_DESCRIPTORS))
380 #endif
381                 return NULL;
382
383         int n = 0;
384
385         if (this->IsIOHooked)
386         {
387                 int result2 = 0;
388                 int MOD_RESULT = 0;
389                 try
390                 {
391                         MOD_RESULT = Instance->Config->GetIOHook(this)->OnRawSocketRead(this->fd,this->ibuf,sizeof(this->ibuf),result2);
392                 }
393                 catch (CoreException& modexcept)
394                 {
395                         Instance->Log(DEFAULT,"%s threw an exception: %s", modexcept.GetSource(), modexcept.GetReason());
396                 }
397                 if (MOD_RESULT < 0)
398                 {
399                         n = -1;
400                         errno = EAGAIN;
401                 }
402                 else
403                 {
404                         n = result2;
405                 }
406         }
407         else
408         {
409                 n = recv(this->fd,this->ibuf,sizeof(this->ibuf),0);
410         }
411
412         if ((n > 0) && (n <= (int)sizeof(this->ibuf)))
413         {
414                 ibuf[n] = 0;
415                 return ibuf;
416         }
417         else
418         {
419                 int err = errno;
420                 if (err == EAGAIN)
421                         return "";
422                 else
423                         return NULL;
424         }
425 }
426
427 void InspSocket::MarkAsClosed()
428 {
429 }
430
431 // There are two possible outcomes to this function.
432 // It will either write all of the data, or an undefined amount.
433 // If an undefined amount is written the connection has failed
434 // and should be aborted.
435 int InspSocket::Write(const std::string &data)
436 {
437         /* Try and append the data to the back of the queue, and send it on its way
438          */
439         outbuffer.push_back(data);
440         this->Instance->SE->WantWrite(this);
441         return (!this->FlushWriteBuffer());
442 }
443
444 bool InspSocket::FlushWriteBuffer()
445 {
446         errno = 0;
447         if ((this->fd > -1) && (this->state == I_CONNECTED))
448         {
449                 if (this->IsIOHooked)
450                 {
451                         while (outbuffer.size() && (errno != EAGAIN))
452                         {
453                                 try
454                                 {
455                                         /* XXX: The lack of buffering here is NOT a bug, modules implementing this interface have to
456                                          * implement their own buffering mechanisms
457                                          */
458                                         Instance->Config->GetIOHook(this)->OnRawSocketWrite(this->fd, outbuffer[0].c_str(), outbuffer[0].length());
459                                         outbuffer.pop_front();
460                                 }
461                                 catch (CoreException& modexcept)
462                                 {
463                                         Instance->Log(DEBUG,"%s threw an exception: %s", modexcept.GetSource(), modexcept.GetReason());
464                                         return true;
465                                 }
466                         }
467                 }
468                 else
469                 {
470                         /* If we have multiple lines, try to send them all,
471                          * not just the first one -- Brain
472                          */
473                         while (outbuffer.size() && (errno != EAGAIN))
474                         {
475                                 /* Send a line */
476 #ifndef WIN32
477                                 int result = write(this->fd,outbuffer[0].c_str(),outbuffer[0].length());
478 #else
479                                 int result = send(this->fd,outbuffer[0].c_str(),outbuffer[0].length(), 0);
480 #endif
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 #ifdef WINDOWS
555         if(Instance->SE->GetRef(this->fd) != this)
556                 return false;
557         int incoming = -1;
558 #else
559         if (this->Instance->SE->GetRef(this->fd) != this)
560                 return false;
561
562         int incoming = -1;
563
564         if ((fd < 0) || (fd > MAX_DESCRIPTORS))
565                 return false;
566 #endif
567         switch (this->state)
568         {
569                 case I_CONNECTING:
570                         /* Our socket was in write-state, so delete it and re-add it
571                          * in read-state.
572                          */
573 #ifndef WINDOWS
574                         if (this->fd > -1)
575                         {
576                                 this->Instance->SE->DelFd(this);
577                                 this->SetState(I_CONNECTED);
578                                 if (!this->Instance->SE->AddFd(this))
579                                         return false;
580                         }
581 #else
582                         this->SetState(I_CONNECTED);
583 #endif
584                         Instance->Log(DEBUG,"Inspsocket I_CONNECTING state");
585                         if (Instance->Config->GetIOHook(this))
586                         {
587                                 Instance->Log(DEBUG,"Hook for raw connect");
588                                 try
589                                 {
590                                         Instance->Config->GetIOHook(this)->OnRawSocketConnect(this->fd);
591                                 }
592                                 catch (CoreException& modexcept)
593                                 {
594                                         Instance->Log(DEBUG,"%s threw an exception: %s", modexcept.GetSource(), modexcept.GetReason());
595                                 }
596                         }
597                         return this->OnConnected();
598                 break;
599                 case I_LISTENING:
600                 {
601                         sockaddr* client = new sockaddr[2];
602                         length = sizeof (sockaddr_in);
603                         std::string recvip;
604 #ifdef IPV6
605                         if ((!*this->host) || strchr(this->host, ':'))
606                                 length = sizeof(sockaddr_in6);
607 #endif
608                         incoming = _accept (this->fd, client, &length);
609 #ifdef IPV6
610                         if ((!*this->host) || strchr(this->host, ':'))
611                         {
612                                 char buf[1024];
613                                 recvip = inet_ntop(AF_INET6, &((sockaddr_in6*)client)->sin6_addr, buf, sizeof(buf));
614                         }
615                         else
616 #endif
617                         recvip = inet_ntoa(((sockaddr_in*)client)->sin_addr);
618                         this->OnIncomingConnection(incoming, (char*)recvip.c_str());
619
620                         if (this->IsIOHooked)
621                         {
622                                 try
623                                 {
624                                         Instance->Config->GetIOHook(this)->OnRawSocketAccept(incoming, recvip.c_str(), this->port);
625                                 }
626                                 catch (CoreException& modexcept)
627                                 {
628                                         Instance->Log(DEBUG,"%s threw an exception: %s", modexcept.GetSource(), modexcept.GetReason());
629                                 }
630                         }
631
632                         this->SetQueues(incoming);
633
634                         delete[] client;
635                         return true;
636                 }
637                 break;
638                 case I_CONNECTED:
639                         /* Process the read event */
640                         return this->OnDataReady();
641                 break;
642                 default:
643                 break;
644         }
645         return true;
646 }
647
648 void InspSocket::SetState(InspSocketState s)
649 {
650         this->state = s;
651 }
652
653 InspSocketState InspSocket::GetState()
654 {
655         return this->state;
656 }
657
658 int InspSocket::GetFd()
659 {
660         return this->fd;
661 }
662
663 bool InspSocket::OnConnected() { return true; }
664 void InspSocket::OnError(InspSocketError e) { return; }
665 int InspSocket::OnDisconnect() { return 0; }
666 int InspSocket::OnIncomingConnection(int newfd, char* ip) { return 0; }
667 bool InspSocket::OnDataReady() { return true; }
668 bool InspSocket::OnWriteReady() { return true; }
669 void InspSocket::OnTimeout() { return; }
670 void InspSocket::OnClose() { return; }
671
672 InspSocket::~InspSocket()
673 {
674         this->Close();
675         if (Timeout)
676         {
677                 Instance->Timers->DelTimer(Timeout);
678                 Timeout = NULL;
679         }
680 }
681
682 void InspSocket::HandleEvent(EventType et, int errornum)
683 {
684         switch (et)
685         {
686                 case EVENT_ERROR:
687                         switch (errornum)
688                         {
689                                 case ETIMEDOUT:
690                                         this->OnError(I_ERR_TIMEOUT);
691                                 break;
692                                 case ECONNREFUSED:
693                                 case 0:
694                                         this->OnError(this->state == I_CONNECTING ? I_ERR_CONNECT : I_ERR_WRITE);
695                                 break;
696                                 case EADDRINUSE:
697                                         this->OnError(I_ERR_BIND);
698                                 break;
699                                 case EPIPE:
700                                 case EIO:
701                                         this->OnError(I_ERR_WRITE);
702                                 break;
703                         }
704                         if (this->Instance->SocketCull.find(this) == this->Instance->SocketCull.end())
705                                 this->Instance->SocketCull[this] = this;
706                         return;
707                 break;
708                 case EVENT_READ:
709                         if (!this->Poll())
710                         {
711                                 if (this->Instance->SocketCull.find(this) == this->Instance->SocketCull.end())
712                                         this->Instance->SocketCull[this] = this;
713                                 return;
714                         }
715                 break;
716                 case EVENT_WRITE:
717                         if (this->WaitingForWriteEvent)
718                         {
719                                 this->WaitingForWriteEvent = false;
720                                 if (!this->OnWriteReady())
721                                 {
722                                         if (this->Instance->SocketCull.find(this) == this->Instance->SocketCull.end())
723                                                 this->Instance->SocketCull[this] = this;
724                                         return;
725                                 }
726                         }
727                         if (this->state == I_CONNECTING)
728                         {
729                                 /* This might look wrong as if we should be actually calling
730                                  * with EVENT_WRITE, but trust me it is correct. There are some
731                                  * writeability-state things in the read code, because of how
732                                  * InspSocket used to work regarding write buffering in previous
733                                  * versions of InspIRCd. - Brain
734                                  */
735                                 this->HandleEvent(EVENT_READ);
736                                 return;
737                         }
738                         else
739                         {
740                                 if (this->FlushWriteBuffer())
741                                 {
742                                         if (this->Instance->SocketCull.find(this) == this->Instance->SocketCull.end())
743                                                 this->Instance->SocketCull[this] = this;
744                                         return;
745                                 }
746                         }
747                 break;
748         }
749 }
750