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