]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/inspsocket.cpp
678583ed0c3b6025c8d7bc67afabc4df79d1461d
[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                                         s.sin6_addr = 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(insp_inaddr));
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;
204         flags = fcntl(this->fd, F_GETFL, 0);
205         fcntl(this->fd, F_SETFL, flags | O_NONBLOCK);
206
207         if (connect(this->fd, (sockaddr*)&this->addr,sizeof(this->addr)) == -1)
208         {
209                 if (errno != EINPROGRESS)
210                 {
211                         this->OnError(I_ERR_CONNECT);
212                         this->Close();
213                         this->state = I_ERROR;
214                         return false;
215                 }
216
217                 this->Timeout = new SocketTimeout(this->GetFd(), this->Instance, this, timeout_val, this->Instance->Time());
218                 this->Instance->Timers->AddTimer(this->Timeout);
219         }
220         this->state = I_CONNECTING;
221         if (this->fd > -1)
222         {
223                 if (!this->Instance->SE->AddFd(this))
224                 {
225                         this->OnError(I_ERR_NOMOREFDS);
226                         this->Close();
227                         this->state = I_ERROR;
228                         return false;
229                 }
230                 this->SetQueues(this->fd);
231         }
232         return true;
233 }
234
235
236 void InspSocket::Close()
237 {
238         /* Save this, so we dont lose it,
239          * otherise on failure, error messages
240          * might be inaccurate.
241          */
242         int save = errno;
243         if (this->fd > -1)
244         {
245                 if (this->IsIOHooked && Instance->Config->GetIOHook(this))
246                 {
247                         try
248                         {
249                                 Instance->Config->GetIOHook(this)->OnRawSocketClose(this->fd);
250                         }
251                         catch (CoreException& modexcept)
252                         {
253                                 Instance->Log(DEFAULT,"%s threw an exception: %s", modexcept.GetSource(), modexcept.GetReason());
254                         }
255                 }
256                 this->OnClose();
257                 shutdown(this->fd,2);
258                 close(this->fd);
259         }
260         errno = save;
261 }
262
263 std::string InspSocket::GetIP()
264 {
265         return this->IP;
266 }
267
268 char* InspSocket::Read()
269 {
270         if ((fd < 0) || (fd > MAX_DESCRIPTORS))
271                 return NULL;
272
273         int n = 0;
274
275         if (this->IsIOHooked)
276         {
277                 int result2 = 0;
278                 int MOD_RESULT = 0;
279                 try
280                 {
281                         MOD_RESULT = Instance->Config->GetIOHook(this)->OnRawSocketRead(this->fd,this->ibuf,sizeof(this->ibuf),result2);
282                 }
283                 catch (CoreException& modexcept)
284                 {
285                         Instance->Log(DEFAULT,"%s threw an exception: %s", modexcept.GetSource(), modexcept.GetReason());
286                 }
287                 if (MOD_RESULT < 0)
288                 {
289                         n = -1;
290                         errno = EAGAIN;
291                 }
292                 else
293                 {
294                         n = result2;
295                 }
296         }
297         else
298         {
299                 n = recv(this->fd,this->ibuf,sizeof(this->ibuf),0);
300         }
301
302         if ((n > 0) && (n <= (int)sizeof(this->ibuf)))
303         {
304                 ibuf[n] = 0;
305                 return ibuf;
306         }
307         else
308         {
309                 int err = errno;
310                 if (err == EAGAIN)
311                         return "";
312                 else
313                         return NULL;
314         }
315 }
316
317 void InspSocket::MarkAsClosed()
318 {
319 }
320
321 // There are two possible outcomes to this function.
322 // It will either write all of the data, or an undefined amount.
323 // If an undefined amount is written the connection has failed
324 // and should be aborted.
325 int InspSocket::Write(const std::string &data)
326 {
327         /* Try and append the data to the back of the queue, and send it on its way
328          */
329         outbuffer.push_back(data);
330         this->Instance->SE->WantWrite(this);
331         return (!this->FlushWriteBuffer());
332 }
333
334 bool InspSocket::FlushWriteBuffer()
335 {
336         errno = 0;
337         if ((this->fd > -1) && (this->state == I_CONNECTED))
338         {
339                 if (this->IsIOHooked)
340                 {
341                         while (outbuffer.size() && (errno != EAGAIN))
342                         {
343                                 try
344                                 {
345                                         int result = Instance->Config->GetIOHook(this)->OnRawSocketWrite(this->fd, outbuffer[0].c_str(), outbuffer[0].length());
346                                         if (result > 0)
347                                         {
348                                                 if ((unsigned int)result == outbuffer[0].length())
349                                                 {
350                                                         outbuffer.pop_front();
351                                                 }
352                                                 else
353                                                 {
354                                                         std::string temp = outbuffer[0].substr(result);
355                                                         outbuffer[0] = temp;
356                                                         errno = EAGAIN;
357                                                 }
358                                         }
359                                         else if (((result == -1) && (errno != EAGAIN)) || (result == 0))
360                                         {
361                                                 this->OnError(I_ERR_WRITE);
362                                                 this->state = I_ERROR;
363                                                 this->Instance->SE->DelFd(this);
364                                                 this->Close();
365                                                 return true;
366                                         }
367                                 }
368                                 catch (CoreException& modexcept)
369                                 {
370                                         Instance->Log(DEBUG,"%s threw an exception: %s", modexcept.GetSource(), modexcept.GetReason());
371                                         return true;
372                                 }
373                         }
374                 }
375                 else
376                 {
377                         /* If we have multiple lines, try to send them all,
378                          * not just the first one -- Brain
379                          */
380                         while (outbuffer.size() && (errno != EAGAIN))
381                         {
382                                 /* Send a line */
383                                 int result = write(this->fd,outbuffer[0].c_str(),outbuffer[0].length());
384                                 if (result > 0)
385                                 {
386                                         if ((unsigned int)result == outbuffer[0].length())
387                                         {
388                                                 /* The whole block was written (usually a line)
389                                                  * Pop the block off the front of the queue,
390                                                  * dont set errno, because we are clear of errors
391                                                  * and want to try and write the next block too.
392                                                  */
393                                                 outbuffer.pop_front();
394                                         }
395                                         else
396                                         {
397                                                 std::string temp = outbuffer[0].substr(result);
398                                                 outbuffer[0] = temp;
399                                                 /* We didnt get the whole line out. arses.
400                                                  * Try again next time, i guess. Set errno,
401                                                  * because we shouldnt be writing any more now,
402                                                  * until the socketengine says its safe to do so.
403                                                  */
404                                                 errno = EAGAIN;
405                                         }
406                                 }
407                                 else if ((result == -1) && (errno != EAGAIN))
408                                 {
409                                         this->OnError(I_ERR_WRITE);
410                                         this->state = I_ERROR;
411                                         this->Instance->SE->DelFd(this);
412                                         this->Close();
413                                         return true;
414                                 }
415                         }
416                 }
417         }
418
419         if ((errno == EAGAIN) && (fd > -1))
420         {
421                 this->Instance->SE->WantWrite(this);
422         }
423
424         return (fd < 0);
425 }
426
427 void SocketTimeout::Tick(time_t now)
428 {
429         if (ServerInstance->SE->GetRef(this->sfd) != this->sock)
430                 return;
431
432         if (this->sock->state == I_CONNECTING)
433         {
434                 // for non-listening sockets, the timeout can occur
435                 // which causes termination of the connection after
436                 // the given number of seconds without a successful
437                 // connection.
438                 this->sock->OnTimeout();
439                 this->sock->OnError(I_ERR_TIMEOUT);
440                 this->sock->timeout = true;
441                 ServerInstance->SE->DelFd(this->sock);
442                 /* NOTE: We must set this AFTER DelFd, as we added
443                  * this socket whilst writeable. This means that we
444                  * must DELETE the socket whilst writeable too!
445                  */
446                 this->sock->state = I_ERROR;
447                 this->sock->Close();
448                 delete this->sock;
449                 return;
450         }
451 }
452
453 bool InspSocket::Poll()
454 {
455         if (this->Instance->SE->GetRef(this->fd) != this)
456                 return false;
457
458         int incoming = -1;
459
460         if ((fd < 0) || (fd > MAX_DESCRIPTORS))
461                 return false;
462
463         switch (this->state)
464         {
465                 case I_CONNECTING:
466                         /* Our socket was in write-state, so delete it and re-add it
467                          * in read-state.
468                          */
469                         if (this->fd > -1)
470                         {
471                                 this->Instance->SE->DelFd(this);
472                                 this->SetState(I_CONNECTED);
473                                 if (!this->Instance->SE->AddFd(this))
474                                         return false;
475                         }
476                         if (Instance->Config->GetIOHook(this))
477                         {
478                                 try
479                                 {
480                                         Instance->Config->GetIOHook(this)->OnRawSocketConnect(this->fd);
481                                 }
482                                 catch (CoreException& modexcept)
483                                 {
484                                         Instance->Log(DEBUG,"%s threw an exception: %s", modexcept.GetSource(), modexcept.GetReason());
485                                 }
486                         }
487                         return this->OnConnected();
488                 break;
489                 case I_LISTENING:
490                         length = sizeof (client);
491                         incoming = accept (this->fd, (sockaddr*)&client,&length);
492
493 #ifdef IPV6
494                         this->OnIncomingConnection(incoming, (char*)insp_ntoa(client.sin6_addr));
495 #else
496                         this->OnIncomingConnection(incoming, (char*)insp_ntoa(client.sin_addr));
497 #endif
498
499                         if (this->IsIOHooked)
500                         {
501                                 try
502                                 {
503 #ifdef IPV6
504                                         Instance->Config->GetIOHook(this)->OnRawSocketAccept(incoming, insp_ntoa(client.sin6_addr), this->port);
505 #else
506                                         Instance->Config->GetIOHook(this)->OnRawSocketAccept(incoming, insp_ntoa(client.sin_addr), this->port);
507 #endif
508                                 }
509                                 catch (CoreException& modexcept)
510                                 {
511                                         Instance->Log(DEBUG,"%s threw an exception: %s", modexcept.GetSource(), modexcept.GetReason());
512                                 }
513                         }
514
515                         this->SetQueues(incoming);
516                         return true;
517                 break;
518                 case I_CONNECTED:
519                         /* Process the read event */
520                         return this->OnDataReady();
521                 break;
522                 default:
523                 break;
524         }
525         return true;
526 }
527
528 void InspSocket::SetState(InspSocketState s)
529 {
530         this->state = s;
531 }
532
533 InspSocketState InspSocket::GetState()
534 {
535         return this->state;
536 }
537
538 int InspSocket::GetFd()
539 {
540         return this->fd;
541 }
542
543 bool InspSocket::OnConnected() { return true; }
544 void InspSocket::OnError(InspSocketError e) { return; }
545 int InspSocket::OnDisconnect() { return 0; }
546 int InspSocket::OnIncomingConnection(int newfd, char* ip) { return 0; }
547 bool InspSocket::OnDataReady() { return true; }
548 bool InspSocket::OnWriteReady() { return true; }
549 void InspSocket::OnTimeout() { return; }
550 void InspSocket::OnClose() { return; }
551
552 InspSocket::~InspSocket()
553 {
554         this->Close();
555 }
556
557 void InspSocket::HandleEvent(EventType et, int errornum)
558 {
559         switch (et)
560         {
561                 case EVENT_ERROR:
562                         this->Instance->SE->DelFd(this);
563                         this->Close();
564                         delete this;
565                         return;
566                 break;
567                 case EVENT_READ:
568                         if (!this->Poll())
569                         {
570                                 this->Instance->SE->DelFd(this);
571                                 this->Close();
572                                 delete this;
573                                 return;
574                         }
575                 break;
576                 case EVENT_WRITE:
577                         if (this->WaitingForWriteEvent)
578                         {
579                                 this->WaitingForWriteEvent = false;
580                                 if (!this->OnWriteReady())
581                                 {
582                                         this->Instance->SE->DelFd(this);
583                                         this->Close();
584                                         delete this;
585                                         return;
586                                 }
587                         }
588                         if (this->state == I_CONNECTING)
589                         {
590                                 /* This might look wrong as if we should be actually calling
591                                  * with EVENT_WRITE, but trust me it is correct. There are some
592                                  * writeability-state things in the read code, because of how
593                                  * InspSocket used to work regarding write buffering in previous
594                                  * versions of InspIRCd. - Brain
595                                  */
596                                 this->HandleEvent(EVENT_READ);
597                                 return;
598                         }
599                         else
600                         {
601                                 if (this->FlushWriteBuffer())
602                                 {
603                                         this->Instance->SE->DelFd(this);
604                                         this->Close();
605                                         delete this;
606                                         return;
607                                 }
608                         }
609                 break;
610         }
611 }
612