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