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