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