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