1 /* +------------------------------------+
2 * | Inspire Internet Relay Chat Daemon |
3 * +------------------------------------+
5 * InspIRCd is copyright (C) 2002-2006 ChatSpike-Dev.
7 * <brain@chatspike.net>
8 * <Craig@chatspike.net>
10 * Written by Craig Edwards, Craig McLure, and others.
11 * This program is free but copyrighted software; see
12 * the file COPYING for details.
14 * ---------------------------------------------------
18 #include "configreader.h"
19 #include "inspstring.h"
20 #include "socketengine.h"
23 using irc::sockets::OpenTCPSocket;
24 using irc::sockets::insp_inaddr;
25 using irc::sockets::insp_sockaddr;
27 bool InspSocket::Readable()
29 return ((this->state != I_CONNECTING) && (this->WaitingForWriteEvent == false));
32 InspSocket::InspSocket(InspIRCd* SI)
34 this->state = I_DISCONNECTED;
36 this->WaitingForWriteEvent = false;
38 this->IsIOHooked = false;
41 InspSocket::InspSocket(InspIRCd* SI, int newfd, const char* ip)
44 this->state = I_CONNECTED;
45 strlcpy(this->IP,ip,MAXBUF);
46 this->WaitingForWriteEvent = false;
48 this->IsIOHooked = false;
50 this->Instance->SE->AddFd(this);
53 InspSocket::InspSocket(InspIRCd* SI, const std::string &ipaddr, int aport, bool listening, unsigned long maxtime)
57 strlcpy(host,ipaddr.c_str(),MAXBUF);
58 this->WaitingForWriteEvent = false;
59 this->IsIOHooked = false;
62 if ((this->fd = OpenTCPSocket()) == ERROR)
65 this->state = I_ERROR;
66 this->OnError(I_ERR_SOCKET);
67 this->Instance->Log(DEBUG,"OpenTCPSocket() error");
72 if (!SI->BindSocket(this->fd,this->client,this->server,aport,(char*)ipaddr.c_str()))
74 this->Instance->Log(DEBUG,"BindSocket() error %s",strerror(errno));
77 this->state = I_ERROR;
78 this->OnError(I_ERR_BIND);
79 this->ClosePending = true;
84 this->state = I_LISTENING;
87 if (!this->Instance->SE->AddFd(this))
90 this->state = I_ERROR;
91 this->OnError(I_ERR_NOMOREFDS);
94 this->Instance->Log(DEBUG,"New socket now in I_LISTENING state");
101 strlcpy(this->host,ipaddr.c_str(),MAXBUF);
104 if (insp_aton(host,&addy) < 1)
106 this->Instance->Log(DEBUG,"You cannot pass hostnames to InspSocket, resolve them first with Resolver!");
109 this->state = I_ERROR;
110 this->OnError(I_ERR_RESOLVE);
115 this->Instance->Log(DEBUG,"No need to resolve %s",this->host);
116 strlcpy(this->IP,host,MAXBUF);
117 timeout_val = maxtime;
123 void InspSocket::WantWrite()
125 this->Instance->SE->WantWrite(this);
126 this->WaitingForWriteEvent = true;
129 void InspSocket::SetQueues(int nfd)
131 // attempt to increase socket sendq and recvq as high as its possible
134 setsockopt(nfd,SOL_SOCKET,SO_SNDBUF,(const void *)&sendbuf,sizeof(sendbuf));
135 setsockopt(nfd,SOL_SOCKET,SO_RCVBUF,(const void *)&recvbuf,sizeof(sendbuf));
138 /* Most irc servers require you to specify the ip you want to bind to.
139 * If you dont specify an IP, they rather dumbly bind to the first IP
140 * of the box (e.g. INADDR_ANY). In InspIRCd, we scan thought the IP
141 * addresses we've bound server ports to, and we try and bind our outbound
142 * connections to the first usable non-loopback and non-any IP we find.
143 * This is easier to configure when you have a lot of links and a lot
144 * of servers to configure.
146 bool InspSocket::BindAddr()
149 ConfigReader Conf(this->Instance);
151 this->Instance->Log(DEBUG,"In InspSocket::BindAddr()");
152 for (int j =0; j < Conf.Enumerate("bind"); j++)
154 std::string Type = Conf.ReadValue("bind","type",j);
155 std::string IP = Conf.ReadValue("bind","address",j);
156 if (Type == "servers")
158 if ((IP != "*") && (IP != "127.0.0.1") && (IP != ""))
162 if (insp_aton(IP.c_str(),&n) > 0)
164 this->Instance->Log(DEBUG,"Found an IP to bind to: %s",IP.c_str());
167 s.sin6_family = AF_FAMILY;
170 s.sin_family = AF_FAMILY;
172 if (bind(this->fd,(struct sockaddr*)&s,sizeof(s)) < 0)
174 this->Instance->Log(DEBUG,"Cant bind()");
175 this->state = I_ERROR;
176 this->OnError(I_ERR_BIND);
180 this->Instance->Log(DEBUG,"bind() reports outbound fd bound to ip %s",IP.c_str());
185 this->Instance->Log(DEBUG,"Address '%s' was not an IP address",IP.c_str());
190 this->Instance->Log(DEBUG,"Found no suitable IPs to bind, binding INADDR_ANY");
194 bool InspSocket::DoConnect()
196 this->Instance->Log(DEBUG,"In DoConnect()");
197 if ((this->fd = socket(AF_FAMILY, SOCK_STREAM, 0)) == -1)
199 this->Instance->Log(DEBUG,"Cant socket()");
200 this->state = I_ERROR;
201 this->OnError(I_ERR_SOCKET);
205 if ((strstr(this->IP,"::ffff:") != (char*)&this->IP) && (strstr(this->IP,"::FFFF:") != (char*)&this->IP))
207 if (!this->BindAddr())
211 this->Instance->Log(DEBUG,"Part 2 DoConnect() %s",this->IP);
212 insp_aton(this->IP,&addy);
214 addr.sin6_family = AF_FAMILY;
215 memcpy(&addr.sin6_addr, &addy, sizeof(insp_inaddr));
216 addr.sin6_port = htons(this->port);
218 addr.sin_family = AF_FAMILY;
219 addr.sin_addr = addy;
220 addr.sin_port = htons(this->port);
224 flags = fcntl(this->fd, F_GETFL, 0);
225 fcntl(this->fd, F_SETFL, flags | O_NONBLOCK);
227 if (connect(this->fd, (sockaddr*)&this->addr,sizeof(this->addr)) == -1)
229 if (errno != EINPROGRESS)
231 this->Instance->Log(DEBUG,"Error connect() %d: %s",this->fd,strerror(errno));
232 this->OnError(I_ERR_CONNECT);
234 this->state = I_ERROR;
238 this->Timeout = new SocketTimeout(this->GetFd(), this->Instance, this, timeout_val, this->Instance->Time());
239 this->Instance->Timers->AddTimer(this->Timeout);
241 this->state = I_CONNECTING;
244 if (!this->Instance->SE->AddFd(this))
246 this->OnError(I_ERR_NOMOREFDS);
248 this->state = I_ERROR;
251 this->SetQueues(this->fd);
253 this->Instance->Log(DEBUG,"Returning true from InspSocket::DoConnect");
258 void InspSocket::Close()
262 if (this->IsIOHooked && Instance->Config->GetIOHook(this))
266 Instance->Config->GetIOHook(this)->OnRawSocketClose(this->fd);
268 catch (ModuleException& modexcept)
270 Instance->Log(DEBUG,"Module exception cought: %s",modexcept.GetReason());
274 shutdown(this->fd,2);
279 std::string InspSocket::GetIP()
284 char* InspSocket::Read()
286 if ((fd < 0) || (fd > MAX_DESCRIPTORS))
291 if (this->IsIOHooked)
297 MOD_RESULT = Instance->Config->GetIOHook(this)->OnRawSocketRead(this->fd,this->ibuf,sizeof(this->ibuf),result2);
299 catch (ModuleException& modexcept)
301 Instance->Log(DEBUG,"Module exception caught: %s",modexcept.GetReason());
315 n = recv(this->fd,this->ibuf,sizeof(this->ibuf),0);
318 if ((n > 0) && (n <= (int)sizeof(this->ibuf)))
333 this->Instance->Log(DEBUG,"EOF or error on socket: EOF");
335 this->Instance->Log(DEBUG,"EOF or error on socket: %s",strerror(err));
341 void InspSocket::MarkAsClosed()
343 this->Instance->Log(DEBUG,"Marked as closed");
346 // There are two possible outcomes to this function.
347 // It will either write all of the data, or an undefined amount.
348 // If an undefined amount is written the connection has failed
349 // and should be aborted.
350 int InspSocket::Write(const std::string &data)
352 /* Try and append the data to the back of the queue, and send it on its way
354 outbuffer.push_back(data);
355 this->Instance->SE->WantWrite(this);
356 return (!this->FlushWriteBuffer());
359 bool InspSocket::FlushWriteBuffer()
362 if ((this->fd > -1) && (this->state == I_CONNECTED))
364 if (this->IsIOHooked)
366 while (outbuffer.size() && (errno != EAGAIN))
370 Instance->Log(DEBUG,"To write: %s", outbuffer[0].c_str());
371 int result = Instance->Config->GetIOHook(this)->OnRawSocketWrite(this->fd, outbuffer[0].c_str(), outbuffer[0].length());
374 if ((unsigned int)result == outbuffer[0].length())
376 outbuffer.pop_front();
380 std::string temp = outbuffer[0].substr(result);
385 else if ((result == -1) && (errno != EAGAIN))
387 this->Instance->Log(DEBUG,"Write error on socket: %s",strerror(errno));
388 this->OnError(I_ERR_WRITE);
389 this->state = I_ERROR;
390 this->Instance->SE->DelFd(this);
395 catch (ModuleException& modexcept)
397 Instance->Log(DEBUG,"Module exception caught: %s",modexcept.GetReason());
404 /* If we have multiple lines, try to send them all,
405 * not just the first one -- Brain
407 while (outbuffer.size() && (errno != EAGAIN))
410 int result = write(this->fd,outbuffer[0].c_str(),outbuffer[0].length());
413 if ((unsigned int)result == outbuffer[0].length())
415 /* The whole block was written (usually a line)
416 * Pop the block off the front of the queue,
417 * dont set errno, because we are clear of errors
418 * and want to try and write the next block too.
420 outbuffer.pop_front();
424 std::string temp = outbuffer[0].substr(result);
426 /* We didnt get the whole line out. arses.
427 * Try again next time, i guess. Set errno,
428 * because we shouldnt be writing any more now,
429 * until the socketengine says its safe to do so.
434 else if ((result == -1) && (errno != EAGAIN))
436 this->Instance->Log(DEBUG,"Write error on socket: %s",strerror(errno));
437 this->OnError(I_ERR_WRITE);
438 this->state = I_ERROR;
439 this->Instance->SE->DelFd(this);
447 if ((errno == EAGAIN) && (fd > -1))
449 this->Instance->SE->WantWrite(this);
455 void SocketTimeout::Tick(time_t now)
457 if (ServerInstance->SE->GetRef(this->sfd) != this->sock)
459 ServerInstance->Log(DEBUG,"Our socket has been deleted before the timeout was reached.");
463 if (this->sock->state == I_CONNECTING)
465 ServerInstance->Log(DEBUG,"Timed out, current=%lu",now);
466 // for non-listening sockets, the timeout can occur
467 // which causes termination of the connection after
468 // the given number of seconds without a successful
470 this->sock->OnTimeout();
471 this->sock->OnError(I_ERR_TIMEOUT);
472 this->sock->timeout = true;
473 ServerInstance->SE->DelFd(this->sock);
474 /* NOTE: We must set this AFTER DelFd, as we added
475 * this socket whilst writeable. This means that we
476 * must DELETE the socket whilst writeable too!
478 this->sock->state = I_ERROR;
485 bool InspSocket::Poll()
487 if (this->Instance->SE->GetRef(this->fd) != this)
492 if ((fd < 0) || (fd > MAX_DESCRIPTORS))
498 this->Instance->Log(DEBUG,"State = I_CONNECTING");
499 /* Our socket was in write-state, so delete it and re-add it
504 this->Instance->SE->DelFd(this);
505 this->SetState(I_CONNECTED);
506 if (!this->Instance->SE->AddFd(this))
509 if (this->IsIOHooked)
513 Instance->Config->GetIOHook(this)->OnRawSocketConnect(this->fd);
515 catch (ModuleException& modexcept)
517 Instance->Log(DEBUG,"Module exception cought: %s",modexcept.GetReason());
520 return this->OnConnected();
523 length = sizeof (client);
524 incoming = accept (this->fd, (sockaddr*)&client,&length);
527 this->OnIncomingConnection(incoming, (char*)insp_ntoa(client.sin6_addr));
529 this->OnIncomingConnection(incoming, (char*)insp_ntoa(client.sin_addr));
532 if (this->IsIOHooked)
537 Instance->Config->GetIOHook(this)->OnRawSocketAccept(incoming, insp_ntoa(client.sin6_addr), this->port);
539 Instance->Config->GetIOHook(this)->OnRawSocketAccept(incoming, insp_ntoa(client.sin_addr), this->port);
542 catch (ModuleException& modexcept)
544 Instance->Log(DEBUG,"Module exception cought: %s",modexcept.GetReason());
548 this->SetQueues(incoming);
552 /* Process the read event */
553 return this->OnDataReady();
561 void InspSocket::SetState(InspSocketState s)
563 this->Instance->Log(DEBUG,"Socket state change");
567 InspSocketState InspSocket::GetState()
572 int InspSocket::GetFd()
577 bool InspSocket::OnConnected() { return true; }
578 void InspSocket::OnError(InspSocketError e) { return; }
579 int InspSocket::OnDisconnect() { return 0; }
580 int InspSocket::OnIncomingConnection(int newfd, char* ip) { return 0; }
581 bool InspSocket::OnDataReady() { return true; }
582 bool InspSocket::OnWriteReady() { return true; }
583 void InspSocket::OnTimeout() { return; }
584 void InspSocket::OnClose() { return; }
586 InspSocket::~InspSocket()
591 void InspSocket::HandleEvent(EventType et, int errornum)
596 this->Instance->SE->DelFd(this);
604 this->Instance->SE->DelFd(this);
611 if (this->WaitingForWriteEvent)
613 this->WaitingForWriteEvent = false;
614 if (!this->OnWriteReady())
616 this->Instance->SE->DelFd(this);
622 if (this->state == I_CONNECTING)
624 /* This might look wrong as if we should be actually calling
625 * with EVENT_WRITE, but trust me it is correct. There are some
626 * writeability-state things in the read code, because of how
627 * InspSocket used to work regarding write buffering in previous
628 * versions of InspIRCd. - Brain
630 this->HandleEvent(EVENT_READ);
635 Instance->Log(DEBUG,"State=%d CONNECTED=%d", this->state, I_CONNECTED);
636 if (this->FlushWriteBuffer())
638 this->Instance->SE->DelFd(this);