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