]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/inspsocket.cpp
9b691fc7f068920e2566ece4a2043ffa70f3a2fe
[user/henk/code/inspircd.git] / src / inspsocket.cpp
1 /*       +------------------------------------+
2  *       | Inspire Internet Relay Chat Daemon |
3  *       +------------------------------------+
4  *
5  *  InspIRCd is copyright (C) 2002-2006 ChatSpike-Dev.
6  *                       E-mail:
7  *                <brain@chatspike.net>
8  *                <Craig@chatspike.net>
9  *     
10  * Written by Craig Edwards, Craig McLure, and others.
11  * This program is free but copyrighted software; see
12  *            the file COPYING for details.
13  *
14  * ---------------------------------------------------
15  */
16
17 #include "socket.h"
18 #include "configreader.h"
19 #include "inspstring.h"
20 #include "socketengine.h"
21 #include "inspircd.h"
22
23 using irc::sockets::OpenTCPSocket;
24 using irc::sockets::insp_inaddr;
25 using irc::sockets::insp_sockaddr;
26
27 bool InspSocket::Readable()
28 {
29         return ((this->state != I_CONNECTING) && (this->WaitingForWriteEvent == false));
30 }
31
32 InspSocket::InspSocket(InspIRCd* SI)
33 {
34         this->state = I_DISCONNECTED;
35         this->fd = -1;
36         this->WaitingForWriteEvent = false;
37         this->Instance = SI;
38 }
39
40 InspSocket::InspSocket(InspIRCd* SI, int newfd, const char* ip)
41 {
42         this->fd = newfd;
43         this->state = I_CONNECTED;
44         strlcpy(this->IP,ip,MAXBUF);
45         this->WaitingForWriteEvent = false;
46         this->Instance = SI;
47         if (this->fd > -1)
48                 this->Instance->SE->AddFd(this);
49 }
50
51 InspSocket::InspSocket(InspIRCd* SI, const std::string &ipaddr, int aport, bool listening, unsigned long maxtime)
52 {
53         this->fd = -1;
54         this->Instance = SI;
55         strlcpy(host,ipaddr.c_str(),MAXBUF);
56         this->WaitingForWriteEvent = false;
57         if (listening)
58         {
59                 if ((this->fd = OpenTCPSocket()) == ERROR)
60                 {
61                         this->fd = -1;
62                         this->state = I_ERROR;
63                         this->OnError(I_ERR_SOCKET);
64                         this->Instance->Log(DEBUG,"OpenTCPSocket() error");
65                         return;
66                 }
67                 else
68                 {
69                         if (!SI->BindSocket(this->fd,this->client,this->server,aport,(char*)ipaddr.c_str()))
70                         {
71                                 this->Instance->Log(DEBUG,"BindSocket() error %s",strerror(errno));
72                                 this->Close();
73                                 this->fd = -1;
74                                 this->state = I_ERROR;
75                                 this->OnError(I_ERR_BIND);
76                                 this->ClosePending = true;
77                                 return;
78                         }
79                         else
80                         {
81                                 this->state = I_LISTENING;
82                                 if (this->fd > -1)
83                                 {
84                                         if (!this->Instance->SE->AddFd(this))
85                                         {
86                                                 this->Close();
87                                                 this->state = I_ERROR;
88                                                 this->OnError(I_ERR_NOMOREFDS);
89                                         }
90                                 }
91                                 this->Instance->Log(DEBUG,"New socket now in I_LISTENING state");
92                                 return;
93                         }
94                 }                       
95         }
96         else
97         {
98                 strlcpy(this->host,ipaddr.c_str(),MAXBUF);
99                 this->port = aport;
100
101                 if (insp_aton(host,&addy) < 1)
102                 {
103                         this->Instance->Log(DEBUG,"You cannot pass hostnames to InspSocket, resolve them first with Resolver!");
104                         this->Close();
105                         this->fd = -1;
106                         this->state = I_ERROR;
107                         this->OnError(I_ERR_RESOLVE);
108                         return;
109                 }
110                 else
111                 {
112                         this->Instance->Log(DEBUG,"No need to resolve %s",this->host);
113                         strlcpy(this->IP,host,MAXBUF);
114                         timeout_val = maxtime;
115                         this->DoConnect();
116                 }
117         }
118 }
119
120 void InspSocket::WantWrite()
121 {
122         this->Instance->SE->WantWrite(this);
123         this->WaitingForWriteEvent = true;
124 }
125
126 void InspSocket::SetQueues(int nfd)
127 {
128         // attempt to increase socket sendq and recvq as high as its possible
129         int sendbuf = 32768;
130         int recvbuf = 32768;
131         setsockopt(nfd,SOL_SOCKET,SO_SNDBUF,(const void *)&sendbuf,sizeof(sendbuf));
132         setsockopt(nfd,SOL_SOCKET,SO_RCVBUF,(const void *)&recvbuf,sizeof(sendbuf));
133 }
134
135 /* Most irc servers require you to specify the ip you want to bind to.
136  * If you dont specify an IP, they rather dumbly bind to the first IP
137  * of the box (e.g. INADDR_ANY). In InspIRCd, we scan thought the IP
138  * addresses we've bound server ports to, and we try and bind our outbound
139  * connections to the first usable non-loopback and non-any IP we find.
140  * This is easier to configure when you have a lot of links and a lot
141  * of servers to configure.
142  */
143 bool InspSocket::BindAddr()
144 {
145         insp_inaddr n;
146         ConfigReader Conf(this->Instance);
147
148         this->Instance->Log(DEBUG,"In InspSocket::BindAddr()");
149         for (int j =0; j < Conf.Enumerate("bind"); j++)
150         {
151                 std::string Type = Conf.ReadValue("bind","type",j);
152                 std::string IP = Conf.ReadValue("bind","address",j);
153                 if (Type == "servers")
154                 {
155                         if ((IP != "*") && (IP != "127.0.0.1") && (IP != ""))
156                         {
157                                 insp_sockaddr s;
158
159                                 if (insp_aton(IP.c_str(),&n) > 0)
160                                 {
161                                         this->Instance->Log(DEBUG,"Found an IP to bind to: %s",IP.c_str());
162 #ifdef IPV6
163                                         s.sin6_addr = n;
164                                         s.sin6_family = AF_FAMILY;
165 #else
166                                         s.sin_addr = n;
167                                         s.sin_family = AF_FAMILY;
168 #endif
169                                         if (bind(this->fd,(struct sockaddr*)&s,sizeof(s)) < 0)
170                                         {
171                                                 this->Instance->Log(DEBUG,"Cant bind()");
172                                                 this->state = I_ERROR;
173                                                 this->OnError(I_ERR_BIND);
174                                                 this->fd = -1;
175                                                 return false;
176                                         }
177                                         this->Instance->Log(DEBUG,"bind() reports outbound fd bound to ip %s",IP.c_str());
178                                         return true;
179                                 }
180                                 else
181                                 {
182                                         this->Instance->Log(DEBUG,"Address '%s' was not an IP address",IP.c_str());
183                                 }
184                         }
185                 }
186         }
187         this->Instance->Log(DEBUG,"Found no suitable IPs to bind, binding INADDR_ANY");
188         return true;
189 }
190
191 bool InspSocket::DoConnect()
192 {
193         this->Instance->Log(DEBUG,"In DoConnect()");
194         if ((this->fd = socket(AF_FAMILY, SOCK_STREAM, 0)) == -1)
195         {
196                 this->Instance->Log(DEBUG,"Cant socket()");
197                 this->state = I_ERROR;
198                 this->OnError(I_ERR_SOCKET);
199                 return false;
200         }
201
202         if ((strstr(this->IP,"::ffff:") != (char*)&this->IP) && (strstr(this->IP,"::FFFF:") != (char*)&this->IP))
203         {
204                 if (!this->BindAddr())
205                         return false;
206         }
207
208         this->Instance->Log(DEBUG,"Part 2 DoConnect() %s",this->IP);
209         insp_aton(this->IP,&addy);
210 #ifdef IPV6
211         addr.sin6_family = AF_FAMILY;
212         memcpy(&addr.sin6_addr, &addy, sizeof(insp_inaddr));
213         addr.sin6_port = htons(this->port);
214 #else
215         addr.sin_family = AF_FAMILY;
216         addr.sin_addr = addy;
217         addr.sin_port = htons(this->port);
218 #endif
219
220         int flags;
221         flags = fcntl(this->fd, F_GETFL, 0);
222         fcntl(this->fd, F_SETFL, flags | O_NONBLOCK);
223
224         if (connect(this->fd, (sockaddr*)&this->addr,sizeof(this->addr)) == -1)
225         {
226                 if (errno != EINPROGRESS)
227                 {
228                         this->Instance->Log(DEBUG,"Error connect() %d: %s",this->fd,strerror(errno));
229                         this->OnError(I_ERR_CONNECT);
230                         this->Close();
231                         this->state = I_ERROR;
232                         return false;
233                 }
234
235                 this->Timeout = new SocketTimeout(this->GetFd(), this->Instance, this, timeout_val, this->Instance->Time());
236                 this->Instance->Timers->AddTimer(this->Timeout);
237         }
238         this->state = I_CONNECTING;
239         if (this->fd > -1)
240         {
241                 if (!this->Instance->SE->AddFd(this))
242                 {
243                         this->OnError(I_ERR_NOMOREFDS);
244                         this->Close();
245                         this->state = I_ERROR;
246                         return false;
247                 }
248                 this->SetQueues(this->fd);
249         }
250         this->Instance->Log(DEBUG,"Returning true from InspSocket::DoConnect");
251         return true;
252 }
253
254
255 void InspSocket::Close()
256 {
257         if (this->fd > -1)
258         {
259                 this->OnClose();
260                 shutdown(this->fd,2);
261                 close(this->fd);
262         }
263 }
264
265 std::string InspSocket::GetIP()
266 {
267         return this->IP;
268 }
269
270 char* InspSocket::Read()
271 {
272         if ((fd < 0) || (fd > MAX_DESCRIPTORS))
273                 return NULL;
274         int n = recv(this->fd,this->ibuf,sizeof(this->ibuf),0);
275         if ((n > 0) && (n <= (int)sizeof(this->ibuf)))
276         {
277                 ibuf[n] = 0;
278                 return ibuf;
279         }
280         else
281         {
282                 int err = errno;
283                 if (err == EAGAIN)
284                 {
285                         return "";
286                 }
287                 else
288                 {
289                         if (!n)
290                                 this->Instance->Log(DEBUG,"EOF or error on socket: EOF");
291                         else
292                                 this->Instance->Log(DEBUG,"EOF or error on socket: %s",strerror(err));
293                         return NULL;
294                 }
295         }
296 }
297
298 void InspSocket::MarkAsClosed()
299 {
300         this->Instance->Log(DEBUG,"Marked as closed");
301 }
302
303 // There are two possible outcomes to this function.
304 // It will either write all of the data, or an undefined amount.
305 // If an undefined amount is written the connection has failed
306 // and should be aborted.
307 int InspSocket::Write(const std::string &data)
308 {
309         /* Try and append the data to the back of the queue, and send it on its way
310          */
311         outbuffer.push_back(data);
312         this->Instance->SE->WantWrite(this);
313         return (!this->FlushWriteBuffer());
314 }
315
316 bool InspSocket::FlushWriteBuffer()
317 {
318         errno = 0;
319         if ((this->fd > -1) && (this->state == I_CONNECTED))
320         {
321                 /* If we have multiple lines, try to send them all,
322                  * not just the first one -- Brain
323                  */
324                 while (outbuffer.size() && (errno != EAGAIN))
325                 {
326                         /* Send a line */
327                         int result = write(this->fd,outbuffer[0].c_str(),outbuffer[0].length());
328                         if (result > 0)
329                         {
330                                 if ((unsigned int)result == outbuffer[0].length())
331                                 {
332                                         /* The whole block was written (usually a line)
333                                          * Pop the block off the front of the queue,
334                                          * dont set errno, because we are clear of errors
335                                          * and want to try and write the next block too.
336                                          */
337                                         outbuffer.pop_front();
338                                 }
339                                 else
340                                 {
341                                         std::string temp = outbuffer[0].substr(result);
342                                         outbuffer[0] = temp;
343                                         /* We didnt get the whole line out. arses.
344                                          * Try again next time, i guess. Set errno,
345                                          * because we shouldnt be writing any more now,
346                                          * until the socketengine says its safe to do so.
347                                          */
348                                         errno = EAGAIN;
349                                 }
350                         }
351                         else if ((result == -1) && (errno != EAGAIN))
352                         {
353                                 this->Instance->Log(DEBUG,"Write error on socket: %s",strerror(errno));
354                                 this->OnError(I_ERR_WRITE);
355                                 this->state = I_ERROR;
356                                 this->Instance->SE->DelFd(this);
357                                 this->Close();
358                                 return true;
359                         }
360                 }
361         }
362
363         if ((errno == EAGAIN) && (fd > -1))
364         {
365                 this->Instance->SE->WantWrite(this);
366         }
367
368         return (fd < 0);
369 }
370
371 void SocketTimeout::Tick(time_t now)
372 {
373         if (ServerInstance->SE->GetRef(this->sfd) != this->sock)
374         {
375                 ServerInstance->Log(DEBUG,"Our socket has been deleted before the timeout was reached.");
376                 return;
377         }
378
379         if (this->sock->state == I_CONNECTING)
380         {
381                 ServerInstance->Log(DEBUG,"Timed out, current=%lu",now);
382                 // for non-listening sockets, the timeout can occur
383                 // which causes termination of the connection after
384                 // the given number of seconds without a successful
385                 // connection.
386                 this->sock->OnTimeout();
387                 this->sock->OnError(I_ERR_TIMEOUT);
388                 this->sock->timeout = true;
389                 ServerInstance->SE->DelFd(this->sock);
390                 /* NOTE: We must set this AFTER DelFd, as we added
391                  * this socket whilst writeable. This means that we
392                  * must DELETE the socket whilst writeable too!
393                  */
394                 this->sock->state = I_ERROR;
395                 this->sock->Close();
396                 delete this->sock;
397                 return;
398         }
399 }
400
401 bool InspSocket::Poll()
402 {
403         if (this->Instance->SE->GetRef(this->fd) != this)
404                 return false;
405
406         int incoming = -1;
407
408         if ((fd < 0) || (fd > MAX_DESCRIPTORS))
409                 return false;
410
411         switch (this->state)
412         {
413                 case I_CONNECTING:
414                         this->Instance->Log(DEBUG,"State = I_CONNECTING");
415                         /* Our socket was in write-state, so delete it and re-add it
416                          * in read-state.
417                          */
418                         if (this->fd > -1)
419                         {
420                                 this->Instance->SE->DelFd(this);
421                                 this->SetState(I_CONNECTED);
422                                 if (!this->Instance->SE->AddFd(this))
423                                         return false;
424                         }
425                         return this->OnConnected();
426                 break;
427                 case I_LISTENING:
428                         length = sizeof (client);
429                         incoming = accept (this->fd, (sockaddr*)&client,&length);
430                         this->SetQueues(incoming);
431 #ifdef IPV6
432                         this->OnIncomingConnection(incoming,(char*)insp_ntoa(client.sin6_addr));
433 #else
434                         this->OnIncomingConnection(incoming,(char*)insp_ntoa(client.sin_addr));
435 #endif
436                         return true;
437                 break;
438                 case I_CONNECTED:
439                         /* Process the read event */
440                         return this->OnDataReady();
441                 break;
442                 default:
443                 break;
444         }
445         return true;
446 }
447
448 void InspSocket::SetState(InspSocketState s)
449 {
450         this->Instance->Log(DEBUG,"Socket state change");
451         this->state = s;
452 }
453
454 InspSocketState InspSocket::GetState()
455 {
456         return this->state;
457 }
458
459 int InspSocket::GetFd()
460 {
461         return this->fd;
462 }
463
464 bool InspSocket::OnConnected() { return true; }
465 void InspSocket::OnError(InspSocketError e) { return; }
466 int InspSocket::OnDisconnect() { return 0; }
467 int InspSocket::OnIncomingConnection(int newfd, char* ip) { return 0; }
468 bool InspSocket::OnDataReady() { return true; }
469 bool InspSocket::OnWriteReady() { return true; }
470 void InspSocket::OnTimeout() { return; }
471 void InspSocket::OnClose() { return; }
472
473 InspSocket::~InspSocket()
474 {
475         this->Close();
476 }
477
478 void InspSocket::HandleEvent(EventType et)
479 {
480         switch (et)
481         {
482                 case EVENT_READ:
483                         if (!this->Poll())
484                         {
485                                 this->Instance->SE->DelFd(this);
486                                 this->Close();
487                                 delete this;
488                                 return;
489                         }
490                 break;
491                 case EVENT_WRITE:
492                         if (this->WaitingForWriteEvent)
493                         {
494                                 this->WaitingForWriteEvent = false;
495                                 if (!this->OnWriteReady())
496                                 {
497                                         this->Instance->SE->DelFd(this);
498                                         this->Close();
499                                         delete this;
500                                         return;
501                                 }
502                         }
503                         if (this->state == I_CONNECTING)
504                         {
505                                 /* This might look wrong as if we should be actually calling
506                                  * with EVENT_WRITE, but trust me it is correct. There are some
507                                  * writeability-state things in the read code, because of how
508                                  * InspSocket used to work regarding write buffering in previous
509                                  * versions of InspIRCd. - Brain
510                                  */
511                                 this->HandleEvent(EVENT_READ);
512                                 return;
513                         }
514                         else
515                         {
516                                 Instance->Log(DEBUG,"State=%d CONNECTED=%d", this->state, I_CONNECTED);
517                                 if (this->FlushWriteBuffer())
518                                 {
519                                         this->Instance->SE->DelFd(this);
520                                         this->Close();
521                                         delete this;
522                                         return;
523                                 }
524                         }
525                 break;
526         }
527 }
528