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;
50 ServerInstance->SE->AddFd(this->fd,true,X_ESTAB_MODULE);
51 socket_ref[this->fd] = this;
54 InspSocket::InspSocket(const std::string &ahost, int aport, bool listening, unsigned long maxtime) : fd(-1)
56 strlcpy(host,ahost.c_str(),MAXBUF);
57 this->ClosePending = false;
59 if ((this->fd = OpenTCPSocket()) == ERROR)
62 this->state = I_ERROR;
63 this->OnError(I_ERR_SOCKET);
64 this->ClosePending = true;
65 log(DEBUG,"OpenTCPSocket() error");
70 if (!BindSocket(this->fd,this->client,this->server,aport,(char*)ahost.c_str()))
74 this->state = I_ERROR;
75 this->OnError(I_ERR_BIND);
76 this->ClosePending = true;
77 log(DEBUG,"BindSocket() error %s",strerror(errno));
82 this->state = I_LISTENING;
83 ServerInstance->SE->AddFd(this->fd,true,X_ESTAB_MODULE);
84 socket_ref[this->fd] = this;
85 log(DEBUG,"New socket now in I_LISTENING state");
92 strlcpy(this->host,ahost.c_str(),MAXBUF);
95 if (!inet_aton(host,&addy))
97 log(DEBUG,"Attempting to resolve %s",this->host);
98 /* Its not an ip, spawn the resolver */
99 this->dns.SetNS(std::string(Config->DNSServer));
100 this->dns.ForwardLookupWithFD(host,fd);
101 timeout_end = time(NULL) + maxtime;
103 this->state = I_RESOLVING;
104 socket_ref[this->fd] = this;
108 log(DEBUG,"No need to resolve %s",this->host);
109 strlcpy(this->IP,host,MAXBUF);
110 timeout_end = time(NULL) + maxtime;
116 void InspSocket::SetQueues(int nfd)
118 // attempt to increase socket sendq and recvq as high as its possible
121 setsockopt(nfd,SOL_SOCKET,SO_SNDBUF,(const void *)&sendbuf,sizeof(sendbuf));
122 setsockopt(nfd,SOL_SOCKET,SO_RCVBUF,(const void *)&recvbuf,sizeof(sendbuf));
125 bool InspSocket::DoResolve()
127 log(DEBUG,"In DoResolve(), trying to resolve IP");
128 if (this->dns.HasResult())
130 log(DEBUG,"Socket has result");
131 std::string res_ip = dns.GetResultIP();
134 log(DEBUG,"Socket result set to %s",res_ip.c_str());
135 strlcpy(this->IP,res_ip.c_str(),MAXBUF);
136 socket_ref[this->fd] = NULL;
140 log(DEBUG,"Socket DNS failure");
142 this->state = I_ERROR;
143 this->OnError(I_ERR_RESOLVE);
145 this->ClosePending = true;
148 return this->DoConnect();
150 log(DEBUG,"No result for socket yet!");
154 bool InspSocket::DoConnect()
156 log(DEBUG,"In DoConnect()");
157 if ((this->fd = socket(AF_INET, SOCK_STREAM, 0)) == -1)
159 log(DEBUG,"Cant socket()");
160 this->state = I_ERROR;
161 this->OnError(I_ERR_SOCKET);
166 log(DEBUG,"Part 2 DoConnect() %s",this->IP);
167 inet_aton(this->IP,&addy);
168 addr.sin_family = AF_INET;
169 addr.sin_addr = addy;
170 addr.sin_port = htons(this->port);
173 flags = fcntl(this->fd, F_GETFL, 0);
174 fcntl(this->fd, F_SETFL, flags | O_NONBLOCK);
176 if (connect(this->fd, (sockaddr*)&this->addr,sizeof(this->addr)) == -1)
178 if (errno != EINPROGRESS)
180 log(DEBUG,"Error connect() %d: %s",this->fd,strerror(errno));
181 this->OnError(I_ERR_CONNECT);
183 this->state = I_ERROR;
185 this->ClosePending = true;
189 this->state = I_CONNECTING;
190 ServerInstance->SE->AddFd(this->fd,false,X_ESTAB_MODULE);
191 socket_ref[this->fd] = this;
192 this->SetQueues(this->fd);
193 log(DEBUG,"Returning true from InspSocket::DoConnect");
198 void InspSocket::Close()
203 shutdown(this->fd,2);
205 socket_ref[this->fd] = NULL;
206 this->ClosePending = true;
211 std::string InspSocket::GetIP()
216 char* InspSocket::Read()
218 if ((fd < 0) || (fd > MAX_DESCRIPTORS))
220 int n = recv(this->fd,this->ibuf,sizeof(this->ibuf),0);
221 if ((n > 0) && (n <= (int)sizeof(this->ibuf)))
234 log(DEBUG,"EOF or error on socket: %s",strerror(errno));
240 void InspSocket::MarkAsClosed()
242 log(DEBUG,"Marked as closed");
243 this->ClosePending = true;
246 // There are two possible outcomes to this function.
247 // It will either write all of the data, or an undefined amount.
248 // If an undefined amount is written the connection has failed
249 // and should be aborted.
250 int InspSocket::Write(const std::string &data)
252 if (this->ClosePending)
255 /*int result = write(this->fd,data.c_str(),data.length());
260 /* Try and append the data to the back of the queue, and send it on its way
262 outbuffer.push_back(data);
263 return (!this->FlushWriteBuffer());
266 bool InspSocket::FlushWriteBuffer()
268 if (this->ClosePending)
271 if ((this->fd > -1) && (this->state == I_CONNECTED))
273 if (outbuffer.size())
275 int result = write(this->fd,outbuffer[0].c_str(),outbuffer[0].length());
278 if ((unsigned int)result == outbuffer[0].length())
280 /* The whole block was written (usually a line)
281 * Pop the block off the front of the queue
283 outbuffer.pop_front();
287 std::string temp = outbuffer[0].substr(result);
291 else if ((result == -1) && (errno != EAGAIN))
293 log(DEBUG,"Write error on socket: %s",strerror(errno));
294 this->OnError(I_ERR_WRITE);
295 this->state = I_ERROR;
296 this->ClosePending = true;
304 bool InspSocket::Timeout(time_t current)
306 if (!socket_ref[this->fd] || !ServerInstance->SE->HasFd(this->fd))
308 log(DEBUG,"No FD or socket ref");
312 if (this->ClosePending)
314 log(DEBUG,"Close is pending");
318 if (((this->state == I_RESOLVING) || (this->state == I_CONNECTING)) && (current > timeout_end))
320 log(DEBUG,"Timed out, current=%lu timeout_end=%lu");
321 // for non-listening sockets, the timeout can occur
322 // which causes termination of the connection after
323 // the given number of seconds without a successful
326 this->OnError(I_ERR_TIMEOUT);
328 this->state = I_ERROR;
329 this->ClosePending = true;
332 return this->FlushWriteBuffer();
335 bool InspSocket::Poll()
337 if (!socket_ref[this->fd] || !ServerInstance->SE->HasFd(this->fd))
343 if ((fd < 0) || (fd > MAX_DESCRIPTORS) || (this->ClosePending))
349 log(DEBUG,"State = I_RESOLVING, calling DoResolve()");
350 return this->DoResolve();
353 log(DEBUG,"State = I_CONNECTING");
354 this->SetState(I_CONNECTED);
355 /* Our socket was in write-state, so delete it and re-add it
358 ServerInstance->SE->DelFd(this->fd);
359 ServerInstance->SE->AddFd(this->fd,true,X_ESTAB_MODULE);
360 return this->OnConnected();
363 length = sizeof (client);
364 incoming = accept (this->fd, (sockaddr*)&client,&length);
365 this->SetQueues(incoming);
366 this->OnIncomingConnection(incoming,inet_ntoa(client.sin_addr));
370 n = this->OnDataReady();
371 /* Flush any pending, but not till after theyre done with the event
372 * so there are less write calls involved.
373 * Both FlushWriteBuffer AND the return result of OnDataReady must
374 * return true for this to be ok.
376 if (this->FlushWriteBuffer())
386 void InspSocket::SetState(InspSocketState s)
388 log(DEBUG,"Socket state change");
392 InspSocketState InspSocket::GetState()
397 int InspSocket::GetFd()
402 bool InspSocket::OnConnected() { return true; }
403 void InspSocket::OnError(InspSocketError e) { return; }
404 int InspSocket::OnDisconnect() { return 0; }
405 int InspSocket::OnIncomingConnection(int newfd, char* ip) { return 0; }
406 bool InspSocket::OnDataReady() { return true; }
407 void InspSocket::OnTimeout() { return; }
408 void InspSocket::OnClose() { return; }
410 InspSocket::~InspSocket()