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