]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/inspsocket.cpp
Update all wiki links to point to the new wiki. This was done automatically with...
[user/henk/code/inspircd.git] / src / inspsocket.cpp
1 /*       +------------------------------------+
2  *       | Inspire Internet Relay Chat Daemon |
3  *       +------------------------------------+
4  *
5  *  InspIRCd: (C) 2002-2009 InspIRCd Development Team
6  * See: http://wiki.inspircd.org/Credits
7  *
8  * This program is free but copyrighted software; see
9  *            the file COPYING for details.
10  *
11  * ---------------------------------------------------
12  */
13
14 /* $Core */
15
16 #include "socket.h"
17 #include "inspstring.h"
18 #include "socketengine.h"
19 #include "inspircd.h"
20
21 bool BufferedSocket::Readable()
22 {
23         return (this->state != I_CONNECTING);
24 }
25
26 BufferedSocket::BufferedSocket(InspIRCd* SI)
27 {
28         this->Timeout = NULL;
29         this->state = I_DISCONNECTED;
30         this->fd = -1;
31         this->ServerInstance = SI;
32 }
33
34 BufferedSocket::BufferedSocket(InspIRCd* SI, int newfd, const char* ip)
35 {
36         this->Timeout = NULL;
37         this->fd = newfd;
38         this->state = I_CONNECTED;
39         strlcpy(this->IP,ip,MAXBUF);
40         this->ServerInstance = SI;
41         if (this->fd > -1)
42                 this->ServerInstance->SE->AddFd(this);
43 }
44
45 BufferedSocket::BufferedSocket(InspIRCd* SI, const std::string &ipaddr, int aport, unsigned long maxtime, const std::string &connectbindip)
46 {
47         this->cbindip = connectbindip;
48         this->fd = -1;
49         this->ServerInstance = SI;
50         strlcpy(host,ipaddr.c_str(),MAXBUF);
51         this->Timeout = NULL;
52
53         strlcpy(this->host,ipaddr.c_str(),MAXBUF);
54         this->port = aport;
55
56         bool ipvalid = true;
57 #ifdef IPV6
58         if (strchr(host,':'))
59         {
60                 in6_addr n;
61                 if (inet_pton(AF_INET6, host, &n) < 1)
62                         ipvalid = false;
63         }
64         else
65 #endif
66         {
67                 in_addr n;
68                 if (inet_aton(host,&n) < 1)
69                         ipvalid = false;
70         }
71         if (!ipvalid)
72         {
73                 this->ServerInstance->Logs->Log("SOCKET", DEBUG,"BUG: Hostname passed to BufferedSocket, rather than an IP address!");
74                 this->OnError(I_ERR_CONNECT);
75                 this->Close();
76                 this->fd = -1;
77                 this->state = I_ERROR;
78                 return;
79         }
80         else
81         {
82                 strlcpy(this->IP,host,MAXBUF);
83                 if (!this->DoConnect(maxtime))
84                 {
85                         this->OnError(I_ERR_CONNECT);
86                         this->Close();
87                         this->fd = -1;
88                         this->state = I_ERROR;
89                         return;
90                 }
91         }
92 }
93
94 void BufferedSocket::SetQueues()
95 {
96         // attempt to increase socket sendq and recvq as high as its possible
97         int sendbuf = 32768;
98         int recvbuf = 32768;
99         if(setsockopt(this->fd,SOL_SOCKET,SO_SNDBUF,(const char *)&sendbuf,sizeof(sendbuf)) || setsockopt(this->fd,SOL_SOCKET,SO_RCVBUF,(const char *)&recvbuf,sizeof(sendbuf)))
100         {
101                 //this->ServerInstance->Log(DEFAULT, "Could not increase SO_SNDBUF/SO_RCVBUF for socket %u", GetFd());
102                 ; // do nothing. I'm a little sick of people trying to interpret this message as a result of why their incorrect setups don't work.
103         }
104 }
105
106 bool BufferedSocket::DoBindMagic(const std::string &current_ip, bool v6)
107 {
108         /* The [2] is required because we may write a sockaddr_in6 here, and sockaddr_in6 is larger than sockaddr, where sockaddr_in4 is not. */
109         socklen_t size = sizeof(sockaddr_in);
110         sockaddr* s = new sockaddr[2];
111 #ifdef IPV6
112         if (v6)
113         {
114                 in6_addr n;
115                 if (inet_pton(AF_INET6, current_ip.c_str(), &n) > 0)
116                 {
117                         memcpy(&((sockaddr_in6*)s)->sin6_addr, &n, sizeof(sockaddr_in6));
118                         ((sockaddr_in6*)s)->sin6_port = 0;
119                         ((sockaddr_in6*)s)->sin6_family = AF_INET6;
120                         size = sizeof(sockaddr_in6);
121                 }
122                 else
123                 {
124                         // Well, this is as good as it's gonna get.
125                         errno = EADDRNOTAVAIL;
126                         delete[] s;
127                         return false;
128                 }
129         }
130         else
131 #endif
132         {
133                 in_addr n;
134                 if (inet_aton(current_ip.c_str(), &n) > 0)
135                 {
136                         ((sockaddr_in*)s)->sin_addr = n;
137                         ((sockaddr_in*)s)->sin_port = 0;
138                         ((sockaddr_in*)s)->sin_family = AF_INET;
139                 }
140                 else
141                 {
142                         // Well, this is as good as it's gonna get.
143                         errno = EADDRNOTAVAIL;
144                         delete[] s;
145                         return false;
146                 }
147         }
148
149         if (ServerInstance->SE->Bind(this->fd, s, size) < 0)
150         {
151                 this->state = I_ERROR;
152                 this->OnError(I_ERR_BIND);
153                 delete[] s;
154                 return false;
155         }
156
157         delete[] s;
158         return true;
159 }
160
161 /* Most irc servers require you to specify the ip you want to bind to.
162  * If you dont specify an IP, they rather dumbly bind to the first IP
163  * of the box (e.g. INADDR_ANY). In InspIRCd, we scan thought the IP
164  * addresses we've bound server ports to, and we try and bind our outbound
165  * connections to the first usable non-loopback and non-any IP we find.
166  * This is easier to configure when you have a lot of links and a lot
167  * of servers to configure.
168  */
169 bool BufferedSocket::BindAddr(const std::string &ip_to_bind)
170 {
171         ConfigReader Conf(this->ServerInstance);
172         bool v6 = false;
173 #ifdef IPV6
174         /* Are we looking for a binding to fit an ipv6 host? */
175         if ((ip_to_bind.empty()) || (ip_to_bind.find(':') != std::string::npos))
176                 v6 = true;
177 #endif
178
179         // Case one: If they provided an IP, try bind it
180         if (!ip_to_bind.empty())
181         {
182                 // And if it fails, don't do anything.
183                 return this->DoBindMagic(ip_to_bind, v6);
184         }
185
186         for (int j = 0; j < Conf.Enumerate("bind"); j++)
187         {
188                 // We only want to try bind to a server ip.
189                 if (Conf.ReadValue("bind","type",j) != "servers")
190                         continue;
191
192                 // set current IP to the <bind> tag
193                 std::string current_ip = Conf.ReadValue("bind","address",j);
194
195                 // Make sure IP is nothing local
196                 if (current_ip == "*" || current_ip == "127.0.0.1" || current_ip.empty() || current_ip == "::1")
197                         continue;
198
199                 // Try bind, don't fail if it doesn't bind though.
200                 if (this->DoBindMagic(current_ip, v6))
201                         return true;
202         }
203
204         // NOTE: You may wonder WTF we are returning *true* here, but that is because there were no custom binds setup, and so we have nothing to do
205         // (remember, outgoing connections without binding are perfectly ok).
206         ServerInstance->Logs->Log("SOCKET", DEBUG,"nothing in the config to bind()!");
207         return true;
208 }
209
210 bool BufferedSocket::DoConnect(unsigned long maxtime)
211 {
212         /* The [2] is required because we may write a sockaddr_in6 here, and sockaddr_in6 is larger than sockaddr, where sockaddr_in4 is not. */
213         sockaddr* addr = new sockaddr[2];
214         socklen_t size = sizeof(sockaddr_in);
215 #ifdef IPV6
216         bool v6 = false;
217         if ((!*this->host) || strchr(this->host, ':'))
218                 v6 = true;
219
220         if (v6)
221         {
222                 this->fd = socket(AF_INET6, SOCK_STREAM, 0);
223                 if ((this->fd > -1) && ((strstr(this->IP,"::ffff:") != (char*)&this->IP) && (strstr(this->IP,"::FFFF:") != (char*)&this->IP)))
224                 {
225                         if (!this->BindAddr(this->cbindip))
226                         {
227                                 this->Close();
228                                 this->fd = -1;
229                                 delete[] addr;
230                                 return false;
231                         }
232                 }
233         }
234         else
235 #endif
236         {
237                 this->fd = socket(AF_INET, SOCK_STREAM, 0);
238                 if (this->fd > -1)
239                 {
240                         if (!this->BindAddr(this->cbindip))
241                         {
242                                 this->Close();
243                                 this->fd = -1;
244                                 delete[] addr;
245                                 return false;
246                         }
247                 }
248         }
249
250         if (this->fd == -1)
251         {
252                 this->state = I_ERROR;
253                 this->OnError(I_ERR_SOCKET);
254                 delete[] addr;
255                 return false;
256         }
257
258 #ifdef IPV6
259         if (v6)
260         {
261                 in6_addr addy;
262                 if (inet_pton(AF_INET6, this->host, &addy) > 0)
263                 {
264                         ((sockaddr_in6*)addr)->sin6_family = AF_INET6;
265                         memcpy(&((sockaddr_in6*)addr)->sin6_addr, &addy, sizeof(addy));
266                         ((sockaddr_in6*)addr)->sin6_port = htons(this->port);
267                         size = sizeof(sockaddr_in6);
268                 }
269         }
270         else
271 #endif
272         {
273                 in_addr addy;
274                 if (inet_aton(this->host, &addy) > 0)
275                 {
276                         ((sockaddr_in*)addr)->sin_family = AF_INET;
277                         ((sockaddr_in*)addr)->sin_addr = addy;
278                         ((sockaddr_in*)addr)->sin_port = htons(this->port);
279                 }
280         }
281
282         ServerInstance->SE->NonBlocking(this->fd);
283
284         if (ServerInstance->SE->Connect(this, (sockaddr*)addr, size) == -1)
285         {
286                 if (errno != EINPROGRESS)
287                 {
288                         this->OnError(I_ERR_CONNECT);
289                         this->Close();
290                         this->state = I_ERROR;
291                         delete[] addr;
292                         return false;
293                 }
294
295                 this->Timeout = new SocketTimeout(this->GetFd(), this->ServerInstance, this, maxtime, this->ServerInstance->Time());
296                 this->ServerInstance->Timers->AddTimer(this->Timeout);
297         }
298
299         this->state = I_CONNECTING;
300         delete[] addr;
301         if (this->fd > -1)
302         {
303                 if (!this->ServerInstance->SE->AddFd(this))
304                 {
305                         this->OnError(I_ERR_NOMOREFDS);
306                         this->Close();
307                         this->state = I_ERROR;
308                         return false;
309                 }
310                 this->SetQueues();
311         }
312
313         ServerInstance->Logs->Log("SOCKET", DEBUG,"BufferedSocket::DoConnect success");
314         return true;
315 }
316
317
318 void BufferedSocket::Close()
319 {
320         /* Save this, so we dont lose it,
321          * otherise on failure, error messages
322          * might be inaccurate.
323          */
324         int save = errno;
325         if (this->fd > -1)
326         {
327                 if (this->GetIOHook())
328                 {
329                         try
330                         {
331                                 this->GetIOHook()->OnRawSocketClose(this->fd);
332                         }
333                         catch (CoreException& modexcept)
334                         {
335                                 ServerInstance->Logs->Log("SOCKET", DEFAULT,"%s threw an exception: %s", modexcept.GetSource(), modexcept.GetReason());
336                         }
337                 }
338                 ServerInstance->SE->Shutdown(this, 2);
339                 if (ServerInstance->SE->Close(this) != -1)
340                         this->OnClose();
341
342                 if (ServerInstance->SocketCull.find(this) == ServerInstance->SocketCull.end())
343                         ServerInstance->SocketCull[this] = this;
344         }
345         errno = save;
346 }
347
348 std::string BufferedSocket::GetIP()
349 {
350         return this->IP;
351 }
352
353 const char* BufferedSocket::Read()
354 {
355         if (!ServerInstance->SE->BoundsCheckFd(this))
356                 return NULL;
357
358         int n = 0;
359         char* ReadBuffer = ServerInstance->GetReadBuffer();
360
361         if (this->GetIOHook())
362         {
363                 int result2 = 0;
364                 int MOD_RESULT = 0;
365                 try
366                 {
367                         MOD_RESULT = this->GetIOHook()->OnRawSocketRead(this->fd, ReadBuffer, ServerInstance->Config->NetBufferSize, result2);
368                 }
369                 catch (CoreException& modexcept)
370                 {
371                         ServerInstance->Logs->Log("SOCKET", DEFAULT,"%s threw an exception: %s", modexcept.GetSource(), modexcept.GetReason());
372                 }
373                 if (MOD_RESULT < 0)
374                 {
375                         n = -1;
376                         errno = EAGAIN;
377                 }
378                 else
379                 {
380                         n = result2;
381                 }
382         }
383         else
384         {
385                 n = recv(this->fd, ReadBuffer, ServerInstance->Config->NetBufferSize, 0);
386         }
387
388         /*
389          * This used to do some silly bounds checking instead of just passing bufsize - 1 to recv.
390          * Not only does that make absolutely no sense, but it could potentially result in a read buffer's worth
391          * of data being thrown into the bit bucket for no good reason, which is just *stupid*.. do things correctly now.
392          * --w00t (july 2, 2008)
393          */
394         if (n > 0)
395         {
396                 ReadBuffer[n] = 0;
397                 return ReadBuffer;
398         }
399         else
400         {
401                 int err = errno;
402                 if (err == EAGAIN)
403                         return "";
404                 else
405                         return NULL;
406         }
407 }
408
409 /*
410  * This function formerly tried to flush write buffer each call.
411  * While admirable in attempting to get the data out to wherever
412  * it is going, on a full socket, it's just going to syscall write() and
413  * EAGAIN constantly, instead of waiting in the SE to know if it can write
414  * which will chew a bit of CPU.
415  *
416  * So, now this function returns void (take note) and just adds to the sendq.
417  *
418  * It'll get written at a determinate point when the socketengine tells us it can write.
419  *              -- w00t (april 1, 2008)
420  */
421 void BufferedSocket::Write(const std::string &data)
422 {
423         /* Append the data to the back of the queue ready for writing */
424         outbuffer.push_back(data);
425
426         /* Mark ourselves as wanting write */
427         this->ServerInstance->SE->WantWrite(this);
428 }
429
430 bool BufferedSocket::FlushWriteBuffer()
431 {
432         errno = 0;
433         if ((this->fd > -1) && (this->state == I_CONNECTED))
434         {
435                 if (this->GetIOHook())
436                 {
437                         while (outbuffer.size() && (errno != EAGAIN))
438                         {
439                                 try
440                                 {
441                                         /* XXX: The lack of buffering here is NOT a bug, modules implementing this interface have to
442                                          * implement their own buffering mechanisms
443                                          */
444                                         this->GetIOHook()->OnRawSocketWrite(this->fd, outbuffer[0].c_str(), outbuffer[0].length());
445                                         outbuffer.pop_front();
446                                 }
447                                 catch (CoreException& modexcept)
448                                 {
449                                         ServerInstance->Logs->Log("SOCKET", DEBUG,"%s threw an exception: %s", modexcept.GetSource(), modexcept.GetReason());
450                                         return true;
451                                 }
452                         }
453                 }
454                 else
455                 {
456                         /* If we have multiple lines, try to send them all,
457                          * not just the first one -- Brain
458                          */
459                         while (outbuffer.size() && (errno != EAGAIN))
460                         {
461                                 /* Send a line */
462                                 int result = ServerInstance->SE->Send(this, outbuffer[0].c_str(), outbuffer[0].length(), 0);
463
464                                 if (result > 0)
465                                 {
466                                         if ((unsigned int)result >= outbuffer[0].length())
467                                         {
468                                                 /* The whole block was written (usually a line)
469                                                  * Pop the block off the front of the queue,
470                                                  * dont set errno, because we are clear of errors
471                                                  * and want to try and write the next block too.
472                                                  */
473                                                 outbuffer.pop_front();
474                                         }
475                                         else
476                                         {
477                                                 std::string temp = outbuffer[0].substr(result);
478                                                 outbuffer[0] = temp;
479                                                 /* We didnt get the whole line out. arses.
480                                                  * Try again next time, i guess. Set errno,
481                                                  * because we shouldnt be writing any more now,
482                                                  * until the socketengine says its safe to do so.
483                                                  */
484                                                 errno = EAGAIN;
485                                         }
486                                 }
487                                 else if (result == 0)
488                                 {
489                                         this->ServerInstance->SE->DelFd(this);
490                                         this->Close();
491                                         return true;
492                                 }
493                                 else if ((result == -1) && (errno != EAGAIN))
494                                 {
495                                         this->OnError(I_ERR_WRITE);
496                                         this->state = I_ERROR;
497                                         this->ServerInstance->SE->DelFd(this);
498                                         this->Close();
499                                         return true;
500                                 }
501                         }
502                 }
503         }
504
505         if ((errno == EAGAIN) && (fd > -1))
506         {
507                 this->ServerInstance->SE->WantWrite(this);
508         }
509
510         return (fd < 0);
511 }
512
513 void SocketTimeout::Tick(time_t)
514 {
515         ServerInstance->Logs->Log("SOCKET", DEBUG,"SocketTimeout::Tick");
516
517         if (ServerInstance->SE->GetRef(this->sfd) != this->sock)
518                 return;
519
520         if (this->sock->state == I_CONNECTING)
521         {
522                 // for connecting sockets, the timeout can occur
523                 // which causes termination of the connection after
524                 // the given number of seconds without a successful
525                 // connection.
526                 this->sock->OnTimeout();
527                 this->sock->OnError(I_ERR_TIMEOUT);
528
529                 /* NOTE: We must set this AFTER DelFd, as we added
530                  * this socket whilst writeable. This means that we
531                  * must DELETE the socket whilst writeable too!
532                  */
533                 this->sock->state = I_ERROR;
534
535                 if (ServerInstance->SocketCull.find(this->sock) == ServerInstance->SocketCull.end())
536                         ServerInstance->SocketCull[this->sock] = this->sock;
537         }
538
539         this->sock->Timeout = NULL;
540 }
541
542 bool BufferedSocket::InternalMarkConnected()
543 {
544         /* Our socket was in write-state, so delete it and re-add it
545          * in read-state.
546          */
547         this->SetState(I_CONNECTED);
548
549         if (this->GetIOHook())
550         {
551                 ServerInstance->Logs->Log("SOCKET",DEBUG,"Hook for raw connect");
552                 try
553                 {
554                         this->GetIOHook()->OnRawSocketConnect(this->fd);
555                 }
556                 catch (CoreException& modexcept)
557                 {
558                         ServerInstance->Logs->Log("SOCKET",DEBUG,"%s threw an exception: %s", modexcept.GetSource(), modexcept.GetReason());
559                         return false;
560                 }
561         }
562         return this->OnConnected();
563 }
564
565 void BufferedSocket::SetState(BufferedSocketState s)
566 {
567         this->state = s;
568 }
569
570 BufferedSocketState BufferedSocket::GetState()
571 {
572         return this->state;
573 }
574
575 bool BufferedSocket::OnConnected() { return true; }
576 void BufferedSocket::OnError(BufferedSocketError) { return; }
577 int BufferedSocket::OnDisconnect() { return 0; }
578 bool BufferedSocket::OnDataReady() { return true; }
579 bool BufferedSocket::OnWriteReady()
580 {
581         // Default behaviour: just try write some.
582         return !this->FlushWriteBuffer();
583 }
584 void BufferedSocket::OnTimeout() { return; }
585 void BufferedSocket::OnClose() { return; }
586
587 BufferedSocket::~BufferedSocket()
588 {
589         this->Close();
590         if (Timeout)
591         {
592                 ServerInstance->Timers->DelTimer(Timeout);
593                 Timeout = NULL;
594         }
595 }
596
597 void BufferedSocket::HandleEvent(EventType et, int errornum)
598 {
599         switch (et)
600         {
601                 case EVENT_ERROR:
602                 {
603                         switch (errornum)
604                         {
605                                 case ETIMEDOUT:
606                                         this->OnError(I_ERR_TIMEOUT);
607                                         break;
608                                 case ECONNREFUSED:
609                                 case 0:
610                                         this->OnError(this->state == I_CONNECTING ? I_ERR_CONNECT : I_ERR_WRITE);
611                                         break;
612                                 case EADDRINUSE:
613                                         this->OnError(I_ERR_BIND);
614                                         break;
615                                 case EPIPE:
616                                 case EIO:
617                                         this->OnError(I_ERR_WRITE);
618                                         break;
619                         }
620
621                         if (this->ServerInstance->SocketCull.find(this) == this->ServerInstance->SocketCull.end())
622                                 this->ServerInstance->SocketCull[this] = this;
623                         return;
624                         break;
625                 }
626                 case EVENT_READ:
627                 {
628                         if (!this->OnDataReady())
629                         {
630                                 if (this->ServerInstance->SocketCull.find(this) == this->ServerInstance->SocketCull.end())
631                                         this->ServerInstance->SocketCull[this] = this;
632                                 return;
633                         }
634                         break;
635                 }
636                 case EVENT_WRITE:
637                 {
638                         if (this->state == I_CONNECTING)
639                         {
640                                 if (!this->InternalMarkConnected())
641                                 {
642                                         if (this->ServerInstance->SocketCull.find(this) == this->ServerInstance->SocketCull.end())
643                                                 this->ServerInstance->SocketCull[this] = this;
644                                         return;
645                                 }
646                                 return;
647                         }
648                         else
649                         {
650                                 if (!this->OnWriteReady())
651                                 {
652                                         if (this->ServerInstance->SocketCull.find(this) == this->ServerInstance->SocketCull.end())
653                                                 this->ServerInstance->SocketCull[this] = this;
654                                         return;
655                                 }
656                         }
657                         break;
658                 }
659         }
660 }
661