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()
123 * The socket engine may only have each FD in the list ONCE.
124 * This means we cant watch for write AND read at the same
125 * time. We have to remove the READ fd, to insert the WRITE
126 * fd. Once we receive our WRITE event (which WILL ARRIVE,
127 * pretty much gauranteed) we switch back to watching for
130 * This behaviour may be fixed in a later version.
132 this->Instance->SE->WantWrite(this);
135 void InspSocket::SetQueues(int nfd)
137 // attempt to increase socket sendq and recvq as high as its possible
140 setsockopt(nfd,SOL_SOCKET,SO_SNDBUF,(const void *)&sendbuf,sizeof(sendbuf));
141 setsockopt(nfd,SOL_SOCKET,SO_RCVBUF,(const void *)&recvbuf,sizeof(sendbuf));
144 /* Most irc servers require you to specify the ip you want to bind to.
145 * If you dont specify an IP, they rather dumbly bind to the first IP
146 * of the box (e.g. INADDR_ANY). In InspIRCd, we scan thought the IP
147 * addresses we've bound server ports to, and we try and bind our outbound
148 * connections to the first usable non-loopback and non-any IP we find.
149 * This is easier to configure when you have a lot of links and a lot
150 * of servers to configure.
152 bool InspSocket::BindAddr()
155 ConfigReader Conf(this->Instance);
157 this->Instance->Log(DEBUG,"In InspSocket::BindAddr()");
158 for (int j =0; j < Conf.Enumerate("bind"); j++)
160 std::string Type = Conf.ReadValue("bind","type",j);
161 std::string IP = Conf.ReadValue("bind","address",j);
162 if (Type == "servers")
164 if ((IP != "*") && (IP != "127.0.0.1") && (IP != ""))
168 if (insp_aton(IP.c_str(),&n) > 0)
170 this->Instance->Log(DEBUG,"Found an IP to bind to: %s",IP.c_str());
173 s.sin6_family = AF_FAMILY;
176 s.sin_family = AF_FAMILY;
178 if (bind(this->fd,(struct sockaddr*)&s,sizeof(s)) < 0)
180 this->Instance->Log(DEBUG,"Cant bind()");
181 this->state = I_ERROR;
182 this->OnError(I_ERR_BIND);
186 this->Instance->Log(DEBUG,"bind() reports outbound fd bound to ip %s",IP.c_str());
191 this->Instance->Log(DEBUG,"Address '%s' was not an IP address",IP.c_str());
196 this->Instance->Log(DEBUG,"Found no suitable IPs to bind, binding INADDR_ANY");
200 bool InspSocket::DoConnect()
202 this->Instance->Log(DEBUG,"In DoConnect()");
203 if ((this->fd = socket(AF_FAMILY, SOCK_STREAM, 0)) == -1)
205 this->Instance->Log(DEBUG,"Cant socket()");
206 this->state = I_ERROR;
207 this->OnError(I_ERR_SOCKET);
211 if ((strstr(this->IP,"::ffff:") != (char*)&this->IP) && (strstr(this->IP,"::FFFF:") != (char*)&this->IP))
213 if (!this->BindAddr())
217 this->Instance->Log(DEBUG,"Part 2 DoConnect() %s",this->IP);
218 insp_aton(this->IP,&addy);
220 addr.sin6_family = AF_FAMILY;
221 memcpy(&addr.sin6_addr, &addy, sizeof(insp_inaddr));
222 addr.sin6_port = htons(this->port);
224 addr.sin_family = AF_FAMILY;
225 addr.sin_addr = addy;
226 addr.sin_port = htons(this->port);
230 flags = fcntl(this->fd, F_GETFL, 0);
231 fcntl(this->fd, F_SETFL, flags | O_NONBLOCK);
233 if (connect(this->fd, (sockaddr*)&this->addr,sizeof(this->addr)) == -1)
235 if (errno != EINPROGRESS)
237 this->Instance->Log(DEBUG,"Error connect() %d: %s",this->fd,strerror(errno));
238 this->OnError(I_ERR_CONNECT);
240 this->state = I_ERROR;
244 this->Timeout = new SocketTimeout(this->GetFd(), this->Instance, this, timeout_val, this->Instance->Time());
245 this->Instance->Timers->AddTimer(this->Timeout);
247 this->state = I_CONNECTING;
250 if (!this->Instance->SE->AddFd(this))
252 this->OnError(I_ERR_NOMOREFDS);
254 this->state = I_ERROR;
257 this->SetQueues(this->fd);
259 this->Instance->Log(DEBUG,"Returning true from InspSocket::DoConnect");
264 void InspSocket::Close()
269 shutdown(this->fd,2);
274 std::string InspSocket::GetIP()
279 char* InspSocket::Read()
281 if ((fd < 0) || (fd > MAX_DESCRIPTORS))
283 int n = recv(this->fd,this->ibuf,sizeof(this->ibuf),0);
284 if ((n > 0) && (n <= (int)sizeof(this->ibuf)))
299 this->Instance->Log(DEBUG,"EOF or error on socket: EOF");
301 this->Instance->Log(DEBUG,"EOF or error on socket: %s",strerror(err));
307 void InspSocket::MarkAsClosed()
309 this->Instance->Log(DEBUG,"Marked as closed");
312 // There are two possible outcomes to this function.
313 // It will either write all of the data, or an undefined amount.
314 // If an undefined amount is written the connection has failed
315 // and should be aborted.
316 int InspSocket::Write(const std::string &data)
318 /* Try and append the data to the back of the queue, and send it on its way
320 outbuffer.push_back(data);
321 return (!this->FlushWriteBuffer());
324 bool InspSocket::FlushWriteBuffer()
327 if ((this->fd > -1) && (this->state == I_CONNECTED))
329 /* If we have multiple lines, try to send them all,
330 * not just the first one -- Brain
332 while (outbuffer.size() && (errno != EAGAIN))
335 int result = write(this->fd,outbuffer[0].c_str(),outbuffer[0].length());
338 if ((unsigned int)result == outbuffer[0].length())
340 /* The whole block was written (usually a line)
341 * Pop the block off the front of the queue,
342 * dont set errno, because we are clear of errors
343 * and want to try and write the next block too.
345 outbuffer.pop_front();
349 std::string temp = outbuffer[0].substr(result);
351 /* We didnt get the whole line out. arses.
352 * Try again next time, i guess. Set errno,
353 * because we shouldnt be writing any more now,
354 * until the socketengine says its safe to do so.
359 else if ((result == -1) && (errno != EAGAIN))
361 this->Instance->Log(DEBUG,"Write error on socket: %s",strerror(errno));
362 this->OnError(I_ERR_WRITE);
363 this->state = I_ERROR;
364 this->Instance->SE->DelFd(this);
373 void SocketTimeout::Tick(time_t now)
375 if (ServerInstance->SE->GetRef(this->sfd) != this->sock)
377 ServerInstance->Log(DEBUG,"Our socket has been deleted before the timeout was reached.");
381 if (this->sock->state == I_CONNECTING)
383 ServerInstance->Log(DEBUG,"Timed out, current=%lu",now);
384 // for non-listening sockets, the timeout can occur
385 // which causes termination of the connection after
386 // the given number of seconds without a successful
388 this->sock->OnTimeout();
389 this->sock->OnError(I_ERR_TIMEOUT);
390 this->sock->timeout = true;
391 ServerInstance->SE->DelFd(this->sock);
392 /* NOTE: We must set this AFTER DelFd, as we added
393 * this socket whilst writeable. This means that we
394 * must DELETE the socket whilst writeable too!
396 this->sock->state = I_ERROR;
401 this->sock->FlushWriteBuffer();
404 bool InspSocket::Poll()
406 if (this->Instance->SE->GetRef(this->fd) != this)
412 if ((fd < 0) || (fd > MAX_DESCRIPTORS))
418 this->Instance->Log(DEBUG,"State = I_CONNECTING");
419 /* Our socket was in write-state, so delete it and re-add it
424 this->Instance->SE->DelFd(this);
425 this->SetState(I_CONNECTED);
426 if (!this->Instance->SE->AddFd(this))
429 return this->OnConnected();
432 length = sizeof (client);
433 incoming = accept (this->fd, (sockaddr*)&client,&length);
434 this->SetQueues(incoming);
436 this->OnIncomingConnection(incoming,(char*)insp_ntoa(client.sin6_addr));
438 this->OnIncomingConnection(incoming,(char*)insp_ntoa(client.sin_addr));
444 if (this->WaitingForWriteEvent)
446 /* Switch back to read events */
447 this->Instance->SE->DelFd(this);
448 this->WaitingForWriteEvent = false;
449 if (!this->Instance->SE->AddFd(this))
452 /* Trigger the write event */
453 n = this->OnWriteReady();
457 /* Process the read event */
458 n = this->OnDataReady();
460 /* Flush any pending, but not till after theyre done with the event
461 * so there are less write calls involved.
462 * Both FlushWriteBuffer AND the return result of OnDataReady must
463 * return true for this to be ok.
465 if (this->FlushWriteBuffer())
475 void InspSocket::SetState(InspSocketState s)
477 this->Instance->Log(DEBUG,"Socket state change");
481 InspSocketState InspSocket::GetState()
486 int InspSocket::GetFd()
491 bool InspSocket::OnConnected() { return true; }
492 void InspSocket::OnError(InspSocketError e) { return; }
493 int InspSocket::OnDisconnect() { return 0; }
494 int InspSocket::OnIncomingConnection(int newfd, char* ip) { return 0; }
495 bool InspSocket::OnDataReady() { return true; }
496 bool InspSocket::OnWriteReady() { return true; }
497 void InspSocket::OnTimeout() { return; }
498 void InspSocket::OnClose() { return; }
500 InspSocket::~InspSocket()
505 void InspSocket::HandleEvent(EventType et)
509 this->Instance->SE->DelFd(this);