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