]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/inspsocket.cpp
Cleanup of some internals. Tested via m_httpd.
[user/henk/code/inspircd.git] / src / inspsocket.cpp
1 /*       +------------------------------------+
2  *       | Inspire Internet Relay Chat Daemon |
3  *       +------------------------------------+
4  *
5  *  InspIRCd: (C) 2002-2008 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->Instance = 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->Instance = SI;
41         if (this->fd > -1)
42                 this->Instance->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->Instance = 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->Instance->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->Instance->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->Instance);
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 (Instance->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         Instance->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         Instance->SE->NonBlocking(this->fd);
258
259         if (Instance->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                         return false;
267                 }
268
269                 this->Timeout = new SocketTimeout(this->GetFd(), this->Instance, this, maxtime, this->Instance->Time());
270                 this->Instance->Timers->AddTimer(this->Timeout);
271         }
272
273         this->state = I_CONNECTING;
274         if (this->fd > -1)
275         {
276                 if (!this->Instance->SE->AddFd(this))
277                 {
278                         this->OnError(I_ERR_NOMOREFDS);
279                         this->Close();
280                         this->state = I_ERROR;
281                         return false;
282                 }
283                 this->SetQueues();
284         }
285
286         Instance->Logs->Log("SOCKET", DEBUG,"BufferedSocket::DoConnect success");
287         return true;
288 }
289
290
291 void BufferedSocket::Close()
292 {
293         /* Save this, so we dont lose it,
294          * otherise on failure, error messages
295          * might be inaccurate.
296          */
297         int save = errno;
298         if (this->fd > -1)
299         {
300                 if (this->GetIOHook())
301                 {
302                         try
303                         {
304                                 this->GetIOHook()->OnRawSocketClose(this->fd);
305                         }
306                         catch (CoreException& modexcept)
307                         {
308                                 Instance->Logs->Log("SOCKET", DEFAULT,"%s threw an exception: %s", modexcept.GetSource(), modexcept.GetReason());
309                         }
310                 }
311                 Instance->SE->Shutdown(this, 2);
312                 if (Instance->SE->Close(this) != -1)
313                         this->OnClose();
314
315                 if (Instance->SocketCull.find(this) == Instance->SocketCull.end())
316                         Instance->SocketCull[this] = this;
317         }
318         errno = save;
319 }
320
321 std::string BufferedSocket::GetIP()
322 {
323         return this->IP;
324 }
325
326 const char* BufferedSocket::Read()
327 {
328         if (!Instance->SE->BoundsCheckFd(this))
329                 return NULL;
330
331         int n = 0;
332         char* ReadBuffer = Instance->GetReadBuffer();
333
334         if (this->GetIOHook())
335         {
336                 int result2 = 0;
337                 int MOD_RESULT = 0;
338                 try
339                 {
340                         MOD_RESULT = this->GetIOHook()->OnRawSocketRead(this->fd, ReadBuffer, Instance->Config->NetBufferSize, result2);
341                 }
342                 catch (CoreException& modexcept)
343                 {
344                         Instance->Logs->Log("SOCKET", DEFAULT,"%s threw an exception: %s", modexcept.GetSource(), modexcept.GetReason());
345                 }
346                 if (MOD_RESULT < 0)
347                 {
348                         n = -1;
349                         errno = EAGAIN;
350                 }
351                 else
352                 {
353                         n = result2;
354                 }
355         }
356         else
357         {
358                 n = recv(this->fd, ReadBuffer, Instance->Config->NetBufferSize, 0);
359         }
360
361         /*
362          * This used to do some silly bounds checking instead of just passing bufsize - 1 to recv.
363          * Not only does that make absolutely no sense, but it could potentially result in a read buffer's worth
364          * of data being thrown into the bit bucket for no good reason, which is just *stupid*.. do things correctly now.
365          * --w00t (july 2, 2008)
366          */
367         if (n > 0)
368         {
369                 ReadBuffer[n] = 0;
370                 return ReadBuffer;
371         }
372         else
373         {
374                 int err = errno;
375                 if (err == EAGAIN)
376                         return "";
377                 else
378                         return NULL;
379         }
380 }
381
382 /*
383  * This function formerly tried to flush write buffer each call.
384  * While admirable in attempting to get the data out to wherever
385  * it is going, on a full socket, it's just going to syscall write() and
386  * EAGAIN constantly, instead of waiting in the SE to know if it can write
387  * which will chew a bit of CPU.
388  *
389  * So, now this function returns void (take note) and just adds to the sendq.
390  *
391  * It'll get written at a determinate point when the socketengine tells us it can write.
392  *              -- w00t (april 1, 2008)
393  */
394 void BufferedSocket::Write(const std::string &data)
395 {
396         /* Append the data to the back of the queue ready for writing */
397         outbuffer.push_back(data);
398
399         /* Mark ourselves as wanting write */
400         this->Instance->SE->WantWrite(this);
401 }
402
403 bool BufferedSocket::FlushWriteBuffer()
404 {
405         errno = 0;
406         if ((this->fd > -1) && (this->state == I_CONNECTED))
407         {
408                 if (this->GetIOHook())
409                 {
410                         while (outbuffer.size() && (errno != EAGAIN))
411                         {
412                                 try
413                                 {
414                                         /* XXX: The lack of buffering here is NOT a bug, modules implementing this interface have to
415                                          * implement their own buffering mechanisms
416                                          */
417                                         this->GetIOHook()->OnRawSocketWrite(this->fd, outbuffer[0].c_str(), outbuffer[0].length());
418                                         outbuffer.pop_front();
419                                 }
420                                 catch (CoreException& modexcept)
421                                 {
422                                         Instance->Logs->Log("SOCKET", DEBUG,"%s threw an exception: %s", modexcept.GetSource(), modexcept.GetReason());
423                                         return true;
424                                 }
425                         }
426                 }
427                 else
428                 {
429                         /* If we have multiple lines, try to send them all,
430                          * not just the first one -- Brain
431                          */
432                         while (outbuffer.size() && (errno != EAGAIN))
433                         {
434                                 /* Send a line */
435                                 int result = Instance->SE->Send(this, outbuffer[0].c_str(), outbuffer[0].length(), 0);
436
437                                 if (result > 0)
438                                 {
439                                         if ((unsigned int)result >= outbuffer[0].length())
440                                         {
441                                                 /* The whole block was written (usually a line)
442                                                  * Pop the block off the front of the queue,
443                                                  * dont set errno, because we are clear of errors
444                                                  * and want to try and write the next block too.
445                                                  */
446                                                 outbuffer.pop_front();
447                                         }
448                                         else
449                                         {
450                                                 std::string temp = outbuffer[0].substr(result);
451                                                 outbuffer[0] = temp;
452                                                 /* We didnt get the whole line out. arses.
453                                                  * Try again next time, i guess. Set errno,
454                                                  * because we shouldnt be writing any more now,
455                                                  * until the socketengine says its safe to do so.
456                                                  */
457                                                 errno = EAGAIN;
458                                         }
459                                 }
460                                 else if (result == 0)
461                                 {
462                                         this->Instance->SE->DelFd(this);
463                                         this->Close();
464                                         return true;
465                                 }
466                                 else if ((result == -1) && (errno != EAGAIN))
467                                 {
468                                         this->OnError(I_ERR_WRITE);
469                                         this->state = I_ERROR;
470                                         this->Instance->SE->DelFd(this);
471                                         this->Close();
472                                         return true;
473                                 }
474                         }
475                 }
476         }
477
478         if ((errno == EAGAIN) && (fd > -1))
479         {
480                 this->Instance->SE->WantWrite(this);
481         }
482
483         return (fd < 0);
484 }
485
486 void SocketTimeout::Tick(time_t)
487 {
488         ServerInstance->Logs->Log("SOCKET", DEBUG,"SocketTimeout::Tick");
489
490         if (ServerInstance->SE->GetRef(this->sfd) != this->sock)
491                 return;
492
493         if (this->sock->state == I_CONNECTING)
494         {
495                 // for connecting sockets, the timeout can occur
496                 // which causes termination of the connection after
497                 // the given number of seconds without a successful
498                 // connection.
499                 this->sock->OnTimeout();
500                 this->sock->OnError(I_ERR_TIMEOUT);
501
502                 /* NOTE: We must set this AFTER DelFd, as we added
503                  * this socket whilst writeable. This means that we
504                  * must DELETE the socket whilst writeable too!
505                  */
506                 this->sock->state = I_ERROR;
507
508                 if (ServerInstance->SocketCull.find(this->sock) == ServerInstance->SocketCull.end())
509                         ServerInstance->SocketCull[this->sock] = this->sock;
510         }
511
512         this->sock->Timeout = NULL;
513 }
514
515 bool BufferedSocket::InternalMarkConnected()
516 {
517         /* Our socket was in write-state, so delete it and re-add it
518          * in read-state.
519          */
520         this->SetState(I_CONNECTED);
521
522         if (this->GetIOHook())
523         {
524                 Instance->Logs->Log("SOCKET",DEBUG,"Hook for raw connect");
525                 try
526                 {
527                         this->GetIOHook()->OnRawSocketConnect(this->fd);
528                 }
529                 catch (CoreException& modexcept)
530                 {
531                         Instance->Logs->Log("SOCKET",DEBUG,"%s threw an exception: %s", modexcept.GetSource(), modexcept.GetReason());
532                         return false;
533                 }
534         }
535         return this->OnConnected();
536 }
537
538 void BufferedSocket::SetState(BufferedSocketState s)
539 {
540         this->state = s;
541 }
542
543 BufferedSocketState BufferedSocket::GetState()
544 {
545         return this->state;
546 }
547
548 bool BufferedSocket::OnConnected() { return true; }
549 void BufferedSocket::OnError(BufferedSocketError) { return; }
550 int BufferedSocket::OnDisconnect() { return 0; }
551 bool BufferedSocket::OnDataReady() { return true; }
552 bool BufferedSocket::OnWriteReady()
553 {
554         // Default behaviour: just try write some.
555         return !this->FlushWriteBuffer();
556 }
557 void BufferedSocket::OnTimeout() { return; }
558 void BufferedSocket::OnClose() { return; }
559
560 BufferedSocket::~BufferedSocket()
561 {
562         this->Close();
563         if (Timeout)
564         {
565                 Instance->Timers->DelTimer(Timeout);
566                 Timeout = NULL;
567         }
568 }
569
570 void BufferedSocket::HandleEvent(EventType et, int errornum)
571 {
572         switch (et)
573         {
574                 case EVENT_ERROR:
575                 {
576                         switch (errornum)
577                         {
578                                 case ETIMEDOUT:
579                                         this->OnError(I_ERR_TIMEOUT);
580                                         break;
581                                 case ECONNREFUSED:
582                                 case 0:
583                                         this->OnError(this->state == I_CONNECTING ? I_ERR_CONNECT : I_ERR_WRITE);
584                                         break;
585                                 case EADDRINUSE:
586                                         this->OnError(I_ERR_BIND);
587                                         break;
588                                 case EPIPE:
589                                 case EIO:
590                                         this->OnError(I_ERR_WRITE);
591                                         break;
592                         }
593
594                         if (this->Instance->SocketCull.find(this) == this->Instance->SocketCull.end())
595                                 this->Instance->SocketCull[this] = this;
596                         return;
597                         break;
598                 }
599                 case EVENT_READ:
600                 {
601                         if (!this->OnDataReady())
602                         {
603                                 if (this->Instance->SocketCull.find(this) == this->Instance->SocketCull.end())
604                                         this->Instance->SocketCull[this] = this;
605                                 return;
606                         }
607                         break;
608                 }
609                 case EVENT_WRITE:
610                 {
611                         if (this->state == I_CONNECTING)
612                         {
613                                 if (!this->InternalMarkConnected())
614                                 {
615                                         if (this->Instance->SocketCull.find(this) == this->Instance->SocketCull.end())
616                                                 this->Instance->SocketCull[this] = this;
617                                         return;
618                                 }
619                                 return;
620                         }
621                         else
622                         {
623                                 if (!this->OnWriteReady())
624                                 {
625                                         if (this->Instance->SocketCull.find(this) == this->Instance->SocketCull.end())
626                                                 this->Instance->SocketCull[this] = this;
627                                         return;
628                                 }
629                         }
630                         break;
631                 }
632         }
633 }
634