]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/socket.cpp
That's enough tweaks for now
[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 <stdexcept>
33 #include "socket.h"
34 #include "inspircd.h"
35 #include "inspircd_io.h"
36 #include "inspstring.h"
37 #include "helperfuncs.h"
38 #include "socketengine.h"
39
40
41 extern InspIRCd* ServerInstance;
42 extern ServerConfig* Config;
43 extern time_t TIME;
44
45 InspSocket* socket_ref[MAX_DESCRIPTORS];
46
47 InspSocket::InspSocket()
48 {
49         this->state = I_DISCONNECTED;
50         this->fd = -1;
51 }
52
53 InspSocket::InspSocket(int newfd, char* ip)
54 {
55         this->fd = newfd;
56         this->state = I_CONNECTED;
57         this->IP = ip;
58         ServerInstance->SE->AddFd(this->fd,true,X_ESTAB_MODULE);
59         socket_ref[this->fd] = this;
60 }
61
62 InspSocket::InspSocket(std::string ahost, int aport, bool listening, unsigned long maxtime)
63 {
64         this->fd = -1;
65         this->host = ahost;
66         this->Buffer = "";
67         if (listening) {
68                 if ((this->fd = OpenTCPSocket()) == ERROR)
69                 {
70                         this->fd = -1;
71                         this->state = I_ERROR;
72                         this->OnError(I_ERR_SOCKET);
73                         log(DEBUG,"OpenTCPSocket() error");
74                         return;
75                 }
76                 else
77                 {
78                         if (BindSocket(this->fd,this->client,this->server,aport,(char*)ahost.c_str()) == ERROR)
79                         {
80                                 this->Close();
81                                 this->fd = -1;
82                                 this->state = I_ERROR;
83                                 this->OnError(I_ERR_BIND);
84                                 log(DEBUG,"BindSocket() error %s",strerror(errno));
85                                 return;
86                         }
87                         else
88                         {
89                                 this->state = I_LISTENING;
90                                 ServerInstance->SE->AddFd(this->fd,true,X_ESTAB_MODULE);
91                                 socket_ref[this->fd] = this;
92                                 log(DEBUG,"New socket now in I_LISTENING state");
93                                 return;
94                         }
95                 }                       
96         }
97         else
98         {
99                 this->host = ahost;
100                 this->port = aport;
101
102                 if (!inet_aton(host.c_str(),&addy))
103                 {
104                         log(DEBUG,"Attempting to resolve %s",this->host.c_str());
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.c_str());
116                         this->IP = host;
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                         this->IP = res_ip;
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                         return false;
152                 }
153                 return this->DoConnect();
154         }
155         log(DEBUG,"No result for socket yet!");
156         return true;
157 }
158
159 bool InspSocket::DoConnect()
160 {
161         log(DEBUG,"In DoConnect()");
162         if ((this->fd = socket(AF_INET, SOCK_STREAM, 0)) == -1)
163         {
164                 log(DEBUG,"Cant socket()");
165                 this->state = I_ERROR;
166                 this->OnError(I_ERR_SOCKET);
167                 return false;
168         }
169
170         log(DEBUG,"Part 2 DoConnect() %s",this->IP.c_str());
171         inet_aton(this->IP.c_str(),&addy);
172         addr.sin_family = AF_INET;
173         addr.sin_addr = addy;
174         addr.sin_port = htons(this->port);
175
176         int flags;
177         flags = fcntl(this->fd, F_GETFL, 0);
178         fcntl(this->fd, F_SETFL, flags | O_NONBLOCK);
179
180         if (connect(this->fd, (sockaddr*)&this->addr,sizeof(this->addr)) == -1)
181         {
182                 if (errno != EINPROGRESS)
183                 {
184                         log(DEBUG,"Error connect() %d: %s",this->fd,strerror(errno));
185                         this->OnError(I_ERR_CONNECT);
186                         this->state = I_ERROR;
187                         this->Close();
188                         return false;
189                 }
190         }
191         this->state = I_CONNECTING;
192         ServerInstance->SE->AddFd(this->fd,false,X_ESTAB_MODULE);
193         socket_ref[this->fd] = this;
194         this->SetQueues(this->fd);
195         log(DEBUG,"Returning true from InspSocket::DoConnect");
196         return true;
197 }
198
199
200 void InspSocket::Close()
201 {
202         if (this->fd != -1)
203         {
204                 this->OnClose();
205                 shutdown(this->fd,2);
206                 close(this->fd);
207                 socket_ref[this->fd] = NULL;
208                 this->fd = -1;
209         }
210 }
211
212 std::string InspSocket::GetIP()
213 {
214         return this->IP;
215 }
216
217 char* InspSocket::Read()
218 {
219         if ((fd < 0) || (fd > MAX_DESCRIPTORS))
220                 return NULL;
221         int n = recv(this->fd,this->ibuf,sizeof(this->ibuf),0);
222         if ((n > 0) && (n <= (int)sizeof(this->ibuf)))
223         {
224                 ibuf[n] = 0;
225                 return ibuf;
226         }
227         else
228         {
229                 if (errno == EAGAIN)
230                 {
231                         return "";
232                 }
233                 else
234                 {
235                         log(DEBUG,"EOF or error on socket");
236                         return NULL;
237                 }
238         }
239 }
240
241 // There are two possible outcomes to this function.
242 // It will either write all of the data, or an undefined amount.
243 // If an undefined amount is written the connection has failed
244 // and should be aborted.
245 int InspSocket::Write(std::string data)
246 {
247         try
248         {
249                 if ((data != "") && (this->Buffer.length() + data.length() < this->Buffer.max_size()))
250                         this->Buffer.append(data);
251         }
252         catch (std::length_error)
253         {
254                 log(DEBUG,"std::length_error exception caught while appending to socket buffer!");
255                 return 0;
256         }
257         return data.length();
258 }
259
260 void InspSocket::FlushWriteBuffer()
261 {
262         if ((this->fd > -1) && (this->state == I_CONNECTED))
263         {
264                 int result = 0, v = 0;
265                 const char* n = Buffer.c_str();
266                 v = Buffer.length();
267                 if (v > 0)
268                 {
269                         result = write(this->fd,n,v);
270                         if (result > 0)
271                         {
272                                 if (result == v)
273                                 {
274                                         Buffer = "";
275                                 }
276                                 else
277                                 {
278                                         /* If we wrote some, advance the buffer forwards */
279                                         n += result;
280                                         Buffer = n;
281                                 }
282                         }
283                 }
284         }
285 }
286
287 bool InspSocket::Timeout(time_t current)
288 {
289         if (((this->state == I_RESOLVING) || (this->state == I_CONNECTING)) && (current > timeout_end))
290         {
291                 log(DEBUG,"Timed out, current=%lu timeout_end=%lu");
292                 // for non-listening sockets, the timeout can occur
293                 // which causes termination of the connection after
294                 // the given number of seconds without a successful
295                 // connection.
296                 this->OnTimeout();
297                 this->OnError(I_ERR_TIMEOUT);
298                 timeout = true;
299                 this->state = I_ERROR;
300                 return true;
301         }
302         this->FlushWriteBuffer();
303         return false;
304 }
305
306 bool InspSocket::Poll()
307 {
308         int incoming = -1;
309         bool n = true;
310
311         switch (this->state)
312         {
313                 case I_RESOLVING:
314                         log(DEBUG,"State = I_RESOLVING, calling DoResolve()");
315                         return this->DoResolve();
316                 break;
317                 case I_CONNECTING:
318                         log(DEBUG,"State = I_CONNECTING");
319                         this->SetState(I_CONNECTED);
320                         /* Our socket was in write-state, so delete it and re-add it
321                          * in read-state.
322                          */
323                         ServerInstance->SE->DelFd(this->fd);
324                         ServerInstance->SE->AddFd(this->fd,true,X_ESTAB_MODULE);
325                         return this->OnConnected();
326                 break;
327                 case I_LISTENING:
328                         length = sizeof (client);
329                         incoming = accept (this->fd, (sockaddr*)&client,&length);
330                         this->SetQueues(incoming);
331                         this->OnIncomingConnection(incoming,inet_ntoa(client.sin_addr));
332                         return true;
333                 break;
334                 case I_CONNECTED:
335                         n = this->OnDataReady();
336                         /* Flush any pending, but not till after theyre done with the event
337                          * so there are less write calls involved. */
338                         this->FlushWriteBuffer();
339                         return n;
340                 break;
341                 default:
342                 break;
343         }
344         return true;
345 }
346
347 void InspSocket::SetState(InspSocketState s)
348 {
349         log(DEBUG,"Socket state change");
350         this->state = s;
351 }
352
353 InspSocketState InspSocket::GetState()
354 {
355         return this->state;
356 }
357
358 int InspSocket::GetFd()
359 {
360         return this->fd;
361 }
362
363 bool InspSocket::OnConnected() { return true; }
364 void InspSocket::OnError(InspSocketError e) { return; }
365 int InspSocket::OnDisconnect() { return 0; }
366 int InspSocket::OnIncomingConnection(int newfd, char* ip) { return 0; }
367 bool InspSocket::OnDataReady() { return true; }
368 void InspSocket::OnTimeout() { return; }
369 void InspSocket::OnClose() { return; }
370
371 InspSocket::~InspSocket()
372 {
373         this->Close();
374 }
375