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