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