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