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;
53 InspSocket::InspSocket(int newfd, char* ip)
56 this->state = I_CONNECTED;
58 ServerInstance->SE->AddFd(this->fd,true,X_ESTAB_MODULE);
59 socket_ref[this->fd] = this;
62 InspSocket::InspSocket(const std::string &ahost, int aport, bool listening, unsigned long maxtime)
65 this->outbuffer.clear();
67 if ((this->fd = OpenTCPSocket()) == ERROR)
70 this->state = I_ERROR;
71 this->OnError(I_ERR_SOCKET);
72 log(DEBUG,"OpenTCPSocket() error");
77 if (BindSocket(this->fd,this->client,this->server,aport,(char*)ahost.c_str()) == ERROR)
81 this->state = I_ERROR;
82 this->OnError(I_ERR_BIND);
83 log(DEBUG,"BindSocket() error %s",strerror(errno));
88 this->state = I_LISTENING;
89 ServerInstance->SE->AddFd(this->fd,true,X_ESTAB_MODULE);
90 socket_ref[this->fd] = this;
91 log(DEBUG,"New socket now in I_LISTENING state");
101 if (!inet_aton(host.c_str(),&addy))
103 log(DEBUG,"Attempting to resolve %s",this->host.c_str());
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.c_str());
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());
142 socket_ref[this->fd] = NULL;
146 log(DEBUG,"Socket DNS failure");
148 this->state = I_ERROR;
149 this->OnError(I_ERR_RESOLVE);
153 return this->DoConnect();
155 log(DEBUG,"No result for socket yet!");
159 bool InspSocket::DoConnect()
161 log(DEBUG,"In DoConnect()");
162 if ((this->fd = socket(AF_INET, SOCK_STREAM, 0)) == -1)
164 log(DEBUG,"Cant socket()");
165 this->state = I_ERROR;
166 this->OnError(I_ERR_SOCKET);
171 log(DEBUG,"Part 2 DoConnect() %s",this->IP.c_str());
172 inet_aton(this->IP.c_str(),&addy);
173 addr.sin_family = AF_INET;
174 addr.sin_addr = addy;
175 addr.sin_port = htons(this->port);
178 flags = fcntl(this->fd, F_GETFL, 0);
179 fcntl(this->fd, F_SETFL, flags | O_NONBLOCK);
181 if (connect(this->fd, (sockaddr*)&this->addr,sizeof(this->addr)) == -1)
183 if (errno != EINPROGRESS)
185 log(DEBUG,"Error connect() %d: %s",this->fd,strerror(errno));
186 this->OnError(I_ERR_CONNECT);
187 this->state = I_ERROR;
193 this->state = I_CONNECTING;
194 ServerInstance->SE->AddFd(this->fd,false,X_ESTAB_MODULE);
195 socket_ref[this->fd] = this;
196 this->SetQueues(this->fd);
197 log(DEBUG,"Returning true from InspSocket::DoConnect");
202 void InspSocket::Close()
207 shutdown(this->fd,2);
209 socket_ref[this->fd] = NULL;
214 std::string InspSocket::GetIP()
219 char* InspSocket::Read()
221 if ((fd < 0) || (fd > MAX_DESCRIPTORS))
223 int n = recv(this->fd,this->ibuf,sizeof(this->ibuf),0);
224 if ((n > 0) && (n <= (int)sizeof(this->ibuf)))
237 log(DEBUG,"EOF or error on socket: %s",strerror(errno));
243 // There are two possible outcomes to this function.
244 // It will either write all of the data, or an undefined amount.
245 // If an undefined amount is written the connection has failed
246 // and should be aborted.
247 int InspSocket::Write(const std::string &data)
249 /* Try and append the data to the back of the queue, and send it on its way
251 outbuffer.push_back(data);
252 return (!this->FlushWriteBuffer());
255 bool InspSocket::FlushWriteBuffer()
257 if ((this->fd > -1) && (this->state == I_CONNECTED))
259 if (outbuffer.size())
261 int result = write(this->fd,outbuffer[0].c_str(),outbuffer[0].length());
264 if ((unsigned int)result == outbuffer[0].length())
266 /* The whole block was written (usually a line)
267 * Pop the block off the front of the queue
269 outbuffer.pop_front();
273 outbuffer[0] = outbuffer[0].substr(result + 1,outbuffer[0].length());
276 else if ((result == -1) && (errno != EAGAIN))
278 log(DEBUG,"Write error on socket: %s",strerror(errno));
279 this->OnError(I_ERR_WRITE);
280 this->state = I_ERROR;
288 bool InspSocket::Timeout(time_t current)
290 if (!socket_ref[this->fd] || !ServerInstance->SE->HasFd(this->fd))
293 if (((this->state == I_RESOLVING) || (this->state == I_CONNECTING)) && (current > timeout_end))
295 log(DEBUG,"Timed out, current=%lu timeout_end=%lu");
296 // for non-listening sockets, the timeout can occur
297 // which causes termination of the connection after
298 // the given number of seconds without a successful
301 this->OnError(I_ERR_TIMEOUT);
303 this->state = I_ERROR;
306 return this->FlushWriteBuffer();
309 bool InspSocket::Poll()
311 if (!socket_ref[this->fd] || !ServerInstance->SE->HasFd(this->fd))
317 if ((fd < 0) || (fd > MAX_DESCRIPTORS))
323 log(DEBUG,"State = I_RESOLVING, calling DoResolve()");
324 return this->DoResolve();
327 log(DEBUG,"State = I_CONNECTING");
328 this->SetState(I_CONNECTED);
329 /* Our socket was in write-state, so delete it and re-add it
332 ServerInstance->SE->DelFd(this->fd);
333 ServerInstance->SE->AddFd(this->fd,true,X_ESTAB_MODULE);
334 return this->OnConnected();
337 length = sizeof (client);
338 incoming = accept (this->fd, (sockaddr*)&client,&length);
339 this->SetQueues(incoming);
340 this->OnIncomingConnection(incoming,inet_ntoa(client.sin_addr));
344 n = this->OnDataReady();
345 /* Flush any pending, but not till after theyre done with the event
346 * so there are less write calls involved.
347 * Both FlushWriteBuffer AND the return result of OnDataReady must
348 * return true for this to be ok.
350 return (n && !this->FlushWriteBuffer());
358 void InspSocket::SetState(InspSocketState s)
360 log(DEBUG,"Socket state change");
364 InspSocketState InspSocket::GetState()
369 int InspSocket::GetFd()
374 bool InspSocket::OnConnected() { return true; }
375 void InspSocket::OnError(InspSocketError e) { return; }
376 int InspSocket::OnDisconnect() { return 0; }
377 int InspSocket::OnIncomingConnection(int newfd, char* ip) { return 0; }
378 bool InspSocket::OnDataReady() { return true; }
379 void InspSocket::OnTimeout() { return; }
380 void InspSocket::OnClose() { return; }
382 InspSocket::~InspSocket()