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