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"
24 #include "configreader.h"
25 #include "inspstring.h"
27 #include "socketengine.h"
30 using irc::sockets::OpenTCPSocket;
31 using irc::sockets::insp_inaddr;
32 using irc::sockets::insp_sockaddr;
34 InspSocket::InspSocket(InspIRCd* SI)
36 this->state = I_DISCONNECTED;
38 this->ClosePending = false;
42 InspSocket::InspSocket(InspIRCd* SI, int newfd, const char* ip)
45 this->state = I_CONNECTED;
46 strlcpy(this->IP,ip,MAXBUF);
47 this->ClosePending = false;
51 this->ClosePending = (!this->Instance->SE->AddFd(this->fd,true,X_ESTAB_MODULE));
52 this->Instance->socket_ref[this->fd] = this;
56 InspSocket::InspSocket(InspIRCd* SI, const std::string &ipaddr, int aport, bool listening, unsigned long maxtime) : fd(-1)
59 strlcpy(host,ipaddr.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 this->Instance->Log(DEBUG,"OpenTCPSocket() error");
73 if (!SI->BindSocket(this->fd,this->client,this->server,aport,(char*)ipaddr.c_str()))
75 this->Instance->Log(DEBUG,"BindSocket() error %s",strerror(errno));
78 this->state = I_ERROR;
79 this->OnError(I_ERR_BIND);
80 this->ClosePending = true;
85 this->state = I_LISTENING;
88 if (!this->Instance->SE->AddFd(this->fd,true,X_ESTAB_MODULE))
91 this->state = I_ERROR;
92 this->OnError(I_ERR_NOMOREFDS);
93 this->ClosePending = true;
95 this->Instance->socket_ref[this->fd] = this;
97 this->Instance->Log(DEBUG,"New socket now in I_LISTENING state");
104 strlcpy(this->host,ipaddr.c_str(),MAXBUF);
107 if (insp_aton(host,&addy) < 1)
109 this->Instance->Log(DEBUG,"You cannot pass hostnames to InspSocket, resolve them first with Resolver!");
112 this->state = I_ERROR;
113 this->OnError(I_ERR_RESOLVE);
114 this->ClosePending = true;
119 this->Instance->Log(DEBUG,"No need to resolve %s",this->host);
120 strlcpy(this->IP,host,MAXBUF);
121 timeout_end = time(NULL) + maxtime;
127 void InspSocket::WantWrite()
130 * The socket engine may only have each FD in the list ONCE.
131 * This means we cant watch for write AND read at the same
132 * time. We have to remove the READ fd, to insert the WRITE
133 * fd. Once we receive our WRITE event (which WILL ARRIVE,
134 * pretty much gauranteed) we switch back to watching for
137 * This behaviour may be fixed in a later version.
139 this->WaitingForWriteEvent = true;
140 this->Instance->SE->DelFd(this->fd);
141 if (!this->Instance->SE->AddFd(this->fd,false,X_ESTAB_MODULE))
145 this->state = I_ERROR;
146 this->OnError(I_ERR_NOMOREFDS);
147 this->ClosePending = true;
151 void InspSocket::SetQueues(int nfd)
153 // attempt to increase socket sendq and recvq as high as its possible
156 setsockopt(nfd,SOL_SOCKET,SO_SNDBUF,(const void *)&sendbuf,sizeof(sendbuf));
157 setsockopt(nfd,SOL_SOCKET,SO_RCVBUF,(const void *)&recvbuf,sizeof(sendbuf));
160 /* Most irc servers require you to specify the ip you want to bind to.
161 * If you dont specify an IP, they rather dumbly bind to the first IP
162 * of the box (e.g. INADDR_ANY). In InspIRCd, we scan thought the IP
163 * addresses we've bound server ports to, and we try and bind our outbound
164 * connections to the first usable non-loopback and non-any IP we find.
165 * This is easier to configure when you have a lot of links and a lot
166 * of servers to configure.
168 bool InspSocket::BindAddr()
171 ConfigReader Conf(this->Instance);
173 this->Instance->Log(DEBUG,"In InspSocket::BindAddr()");
174 for (int j =0; j < Conf.Enumerate("bind"); j++)
176 std::string Type = Conf.ReadValue("bind","type",j);
177 std::string IP = Conf.ReadValue("bind","address",j);
178 if (Type == "servers")
180 if ((IP != "*") && (IP != "127.0.0.1") && (IP != ""))
184 if (insp_aton(IP.c_str(),&n) > 0)
186 this->Instance->Log(DEBUG,"Found an IP to bind to: %s",IP.c_str());
189 s.sin6_family = AF_FAMILY;
192 s.sin_family = AF_FAMILY;
194 if (bind(this->fd,(struct sockaddr*)&s,sizeof(s)) < 0)
196 this->Instance->Log(DEBUG,"Cant bind()");
197 this->state = I_ERROR;
198 this->OnError(I_ERR_BIND);
202 this->Instance->Log(DEBUG,"bind() reports outbound fd bound to ip %s",IP.c_str());
207 this->Instance->Log(DEBUG,"Address '%s' was not an IP address",IP.c_str());
212 this->Instance->Log(DEBUG,"Found no suitable IPs to bind, binding INADDR_ANY");
216 bool InspSocket::DoConnect()
218 this->Instance->Log(DEBUG,"In DoConnect()");
219 if ((this->fd = socket(AF_FAMILY, SOCK_STREAM, 0)) == -1)
221 this->Instance->Log(DEBUG,"Cant socket()");
222 this->state = I_ERROR;
223 this->OnError(I_ERR_SOCKET);
228 if ((strstr(this->IP,"::ffff:") != (char*)&this->IP) && (strstr(this->IP,"::FFFF:") != (char*)&this->IP))
230 if (!this->BindAddr())
234 this->Instance->Log(DEBUG,"Part 2 DoConnect() %s",this->IP);
235 insp_aton(this->IP,&addy);
237 addr.sin6_family = AF_FAMILY;
238 memcpy(&addr.sin6_addr, &addy, sizeof(insp_inaddr));
239 addr.sin6_port = htons(this->port);
241 addr.sin_family = AF_FAMILY;
242 addr.sin_addr = addy;
243 addr.sin_port = htons(this->port);
247 flags = fcntl(this->fd, F_GETFL, 0);
248 fcntl(this->fd, F_SETFL, flags | O_NONBLOCK);
250 if (connect(this->fd, (sockaddr*)&this->addr,sizeof(this->addr)) == -1)
252 if (errno != EINPROGRESS)
254 this->Instance->Log(DEBUG,"Error connect() %d: %s",this->fd,strerror(errno));
255 this->OnError(I_ERR_CONNECT);
257 this->state = I_ERROR;
259 this->ClosePending = true;
263 this->state = I_CONNECTING;
266 if (!this->Instance->SE->AddFd(this->fd,false,X_ESTAB_MODULE))
268 this->OnError(I_ERR_NOMOREFDS);
271 this->state = I_ERROR;
272 this->ClosePending = true;
275 this->Instance->socket_ref[this->fd] = this;
276 this->SetQueues(this->fd);
278 this->Instance->Log(DEBUG,"Returning true from InspSocket::DoConnect");
283 void InspSocket::Close()
288 shutdown(this->fd,2);
290 this->Instance->socket_ref[this->fd] = NULL;
291 this->ClosePending = true;
296 std::string InspSocket::GetIP()
301 char* InspSocket::Read()
303 if ((fd < 0) || (fd > MAX_DESCRIPTORS))
305 int n = recv(this->fd,this->ibuf,sizeof(this->ibuf),0);
306 if ((n > 0) && (n <= (int)sizeof(this->ibuf)))
319 this->Instance->Log(DEBUG,"EOF or error on socket: %s",strerror(errno));
325 void InspSocket::MarkAsClosed()
327 this->Instance->Log(DEBUG,"Marked as closed");
328 this->ClosePending = true;
331 // There are two possible outcomes to this function.
332 // It will either write all of the data, or an undefined amount.
333 // If an undefined amount is written the connection has failed
334 // and should be aborted.
335 int InspSocket::Write(const std::string &data)
337 if (this->ClosePending)
340 /*int result = write(this->fd,data.c_str(),data.length());
345 /* Try and append the data to the back of the queue, and send it on its way
347 outbuffer.push_back(data);
348 return (!this->FlushWriteBuffer());
351 bool InspSocket::FlushWriteBuffer()
353 if (this->ClosePending)
356 if ((this->fd > -1) && (this->state == I_CONNECTED))
358 if (outbuffer.size())
360 int result = write(this->fd,outbuffer[0].c_str(),outbuffer[0].length());
363 if ((unsigned int)result == outbuffer[0].length())
365 /* The whole block was written (usually a line)
366 * Pop the block off the front of the queue
368 outbuffer.pop_front();
372 std::string temp = outbuffer[0].substr(result);
376 else if ((result == -1) && (errno != EAGAIN))
378 this->Instance->Log(DEBUG,"Write error on socket: %s",strerror(errno));
379 this->OnError(I_ERR_WRITE);
380 this->state = I_ERROR;
381 this->ClosePending = true;
389 bool InspSocket::Timeout(time_t current)
391 if (!this->Instance->socket_ref[this->fd] || !this->Instance->SE->HasFd(this->fd))
393 this->Instance->Log(DEBUG,"No FD or socket ref");
397 if (this->ClosePending)
399 this->Instance->Log(DEBUG,"Close is pending");
403 if ((this->state == I_CONNECTING) && (current > timeout_end))
405 this->Instance->Log(DEBUG,"Timed out, current=%lu timeout_end=%lu");
406 // for non-listening sockets, the timeout can occur
407 // which causes termination of the connection after
408 // the given number of seconds without a successful
411 this->OnError(I_ERR_TIMEOUT);
413 this->state = I_ERROR;
414 this->ClosePending = true;
417 return this->FlushWriteBuffer();
420 bool InspSocket::Poll()
422 if (!this->Instance->socket_ref[this->fd] || !this->Instance->SE->HasFd(this->fd))
428 if ((fd < 0) || (fd > MAX_DESCRIPTORS) || (this->ClosePending))
434 this->Instance->Log(DEBUG,"State = I_CONNECTING");
435 this->SetState(I_CONNECTED);
436 /* Our socket was in write-state, so delete it and re-add it
441 this->Instance->SE->DelFd(this->fd);
442 if (!this->Instance->SE->AddFd(this->fd,true,X_ESTAB_MODULE))
445 return this->OnConnected();
448 length = sizeof (client);
449 incoming = accept (this->fd, (sockaddr*)&client,&length);
450 this->SetQueues(incoming);
452 this->OnIncomingConnection(incoming,(char*)insp_ntoa(client.sin6_addr));
454 this->OnIncomingConnection(incoming,(char*)insp_ntoa(client.sin_addr));
460 if (this->WaitingForWriteEvent)
462 /* Switch back to read events */
463 this->Instance->SE->DelFd(this->fd);
464 if (!this->Instance->SE->AddFd(this->fd,true,X_ESTAB_MODULE))
467 /* Trigger the write event */
468 n = this->OnWriteReady();
472 /* Process the read event */
473 n = this->OnDataReady();
475 /* Flush any pending, but not till after theyre done with the event
476 * so there are less write calls involved.
477 * Both FlushWriteBuffer AND the return result of OnDataReady must
478 * return true for this to be ok.
480 if (this->FlushWriteBuffer())
490 void InspSocket::SetState(InspSocketState s)
492 this->Instance->Log(DEBUG,"Socket state change");
496 InspSocketState InspSocket::GetState()
501 int InspSocket::GetFd()
506 bool InspSocket::OnConnected() { return true; }
507 void InspSocket::OnError(InspSocketError e) { return; }
508 int InspSocket::OnDisconnect() { return 0; }
509 int InspSocket::OnIncomingConnection(int newfd, char* ip) { return 0; }
510 bool InspSocket::OnDataReady() { return true; }
511 bool InspSocket::OnWriteReady() { return true; }
512 void InspSocket::OnTimeout() { return; }
513 void InspSocket::OnClose() { return; }
515 InspSocket::~InspSocket()