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