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 "helperfuncs.h"
27 #include "socketengine.h"
30 using irc::sockets::OpenTCPSocket;
31 using irc::sockets::insp_inaddr;
32 using irc::sockets::insp_sockaddr;
35 extern Server* MyServer;
37 InspSocket::InspSocket(InspIRCd* SI)
39 this->state = I_DISCONNECTED;
41 this->ClosePending = false;
45 InspSocket::InspSocket(InspIRCd* SI, int newfd, const char* ip)
48 this->state = I_CONNECTED;
49 strlcpy(this->IP,ip,MAXBUF);
50 this->ClosePending = false;
54 this->ClosePending = (!this->Instance->SE->AddFd(this->fd,true,X_ESTAB_MODULE));
55 this->Instance->socket_ref[this->fd] = this;
59 InspSocket::InspSocket(InspIRCd* SI, const std::string &ipaddr, int aport, bool listening, unsigned long maxtime) : fd(-1)
62 strlcpy(host,ipaddr.c_str(),MAXBUF);
63 this->ClosePending = false;
65 if ((this->fd = OpenTCPSocket()) == ERROR)
68 this->state = I_ERROR;
69 this->OnError(I_ERR_SOCKET);
70 this->ClosePending = true;
71 log(DEBUG,"OpenTCPSocket() error");
76 if (!SI->BindSocket(this->fd,this->client,this->server,aport,(char*)ipaddr.c_str()))
78 log(DEBUG,"BindSocket() error %s",strerror(errno));
81 this->state = I_ERROR;
82 this->OnError(I_ERR_BIND);
83 this->ClosePending = true;
88 this->state = I_LISTENING;
91 if (!this->Instance->SE->AddFd(this->fd,true,X_ESTAB_MODULE))
94 this->state = I_ERROR;
95 this->OnError(I_ERR_NOMOREFDS);
96 this->ClosePending = true;
98 this->Instance->socket_ref[this->fd] = this;
100 log(DEBUG,"New socket now in I_LISTENING state");
107 strlcpy(this->host,ipaddr.c_str(),MAXBUF);
110 if (insp_aton(host,&addy) < 1)
112 log(DEBUG,"You cannot pass hostnames to InspSocket, resolve them first with Resolver!");
115 this->state = I_ERROR;
116 this->OnError(I_ERR_RESOLVE);
117 this->ClosePending = true;
122 log(DEBUG,"No need to resolve %s",this->host);
123 strlcpy(this->IP,host,MAXBUF);
124 timeout_end = time(NULL) + maxtime;
130 void InspSocket::WantWrite()
133 * The socket engine may only have each FD in the list ONCE.
134 * This means we cant watch for write AND read at the same
135 * time. We have to remove the READ fd, to insert the WRITE
136 * fd. Once we receive our WRITE event (which WILL ARRIVE,
137 * pretty much gauranteed) we switch back to watching for
140 * This behaviour may be fixed in a later version.
142 this->WaitingForWriteEvent = true;
143 this->Instance->SE->DelFd(this->fd);
144 if (!this->Instance->SE->AddFd(this->fd,false,X_ESTAB_MODULE))
148 this->state = I_ERROR;
149 this->OnError(I_ERR_NOMOREFDS);
150 this->ClosePending = true;
154 void InspSocket::SetQueues(int nfd)
156 // attempt to increase socket sendq and recvq as high as its possible
159 setsockopt(nfd,SOL_SOCKET,SO_SNDBUF,(const void *)&sendbuf,sizeof(sendbuf));
160 setsockopt(nfd,SOL_SOCKET,SO_RCVBUF,(const void *)&recvbuf,sizeof(sendbuf));
163 /* Most irc servers require you to specify the ip you want to bind to.
164 * If you dont specify an IP, they rather dumbly bind to the first IP
165 * of the box (e.g. INADDR_ANY). In InspIRCd, we scan thought the IP
166 * addresses we've bound server ports to, and we try and bind our outbound
167 * connections to the first usable non-loopback and non-any IP we find.
168 * This is easier to configure when you have a lot of links and a lot
169 * of servers to configure.
171 bool InspSocket::BindAddr()
176 log(DEBUG,"In InspSocket::BindAddr()");
177 for (int j =0; j < Conf.Enumerate("bind"); j++)
179 std::string Type = Conf.ReadValue("bind","type",j);
180 std::string IP = Conf.ReadValue("bind","address",j);
181 if (Type == "servers")
183 if ((IP != "*") && (IP != "127.0.0.1") && (IP != ""))
187 if (insp_aton(IP.c_str(),&n) > 0)
189 log(DEBUG,"Found an IP to bind to: %s",IP.c_str());
192 s.sin6_family = AF_FAMILY;
195 s.sin_family = AF_FAMILY;
197 if (bind(this->fd,(struct sockaddr*)&s,sizeof(s)) < 0)
199 log(DEBUG,"Cant bind()");
200 this->state = I_ERROR;
201 this->OnError(I_ERR_BIND);
205 log(DEBUG,"bind() reports outbound fd bound to ip %s",IP.c_str());
210 log(DEBUG,"Address '%s' was not an IP address",IP.c_str());
215 log(DEBUG,"Found no suitable IPs to bind, binding INADDR_ANY");
219 bool InspSocket::DoConnect()
221 log(DEBUG,"In DoConnect()");
222 if ((this->fd = socket(AF_FAMILY, SOCK_STREAM, 0)) == -1)
224 log(DEBUG,"Cant socket()");
225 this->state = I_ERROR;
226 this->OnError(I_ERR_SOCKET);
231 if ((strstr(this->IP,"::ffff:") != (char*)&this->IP) && (strstr(this->IP,"::FFFF:") != (char*)&this->IP))
233 if (!this->BindAddr())
237 log(DEBUG,"Part 2 DoConnect() %s",this->IP);
238 insp_aton(this->IP,&addy);
240 addr.sin6_family = AF_FAMILY;
241 memcpy(&addr.sin6_addr, &addy, sizeof(insp_inaddr));
242 addr.sin6_port = htons(this->port);
244 addr.sin_family = AF_FAMILY;
245 addr.sin_addr = addy;
246 addr.sin_port = htons(this->port);
250 flags = fcntl(this->fd, F_GETFL, 0);
251 fcntl(this->fd, F_SETFL, flags | O_NONBLOCK);
253 if (connect(this->fd, (sockaddr*)&this->addr,sizeof(this->addr)) == -1)
255 if (errno != EINPROGRESS)
257 log(DEBUG,"Error connect() %d: %s",this->fd,strerror(errno));
258 this->OnError(I_ERR_CONNECT);
260 this->state = I_ERROR;
262 this->ClosePending = true;
266 this->state = I_CONNECTING;
269 if (!this->Instance->SE->AddFd(this->fd,false,X_ESTAB_MODULE))
271 this->OnError(I_ERR_NOMOREFDS);
274 this->state = I_ERROR;
275 this->ClosePending = true;
278 this->Instance->socket_ref[this->fd] = this;
279 this->SetQueues(this->fd);
281 log(DEBUG,"Returning true from InspSocket::DoConnect");
286 void InspSocket::Close()
291 shutdown(this->fd,2);
293 this->Instance->socket_ref[this->fd] = NULL;
294 this->ClosePending = true;
299 std::string InspSocket::GetIP()
304 char* InspSocket::Read()
306 if ((fd < 0) || (fd > MAX_DESCRIPTORS))
308 int n = recv(this->fd,this->ibuf,sizeof(this->ibuf),0);
309 if ((n > 0) && (n <= (int)sizeof(this->ibuf)))
322 log(DEBUG,"EOF or error on socket: %s",strerror(errno));
328 void InspSocket::MarkAsClosed()
330 log(DEBUG,"Marked as closed");
331 this->ClosePending = true;
334 // There are two possible outcomes to this function.
335 // It will either write all of the data, or an undefined amount.
336 // If an undefined amount is written the connection has failed
337 // and should be aborted.
338 int InspSocket::Write(const std::string &data)
340 if (this->ClosePending)
343 /*int result = write(this->fd,data.c_str(),data.length());
348 /* Try and append the data to the back of the queue, and send it on its way
350 outbuffer.push_back(data);
351 return (!this->FlushWriteBuffer());
354 bool InspSocket::FlushWriteBuffer()
356 if (this->ClosePending)
359 if ((this->fd > -1) && (this->state == I_CONNECTED))
361 if (outbuffer.size())
363 int result = write(this->fd,outbuffer[0].c_str(),outbuffer[0].length());
366 if ((unsigned int)result == outbuffer[0].length())
368 /* The whole block was written (usually a line)
369 * Pop the block off the front of the queue
371 outbuffer.pop_front();
375 std::string temp = outbuffer[0].substr(result);
379 else if ((result == -1) && (errno != EAGAIN))
381 log(DEBUG,"Write error on socket: %s",strerror(errno));
382 this->OnError(I_ERR_WRITE);
383 this->state = I_ERROR;
384 this->ClosePending = true;
392 bool InspSocket::Timeout(time_t current)
394 if (!this->Instance->socket_ref[this->fd] || !this->Instance->SE->HasFd(this->fd))
396 log(DEBUG,"No FD or socket ref");
400 if (this->ClosePending)
402 log(DEBUG,"Close is pending");
406 if ((this->state == I_CONNECTING) && (current > timeout_end))
408 log(DEBUG,"Timed out, current=%lu timeout_end=%lu");
409 // for non-listening sockets, the timeout can occur
410 // which causes termination of the connection after
411 // the given number of seconds without a successful
414 this->OnError(I_ERR_TIMEOUT);
416 this->state = I_ERROR;
417 this->ClosePending = true;
420 return this->FlushWriteBuffer();
423 bool InspSocket::Poll()
425 if (!this->Instance->socket_ref[this->fd] || !this->Instance->SE->HasFd(this->fd))
431 if ((fd < 0) || (fd > MAX_DESCRIPTORS) || (this->ClosePending))
437 log(DEBUG,"State = I_CONNECTING");
438 this->SetState(I_CONNECTED);
439 /* Our socket was in write-state, so delete it and re-add it
444 this->Instance->SE->DelFd(this->fd);
445 if (!this->Instance->SE->AddFd(this->fd,true,X_ESTAB_MODULE))
448 return this->OnConnected();
451 length = sizeof (client);
452 incoming = accept (this->fd, (sockaddr*)&client,&length);
453 this->SetQueues(incoming);
455 this->OnIncomingConnection(incoming,(char*)insp_ntoa(client.sin6_addr));
457 this->OnIncomingConnection(incoming,(char*)insp_ntoa(client.sin_addr));
463 if (this->WaitingForWriteEvent)
465 /* Switch back to read events */
466 this->Instance->SE->DelFd(this->fd);
467 if (!this->Instance->SE->AddFd(this->fd,true,X_ESTAB_MODULE))
470 /* Trigger the write event */
471 n = this->OnWriteReady();
475 /* Process the read event */
476 n = this->OnDataReady();
478 /* Flush any pending, but not till after theyre done with the event
479 * so there are less write calls involved.
480 * Both FlushWriteBuffer AND the return result of OnDataReady must
481 * return true for this to be ok.
483 if (this->FlushWriteBuffer())
493 void InspSocket::SetState(InspSocketState s)
495 log(DEBUG,"Socket state change");
499 InspSocketState InspSocket::GetState()
504 int InspSocket::GetFd()
509 bool InspSocket::OnConnected() { return true; }
510 void InspSocket::OnError(InspSocketError e) { return; }
511 int InspSocket::OnDisconnect() { return 0; }
512 int InspSocket::OnIncomingConnection(int newfd, char* ip) { return 0; }
513 bool InspSocket::OnDataReady() { return true; }
514 bool InspSocket::OnWriteReady() { return true; }
515 void InspSocket::OnTimeout() { return; }
516 void InspSocket::OnClose() { return; }
518 InspSocket::~InspSocket()