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