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