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"
25 #include "configreader.h"
26 #include "inspstring.h"
27 #include "helperfuncs.h"
28 #include "socketengine.h"
32 extern InspIRCd* ServerInstance;
33 extern ServerConfig* Config;
35 extern Server* MyServer;
37 InspSocket* socket_ref[MAX_DESCRIPTORS];
40 InspSocket::InspSocket()
42 this->state = I_DISCONNECTED;
44 this->ClosePending = false;
47 InspSocket::InspSocket(int newfd, const char* ip)
50 this->state = I_CONNECTED;
51 strlcpy(this->IP,ip,MAXBUF);
52 this->ClosePending = false;
55 ServerInstance->SE->AddFd(this->fd,true,X_ESTAB_MODULE);
56 socket_ref[this->fd] = this;
60 InspSocket::InspSocket(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 (!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 ServerInstance->SE->AddFd(this->fd,true,X_ESTAB_MODULE);
92 socket_ref[this->fd] = this;
94 log(DEBUG,"New socket now in I_LISTENING state");
101 strlcpy(this->host,ipaddr.c_str(),MAXBUF);
104 if (insp_aton(host,&addy) < 1)
106 log(DEBUG,"You cannot pass hostnames to InspSocket, resolve them first with Resolver!");
109 this->state = I_ERROR;
110 this->OnError(I_ERR_RESOLVE);
111 this->ClosePending = true;
116 log(DEBUG,"No need to resolve %s",this->host);
117 strlcpy(this->IP,host,MAXBUF);
118 timeout_end = time(NULL) + maxtime;
124 void InspSocket::WantWrite()
127 * The socket engine may only have each FD in the list ONCE.
128 * This means we cant watch for write AND read at the same
129 * time. We have to remove the READ fd, to insert the WRITE
130 * fd. Once we receive our WRITE event (which WILL ARRIVE,
131 * pretty much gauranteed) we switch back to watching for
134 * This behaviour may be fixed in a later version.
136 this->WaitingForWriteEvent = true;
137 ServerInstance->SE->DelFd(this->fd);
138 ServerInstance->SE->AddFd(this->fd,false,X_ESTAB_MODULE);
141 void InspSocket::SetQueues(int nfd)
143 // attempt to increase socket sendq and recvq as high as its possible
146 setsockopt(nfd,SOL_SOCKET,SO_SNDBUF,(const void *)&sendbuf,sizeof(sendbuf));
147 setsockopt(nfd,SOL_SOCKET,SO_RCVBUF,(const void *)&recvbuf,sizeof(sendbuf));
150 /* Most irc servers require you to specify the ip you want to bind to.
151 * If you dont specify an IP, they rather dumbly bind to the first IP
152 * of the box (e.g. INADDR_ANY). In InspIRCd, we scan thought the IP
153 * addresses we've bound server ports to, and we try and bind our outbound
154 * connections to the first usable non-loopback and non-any IP we find.
155 * This is easier to configure when you have a lot of links and a lot
156 * of servers to configure.
158 bool InspSocket::BindAddr()
163 log(DEBUG,"In InspSocket::BindAddr()");
164 for (int j =0; j < Conf.Enumerate("bind"); j++)
166 std::string Type = Conf.ReadValue("bind","type",j);
167 std::string IP = Conf.ReadValue("bind","address",j);
168 if (Type == "servers")
170 if ((IP != "*") && (IP != "127.0.0.1") && (IP != ""))
174 if (insp_aton(IP.c_str(),&n) > 0)
176 log(DEBUG,"Found an IP to bind to: %s",IP.c_str());
179 s.sin6_family = AF_FAMILY;
182 s.sin_family = AF_FAMILY;
184 if (bind(this->fd,(struct sockaddr*)&s,sizeof(s)) < 0)
186 log(DEBUG,"Cant bind()");
187 this->state = I_ERROR;
188 this->OnError(I_ERR_BIND);
192 log(DEBUG,"bind() reports outbound fd bound to ip %s",IP.c_str());
197 log(DEBUG,"Address '%s' was not an IP address",IP.c_str());
202 log(DEBUG,"Found no suitable IPs to bind, binding INADDR_ANY");
206 bool InspSocket::DoConnect()
208 log(DEBUG,"In DoConnect()");
209 if ((this->fd = socket(AF_FAMILY, SOCK_STREAM, 0)) == -1)
211 log(DEBUG,"Cant socket()");
212 this->state = I_ERROR;
213 this->OnError(I_ERR_SOCKET);
218 if (!this->BindAddr())
221 log(DEBUG,"Part 2 DoConnect() %s",this->IP);
222 insp_aton(this->IP,&addy);
224 addr.sin6_family = AF_FAMILY;
225 memcpy(&addy, &addr.sin6_addr, sizeof(insp_inaddr));
226 addr.sin6_port = htons(this->port);
228 addr.sin_family = AF_FAMILY;
229 addr.sin_addr = addy;
230 addr.sin_port = htons(this->port);
234 flags = fcntl(this->fd, F_GETFL, 0);
235 fcntl(this->fd, F_SETFL, flags | O_NONBLOCK);
237 if (connect(this->fd, (sockaddr*)&this->addr,sizeof(this->addr)) == -1)
239 if (errno != EINPROGRESS)
241 log(DEBUG,"Error connect() %d: %s",this->fd,strerror(errno));
242 this->OnError(I_ERR_CONNECT);
244 this->state = I_ERROR;
246 this->ClosePending = true;
250 this->state = I_CONNECTING;
253 ServerInstance->SE->AddFd(this->fd,false,X_ESTAB_MODULE);
254 socket_ref[this->fd] = this;
255 this->SetQueues(this->fd);
257 log(DEBUG,"Returning true from InspSocket::DoConnect");
262 void InspSocket::Close()
267 shutdown(this->fd,2);
269 socket_ref[this->fd] = NULL;
270 this->ClosePending = true;
275 std::string InspSocket::GetIP()
280 char* InspSocket::Read()
282 if ((fd < 0) || (fd > MAX_DESCRIPTORS))
284 int n = recv(this->fd,this->ibuf,sizeof(this->ibuf),0);
285 if ((n > 0) && (n <= (int)sizeof(this->ibuf)))
298 log(DEBUG,"EOF or error on socket: %s",strerror(errno));
304 void InspSocket::MarkAsClosed()
306 log(DEBUG,"Marked as closed");
307 this->ClosePending = true;
310 // There are two possible outcomes to this function.
311 // It will either write all of the data, or an undefined amount.
312 // If an undefined amount is written the connection has failed
313 // and should be aborted.
314 int InspSocket::Write(const std::string &data)
316 if (this->ClosePending)
319 /*int result = write(this->fd,data.c_str(),data.length());
324 /* Try and append the data to the back of the queue, and send it on its way
326 outbuffer.push_back(data);
327 return (!this->FlushWriteBuffer());
330 bool InspSocket::FlushWriteBuffer()
332 if (this->ClosePending)
335 if ((this->fd > -1) && (this->state == I_CONNECTED))
337 if (outbuffer.size())
339 int result = write(this->fd,outbuffer[0].c_str(),outbuffer[0].length());
342 if ((unsigned int)result == outbuffer[0].length())
344 /* The whole block was written (usually a line)
345 * Pop the block off the front of the queue
347 outbuffer.pop_front();
351 std::string temp = outbuffer[0].substr(result);
355 else if ((result == -1) && (errno != EAGAIN))
357 log(DEBUG,"Write error on socket: %s",strerror(errno));
358 this->OnError(I_ERR_WRITE);
359 this->state = I_ERROR;
360 this->ClosePending = true;
368 bool InspSocket::Timeout(time_t current)
370 if (!socket_ref[this->fd] || !ServerInstance->SE->HasFd(this->fd))
372 log(DEBUG,"No FD or socket ref");
376 if (this->ClosePending)
378 log(DEBUG,"Close is pending");
382 if ((this->state == I_CONNECTING) && (current > timeout_end))
384 log(DEBUG,"Timed out, current=%lu timeout_end=%lu");
385 // for non-listening sockets, the timeout can occur
386 // which causes termination of the connection after
387 // the given number of seconds without a successful
390 this->OnError(I_ERR_TIMEOUT);
392 this->state = I_ERROR;
393 this->ClosePending = true;
396 return this->FlushWriteBuffer();
399 bool InspSocket::Poll()
401 if (!socket_ref[this->fd] || !ServerInstance->SE->HasFd(this->fd))
407 if ((fd < 0) || (fd > MAX_DESCRIPTORS) || (this->ClosePending))
413 log(DEBUG,"State = I_CONNECTING");
414 this->SetState(I_CONNECTED);
415 /* Our socket was in write-state, so delete it and re-add it
420 ServerInstance->SE->DelFd(this->fd);
421 ServerInstance->SE->AddFd(this->fd,true,X_ESTAB_MODULE);
423 return this->OnConnected();
426 length = sizeof (client);
427 incoming = accept (this->fd, (sockaddr*)&client,&length);
428 this->SetQueues(incoming);
430 this->OnIncomingConnection(incoming,(char*)insp_ntoa(client.sin6_addr));
432 this->OnIncomingConnection(incoming,(char*)insp_ntoa(client.sin_addr));
438 if (this->WaitingForWriteEvent)
440 /* Switch back to read events */
441 ServerInstance->SE->DelFd(this->fd);
442 ServerInstance->SE->AddFd(this->fd,true,X_ESTAB_MODULE);
443 /* Trigger the write event */
444 n = this->OnWriteReady();
448 /* Process the read event */
449 n = this->OnDataReady();
451 /* Flush any pending, but not till after theyre done with the event
452 * so there are less write calls involved.
453 * Both FlushWriteBuffer AND the return result of OnDataReady must
454 * return true for this to be ok.
456 if (this->FlushWriteBuffer())
466 void InspSocket::SetState(InspSocketState s)
468 log(DEBUG,"Socket state change");
472 InspSocketState InspSocket::GetState()
477 int InspSocket::GetFd()
482 bool InspSocket::OnConnected() { return true; }
483 void InspSocket::OnError(InspSocketError e) { return; }
484 int InspSocket::OnDisconnect() { return 0; }
485 int InspSocket::OnIncomingConnection(int newfd, char* ip) { return 0; }
486 bool InspSocket::OnDataReady() { return true; }
487 bool InspSocket::OnWriteReady() { return true; }
488 void InspSocket::OnTimeout() { return; }
489 void InspSocket::OnClose() { return; }
491 InspSocket::~InspSocket()