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