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;
40 InspSocket::InspSocket(InspIRCd* SI, int newfd, const char* ip)
43 this->state = I_CONNECTED;
44 strlcpy(this->IP,ip,MAXBUF);
45 this->WaitingForWriteEvent = false;
48 this->Instance->SE->AddFd(this);
51 InspSocket::InspSocket(InspIRCd* SI, const std::string &ipaddr, int aport, bool listening, unsigned long maxtime)
55 strlcpy(host,ipaddr.c_str(),MAXBUF);
56 this->WaitingForWriteEvent = 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()
260 shutdown(this->fd,2);
265 std::string InspSocket::GetIP()
270 char* InspSocket::Read()
272 if ((fd < 0) || (fd > MAX_DESCRIPTORS))
274 int n = recv(this->fd,this->ibuf,sizeof(this->ibuf),0);
275 if ((n > 0) && (n <= (int)sizeof(this->ibuf)))
290 this->Instance->Log(DEBUG,"EOF or error on socket: EOF");
292 this->Instance->Log(DEBUG,"EOF or error on socket: %s",strerror(err));
298 void InspSocket::MarkAsClosed()
300 this->Instance->Log(DEBUG,"Marked as closed");
303 // There are two possible outcomes to this function.
304 // It will either write all of the data, or an undefined amount.
305 // If an undefined amount is written the connection has failed
306 // and should be aborted.
307 int InspSocket::Write(const std::string &data)
309 /* Try and append the data to the back of the queue, and send it on its way
311 outbuffer.push_back(data);
312 this->Instance->SE->WantWrite(this);
313 return (!this->FlushWriteBuffer());
316 bool InspSocket::FlushWriteBuffer()
319 if ((this->fd > -1) && (this->state == I_CONNECTED))
321 /* If we have multiple lines, try to send them all,
322 * not just the first one -- Brain
324 while (outbuffer.size() && (errno != EAGAIN))
327 int result = write(this->fd,outbuffer[0].c_str(),outbuffer[0].length());
330 if ((unsigned int)result == outbuffer[0].length())
332 /* The whole block was written (usually a line)
333 * Pop the block off the front of the queue,
334 * dont set errno, because we are clear of errors
335 * and want to try and write the next block too.
337 outbuffer.pop_front();
341 std::string temp = outbuffer[0].substr(result);
343 /* We didnt get the whole line out. arses.
344 * Try again next time, i guess. Set errno,
345 * because we shouldnt be writing any more now,
346 * until the socketengine says its safe to do so.
351 else if ((result == -1) && (errno != EAGAIN))
353 this->Instance->Log(DEBUG,"Write error on socket: %s",strerror(errno));
354 this->OnError(I_ERR_WRITE);
355 this->state = I_ERROR;
356 this->Instance->SE->DelFd(this);
363 if ((errno == EAGAIN) && (fd > -1))
365 this->Instance->SE->WantWrite(this);
371 void SocketTimeout::Tick(time_t now)
373 if (ServerInstance->SE->GetRef(this->sfd) != this->sock)
375 ServerInstance->Log(DEBUG,"Our socket has been deleted before the timeout was reached.");
379 if (this->sock->state == I_CONNECTING)
381 ServerInstance->Log(DEBUG,"Timed out, current=%lu",now);
382 // for non-listening sockets, the timeout can occur
383 // which causes termination of the connection after
384 // the given number of seconds without a successful
386 this->sock->OnTimeout();
387 this->sock->OnError(I_ERR_TIMEOUT);
388 this->sock->timeout = true;
389 ServerInstance->SE->DelFd(this->sock);
390 /* NOTE: We must set this AFTER DelFd, as we added
391 * this socket whilst writeable. This means that we
392 * must DELETE the socket whilst writeable too!
394 this->sock->state = I_ERROR;
401 bool InspSocket::Poll()
403 if (this->Instance->SE->GetRef(this->fd) != this)
408 if ((fd < 0) || (fd > MAX_DESCRIPTORS))
414 this->Instance->Log(DEBUG,"State = I_CONNECTING");
415 /* Our socket was in write-state, so delete it and re-add it
420 this->Instance->SE->DelFd(this);
421 this->SetState(I_CONNECTED);
422 if (!this->Instance->SE->AddFd(this))
425 return this->OnConnected();
428 length = sizeof (client);
429 incoming = accept (this->fd, (sockaddr*)&client,&length);
430 this->SetQueues(incoming);
432 this->OnIncomingConnection(incoming,(char*)insp_ntoa(client.sin6_addr));
434 this->OnIncomingConnection(incoming,(char*)insp_ntoa(client.sin_addr));
439 /* Process the read event */
440 return this->OnDataReady();
448 void InspSocket::SetState(InspSocketState s)
450 this->Instance->Log(DEBUG,"Socket state change");
454 InspSocketState InspSocket::GetState()
459 int InspSocket::GetFd()
464 bool InspSocket::OnConnected() { return true; }
465 void InspSocket::OnError(InspSocketError e) { return; }
466 int InspSocket::OnDisconnect() { return 0; }
467 int InspSocket::OnIncomingConnection(int newfd, char* ip) { return 0; }
468 bool InspSocket::OnDataReady() { return true; }
469 bool InspSocket::OnWriteReady() { return true; }
470 void InspSocket::OnTimeout() { return; }
471 void InspSocket::OnClose() { return; }
473 InspSocket::~InspSocket()
478 void InspSocket::HandleEvent(EventType et, int errornum)
487 this->Instance->SE->DelFd(this);
494 if (this->WaitingForWriteEvent)
496 this->WaitingForWriteEvent = false;
497 if (!this->OnWriteReady())
499 this->Instance->SE->DelFd(this);
505 if (this->state == I_CONNECTING)
507 /* This might look wrong as if we should be actually calling
508 * with EVENT_WRITE, but trust me it is correct. There are some
509 * writeability-state things in the read code, because of how
510 * InspSocket used to work regarding write buffering in previous
511 * versions of InspIRCd. - Brain
513 this->HandleEvent(EVENT_READ);
518 Instance->Log(DEBUG,"State=%d CONNECTED=%d", this->state, I_CONNECTED);
519 if (this->FlushWriteBuffer())
521 this->Instance->SE->DelFd(this);