]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/inspsocket.cpp
This file *BROKEN AGAIN* in windows builds (VC9) - uint_16t and uint_32t do not exist...
[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
174         // Case one: If they provided an IP, try bind it
175         if (!ip_to_bind.empty())
176         {
177 #ifdef IPV6
178                 // Check whether or not they are binding to an IPv6 IP..
179                 if (ip_to_bind.find(':') != std::string::npos)
180                         v6 = true;
181 #endif
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 #ifdef IPV6
196                 // Check whether this <bind> is for an ipv6 address
197                 if (current_ip.find(':') != std::string::npos)
198                         v6 = true;
199                 else
200                         v6 = false;
201 #endif
202
203                 // Make sure IP is nothing local
204                 if (current_ip == "*" || current_ip == "127.0.0.1" || current_ip.empty() || current_ip == "::1")
205                         continue;
206
207                 // Try bind, don't fail if it doesn't bind though.
208                 if (this->DoBindMagic(current_ip, v6))
209                         return true;
210         }
211
212         // 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
213         // (remember, outgoing connections without binding are perfectly ok).
214         ServerInstance->Logs->Log("SOCKET", DEBUG,"nothing in the config to bind()!");
215         return true;
216 }
217
218 bool BufferedSocket::DoConnect(unsigned long maxtime)
219 {
220         /* The [2] is required because we may write a sockaddr_in6 here, and sockaddr_in6 is larger than sockaddr, where sockaddr_in4 is not. */
221         sockaddr* addr = new sockaddr[2];
222         socklen_t size = sizeof(sockaddr_in);
223 #ifdef IPV6
224         bool v6 = false;
225         if ((!*this->host) || strchr(this->host, ':'))
226                 v6 = true;
227
228         if (v6)
229         {
230                 this->fd = socket(AF_INET6, SOCK_STREAM, 0);
231                 if ((this->fd > -1) && ((strstr(this->IP,"::ffff:") != (char*)&this->IP) && (strstr(this->IP,"::FFFF:") != (char*)&this->IP)))
232                 {
233                         if (!this->BindAddr(this->cbindip))
234                         {
235                                 this->Close();
236                                 this->fd = -1;
237                                 delete[] addr;
238                                 return false;
239                         }
240                 }
241         }
242         else
243 #endif
244         {
245                 this->fd = socket(AF_INET, SOCK_STREAM, 0);
246                 if (this->fd > -1)
247                 {
248                         if (!this->BindAddr(this->cbindip))
249                         {
250                                 this->Close();
251                                 this->fd = -1;
252                                 delete[] addr;
253                                 return false;
254                         }
255                 }
256         }
257
258         if (this->fd == -1)
259         {
260                 this->state = I_ERROR;
261                 this->OnError(I_ERR_SOCKET);
262                 delete[] addr;
263                 return false;
264         }
265
266 #ifdef IPV6
267         if (v6)
268         {
269                 in6_addr addy;
270                 if (inet_pton(AF_INET6, this->host, &addy) > 0)
271                 {
272                         ((sockaddr_in6*)addr)->sin6_family = AF_INET6;
273                         memcpy(&((sockaddr_in6*)addr)->sin6_addr, &addy, sizeof(addy));
274                         ((sockaddr_in6*)addr)->sin6_port = htons(this->port);
275                         size = sizeof(sockaddr_in6);
276                 }
277         }
278         else
279 #endif
280         {
281                 in_addr addy;
282                 if (inet_aton(this->host, &addy) > 0)
283                 {
284                         ((sockaddr_in*)addr)->sin_family = AF_INET;
285                         ((sockaddr_in*)addr)->sin_addr = addy;
286                         ((sockaddr_in*)addr)->sin_port = htons(this->port);
287                 }
288         }
289
290         ServerInstance->SE->NonBlocking(this->fd);
291
292         if (ServerInstance->SE->Connect(this, (sockaddr*)addr, size) == -1)
293         {
294                 if (errno != EINPROGRESS)
295                 {
296                         this->OnError(I_ERR_CONNECT);
297                         this->Close();
298                         this->state = I_ERROR;
299                         delete[] addr;
300                         return false;
301                 }
302
303                 this->Timeout = new SocketTimeout(this->GetFd(), this->ServerInstance, this, maxtime, this->ServerInstance->Time());
304                 this->ServerInstance->Timers->AddTimer(this->Timeout);
305         }
306
307         this->state = I_CONNECTING;
308         delete[] addr;
309         if (this->fd > -1)
310         {
311                 if (!this->ServerInstance->SE->AddFd(this))
312                 {
313                         this->OnError(I_ERR_NOMOREFDS);
314                         this->Close();
315                         this->state = I_ERROR;
316                         return false;
317                 }
318                 this->SetQueues();
319         }
320
321         ServerInstance->Logs->Log("SOCKET", DEBUG,"BufferedSocket::DoConnect success");
322         return true;
323 }
324
325
326 void BufferedSocket::Close()
327 {
328         /* Save this, so we dont lose it,
329          * otherise on failure, error messages
330          * might be inaccurate.
331          */
332         int save = errno;
333         if (this->fd > -1)
334         {
335                 if (this->GetIOHook())
336                 {
337                         try
338                         {
339                                 this->GetIOHook()->OnRawSocketClose(this->fd);
340                         }
341                         catch (CoreException& modexcept)
342                         {
343                                 ServerInstance->Logs->Log("SOCKET", DEFAULT,"%s threw an exception: %s", modexcept.GetSource(), modexcept.GetReason());
344                         }
345                 }
346                 ServerInstance->SE->Shutdown(this, 2);
347                 if (ServerInstance->SE->Close(this) != -1)
348                         this->OnClose();
349
350                 if (ServerInstance->SocketCull.find(this) == ServerInstance->SocketCull.end())
351                         ServerInstance->SocketCull[this] = this;
352         }
353         errno = save;
354 }
355
356 std::string BufferedSocket::GetIP()
357 {
358         return this->IP;
359 }
360
361 const char* BufferedSocket::Read()
362 {
363         if (!ServerInstance->SE->BoundsCheckFd(this))
364                 return NULL;
365
366         int n = 0;
367         char* ReadBuffer = ServerInstance->GetReadBuffer();
368
369         if (this->GetIOHook())
370         {
371                 int result2 = 0;
372                 int MOD_RESULT = 0;
373                 try
374                 {
375                         MOD_RESULT = this->GetIOHook()->OnRawSocketRead(this->fd, ReadBuffer, ServerInstance->Config->NetBufferSize, result2);
376                 }
377                 catch (CoreException& modexcept)
378                 {
379                         ServerInstance->Logs->Log("SOCKET", DEFAULT,"%s threw an exception: %s", modexcept.GetSource(), modexcept.GetReason());
380                 }
381                 if (MOD_RESULT < 0)
382                 {
383                         n = -1;
384                         errno = EAGAIN;
385                 }
386                 else
387                 {
388                         n = result2;
389                 }
390         }
391         else
392         {
393                 n = recv(this->fd, ReadBuffer, ServerInstance->Config->NetBufferSize, 0);
394         }
395
396         /*
397          * This used to do some silly bounds checking instead of just passing bufsize - 1 to recv.
398          * Not only does that make absolutely no sense, but it could potentially result in a read buffer's worth
399          * of data being thrown into the bit bucket for no good reason, which is just *stupid*.. do things correctly now.
400          * --w00t (july 2, 2008)
401          */
402         if (n > 0)
403         {
404                 ReadBuffer[n] = 0;
405                 return ReadBuffer;
406         }
407         else
408         {
409                 int err = errno;
410                 if (err == EAGAIN)
411                         return "";
412                 else
413                         return NULL;
414         }
415 }
416
417 /*
418  * This function formerly tried to flush write buffer each call.
419  * While admirable in attempting to get the data out to wherever
420  * it is going, on a full socket, it's just going to syscall write() and
421  * EAGAIN constantly, instead of waiting in the SE to know if it can write
422  * which will chew a bit of CPU.
423  *
424  * So, now this function returns void (take note) and just adds to the sendq.
425  *
426  * It'll get written at a determinate point when the socketengine tells us it can write.
427  *              -- w00t (april 1, 2008)
428  */
429 void BufferedSocket::Write(const std::string &data)
430 {
431         /* Append the data to the back of the queue ready for writing */
432         outbuffer.push_back(data);
433
434         /* Mark ourselves as wanting write */
435         this->ServerInstance->SE->WantWrite(this);
436 }
437
438 bool BufferedSocket::FlushWriteBuffer()
439 {
440         errno = 0;
441         if ((this->fd > -1) && (this->state == I_CONNECTED))
442         {
443                 if (this->GetIOHook())
444                 {
445                         while (outbuffer.size() && (errno != EAGAIN))
446                         {
447                                 try
448                                 {
449                                         /* XXX: The lack of buffering here is NOT a bug, modules implementing this interface have to
450                                          * implement their own buffering mechanisms
451                                          */
452                                         this->GetIOHook()->OnRawSocketWrite(this->fd, outbuffer[0].c_str(), outbuffer[0].length());
453                                         outbuffer.pop_front();
454                                 }
455                                 catch (CoreException& modexcept)
456                                 {
457                                         ServerInstance->Logs->Log("SOCKET", DEBUG,"%s threw an exception: %s", modexcept.GetSource(), modexcept.GetReason());
458                                         return true;
459                                 }
460                         }
461                 }
462                 else
463                 {
464                         /* If we have multiple lines, try to send them all,
465                          * not just the first one -- Brain
466                          */
467                         while (outbuffer.size() && (errno != EAGAIN))
468                         {
469                                 /* Send a line */
470                                 int result = ServerInstance->SE->Send(this, outbuffer[0].c_str(), outbuffer[0].length(), 0);
471
472                                 if (result > 0)
473                                 {
474                                         if ((unsigned int)result >= outbuffer[0].length())
475                                         {
476                                                 /* The whole block was written (usually a line)
477                                                  * Pop the block off the front of the queue,
478                                                  * dont set errno, because we are clear of errors
479                                                  * and want to try and write the next block too.
480                                                  */
481                                                 outbuffer.pop_front();
482                                         }
483                                         else
484                                         {
485                                                 std::string temp = outbuffer[0].substr(result);
486                                                 outbuffer[0] = temp;
487                                                 /* We didnt get the whole line out. arses.
488                                                  * Try again next time, i guess. Set errno,
489                                                  * because we shouldnt be writing any more now,
490                                                  * until the socketengine says its safe to do so.
491                                                  */
492                                                 errno = EAGAIN;
493                                         }
494                                 }
495                                 else if (result == 0)
496                                 {
497                                         this->ServerInstance->SE->DelFd(this);
498                                         this->Close();
499                                         return true;
500                                 }
501                                 else if ((result == -1) && (errno != EAGAIN))
502                                 {
503                                         this->OnError(I_ERR_WRITE);
504                                         this->state = I_ERROR;
505                                         this->ServerInstance->SE->DelFd(this);
506                                         this->Close();
507                                         return true;
508                                 }
509                         }
510                 }
511         }
512
513         if ((errno == EAGAIN) && (fd > -1))
514         {
515                 this->ServerInstance->SE->WantWrite(this);
516         }
517
518         return (fd < 0);
519 }
520
521 void SocketTimeout::Tick(time_t)
522 {
523         ServerInstance->Logs->Log("SOCKET", DEBUG,"SocketTimeout::Tick");
524
525         if (ServerInstance->SE->GetRef(this->sfd) != this->sock)
526                 return;
527
528         if (this->sock->state == I_CONNECTING)
529         {
530                 // for connecting sockets, the timeout can occur
531                 // which causes termination of the connection after
532                 // the given number of seconds without a successful
533                 // connection.
534                 this->sock->OnTimeout();
535                 this->sock->OnError(I_ERR_TIMEOUT);
536
537                 /* NOTE: We must set this AFTER DelFd, as we added
538                  * this socket whilst writeable. This means that we
539                  * must DELETE the socket whilst writeable too!
540                  */
541                 this->sock->state = I_ERROR;
542
543                 if (ServerInstance->SocketCull.find(this->sock) == ServerInstance->SocketCull.end())
544                         ServerInstance->SocketCull[this->sock] = this->sock;
545         }
546
547         this->sock->Timeout = NULL;
548 }
549
550 bool BufferedSocket::InternalMarkConnected()
551 {
552         /* Our socket was in write-state, so delete it and re-add it
553          * in read-state.
554          */
555         this->SetState(I_CONNECTED);
556
557         if (this->GetIOHook())
558         {
559                 ServerInstance->Logs->Log("SOCKET",DEBUG,"Hook for raw connect");
560                 try
561                 {
562                         this->GetIOHook()->OnRawSocketConnect(this->fd);
563                 }
564                 catch (CoreException& modexcept)
565                 {
566                         ServerInstance->Logs->Log("SOCKET",DEBUG,"%s threw an exception: %s", modexcept.GetSource(), modexcept.GetReason());
567                         return false;
568                 }
569         }
570         return this->OnConnected();
571 }
572
573 void BufferedSocket::SetState(BufferedSocketState s)
574 {
575         this->state = s;
576 }
577
578 BufferedSocketState BufferedSocket::GetState()
579 {
580         return this->state;
581 }
582
583 bool BufferedSocket::OnConnected() { return true; }
584 void BufferedSocket::OnError(BufferedSocketError) { return; }
585 int BufferedSocket::OnDisconnect() { return 0; }
586 bool BufferedSocket::OnDataReady() { return true; }
587 bool BufferedSocket::OnWriteReady()
588 {
589         // Default behaviour: just try write some.
590         return !this->FlushWriteBuffer();
591 }
592 void BufferedSocket::OnTimeout() { return; }
593 void BufferedSocket::OnClose() { return; }
594
595 BufferedSocket::~BufferedSocket()
596 {
597         this->Close();
598         if (Timeout)
599         {
600                 ServerInstance->Timers->DelTimer(Timeout);
601                 Timeout = NULL;
602         }
603 }
604
605 void BufferedSocket::HandleEvent(EventType et, int errornum)
606 {
607         switch (et)
608         {
609                 case EVENT_ERROR:
610                 {
611                         switch (errornum)
612                         {
613                                 case ETIMEDOUT:
614                                         this->OnError(I_ERR_TIMEOUT);
615                                         break;
616                                 case ECONNREFUSED:
617                                 case 0:
618                                         this->OnError(this->state == I_CONNECTING ? I_ERR_CONNECT : I_ERR_WRITE);
619                                         break;
620                                 case EADDRINUSE:
621                                         this->OnError(I_ERR_BIND);
622                                         break;
623                                 case EPIPE:
624                                 case EIO:
625                                         this->OnError(I_ERR_WRITE);
626                                         break;
627                         }
628
629                         if (this->ServerInstance->SocketCull.find(this) == this->ServerInstance->SocketCull.end())
630                                 this->ServerInstance->SocketCull[this] = this;
631                         return;
632                         break;
633                 }
634                 case EVENT_READ:
635                 {
636                         if (!this->OnDataReady())
637                         {
638                                 if (this->ServerInstance->SocketCull.find(this) == this->ServerInstance->SocketCull.end())
639                                         this->ServerInstance->SocketCull[this] = this;
640                                 return;
641                         }
642                         break;
643                 }
644                 case EVENT_WRITE:
645                 {
646                         if (this->state == I_CONNECTING)
647                         {
648                                 if (!this->InternalMarkConnected())
649                                 {
650                                         if (this->ServerInstance->SocketCull.find(this) == this->ServerInstance->SocketCull.end())
651                                                 this->ServerInstance->SocketCull[this] = this;
652                                         return;
653                                 }
654                                 return;
655                         }
656                         else
657                         {
658                                 if (!this->OnWriteReady())
659                                 {
660                                         if (this->ServerInstance->SocketCull.find(this) == this->ServerInstance->SocketCull.end())
661                                                 this->ServerInstance->SocketCull[this] = this;
662                                         return;
663                                 }
664                         }
665                         break;
666                 }
667         }
668 }
669