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