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