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"
31 using irc::sockets::BindSocket;
32 using irc::sockets::OpenTCPSocket;
33 using irc::sockets::insp_inaddr;
34 using irc::sockets::insp_sockaddr;
37 extern Server* MyServer;
39 InspSocket::InspSocket(InspIRCd* SI)
41 this->state = I_DISCONNECTED;
43 this->ClosePending = false;
47 InspSocket::InspSocket(InspIRCd* SI, int newfd, const char* ip)
50 this->state = I_CONNECTED;
51 strlcpy(this->IP,ip,MAXBUF);
52 this->ClosePending = false;
56 this->ClosePending = (!this->Instance->SE->AddFd(this->fd,true,X_ESTAB_MODULE));
57 this->Instance->socket_ref[this->fd] = this;
61 InspSocket::InspSocket(InspIRCd* SI, const std::string &ipaddr, int aport, bool listening, unsigned long maxtime) : fd(-1)
64 strlcpy(host,ipaddr.c_str(),MAXBUF);
65 this->ClosePending = false;
67 if ((this->fd = OpenTCPSocket()) == ERROR)
70 this->state = I_ERROR;
71 this->OnError(I_ERR_SOCKET);
72 this->ClosePending = true;
73 log(DEBUG,"OpenTCPSocket() error");
78 if (!BindSocket(this->fd,this->client,this->server,aport,(char*)ipaddr.c_str()))
80 log(DEBUG,"BindSocket() error %s",strerror(errno));
83 this->state = I_ERROR;
84 this->OnError(I_ERR_BIND);
85 this->ClosePending = true;
90 this->state = I_LISTENING;
93 if (!this->Instance->SE->AddFd(this->fd,true,X_ESTAB_MODULE))
96 this->state = I_ERROR;
97 this->OnError(I_ERR_NOMOREFDS);
98 this->ClosePending = true;
100 this->Instance->socket_ref[this->fd] = this;
102 log(DEBUG,"New socket now in I_LISTENING state");
109 strlcpy(this->host,ipaddr.c_str(),MAXBUF);
112 if (insp_aton(host,&addy) < 1)
114 log(DEBUG,"You cannot pass hostnames to InspSocket, resolve them first with Resolver!");
117 this->state = I_ERROR;
118 this->OnError(I_ERR_RESOLVE);
119 this->ClosePending = true;
124 log(DEBUG,"No need to resolve %s",this->host);
125 strlcpy(this->IP,host,MAXBUF);
126 timeout_end = time(NULL) + maxtime;
132 void InspSocket::WantWrite()
135 * The socket engine may only have each FD in the list ONCE.
136 * This means we cant watch for write AND read at the same
137 * time. We have to remove the READ fd, to insert the WRITE
138 * fd. Once we receive our WRITE event (which WILL ARRIVE,
139 * pretty much gauranteed) we switch back to watching for
142 * This behaviour may be fixed in a later version.
144 this->WaitingForWriteEvent = true;
145 this->Instance->SE->DelFd(this->fd);
146 if (!this->Instance->SE->AddFd(this->fd,false,X_ESTAB_MODULE))
150 this->state = I_ERROR;
151 this->OnError(I_ERR_NOMOREFDS);
152 this->ClosePending = true;
156 void InspSocket::SetQueues(int nfd)
158 // attempt to increase socket sendq and recvq as high as its possible
161 setsockopt(nfd,SOL_SOCKET,SO_SNDBUF,(const void *)&sendbuf,sizeof(sendbuf));
162 setsockopt(nfd,SOL_SOCKET,SO_RCVBUF,(const void *)&recvbuf,sizeof(sendbuf));
165 /* Most irc servers require you to specify the ip you want to bind to.
166 * If you dont specify an IP, they rather dumbly bind to the first IP
167 * of the box (e.g. INADDR_ANY). In InspIRCd, we scan thought the IP
168 * addresses we've bound server ports to, and we try and bind our outbound
169 * connections to the first usable non-loopback and non-any IP we find.
170 * This is easier to configure when you have a lot of links and a lot
171 * of servers to configure.
173 bool InspSocket::BindAddr()
178 log(DEBUG,"In InspSocket::BindAddr()");
179 for (int j =0; j < Conf.Enumerate("bind"); j++)
181 std::string Type = Conf.ReadValue("bind","type",j);
182 std::string IP = Conf.ReadValue("bind","address",j);
183 if (Type == "servers")
185 if ((IP != "*") && (IP != "127.0.0.1") && (IP != ""))
189 if (insp_aton(IP.c_str(),&n) > 0)
191 log(DEBUG,"Found an IP to bind to: %s",IP.c_str());
194 s.sin6_family = AF_FAMILY;
197 s.sin_family = AF_FAMILY;
199 if (bind(this->fd,(struct sockaddr*)&s,sizeof(s)) < 0)
201 log(DEBUG,"Cant bind()");
202 this->state = I_ERROR;
203 this->OnError(I_ERR_BIND);
207 log(DEBUG,"bind() reports outbound fd bound to ip %s",IP.c_str());
212 log(DEBUG,"Address '%s' was not an IP address",IP.c_str());
217 log(DEBUG,"Found no suitable IPs to bind, binding INADDR_ANY");
221 bool InspSocket::DoConnect()
223 log(DEBUG,"In DoConnect()");
224 if ((this->fd = socket(AF_FAMILY, SOCK_STREAM, 0)) == -1)
226 log(DEBUG,"Cant socket()");
227 this->state = I_ERROR;
228 this->OnError(I_ERR_SOCKET);
233 if ((strstr(this->IP,"::ffff:") != (char*)&this->IP) && (strstr(this->IP,"::FFFF:") != (char*)&this->IP))
235 if (!this->BindAddr())
239 log(DEBUG,"Part 2 DoConnect() %s",this->IP);
240 insp_aton(this->IP,&addy);
242 addr.sin6_family = AF_FAMILY;
243 memcpy(&addr.sin6_addr, &addy, sizeof(insp_inaddr));
244 addr.sin6_port = htons(this->port);
246 addr.sin_family = AF_FAMILY;
247 addr.sin_addr = addy;
248 addr.sin_port = htons(this->port);
252 flags = fcntl(this->fd, F_GETFL, 0);
253 fcntl(this->fd, F_SETFL, flags | O_NONBLOCK);
255 if (connect(this->fd, (sockaddr*)&this->addr,sizeof(this->addr)) == -1)
257 if (errno != EINPROGRESS)
259 log(DEBUG,"Error connect() %d: %s",this->fd,strerror(errno));
260 this->OnError(I_ERR_CONNECT);
262 this->state = I_ERROR;
264 this->ClosePending = true;
268 this->state = I_CONNECTING;
271 if (!this->Instance->SE->AddFd(this->fd,false,X_ESTAB_MODULE))
273 this->OnError(I_ERR_NOMOREFDS);
276 this->state = I_ERROR;
277 this->ClosePending = true;
280 this->Instance->socket_ref[this->fd] = this;
281 this->SetQueues(this->fd);
283 log(DEBUG,"Returning true from InspSocket::DoConnect");
288 void InspSocket::Close()
293 shutdown(this->fd,2);
295 this->Instance->socket_ref[this->fd] = NULL;
296 this->ClosePending = true;
301 std::string InspSocket::GetIP()
306 char* InspSocket::Read()
308 if ((fd < 0) || (fd > MAX_DESCRIPTORS))
310 int n = recv(this->fd,this->ibuf,sizeof(this->ibuf),0);
311 if ((n > 0) && (n <= (int)sizeof(this->ibuf)))
324 log(DEBUG,"EOF or error on socket: %s",strerror(errno));
330 void InspSocket::MarkAsClosed()
332 log(DEBUG,"Marked as closed");
333 this->ClosePending = true;
336 // There are two possible outcomes to this function.
337 // It will either write all of the data, or an undefined amount.
338 // If an undefined amount is written the connection has failed
339 // and should be aborted.
340 int InspSocket::Write(const std::string &data)
342 if (this->ClosePending)
345 /*int result = write(this->fd,data.c_str(),data.length());
350 /* Try and append the data to the back of the queue, and send it on its way
352 outbuffer.push_back(data);
353 return (!this->FlushWriteBuffer());
356 bool InspSocket::FlushWriteBuffer()
358 if (this->ClosePending)
361 if ((this->fd > -1) && (this->state == I_CONNECTED))
363 if (outbuffer.size())
365 int result = write(this->fd,outbuffer[0].c_str(),outbuffer[0].length());
368 if ((unsigned int)result == outbuffer[0].length())
370 /* The whole block was written (usually a line)
371 * Pop the block off the front of the queue
373 outbuffer.pop_front();
377 std::string temp = outbuffer[0].substr(result);
381 else if ((result == -1) && (errno != EAGAIN))
383 log(DEBUG,"Write error on socket: %s",strerror(errno));
384 this->OnError(I_ERR_WRITE);
385 this->state = I_ERROR;
386 this->ClosePending = true;
394 bool InspSocket::Timeout(time_t current)
396 if (!this->Instance->socket_ref[this->fd] || !this->Instance->SE->HasFd(this->fd))
398 log(DEBUG,"No FD or socket ref");
402 if (this->ClosePending)
404 log(DEBUG,"Close is pending");
408 if ((this->state == I_CONNECTING) && (current > timeout_end))
410 log(DEBUG,"Timed out, current=%lu timeout_end=%lu");
411 // for non-listening sockets, the timeout can occur
412 // which causes termination of the connection after
413 // the given number of seconds without a successful
416 this->OnError(I_ERR_TIMEOUT);
418 this->state = I_ERROR;
419 this->ClosePending = true;
422 return this->FlushWriteBuffer();
425 bool InspSocket::Poll()
427 if (!this->Instance->socket_ref[this->fd] || !this->Instance->SE->HasFd(this->fd))
433 if ((fd < 0) || (fd > MAX_DESCRIPTORS) || (this->ClosePending))
439 log(DEBUG,"State = I_CONNECTING");
440 this->SetState(I_CONNECTED);
441 /* Our socket was in write-state, so delete it and re-add it
446 this->Instance->SE->DelFd(this->fd);
447 if (!this->Instance->SE->AddFd(this->fd,true,X_ESTAB_MODULE))
450 return this->OnConnected();
453 length = sizeof (client);
454 incoming = accept (this->fd, (sockaddr*)&client,&length);
455 this->SetQueues(incoming);
457 this->OnIncomingConnection(incoming,(char*)insp_ntoa(client.sin6_addr));
459 this->OnIncomingConnection(incoming,(char*)insp_ntoa(client.sin_addr));
465 if (this->WaitingForWriteEvent)
467 /* Switch back to read events */
468 this->Instance->SE->DelFd(this->fd);
469 if (!this->Instance->SE->AddFd(this->fd,true,X_ESTAB_MODULE))
472 /* Trigger the write event */
473 n = this->OnWriteReady();
477 /* Process the read event */
478 n = this->OnDataReady();
480 /* Flush any pending, but not till after theyre done with the event
481 * so there are less write calls involved.
482 * Both FlushWriteBuffer AND the return result of OnDataReady must
483 * return true for this to be ok.
485 if (this->FlushWriteBuffer())
495 void InspSocket::SetState(InspSocketState s)
497 log(DEBUG,"Socket state change");
501 InspSocketState InspSocket::GetState()
506 int InspSocket::GetFd()
511 bool InspSocket::OnConnected() { return true; }
512 void InspSocket::OnError(InspSocketError e) { return; }
513 int InspSocket::OnDisconnect() { return 0; }
514 int InspSocket::OnIncomingConnection(int newfd, char* ip) { return 0; }
515 bool InspSocket::OnDataReady() { return true; }
516 bool InspSocket::OnWriteReady() { return true; }
517 void InspSocket::OnTimeout() { return; }
518 void InspSocket::OnClose() { return; }
520 InspSocket::~InspSocket()