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;
36 InspSocket::InspSocket(InspIRCd* SI)
38 this->state = I_DISCONNECTED;
40 this->ClosePending = false;
44 InspSocket::InspSocket(InspIRCd* SI, int newfd, const char* ip)
47 this->state = I_CONNECTED;
48 strlcpy(this->IP,ip,MAXBUF);
49 this->ClosePending = false;
53 this->ClosePending = (!this->Instance->SE->AddFd(this->fd,true,X_ESTAB_MODULE));
54 this->Instance->socket_ref[this->fd] = this;
58 InspSocket::InspSocket(InspIRCd* SI, const std::string &ipaddr, int aport, bool listening, unsigned long maxtime) : fd(-1)
61 strlcpy(host,ipaddr.c_str(),MAXBUF);
62 this->ClosePending = false;
64 if ((this->fd = OpenTCPSocket()) == ERROR)
67 this->state = I_ERROR;
68 this->OnError(I_ERR_SOCKET);
69 this->ClosePending = true;
70 log(DEBUG,"OpenTCPSocket() error");
75 if (!SI->BindSocket(this->fd,this->client,this->server,aport,(char*)ipaddr.c_str()))
77 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->fd,true,X_ESTAB_MODULE))
93 this->state = I_ERROR;
94 this->OnError(I_ERR_NOMOREFDS);
95 this->ClosePending = true;
97 this->Instance->socket_ref[this->fd] = this;
99 log(DEBUG,"New socket now in I_LISTENING state");
106 strlcpy(this->host,ipaddr.c_str(),MAXBUF);
109 if (insp_aton(host,&addy) < 1)
111 log(DEBUG,"You cannot pass hostnames to InspSocket, resolve them first with Resolver!");
114 this->state = I_ERROR;
115 this->OnError(I_ERR_RESOLVE);
116 this->ClosePending = true;
121 log(DEBUG,"No need to resolve %s",this->host);
122 strlcpy(this->IP,host,MAXBUF);
123 timeout_end = time(NULL) + maxtime;
129 void InspSocket::WantWrite()
132 * The socket engine may only have each FD in the list ONCE.
133 * This means we cant watch for write AND read at the same
134 * time. We have to remove the READ fd, to insert the WRITE
135 * fd. Once we receive our WRITE event (which WILL ARRIVE,
136 * pretty much gauranteed) we switch back to watching for
139 * This behaviour may be fixed in a later version.
141 this->WaitingForWriteEvent = true;
142 this->Instance->SE->DelFd(this->fd);
143 if (!this->Instance->SE->AddFd(this->fd,false,X_ESTAB_MODULE))
147 this->state = I_ERROR;
148 this->OnError(I_ERR_NOMOREFDS);
149 this->ClosePending = true;
153 void InspSocket::SetQueues(int nfd)
155 // attempt to increase socket sendq and recvq as high as its possible
158 setsockopt(nfd,SOL_SOCKET,SO_SNDBUF,(const void *)&sendbuf,sizeof(sendbuf));
159 setsockopt(nfd,SOL_SOCKET,SO_RCVBUF,(const void *)&recvbuf,sizeof(sendbuf));
162 /* Most irc servers require you to specify the ip you want to bind to.
163 * If you dont specify an IP, they rather dumbly bind to the first IP
164 * of the box (e.g. INADDR_ANY). In InspIRCd, we scan thought the IP
165 * addresses we've bound server ports to, and we try and bind our outbound
166 * connections to the first usable non-loopback and non-any IP we find.
167 * This is easier to configure when you have a lot of links and a lot
168 * of servers to configure.
170 bool InspSocket::BindAddr()
175 log(DEBUG,"In InspSocket::BindAddr()");
176 for (int j =0; j < Conf.Enumerate("bind"); j++)
178 std::string Type = Conf.ReadValue("bind","type",j);
179 std::string IP = Conf.ReadValue("bind","address",j);
180 if (Type == "servers")
182 if ((IP != "*") && (IP != "127.0.0.1") && (IP != ""))
186 if (insp_aton(IP.c_str(),&n) > 0)
188 log(DEBUG,"Found an IP to bind to: %s",IP.c_str());
191 s.sin6_family = AF_FAMILY;
194 s.sin_family = AF_FAMILY;
196 if (bind(this->fd,(struct sockaddr*)&s,sizeof(s)) < 0)
198 log(DEBUG,"Cant bind()");
199 this->state = I_ERROR;
200 this->OnError(I_ERR_BIND);
204 log(DEBUG,"bind() reports outbound fd bound to ip %s",IP.c_str());
209 log(DEBUG,"Address '%s' was not an IP address",IP.c_str());
214 log(DEBUG,"Found no suitable IPs to bind, binding INADDR_ANY");
218 bool InspSocket::DoConnect()
220 log(DEBUG,"In DoConnect()");
221 if ((this->fd = socket(AF_FAMILY, SOCK_STREAM, 0)) == -1)
223 log(DEBUG,"Cant socket()");
224 this->state = I_ERROR;
225 this->OnError(I_ERR_SOCKET);
230 if ((strstr(this->IP,"::ffff:") != (char*)&this->IP) && (strstr(this->IP,"::FFFF:") != (char*)&this->IP))
232 if (!this->BindAddr())
236 log(DEBUG,"Part 2 DoConnect() %s",this->IP);
237 insp_aton(this->IP,&addy);
239 addr.sin6_family = AF_FAMILY;
240 memcpy(&addr.sin6_addr, &addy, sizeof(insp_inaddr));
241 addr.sin6_port = htons(this->port);
243 addr.sin_family = AF_FAMILY;
244 addr.sin_addr = addy;
245 addr.sin_port = htons(this->port);
249 flags = fcntl(this->fd, F_GETFL, 0);
250 fcntl(this->fd, F_SETFL, flags | O_NONBLOCK);
252 if (connect(this->fd, (sockaddr*)&this->addr,sizeof(this->addr)) == -1)
254 if (errno != EINPROGRESS)
256 log(DEBUG,"Error connect() %d: %s",this->fd,strerror(errno));
257 this->OnError(I_ERR_CONNECT);
259 this->state = I_ERROR;
261 this->ClosePending = true;
265 this->state = I_CONNECTING;
268 if (!this->Instance->SE->AddFd(this->fd,false,X_ESTAB_MODULE))
270 this->OnError(I_ERR_NOMOREFDS);
273 this->state = I_ERROR;
274 this->ClosePending = true;
277 this->Instance->socket_ref[this->fd] = this;
278 this->SetQueues(this->fd);
280 log(DEBUG,"Returning true from InspSocket::DoConnect");
285 void InspSocket::Close()
290 shutdown(this->fd,2);
292 this->Instance->socket_ref[this->fd] = NULL;
293 this->ClosePending = true;
298 std::string InspSocket::GetIP()
303 char* InspSocket::Read()
305 if ((fd < 0) || (fd > MAX_DESCRIPTORS))
307 int n = recv(this->fd,this->ibuf,sizeof(this->ibuf),0);
308 if ((n > 0) && (n <= (int)sizeof(this->ibuf)))
321 log(DEBUG,"EOF or error on socket: %s",strerror(errno));
327 void InspSocket::MarkAsClosed()
329 log(DEBUG,"Marked as closed");
330 this->ClosePending = true;
333 // There are two possible outcomes to this function.
334 // It will either write all of the data, or an undefined amount.
335 // If an undefined amount is written the connection has failed
336 // and should be aborted.
337 int InspSocket::Write(const std::string &data)
339 if (this->ClosePending)
342 /*int result = write(this->fd,data.c_str(),data.length());
347 /* Try and append the data to the back of the queue, and send it on its way
349 outbuffer.push_back(data);
350 return (!this->FlushWriteBuffer());
353 bool InspSocket::FlushWriteBuffer()
355 if (this->ClosePending)
358 if ((this->fd > -1) && (this->state == I_CONNECTED))
360 if (outbuffer.size())
362 int result = write(this->fd,outbuffer[0].c_str(),outbuffer[0].length());
365 if ((unsigned int)result == outbuffer[0].length())
367 /* The whole block was written (usually a line)
368 * Pop the block off the front of the queue
370 outbuffer.pop_front();
374 std::string temp = outbuffer[0].substr(result);
378 else if ((result == -1) && (errno != EAGAIN))
380 log(DEBUG,"Write error on socket: %s",strerror(errno));
381 this->OnError(I_ERR_WRITE);
382 this->state = I_ERROR;
383 this->ClosePending = true;
391 bool InspSocket::Timeout(time_t current)
393 if (!this->Instance->socket_ref[this->fd] || !this->Instance->SE->HasFd(this->fd))
395 log(DEBUG,"No FD or socket ref");
399 if (this->ClosePending)
401 log(DEBUG,"Close is pending");
405 if ((this->state == I_CONNECTING) && (current > timeout_end))
407 log(DEBUG,"Timed out, current=%lu timeout_end=%lu");
408 // for non-listening sockets, the timeout can occur
409 // which causes termination of the connection after
410 // the given number of seconds without a successful
413 this->OnError(I_ERR_TIMEOUT);
415 this->state = I_ERROR;
416 this->ClosePending = true;
419 return this->FlushWriteBuffer();
422 bool InspSocket::Poll()
424 if (!this->Instance->socket_ref[this->fd] || !this->Instance->SE->HasFd(this->fd))
430 if ((fd < 0) || (fd > MAX_DESCRIPTORS) || (this->ClosePending))
436 log(DEBUG,"State = I_CONNECTING");
437 this->SetState(I_CONNECTED);
438 /* Our socket was in write-state, so delete it and re-add it
443 this->Instance->SE->DelFd(this->fd);
444 if (!this->Instance->SE->AddFd(this->fd,true,X_ESTAB_MODULE))
447 return this->OnConnected();
450 length = sizeof (client);
451 incoming = accept (this->fd, (sockaddr*)&client,&length);
452 this->SetQueues(incoming);
454 this->OnIncomingConnection(incoming,(char*)insp_ntoa(client.sin6_addr));
456 this->OnIncomingConnection(incoming,(char*)insp_ntoa(client.sin_addr));
462 if (this->WaitingForWriteEvent)
464 /* Switch back to read events */
465 this->Instance->SE->DelFd(this->fd);
466 if (!this->Instance->SE->AddFd(this->fd,true,X_ESTAB_MODULE))
469 /* Trigger the write event */
470 n = this->OnWriteReady();
474 /* Process the read event */
475 n = this->OnDataReady();
477 /* Flush any pending, but not till after theyre done with the event
478 * so there are less write calls involved.
479 * Both FlushWriteBuffer AND the return result of OnDataReady must
480 * return true for this to be ok.
482 if (this->FlushWriteBuffer())
492 void InspSocket::SetState(InspSocketState s)
494 log(DEBUG,"Socket state change");
498 InspSocketState InspSocket::GetState()
503 int InspSocket::GetFd()
508 bool InspSocket::OnConnected() { return true; }
509 void InspSocket::OnError(InspSocketError e) { return; }
510 int InspSocket::OnDisconnect() { return 0; }
511 int InspSocket::OnIncomingConnection(int newfd, char* ip) { return 0; }
512 bool InspSocket::OnDataReady() { return true; }
513 bool InspSocket::OnWriteReady() { return true; }
514 void InspSocket::OnTimeout() { return; }
515 void InspSocket::OnClose() { return; }
517 InspSocket::~InspSocket()