]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/inspsocket.cpp
651a02b71d550da6e734eb6573675b6f55acabb4
[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, 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                                 this->Close();
77                                 this->fd = -1;
78                                 this->state = I_ERROR;
79                                 this->OnError(I_ERR_BIND);
80                                 this->ClosePending = true;
81                                 log(DEBUG,"BindSocket() error %s",strerror(errno));
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 (!inet_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::SetQueues(int nfd)
124 {
125         // attempt to increase socket sendq and recvq as high as its possible
126         int sendbuf = 32768;
127         int recvbuf = 32768;
128         setsockopt(nfd,SOL_SOCKET,SO_SNDBUF,(const void *)&sendbuf,sizeof(sendbuf));
129         setsockopt(nfd,SOL_SOCKET,SO_RCVBUF,(const void *)&recvbuf,sizeof(sendbuf));
130 }
131
132 bool InspSocket::DoResolve()
133 {
134         log(DEBUG,"In DoResolve(), trying to resolve IP");
135         if (this->dns.HasResult())
136         {
137                 log(DEBUG,"Socket has result");
138                 std::string res_ip = dns.GetResultIP();
139                 if (res_ip != "")
140                 {
141                         log(DEBUG,"Socket result set to %s",res_ip.c_str());
142                         strlcpy(this->IP,res_ip.c_str(),MAXBUF);
143                         socket_ref[this->fd] = NULL;
144                 }
145                 else
146                 {
147                         log(DEBUG,"Socket DNS failure");
148                         this->Close();
149                         this->state = I_ERROR;
150                         this->OnError(I_ERR_RESOLVE);
151                         this->fd = -1;
152                         this->ClosePending = true;
153                         return false;
154                 }
155                 return this->DoConnect();
156         }
157         log(DEBUG,"No result for socket yet!");
158         return true;
159 }
160
161 /* Most irc servers require you to specify the ip you want to bind to.
162  * If you dont specify an IP, they rather dumbly bind to the first IP
163  * of the box (e.g. INADDR_ANY). In InspIRCd, we scan thought the IP
164  * addresses we've bound server ports to, and we try and bind our outbound
165  * connections to the first usable non-loopback and non-any IP we find.
166  * This is easier to configure when you have a lot of links and a lot
167  * of servers to configure.
168  */
169 bool InspSocket::BindAddr()
170 {
171         insp_inaddr n;
172         ConfigReader Conf;
173
174         log(DEBUG,"In InspSocket::BindAddr()");
175         for (int j =0; j < Conf.Enumerate("bind"); j++)
176         {
177                 std::string Type = Conf.ReadValue("bind","type",j);
178                 std::string IP = Conf.ReadValue("bind","address",j);
179                 if (Type == "servers")
180                 {
181                         if ((IP != "*") && (IP != "127.0.0.1") && (IP != ""))
182                         {
183                                 insp_sockaddr s;
184                                 char resolved_addr[MAXBUF];
185                                 
186                                 if (!inet_aton(IP.c_str(),&n))
187                                 {
188                                         /* If they gave a hostname, bind to the IP it resolves to */
189                                         log(DEBUG,"Resolving host %s",IP.c_str());
190                                         if (CleanAndResolve(resolved_addr, IP.c_str(), true))
191                                         {
192                                                 log(DEBUG,"Resolved host %s to %s",IP.c_str(),resolved_addr);
193                                                 IP = resolved_addr;
194                                         }
195                                 }
196
197                                 if (inet_aton(IP.c_str(),&n))
198                                 {
199                                         log(DEBUG,"Found an IP to bind to: %s",IP.c_str());
200                                         s.sin_addr = n;
201                                         s.sin_family = AF_INET;
202                                         if (bind(this->fd,(struct sockaddr*)&s,sizeof(s)) < 0)
203                                         {
204                                                 log(DEBUG,"Cant bind()");
205                                                 this->state = I_ERROR;
206                                                 this->OnError(I_ERR_BIND);
207                                                 this->fd = -1;
208                                                 return false;
209                                         }
210                                         log(DEBUG,"bind() reports outbound fd bound to ip %s",IP.c_str());
211                                         return true;
212                                 }
213                                 else
214                                 {
215                                         log(DEBUG,"Address '%s' was not an IP address",IP.c_str());
216                                 }
217                         }
218                 }
219         }
220         log(DEBUG,"Found no suitable IPs to bind, binding INADDR_ANY");
221         return true;
222 }
223
224 bool InspSocket::DoConnect()
225 {
226         log(DEBUG,"In DoConnect()");
227         if ((this->fd = socket(AF_INET, SOCK_STREAM, 0)) == -1)
228         {
229                 log(DEBUG,"Cant socket()");
230                 this->state = I_ERROR;
231                 this->OnError(I_ERR_SOCKET);
232                 this->fd = -1;
233                 return false;
234         }
235
236         if (!this->BindAddr())
237                 return false;
238
239         log(DEBUG,"Part 2 DoConnect() %s",this->IP);
240         inet_aton(this->IP,&addy);
241         addr.sin_family = AF_INET;
242         addr.sin_addr = addy;
243         addr.sin_port = htons(this->port);
244
245         int flags;
246         flags = fcntl(this->fd, F_GETFL, 0);
247         fcntl(this->fd, F_SETFL, flags | O_NONBLOCK);
248
249         if (connect(this->fd, (sockaddr*)&this->addr,sizeof(this->addr)) == -1)
250         {
251                 if (errno != EINPROGRESS)
252                 {
253                         log(DEBUG,"Error connect() %d: %s",this->fd,strerror(errno));
254                         this->OnError(I_ERR_CONNECT);
255                         this->Close();
256                         this->state = I_ERROR;
257                         this->fd = -1;
258                         this->ClosePending = true;
259                         return false;
260                 }
261         }
262         this->state = I_CONNECTING;
263         if (this->fd > -1)
264         {
265                 ServerInstance->SE->AddFd(this->fd,false,X_ESTAB_MODULE);
266                 socket_ref[this->fd] = this;
267                 this->SetQueues(this->fd);
268         }
269         log(DEBUG,"Returning true from InspSocket::DoConnect");
270         return true;
271 }
272
273
274 void InspSocket::Close()
275 {
276         if (this->fd != -1)
277         {
278                 this->OnClose();
279                 shutdown(this->fd,2);
280                 close(this->fd);
281                 socket_ref[this->fd] = NULL;
282                 this->ClosePending = true;
283                 this->fd = -1;
284         }
285 }
286
287 std::string InspSocket::GetIP()
288 {
289         return this->IP;
290 }
291
292 char* InspSocket::Read()
293 {
294         if ((fd < 0) || (fd > MAX_DESCRIPTORS))
295                 return NULL;
296         int n = recv(this->fd,this->ibuf,sizeof(this->ibuf),0);
297         if ((n > 0) && (n <= (int)sizeof(this->ibuf)))
298         {
299                 ibuf[n] = 0;
300                 return ibuf;
301         }
302         else
303         {
304                 if (errno == EAGAIN)
305                 {
306                         return "";
307                 }
308                 else
309                 {
310                         log(DEBUG,"EOF or error on socket: %s",strerror(errno));
311                         return NULL;
312                 }
313         }
314 }
315
316 void InspSocket::MarkAsClosed()
317 {
318         log(DEBUG,"Marked as closed");
319         this->ClosePending = true;
320 }
321
322 // There are two possible outcomes to this function.
323 // It will either write all of the data, or an undefined amount.
324 // If an undefined amount is written the connection has failed
325 // and should be aborted.
326 int InspSocket::Write(const std::string &data)
327 {
328         if (this->ClosePending)
329                 return false;
330
331         /*int result = write(this->fd,data.c_str(),data.length());
332         if (result < 1)
333                 return false;
334         return true;*/
335
336         /* Try and append the data to the back of the queue, and send it on its way
337          */
338         outbuffer.push_back(data);
339         return (!this->FlushWriteBuffer());
340 }
341
342 bool InspSocket::FlushWriteBuffer()
343 {
344         if (this->ClosePending)
345                 return true;
346
347         if ((this->fd > -1) && (this->state == I_CONNECTED))
348         {
349                 if (outbuffer.size())
350                 {
351                         int result = write(this->fd,outbuffer[0].c_str(),outbuffer[0].length());
352                         if (result > 0)
353                         {
354                                 if ((unsigned int)result == outbuffer[0].length())
355                                 {
356                                         /* The whole block was written (usually a line)
357                                          * Pop the block off the front of the queue
358                                          */
359                                         outbuffer.pop_front();
360                                 }
361                                 else
362                                 {
363                                         std::string temp = outbuffer[0].substr(result);
364                                         outbuffer[0] = temp;
365                                 }
366                         }
367                         else if ((result == -1) && (errno != EAGAIN))
368                         {
369                                 log(DEBUG,"Write error on socket: %s",strerror(errno));
370                                 this->OnError(I_ERR_WRITE);
371                                 this->state = I_ERROR;
372                                 this->ClosePending = true;
373                                 return true;
374                         }
375                 }
376         }
377         return (fd < 0);
378 }
379
380 bool InspSocket::Timeout(time_t current)
381 {
382         if (!socket_ref[this->fd] || !ServerInstance->SE->HasFd(this->fd))
383         {
384                 log(DEBUG,"No FD or socket ref");
385                 return false;
386         }
387
388         if (this->ClosePending)
389         {
390                 log(DEBUG,"Close is pending");
391                 return true;
392         }
393
394         if (((this->state == I_RESOLVING) || (this->state == I_CONNECTING)) && (current > timeout_end))
395         {
396                 log(DEBUG,"Timed out, current=%lu timeout_end=%lu");
397                 // for non-listening sockets, the timeout can occur
398                 // which causes termination of the connection after
399                 // the given number of seconds without a successful
400                 // connection.
401                 this->OnTimeout();
402                 this->OnError(I_ERR_TIMEOUT);
403                 timeout = true;
404                 this->state = I_ERROR;
405                 this->ClosePending = true;
406                 return true;
407         }
408         return this->FlushWriteBuffer();
409 }
410
411 bool InspSocket::Poll()
412 {
413         if (!socket_ref[this->fd] || !ServerInstance->SE->HasFd(this->fd))
414                 return false;
415
416         int incoming = -1;
417         bool n = true;
418
419         if ((fd < 0) || (fd > MAX_DESCRIPTORS) || (this->ClosePending))
420                 return false;
421
422         switch (this->state)
423         {
424                 case I_RESOLVING:
425                         log(DEBUG,"State = I_RESOLVING, calling DoResolve()");
426                         return this->DoResolve();
427                 break;
428                 case I_CONNECTING:
429                         log(DEBUG,"State = I_CONNECTING");
430                         this->SetState(I_CONNECTED);
431                         /* Our socket was in write-state, so delete it and re-add it
432                          * in read-state.
433                          */
434                         if (this->fd > -1)
435                         {
436                                 ServerInstance->SE->DelFd(this->fd);
437                                 ServerInstance->SE->AddFd(this->fd,true,X_ESTAB_MODULE);
438                         }
439                         return this->OnConnected();
440                 break;
441                 case I_LISTENING:
442                         length = sizeof (client);
443                         incoming = accept (this->fd, (sockaddr*)&client,&length);
444                         this->SetQueues(incoming);
445                         this->OnIncomingConnection(incoming,inet_ntoa(client.sin_addr));
446                         return true;
447                 break;
448                 case I_CONNECTED:
449                         n = this->OnDataReady();
450                         /* Flush any pending, but not till after theyre done with the event
451                          * so there are less write calls involved.
452                          * Both FlushWriteBuffer AND the return result of OnDataReady must
453                          * return true for this to be ok.
454                          */
455                         if (this->FlushWriteBuffer())
456                                 return false;
457                         return n;
458                 break;
459                 default:
460                 break;
461         }
462         return true;
463 }
464
465 void InspSocket::SetState(InspSocketState s)
466 {
467         log(DEBUG,"Socket state change");
468         this->state = s;
469 }
470
471 InspSocketState InspSocket::GetState()
472 {
473         return this->state;
474 }
475
476 int InspSocket::GetFd()
477 {
478         return this->fd;
479 }
480
481 bool InspSocket::OnConnected() { return true; }
482 void InspSocket::OnError(InspSocketError e) { return; }
483 int InspSocket::OnDisconnect() { return 0; }
484 int InspSocket::OnIncomingConnection(int newfd, char* ip) { return 0; }
485 bool InspSocket::OnDataReady() { return true; }
486 void InspSocket::OnTimeout() { return; }
487 void InspSocket::OnClose() { return; }
488
489 InspSocket::~InspSocket()
490 {
491         this->Close();
492 }