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::BindSocket;
31 using irc::sockets::OpenTCPSocket;
32 using irc::sockets::insp_inaddr;
33 using irc::sockets::insp_sockaddr;
36 extern Server* MyServer;
38 InspSocket::InspSocket(InspIRCd* SI)
40 this->state = I_DISCONNECTED;
42 this->ClosePending = false;
46 InspSocket::InspSocket(InspIRCd* SI, int newfd, const char* ip)
49 this->state = I_CONNECTED;
50 strlcpy(this->IP,ip,MAXBUF);
51 this->ClosePending = false;
55 this->ClosePending = (!this->Instance->SE->AddFd(this->fd,true,X_ESTAB_MODULE));
56 this->Instance->socket_ref[this->fd] = this;
60 InspSocket::InspSocket(InspIRCd* SI, const std::string &ipaddr, int aport, bool listening, unsigned long maxtime) : fd(-1)
63 strlcpy(host,ipaddr.c_str(),MAXBUF);
64 this->ClosePending = false;
66 if ((this->fd = OpenTCPSocket()) == ERROR)
69 this->state = I_ERROR;
70 this->OnError(I_ERR_SOCKET);
71 this->ClosePending = true;
72 log(DEBUG,"OpenTCPSocket() error");
77 if (!BindSocket(this->fd,this->client,this->server,aport,(char*)ipaddr.c_str()))
79 log(DEBUG,"BindSocket() error %s",strerror(errno));
82 this->state = I_ERROR;
83 this->OnError(I_ERR_BIND);
84 this->ClosePending = true;
89 this->state = I_LISTENING;
92 if (!this->Instance->SE->AddFd(this->fd,true,X_ESTAB_MODULE))
95 this->state = I_ERROR;
96 this->OnError(I_ERR_NOMOREFDS);
97 this->ClosePending = true;
99 this->Instance->socket_ref[this->fd] = this;
101 log(DEBUG,"New socket now in I_LISTENING state");
108 strlcpy(this->host,ipaddr.c_str(),MAXBUF);
111 if (insp_aton(host,&addy) < 1)
113 log(DEBUG,"You cannot pass hostnames to InspSocket, resolve them first with Resolver!");
116 this->state = I_ERROR;
117 this->OnError(I_ERR_RESOLVE);
118 this->ClosePending = true;
123 log(DEBUG,"No need to resolve %s",this->host);
124 strlcpy(this->IP,host,MAXBUF);
125 timeout_end = time(NULL) + maxtime;
131 void InspSocket::WantWrite()
134 * The socket engine may only have each FD in the list ONCE.
135 * This means we cant watch for write AND read at the same
136 * time. We have to remove the READ fd, to insert the WRITE
137 * fd. Once we receive our WRITE event (which WILL ARRIVE,
138 * pretty much gauranteed) we switch back to watching for
141 * This behaviour may be fixed in a later version.
143 this->WaitingForWriteEvent = true;
144 this->Instance->SE->DelFd(this->fd);
145 if (!this->Instance->SE->AddFd(this->fd,false,X_ESTAB_MODULE))
149 this->state = I_ERROR;
150 this->OnError(I_ERR_NOMOREFDS);
151 this->ClosePending = true;
155 void InspSocket::SetQueues(int nfd)
157 // attempt to increase socket sendq and recvq as high as its possible
160 setsockopt(nfd,SOL_SOCKET,SO_SNDBUF,(const void *)&sendbuf,sizeof(sendbuf));
161 setsockopt(nfd,SOL_SOCKET,SO_RCVBUF,(const void *)&recvbuf,sizeof(sendbuf));
164 /* Most irc servers require you to specify the ip you want to bind to.
165 * If you dont specify an IP, they rather dumbly bind to the first IP
166 * of the box (e.g. INADDR_ANY). In InspIRCd, we scan thought the IP
167 * addresses we've bound server ports to, and we try and bind our outbound
168 * connections to the first usable non-loopback and non-any IP we find.
169 * This is easier to configure when you have a lot of links and a lot
170 * of servers to configure.
172 bool InspSocket::BindAddr()
177 log(DEBUG,"In InspSocket::BindAddr()");
178 for (int j =0; j < Conf.Enumerate("bind"); j++)
180 std::string Type = Conf.ReadValue("bind","type",j);
181 std::string IP = Conf.ReadValue("bind","address",j);
182 if (Type == "servers")
184 if ((IP != "*") && (IP != "127.0.0.1") && (IP != ""))
188 if (insp_aton(IP.c_str(),&n) > 0)
190 log(DEBUG,"Found an IP to bind to: %s",IP.c_str());
193 s.sin6_family = AF_FAMILY;
196 s.sin_family = AF_FAMILY;
198 if (bind(this->fd,(struct sockaddr*)&s,sizeof(s)) < 0)
200 log(DEBUG,"Cant bind()");
201 this->state = I_ERROR;
202 this->OnError(I_ERR_BIND);
206 log(DEBUG,"bind() reports outbound fd bound to ip %s",IP.c_str());
211 log(DEBUG,"Address '%s' was not an IP address",IP.c_str());
216 log(DEBUG,"Found no suitable IPs to bind, binding INADDR_ANY");
220 bool InspSocket::DoConnect()
222 log(DEBUG,"In DoConnect()");
223 if ((this->fd = socket(AF_FAMILY, SOCK_STREAM, 0)) == -1)
225 log(DEBUG,"Cant socket()");
226 this->state = I_ERROR;
227 this->OnError(I_ERR_SOCKET);
232 if ((strstr(this->IP,"::ffff:") != (char*)&this->IP) && (strstr(this->IP,"::FFFF:") != (char*)&this->IP))
234 if (!this->BindAddr())
238 log(DEBUG,"Part 2 DoConnect() %s",this->IP);
239 insp_aton(this->IP,&addy);
241 addr.sin6_family = AF_FAMILY;
242 memcpy(&addr.sin6_addr, &addy, sizeof(insp_inaddr));
243 addr.sin6_port = htons(this->port);
245 addr.sin_family = AF_FAMILY;
246 addr.sin_addr = addy;
247 addr.sin_port = htons(this->port);
251 flags = fcntl(this->fd, F_GETFL, 0);
252 fcntl(this->fd, F_SETFL, flags | O_NONBLOCK);
254 if (connect(this->fd, (sockaddr*)&this->addr,sizeof(this->addr)) == -1)
256 if (errno != EINPROGRESS)
258 log(DEBUG,"Error connect() %d: %s",this->fd,strerror(errno));
259 this->OnError(I_ERR_CONNECT);
261 this->state = I_ERROR;
263 this->ClosePending = true;
267 this->state = I_CONNECTING;
270 if (!this->Instance->SE->AddFd(this->fd,false,X_ESTAB_MODULE))
272 this->OnError(I_ERR_NOMOREFDS);
275 this->state = I_ERROR;
276 this->ClosePending = true;
279 this->Instance->socket_ref[this->fd] = this;
280 this->SetQueues(this->fd);
282 log(DEBUG,"Returning true from InspSocket::DoConnect");
287 void InspSocket::Close()
292 shutdown(this->fd,2);
294 this->Instance->socket_ref[this->fd] = NULL;
295 this->ClosePending = true;
300 std::string InspSocket::GetIP()
305 char* InspSocket::Read()
307 if ((fd < 0) || (fd > MAX_DESCRIPTORS))
309 int n = recv(this->fd,this->ibuf,sizeof(this->ibuf),0);
310 if ((n > 0) && (n <= (int)sizeof(this->ibuf)))
323 log(DEBUG,"EOF or error on socket: %s",strerror(errno));
329 void InspSocket::MarkAsClosed()
331 log(DEBUG,"Marked as closed");
332 this->ClosePending = true;
335 // There are two possible outcomes to this function.
336 // It will either write all of the data, or an undefined amount.
337 // If an undefined amount is written the connection has failed
338 // and should be aborted.
339 int InspSocket::Write(const std::string &data)
341 if (this->ClosePending)
344 /*int result = write(this->fd,data.c_str(),data.length());
349 /* Try and append the data to the back of the queue, and send it on its way
351 outbuffer.push_back(data);
352 return (!this->FlushWriteBuffer());
355 bool InspSocket::FlushWriteBuffer()
357 if (this->ClosePending)
360 if ((this->fd > -1) && (this->state == I_CONNECTED))
362 if (outbuffer.size())
364 int result = write(this->fd,outbuffer[0].c_str(),outbuffer[0].length());
367 if ((unsigned int)result == outbuffer[0].length())
369 /* The whole block was written (usually a line)
370 * Pop the block off the front of the queue
372 outbuffer.pop_front();
376 std::string temp = outbuffer[0].substr(result);
380 else if ((result == -1) && (errno != EAGAIN))
382 log(DEBUG,"Write error on socket: %s",strerror(errno));
383 this->OnError(I_ERR_WRITE);
384 this->state = I_ERROR;
385 this->ClosePending = true;
393 bool InspSocket::Timeout(time_t current)
395 if (!this->Instance->socket_ref[this->fd] || !this->Instance->SE->HasFd(this->fd))
397 log(DEBUG,"No FD or socket ref");
401 if (this->ClosePending)
403 log(DEBUG,"Close is pending");
407 if ((this->state == I_CONNECTING) && (current > timeout_end))
409 log(DEBUG,"Timed out, current=%lu timeout_end=%lu");
410 // for non-listening sockets, the timeout can occur
411 // which causes termination of the connection after
412 // the given number of seconds without a successful
415 this->OnError(I_ERR_TIMEOUT);
417 this->state = I_ERROR;
418 this->ClosePending = true;
421 return this->FlushWriteBuffer();
424 bool InspSocket::Poll()
426 if (!this->Instance->socket_ref[this->fd] || !this->Instance->SE->HasFd(this->fd))
432 if ((fd < 0) || (fd > MAX_DESCRIPTORS) || (this->ClosePending))
438 log(DEBUG,"State = I_CONNECTING");
439 this->SetState(I_CONNECTED);
440 /* Our socket was in write-state, so delete it and re-add it
445 this->Instance->SE->DelFd(this->fd);
446 if (!this->Instance->SE->AddFd(this->fd,true,X_ESTAB_MODULE))
449 return this->OnConnected();
452 length = sizeof (client);
453 incoming = accept (this->fd, (sockaddr*)&client,&length);
454 this->SetQueues(incoming);
456 this->OnIncomingConnection(incoming,(char*)insp_ntoa(client.sin6_addr));
458 this->OnIncomingConnection(incoming,(char*)insp_ntoa(client.sin_addr));
464 if (this->WaitingForWriteEvent)
466 /* Switch back to read events */
467 this->Instance->SE->DelFd(this->fd);
468 if (!this->Instance->SE->AddFd(this->fd,true,X_ESTAB_MODULE))
471 /* Trigger the write event */
472 n = this->OnWriteReady();
476 /* Process the read event */
477 n = this->OnDataReady();
479 /* Flush any pending, but not till after theyre done with the event
480 * so there are less write calls involved.
481 * Both FlushWriteBuffer AND the return result of OnDataReady must
482 * return true for this to be ok.
484 if (this->FlushWriteBuffer())
494 void InspSocket::SetState(InspSocketState s)
496 log(DEBUG,"Socket state change");
500 InspSocketState InspSocket::GetState()
505 int InspSocket::GetFd()
510 bool InspSocket::OnConnected() { return true; }
511 void InspSocket::OnError(InspSocketError e) { return; }
512 int InspSocket::OnDisconnect() { return 0; }
513 int InspSocket::OnIncomingConnection(int newfd, char* ip) { return 0; }
514 bool InspSocket::OnDataReady() { return true; }
515 bool InspSocket::OnWriteReady() { return true; }
516 void InspSocket::OnTimeout() { return; }
517 void InspSocket::OnClose() { return; }
519 InspSocket::~InspSocket()