]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/inspsocket.cpp
Untested! New m_watch that should be hundreds of times faster (im not joking either)
[user/henk/code/inspircd.git] / src / inspsocket.cpp
1 /*       +------------------------------------+
2  *       | Inspire Internet Relay Chat Daemon |
3  *       +------------------------------------+
4  *
5  *  InspIRCd is copyright (C) 2002-2006 ChatSpike-Dev.
6  *                       E-mail:
7  *                <brain@chatspike.net>
8  *                <Craig@chatspike.net>
9  *     
10  * Written by Craig Edwards, Craig McLure, and others.
11  * This program is free but copyrighted software; see
12  *            the file COPYING for details.
13  *
14  * ---------------------------------------------------
15  */
16
17 #include "socket.h"
18 #include "configreader.h"
19 #include "inspstring.h"
20 #include "socketengine.h"
21 #include "inspircd.h"
22
23 using irc::sockets::OpenTCPSocket;
24 using irc::sockets::insp_inaddr;
25 using irc::sockets::insp_sockaddr;
26
27 bool InspSocket::Readable()
28 {
29         return ((this->state != I_CONNECTING) && (this->WaitingForWriteEvent == false));
30 }
31
32 InspSocket::InspSocket(InspIRCd* SI)
33 {
34         this->state = I_DISCONNECTED;
35         this->fd = -1;
36         this->WaitingForWriteEvent = false;
37         this->Instance = SI;
38         this->IsIOHooked = false;
39 }
40
41 InspSocket::InspSocket(InspIRCd* SI, int newfd, const char* ip)
42 {
43         this->fd = newfd;
44         this->state = I_CONNECTED;
45         strlcpy(this->IP,ip,MAXBUF);
46         this->WaitingForWriteEvent = false;
47         this->Instance = SI;
48         this->IsIOHooked = false;
49         if (this->fd > -1)
50                 this->Instance->SE->AddFd(this);
51 }
52
53 InspSocket::InspSocket(InspIRCd* SI, const std::string &ipaddr, int aport, bool listening, unsigned long maxtime)
54 {
55         this->fd = -1;
56         this->Instance = SI;
57         strlcpy(host,ipaddr.c_str(),MAXBUF);
58         this->WaitingForWriteEvent = false;
59         this->IsIOHooked = false;
60         if (listening)
61         {
62                 if ((this->fd = OpenTCPSocket()) == ERROR)
63                 {
64                         this->fd = -1;
65                         this->state = I_ERROR;
66                         this->OnError(I_ERR_SOCKET);
67                         this->Instance->Log(DEBUG,"OpenTCPSocket() error");
68                         return;
69                 }
70                 else
71                 {
72                         if (!SI->BindSocket(this->fd,this->client,this->server,aport,(char*)ipaddr.c_str()))
73                         {
74                                 this->Instance->Log(DEBUG,"BindSocket() error %s",strerror(errno));
75                                 this->Close();
76                                 this->fd = -1;
77                                 this->state = I_ERROR;
78                                 this->OnError(I_ERR_BIND);
79                                 this->ClosePending = true;
80                                 return;
81                         }
82                         else
83                         {
84                                 this->state = I_LISTENING;
85                                 if (this->fd > -1)
86                                 {
87                                         if (!this->Instance->SE->AddFd(this))
88                                         {
89                                                 this->Close();
90                                                 this->state = I_ERROR;
91                                                 this->OnError(I_ERR_NOMOREFDS);
92                                         }
93                                 }
94                                 this->Instance->Log(DEBUG,"New socket now in I_LISTENING state");
95                                 return;
96                         }
97                 }                       
98         }
99         else
100         {
101                 strlcpy(this->host,ipaddr.c_str(),MAXBUF);
102                 this->port = aport;
103
104                 if (insp_aton(host,&addy) < 1)
105                 {
106                         this->Instance->Log(DEBUG,"You cannot pass hostnames to InspSocket, resolve them first with Resolver!");
107                         this->Close();
108                         this->fd = -1;
109                         this->state = I_ERROR;
110                         this->OnError(I_ERR_RESOLVE);
111                         return;
112                 }
113                 else
114                 {
115                         this->Instance->Log(DEBUG,"No need to resolve %s",this->host);
116                         strlcpy(this->IP,host,MAXBUF);
117                         timeout_val = maxtime;
118                         this->DoConnect();
119                 }
120         }
121 }
122
123 void InspSocket::WantWrite()
124 {
125         this->Instance->SE->WantWrite(this);
126         this->WaitingForWriteEvent = true;
127 }
128
129 void InspSocket::SetQueues(int nfd)
130 {
131         // attempt to increase socket sendq and recvq as high as its possible
132         int sendbuf = 32768;
133         int recvbuf = 32768;
134         setsockopt(nfd,SOL_SOCKET,SO_SNDBUF,(const void *)&sendbuf,sizeof(sendbuf));
135         setsockopt(nfd,SOL_SOCKET,SO_RCVBUF,(const void *)&recvbuf,sizeof(sendbuf));
136 }
137
138 /* Most irc servers require you to specify the ip you want to bind to.
139  * If you dont specify an IP, they rather dumbly bind to the first IP
140  * of the box (e.g. INADDR_ANY). In InspIRCd, we scan thought the IP
141  * addresses we've bound server ports to, and we try and bind our outbound
142  * connections to the first usable non-loopback and non-any IP we find.
143  * This is easier to configure when you have a lot of links and a lot
144  * of servers to configure.
145  */
146 bool InspSocket::BindAddr()
147 {
148         insp_inaddr n;
149         ConfigReader Conf(this->Instance);
150
151         this->Instance->Log(DEBUG,"In InspSocket::BindAddr()");
152         for (int j =0; j < Conf.Enumerate("bind"); j++)
153         {
154                 std::string Type = Conf.ReadValue("bind","type",j);
155                 std::string IP = Conf.ReadValue("bind","address",j);
156                 if (Type == "servers")
157                 {
158                         if ((IP != "*") && (IP != "127.0.0.1") && (IP != ""))
159                         {
160                                 insp_sockaddr s;
161
162                                 if (insp_aton(IP.c_str(),&n) > 0)
163                                 {
164                                         this->Instance->Log(DEBUG,"Found an IP to bind to: %s",IP.c_str());
165 #ifdef IPV6
166                                         s.sin6_addr = n;
167                                         s.sin6_family = AF_FAMILY;
168 #else
169                                         s.sin_addr = n;
170                                         s.sin_family = AF_FAMILY;
171 #endif
172                                         if (bind(this->fd,(struct sockaddr*)&s,sizeof(s)) < 0)
173                                         {
174                                                 this->Instance->Log(DEBUG,"Cant bind()");
175                                                 this->state = I_ERROR;
176                                                 this->OnError(I_ERR_BIND);
177                                                 this->fd = -1;
178                                                 return false;
179                                         }
180                                         this->Instance->Log(DEBUG,"bind() reports outbound fd bound to ip %s",IP.c_str());
181                                         return true;
182                                 }
183                                 else
184                                 {
185                                         this->Instance->Log(DEBUG,"Address '%s' was not an IP address",IP.c_str());
186                                 }
187                         }
188                 }
189         }
190         this->Instance->Log(DEBUG,"Found no suitable IPs to bind, binding INADDR_ANY");
191         return true;
192 }
193
194 bool InspSocket::DoConnect()
195 {
196         this->Instance->Log(DEBUG,"In DoConnect()");
197         if ((this->fd = socket(AF_FAMILY, SOCK_STREAM, 0)) == -1)
198         {
199                 this->Instance->Log(DEBUG,"Cant socket()");
200                 this->state = I_ERROR;
201                 this->OnError(I_ERR_SOCKET);
202                 return false;
203         }
204
205         if ((strstr(this->IP,"::ffff:") != (char*)&this->IP) && (strstr(this->IP,"::FFFF:") != (char*)&this->IP))
206         {
207                 if (!this->BindAddr())
208                         return false;
209         }
210
211         this->Instance->Log(DEBUG,"Part 2 DoConnect() %s",this->IP);
212         insp_aton(this->IP,&addy);
213 #ifdef IPV6
214         addr.sin6_family = AF_FAMILY;
215         memcpy(&addr.sin6_addr, &addy, sizeof(insp_inaddr));
216         addr.sin6_port = htons(this->port);
217 #else
218         addr.sin_family = AF_FAMILY;
219         addr.sin_addr = addy;
220         addr.sin_port = htons(this->port);
221 #endif
222
223         int flags;
224         flags = fcntl(this->fd, F_GETFL, 0);
225         fcntl(this->fd, F_SETFL, flags | O_NONBLOCK);
226
227         if (connect(this->fd, (sockaddr*)&this->addr,sizeof(this->addr)) == -1)
228         {
229                 if (errno != EINPROGRESS)
230                 {
231                         this->Instance->Log(DEBUG,"Error connect() %d: %s",this->fd,strerror(errno));
232                         this->OnError(I_ERR_CONNECT);
233                         this->Close();
234                         this->state = I_ERROR;
235                         return false;
236                 }
237
238                 this->Timeout = new SocketTimeout(this->GetFd(), this->Instance, this, timeout_val, this->Instance->Time());
239                 this->Instance->Timers->AddTimer(this->Timeout);
240         }
241         this->state = I_CONNECTING;
242         if (this->fd > -1)
243         {
244                 if (!this->Instance->SE->AddFd(this))
245                 {
246                         this->OnError(I_ERR_NOMOREFDS);
247                         this->Close();
248                         this->state = I_ERROR;
249                         return false;
250                 }
251                 this->SetQueues(this->fd);
252         }
253         this->Instance->Log(DEBUG,"Returning true from InspSocket::DoConnect");
254         return true;
255 }
256
257
258 void InspSocket::Close()
259 {
260         if (this->fd > -1)
261         {
262                 if (this->IsIOHooked && Instance->Config->GetIOHook(this))
263                 {
264                         try
265                         {
266                                 Instance->Config->GetIOHook(this)->OnRawSocketClose(this->fd);
267                         }
268                         catch (ModuleException& modexcept)
269                         {
270                                 Instance->Log(DEBUG,"Module exception cought: %s",modexcept.GetReason());
271                         }
272                 }
273                 this->OnClose();
274                 shutdown(this->fd,2);
275                 close(this->fd);
276         }
277 }
278
279 std::string InspSocket::GetIP()
280 {
281         return this->IP;
282 }
283
284 char* InspSocket::Read()
285 {
286         if ((fd < 0) || (fd > MAX_DESCRIPTORS))
287                 return NULL;
288
289         int n = 0;
290
291         if (this->IsIOHooked)
292         {
293                 int result2 = 0;
294                 int MOD_RESULT = 0;
295                 try
296                 {
297                         MOD_RESULT = Instance->Config->GetIOHook(this)->OnRawSocketRead(this->fd,this->ibuf,sizeof(this->ibuf),result2);
298                 }
299                 catch (ModuleException& modexcept)
300                 {
301                         Instance->Log(DEBUG,"Module exception caught: %s",modexcept.GetReason());
302                 }
303                 if (MOD_RESULT < 0)
304                 {
305                         n = -1;
306                         errno = EAGAIN;
307                 }
308                 else
309                 {
310                         n = result2;
311                 }
312         }
313         else
314         {
315                 n = recv(this->fd,this->ibuf,sizeof(this->ibuf),0);
316         }
317
318         if ((n > 0) && (n <= (int)sizeof(this->ibuf)))
319         {
320                 ibuf[n] = 0;
321                 return ibuf;
322         }
323         else
324         {
325                 int err = errno;
326                 if (err == EAGAIN)
327                 {
328                         return "";
329                 }
330                 else
331                 {
332                         if (!n)
333                                 this->Instance->Log(DEBUG,"EOF or error on socket: EOF");
334                         else
335                                 this->Instance->Log(DEBUG,"EOF or error on socket: %s",strerror(err));
336                         return NULL;
337                 }
338         }
339 }
340
341 void InspSocket::MarkAsClosed()
342 {
343         this->Instance->Log(DEBUG,"Marked as closed");
344 }
345
346 // There are two possible outcomes to this function.
347 // It will either write all of the data, or an undefined amount.
348 // If an undefined amount is written the connection has failed
349 // and should be aborted.
350 int InspSocket::Write(const std::string &data)
351 {
352         /* Try and append the data to the back of the queue, and send it on its way
353          */
354         outbuffer.push_back(data);
355         this->Instance->SE->WantWrite(this);
356         return (!this->FlushWriteBuffer());
357 }
358
359 bool InspSocket::FlushWriteBuffer()
360 {
361         errno = 0;
362         if ((this->fd > -1) && (this->state == I_CONNECTED))
363         {
364                 if (this->IsIOHooked)
365                 {
366                         while (outbuffer.size() && (errno != EAGAIN))
367                         {
368                                 try
369                                 {
370                                         int result = Instance->Config->GetIOHook(this)->OnRawSocketWrite(this->fd, outbuffer[0].c_str(), outbuffer[0].length());
371                                         if (result > 0)
372                                         {
373                                                 if ((unsigned int)result == outbuffer[0].length())
374                                                 {
375                                                         outbuffer.pop_front();
376                                                 }
377                                                 else
378                                                 {
379                                                         std::string temp = outbuffer[0].substr(result);
380                                                         outbuffer[0] = temp;
381                                                         errno = EAGAIN;
382                                                 }
383                                         }
384                                         else if ((result == -1) && (errno != EAGAIN))
385                                         {
386                                                 this->Instance->Log(DEBUG,"Write error on socket: %s",strerror(errno));
387                                                 this->OnError(I_ERR_WRITE);
388                                                 this->state = I_ERROR;
389                                                 this->Instance->SE->DelFd(this);
390                                                 this->Close();
391                                                 return true;
392                                         }
393                                         else if (result == 0)
394                                         {
395                                                 this->Instance->Log(DEBUG,"Write error on socket: EOF");
396                                                 this->OnError(I_ERR_WRITE);
397                                                 this->state = I_ERROR;
398                                                 this->Instance->SE->DelFd(this);
399                                                 this->Close();
400                                                 return true;
401                                         }
402                                 }
403                                 catch (ModuleException& modexcept)
404                                 {
405                                         Instance->Log(DEBUG,"Module exception caught: %s",modexcept.GetReason());
406                                         return true;
407                                 }
408                         }
409                 }
410                 else
411                 {
412                         /* If we have multiple lines, try to send them all,
413                          * not just the first one -- Brain
414                          */
415                         while (outbuffer.size() && (errno != EAGAIN))
416                         {
417                                 /* Send a line */
418                                 int result = write(this->fd,outbuffer[0].c_str(),outbuffer[0].length());
419                                 if (result > 0)
420                                 {
421                                         if ((unsigned int)result == outbuffer[0].length())
422                                         {
423                                                 /* The whole block was written (usually a line)
424                                                  * Pop the block off the front of the queue,
425                                                  * dont set errno, because we are clear of errors
426                                                  * and want to try and write the next block too.
427                                                  */
428                                                 outbuffer.pop_front();
429                                         }
430                                         else
431                                         {
432                                                 std::string temp = outbuffer[0].substr(result);
433                                                 outbuffer[0] = temp;
434                                                 /* We didnt get the whole line out. arses.
435                                                  * Try again next time, i guess. Set errno,
436                                                  * because we shouldnt be writing any more now,
437                                                  * until the socketengine says its safe to do so.
438                                                  */
439                                                 errno = EAGAIN;
440                                         }
441                                 }
442                                 else if ((result == -1) && (errno != EAGAIN))
443                                 {
444                                         this->Instance->Log(DEBUG,"Write error on socket: %s",strerror(errno));
445                                         this->OnError(I_ERR_WRITE);
446                                         this->state = I_ERROR;
447                                         this->Instance->SE->DelFd(this);
448                                         this->Close();
449                                         return true;
450                                 }
451                         }
452                 }
453         }
454
455         if ((errno == EAGAIN) && (fd > -1))
456         {
457                 this->Instance->SE->WantWrite(this);
458         }
459
460         return (fd < 0);
461 }
462
463 void SocketTimeout::Tick(time_t now)
464 {
465         if (ServerInstance->SE->GetRef(this->sfd) != this->sock)
466         {
467                 ServerInstance->Log(DEBUG,"Our socket has been deleted before the timeout was reached.");
468                 return;
469         }
470
471         if (this->sock->state == I_CONNECTING)
472         {
473                 ServerInstance->Log(DEBUG,"Timed out, current=%lu",now);
474                 // for non-listening sockets, the timeout can occur
475                 // which causes termination of the connection after
476                 // the given number of seconds without a successful
477                 // connection.
478                 this->sock->OnTimeout();
479                 this->sock->OnError(I_ERR_TIMEOUT);
480                 this->sock->timeout = true;
481                 ServerInstance->SE->DelFd(this->sock);
482                 /* NOTE: We must set this AFTER DelFd, as we added
483                  * this socket whilst writeable. This means that we
484                  * must DELETE the socket whilst writeable too!
485                  */
486                 this->sock->state = I_ERROR;
487                 this->sock->Close();
488                 delete this->sock;
489                 return;
490         }
491 }
492
493 bool InspSocket::Poll()
494 {
495         if (this->Instance->SE->GetRef(this->fd) != this)
496                 return false;
497
498         int incoming = -1;
499
500         if ((fd < 0) || (fd > MAX_DESCRIPTORS))
501                 return false;
502
503         switch (this->state)
504         {
505                 case I_CONNECTING:
506                         this->Instance->Log(DEBUG,"State = I_CONNECTING");
507                         /* Our socket was in write-state, so delete it and re-add it
508                          * in read-state.
509                          */
510                         if (this->fd > -1)
511                         {
512                                 this->Instance->SE->DelFd(this);
513                                 this->SetState(I_CONNECTED);
514                                 if (!this->Instance->SE->AddFd(this))
515                                         return false;
516                         }
517                         if (Instance->Config->GetIOHook(this))
518                         {
519                                 try
520                                 {
521                                         Instance->Config->GetIOHook(this)->OnRawSocketConnect(this->fd);
522                                 }
523                                 catch (ModuleException& modexcept)
524                                 {
525                                         Instance->Log(DEBUG,"Module exception cought: %s",modexcept.GetReason());
526                                 }
527                         }
528                         return this->OnConnected();
529                 break;
530                 case I_LISTENING:
531                         length = sizeof (client);
532                         incoming = accept (this->fd, (sockaddr*)&client,&length);
533
534 #ifdef IPV6
535                         this->OnIncomingConnection(incoming, (char*)insp_ntoa(client.sin6_addr));
536 #else
537                         this->OnIncomingConnection(incoming, (char*)insp_ntoa(client.sin_addr));
538 #endif
539
540                         if (this->IsIOHooked)
541                         {
542                                 try
543                                 {
544 #ifdef IPV6
545                                         Instance->Config->GetIOHook(this)->OnRawSocketAccept(incoming, insp_ntoa(client.sin6_addr), this->port);
546 #else
547                                         Instance->Config->GetIOHook(this)->OnRawSocketAccept(incoming, insp_ntoa(client.sin_addr), this->port);
548 #endif
549                                 }
550                                 catch (ModuleException& modexcept)
551                                 {
552                                         Instance->Log(DEBUG,"Module exception cought: %s",modexcept.GetReason());
553                                 }
554                         }
555
556                         this->SetQueues(incoming);
557                         return true;
558                 break;
559                 case I_CONNECTED:
560                         /* Process the read event */
561                         return this->OnDataReady();
562                 break;
563                 default:
564                 break;
565         }
566         return true;
567 }
568
569 void InspSocket::SetState(InspSocketState s)
570 {
571         this->Instance->Log(DEBUG,"Socket state change");
572         this->state = s;
573 }
574
575 InspSocketState InspSocket::GetState()
576 {
577         return this->state;
578 }
579
580 int InspSocket::GetFd()
581 {
582         return this->fd;
583 }
584
585 bool InspSocket::OnConnected() { return true; }
586 void InspSocket::OnError(InspSocketError e) { return; }
587 int InspSocket::OnDisconnect() { return 0; }
588 int InspSocket::OnIncomingConnection(int newfd, char* ip) { return 0; }
589 bool InspSocket::OnDataReady() { return true; }
590 bool InspSocket::OnWriteReady() { return true; }
591 void InspSocket::OnTimeout() { return; }
592 void InspSocket::OnClose() { return; }
593
594 InspSocket::~InspSocket()
595 {
596         this->Close();
597 }
598
599 void InspSocket::HandleEvent(EventType et, int errornum)
600 {
601         switch (et)
602         {
603                 case EVENT_ERROR:
604                         this->Instance->SE->DelFd(this);
605                         this->Close();
606                         delete this;
607                         return;
608                 break;
609                 case EVENT_READ:
610                         if (!this->Poll())
611                         {
612                                 this->Instance->SE->DelFd(this);
613                                 this->Close();
614                                 delete this;
615                                 return;
616                         }
617                 break;
618                 case EVENT_WRITE:
619                         if (this->WaitingForWriteEvent)
620                         {
621                                 this->WaitingForWriteEvent = false;
622                                 if (!this->OnWriteReady())
623                                 {
624                                         this->Instance->SE->DelFd(this);
625                                         this->Close();
626                                         delete this;
627                                         return;
628                                 }
629                         }
630                         if (this->state == I_CONNECTING)
631                         {
632                                 /* This might look wrong as if we should be actually calling
633                                  * with EVENT_WRITE, but trust me it is correct. There are some
634                                  * writeability-state things in the read code, because of how
635                                  * InspSocket used to work regarding write buffering in previous
636                                  * versions of InspIRCd. - Brain
637                                  */
638                                 this->HandleEvent(EVENT_READ);
639                                 return;
640                         }
641                         else
642                         {
643                                 Instance->Log(DEBUG,"State=%d CONNECTED=%d", this->state, I_CONNECTED);
644                                 if (this->FlushWriteBuffer())
645                                 {
646                                         this->Instance->SE->DelFd(this);
647                                         this->Close();
648                                         delete this;
649                                         return;
650                                 }
651                         }
652                 break;
653         }
654 }
655