]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/inspsocket.cpp
Add strerror(errno) to port bind failure on TreeSocket
[user/henk/code/inspircd.git] / src / inspsocket.cpp
1 /*       +------------------------------------+
2  *       | Inspire Internet Relay Chat Daemon |
3  *       +------------------------------------+
4  *
5  *  InspIRCd: (C) 2002-2007 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 #include "socket.h"
15 #include "configreader.h"
16 #include "inspstring.h"
17 #include "socketengine.h"
18 #include "inspircd.h"
19
20 using irc::sockets::OpenTCPSocket;
21 using irc::sockets::insp_inaddr;
22 using irc::sockets::insp_sockaddr;
23
24 bool InspSocket::Readable()
25 {
26         return ((this->state != I_CONNECTING) && (this->WaitingForWriteEvent == false));
27 }
28
29 InspSocket::InspSocket(InspIRCd* SI)
30 {
31         this->state = I_DISCONNECTED;
32         this->fd = -1;
33         this->WaitingForWriteEvent = false;
34         this->Instance = SI;
35         this->IsIOHooked = false;
36 }
37
38 InspSocket::InspSocket(InspIRCd* SI, int newfd, const char* ip)
39 {
40         this->fd = newfd;
41         this->state = I_CONNECTED;
42         strlcpy(this->IP,ip,MAXBUF);
43         this->WaitingForWriteEvent = false;
44         this->Instance = SI;
45         this->IsIOHooked = false;
46         if (this->fd > -1)
47                 this->Instance->SE->AddFd(this);
48 }
49
50 InspSocket::InspSocket(InspIRCd* SI, const std::string &ipaddr, int aport, bool listening, unsigned long maxtime)
51 {
52         this->fd = -1;
53         this->Instance = SI;
54         strlcpy(host,ipaddr.c_str(),MAXBUF);
55         this->WaitingForWriteEvent = false;
56         this->IsIOHooked = false;
57         if (listening)
58         {
59                 if ((this->fd = OpenTCPSocket()) == ERROR)
60                 {
61                         this->fd = -1;
62                         this->state = I_ERROR;
63                         this->OnError(I_ERR_SOCKET);
64                         return;
65                 }
66                 else
67                 {
68                         if (!SI->BindSocket(this->fd,this->client,this->server,aport,(char*)ipaddr.c_str()))
69                         {
70                                 this->Close();
71                                 this->fd = -1;
72                                 this->state = I_ERROR;
73                                 this->OnError(I_ERR_BIND);
74                                 this->ClosePending = true;
75                                 return;
76                         }
77                         else
78                         {
79                                 this->state = I_LISTENING;
80                                 if (this->fd > -1)
81                                 {
82                                         if (!this->Instance->SE->AddFd(this))
83                                         {
84                                                 this->Close();
85                                                 this->state = I_ERROR;
86                                                 this->OnError(I_ERR_NOMOREFDS);
87                                         }
88                                 }
89                                 return;
90                         }
91                 }                       
92         }
93         else
94         {
95                 strlcpy(this->host,ipaddr.c_str(),MAXBUF);
96                 this->port = aport;
97
98                 if (insp_aton(host,&addy) < 1)
99                 {
100                         this->Instance->Log(DEBUG,"BUG: Hostname passed to InspSocket, rather than an IP address!");
101                         this->Close();
102                         this->fd = -1;
103                         this->state = I_ERROR;
104                         this->OnError(I_ERR_RESOLVE);
105                         return;
106                 }
107                 else
108                 {
109                         strlcpy(this->IP,host,MAXBUF);
110                         timeout_val = maxtime;
111                         this->DoConnect();
112                 }
113         }
114 }
115
116 void InspSocket::WantWrite()
117 {
118         this->Instance->SE->WantWrite(this);
119         this->WaitingForWriteEvent = true;
120 }
121
122 void InspSocket::SetQueues(int nfd)
123 {
124         // attempt to increase socket sendq and recvq as high as its possible
125         int sendbuf = 32768;
126         int recvbuf = 32768;
127         setsockopt(nfd,SOL_SOCKET,SO_SNDBUF,(const void *)&sendbuf,sizeof(sendbuf));
128         setsockopt(nfd,SOL_SOCKET,SO_RCVBUF,(const void *)&recvbuf,sizeof(sendbuf));
129 }
130
131 /* Most irc servers require you to specify the ip you want to bind to.
132  * If you dont specify an IP, they rather dumbly bind to the first IP
133  * of the box (e.g. INADDR_ANY). In InspIRCd, we scan thought the IP
134  * addresses we've bound server ports to, and we try and bind our outbound
135  * connections to the first usable non-loopback and non-any IP we find.
136  * This is easier to configure when you have a lot of links and a lot
137  * of servers to configure.
138  */
139 bool InspSocket::BindAddr()
140 {
141         insp_inaddr n;
142         ConfigReader Conf(this->Instance);
143         for (int j =0; j < Conf.Enumerate("bind"); j++)
144         {
145                 std::string Type = Conf.ReadValue("bind","type",j);
146                 std::string IP = Conf.ReadValue("bind","address",j);
147                 if (Type == "servers")
148                 {
149                         if ((IP != "*") && (IP != "127.0.0.1") && (IP != ""))
150                         {
151                                 insp_sockaddr s;
152
153                                 if (insp_aton(IP.c_str(),&n) > 0)
154                                 {
155 #ifdef IPV6
156                                         s.sin6_addr = n;
157                                         s.sin6_family = AF_FAMILY;
158 #else
159                                         s.sin_addr = n;
160                                         s.sin_family = AF_FAMILY;
161 #endif
162                                         if (bind(this->fd,(struct sockaddr*)&s,sizeof(s)) < 0)
163                                         {
164                                                 this->state = I_ERROR;
165                                                 this->OnError(I_ERR_BIND);
166                                                 this->fd = -1;
167                                                 return false;
168                                         }
169                                         return true;
170                                 }
171                         }
172                 }
173         }
174         return true;
175 }
176
177 bool InspSocket::DoConnect()
178 {
179         if ((this->fd = socket(AF_FAMILY, SOCK_STREAM, 0)) == -1)
180         {
181                 this->state = I_ERROR;
182                 this->OnError(I_ERR_SOCKET);
183                 return false;
184         }
185
186         if ((strstr(this->IP,"::ffff:") != (char*)&this->IP) && (strstr(this->IP,"::FFFF:") != (char*)&this->IP))
187         {
188                 if (!this->BindAddr())
189                         return false;
190         }
191
192         insp_aton(this->IP,&addy);
193 #ifdef IPV6
194         addr.sin6_family = AF_FAMILY;
195         memcpy(&addr.sin6_addr, &addy, sizeof(insp_inaddr));
196         addr.sin6_port = htons(this->port);
197 #else
198         addr.sin_family = AF_FAMILY;
199         addr.sin_addr = addy;
200         addr.sin_port = htons(this->port);
201 #endif
202
203         int flags;
204         flags = fcntl(this->fd, F_GETFL, 0);
205         fcntl(this->fd, F_SETFL, flags | O_NONBLOCK);
206
207         if (connect(this->fd, (sockaddr*)&this->addr,sizeof(this->addr)) == -1)
208         {
209                 if (errno != EINPROGRESS)
210                 {
211                         this->OnError(I_ERR_CONNECT);
212                         this->Close();
213                         this->state = I_ERROR;
214                         return false;
215                 }
216
217                 this->Timeout = new SocketTimeout(this->GetFd(), this->Instance, this, timeout_val, this->Instance->Time());
218                 this->Instance->Timers->AddTimer(this->Timeout);
219         }
220         this->state = I_CONNECTING;
221         if (this->fd > -1)
222         {
223                 if (!this->Instance->SE->AddFd(this))
224                 {
225                         this->OnError(I_ERR_NOMOREFDS);
226                         this->Close();
227                         this->state = I_ERROR;
228                         return false;
229                 }
230                 this->SetQueues(this->fd);
231         }
232         return true;
233 }
234
235
236 void InspSocket::Close()
237 {
238         if (this->fd > -1)
239         {
240                 if (this->IsIOHooked && Instance->Config->GetIOHook(this))
241                 {
242                         try
243                         {
244                                 Instance->Config->GetIOHook(this)->OnRawSocketClose(this->fd);
245                         }
246                         catch (CoreException& modexcept)
247                         {
248                                 Instance->Log(DEFAULT,"%s threw an exception: %s", modexcept.GetSource(), modexcept.GetReason());
249                         }
250                 }
251                 this->OnClose();
252                 shutdown(this->fd,2);
253                 close(this->fd);
254         }
255 }
256
257 std::string InspSocket::GetIP()
258 {
259         return this->IP;
260 }
261
262 char* InspSocket::Read()
263 {
264         if ((fd < 0) || (fd > MAX_DESCRIPTORS))
265                 return NULL;
266
267         int n = 0;
268
269         if (this->IsIOHooked)
270         {
271                 int result2 = 0;
272                 int MOD_RESULT = 0;
273                 try
274                 {
275                         MOD_RESULT = Instance->Config->GetIOHook(this)->OnRawSocketRead(this->fd,this->ibuf,sizeof(this->ibuf),result2);
276                 }
277                 catch (CoreException& modexcept)
278                 {
279                         Instance->Log(DEFAULT,"%s threw an exception: %s", modexcept.GetSource(), modexcept.GetReason());
280                 }
281                 if (MOD_RESULT < 0)
282                 {
283                         n = -1;
284                         errno = EAGAIN;
285                 }
286                 else
287                 {
288                         n = result2;
289                 }
290         }
291         else
292         {
293                 n = recv(this->fd,this->ibuf,sizeof(this->ibuf),0);
294         }
295
296         if ((n > 0) && (n <= (int)sizeof(this->ibuf)))
297         {
298                 ibuf[n] = 0;
299                 return ibuf;
300         }
301         else
302         {
303                 int err = errno;
304                 if (err == EAGAIN)
305                         return "";
306                 else
307                         return NULL;
308         }
309 }
310
311 void InspSocket::MarkAsClosed()
312 {
313 }
314
315 // There are two possible outcomes to this function.
316 // It will either write all of the data, or an undefined amount.
317 // If an undefined amount is written the connection has failed
318 // and should be aborted.
319 int InspSocket::Write(const std::string &data)
320 {
321         /* Try and append the data to the back of the queue, and send it on its way
322          */
323         outbuffer.push_back(data);
324         this->Instance->SE->WantWrite(this);
325         return (!this->FlushWriteBuffer());
326 }
327
328 bool InspSocket::FlushWriteBuffer()
329 {
330         errno = 0;
331         if ((this->fd > -1) && (this->state == I_CONNECTED))
332         {
333                 if (this->IsIOHooked)
334                 {
335                         while (outbuffer.size() && (errno != EAGAIN))
336                         {
337                                 try
338                                 {
339                                         int result = Instance->Config->GetIOHook(this)->OnRawSocketWrite(this->fd, outbuffer[0].c_str(), outbuffer[0].length());
340                                         if (result > 0)
341                                         {
342                                                 if ((unsigned int)result == outbuffer[0].length())
343                                                 {
344                                                         outbuffer.pop_front();
345                                                 }
346                                                 else
347                                                 {
348                                                         std::string temp = outbuffer[0].substr(result);
349                                                         outbuffer[0] = temp;
350                                                         errno = EAGAIN;
351                                                 }
352                                         }
353                                         else if (((result == -1) && (errno != EAGAIN)) || (result == 0))
354                                         {
355                                                 this->OnError(I_ERR_WRITE);
356                                                 this->state = I_ERROR;
357                                                 this->Instance->SE->DelFd(this);
358                                                 this->Close();
359                                                 return true;
360                                         }
361                                 }
362                                 catch (CoreException& modexcept)
363                                 {
364                                         Instance->Log(DEBUG,"%s threw an exception: %s", modexcept.GetSource(), modexcept.GetReason());
365                                         return true;
366                                 }
367                         }
368                 }
369                 else
370                 {
371                         /* If we have multiple lines, try to send them all,
372                          * not just the first one -- Brain
373                          */
374                         while (outbuffer.size() && (errno != EAGAIN))
375                         {
376                                 /* Send a line */
377                                 int result = write(this->fd,outbuffer[0].c_str(),outbuffer[0].length());
378                                 if (result > 0)
379                                 {
380                                         if ((unsigned int)result == outbuffer[0].length())
381                                         {
382                                                 /* The whole block was written (usually a line)
383                                                  * Pop the block off the front of the queue,
384                                                  * dont set errno, because we are clear of errors
385                                                  * and want to try and write the next block too.
386                                                  */
387                                                 outbuffer.pop_front();
388                                         }
389                                         else
390                                         {
391                                                 std::string temp = outbuffer[0].substr(result);
392                                                 outbuffer[0] = temp;
393                                                 /* We didnt get the whole line out. arses.
394                                                  * Try again next time, i guess. Set errno,
395                                                  * because we shouldnt be writing any more now,
396                                                  * until the socketengine says its safe to do so.
397                                                  */
398                                                 errno = EAGAIN;
399                                         }
400                                 }
401                                 else if ((result == -1) && (errno != EAGAIN))
402                                 {
403                                         this->OnError(I_ERR_WRITE);
404                                         this->state = I_ERROR;
405                                         this->Instance->SE->DelFd(this);
406                                         this->Close();
407                                         return true;
408                                 }
409                         }
410                 }
411         }
412
413         if ((errno == EAGAIN) && (fd > -1))
414         {
415                 this->Instance->SE->WantWrite(this);
416         }
417
418         return (fd < 0);
419 }
420
421 void SocketTimeout::Tick(time_t now)
422 {
423         if (ServerInstance->SE->GetRef(this->sfd) != this->sock)
424                 return;
425
426         if (this->sock->state == I_CONNECTING)
427         {
428                 // for non-listening sockets, the timeout can occur
429                 // which causes termination of the connection after
430                 // the given number of seconds without a successful
431                 // connection.
432                 this->sock->OnTimeout();
433                 this->sock->OnError(I_ERR_TIMEOUT);
434                 this->sock->timeout = true;
435                 ServerInstance->SE->DelFd(this->sock);
436                 /* NOTE: We must set this AFTER DelFd, as we added
437                  * this socket whilst writeable. This means that we
438                  * must DELETE the socket whilst writeable too!
439                  */
440                 this->sock->state = I_ERROR;
441                 this->sock->Close();
442                 delete this->sock;
443                 return;
444         }
445 }
446
447 bool InspSocket::Poll()
448 {
449         if (this->Instance->SE->GetRef(this->fd) != this)
450                 return false;
451
452         int incoming = -1;
453
454         if ((fd < 0) || (fd > MAX_DESCRIPTORS))
455                 return false;
456
457         switch (this->state)
458         {
459                 case I_CONNECTING:
460                         /* Our socket was in write-state, so delete it and re-add it
461                          * in read-state.
462                          */
463                         if (this->fd > -1)
464                         {
465                                 this->Instance->SE->DelFd(this);
466                                 this->SetState(I_CONNECTED);
467                                 if (!this->Instance->SE->AddFd(this))
468                                         return false;
469                         }
470                         if (Instance->Config->GetIOHook(this))
471                         {
472                                 try
473                                 {
474                                         Instance->Config->GetIOHook(this)->OnRawSocketConnect(this->fd);
475                                 }
476                                 catch (CoreException& modexcept)
477                                 {
478                                         Instance->Log(DEBUG,"%s threw an exception: %s", modexcept.GetSource(), modexcept.GetReason());
479                                 }
480                         }
481                         return this->OnConnected();
482                 break;
483                 case I_LISTENING:
484                         length = sizeof (client);
485                         incoming = accept (this->fd, (sockaddr*)&client,&length);
486
487 #ifdef IPV6
488                         this->OnIncomingConnection(incoming, (char*)insp_ntoa(client.sin6_addr));
489 #else
490                         this->OnIncomingConnection(incoming, (char*)insp_ntoa(client.sin_addr));
491 #endif
492
493                         if (this->IsIOHooked)
494                         {
495                                 try
496                                 {
497 #ifdef IPV6
498                                         Instance->Config->GetIOHook(this)->OnRawSocketAccept(incoming, insp_ntoa(client.sin6_addr), this->port);
499 #else
500                                         Instance->Config->GetIOHook(this)->OnRawSocketAccept(incoming, insp_ntoa(client.sin_addr), this->port);
501 #endif
502                                 }
503                                 catch (CoreException& modexcept)
504                                 {
505                                         Instance->Log(DEBUG,"%s threw an exception: %s", modexcept.GetSource(), modexcept.GetReason());
506                                 }
507                         }
508
509                         this->SetQueues(incoming);
510                         return true;
511                 break;
512                 case I_CONNECTED:
513                         /* Process the read event */
514                         return this->OnDataReady();
515                 break;
516                 default:
517                 break;
518         }
519         return true;
520 }
521
522 void InspSocket::SetState(InspSocketState s)
523 {
524         this->state = s;
525 }
526
527 InspSocketState InspSocket::GetState()
528 {
529         return this->state;
530 }
531
532 int InspSocket::GetFd()
533 {
534         return this->fd;
535 }
536
537 bool InspSocket::OnConnected() { return true; }
538 void InspSocket::OnError(InspSocketError e) { return; }
539 int InspSocket::OnDisconnect() { return 0; }
540 int InspSocket::OnIncomingConnection(int newfd, char* ip) { return 0; }
541 bool InspSocket::OnDataReady() { return true; }
542 bool InspSocket::OnWriteReady() { return true; }
543 void InspSocket::OnTimeout() { return; }
544 void InspSocket::OnClose() { return; }
545
546 InspSocket::~InspSocket()
547 {
548         this->Close();
549 }
550
551 void InspSocket::HandleEvent(EventType et, int errornum)
552 {
553         switch (et)
554         {
555                 case EVENT_ERROR:
556                         this->Instance->SE->DelFd(this);
557                         this->Close();
558                         delete this;
559                         return;
560                 break;
561                 case EVENT_READ:
562                         if (!this->Poll())
563                         {
564                                 this->Instance->SE->DelFd(this);
565                                 this->Close();
566                                 delete this;
567                                 return;
568                         }
569                 break;
570                 case EVENT_WRITE:
571                         if (this->WaitingForWriteEvent)
572                         {
573                                 this->WaitingForWriteEvent = false;
574                                 if (!this->OnWriteReady())
575                                 {
576                                         this->Instance->SE->DelFd(this);
577                                         this->Close();
578                                         delete this;
579                                         return;
580                                 }
581                         }
582                         if (this->state == I_CONNECTING)
583                         {
584                                 /* This might look wrong as if we should be actually calling
585                                  * with EVENT_WRITE, but trust me it is correct. There are some
586                                  * writeability-state things in the read code, because of how
587                                  * InspSocket used to work regarding write buffering in previous
588                                  * versions of InspIRCd. - Brain
589                                  */
590                                 this->HandleEvent(EVENT_READ);
591                                 return;
592                         }
593                         else
594                         {
595                                 if (this->FlushWriteBuffer())
596                                 {
597                                         this->Instance->SE->DelFd(this);
598                                         this->Close();
599                                         delete this;
600                                         return;
601                                 }
602                         }
603                 break;
604         }
605 }
606