]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/inspsocket.cpp
Dont allow an empty key (thanks stskeeps)
[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 "socketengine.h"
27 #include "inspircd.h"
28
29 using irc::sockets::OpenTCPSocket;
30 using irc::sockets::insp_inaddr;
31 using irc::sockets::insp_sockaddr;
32
33 bool InspSocket::Readable()
34 {
35         return ((this->state != I_CONNECTING) && (this->WaitingForWriteEvent == false));
36 }
37
38 InspSocket::InspSocket(InspIRCd* SI)
39 {
40         this->state = I_DISCONNECTED;
41         this->fd = -1;
42         this->WaitingForWriteEvent = false;
43         this->ClosePending = false;
44         this->Instance = SI;
45 }
46
47 InspSocket::InspSocket(InspIRCd* SI, 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         this->WaitingForWriteEvent = false;
54         this->Instance = SI;
55         if (this->fd > -1)
56                 this->ClosePending = (!this->Instance->SE->AddFd(this));
57 }
58
59 InspSocket::InspSocket(InspIRCd* SI, const std::string &ipaddr, int aport, bool listening, unsigned long maxtime)
60 {
61         this->fd = -1;
62         this->Instance = SI;
63         strlcpy(host,ipaddr.c_str(),MAXBUF);
64         this->ClosePending = false;
65         this->WaitingForWriteEvent = false;
66         if (listening)
67         {
68                 if ((this->fd = OpenTCPSocket()) == ERROR)
69                 {
70                         this->fd = -1;
71                         this->state = I_ERROR;
72                         this->OnError(I_ERR_SOCKET);
73                         this->ClosePending = true;
74                         this->Instance->Log(DEBUG,"OpenTCPSocket() error");
75                         return;
76                 }
77                 else
78                 {
79                         if (!SI->BindSocket(this->fd,this->client,this->server,aport,(char*)ipaddr.c_str()))
80                         {
81                                 this->Instance->Log(DEBUG,"BindSocket() error %s",strerror(errno));
82                                 this->Close();
83                                 this->fd = -1;
84                                 this->state = I_ERROR;
85                                 this->OnError(I_ERR_BIND);
86                                 this->ClosePending = true;
87                                 return;
88                         }
89                         else
90                         {
91                                 this->state = I_LISTENING;
92                                 if (this->fd > -1)
93                                 {
94                                         if (!this->Instance->SE->AddFd(this))
95                                         {
96                                                 this->Close();
97                                                 this->state = I_ERROR;
98                                                 this->OnError(I_ERR_NOMOREFDS);
99                                                 this->ClosePending = true;
100                                         }
101                                 }
102                                 this->Instance->Log(DEBUG,"New socket now in I_LISTENING state");
103                                 return;
104                         }
105                 }                       
106         }
107         else
108         {
109                 strlcpy(this->host,ipaddr.c_str(),MAXBUF);
110                 this->port = aport;
111
112                 if (insp_aton(host,&addy) < 1)
113                 {
114                         this->Instance->Log(DEBUG,"You cannot pass hostnames to InspSocket, resolve them first with Resolver!");
115                         this->Close();
116                         this->fd = -1;
117                         this->state = I_ERROR;
118                         this->OnError(I_ERR_RESOLVE);
119                         this->ClosePending = true;
120                         return;
121                 }
122                 else
123                 {
124                         this->Instance->Log(DEBUG,"No need to resolve %s",this->host);
125                         strlcpy(this->IP,host,MAXBUF);
126                         timeout_end = time(NULL) + maxtime;
127                         this->DoConnect();
128                 }
129         }
130 }
131
132 void InspSocket::WantWrite()
133 {
134         /** XXX:
135          * The socket engine may only have each FD in the list ONCE.
136          * This means we cant watch for write AND read at the same
137          * time. We have to remove the READ fd, to insert the WRITE
138          * fd. Once we receive our WRITE event (which WILL ARRIVE,
139          * pretty much gauranteed) we switch back to watching for
140          * READ events again.
141          *
142          * This behaviour may be fixed in a later version.
143          */
144         this->Instance->SE->DelFd(this);
145         this->WaitingForWriteEvent = true;
146         if (!this->Instance->SE->AddFd(this))
147         {
148                 this->Close();
149                 this->fd = -1;
150                 this->state = I_ERROR;
151                 this->OnError(I_ERR_NOMOREFDS);
152                 this->ClosePending = true;
153         }
154 }
155
156 void InspSocket::SetQueues(int nfd)
157 {
158         // attempt to increase socket sendq and recvq as high as its possible
159         int sendbuf = 32768;
160         int recvbuf = 32768;
161         setsockopt(nfd,SOL_SOCKET,SO_SNDBUF,(const void *)&sendbuf,sizeof(sendbuf));
162         setsockopt(nfd,SOL_SOCKET,SO_RCVBUF,(const void *)&recvbuf,sizeof(sendbuf));
163 }
164
165 /* Most irc servers require you to specify the ip you want to bind to.
166  * If you dont specify an IP, they rather dumbly bind to the first IP
167  * of the box (e.g. INADDR_ANY). In InspIRCd, we scan thought the IP
168  * addresses we've bound server ports to, and we try and bind our outbound
169  * connections to the first usable non-loopback and non-any IP we find.
170  * This is easier to configure when you have a lot of links and a lot
171  * of servers to configure.
172  */
173 bool InspSocket::BindAddr()
174 {
175         insp_inaddr n;
176         ConfigReader Conf(this->Instance);
177
178         this->Instance->Log(DEBUG,"In InspSocket::BindAddr()");
179         for (int j =0; j < Conf.Enumerate("bind"); j++)
180         {
181                 std::string Type = Conf.ReadValue("bind","type",j);
182                 std::string IP = Conf.ReadValue("bind","address",j);
183                 if (Type == "servers")
184                 {
185                         if ((IP != "*") && (IP != "127.0.0.1") && (IP != ""))
186                         {
187                                 insp_sockaddr s;
188
189                                 if (insp_aton(IP.c_str(),&n) > 0)
190                                 {
191                                         this->Instance->Log(DEBUG,"Found an IP to bind to: %s",IP.c_str());
192 #ifdef IPV6
193                                         s.sin6_addr = n;
194                                         s.sin6_family = AF_FAMILY;
195 #else
196                                         s.sin_addr = n;
197                                         s.sin_family = AF_FAMILY;
198 #endif
199                                         if (bind(this->fd,(struct sockaddr*)&s,sizeof(s)) < 0)
200                                         {
201                                                 this->Instance->Log(DEBUG,"Cant bind()");
202                                                 this->state = I_ERROR;
203                                                 this->OnError(I_ERR_BIND);
204                                                 this->fd = -1;
205                                                 return false;
206                                         }
207                                         this->Instance->Log(DEBUG,"bind() reports outbound fd bound to ip %s",IP.c_str());
208                                         return true;
209                                 }
210                                 else
211                                 {
212                                         this->Instance->Log(DEBUG,"Address '%s' was not an IP address",IP.c_str());
213                                 }
214                         }
215                 }
216         }
217         this->Instance->Log(DEBUG,"Found no suitable IPs to bind, binding INADDR_ANY");
218         return true;
219 }
220
221 bool InspSocket::DoConnect()
222 {
223         this->Instance->Log(DEBUG,"In DoConnect()");
224         if ((this->fd = socket(AF_FAMILY, SOCK_STREAM, 0)) == -1)
225         {
226                 this->Instance->Log(DEBUG,"Cant socket()");
227                 this->state = I_ERROR;
228                 this->OnError(I_ERR_SOCKET);
229                 this->fd = -1;
230                 return false;
231         }
232
233         if ((strstr(this->IP,"::ffff:") != (char*)&this->IP) && (strstr(this->IP,"::FFFF:") != (char*)&this->IP))
234         {
235                 if (!this->BindAddr())
236                         return false;
237         }
238
239         this->Instance->Log(DEBUG,"Part 2 DoConnect() %s",this->IP);
240         insp_aton(this->IP,&addy);
241 #ifdef IPV6
242         addr.sin6_family = AF_FAMILY;
243         memcpy(&addr.sin6_addr, &addy, sizeof(insp_inaddr));
244         addr.sin6_port = htons(this->port);
245 #else
246         addr.sin_family = AF_FAMILY;
247         addr.sin_addr = addy;
248         addr.sin_port = htons(this->port);
249 #endif
250
251         int flags;
252         flags = fcntl(this->fd, F_GETFL, 0);
253         fcntl(this->fd, F_SETFL, flags | O_NONBLOCK);
254
255         if (connect(this->fd, (sockaddr*)&this->addr,sizeof(this->addr)) == -1)
256         {
257                 if (errno != EINPROGRESS)
258                 {
259                         this->Instance->Log(DEBUG,"Error connect() %d: %s",this->fd,strerror(errno));
260                         this->OnError(I_ERR_CONNECT);
261                         this->Close();
262                         this->state = I_ERROR;
263                         this->fd = -1;
264                         this->ClosePending = true;
265                         return false;
266                 }
267         }
268         this->state = I_CONNECTING;
269         if (this->fd > -1)
270         {
271                 if (!this->Instance->SE->AddFd(this))
272                 {
273                         this->OnError(I_ERR_NOMOREFDS);
274                         this->Close();
275                         this->fd = -1;
276                         this->state = I_ERROR;
277                         this->ClosePending = true;
278                         return false;
279                 }
280                 this->SetQueues(this->fd);
281         }
282         this->Instance->Log(DEBUG,"Returning true from InspSocket::DoConnect");
283         return true;
284 }
285
286
287 void InspSocket::Close()
288 {
289         if (this->fd != -1)
290         {
291                 this->OnClose();
292                 shutdown(this->fd,2);
293                 close(this->fd);
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                         this->Instance->Log(DEBUG,"EOF or error on socket: %s",strerror(errno));
323                         return NULL;
324                 }
325         }
326 }
327
328 void InspSocket::MarkAsClosed()
329 {
330         this->Instance->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                                 this->Instance->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 (this->Instance->SE->GetRef(this->fd) != this)
395         {
396                 this->Instance->Log(DEBUG,"No FD or socket ref");
397                 return false;
398         }
399
400         if (this->ClosePending)
401         {
402                 this->Instance->Log(DEBUG,"Close is pending");
403                 return true;
404         }
405
406         if ((this->state == I_CONNECTING) && (current > timeout_end))
407         {
408                 this->Instance->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 (this->Instance->SE->GetRef(this->fd) != this)
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                         this->Instance->Log(DEBUG,"State = I_CONNECTING");
438                         /* Our socket was in write-state, so delete it and re-add it
439                          * in read-state.
440                          */
441                         if (this->fd > -1)
442                         {
443                                 this->Instance->SE->DelFd(this);
444                                 this->SetState(I_CONNECTED);
445                                 if (!this->Instance->SE->AddFd(this))
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                                 this->Instance->SE->DelFd(this);
467                                 this->WaitingForWriteEvent = false;
468                                 if (!this->Instance->SE->AddFd(this))
469                                         return false;
470
471                                 /* Trigger the write event */
472                                 n = this->OnWriteReady();
473                         }
474                         else
475                         {
476                                 /* Process the read event */
477                                 n = this->OnDataReady();
478                         }
479                         /* Flush any pending, but not till after theyre done with the event
480                          * so there are less write calls involved.
481                          * Both FlushWriteBuffer AND the return result of OnDataReady must
482                          * return true for this to be ok.
483                          */
484                         if (this->FlushWriteBuffer())
485                                 return false;
486                         return n;
487                 break;
488                 default:
489                 break;
490         }
491         return true;
492 }
493
494 void InspSocket::SetState(InspSocketState s)
495 {
496         this->Instance->Log(DEBUG,"Socket state change");
497         this->state = s;
498 }
499
500 InspSocketState InspSocket::GetState()
501 {
502         return this->state;
503 }
504
505 int InspSocket::GetFd()
506 {
507         return this->fd;
508 }
509
510 bool InspSocket::OnConnected() { return true; }
511 void InspSocket::OnError(InspSocketError e) { return; }
512 int InspSocket::OnDisconnect() { return 0; }
513 int InspSocket::OnIncomingConnection(int newfd, char* ip) { return 0; }
514 bool InspSocket::OnDataReady() { return true; }
515 bool InspSocket::OnWriteReady() { return true; }
516 void InspSocket::OnTimeout() { return; }
517 void InspSocket::OnClose() { return; }
518
519 InspSocket::~InspSocket()
520 {
521         this->Close();
522 }
523
524 void InspSocket::HandleEvent(EventType et)
525 {
526         if (!this->Poll())
527         {
528                 this->Instance->SE->DelFd(this);
529                 delete this;
530         }
531 }
532