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