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