]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/inspsocket.cpp
63bfee39e067b925220e13fd43bd6ffbebba430b
[user/henk/code/inspircd.git] / src / inspsocket.cpp
1 /*       +------------------------------------+
2  *       | Inspire Internet Relay Chat Daemon |
3  *       +------------------------------------+
4  *
5  *  InspIRCd is copyright (C) 2002-2006 ChatSpike-Dev.
6  *                       E-mail:
7  *                <brain@chatspike.net>
8  *                <Craig@chatspike.net>
9  *     
10  * Written by Craig Edwards, Craig McLure, and others.
11  * This program is free but copyrighted software; see
12  *            the file COPYING for details.
13  *
14  * ---------------------------------------------------
15  */
16
17 #include <string>
18 #include <sstream>
19 #include <iostream>
20 #include <fstream>
21 #include <stdexcept>
22 #include "inspircd_config.h"
23 #include "socket.h"
24 #include "configreader.h"
25 #include "inspstring.h"
26 #include "socketengine.h"
27 #include "inspircd.h"
28
29 using irc::sockets::OpenTCPSocket;
30 using irc::sockets::insp_inaddr;
31 using irc::sockets::insp_sockaddr;
32
33 bool InspSocket::Readable()
34 {
35         return ((this->state != I_CONNECTING) && (this->WaitingForWriteEvent == false));
36 }
37
38 InspSocket::InspSocket(InspIRCd* SI)
39 {
40         this->state = I_DISCONNECTED;
41         this->fd = -1;
42         this->WaitingForWriteEvent = false;
43         this->Instance = SI;
44 }
45
46 InspSocket::InspSocket(InspIRCd* SI, int newfd, const char* ip)
47 {
48         this->fd = newfd;
49         this->state = I_CONNECTED;
50         strlcpy(this->IP,ip,MAXBUF);
51         this->WaitingForWriteEvent = false;
52         this->Instance = SI;
53         if (this->fd > -1)
54                 this->Instance->SE->AddFd(this);
55 }
56
57 InspSocket::InspSocket(InspIRCd* SI, const std::string &ipaddr, int aport, bool listening, unsigned long maxtime)
58 {
59         this->fd = -1;
60         this->Instance = SI;
61         strlcpy(host,ipaddr.c_str(),MAXBUF);
62         this->WaitingForWriteEvent = false;
63         if (listening)
64         {
65                 if ((this->fd = OpenTCPSocket()) == ERROR)
66                 {
67                         this->fd = -1;
68                         this->state = I_ERROR;
69                         this->OnError(I_ERR_SOCKET);
70                         this->Instance->Log(DEBUG,"OpenTCPSocket() error");
71                         return;
72                 }
73                 else
74                 {
75                         if (!SI->BindSocket(this->fd,this->client,this->server,aport,(char*)ipaddr.c_str()))
76                         {
77                                 this->Instance->Log(DEBUG,"BindSocket() error %s",strerror(errno));
78                                 this->Close();
79                                 this->fd = -1;
80                                 this->state = I_ERROR;
81                                 this->OnError(I_ERR_BIND);
82                                 this->ClosePending = true;
83                                 return;
84                         }
85                         else
86                         {
87                                 this->state = I_LISTENING;
88                                 if (this->fd > -1)
89                                 {
90                                         if (!this->Instance->SE->AddFd(this))
91                                         {
92                                                 this->Close();
93                                                 this->state = I_ERROR;
94                                                 this->OnError(I_ERR_NOMOREFDS);
95                                         }
96                                 }
97                                 this->Instance->Log(DEBUG,"New socket now in I_LISTENING state");
98                                 return;
99                         }
100                 }                       
101         }
102         else
103         {
104                 strlcpy(this->host,ipaddr.c_str(),MAXBUF);
105                 this->port = aport;
106
107                 if (insp_aton(host,&addy) < 1)
108                 {
109                         this->Instance->Log(DEBUG,"You cannot pass hostnames to InspSocket, resolve them first with Resolver!");
110                         this->Close();
111                         this->fd = -1;
112                         this->state = I_ERROR;
113                         this->OnError(I_ERR_RESOLVE);
114                         return;
115                 }
116                 else
117                 {
118                         this->Instance->Log(DEBUG,"No need to resolve %s",this->host);
119                         strlcpy(this->IP,host,MAXBUF);
120                         timeout_val = maxtime;
121                         this->DoConnect();
122                 }
123         }
124 }
125
126 void InspSocket::WantWrite()
127 {
128         /** XXX:
129          * The socket engine may only have each FD in the list ONCE.
130          * This means we cant watch for write AND read at the same
131          * time. We have to remove the READ fd, to insert the WRITE
132          * fd. Once we receive our WRITE event (which WILL ARRIVE,
133          * pretty much gauranteed) we switch back to watching for
134          * READ events again.
135          *
136          * This behaviour may be fixed in a later version.
137          */
138         this->Instance->SE->DelFd(this);
139         this->WaitingForWriteEvent = true;
140         if (!this->Instance->SE->AddFd(this))
141         {
142                 this->Close();
143                 this->fd = -1;
144                 this->state = I_ERROR;
145                 this->OnError(I_ERR_NOMOREFDS);
146         }
147 }
148
149 void InspSocket::SetQueues(int nfd)
150 {
151         // attempt to increase socket sendq and recvq as high as its possible
152         int sendbuf = 32768;
153         int recvbuf = 32768;
154         setsockopt(nfd,SOL_SOCKET,SO_SNDBUF,(const void *)&sendbuf,sizeof(sendbuf));
155         setsockopt(nfd,SOL_SOCKET,SO_RCVBUF,(const void *)&recvbuf,sizeof(sendbuf));
156 }
157
158 /* Most irc servers require you to specify the ip you want to bind to.
159  * If you dont specify an IP, they rather dumbly bind to the first IP
160  * of the box (e.g. INADDR_ANY). In InspIRCd, we scan thought the IP
161  * addresses we've bound server ports to, and we try and bind our outbound
162  * connections to the first usable non-loopback and non-any IP we find.
163  * This is easier to configure when you have a lot of links and a lot
164  * of servers to configure.
165  */
166 bool InspSocket::BindAddr()
167 {
168         insp_inaddr n;
169         ConfigReader Conf(this->Instance);
170
171         this->Instance->Log(DEBUG,"In InspSocket::BindAddr()");
172         for (int j =0; j < Conf.Enumerate("bind"); j++)
173         {
174                 std::string Type = Conf.ReadValue("bind","type",j);
175                 std::string IP = Conf.ReadValue("bind","address",j);
176                 if (Type == "servers")
177                 {
178                         if ((IP != "*") && (IP != "127.0.0.1") && (IP != ""))
179                         {
180                                 insp_sockaddr s;
181
182                                 if (insp_aton(IP.c_str(),&n) > 0)
183                                 {
184                                         this->Instance->Log(DEBUG,"Found an IP to bind to: %s",IP.c_str());
185 #ifdef IPV6
186                                         s.sin6_addr = n;
187                                         s.sin6_family = AF_FAMILY;
188 #else
189                                         s.sin_addr = n;
190                                         s.sin_family = AF_FAMILY;
191 #endif
192                                         if (bind(this->fd,(struct sockaddr*)&s,sizeof(s)) < 0)
193                                         {
194                                                 this->Instance->Log(DEBUG,"Cant bind()");
195                                                 this->state = I_ERROR;
196                                                 this->OnError(I_ERR_BIND);
197                                                 this->fd = -1;
198                                                 return false;
199                                         }
200                                         this->Instance->Log(DEBUG,"bind() reports outbound fd bound to ip %s",IP.c_str());
201                                         return true;
202                                 }
203                                 else
204                                 {
205                                         this->Instance->Log(DEBUG,"Address '%s' was not an IP address",IP.c_str());
206                                 }
207                         }
208                 }
209         }
210         this->Instance->Log(DEBUG,"Found no suitable IPs to bind, binding INADDR_ANY");
211         return true;
212 }
213
214 bool InspSocket::DoConnect()
215 {
216         this->Instance->Log(DEBUG,"In DoConnect()");
217         if ((this->fd = socket(AF_FAMILY, SOCK_STREAM, 0)) == -1)
218         {
219                 this->Instance->Log(DEBUG,"Cant socket()");
220                 this->state = I_ERROR;
221                 this->OnError(I_ERR_SOCKET);
222                 return false;
223         }
224
225         if ((strstr(this->IP,"::ffff:") != (char*)&this->IP) && (strstr(this->IP,"::FFFF:") != (char*)&this->IP))
226         {
227                 if (!this->BindAddr())
228                         return false;
229         }
230
231         this->Instance->Log(DEBUG,"Part 2 DoConnect() %s",this->IP);
232         insp_aton(this->IP,&addy);
233 #ifdef IPV6
234         addr.sin6_family = AF_FAMILY;
235         memcpy(&addr.sin6_addr, &addy, sizeof(insp_inaddr));
236         addr.sin6_port = htons(this->port);
237 #else
238         addr.sin_family = AF_FAMILY;
239         addr.sin_addr = addy;
240         addr.sin_port = htons(this->port);
241 #endif
242
243         int flags;
244         flags = fcntl(this->fd, F_GETFL, 0);
245         fcntl(this->fd, F_SETFL, flags | O_NONBLOCK);
246
247         if (connect(this->fd, (sockaddr*)&this->addr,sizeof(this->addr)) == -1)
248         {
249                 if (errno != EINPROGRESS)
250                 {
251                         this->Instance->Log(DEBUG,"Error connect() %d: %s",this->fd,strerror(errno));
252                         this->OnError(I_ERR_CONNECT);
253                         this->Close();
254                         this->state = I_ERROR;
255                         return false;
256                 }
257
258                 this->Timeout = new SocketTimeout(this->GetFd(), this->Instance, this, timeout_val, this->Instance->Time());
259                 this->Instance->Timers->AddTimer(this->Timeout);
260         }
261         this->state = I_CONNECTING;
262         if (this->fd > -1)
263         {
264                 if (!this->Instance->SE->AddFd(this))
265                 {
266                         this->OnError(I_ERR_NOMOREFDS);
267                         this->Close();
268                         this->state = I_ERROR;
269                         return false;
270                 }
271                 this->SetQueues(this->fd);
272         }
273         this->Instance->Log(DEBUG,"Returning true from InspSocket::DoConnect");
274         return true;
275 }
276
277
278 void InspSocket::Close()
279 {
280         if (this->fd > -1)
281         {
282                 this->OnClose();
283                 shutdown(this->fd,2);
284                 close(this->fd);
285         }
286 }
287
288 std::string InspSocket::GetIP()
289 {
290         return this->IP;
291 }
292
293 char* InspSocket::Read()
294 {
295         if ((fd < 0) || (fd > MAX_DESCRIPTORS))
296                 return NULL;
297         int n = recv(this->fd,this->ibuf,sizeof(this->ibuf),0);
298         if ((n > 0) && (n <= (int)sizeof(this->ibuf)))
299         {
300                 ibuf[n] = 0;
301                 return ibuf;
302         }
303         else
304         {
305                 int err = errno;
306                 if (err == EAGAIN)
307                 {
308                         return "";
309                 }
310                 else
311                 {
312                         if (!n)
313                                 this->Instance->Log(DEBUG,"EOF or error on socket: EOF");
314                         else
315                                 this->Instance->Log(DEBUG,"EOF or error on socket: %s",strerror(err));
316                         return NULL;
317                 }
318         }
319 }
320
321 void InspSocket::MarkAsClosed()
322 {
323         this->Instance->Log(DEBUG,"Marked as closed");
324 }
325
326 // There are two possible outcomes to this function.
327 // It will either write all of the data, or an undefined amount.
328 // If an undefined amount is written the connection has failed
329 // and should be aborted.
330 int InspSocket::Write(const std::string &data)
331 {
332         /* Try and append the data to the back of the queue, and send it on its way
333          */
334         outbuffer.push_back(data);
335         return (!this->FlushWriteBuffer());
336 }
337
338 bool InspSocket::FlushWriteBuffer()
339 {
340         if ((this->fd > -1) && (this->state == I_CONNECTED))
341         {
342                 if (outbuffer.size())
343                 {
344                         int result = write(this->fd,outbuffer[0].c_str(),outbuffer[0].length());
345                         if (result > 0)
346                         {
347                                 if ((unsigned int)result == outbuffer[0].length())
348                                 {
349                                         /* The whole block was written (usually a line)
350                                          * Pop the block off the front of the queue
351                                          */
352                                         outbuffer.pop_front();
353                                 }
354                                 else
355                                 {
356                                         std::string temp = outbuffer[0].substr(result);
357                                         outbuffer[0] = temp;
358                                 }
359                         }
360                         else if ((result == -1) && (errno != EAGAIN))
361                         {
362                                 this->Instance->Log(DEBUG,"Write error on socket: %s",strerror(errno));
363                                 this->OnError(I_ERR_WRITE);
364                                 this->state = I_ERROR;
365                                 return true;
366                         }
367                 }
368         }
369         return (fd < 0);
370 }
371
372 void SocketTimeout::Tick(time_t now)
373 {
374         if (ServerInstance->SE->GetRef(this->sfd) != this->sock)
375         {
376                 ServerInstance->Log(DEBUG,"No FD or socket ref");
377                 return;
378         }
379
380         if (this->sock->state == I_CONNECTING)
381         {
382                 ServerInstance->Log(DEBUG,"Timed out, current=%lu",now);
383                 // for non-listening sockets, the timeout can occur
384                 // which causes termination of the connection after
385                 // the given number of seconds without a successful
386                 // connection.
387                 this->sock->OnTimeout();
388                 this->sock->OnError(I_ERR_TIMEOUT);
389                 this->sock->timeout = true;
390                 this->sock->state = I_ERROR;
391                 ServerInstance->SE->DelFd(this->sock);
392                 this->sock->Close();
393                 delete this->sock;
394                 return;
395         }
396         this->sock->FlushWriteBuffer();
397 }
398
399 bool InspSocket::Poll()
400 {
401         if (this->Instance->SE->GetRef(this->fd) != this)
402                 return false;
403
404         int incoming = -1;
405         bool n = true;
406
407         if ((fd < 0) || (fd > MAX_DESCRIPTORS))
408                 return false;
409
410         switch (this->state)
411         {
412                 case I_CONNECTING:
413                         this->Instance->Log(DEBUG,"State = I_CONNECTING");
414                         /* Our socket was in write-state, so delete it and re-add it
415                          * in read-state.
416                          */
417                         if (this->fd > -1)
418                         {
419                                 this->Instance->SE->DelFd(this);
420                                 this->SetState(I_CONNECTED);
421                                 if (!this->Instance->SE->AddFd(this))
422                                         return false;
423                         }
424                         return this->OnConnected();
425                 break;
426                 case I_LISTENING:
427                         length = sizeof (client);
428                         incoming = accept (this->fd, (sockaddr*)&client,&length);
429                         this->SetQueues(incoming);
430 #ifdef IPV6
431                         this->OnIncomingConnection(incoming,(char*)insp_ntoa(client.sin6_addr));
432 #else
433                         this->OnIncomingConnection(incoming,(char*)insp_ntoa(client.sin_addr));
434 #endif
435                         return true;
436                 break;
437                 case I_CONNECTED:
438
439                         if (this->WaitingForWriteEvent)
440                         {
441                                 /* Switch back to read events */
442                                 this->Instance->SE->DelFd(this);
443                                 this->WaitingForWriteEvent = false;
444                                 if (!this->Instance->SE->AddFd(this))
445                                         return false;
446
447                                 /* Trigger the write event */
448                                 n = this->OnWriteReady();
449                         }
450                         else
451                         {
452                                 /* Process the read event */
453                                 n = this->OnDataReady();
454                         }
455                         /* Flush any pending, but not till after theyre done with the event
456                          * so there are less write calls involved.
457                          * Both FlushWriteBuffer AND the return result of OnDataReady must
458                          * return true for this to be ok.
459                          */
460                         if (this->FlushWriteBuffer())
461                                 return false;
462                         return n;
463                 break;
464                 default:
465                 break;
466         }
467         return true;
468 }
469
470 void InspSocket::SetState(InspSocketState s)
471 {
472         this->Instance->Log(DEBUG,"Socket state change");
473         this->state = s;
474 }
475
476 InspSocketState InspSocket::GetState()
477 {
478         return this->state;
479 }
480
481 int InspSocket::GetFd()
482 {
483         return this->fd;
484 }
485
486 bool InspSocket::OnConnected() { return true; }
487 void InspSocket::OnError(InspSocketError e) { return; }
488 int InspSocket::OnDisconnect() { return 0; }
489 int InspSocket::OnIncomingConnection(int newfd, char* ip) { return 0; }
490 bool InspSocket::OnDataReady() { return true; }
491 bool InspSocket::OnWriteReady() { return true; }
492 void InspSocket::OnTimeout() { return; }
493 void InspSocket::OnClose() { return; }
494
495 InspSocket::~InspSocket()
496 {
497         this->Close();
498 }
499
500 void InspSocket::HandleEvent(EventType et)
501 {
502         if (!this->Poll())
503         {
504                 this->Instance->SE->DelFd(this);
505                 this->Close();
506                 delete this;
507         }
508 }
509