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"
31 extern InspIRCd* ServerInstance;
32 extern ServerConfig* Config;
35 InspSocket* socket_ref[MAX_DESCRIPTORS];
37 InspSocket::InspSocket()
39 this->state = I_DISCONNECTED;
41 this->ClosePending = false;
44 InspSocket::InspSocket(int newfd, char* ip)
47 this->state = I_CONNECTED;
48 strlcpy(this->IP,ip,MAXBUF);
49 this->ClosePending = false;
52 ServerInstance->SE->AddFd(this->fd,true,X_ESTAB_MODULE);
53 socket_ref[this->fd] = this;
57 InspSocket::InspSocket(const std::string &ahost, int aport, bool listening, unsigned long maxtime) : fd(-1)
59 strlcpy(host,ahost.c_str(),MAXBUF);
60 this->ClosePending = false;
62 if ((this->fd = OpenTCPSocket()) == ERROR)
65 this->state = I_ERROR;
66 this->OnError(I_ERR_SOCKET);
67 this->ClosePending = true;
68 log(DEBUG,"OpenTCPSocket() error");
73 if (!BindSocket(this->fd,this->client,this->server,aport,(char*)ahost.c_str()))
77 this->state = I_ERROR;
78 this->OnError(I_ERR_BIND);
79 this->ClosePending = true;
80 log(DEBUG,"BindSocket() error %s",strerror(errno));
85 this->state = I_LISTENING;
88 ServerInstance->SE->AddFd(this->fd,true,X_ESTAB_MODULE);
89 socket_ref[this->fd] = this;
91 log(DEBUG,"New socket now in I_LISTENING state");
98 strlcpy(this->host,ahost.c_str(),MAXBUF);
101 if (!inet_aton(host,&addy))
103 log(DEBUG,"Attempting to resolve %s",this->host);
104 /* Its not an ip, spawn the resolver */
105 this->dns.SetNS(std::string(Config->DNSServer));
106 this->dns.ForwardLookupWithFD(host,fd);
107 timeout_end = time(NULL) + maxtime;
109 this->state = I_RESOLVING;
110 socket_ref[this->fd] = this;
114 log(DEBUG,"No need to resolve %s",this->host);
115 strlcpy(this->IP,host,MAXBUF);
116 timeout_end = time(NULL) + maxtime;
122 void InspSocket::SetQueues(int nfd)
124 // attempt to increase socket sendq and recvq as high as its possible
127 setsockopt(nfd,SOL_SOCKET,SO_SNDBUF,(const void *)&sendbuf,sizeof(sendbuf));
128 setsockopt(nfd,SOL_SOCKET,SO_RCVBUF,(const void *)&recvbuf,sizeof(sendbuf));
131 bool InspSocket::DoResolve()
133 log(DEBUG,"In DoResolve(), trying to resolve IP");
134 if (this->dns.HasResult())
136 log(DEBUG,"Socket has result");
137 std::string res_ip = dns.GetResultIP();
140 log(DEBUG,"Socket result set to %s",res_ip.c_str());
141 strlcpy(this->IP,res_ip.c_str(),MAXBUF);
142 socket_ref[this->fd] = NULL;
146 log(DEBUG,"Socket DNS failure");
148 this->state = I_ERROR;
149 this->OnError(I_ERR_RESOLVE);
151 this->ClosePending = true;
154 return this->DoConnect();
156 log(DEBUG,"No result for socket yet!");
160 bool InspSocket::BindAddr()
165 log(DEBUG,"In InspSocket::BindAddr()");
166 for (int j =0; j < Conf.Enumerate("bind"); j++)
168 std::string Type = Conf.ReadValue("bind","type",j);
169 std::string IP = Conf.ReadValue("bind","address",j);
170 if (Type == "servers")
172 if ((IP != "*") && (IP != "127.0.0.1"))
176 if (inet_aton(IP.c_str(),&n))
178 log(DEBUG,"Found an IP to bind to: %s",IP.c_str());
180 s.sin_family = AF_INET;
181 if (bind(this->fd,(struct sockaddr*)&s,sizeof(s)) < 0)
183 log(DEBUG,"Cant bind()");
184 this->state = I_ERROR;
185 this->OnError(I_ERR_BIND);
189 log(DEBUG,"bind() reports outbound fd bound to ip %s",IP.c_str());
194 log(DEBUG,"Address '%s' was not an IP address",IP.c_str());
199 log(DEBUG,"Found no suitable IPs to bind, binding INADDR_ANY");
203 bool InspSocket::DoConnect()
205 log(DEBUG,"In DoConnect()");
206 if ((this->fd = socket(AF_INET, SOCK_STREAM, 0)) == -1)
208 log(DEBUG,"Cant socket()");
209 this->state = I_ERROR;
210 this->OnError(I_ERR_SOCKET);
215 if (!this->BindAddr())
218 log(DEBUG,"Part 2 DoConnect() %s",this->IP);
219 inet_aton(this->IP,&addy);
220 addr.sin_family = AF_INET;
221 addr.sin_addr = addy;
222 addr.sin_port = htons(this->port);
225 flags = fcntl(this->fd, F_GETFL, 0);
226 fcntl(this->fd, F_SETFL, flags | O_NONBLOCK);
228 if (connect(this->fd, (sockaddr*)&this->addr,sizeof(this->addr)) == -1)
230 if (errno != EINPROGRESS)
232 log(DEBUG,"Error connect() %d: %s",this->fd,strerror(errno));
233 this->OnError(I_ERR_CONNECT);
235 this->state = I_ERROR;
237 this->ClosePending = true;
241 this->state = I_CONNECTING;
244 ServerInstance->SE->AddFd(this->fd,false,X_ESTAB_MODULE);
245 socket_ref[this->fd] = this;
246 this->SetQueues(this->fd);
248 log(DEBUG,"Returning true from InspSocket::DoConnect");
253 void InspSocket::Close()
258 shutdown(this->fd,2);
260 socket_ref[this->fd] = NULL;
261 this->ClosePending = true;
266 std::string InspSocket::GetIP()
271 char* InspSocket::Read()
273 if ((fd < 0) || (fd > MAX_DESCRIPTORS))
275 int n = recv(this->fd,this->ibuf,sizeof(this->ibuf),0);
276 if ((n > 0) && (n <= (int)sizeof(this->ibuf)))
289 log(DEBUG,"EOF or error on socket: %s",strerror(errno));
295 void InspSocket::MarkAsClosed()
297 log(DEBUG,"Marked as closed");
298 this->ClosePending = true;
301 // There are two possible outcomes to this function.
302 // It will either write all of the data, or an undefined amount.
303 // If an undefined amount is written the connection has failed
304 // and should be aborted.
305 int InspSocket::Write(const std::string &data)
307 if (this->ClosePending)
310 /*int result = write(this->fd,data.c_str(),data.length());
315 /* Try and append the data to the back of the queue, and send it on its way
317 outbuffer.push_back(data);
318 return (!this->FlushWriteBuffer());
321 bool InspSocket::FlushWriteBuffer()
323 if (this->ClosePending)
326 if ((this->fd > -1) && (this->state == I_CONNECTED))
328 if (outbuffer.size())
330 int result = write(this->fd,outbuffer[0].c_str(),outbuffer[0].length());
333 if ((unsigned int)result == outbuffer[0].length())
335 /* The whole block was written (usually a line)
336 * Pop the block off the front of the queue
338 outbuffer.pop_front();
342 std::string temp = outbuffer[0].substr(result);
346 else if ((result == -1) && (errno != EAGAIN))
348 log(DEBUG,"Write error on socket: %s",strerror(errno));
349 this->OnError(I_ERR_WRITE);
350 this->state = I_ERROR;
351 this->ClosePending = true;
359 bool InspSocket::Timeout(time_t current)
361 if (!socket_ref[this->fd] || !ServerInstance->SE->HasFd(this->fd))
363 log(DEBUG,"No FD or socket ref");
367 if (this->ClosePending)
369 log(DEBUG,"Close is pending");
373 if (((this->state == I_RESOLVING) || (this->state == I_CONNECTING)) && (current > timeout_end))
375 log(DEBUG,"Timed out, current=%lu timeout_end=%lu");
376 // for non-listening sockets, the timeout can occur
377 // which causes termination of the connection after
378 // the given number of seconds without a successful
381 this->OnError(I_ERR_TIMEOUT);
383 this->state = I_ERROR;
384 this->ClosePending = true;
387 return this->FlushWriteBuffer();
390 bool InspSocket::Poll()
392 if (!socket_ref[this->fd] || !ServerInstance->SE->HasFd(this->fd))
398 if ((fd < 0) || (fd > MAX_DESCRIPTORS) || (this->ClosePending))
404 log(DEBUG,"State = I_RESOLVING, calling DoResolve()");
405 return this->DoResolve();
408 log(DEBUG,"State = I_CONNECTING");
409 this->SetState(I_CONNECTED);
410 /* Our socket was in write-state, so delete it and re-add it
415 ServerInstance->SE->DelFd(this->fd);
416 ServerInstance->SE->AddFd(this->fd,true,X_ESTAB_MODULE);
418 return this->OnConnected();
421 length = sizeof (client);
422 incoming = accept (this->fd, (sockaddr*)&client,&length);
423 this->SetQueues(incoming);
424 this->OnIncomingConnection(incoming,inet_ntoa(client.sin_addr));
428 n = this->OnDataReady();
429 /* Flush any pending, but not till after theyre done with the event
430 * so there are less write calls involved.
431 * Both FlushWriteBuffer AND the return result of OnDataReady must
432 * return true for this to be ok.
434 if (this->FlushWriteBuffer())
444 void InspSocket::SetState(InspSocketState s)
446 log(DEBUG,"Socket state change");
450 InspSocketState InspSocket::GetState()
455 int InspSocket::GetFd()
460 bool InspSocket::OnConnected() { return true; }
461 void InspSocket::OnError(InspSocketError e) { return; }
462 int InspSocket::OnDisconnect() { return 0; }
463 int InspSocket::OnIncomingConnection(int newfd, char* ip) { return 0; }
464 bool InspSocket::OnDataReady() { return true; }
465 void InspSocket::OnTimeout() { return; }
466 void InspSocket::OnClose() { return; }
468 InspSocket::~InspSocket()