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(host)) == ERROR)
62 this->state = I_ERROR;
63 this->OnError(I_ERR_SOCKET);
68 if (!SI->BindSocket(this->fd,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 != "") && (IP != "::1"))
153 if (insp_aton(IP.c_str(),&n) > 0)
156 memcpy(&s.sin6_addr, &n, sizeof(n));
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(addy));
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);
203 int flags = fcntl(this->fd, F_GETFL, 0);
204 fcntl(this->fd, F_SETFL, flags | O_NONBLOCK);
206 if (connect(this->fd, (sockaddr*)&this->addr,sizeof(this->addr)) == -1)
208 if (errno != EINPROGRESS)
210 this->OnError(I_ERR_CONNECT);
212 this->state = I_ERROR;
216 this->Timeout = new SocketTimeout(this->GetFd(), this->Instance, this, timeout_val, this->Instance->Time());
217 this->Instance->Timers->AddTimer(this->Timeout);
219 this->state = I_CONNECTING;
222 if (!this->Instance->SE->AddFd(this))
224 this->OnError(I_ERR_NOMOREFDS);
226 this->state = I_ERROR;
229 this->SetQueues(this->fd);
235 void InspSocket::Close()
237 /* Save this, so we dont lose it,
238 * otherise on failure, error messages
239 * might be inaccurate.
244 if (this->IsIOHooked && Instance->Config->GetIOHook(this))
248 Instance->Config->GetIOHook(this)->OnRawSocketClose(this->fd);
250 catch (CoreException& modexcept)
252 Instance->Log(DEFAULT,"%s threw an exception: %s", modexcept.GetSource(), modexcept.GetReason());
256 shutdown(this->fd,2);
262 std::string InspSocket::GetIP()
267 char* InspSocket::Read()
269 if ((fd < 0) || (fd > MAX_DESCRIPTORS))
274 if (this->IsIOHooked)
280 MOD_RESULT = Instance->Config->GetIOHook(this)->OnRawSocketRead(this->fd,this->ibuf,sizeof(this->ibuf),result2);
282 catch (CoreException& modexcept)
284 Instance->Log(DEFAULT,"%s threw an exception: %s", modexcept.GetSource(), modexcept.GetReason());
298 n = recv(this->fd,this->ibuf,sizeof(this->ibuf),0);
301 if ((n > 0) && (n <= (int)sizeof(this->ibuf)))
316 void InspSocket::MarkAsClosed()
320 // There are two possible outcomes to this function.
321 // It will either write all of the data, or an undefined amount.
322 // If an undefined amount is written the connection has failed
323 // and should be aborted.
324 int InspSocket::Write(const std::string &data)
326 /* Try and append the data to the back of the queue, and send it on its way
328 outbuffer.push_back(data);
329 this->Instance->SE->WantWrite(this);
330 return (!this->FlushWriteBuffer());
333 bool InspSocket::FlushWriteBuffer()
336 if ((this->fd > -1) && (this->state == I_CONNECTED))
338 if (this->IsIOHooked)
340 while (outbuffer.size() && (errno != EAGAIN))
344 int result = Instance->Config->GetIOHook(this)->OnRawSocketWrite(this->fd, outbuffer[0].c_str(), outbuffer[0].length());
347 if ((unsigned int)result == outbuffer[0].length())
349 outbuffer.pop_front();
353 std::string temp = outbuffer[0].substr(result);
358 else if (((result == -1) && (errno != EAGAIN)) || (result == 0))
360 this->OnError(I_ERR_WRITE);
361 this->state = I_ERROR;
362 this->Instance->SE->DelFd(this);
367 catch (CoreException& modexcept)
369 Instance->Log(DEBUG,"%s threw an exception: %s", modexcept.GetSource(), modexcept.GetReason());
376 /* If we have multiple lines, try to send them all,
377 * not just the first one -- Brain
379 while (outbuffer.size() && (errno != EAGAIN))
382 int result = write(this->fd,outbuffer[0].c_str(),outbuffer[0].length());
385 if ((unsigned int)result == outbuffer[0].length())
387 /* The whole block was written (usually a line)
388 * Pop the block off the front of the queue,
389 * dont set errno, because we are clear of errors
390 * and want to try and write the next block too.
392 outbuffer.pop_front();
396 std::string temp = outbuffer[0].substr(result);
398 /* We didnt get the whole line out. arses.
399 * Try again next time, i guess. Set errno,
400 * because we shouldnt be writing any more now,
401 * until the socketengine says its safe to do so.
406 else if ((result == -1) && (errno != EAGAIN))
408 this->OnError(I_ERR_WRITE);
409 this->state = I_ERROR;
410 this->Instance->SE->DelFd(this);
418 if ((errno == EAGAIN) && (fd > -1))
420 this->Instance->SE->WantWrite(this);
426 void SocketTimeout::Tick(time_t now)
428 if (ServerInstance->SE->GetRef(this->sfd) != this->sock)
431 if (this->sock->state == I_CONNECTING)
433 // for non-listening sockets, the timeout can occur
434 // which causes termination of the connection after
435 // the given number of seconds without a successful
437 this->sock->OnTimeout();
438 this->sock->OnError(I_ERR_TIMEOUT);
439 this->sock->timeout = true;
440 ServerInstance->SE->DelFd(this->sock);
441 /* NOTE: We must set this AFTER DelFd, as we added
442 * this socket whilst writeable. This means that we
443 * must DELETE the socket whilst writeable too!
445 this->sock->state = I_ERROR;
452 bool InspSocket::Poll()
454 if (this->Instance->SE->GetRef(this->fd) != this)
459 if ((fd < 0) || (fd > MAX_DESCRIPTORS))
465 /* Our socket was in write-state, so delete it and re-add it
470 this->Instance->SE->DelFd(this);
471 this->SetState(I_CONNECTED);
472 if (!this->Instance->SE->AddFd(this))
475 if (Instance->Config->GetIOHook(this))
479 Instance->Config->GetIOHook(this)->OnRawSocketConnect(this->fd);
481 catch (CoreException& modexcept)
483 Instance->Log(DEBUG,"%s threw an exception: %s", modexcept.GetSource(), modexcept.GetReason());
486 return this->OnConnected();
489 length = sizeof (client);
490 incoming = accept (this->fd, (sockaddr*)&client,&length);
493 this->OnIncomingConnection(incoming, (char*)insp_ntoa(client.sin6_addr));
495 this->OnIncomingConnection(incoming, (char*)insp_ntoa(client.sin_addr));
498 if (this->IsIOHooked)
503 Instance->Config->GetIOHook(this)->OnRawSocketAccept(incoming, insp_ntoa(client.sin6_addr), this->port);
505 Instance->Config->GetIOHook(this)->OnRawSocketAccept(incoming, insp_ntoa(client.sin_addr), this->port);
508 catch (CoreException& modexcept)
510 Instance->Log(DEBUG,"%s threw an exception: %s", modexcept.GetSource(), modexcept.GetReason());
514 this->SetQueues(incoming);
518 /* Process the read event */
519 return this->OnDataReady();
527 void InspSocket::SetState(InspSocketState s)
532 InspSocketState InspSocket::GetState()
537 int InspSocket::GetFd()
542 bool InspSocket::OnConnected() { return true; }
543 void InspSocket::OnError(InspSocketError e) { return; }
544 int InspSocket::OnDisconnect() { return 0; }
545 int InspSocket::OnIncomingConnection(int newfd, char* ip) { return 0; }
546 bool InspSocket::OnDataReady() { return true; }
547 bool InspSocket::OnWriteReady() { return true; }
548 void InspSocket::OnTimeout() { return; }
549 void InspSocket::OnClose() { return; }
551 InspSocket::~InspSocket()
556 void InspSocket::HandleEvent(EventType et, int errornum)
561 this->Instance->SE->DelFd(this);
569 this->Instance->SE->DelFd(this);
576 if (this->WaitingForWriteEvent)
578 this->WaitingForWriteEvent = false;
579 if (!this->OnWriteReady())
581 this->Instance->SE->DelFd(this);
587 if (this->state == I_CONNECTING)
589 /* This might look wrong as if we should be actually calling
590 * with EVENT_WRITE, but trust me it is correct. There are some
591 * writeability-state things in the read code, because of how
592 * InspSocket used to work regarding write buffering in previous
593 * versions of InspIRCd. - Brain
595 this->HandleEvent(EVENT_READ);
600 if (this->FlushWriteBuffer())
602 this->Instance->SE->DelFd(this);