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;
36 InspSocket* socket_ref[MAX_DESCRIPTORS];
38 InspSocket::InspSocket()
40 this->state = I_DISCONNECTED;
42 this->ClosePending = false;
45 InspSocket::InspSocket(int newfd, const char* ip)
48 this->state = I_CONNECTED;
49 strlcpy(this->IP,ip,MAXBUF);
50 this->ClosePending = false;
53 ServerInstance->SE->AddFd(this->fd,true,X_ESTAB_MODULE);
54 socket_ref[this->fd] = this;
58 InspSocket::InspSocket(const std::string &ahost, int aport, bool listening, unsigned long maxtime) : fd(-1)
60 strlcpy(host,ahost.c_str(),MAXBUF);
61 this->ClosePending = false;
63 if ((this->fd = OpenTCPSocket()) == ERROR)
66 this->state = I_ERROR;
67 this->OnError(I_ERR_SOCKET);
68 this->ClosePending = true;
69 log(DEBUG,"OpenTCPSocket() error");
74 if (!BindSocket(this->fd,this->client,this->server,aport,(char*)ahost.c_str()))
76 log(DEBUG,"BindSocket() error %s",strerror(errno));
79 this->state = I_ERROR;
80 this->OnError(I_ERR_BIND);
81 this->ClosePending = true;
86 this->state = I_LISTENING;
89 ServerInstance->SE->AddFd(this->fd,true,X_ESTAB_MODULE);
90 socket_ref[this->fd] = this;
92 log(DEBUG,"New socket now in I_LISTENING state");
99 strlcpy(this->host,ahost.c_str(),MAXBUF);
102 if (!inet_aton(host,&addy))
104 log(DEBUG,"Attempting to resolve %s",this->host);
105 /* Its not an ip, spawn the resolver */
106 this->dns.SetNS(std::string(Config->DNSServer));
107 this->dns.ForwardLookupWithFD(host,fd, true);
108 timeout_end = time(NULL) + maxtime;
110 this->state = I_RESOLVING;
111 socket_ref[this->fd] = this;
115 log(DEBUG,"No need to resolve %s",this->host);
116 strlcpy(this->IP,host,MAXBUF);
117 timeout_end = time(NULL) + maxtime;
123 void InspSocket::WantWrite()
126 * The socket engine may only have each FD in the list ONCE.
127 * This means we cant watch for write AND read at the same
128 * time. We have to remove the READ fd, to insert the WRITE
129 * fd. Once we receive our WRITE event (which WILL ARRIVE,
130 * pretty much gauranteed) we switch back to watching for
133 * This behaviour may be fixed in a later version.
135 this->WaitingForWriteEvent = true;
136 ServerInstance->SE->DelFd(this->fd);
137 ServerInstance->SE->AddFd(this->fd,false,X_ESTAB_MODULE);
140 void InspSocket::SetQueues(int nfd)
142 // attempt to increase socket sendq and recvq as high as its possible
145 setsockopt(nfd,SOL_SOCKET,SO_SNDBUF,(const void *)&sendbuf,sizeof(sendbuf));
146 setsockopt(nfd,SOL_SOCKET,SO_RCVBUF,(const void *)&recvbuf,sizeof(sendbuf));
149 bool InspSocket::DoResolve()
151 log(DEBUG,"In DoResolve(), trying to resolve IP");
152 if (this->dns.HasResult())
154 log(DEBUG,"Socket has result");
155 std::string res_ip = dns.GetResultIP();
158 log(DEBUG,"Socket result set to %s",res_ip.c_str());
159 strlcpy(this->IP,res_ip.c_str(),MAXBUF);
160 socket_ref[this->fd] = NULL;
164 log(DEBUG,"Socket DNS failure");
166 this->state = I_ERROR;
167 this->OnError(I_ERR_RESOLVE);
169 this->ClosePending = true;
172 return this->DoConnect();
174 log(DEBUG,"No result for socket yet!");
178 /* Most irc servers require you to specify the ip you want to bind to.
179 * If you dont specify an IP, they rather dumbly bind to the first IP
180 * of the box (e.g. INADDR_ANY). In InspIRCd, we scan thought the IP
181 * addresses we've bound server ports to, and we try and bind our outbound
182 * connections to the first usable non-loopback and non-any IP we find.
183 * This is easier to configure when you have a lot of links and a lot
184 * of servers to configure.
186 bool InspSocket::BindAddr()
191 log(DEBUG,"In InspSocket::BindAddr()");
192 for (int j =0; j < Conf.Enumerate("bind"); j++)
194 std::string Type = Conf.ReadValue("bind","type",j);
195 std::string IP = Conf.ReadValue("bind","address",j);
196 if (Type == "servers")
198 if ((IP != "*") && (IP != "127.0.0.1") && (IP != ""))
201 char resolved_addr[MAXBUF];
203 if (!inet_aton(IP.c_str(),&n))
205 /* If they gave a hostname, bind to the IP it resolves to */
206 log(DEBUG,"Resolving host %s",IP.c_str());
207 if (CleanAndResolve(resolved_addr, IP.c_str(), true))
209 log(DEBUG,"Resolved host %s to %s",IP.c_str(),resolved_addr);
214 if (inet_aton(IP.c_str(),&n))
216 log(DEBUG,"Found an IP to bind to: %s",IP.c_str());
218 s.sin_family = AF_INET;
219 if (bind(this->fd,(struct sockaddr*)&s,sizeof(s)) < 0)
221 log(DEBUG,"Cant bind()");
222 this->state = I_ERROR;
223 this->OnError(I_ERR_BIND);
227 log(DEBUG,"bind() reports outbound fd bound to ip %s",IP.c_str());
232 log(DEBUG,"Address '%s' was not an IP address",IP.c_str());
237 log(DEBUG,"Found no suitable IPs to bind, binding INADDR_ANY");
241 bool InspSocket::DoConnect()
243 log(DEBUG,"In DoConnect()");
244 if ((this->fd = socket(AF_INET, SOCK_STREAM, 0)) == -1)
246 log(DEBUG,"Cant socket()");
247 this->state = I_ERROR;
248 this->OnError(I_ERR_SOCKET);
253 if (!this->BindAddr())
256 log(DEBUG,"Part 2 DoConnect() %s",this->IP);
257 inet_aton(this->IP,&addy);
258 addr.sin_family = AF_INET;
259 addr.sin_addr = addy;
260 addr.sin_port = htons(this->port);
263 flags = fcntl(this->fd, F_GETFL, 0);
264 fcntl(this->fd, F_SETFL, flags | O_NONBLOCK);
266 if (connect(this->fd, (sockaddr*)&this->addr,sizeof(this->addr)) == -1)
268 if (errno != EINPROGRESS)
270 log(DEBUG,"Error connect() %d: %s",this->fd,strerror(errno));
271 this->OnError(I_ERR_CONNECT);
273 this->state = I_ERROR;
275 this->ClosePending = true;
279 this->state = I_CONNECTING;
282 ServerInstance->SE->AddFd(this->fd,false,X_ESTAB_MODULE);
283 socket_ref[this->fd] = this;
284 this->SetQueues(this->fd);
286 log(DEBUG,"Returning true from InspSocket::DoConnect");
291 void InspSocket::Close()
296 shutdown(this->fd,2);
298 socket_ref[this->fd] = NULL;
299 this->ClosePending = true;
304 std::string InspSocket::GetIP()
309 char* InspSocket::Read()
311 if ((fd < 0) || (fd > MAX_DESCRIPTORS))
313 int n = recv(this->fd,this->ibuf,sizeof(this->ibuf),0);
314 if ((n > 0) && (n <= (int)sizeof(this->ibuf)))
327 log(DEBUG,"EOF or error on socket: %s",strerror(errno));
333 void InspSocket::MarkAsClosed()
335 log(DEBUG,"Marked as closed");
336 this->ClosePending = true;
339 // There are two possible outcomes to this function.
340 // It will either write all of the data, or an undefined amount.
341 // If an undefined amount is written the connection has failed
342 // and should be aborted.
343 int InspSocket::Write(const std::string &data)
345 if (this->ClosePending)
348 /*int result = write(this->fd,data.c_str(),data.length());
353 /* Try and append the data to the back of the queue, and send it on its way
355 outbuffer.push_back(data);
356 return (!this->FlushWriteBuffer());
359 bool InspSocket::FlushWriteBuffer()
361 if (this->ClosePending)
364 if ((this->fd > -1) && (this->state == I_CONNECTED))
366 if (outbuffer.size())
368 int result = write(this->fd,outbuffer[0].c_str(),outbuffer[0].length());
371 if ((unsigned int)result == outbuffer[0].length())
373 /* The whole block was written (usually a line)
374 * Pop the block off the front of the queue
376 outbuffer.pop_front();
380 std::string temp = outbuffer[0].substr(result);
384 else if ((result == -1) && (errno != EAGAIN))
386 log(DEBUG,"Write error on socket: %s",strerror(errno));
387 this->OnError(I_ERR_WRITE);
388 this->state = I_ERROR;
389 this->ClosePending = true;
397 bool InspSocket::Timeout(time_t current)
399 if (!socket_ref[this->fd] || !ServerInstance->SE->HasFd(this->fd))
401 log(DEBUG,"No FD or socket ref");
405 if (this->ClosePending)
407 log(DEBUG,"Close is pending");
411 if (((this->state == I_RESOLVING) || (this->state == I_CONNECTING)) && (current > timeout_end))
413 log(DEBUG,"Timed out, current=%lu timeout_end=%lu");
414 // for non-listening sockets, the timeout can occur
415 // which causes termination of the connection after
416 // the given number of seconds without a successful
419 this->OnError(I_ERR_TIMEOUT);
421 this->state = I_ERROR;
422 this->ClosePending = true;
425 return this->FlushWriteBuffer();
428 bool InspSocket::Poll()
430 if (!socket_ref[this->fd] || !ServerInstance->SE->HasFd(this->fd))
436 if ((fd < 0) || (fd > MAX_DESCRIPTORS) || (this->ClosePending))
442 log(DEBUG,"State = I_RESOLVING, calling DoResolve()");
443 return this->DoResolve();
446 log(DEBUG,"State = I_CONNECTING");
447 this->SetState(I_CONNECTED);
448 /* Our socket was in write-state, so delete it and re-add it
453 ServerInstance->SE->DelFd(this->fd);
454 ServerInstance->SE->AddFd(this->fd,true,X_ESTAB_MODULE);
456 return this->OnConnected();
459 length = sizeof (client);
460 incoming = accept (this->fd, (sockaddr*)&client,&length);
461 this->SetQueues(incoming);
462 this->OnIncomingConnection(incoming,inet_ntoa(client.sin_addr));
467 if (this->WaitingForWriteEvent)
469 /* Switch back to read events */
470 ServerInstance->SE->DelFd(this->fd);
471 ServerInstance->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()