1 /* +------------------------------------+
2 * | Inspire Internet Relay Chat Daemon |
3 * +------------------------------------+
5 * InspIRCd: (C) 2002-2007 InspIRCd Development Team
6 * See: http://www.inspircd.org/wiki/index.php/Credits
8 * This program is free but copyrighted software; see
9 * the file COPYING for details.
11 * ---------------------------------------------------
15 #include "configreader.h"
16 #include "inspstring.h"
17 #include "socketengine.h"
20 using irc::sockets::OpenTCPSocket;
21 using irc::sockets::insp_inaddr;
22 using irc::sockets::insp_sockaddr;
24 bool InspSocket::Readable()
26 return ((this->state != I_CONNECTING) && (this->WaitingForWriteEvent == false));
29 InspSocket::InspSocket(InspIRCd* SI)
31 this->state = I_DISCONNECTED;
33 this->WaitingForWriteEvent = false;
35 this->IsIOHooked = false;
38 InspSocket::InspSocket(InspIRCd* SI, int newfd, const char* ip)
41 this->state = I_CONNECTED;
42 strlcpy(this->IP,ip,MAXBUF);
43 this->WaitingForWriteEvent = false;
45 this->IsIOHooked = false;
47 this->Instance->SE->AddFd(this);
50 InspSocket::InspSocket(InspIRCd* SI, const std::string &ipaddr, int aport, bool listening, unsigned long maxtime)
54 strlcpy(host,ipaddr.c_str(),MAXBUF);
55 this->WaitingForWriteEvent = false;
56 this->IsIOHooked = false;
59 if ((this->fd = OpenTCPSocket()) == ERROR)
62 this->state = I_ERROR;
63 this->OnError(I_ERR_SOCKET);
64 this->Instance->Log(DEBUG,"OpenTCPSocket() error");
69 if (!SI->BindSocket(this->fd,this->client,this->server,aport,(char*)ipaddr.c_str()))
71 this->Instance->Log(DEBUG,"BindSocket() error %s",strerror(errno));
74 this->state = I_ERROR;
75 this->OnError(I_ERR_BIND);
76 this->ClosePending = true;
81 this->state = I_LISTENING;
84 if (!this->Instance->SE->AddFd(this))
87 this->state = I_ERROR;
88 this->OnError(I_ERR_NOMOREFDS);
91 this->Instance->Log(DEBUG,"New socket now in I_LISTENING state");
98 strlcpy(this->host,ipaddr.c_str(),MAXBUF);
101 if (insp_aton(host,&addy) < 1)
103 this->Instance->Log(DEBUG,"You cannot pass hostnames to InspSocket, resolve them first with Resolver!");
106 this->state = I_ERROR;
107 this->OnError(I_ERR_RESOLVE);
112 this->Instance->Log(DEBUG,"No need to resolve %s",this->host);
113 strlcpy(this->IP,host,MAXBUF);
114 timeout_val = maxtime;
120 void InspSocket::WantWrite()
122 this->Instance->SE->WantWrite(this);
123 this->WaitingForWriteEvent = true;
126 void InspSocket::SetQueues(int nfd)
128 // attempt to increase socket sendq and recvq as high as its possible
131 setsockopt(nfd,SOL_SOCKET,SO_SNDBUF,(const void *)&sendbuf,sizeof(sendbuf));
132 setsockopt(nfd,SOL_SOCKET,SO_RCVBUF,(const void *)&recvbuf,sizeof(sendbuf));
135 /* Most irc servers require you to specify the ip you want to bind to.
136 * If you dont specify an IP, they rather dumbly bind to the first IP
137 * of the box (e.g. INADDR_ANY). In InspIRCd, we scan thought the IP
138 * addresses we've bound server ports to, and we try and bind our outbound
139 * connections to the first usable non-loopback and non-any IP we find.
140 * This is easier to configure when you have a lot of links and a lot
141 * of servers to configure.
143 bool InspSocket::BindAddr()
146 ConfigReader Conf(this->Instance);
148 this->Instance->Log(DEBUG,"In InspSocket::BindAddr()");
149 for (int j =0; j < Conf.Enumerate("bind"); j++)
151 std::string Type = Conf.ReadValue("bind","type",j);
152 std::string IP = Conf.ReadValue("bind","address",j);
153 if (Type == "servers")
155 if ((IP != "*") && (IP != "127.0.0.1") && (IP != ""))
159 if (insp_aton(IP.c_str(),&n) > 0)
161 this->Instance->Log(DEBUG,"Found an IP to bind to: %s",IP.c_str());
164 s.sin6_family = AF_FAMILY;
167 s.sin_family = AF_FAMILY;
169 if (bind(this->fd,(struct sockaddr*)&s,sizeof(s)) < 0)
171 this->Instance->Log(DEBUG,"Cant bind()");
172 this->state = I_ERROR;
173 this->OnError(I_ERR_BIND);
177 this->Instance->Log(DEBUG,"bind() reports outbound fd bound to ip %s",IP.c_str());
182 this->Instance->Log(DEBUG,"Address '%s' was not an IP address",IP.c_str());
187 this->Instance->Log(DEBUG,"Found no suitable IPs to bind, binding INADDR_ANY");
191 bool InspSocket::DoConnect()
193 this->Instance->Log(DEBUG,"In DoConnect()");
194 if ((this->fd = socket(AF_FAMILY, SOCK_STREAM, 0)) == -1)
196 this->Instance->Log(DEBUG,"Cant socket()");
197 this->state = I_ERROR;
198 this->OnError(I_ERR_SOCKET);
202 if ((strstr(this->IP,"::ffff:") != (char*)&this->IP) && (strstr(this->IP,"::FFFF:") != (char*)&this->IP))
204 if (!this->BindAddr())
208 this->Instance->Log(DEBUG,"Part 2 DoConnect() %s",this->IP);
209 insp_aton(this->IP,&addy);
211 addr.sin6_family = AF_FAMILY;
212 memcpy(&addr.sin6_addr, &addy, sizeof(insp_inaddr));
213 addr.sin6_port = htons(this->port);
215 addr.sin_family = AF_FAMILY;
216 addr.sin_addr = addy;
217 addr.sin_port = htons(this->port);
221 flags = fcntl(this->fd, F_GETFL, 0);
222 fcntl(this->fd, F_SETFL, flags | O_NONBLOCK);
224 if (connect(this->fd, (sockaddr*)&this->addr,sizeof(this->addr)) == -1)
226 if (errno != EINPROGRESS)
228 this->Instance->Log(DEBUG,"Error connect() %d: %s",this->fd,strerror(errno));
229 this->OnError(I_ERR_CONNECT);
231 this->state = I_ERROR;
235 this->Timeout = new SocketTimeout(this->GetFd(), this->Instance, this, timeout_val, this->Instance->Time());
236 this->Instance->Timers->AddTimer(this->Timeout);
238 this->state = I_CONNECTING;
241 if (!this->Instance->SE->AddFd(this))
243 this->OnError(I_ERR_NOMOREFDS);
245 this->state = I_ERROR;
248 this->SetQueues(this->fd);
250 this->Instance->Log(DEBUG,"Returning true from InspSocket::DoConnect");
255 void InspSocket::Close()
259 if (this->IsIOHooked && Instance->Config->GetIOHook(this))
263 Instance->Config->GetIOHook(this)->OnRawSocketClose(this->fd);
265 catch (ModuleException& modexcept)
267 Instance->Log(DEBUG,"Module exception cought: %s",modexcept.GetReason());
271 shutdown(this->fd,2);
276 std::string InspSocket::GetIP()
281 char* InspSocket::Read()
283 if ((fd < 0) || (fd > MAX_DESCRIPTORS))
288 if (this->IsIOHooked)
294 MOD_RESULT = Instance->Config->GetIOHook(this)->OnRawSocketRead(this->fd,this->ibuf,sizeof(this->ibuf),result2);
296 catch (ModuleException& modexcept)
298 Instance->Log(DEBUG,"Module exception caught: %s",modexcept.GetReason());
312 n = recv(this->fd,this->ibuf,sizeof(this->ibuf),0);
315 if ((n > 0) && (n <= (int)sizeof(this->ibuf)))
330 this->Instance->Log(DEBUG,"EOF or error on socket: EOF");
332 this->Instance->Log(DEBUG,"EOF or error on socket: %s",strerror(err));
338 void InspSocket::MarkAsClosed()
340 this->Instance->Log(DEBUG,"Marked as closed");
343 // There are two possible outcomes to this function.
344 // It will either write all of the data, or an undefined amount.
345 // If an undefined amount is written the connection has failed
346 // and should be aborted.
347 int InspSocket::Write(const std::string &data)
349 /* Try and append the data to the back of the queue, and send it on its way
351 outbuffer.push_back(data);
352 this->Instance->SE->WantWrite(this);
353 return (!this->FlushWriteBuffer());
356 bool InspSocket::FlushWriteBuffer()
359 if ((this->fd > -1) && (this->state == I_CONNECTED))
361 if (this->IsIOHooked)
363 while (outbuffer.size() && (errno != EAGAIN))
367 int result = Instance->Config->GetIOHook(this)->OnRawSocketWrite(this->fd, outbuffer[0].c_str(), outbuffer[0].length());
370 if ((unsigned int)result == outbuffer[0].length())
372 outbuffer.pop_front();
376 std::string temp = outbuffer[0].substr(result);
381 else if ((result == -1) && (errno != EAGAIN))
383 this->Instance->Log(DEBUG,"Write error on socket: %s",strerror(errno));
384 this->OnError(I_ERR_WRITE);
385 this->state = I_ERROR;
386 this->Instance->SE->DelFd(this);
390 else if (result == 0)
392 this->Instance->Log(DEBUG,"Write error on socket: EOF");
393 this->OnError(I_ERR_WRITE);
394 this->state = I_ERROR;
395 this->Instance->SE->DelFd(this);
400 catch (ModuleException& modexcept)
402 Instance->Log(DEBUG,"Module exception caught: %s",modexcept.GetReason());
409 /* If we have multiple lines, try to send them all,
410 * not just the first one -- Brain
412 while (outbuffer.size() && (errno != EAGAIN))
415 int result = write(this->fd,outbuffer[0].c_str(),outbuffer[0].length());
418 if ((unsigned int)result == outbuffer[0].length())
420 /* The whole block was written (usually a line)
421 * Pop the block off the front of the queue,
422 * dont set errno, because we are clear of errors
423 * and want to try and write the next block too.
425 outbuffer.pop_front();
429 std::string temp = outbuffer[0].substr(result);
431 /* We didnt get the whole line out. arses.
432 * Try again next time, i guess. Set errno,
433 * because we shouldnt be writing any more now,
434 * until the socketengine says its safe to do so.
439 else if ((result == -1) && (errno != EAGAIN))
441 this->Instance->Log(DEBUG,"Write error on socket: %s",strerror(errno));
442 this->OnError(I_ERR_WRITE);
443 this->state = I_ERROR;
444 this->Instance->SE->DelFd(this);
452 if ((errno == EAGAIN) && (fd > -1))
454 this->Instance->SE->WantWrite(this);
460 void SocketTimeout::Tick(time_t now)
462 if (ServerInstance->SE->GetRef(this->sfd) != this->sock)
464 ServerInstance->Log(DEBUG,"Our socket has been deleted before the timeout was reached.");
468 if (this->sock->state == I_CONNECTING)
470 ServerInstance->Log(DEBUG,"Timed out, current=%lu",now);
471 // for non-listening sockets, the timeout can occur
472 // which causes termination of the connection after
473 // the given number of seconds without a successful
475 this->sock->OnTimeout();
476 this->sock->OnError(I_ERR_TIMEOUT);
477 this->sock->timeout = true;
478 ServerInstance->SE->DelFd(this->sock);
479 /* NOTE: We must set this AFTER DelFd, as we added
480 * this socket whilst writeable. This means that we
481 * must DELETE the socket whilst writeable too!
483 this->sock->state = I_ERROR;
490 bool InspSocket::Poll()
492 if (this->Instance->SE->GetRef(this->fd) != this)
497 if ((fd < 0) || (fd > MAX_DESCRIPTORS))
503 this->Instance->Log(DEBUG,"State = I_CONNECTING");
504 /* Our socket was in write-state, so delete it and re-add it
509 this->Instance->SE->DelFd(this);
510 this->SetState(I_CONNECTED);
511 if (!this->Instance->SE->AddFd(this))
514 if (Instance->Config->GetIOHook(this))
518 Instance->Config->GetIOHook(this)->OnRawSocketConnect(this->fd);
520 catch (ModuleException& modexcept)
522 Instance->Log(DEBUG,"Module exception cought: %s",modexcept.GetReason());
525 return this->OnConnected();
528 length = sizeof (client);
529 incoming = accept (this->fd, (sockaddr*)&client,&length);
532 this->OnIncomingConnection(incoming, (char*)insp_ntoa(client.sin6_addr));
534 this->OnIncomingConnection(incoming, (char*)insp_ntoa(client.sin_addr));
537 if (this->IsIOHooked)
542 Instance->Config->GetIOHook(this)->OnRawSocketAccept(incoming, insp_ntoa(client.sin6_addr), this->port);
544 Instance->Config->GetIOHook(this)->OnRawSocketAccept(incoming, insp_ntoa(client.sin_addr), this->port);
547 catch (ModuleException& modexcept)
549 Instance->Log(DEBUG,"Module exception cought: %s",modexcept.GetReason());
553 this->SetQueues(incoming);
557 /* Process the read event */
558 return this->OnDataReady();
566 void InspSocket::SetState(InspSocketState s)
568 this->Instance->Log(DEBUG,"Socket state change");
572 InspSocketState InspSocket::GetState()
577 int InspSocket::GetFd()
582 bool InspSocket::OnConnected() { return true; }
583 void InspSocket::OnError(InspSocketError e) { return; }
584 int InspSocket::OnDisconnect() { return 0; }
585 int InspSocket::OnIncomingConnection(int newfd, char* ip) { return 0; }
586 bool InspSocket::OnDataReady() { return true; }
587 bool InspSocket::OnWriteReady() { return true; }
588 void InspSocket::OnTimeout() { return; }
589 void InspSocket::OnClose() { return; }
591 InspSocket::~InspSocket()
596 void InspSocket::HandleEvent(EventType et, int errornum)
601 this->Instance->SE->DelFd(this);
609 this->Instance->SE->DelFd(this);
616 if (this->WaitingForWriteEvent)
618 this->WaitingForWriteEvent = false;
619 if (!this->OnWriteReady())
621 this->Instance->SE->DelFd(this);
627 if (this->state == I_CONNECTING)
629 /* This might look wrong as if we should be actually calling
630 * with EVENT_WRITE, but trust me it is correct. There are some
631 * writeability-state things in the read code, because of how
632 * InspSocket used to work regarding write buffering in previous
633 * versions of InspIRCd. - Brain
635 this->HandleEvent(EVENT_READ);
640 Instance->Log(DEBUG,"State=%d CONNECTED=%d", this->state, I_CONNECTED);
641 if (this->FlushWriteBuffer())
643 this->Instance->SE->DelFd(this);