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