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 * ---------------------------------------------------
22 #include "inspircd_config.h"
24 #include "configreader.h"
25 #include "inspstring.h"
26 #include "socketengine.h"
29 using irc::sockets::OpenTCPSocket;
30 using irc::sockets::insp_inaddr;
31 using irc::sockets::insp_sockaddr;
33 bool InspSocket::Readable()
35 return ((this->state != I_CONNECTING) && (this->WaitingForWriteEvent == false));
38 InspSocket::InspSocket(InspIRCd* SI)
40 this->state = I_DISCONNECTED;
42 this->WaitingForWriteEvent = false;
46 InspSocket::InspSocket(InspIRCd* SI, int newfd, const char* ip)
49 this->state = I_CONNECTED;
50 strlcpy(this->IP,ip,MAXBUF);
51 this->WaitingForWriteEvent = false;
54 this->Instance->SE->AddFd(this);
57 InspSocket::InspSocket(InspIRCd* SI, const std::string &ipaddr, int aport, bool listening, unsigned long maxtime)
61 strlcpy(host,ipaddr.c_str(),MAXBUF);
62 this->WaitingForWriteEvent = false;
65 if ((this->fd = OpenTCPSocket()) == ERROR)
68 this->state = I_ERROR;
69 this->OnError(I_ERR_SOCKET);
70 this->Instance->Log(DEBUG,"OpenTCPSocket() error");
75 if (!SI->BindSocket(this->fd,this->client,this->server,aport,(char*)ipaddr.c_str()))
77 this->Instance->Log(DEBUG,"BindSocket() error %s",strerror(errno));
80 this->state = I_ERROR;
81 this->OnError(I_ERR_BIND);
82 this->ClosePending = true;
87 this->state = I_LISTENING;
90 if (!this->Instance->SE->AddFd(this))
93 this->state = I_ERROR;
94 this->OnError(I_ERR_NOMOREFDS);
97 this->Instance->Log(DEBUG,"New socket now in I_LISTENING state");
104 strlcpy(this->host,ipaddr.c_str(),MAXBUF);
107 if (insp_aton(host,&addy) < 1)
109 this->Instance->Log(DEBUG,"You cannot pass hostnames to InspSocket, resolve them first with Resolver!");
112 this->state = I_ERROR;
113 this->OnError(I_ERR_RESOLVE);
118 this->Instance->Log(DEBUG,"No need to resolve %s",this->host);
119 strlcpy(this->IP,host,MAXBUF);
120 timeout_val = maxtime;
126 void InspSocket::WantWrite()
129 * The socket engine may only have each FD in the list ONCE.
130 * This means we cant watch for write AND read at the same
131 * time. We have to remove the READ fd, to insert the WRITE
132 * fd. Once we receive our WRITE event (which WILL ARRIVE,
133 * pretty much gauranteed) we switch back to watching for
136 * This behaviour may be fixed in a later version.
138 this->Instance->SE->DelFd(this);
139 this->WaitingForWriteEvent = true;
140 if (!this->Instance->SE->AddFd(this))
144 this->state = I_ERROR;
145 this->OnError(I_ERR_NOMOREFDS);
149 void InspSocket::SetQueues(int nfd)
151 // attempt to increase socket sendq and recvq as high as its possible
154 setsockopt(nfd,SOL_SOCKET,SO_SNDBUF,(const void *)&sendbuf,sizeof(sendbuf));
155 setsockopt(nfd,SOL_SOCKET,SO_RCVBUF,(const void *)&recvbuf,sizeof(sendbuf));
158 /* Most irc servers require you to specify the ip you want to bind to.
159 * If you dont specify an IP, they rather dumbly bind to the first IP
160 * of the box (e.g. INADDR_ANY). In InspIRCd, we scan thought the IP
161 * addresses we've bound server ports to, and we try and bind our outbound
162 * connections to the first usable non-loopback and non-any IP we find.
163 * This is easier to configure when you have a lot of links and a lot
164 * of servers to configure.
166 bool InspSocket::BindAddr()
169 ConfigReader Conf(this->Instance);
171 this->Instance->Log(DEBUG,"In InspSocket::BindAddr()");
172 for (int j =0; j < Conf.Enumerate("bind"); j++)
174 std::string Type = Conf.ReadValue("bind","type",j);
175 std::string IP = Conf.ReadValue("bind","address",j);
176 if (Type == "servers")
178 if ((IP != "*") && (IP != "127.0.0.1") && (IP != ""))
182 if (insp_aton(IP.c_str(),&n) > 0)
184 this->Instance->Log(DEBUG,"Found an IP to bind to: %s",IP.c_str());
187 s.sin6_family = AF_FAMILY;
190 s.sin_family = AF_FAMILY;
192 if (bind(this->fd,(struct sockaddr*)&s,sizeof(s)) < 0)
194 this->Instance->Log(DEBUG,"Cant bind()");
195 this->state = I_ERROR;
196 this->OnError(I_ERR_BIND);
200 this->Instance->Log(DEBUG,"bind() reports outbound fd bound to ip %s",IP.c_str());
205 this->Instance->Log(DEBUG,"Address '%s' was not an IP address",IP.c_str());
210 this->Instance->Log(DEBUG,"Found no suitable IPs to bind, binding INADDR_ANY");
214 bool InspSocket::DoConnect()
216 this->Instance->Log(DEBUG,"In DoConnect()");
217 if ((this->fd = socket(AF_FAMILY, SOCK_STREAM, 0)) == -1)
219 this->Instance->Log(DEBUG,"Cant socket()");
220 this->state = I_ERROR;
221 this->OnError(I_ERR_SOCKET);
225 if ((strstr(this->IP,"::ffff:") != (char*)&this->IP) && (strstr(this->IP,"::FFFF:") != (char*)&this->IP))
227 if (!this->BindAddr())
231 this->Instance->Log(DEBUG,"Part 2 DoConnect() %s",this->IP);
232 insp_aton(this->IP,&addy);
234 addr.sin6_family = AF_FAMILY;
235 memcpy(&addr.sin6_addr, &addy, sizeof(insp_inaddr));
236 addr.sin6_port = htons(this->port);
238 addr.sin_family = AF_FAMILY;
239 addr.sin_addr = addy;
240 addr.sin_port = htons(this->port);
244 flags = fcntl(this->fd, F_GETFL, 0);
245 fcntl(this->fd, F_SETFL, flags | O_NONBLOCK);
247 if (connect(this->fd, (sockaddr*)&this->addr,sizeof(this->addr)) == -1)
249 if (errno != EINPROGRESS)
251 this->Instance->Log(DEBUG,"Error connect() %d: %s",this->fd,strerror(errno));
252 this->OnError(I_ERR_CONNECT);
254 this->state = I_ERROR;
258 this->Timeout = new SocketTimeout(this->GetFd(), this->Instance, this, timeout_val, this->Instance->Time());
259 this->Instance->Timers->AddTimer(this->Timeout);
261 this->state = I_CONNECTING;
264 if (!this->Instance->SE->AddFd(this))
266 this->OnError(I_ERR_NOMOREFDS);
268 this->state = I_ERROR;
271 this->SetQueues(this->fd);
273 this->Instance->Log(DEBUG,"Returning true from InspSocket::DoConnect");
278 void InspSocket::Close()
283 shutdown(this->fd,2);
288 std::string InspSocket::GetIP()
293 char* InspSocket::Read()
295 if ((fd < 0) || (fd > MAX_DESCRIPTORS))
297 int n = recv(this->fd,this->ibuf,sizeof(this->ibuf),0);
298 if ((n > 0) && (n <= (int)sizeof(this->ibuf)))
313 this->Instance->Log(DEBUG,"EOF or error on socket: EOF");
315 this->Instance->Log(DEBUG,"EOF or error on socket: %s",strerror(err));
321 void InspSocket::MarkAsClosed()
323 this->Instance->Log(DEBUG,"Marked as closed");
326 // There are two possible outcomes to this function.
327 // It will either write all of the data, or an undefined amount.
328 // If an undefined amount is written the connection has failed
329 // and should be aborted.
330 int InspSocket::Write(const std::string &data)
332 /* Try and append the data to the back of the queue, and send it on its way
334 outbuffer.push_back(data);
335 return (!this->FlushWriteBuffer());
338 bool InspSocket::FlushWriteBuffer()
340 if ((this->fd > -1) && (this->state == I_CONNECTED))
342 if (outbuffer.size())
344 int result = write(this->fd,outbuffer[0].c_str(),outbuffer[0].length());
347 if ((unsigned int)result == outbuffer[0].length())
349 /* The whole block was written (usually a line)
350 * Pop the block off the front of the queue
352 outbuffer.pop_front();
356 std::string temp = outbuffer[0].substr(result);
360 else if ((result == -1) && (errno != EAGAIN))
362 this->Instance->Log(DEBUG,"Write error on socket: %s",strerror(errno));
363 this->OnError(I_ERR_WRITE);
364 this->state = I_ERROR;
372 void SocketTimeout::Tick(time_t now)
374 if (ServerInstance->SE->GetRef(this->sfd) != this->sock)
376 ServerInstance->Log(DEBUG,"No FD or socket ref");
380 if (this->sock->state == I_CONNECTING)
382 ServerInstance->Log(DEBUG,"Timed out, current=%lu",now);
383 // for non-listening sockets, the timeout can occur
384 // which causes termination of the connection after
385 // the given number of seconds without a successful
387 this->sock->OnTimeout();
388 this->sock->OnError(I_ERR_TIMEOUT);
389 this->sock->timeout = true;
390 this->sock->state = I_ERROR;
391 ServerInstance->SE->DelFd(this->sock);
396 this->sock->FlushWriteBuffer();
399 bool InspSocket::Poll()
401 if (this->Instance->SE->GetRef(this->fd) != this)
407 if ((fd < 0) || (fd > MAX_DESCRIPTORS))
413 this->Instance->Log(DEBUG,"State = I_CONNECTING");
414 /* Our socket was in write-state, so delete it and re-add it
419 this->Instance->SE->DelFd(this);
420 this->SetState(I_CONNECTED);
421 if (!this->Instance->SE->AddFd(this))
424 return this->OnConnected();
427 length = sizeof (client);
428 incoming = accept (this->fd, (sockaddr*)&client,&length);
429 this->SetQueues(incoming);
431 this->OnIncomingConnection(incoming,(char*)insp_ntoa(client.sin6_addr));
433 this->OnIncomingConnection(incoming,(char*)insp_ntoa(client.sin_addr));
439 if (this->WaitingForWriteEvent)
441 /* Switch back to read events */
442 this->Instance->SE->DelFd(this);
443 this->WaitingForWriteEvent = false;
444 if (!this->Instance->SE->AddFd(this))
447 /* Trigger the write event */
448 n = this->OnWriteReady();
452 /* Process the read event */
453 n = this->OnDataReady();
455 /* Flush any pending, but not till after theyre done with the event
456 * so there are less write calls involved.
457 * Both FlushWriteBuffer AND the return result of OnDataReady must
458 * return true for this to be ok.
460 if (this->FlushWriteBuffer())
470 void InspSocket::SetState(InspSocketState s)
472 this->Instance->Log(DEBUG,"Socket state change");
476 InspSocketState InspSocket::GetState()
481 int InspSocket::GetFd()
486 bool InspSocket::OnConnected() { return true; }
487 void InspSocket::OnError(InspSocketError e) { return; }
488 int InspSocket::OnDisconnect() { return 0; }
489 int InspSocket::OnIncomingConnection(int newfd, char* ip) { return 0; }
490 bool InspSocket::OnDataReady() { return true; }
491 bool InspSocket::OnWriteReady() { return true; }
492 void InspSocket::OnTimeout() { return; }
493 void InspSocket::OnClose() { return; }
495 InspSocket::~InspSocket()
500 void InspSocket::HandleEvent(EventType et)
504 this->Instance->SE->DelFd(this);