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