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