]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/inspsocket.cpp
Change Extensible to use strongly typed entries
[user/henk/code/inspircd.git] / src / inspsocket.cpp
1 /*       +------------------------------------+
2  *       | Inspire Internet Relay Chat Daemon |
3  *       +------------------------------------+
4  *
5  *  InspIRCd: (C) 2002-2009 InspIRCd Development Team
6  * See: http://wiki.inspircd.org/Credits
7  *
8  * This program is free but copyrighted software; see
9  *            the file COPYING for details.
10  *
11  * ---------------------------------------------------
12  */
13
14 #include "inspircd.h"
15 #include "socket.h"
16 #include "inspstring.h"
17 #include "socketengine.h"
18
19 bool BufferedSocket::Readable()
20 {
21         return (this->state != I_CONNECTING);
22 }
23
24 BufferedSocket::BufferedSocket(InspIRCd* SI)
25 {
26         this->Timeout = NULL;
27         this->state = I_DISCONNECTED;
28         this->fd = -1;
29         this->ServerInstance = SI;
30 }
31
32 BufferedSocket::BufferedSocket(InspIRCd* SI, int newfd, const char* ip)
33 {
34         this->Timeout = NULL;
35         this->fd = newfd;
36         this->state = I_CONNECTED;
37         strlcpy(this->IP,ip,MAXBUF);
38         this->ServerInstance = SI;
39         if (this->fd > -1)
40                 this->ServerInstance->SE->AddFd(this);
41 }
42
43 BufferedSocket::BufferedSocket(InspIRCd* SI, const std::string &ipaddr, int aport, unsigned long maxtime, const std::string &connectbindip)
44 {
45         this->cbindip = connectbindip;
46         this->fd = -1;
47         this->ServerInstance = SI;
48         strlcpy(host,ipaddr.c_str(),MAXBUF);
49         this->Timeout = NULL;
50
51         strlcpy(this->host,ipaddr.c_str(),MAXBUF);
52         this->port = aport;
53
54         irc::sockets::sockaddrs testaddr;
55         if (!irc::sockets::aptosa(host, aport, &testaddr))
56         {
57                 this->ServerInstance->Logs->Log("SOCKET", DEBUG,"BUG: Hostname passed to BufferedSocket, rather than an IP address!");
58                 this->OnError(I_ERR_CONNECT);
59                 this->Close();
60                 this->fd = -1;
61                 this->state = I_ERROR;
62                 return;
63         }
64         else
65         {
66                 strlcpy(this->IP,host,MAXBUF);
67                 if (!this->DoConnect(maxtime))
68                 {
69                         this->OnError(I_ERR_CONNECT);
70                         this->Close();
71                         this->fd = -1;
72                         this->state = I_ERROR;
73                         return;
74                 }
75         }
76 }
77
78 void BufferedSocket::SetQueues()
79 {
80         // attempt to increase socket sendq and recvq as high as its possible
81         int sendbuf = 32768;
82         int recvbuf = 32768;
83         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)))
84         {
85                 //this->ServerInstance->Log(DEFAULT, "Could not increase SO_SNDBUF/SO_RCVBUF for socket %u", GetFd());
86                 ; // 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.
87         }
88 }
89
90 bool BufferedSocket::DoBindMagic(const std::string &current_ip)
91 {
92         irc::sockets::sockaddrs s;
93         if (!irc::sockets::aptosa(current_ip.c_str(), 0, &s))
94         {
95                 errno = EADDRNOTAVAIL;
96                 return false;
97         }
98
99         if (ServerInstance->SE->Bind(this->fd, &s.sa, sa_size(s)) < 0)
100         {
101                 this->state = I_ERROR;
102                 this->OnError(I_ERR_BIND);
103                 return false;
104         }
105
106         return true;
107 }
108
109 /* Most irc servers require you to specify the ip you want to bind to.
110  * If you dont specify an IP, they rather dumbly bind to the first IP
111  * of the box (e.g. INADDR_ANY). In InspIRCd, we scan thought the IP
112  * addresses we've bound server ports to, and we try and bind our outbound
113  * connections to the first usable non-loopback and non-any IP we find.
114  * This is easier to configure when you have a lot of links and a lot
115  * of servers to configure.
116  */
117 bool BufferedSocket::BindAddr(const std::string &ip_to_bind)
118 {
119         ConfigReader Conf(this->ServerInstance);
120
121         // Case one: If they provided an IP, try bind it
122         if (!ip_to_bind.empty())
123         {
124                 // And if it fails, don't do anything.
125                 return this->DoBindMagic(ip_to_bind);
126         }
127
128         for (int j = 0; j < Conf.Enumerate("bind"); j++)
129         {
130                 // We only want to try bind to a server ip.
131                 if (Conf.ReadValue("bind","type",j) != "servers")
132                         continue;
133
134                 // set current IP to the <bind> tag
135                 std::string current_ip = Conf.ReadValue("bind","address",j);
136
137                 // Make sure IP is nothing local
138                 if (current_ip == "*" || current_ip == "127.0.0.1" || current_ip.empty() || current_ip == "::1")
139                         continue;
140
141                 // Try bind, don't fail if it doesn't bind though.
142                 if (this->DoBindMagic(current_ip))
143                         return true;
144         }
145
146         // NOTE: You may wonder WTF we are returning *true* here, but that is because there were no custom binds setup, and so we have nothing to do
147         // (remember, outgoing connections without binding are perfectly ok).
148         ServerInstance->Logs->Log("SOCKET", DEBUG,"nothing in the config to bind()!");
149         return true;
150 }
151
152 bool BufferedSocket::DoConnect(unsigned long maxtime)
153 {
154         irc::sockets::sockaddrs addr;
155         irc::sockets::aptosa(this->host, this->port, &addr);
156
157         this->fd = socket(addr.sa.sa_family, SOCK_STREAM, 0);
158
159         if (this->fd == -1)
160         {
161                 this->state = I_ERROR;
162                 this->OnError(I_ERR_SOCKET);
163                 return false;
164         }
165
166         if (!this->BindAddr(this->cbindip))
167         {
168                 this->Close();
169                 this->fd = -1;
170                 return false;
171         }
172
173         ServerInstance->SE->NonBlocking(this->fd);
174
175         if (ServerInstance->SE->Connect(this, &addr.sa, sa_size(addr)) == -1)
176         {
177                 if (errno != EINPROGRESS)
178                 {
179                         this->OnError(I_ERR_CONNECT);
180                         this->Close();
181                         this->state = I_ERROR;
182                         return false;
183                 }
184
185                 this->Timeout = new SocketTimeout(this->GetFd(), this->ServerInstance, this, maxtime, this->ServerInstance->Time());
186                 this->ServerInstance->Timers->AddTimer(this->Timeout);
187         }
188
189         this->state = I_CONNECTING;
190         if (this->fd > -1)
191         {
192                 if (!this->ServerInstance->SE->AddFd(this))
193                 {
194                         this->OnError(I_ERR_NOMOREFDS);
195                         this->Close();
196                         this->state = I_ERROR;
197                         return false;
198                 }
199                 this->SetQueues();
200         }
201
202         ServerInstance->Logs->Log("SOCKET", DEBUG,"BufferedSocket::DoConnect success");
203         return true;
204 }
205
206
207 void BufferedSocket::Close()
208 {
209         /* Save this, so we dont lose it,
210          * otherise on failure, error messages
211          * might be inaccurate.
212          */
213         int save = errno;
214         if (this->fd > -1)
215         {
216                 if (this->GetIOHook())
217                 {
218                         try
219                         {
220                                 this->GetIOHook()->OnRawSocketClose(this->fd);
221                         }
222                         catch (CoreException& modexcept)
223                         {
224                                 ServerInstance->Logs->Log("SOCKET", DEFAULT,"%s threw an exception: %s", modexcept.GetSource(), modexcept.GetReason());
225                         }
226                 }
227                 ServerInstance->SE->Shutdown(this, 2);
228                 if (ServerInstance->SE->Close(this) != -1)
229                         this->OnClose();
230
231                 if (ServerInstance->SocketCull.find(this) == ServerInstance->SocketCull.end())
232                         ServerInstance->SocketCull[this] = this;
233         }
234         errno = save;
235 }
236
237 std::string BufferedSocket::GetIP()
238 {
239         return this->IP;
240 }
241
242 const char* BufferedSocket::Read()
243 {
244         if (!ServerInstance->SE->BoundsCheckFd(this))
245                 return NULL;
246
247         int n = 0;
248         char* ReadBuffer = ServerInstance->GetReadBuffer();
249
250         if (this->GetIOHook())
251         {
252                 int result2 = 0;
253                 int MOD_RESULT = 0;
254                 try
255                 {
256                         MOD_RESULT = this->GetIOHook()->OnRawSocketRead(this->fd, ReadBuffer, ServerInstance->Config->NetBufferSize, result2);
257                 }
258                 catch (CoreException& modexcept)
259                 {
260                         ServerInstance->Logs->Log("SOCKET", DEFAULT,"%s threw an exception: %s", modexcept.GetSource(), modexcept.GetReason());
261                 }
262                 if (MOD_RESULT < 0)
263                 {
264                         n = -1;
265                         errno = EAGAIN;
266                 }
267                 else
268                 {
269                         n = result2;
270                 }
271         }
272         else
273         {
274                 n = recv(this->fd, ReadBuffer, ServerInstance->Config->NetBufferSize, 0);
275         }
276
277         /*
278          * This used to do some silly bounds checking instead of just passing bufsize - 1 to recv.
279          * Not only does that make absolutely no sense, but it could potentially result in a read buffer's worth
280          * of data being thrown into the bit bucket for no good reason, which is just *stupid*.. do things correctly now.
281          * --w00t (july 2, 2008)
282          */
283         if (n > 0)
284         {
285                 ReadBuffer[n] = 0;
286                 return ReadBuffer;
287         }
288         else
289         {
290                 int err = errno;
291                 if (err == EAGAIN)
292                         return "";
293                 else
294                         return NULL;
295         }
296 }
297
298 /*
299  * This function formerly tried to flush write buffer each call.
300  * While admirable in attempting to get the data out to wherever
301  * it is going, on a full socket, it's just going to syscall write() and
302  * EAGAIN constantly, instead of waiting in the SE to know if it can write
303  * which will chew a bit of CPU.
304  *
305  * So, now this function returns void (take note) and just adds to the sendq.
306  *
307  * It'll get written at a determinate point when the socketengine tells us it can write.
308  *              -- w00t (april 1, 2008)
309  */
310 void BufferedSocket::Write(const std::string &data)
311 {
312         /* Append the data to the back of the queue ready for writing */
313         outbuffer.push_back(data);
314
315         /* Mark ourselves as wanting write */
316         this->ServerInstance->SE->WantWrite(this);
317 }
318
319 bool BufferedSocket::FlushWriteBuffer()
320 {
321         errno = 0;
322         if ((this->fd > -1) && (this->state == I_CONNECTED))
323         {
324                 if (this->GetIOHook())
325                 {
326                         while (outbuffer.size() && (errno != EAGAIN))
327                         {
328                                 try
329                                 {
330                                         /* XXX: The lack of buffering here is NOT a bug, modules implementing this interface have to
331                                          * implement their own buffering mechanisms
332                                          */
333                                         this->GetIOHook()->OnRawSocketWrite(this->fd, outbuffer[0].c_str(), outbuffer[0].length());
334                                         outbuffer.pop_front();
335                                 }
336                                 catch (CoreException& modexcept)
337                                 {
338                                         ServerInstance->Logs->Log("SOCKET", DEBUG,"%s threw an exception: %s", modexcept.GetSource(), modexcept.GetReason());
339                                         return true;
340                                 }
341                         }
342                 }
343                 else
344                 {
345                         /* If we have multiple lines, try to send them all,
346                          * not just the first one -- Brain
347                          */
348                         while (outbuffer.size() && (errno != EAGAIN))
349                         {
350                                 /* Send a line */
351                                 int result = ServerInstance->SE->Send(this, outbuffer[0].c_str(), outbuffer[0].length(), 0);
352
353                                 if (result > 0)
354                                 {
355                                         if ((unsigned int)result >= outbuffer[0].length())
356                                         {
357                                                 /* The whole block was written (usually a line)
358                                                  * Pop the block off the front of the queue,
359                                                  * dont set errno, because we are clear of errors
360                                                  * and want to try and write the next block too.
361                                                  */
362                                                 outbuffer.pop_front();
363                                         }
364                                         else
365                                         {
366                                                 std::string temp = outbuffer[0].substr(result);
367                                                 outbuffer[0] = temp;
368                                                 /* We didnt get the whole line out. arses.
369                                                  * Try again next time, i guess. Set errno,
370                                                  * because we shouldnt be writing any more now,
371                                                  * until the socketengine says its safe to do so.
372                                                  */
373                                                 errno = EAGAIN;
374                                         }
375                                 }
376                                 else if (result == 0)
377                                 {
378                                         this->ServerInstance->SE->DelFd(this);
379                                         this->Close();
380                                         return true;
381                                 }
382                                 else if ((result == -1) && (errno != EAGAIN))
383                                 {
384                                         this->OnError(I_ERR_WRITE);
385                                         this->state = I_ERROR;
386                                         this->ServerInstance->SE->DelFd(this);
387                                         this->Close();
388                                         return true;
389                                 }
390                         }
391                 }
392         }
393
394         if ((errno == EAGAIN) && (fd > -1))
395         {
396                 this->ServerInstance->SE->WantWrite(this);
397         }
398
399         return (fd < 0);
400 }
401
402 void SocketTimeout::Tick(time_t)
403 {
404         ServerInstance->Logs->Log("SOCKET", DEBUG,"SocketTimeout::Tick");
405
406         if (ServerInstance->SE->GetRef(this->sfd) != this->sock)
407                 return;
408
409         if (this->sock->state == I_CONNECTING)
410         {
411                 // for connecting sockets, the timeout can occur
412                 // which causes termination of the connection after
413                 // the given number of seconds without a successful
414                 // connection.
415                 this->sock->OnTimeout();
416                 this->sock->OnError(I_ERR_TIMEOUT);
417
418                 /* NOTE: We must set this AFTER DelFd, as we added
419                  * this socket whilst writeable. This means that we
420                  * must DELETE the socket whilst writeable too!
421                  */
422                 this->sock->state = I_ERROR;
423
424                 if (ServerInstance->SocketCull.find(this->sock) == ServerInstance->SocketCull.end())
425                         ServerInstance->SocketCull[this->sock] = this->sock;
426         }
427
428         this->sock->Timeout = NULL;
429 }
430
431 bool BufferedSocket::InternalMarkConnected()
432 {
433         /* Our socket was in write-state, so delete it and re-add it
434          * in read-state.
435          */
436         this->SetState(I_CONNECTED);
437
438         if (this->GetIOHook())
439         {
440                 ServerInstance->Logs->Log("SOCKET",DEBUG,"Hook for raw connect");
441                 try
442                 {
443                         this->GetIOHook()->OnRawSocketConnect(this->fd);
444                 }
445                 catch (CoreException& modexcept)
446                 {
447                         ServerInstance->Logs->Log("SOCKET",DEBUG,"%s threw an exception: %s", modexcept.GetSource(), modexcept.GetReason());
448                         return false;
449                 }
450         }
451         return this->OnConnected();
452 }
453
454 void BufferedSocket::SetState(BufferedSocketState s)
455 {
456         this->state = s;
457 }
458
459 BufferedSocketState BufferedSocket::GetState()
460 {
461         return this->state;
462 }
463
464 bool BufferedSocket::OnConnected() { return true; }
465 void BufferedSocket::OnError(BufferedSocketError) { return; }
466 int BufferedSocket::OnDisconnect() { return 0; }
467 bool BufferedSocket::OnDataReady() { return true; }
468 bool BufferedSocket::OnWriteReady()
469 {
470         // Default behaviour: just try write some.
471         return !this->FlushWriteBuffer();
472 }
473 void BufferedSocket::OnTimeout() { return; }
474 void BufferedSocket::OnClose() { return; }
475
476 BufferedSocket::~BufferedSocket()
477 {
478         this->Close();
479         if (Timeout)
480         {
481                 ServerInstance->Timers->DelTimer(Timeout);
482                 Timeout = NULL;
483         }
484 }
485
486 void BufferedSocket::HandleEvent(EventType et, int errornum)
487 {
488         switch (et)
489         {
490                 case EVENT_ERROR:
491                 {
492                         switch (errornum)
493                         {
494                                 case ETIMEDOUT:
495                                         this->OnError(I_ERR_TIMEOUT);
496                                         break;
497                                 case ECONNREFUSED:
498                                 case 0:
499                                         this->OnError(this->state == I_CONNECTING ? I_ERR_CONNECT : I_ERR_WRITE);
500                                         break;
501                                 case EADDRINUSE:
502                                         this->OnError(I_ERR_BIND);
503                                         break;
504                                 case EPIPE:
505                                 case EIO:
506                                         this->OnError(I_ERR_WRITE);
507                                         break;
508                         }
509
510                         if (this->ServerInstance->SocketCull.find(this) == this->ServerInstance->SocketCull.end())
511                                 this->ServerInstance->SocketCull[this] = this;
512                         return;
513                         break;
514                 }
515                 case EVENT_READ:
516                 {
517                         if (!this->OnDataReady())
518                         {
519                                 if (this->ServerInstance->SocketCull.find(this) == this->ServerInstance->SocketCull.end())
520                                         this->ServerInstance->SocketCull[this] = this;
521                                 return;
522                         }
523                         break;
524                 }
525                 case EVENT_WRITE:
526                 {
527                         if (this->state == I_CONNECTING)
528                         {
529                                 if (!this->InternalMarkConnected())
530                                 {
531                                         if (this->ServerInstance->SocketCull.find(this) == this->ServerInstance->SocketCull.end())
532                                                 this->ServerInstance->SocketCull[this] = this;
533                                         return;
534                                 }
535                                 return;
536                         }
537                         else
538                         {
539                                 if (!this->OnWriteReady())
540                                 {
541                                         if (this->ServerInstance->SocketCull.find(this) == this->ServerInstance->SocketCull.end())
542                                                 this->ServerInstance->SocketCull[this] = this;
543                                         return;
544                                 }
545                         }
546                         break;
547                 }
548         }
549 }
550