]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/socket.cpp
(TEST CODE) remote ping, do not use until debugged
[user/henk/code/inspircd.git] / src / socket.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 using namespace std;
18
19 #include "inspircd_config.h"
20 #include <sys/time.h>
21 #include <sys/resource.h>
22 #include <sys/types.h>
23 #include <sys/socket.h>
24 #include <netinet/in.h>
25 #include <string>
26 #include <unistd.h>
27 #include <fcntl.h>
28 #include <poll.h>
29 #include <sstream>
30 #include <iostream>
31 #include <fstream>
32 #include "socket.h"
33 #include "inspircd.h"
34 #include "inspircd_io.h"
35 #include "inspstring.h"
36 #include "helperfuncs.h"
37 #include "socketengine.h"
38
39
40 extern InspIRCd* ServerInstance;
41 extern ServerConfig* Config;
42 extern time_t TIME;
43
44 InspSocket* socket_ref[MAX_DESCRIPTORS];
45
46 InspSocket::InspSocket()
47 {
48         this->state = I_DISCONNECTED;
49 }
50
51 InspSocket::InspSocket(int newfd, char* ip)
52 {
53         this->fd = newfd;
54         this->state = I_CONNECTED;
55         this->IP = ip;
56         ServerInstance->SE->AddFd(this->fd,true,X_ESTAB_MODULE);
57         socket_ref[this->fd] = this;
58 }
59
60 InspSocket::InspSocket(std::string host, int port, bool listening, unsigned long maxtime)
61 {
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                         log(DEBUG,"OpenTCPSocket() error");
69                         return;
70                 }
71                 else
72                 {
73                         if (BindSocket(this->fd,this->client,this->server,port,(char*)host.c_str()) == ERROR)
74                         {
75                                 this->Close();
76                                 this->fd = -1;
77                                 this->state = I_ERROR;
78                                 this->OnError(I_ERR_BIND);
79                                 log(DEBUG,"BindSocket() error %s",strerror(errno));
80                                 return;
81                         }
82                         else
83                         {
84                                 this->state = I_LISTENING;
85                                 ServerInstance->SE->AddFd(this->fd,true,X_ESTAB_MODULE);
86                                 socket_ref[this->fd] = this;
87                                 log(DEBUG,"New socket now in I_LISTENING state");
88                                 return;
89                         }
90                 }                       
91         }
92         else
93         {
94                 this->host = host;
95                 this->port = port;
96
97                 if (!inet_aton(host.c_str(),&addy))
98                 {
99                         log(DEBUG,"Attempting to resolve %s",this->host.c_str());
100                         /* Its not an ip, spawn the resolver */
101                         this->dns.SetNS(std::string(Config->DNSServer));
102                         this->dns.ForwardLookupWithFD(host,fd);
103                         timeout_end = time(NULL)+maxtime;
104                         timeout = false;
105                         this->state = I_RESOLVING;
106                         socket_ref[this->fd] = this;
107                 }
108                 else
109                 {
110                         log(DEBUG,"No need to resolve %s",this->host.c_str());
111                         this->IP = host;
112                         this->DoConnect();
113                 }
114         }
115 }
116
117 void InspSocket::SetQueues(int nfd)
118 {
119         // attempt to increase socket sendq and recvq as high as its possible
120         int sendbuf = 32768;
121         int recvbuf = 32768;
122         setsockopt(nfd,SOL_SOCKET,SO_SNDBUF,(const void *)&sendbuf,sizeof(sendbuf));
123         setsockopt(nfd,SOL_SOCKET,SO_RCVBUF,(const void *)&recvbuf,sizeof(sendbuf));
124 }
125
126 bool InspSocket::DoResolve()
127 {
128         log(DEBUG,"In DoResolve(), trying to resolve IP");
129         if (this->dns.HasResult())
130         {
131                 log(DEBUG,"Socket has result");
132                 std::string res_ip = dns.GetResultIP();
133                 if (res_ip != "")
134                 {
135                         log(DEBUG,"Socket result set to %s",res_ip.c_str());
136                         this->IP = res_ip;
137                         socket_ref[this->fd] = NULL;
138                 }
139                 else
140                 {
141                         log(DEBUG,"Socket DNS failure");
142                         this->Close();
143                         this->state = I_ERROR;
144                         this->OnError(I_ERR_RESOLVE);
145                         return false;
146                 }
147                 return this->DoConnect();
148         }
149         log(DEBUG,"No result for socket yet!");
150         return true;
151 }
152
153 bool InspSocket::DoConnect()
154 {
155         log(DEBUG,"In DoConnect()");
156         if ((this->fd = socket(AF_INET, SOCK_STREAM, 0)) == -1)
157         {
158                 log(DEBUG,"Cant socket()");
159                 this->state = I_ERROR;
160                 this->OnError(I_ERR_SOCKET);
161                 return false;
162         }
163
164         log(DEBUG,"Part 2 DoConnect() %s",this->IP.c_str());
165         inet_aton(this->IP.c_str(),&addy);
166         addr.sin_family = AF_INET;
167         addr.sin_addr = addy;
168         addr.sin_port = htons(this->port);
169
170         int flags;
171         flags = fcntl(this->fd, F_GETFL, 0);
172         fcntl(this->fd, F_SETFL, flags | O_NONBLOCK);
173
174         if(connect(this->fd, (sockaddr*)&this->addr,sizeof(this->addr)) == -1)
175         {
176                 if (errno != EINPROGRESS)
177                 {
178                         log(DEBUG,"Error connect() %d: %s",this->fd,strerror(errno));
179                         this->OnError(I_ERR_CONNECT);
180                         this->state = I_ERROR;
181                         this->Close();
182                         return false;
183                 }
184         }
185         this->state = I_CONNECTING;
186         ServerInstance->SE->AddFd(this->fd,false,X_ESTAB_MODULE);
187         socket_ref[this->fd] = this;
188         this->SetQueues(this->fd);
189         return true;
190 }
191
192
193 void InspSocket::Close()
194 {
195         if (this->fd != -1)
196         {
197                 this->OnClose();
198                 shutdown(this->fd,2);
199                 close(this->fd);
200                 socket_ref[this->fd] = NULL;
201                 this->fd = -1;
202         }
203 }
204
205 std::string InspSocket::GetIP()
206 {
207         return this->IP;
208 }
209
210 char* InspSocket::Read()
211 {
212         int n = recv(this->fd,this->ibuf,sizeof(this->ibuf),0);
213         if (n > 0)
214         {
215                 ibuf[n] = 0;
216                 return ibuf;
217         }
218         else
219         {
220                 if (n == EAGAIN)
221                 {
222                         return "";
223                 }
224                 else
225                 {
226                         log(DEBUG,"EOF or error on socket");
227                         return NULL;
228                 }
229         }
230 }
231
232 // There are two possible outcomes to this function.
233 // It will either write all of the data, or an undefined amount.
234 // If an undefined amount is written the connection has failed
235 // and should be aborted.
236 int InspSocket::Write(std::string data)
237 {
238         this->Buffer.append(data);
239         return data.length();
240 }
241
242 void InspSocket::FlushWriteBuffer()
243 {
244         int result = 0;
245         if (this->Buffer.length())
246         {
247                 result = send(this->fd,this->Buffer.c_str(),this->Buffer.length(),0);
248                 if (result > 0)
249                 {
250                         if (result == (int)this->Buffer.length())
251                         {
252                                 this->Buffer = "";
253                         }
254                         else
255                         {
256                                 /* If we wrote some, advance the buffer forwards */
257                                 char* n = (char*)this->Buffer.c_str();
258                                 n += result;
259                                 this->Buffer = n;
260                         }
261                 }
262         }
263 }
264
265 bool InspSocket::Timeout(time_t current)
266 {
267         if (((this->state == I_RESOLVING) || (this->state == I_CONNECTING)) && (current > timeout_end))
268         {
269                 // for non-listening sockets, the timeout can occur
270                 // which causes termination of the connection after
271                 // the given number of seconds without a successful
272                 // connection.
273                 this->OnTimeout();
274                 this->OnError(I_ERR_TIMEOUT);
275                 timeout = true;
276                 this->state = I_ERROR;
277                 return true;
278         }
279         this->FlushWriteBuffer();
280         return false;
281 }
282
283 bool InspSocket::Poll()
284 {
285         int incoming = -1;
286         bool n = true;
287         
288         switch (this->state)
289         {
290                 case I_RESOLVING:
291                         log(DEBUG,"State = I_RESOLVING, calling DoResolve()");
292                         return this->DoResolve();
293                 break;
294                 case I_CONNECTING:
295                         log(DEBUG,"State = I_CONNECTED");
296                         this->SetState(I_CONNECTED);
297                         /* Our socket was in write-state, so delete it and re-add it
298                          * in read-state.
299                          */
300                         ServerInstance->SE->DelFd(this->fd);
301                         ServerInstance->SE->AddFd(this->fd,true,X_ESTAB_MODULE);
302                         return this->OnConnected();
303                 break;
304                 case I_LISTENING:
305                         length = sizeof (client);
306                         incoming = accept (this->fd, (sockaddr*)&client,&length);
307                         this->SetQueues(incoming);
308                         this->OnIncomingConnection(incoming,inet_ntoa(client.sin_addr));
309                         return true;
310                 break;
311                 case I_CONNECTED:
312                         n = this->OnDataReady();
313                         /* Flush any pending, but not till after theyre done with the event
314                          * so there are less write calls involved. */
315                         this->FlushWriteBuffer();
316                         return n;
317                 break;
318                 default:
319                 break;
320         }
321         return true;
322 }
323
324 void InspSocket::SetState(InspSocketState s)
325 {
326         log(DEBUG,"Socket state change");
327         this->state = s;
328 }
329
330 InspSocketState InspSocket::GetState()
331 {
332         return this->state;
333 }
334
335 int InspSocket::GetFd()
336 {
337         return this->fd;
338 }
339
340 bool InspSocket::OnConnected() { return true; }
341 void InspSocket::OnError(InspSocketError e) { return; }
342 int InspSocket::OnDisconnect() { return 0; }
343 int InspSocket::OnIncomingConnection(int newfd, char* ip) { return 0; }
344 bool InspSocket::OnDataReady() { return true; }
345 void InspSocket::OnTimeout() { return; }
346 void InspSocket::OnClose() { return; }
347
348 InspSocket::~InspSocket()
349 {
350         this->Close();
351 }
352