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 * ---------------------------------------------------
19 #include "inspircd_config.h"
21 #include <sys/resource.h>
22 #include <sys/types.h>
23 #include <sys/socket.h>
24 #include <netinet/in.h>
35 #include "inspircd_io.h"
36 #include "inspstring.h"
37 #include "helperfuncs.h"
38 #include "socketengine.h"
41 extern InspIRCd* ServerInstance;
42 extern ServerConfig* Config;
45 InspSocket* socket_ref[MAX_DESCRIPTORS];
47 InspSocket::InspSocket()
49 this->state = I_DISCONNECTED;
51 this->ClosePending = false;
54 InspSocket::InspSocket(int newfd, char* ip)
57 this->state = I_CONNECTED;
59 this->ClosePending = false;
60 ServerInstance->SE->AddFd(this->fd,true,X_ESTAB_MODULE);
61 socket_ref[this->fd] = this;
64 InspSocket::InspSocket(const std::string &ahost, int aport, bool listening, unsigned long maxtime) : fd(-1), host(ahost)
66 this->ClosePending = false;
67 this->outbuffer.clear();
69 if ((this->fd = OpenTCPSocket()) == ERROR)
72 this->state = I_ERROR;
73 this->OnError(I_ERR_SOCKET);
74 log(DEBUG,"OpenTCPSocket() error");
79 if (BindSocket(this->fd,this->client,this->server,aport,(char*)ahost.c_str()) == ERROR)
83 this->state = I_ERROR;
84 this->OnError(I_ERR_BIND);
85 log(DEBUG,"BindSocket() error %s",strerror(errno));
90 this->state = I_LISTENING;
91 ServerInstance->SE->AddFd(this->fd,true,X_ESTAB_MODULE);
92 socket_ref[this->fd] = this;
93 log(DEBUG,"New socket now in I_LISTENING state");
103 if (!inet_aton(host.c_str(),&addy))
105 log(DEBUG,"Attempting to resolve %s",this->host.c_str());
106 /* Its not an ip, spawn the resolver */
107 this->dns.SetNS(std::string(Config->DNSServer));
108 this->dns.ForwardLookupWithFD(host,fd);
109 timeout_end = time(NULL) + maxtime;
111 this->state = I_RESOLVING;
112 socket_ref[this->fd] = this;
116 log(DEBUG,"No need to resolve %s",this->host.c_str());
118 timeout_end = time(NULL) + maxtime;
124 void InspSocket::SetQueues(int nfd)
126 // attempt to increase socket sendq and recvq as high as its possible
129 setsockopt(nfd,SOL_SOCKET,SO_SNDBUF,(const void *)&sendbuf,sizeof(sendbuf));
130 setsockopt(nfd,SOL_SOCKET,SO_RCVBUF,(const void *)&recvbuf,sizeof(sendbuf));
133 bool InspSocket::DoResolve()
135 log(DEBUG,"In DoResolve(), trying to resolve IP");
136 if (this->dns.HasResult())
138 log(DEBUG,"Socket has result");
139 std::string res_ip = dns.GetResultIP();
142 log(DEBUG,"Socket result set to %s",res_ip.c_str());
144 socket_ref[this->fd] = NULL;
148 log(DEBUG,"Socket DNS failure");
150 this->state = I_ERROR;
151 this->OnError(I_ERR_RESOLVE);
155 return this->DoConnect();
157 log(DEBUG,"No result for socket yet!");
161 bool InspSocket::DoConnect()
163 log(DEBUG,"In DoConnect()");
164 if ((this->fd = socket(AF_INET, SOCK_STREAM, 0)) == -1)
166 log(DEBUG,"Cant socket()");
167 this->state = I_ERROR;
168 this->OnError(I_ERR_SOCKET);
173 log(DEBUG,"Part 2 DoConnect() %s",this->IP.c_str());
174 inet_aton(this->IP.c_str(),&addy);
175 addr.sin_family = AF_INET;
176 addr.sin_addr = addy;
177 addr.sin_port = htons(this->port);
180 flags = fcntl(this->fd, F_GETFL, 0);
181 fcntl(this->fd, F_SETFL, flags | O_NONBLOCK);
183 if (connect(this->fd, (sockaddr*)&this->addr,sizeof(this->addr)) == -1)
185 if (errno != EINPROGRESS)
187 log(DEBUG,"Error connect() %d: %s",this->fd,strerror(errno));
188 this->OnError(I_ERR_CONNECT);
189 this->state = I_ERROR;
195 this->state = I_CONNECTING;
196 ServerInstance->SE->AddFd(this->fd,false,X_ESTAB_MODULE);
197 socket_ref[this->fd] = this;
198 this->SetQueues(this->fd);
199 log(DEBUG,"Returning true from InspSocket::DoConnect");
204 void InspSocket::Close()
209 shutdown(this->fd,2);
211 socket_ref[this->fd] = NULL;
216 std::string InspSocket::GetIP()
221 char* InspSocket::Read()
223 if ((fd < 0) || (fd > MAX_DESCRIPTORS))
225 int n = recv(this->fd,this->ibuf,sizeof(this->ibuf),0);
226 if ((n > 0) && (n <= (int)sizeof(this->ibuf)))
239 log(DEBUG,"EOF or error on socket: %s",strerror(errno));
245 void InspSocket::MarkAsClosed()
247 log(DEBUG,"Marked as closed");
248 this->ClosePending = true;
251 // There are two possible outcomes to this function.
252 // It will either write all of the data, or an undefined amount.
253 // If an undefined amount is written the connection has failed
254 // and should be aborted.
255 int InspSocket::Write(const std::string &data)
257 if (this->ClosePending)
259 /* Try and append the data to the back of the queue, and send it on its way
261 outbuffer.push_back(data);
262 return (!this->FlushWriteBuffer());
265 bool InspSocket::FlushWriteBuffer()
267 if (this->ClosePending)
270 if ((this->fd > -1) && (this->state == I_CONNECTED))
272 if (outbuffer.size())
274 log(DEBUG,"Writing %d to socket",outbuffer.size())
275 int result = write(this->fd,outbuffer[0].c_str(),outbuffer[0].length());
278 log(DEBUG,"Wrote %d to socket",result);
279 if ((unsigned int)result == outbuffer[0].length())
281 /* The whole block was written (usually a line)
282 * Pop the block off the front of the queue
284 log(DEBUG,"Popping front item, now %d items left",outbuffer.size());
285 outbuffer.pop_front();
289 log(DEBUG,"Cutting front item");
290 std::string temp = outbuffer[0].substr(result);
292 log(DEBUG,"Front item is now: ",outbuffer[0].c_str());
295 else if ((result == -1) && (errno != EAGAIN))
297 log(DEBUG,"Write error on socket: %s",strerror(errno));
298 this->OnError(I_ERR_WRITE);
299 this->state = I_ERROR;
307 bool InspSocket::Timeout(time_t current)
309 if (!socket_ref[this->fd] || !ServerInstance->SE->HasFd(this->fd))
311 log(DEBUG,"No FD or socket ref");
315 if (this->ClosePending)
317 log(DEBUG,"Close is pending");
321 if (((this->state == I_RESOLVING) || (this->state == I_CONNECTING)) && (current > timeout_end))
323 log(DEBUG,"Timed out, current=%lu timeout_end=%lu");
324 // for non-listening sockets, the timeout can occur
325 // which causes termination of the connection after
326 // the given number of seconds without a successful
329 this->OnError(I_ERR_TIMEOUT);
331 this->state = I_ERROR;
334 return this->FlushWriteBuffer();
337 bool InspSocket::Poll()
339 if (!socket_ref[this->fd] || !ServerInstance->SE->HasFd(this->fd))
345 if ((fd < 0) || (fd > MAX_DESCRIPTORS) || (this->ClosePending))
351 log(DEBUG,"State = I_RESOLVING, calling DoResolve()");
352 return this->DoResolve();
355 log(DEBUG,"State = I_CONNECTING");
356 this->SetState(I_CONNECTED);
357 /* Our socket was in write-state, so delete it and re-add it
360 ServerInstance->SE->DelFd(this->fd);
361 ServerInstance->SE->AddFd(this->fd,true,X_ESTAB_MODULE);
362 return this->OnConnected();
365 length = sizeof (client);
366 incoming = accept (this->fd, (sockaddr*)&client,&length);
367 this->SetQueues(incoming);
368 this->OnIncomingConnection(incoming,inet_ntoa(client.sin_addr));
372 n = this->OnDataReady();
373 /* Flush any pending, but not till after theyre done with the event
374 * so there are less write calls involved.
375 * Both FlushWriteBuffer AND the return result of OnDataReady must
376 * return true for this to be ok.
378 return (n && !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()