]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/inspsocket.cpp
99ef731c614579a341f858fb53b03e3921bb6a49
[user/henk/code/inspircd.git] / src / inspsocket.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 #include <string>
18 #include <sstream>
19 #include <iostream>
20 #include <fstream>
21 #include <stdexcept>
22 #include "inspircd_config.h"
23 #include "socket.h"
24 #include "inspircd.h"
25 #include "configreader.h"
26 #include "inspstring.h"
27 #include "helperfuncs.h"
28 #include "socketengine.h"
29 #include "message.h"
30
31
32 extern InspIRCd* ServerInstance;
33 extern ServerConfig* Config;
34 extern time_t TIME;
35
36 InspSocket* socket_ref[MAX_DESCRIPTORS];
37
38 InspSocket::InspSocket()
39 {
40         this->state = I_DISCONNECTED;
41         this->fd = -1;
42         this->ClosePending = false;
43 }
44
45 InspSocket::InspSocket(int newfd, const char* ip)
46 {
47         this->fd = newfd;
48         this->state = I_CONNECTED;
49         strlcpy(this->IP,ip,MAXBUF);
50         this->ClosePending = false;
51         if (this->fd > -1)
52         {
53                 ServerInstance->SE->AddFd(this->fd,true,X_ESTAB_MODULE);
54                 socket_ref[this->fd] = this;
55         }
56 }
57
58 InspSocket::InspSocket(const std::string &ahost, int aport, bool listening, unsigned long maxtime) : fd(-1)
59 {
60         strlcpy(host,ahost.c_str(),MAXBUF);
61         this->ClosePending = false;
62         if (listening) {
63                 if ((this->fd = OpenTCPSocket()) == ERROR)
64                 {
65                         this->fd = -1;
66                         this->state = I_ERROR;
67                         this->OnError(I_ERR_SOCKET);
68                         this->ClosePending = true;
69                         log(DEBUG,"OpenTCPSocket() error");
70                         return;
71                 }
72                 else
73                 {
74                         if (!BindSocket(this->fd,this->client,this->server,aport,(char*)ahost.c_str()))
75                         {
76                                 log(DEBUG,"BindSocket() error %s",strerror(errno));
77                                 this->Close();
78                                 this->fd = -1;
79                                 this->state = I_ERROR;
80                                 this->OnError(I_ERR_BIND);
81                                 this->ClosePending = true;
82                                 return;
83                         }
84                         else
85                         {
86                                 this->state = I_LISTENING;
87                                 if (this->fd > -1)
88                                 {
89                                         ServerInstance->SE->AddFd(this->fd,true,X_ESTAB_MODULE);
90                                         socket_ref[this->fd] = this;
91                                 }
92                                 log(DEBUG,"New socket now in I_LISTENING state");
93                                 return;
94                         }
95                 }                       
96         }
97         else
98         {
99                 strlcpy(this->host,ahost.c_str(),MAXBUF);
100                 this->port = aport;
101
102                 if (insp_aton(host,&addy) < 1)
103                 {
104                         log(DEBUG,"Attempting to resolve %s",this->host);
105                         /* Its not an ip, spawn the resolver */
106
107                         /* TODO: Implement resolver with new Resolver class */
108
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);
117                         strlcpy(this->IP,host,MAXBUF);
118                         timeout_end = time(NULL) + maxtime;
119                         this->DoConnect();
120                 }
121         }
122 }
123
124 void InspSocket::WantWrite()
125 {
126         /** XXX:
127          * The socket engine may only have each FD in the list ONCE.
128          * This means we cant watch for write AND read at the same
129          * time. We have to remove the READ fd, to insert the WRITE
130          * fd. Once we receive our WRITE event (which WILL ARRIVE,
131          * pretty much gauranteed) we switch back to watching for
132          * READ events again.
133          *
134          * This behaviour may be fixed in a later version.
135          */
136         this->WaitingForWriteEvent = true;
137         ServerInstance->SE->DelFd(this->fd);
138         ServerInstance->SE->AddFd(this->fd,false,X_ESTAB_MODULE);
139 }
140
141 void InspSocket::SetQueues(int nfd)
142 {
143         // attempt to increase socket sendq and recvq as high as its possible
144         int sendbuf = 32768;
145         int recvbuf = 32768;
146         setsockopt(nfd,SOL_SOCKET,SO_SNDBUF,(const void *)&sendbuf,sizeof(sendbuf));
147         setsockopt(nfd,SOL_SOCKET,SO_RCVBUF,(const void *)&recvbuf,sizeof(sendbuf));
148 }
149
150 bool InspSocket::DoResolve()
151 {
152         log(DEBUG,"In DoResolve(), trying to resolve IP");
153
154         log(DEBUG,"No result for socket yet!");
155         return true;
156 }
157
158 /* Most irc servers require you to specify the ip you want to bind to.
159  * If you dont specify an IP, they rather dumbly bind to the first IP
160  * of the box (e.g. INADDR_ANY). In InspIRCd, we scan thought the IP
161  * addresses we've bound server ports to, and we try and bind our outbound
162  * connections to the first usable non-loopback and non-any IP we find.
163  * This is easier to configure when you have a lot of links and a lot
164  * of servers to configure.
165  */
166 bool InspSocket::BindAddr()
167 {
168         insp_inaddr n;
169         ConfigReader Conf;
170
171         log(DEBUG,"In InspSocket::BindAddr()");
172         for (int j =0; j < Conf.Enumerate("bind"); j++)
173         {
174                 std::string Type = Conf.ReadValue("bind","type",j);
175                 std::string IP = Conf.ReadValue("bind","address",j);
176                 if (Type == "servers")
177                 {
178                         if ((IP != "*") && (IP != "127.0.0.1") && (IP != ""))
179                         {
180                                 insp_sockaddr s;
181                                 char resolved_addr[MAXBUF];
182                                 
183                                 if (insp_aton(IP.c_str(),&n) < 1)
184                                 {
185                                         /* If they gave a hostname, bind to the IP it resolves to */
186                                         log(DEBUG,"Resolving host %s",IP.c_str());
187                                         if (CleanAndResolve(resolved_addr, IP.c_str(), true, 1))
188                                         {
189                                                 log(DEBUG,"Resolved host %s to %s",IP.c_str(),resolved_addr);
190                                                 IP = resolved_addr;
191                                         }
192                                 }
193
194                                 if (insp_aton(IP.c_str(),&n) > 0)
195                                 {
196                                         log(DEBUG,"Found an IP to bind to: %s",IP.c_str());
197 #ifdef IPV6
198                                         s.sin6_addr = n;
199                                         s.sin6_family = AF_FAMILY;
200 #else
201                                         s.sin_addr = n;
202                                         s.sin_family = AF_FAMILY;
203 #endif
204                                         if (bind(this->fd,(struct sockaddr*)&s,sizeof(s)) < 0)
205                                         {
206                                                 log(DEBUG,"Cant bind()");
207                                                 this->state = I_ERROR;
208                                                 this->OnError(I_ERR_BIND);
209                                                 this->fd = -1;
210                                                 return false;
211                                         }
212                                         log(DEBUG,"bind() reports outbound fd bound to ip %s",IP.c_str());
213                                         return true;
214                                 }
215                                 else
216                                 {
217                                         log(DEBUG,"Address '%s' was not an IP address",IP.c_str());
218                                 }
219                         }
220                 }
221         }
222         log(DEBUG,"Found no suitable IPs to bind, binding INADDR_ANY");
223         return true;
224 }
225
226 bool InspSocket::DoConnect()
227 {
228         log(DEBUG,"In DoConnect()");
229         if ((this->fd = socket(AF_FAMILY, SOCK_STREAM, 0)) == -1)
230         {
231                 log(DEBUG,"Cant socket()");
232                 this->state = I_ERROR;
233                 this->OnError(I_ERR_SOCKET);
234                 this->fd = -1;
235                 return false;
236         }
237
238         if (!this->BindAddr())
239                 return false;
240
241         log(DEBUG,"Part 2 DoConnect() %s",this->IP);
242         insp_aton(this->IP,&addy);
243 #ifdef IPV6
244         addr.sin6_family = AF_FAMILY;
245         memcpy(&addy, &addr.sin6_addr, sizeof(insp_inaddr));
246         addr.sin6_port = htons(this->port);
247 #else
248         addr.sin_family = AF_FAMILY;
249         addr.sin_addr = addy;
250         addr.sin_port = htons(this->port);
251 #endif
252
253         int flags;
254         flags = fcntl(this->fd, F_GETFL, 0);
255         fcntl(this->fd, F_SETFL, flags | O_NONBLOCK);
256
257         if (connect(this->fd, (sockaddr*)&this->addr,sizeof(this->addr)) == -1)
258         {
259                 if (errno != EINPROGRESS)
260                 {
261                         log(DEBUG,"Error connect() %d: %s",this->fd,strerror(errno));
262                         this->OnError(I_ERR_CONNECT);
263                         this->Close();
264                         this->state = I_ERROR;
265                         this->fd = -1;
266                         this->ClosePending = true;
267                         return false;
268                 }
269         }
270         this->state = I_CONNECTING;
271         if (this->fd > -1)
272         {
273                 ServerInstance->SE->AddFd(this->fd,false,X_ESTAB_MODULE);
274                 socket_ref[this->fd] = this;
275                 this->SetQueues(this->fd);
276         }
277         log(DEBUG,"Returning true from InspSocket::DoConnect");
278         return true;
279 }
280
281
282 void InspSocket::Close()
283 {
284         if (this->fd != -1)
285         {
286                 this->OnClose();
287                 shutdown(this->fd,2);
288                 close(this->fd);
289                 socket_ref[this->fd] = NULL;
290                 this->ClosePending = true;
291                 this->fd = -1;
292         }
293 }
294
295 std::string InspSocket::GetIP()
296 {
297         return this->IP;
298 }
299
300 char* InspSocket::Read()
301 {
302         if ((fd < 0) || (fd > MAX_DESCRIPTORS))
303                 return NULL;
304         int n = recv(this->fd,this->ibuf,sizeof(this->ibuf),0);
305         if ((n > 0) && (n <= (int)sizeof(this->ibuf)))
306         {
307                 ibuf[n] = 0;
308                 return ibuf;
309         }
310         else
311         {
312                 if (errno == EAGAIN)
313                 {
314                         return "";
315                 }
316                 else
317                 {
318                         log(DEBUG,"EOF or error on socket: %s",strerror(errno));
319                         return NULL;
320                 }
321         }
322 }
323
324 void InspSocket::MarkAsClosed()
325 {
326         log(DEBUG,"Marked as closed");
327         this->ClosePending = true;
328 }
329
330 // There are two possible outcomes to this function.
331 // It will either write all of the data, or an undefined amount.
332 // If an undefined amount is written the connection has failed
333 // and should be aborted.
334 int InspSocket::Write(const std::string &data)
335 {
336         if (this->ClosePending)
337                 return false;
338
339         /*int result = write(this->fd,data.c_str(),data.length());
340         if (result < 1)
341                 return false;
342         return true;*/
343
344         /* Try and append the data to the back of the queue, and send it on its way
345          */
346         outbuffer.push_back(data);
347         return (!this->FlushWriteBuffer());
348 }
349
350 bool InspSocket::FlushWriteBuffer()
351 {
352         if (this->ClosePending)
353                 return true;
354
355         if ((this->fd > -1) && (this->state == I_CONNECTED))
356         {
357                 if (outbuffer.size())
358                 {
359                         int result = write(this->fd,outbuffer[0].c_str(),outbuffer[0].length());
360                         if (result > 0)
361                         {
362                                 if ((unsigned int)result == outbuffer[0].length())
363                                 {
364                                         /* The whole block was written (usually a line)
365                                          * Pop the block off the front of the queue
366                                          */
367                                         outbuffer.pop_front();
368                                 }
369                                 else
370                                 {
371                                         std::string temp = outbuffer[0].substr(result);
372                                         outbuffer[0] = temp;
373                                 }
374                         }
375                         else if ((result == -1) && (errno != EAGAIN))
376                         {
377                                 log(DEBUG,"Write error on socket: %s",strerror(errno));
378                                 this->OnError(I_ERR_WRITE);
379                                 this->state = I_ERROR;
380                                 this->ClosePending = true;
381                                 return true;
382                         }
383                 }
384         }
385         return (fd < 0);
386 }
387
388 bool InspSocket::Timeout(time_t current)
389 {
390         if (!socket_ref[this->fd] || !ServerInstance->SE->HasFd(this->fd))
391         {
392                 log(DEBUG,"No FD or socket ref");
393                 return false;
394         }
395
396         if (this->ClosePending)
397         {
398                 log(DEBUG,"Close is pending");
399                 return true;
400         }
401
402         if (((this->state == I_RESOLVING) || (this->state == I_CONNECTING)) && (current > timeout_end))
403         {
404                 log(DEBUG,"Timed out, current=%lu timeout_end=%lu");
405                 // for non-listening sockets, the timeout can occur
406                 // which causes termination of the connection after
407                 // the given number of seconds without a successful
408                 // connection.
409                 this->OnTimeout();
410                 this->OnError(I_ERR_TIMEOUT);
411                 timeout = true;
412                 this->state = I_ERROR;
413                 this->ClosePending = true;
414                 return true;
415         }
416         return this->FlushWriteBuffer();
417 }
418
419 bool InspSocket::Poll()
420 {
421         if (!socket_ref[this->fd] || !ServerInstance->SE->HasFd(this->fd))
422                 return false;
423
424         int incoming = -1;
425         bool n = true;
426
427         if ((fd < 0) || (fd > MAX_DESCRIPTORS) || (this->ClosePending))
428                 return false;
429
430         switch (this->state)
431         {
432                 case I_RESOLVING:
433                         log(DEBUG,"State = I_RESOLVING, calling DoResolve()");
434                         return this->DoResolve();
435                 break;
436                 case I_CONNECTING:
437                         log(DEBUG,"State = I_CONNECTING");
438                         this->SetState(I_CONNECTED);
439                         /* Our socket was in write-state, so delete it and re-add it
440                          * in read-state.
441                          */
442                         if (this->fd > -1)
443                         {
444                                 ServerInstance->SE->DelFd(this->fd);
445                                 ServerInstance->SE->AddFd(this->fd,true,X_ESTAB_MODULE);
446                         }
447                         return this->OnConnected();
448                 break;
449                 case I_LISTENING:
450                         length = sizeof (client);
451                         incoming = accept (this->fd, (sockaddr*)&client,&length);
452                         this->SetQueues(incoming);
453 #ifdef IPV6
454                         this->OnIncomingConnection(incoming,(char*)insp_ntoa(client.sin6_addr));
455 #else
456                         this->OnIncomingConnection(incoming,(char*)insp_ntoa(client.sin_addr));
457 #endif
458                         return true;
459                 break;
460                 case I_CONNECTED:
461
462                         if (this->WaitingForWriteEvent)
463                         {
464                                 /* Switch back to read events */
465                                 ServerInstance->SE->DelFd(this->fd);
466                                 ServerInstance->SE->AddFd(this->fd,true,X_ESTAB_MODULE);
467                                 /* Trigger the write event */
468                                 n = this->OnWriteReady();
469                         }
470                         else
471                         {
472                                 /* Process the read event */
473                                 n = this->OnDataReady();
474                         }
475                         /* Flush any pending, but not till after theyre done with the event
476                          * so there are less write calls involved.
477                          * Both FlushWriteBuffer AND the return result of OnDataReady must
478                          * return true for this to be ok.
479                          */
480                         if (this->FlushWriteBuffer())
481                                 return false;
482                         return n;
483                 break;
484                 default:
485                 break;
486         }
487         return true;
488 }
489
490 void InspSocket::SetState(InspSocketState s)
491 {
492         log(DEBUG,"Socket state change");
493         this->state = s;
494 }
495
496 InspSocketState InspSocket::GetState()
497 {
498         return this->state;
499 }
500
501 int InspSocket::GetFd()
502 {
503         return this->fd;
504 }
505
506 bool InspSocket::OnConnected() { return true; }
507 void InspSocket::OnError(InspSocketError e) { return; }
508 int InspSocket::OnDisconnect() { return 0; }
509 int InspSocket::OnIncomingConnection(int newfd, char* ip) { return 0; }
510 bool InspSocket::OnDataReady() { return true; }
511 bool InspSocket::OnWriteReady() { return true; }
512 void InspSocket::OnTimeout() { return; }
513 void InspSocket::OnClose() { return; }
514
515 InspSocket::~InspSocket()
516 {
517         this->Close();
518 }