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);
68 if (!SI->BindSocket(this->fd,this->client,this->server,aport,(char*)ipaddr.c_str()))
72 this->state = I_ERROR;
73 this->OnError(I_ERR_BIND);
74 this->ClosePending = true;
79 this->state = I_LISTENING;
82 if (!this->Instance->SE->AddFd(this))
85 this->state = I_ERROR;
86 this->OnError(I_ERR_NOMOREFDS);
95 strlcpy(this->host,ipaddr.c_str(),MAXBUF);
98 if (insp_aton(host,&addy) < 1)
100 this->Instance->Log(DEBUG,"BUG: Hostname passed to InspSocket, rather than an IP address!");
103 this->state = I_ERROR;
104 this->OnError(I_ERR_RESOLVE);
109 strlcpy(this->IP,host,MAXBUF);
110 timeout_val = maxtime;
116 void InspSocket::WantWrite()
118 this->Instance->SE->WantWrite(this);
119 this->WaitingForWriteEvent = true;
122 void InspSocket::SetQueues(int nfd)
124 // attempt to increase socket sendq and recvq as high as its possible
127 setsockopt(nfd,SOL_SOCKET,SO_SNDBUF,(const void *)&sendbuf,sizeof(sendbuf));
128 setsockopt(nfd,SOL_SOCKET,SO_RCVBUF,(const void *)&recvbuf,sizeof(sendbuf));
131 /* Most irc servers require you to specify the ip you want to bind to.
132 * If you dont specify an IP, they rather dumbly bind to the first IP
133 * of the box (e.g. INADDR_ANY). In InspIRCd, we scan thought the IP
134 * addresses we've bound server ports to, and we try and bind our outbound
135 * connections to the first usable non-loopback and non-any IP we find.
136 * This is easier to configure when you have a lot of links and a lot
137 * of servers to configure.
139 bool InspSocket::BindAddr()
142 ConfigReader Conf(this->Instance);
143 for (int j =0; j < Conf.Enumerate("bind"); j++)
145 std::string Type = Conf.ReadValue("bind","type",j);
146 std::string IP = Conf.ReadValue("bind","address",j);
147 if (Type == "servers")
149 if ((IP != "*") && (IP != "127.0.0.1") && (IP != ""))
153 if (insp_aton(IP.c_str(),&n) > 0)
157 s.sin6_family = AF_FAMILY;
160 s.sin_family = AF_FAMILY;
162 if (bind(this->fd,(struct sockaddr*)&s,sizeof(s)) < 0)
164 this->state = I_ERROR;
165 this->OnError(I_ERR_BIND);
177 bool InspSocket::DoConnect()
179 if ((this->fd = socket(AF_FAMILY, SOCK_STREAM, 0)) == -1)
181 this->state = I_ERROR;
182 this->OnError(I_ERR_SOCKET);
186 if ((strstr(this->IP,"::ffff:") != (char*)&this->IP) && (strstr(this->IP,"::FFFF:") != (char*)&this->IP))
188 if (!this->BindAddr())
192 insp_aton(this->IP,&addy);
194 addr.sin6_family = AF_FAMILY;
195 memcpy(&addr.sin6_addr, &addy, sizeof(insp_inaddr));
196 addr.sin6_port = htons(this->port);
198 addr.sin_family = AF_FAMILY;
199 addr.sin_addr = addy;
200 addr.sin_port = htons(this->port);
204 flags = fcntl(this->fd, F_GETFL, 0);
205 fcntl(this->fd, F_SETFL, flags | O_NONBLOCK);
207 if (connect(this->fd, (sockaddr*)&this->addr,sizeof(this->addr)) == -1)
209 if (errno != EINPROGRESS)
211 this->OnError(I_ERR_CONNECT);
213 this->state = I_ERROR;
217 this->Timeout = new SocketTimeout(this->GetFd(), this->Instance, this, timeout_val, this->Instance->Time());
218 this->Instance->Timers->AddTimer(this->Timeout);
220 this->state = I_CONNECTING;
223 if (!this->Instance->SE->AddFd(this))
225 this->OnError(I_ERR_NOMOREFDS);
227 this->state = I_ERROR;
230 this->SetQueues(this->fd);
236 void InspSocket::Close()
240 if (this->IsIOHooked && Instance->Config->GetIOHook(this))
244 Instance->Config->GetIOHook(this)->OnRawSocketClose(this->fd);
246 catch (CoreException& modexcept)
248 Instance->Log(DEFAULT,"%s threw an exception: %s", modexcept.GetSource(), modexcept.GetReason());
252 shutdown(this->fd,2);
257 std::string InspSocket::GetIP()
262 char* InspSocket::Read()
264 if ((fd < 0) || (fd > MAX_DESCRIPTORS))
269 if (this->IsIOHooked)
275 MOD_RESULT = Instance->Config->GetIOHook(this)->OnRawSocketRead(this->fd,this->ibuf,sizeof(this->ibuf),result2);
277 catch (CoreException& modexcept)
279 Instance->Log(DEFAULT,"%s threw an exception: %s", modexcept.GetSource(), modexcept.GetReason());
293 n = recv(this->fd,this->ibuf,sizeof(this->ibuf),0);
296 if ((n > 0) && (n <= (int)sizeof(this->ibuf)))
311 void InspSocket::MarkAsClosed()
315 // There are two possible outcomes to this function.
316 // It will either write all of the data, or an undefined amount.
317 // If an undefined amount is written the connection has failed
318 // and should be aborted.
319 int InspSocket::Write(const std::string &data)
321 /* Try and append the data to the back of the queue, and send it on its way
323 outbuffer.push_back(data);
324 this->Instance->SE->WantWrite(this);
325 return (!this->FlushWriteBuffer());
328 bool InspSocket::FlushWriteBuffer()
331 if ((this->fd > -1) && (this->state == I_CONNECTED))
333 if (this->IsIOHooked)
335 while (outbuffer.size() && (errno != EAGAIN))
339 int result = Instance->Config->GetIOHook(this)->OnRawSocketWrite(this->fd, outbuffer[0].c_str(), outbuffer[0].length());
342 if ((unsigned int)result == outbuffer[0].length())
344 outbuffer.pop_front();
348 std::string temp = outbuffer[0].substr(result);
353 else if (((result == -1) && (errno != EAGAIN)) || (result == 0))
355 this->OnError(I_ERR_WRITE);
356 this->state = I_ERROR;
357 this->Instance->SE->DelFd(this);
362 catch (CoreException& modexcept)
364 Instance->Log(DEBUG,"%s threw an exception: %s", modexcept.GetSource(), modexcept.GetReason());
371 /* If we have multiple lines, try to send them all,
372 * not just the first one -- Brain
374 while (outbuffer.size() && (errno != EAGAIN))
377 int result = write(this->fd,outbuffer[0].c_str(),outbuffer[0].length());
380 if ((unsigned int)result == outbuffer[0].length())
382 /* The whole block was written (usually a line)
383 * Pop the block off the front of the queue,
384 * dont set errno, because we are clear of errors
385 * and want to try and write the next block too.
387 outbuffer.pop_front();
391 std::string temp = outbuffer[0].substr(result);
393 /* We didnt get the whole line out. arses.
394 * Try again next time, i guess. Set errno,
395 * because we shouldnt be writing any more now,
396 * until the socketengine says its safe to do so.
401 else if ((result == -1) && (errno != EAGAIN))
403 this->OnError(I_ERR_WRITE);
404 this->state = I_ERROR;
405 this->Instance->SE->DelFd(this);
413 if ((errno == EAGAIN) && (fd > -1))
415 this->Instance->SE->WantWrite(this);
421 void SocketTimeout::Tick(time_t now)
423 if (ServerInstance->SE->GetRef(this->sfd) != this->sock)
426 if (this->sock->state == I_CONNECTING)
428 // for non-listening sockets, the timeout can occur
429 // which causes termination of the connection after
430 // the given number of seconds without a successful
432 this->sock->OnTimeout();
433 this->sock->OnError(I_ERR_TIMEOUT);
434 this->sock->timeout = true;
435 ServerInstance->SE->DelFd(this->sock);
436 /* NOTE: We must set this AFTER DelFd, as we added
437 * this socket whilst writeable. This means that we
438 * must DELETE the socket whilst writeable too!
440 this->sock->state = I_ERROR;
447 bool InspSocket::Poll()
449 if (this->Instance->SE->GetRef(this->fd) != this)
454 if ((fd < 0) || (fd > MAX_DESCRIPTORS))
460 /* Our socket was in write-state, so delete it and re-add it
465 this->Instance->SE->DelFd(this);
466 this->SetState(I_CONNECTED);
467 if (!this->Instance->SE->AddFd(this))
470 if (Instance->Config->GetIOHook(this))
474 Instance->Config->GetIOHook(this)->OnRawSocketConnect(this->fd);
476 catch (CoreException& modexcept)
478 Instance->Log(DEBUG,"%s threw an exception: %s", modexcept.GetSource(), modexcept.GetReason());
481 return this->OnConnected();
484 length = sizeof (client);
485 incoming = accept (this->fd, (sockaddr*)&client,&length);
488 this->OnIncomingConnection(incoming, (char*)insp_ntoa(client.sin6_addr));
490 this->OnIncomingConnection(incoming, (char*)insp_ntoa(client.sin_addr));
493 if (this->IsIOHooked)
498 Instance->Config->GetIOHook(this)->OnRawSocketAccept(incoming, insp_ntoa(client.sin6_addr), this->port);
500 Instance->Config->GetIOHook(this)->OnRawSocketAccept(incoming, insp_ntoa(client.sin_addr), this->port);
503 catch (CoreException& modexcept)
505 Instance->Log(DEBUG,"%s threw an exception: %s", modexcept.GetSource(), modexcept.GetReason());
509 this->SetQueues(incoming);
513 /* Process the read event */
514 return this->OnDataReady();
522 void InspSocket::SetState(InspSocketState s)
527 InspSocketState InspSocket::GetState()
532 int InspSocket::GetFd()
537 bool InspSocket::OnConnected() { return true; }
538 void InspSocket::OnError(InspSocketError e) { return; }
539 int InspSocket::OnDisconnect() { return 0; }
540 int InspSocket::OnIncomingConnection(int newfd, char* ip) { return 0; }
541 bool InspSocket::OnDataReady() { return true; }
542 bool InspSocket::OnWriteReady() { return true; }
543 void InspSocket::OnTimeout() { return; }
544 void InspSocket::OnClose() { return; }
546 InspSocket::~InspSocket()
551 void InspSocket::HandleEvent(EventType et, int errornum)
556 this->Instance->SE->DelFd(this);
564 this->Instance->SE->DelFd(this);
571 if (this->WaitingForWriteEvent)
573 this->WaitingForWriteEvent = false;
574 if (!this->OnWriteReady())
576 this->Instance->SE->DelFd(this);
582 if (this->state == I_CONNECTING)
584 /* This might look wrong as if we should be actually calling
585 * with EVENT_WRITE, but trust me it is correct. There are some
586 * writeability-state things in the read code, because of how
587 * InspSocket used to work regarding write buffering in previous
588 * versions of InspIRCd. - Brain
590 this->HandleEvent(EVENT_READ);
595 if (this->FlushWriteBuffer())
597 this->Instance->SE->DelFd(this);