]> arthur.barton.de Git - ngircd-alex.git/blob - src/ngircd/conn.c
IPv6 support.
[ngircd-alex.git] / src / ngircd / conn.c
1 /*
2  * ngIRCd -- The Next Generation IRC Daemon
3  * Copyright (c)2001-2007 Alexander Barton (alex@barton.de)
4  *
5  * This program is free software; you can redistribute it and/or modify
6  * it under the terms of the GNU General Public License as published by
7  * the Free Software Foundation; either version 2 of the License, or
8  * (at your option) any later version.
9  * Please read the file COPYING, README and AUTHORS for more information.
10  *
11  * Connection management
12  */
13
14
15 #define CONN_MODULE
16
17 #include "portab.h"
18 #include "io.h"
19
20 static char UNUSED id[] = "$Id: conn.c,v 1.221 2008/02/26 22:04:17 fw Exp $";
21
22 #include "imp.h"
23 #include <assert.h>
24 #ifdef PROTOTYPES
25 #       include <stdarg.h>
26 #else
27 #       include <varargs.h>
28 #endif
29 #include <stdio.h>
30 #include <stdlib.h>
31 #include <unistd.h>
32 #include <errno.h>
33 #include <string.h>
34 #include <sys/socket.h>
35 #include <sys/time.h>
36 #include <sys/types.h>
37 #include <time.h>
38 #include <netinet/in.h>
39
40 #ifdef HAVE_NETINET_IP_H
41 # include <netinet/ip.h>
42 #endif
43
44 #ifdef HAVE_STDINT_H
45 # include <stdint.h>                    /* e.g. for Mac OS X */
46 #endif
47
48 #ifdef TCPWRAP
49 # include <tcpd.h>                      /* for TCP Wrappers */
50 #endif
51
52 #include "array.h"
53 #include "defines.h"
54 #include "resolve.h"
55
56 #include "exp.h"
57 #include "conn.h"
58
59 #include "imp.h"
60 #include "ngircd.h"
61 #include "client.h"
62 #include "conf.h"
63 #include "conn-zip.h"
64 #include "conn-func.h"
65 #include "log.h"
66 #include "parse.h"
67 #include "tool.h"
68
69 #ifdef ZEROCONF
70 # include "rendezvous.h"
71 #endif
72
73 #include "exp.h"
74
75
76 #define SERVER_WAIT (NONE - 1)
77
78
79 static bool Handle_Write PARAMS(( CONN_ID Idx ));
80 static bool Conn_Write PARAMS(( CONN_ID Idx, char *Data, size_t Len ));
81 static int New_Connection PARAMS(( int Sock ));
82 static CONN_ID Socket2Index PARAMS(( int Sock ));
83 static void Read_Request PARAMS(( CONN_ID Idx ));
84 static bool Handle_Buffer PARAMS(( CONN_ID Idx ));
85 static void Check_Connections PARAMS(( void ));
86 static void Check_Servers PARAMS(( void ));
87 static void Init_Conn_Struct PARAMS(( CONN_ID Idx ));
88 static bool Init_Socket PARAMS(( int Sock ));
89 static void New_Server PARAMS(( int Server, ng_ipaddr_t *dest ));
90 static void Simple_Message PARAMS(( int Sock, const char *Msg ));
91 static int NewListener PARAMS(( int af, const UINT16 Port ));
92
93 static array My_Listeners;
94 static array My_ConnArray;
95
96 #ifdef TCPWRAP
97 int allow_severity = LOG_INFO;
98 int deny_severity = LOG_ERR;
99 #endif
100
101 static void server_login PARAMS((CONN_ID idx));
102
103 static void cb_Read_Resolver_Result PARAMS(( int sock, UNUSED short what));
104 static void cb_Connect_to_Server PARAMS(( int sock, UNUSED short what));
105 static void cb_clientserver PARAMS((int sock, short what));
106
107 static void
108 cb_listen(int sock, short irrelevant)
109 {
110         (void) irrelevant;
111         New_Connection( sock );
112 }
113
114
115 static void
116 cb_connserver(int sock, UNUSED short what)
117 {
118         int res, err;
119         socklen_t sock_len;
120         CONN_ID idx = Socket2Index( sock );
121         if (idx <= NONE) {
122                 LogDebug("cb_connserver wants to write on unknown socket?!");
123                 io_close(sock);
124                 return;
125         }
126
127         assert( what & IO_WANTWRITE);
128
129         /* connect() finished, get result. */
130         sock_len = sizeof( err );
131         res = getsockopt( My_Connections[idx].sock, SOL_SOCKET, SO_ERROR, &err, &sock_len );
132         assert( sock_len == sizeof( err ));
133
134         /* Error while connecting? */
135         if ((res != 0) || (err != 0)) {
136                 if (res != 0)
137                         Log(LOG_CRIT, "getsockopt (connection %d): %s!",
138                             idx, strerror(errno));
139                 else
140                         Log(LOG_CRIT,
141                             "Can't connect socket to \"%s:%d\" (connection %d): %s!",
142                             My_Connections[idx].host,
143                             Conf_Server[Conf_GetServer(idx)].port,
144                             idx, strerror(err));
145
146                 res = Conf_GetServer(idx);
147                 assert(res >= 0);
148
149                 Conn_Close(idx, "Can't connect!", NULL, false);
150
151                 if (res < 0)
152                         return;
153                 if (ng_ipaddr_af(&Conf_Server[res].dst_addr[0])) {
154                         /* more addresses to try... */
155                         New_Server(res, &Conf_Server[res].dst_addr[0]);
156                         /* connection to dst_addr[0] in progress, remove this address... */
157                         Conf_Server[res].dst_addr[0] = Conf_Server[res].dst_addr[1];
158
159                         memset(&Conf_Server[res].dst_addr[1], 0, sizeof(&Conf_Server[res].dst_addr[1]));
160                 }
161                 return;
162         }
163
164         res = Conf_GetServer(idx);
165         assert(res >= 0);
166         if (res >= 0) /* connect succeeded, remove all additional addresses */
167                 memset(&Conf_Server[res].dst_addr, 0, sizeof(&Conf_Server[res].dst_addr));
168         Conn_OPTION_DEL( &My_Connections[idx], CONN_ISCONNECTING );
169         server_login(idx);
170 }
171
172
173 static void
174 server_login(CONN_ID idx)
175 {
176         Log( LOG_INFO, "Connection %d with \"%s:%d\" established. Now logging in ...", idx,
177                         My_Connections[idx].host, Conf_Server[Conf_GetServer( idx )].port );
178
179         io_event_setcb( My_Connections[idx].sock, cb_clientserver);
180         io_event_add( My_Connections[idx].sock, IO_WANTREAD|IO_WANTWRITE);
181
182         /* Send PASS and SERVER command to peer */
183         Conn_WriteStr( idx, "PASS %s %s", Conf_Server[Conf_GetServer( idx )].pwd_out, NGIRCd_ProtoID );
184         Conn_WriteStr( idx, "SERVER %s :%s", Conf_ServerName, Conf_ServerInfo );
185 }
186
187
188 static void
189 cb_clientserver(int sock, short what)
190 {
191         CONN_ID idx = Socket2Index( sock );
192         if (idx <= NONE) {
193 #ifdef DEBUG
194                 Log(LOG_WARNING, "WTF: cb_clientserver wants to write on unknown socket?!");
195 #endif
196                 io_close(sock);
197                 return;
198         }
199
200         if (what & IO_WANTREAD)
201                 Read_Request( idx );
202
203         if (what & IO_WANTWRITE)
204                 Handle_Write( idx );
205 }
206
207
208 GLOBAL void
209 Conn_Init( void )
210 {
211         /* Modul initialisieren: statische Strukturen "ausnullen". */
212
213         CONN_ID i;
214
215         /* Speicher fuer Verbindungs-Pool anfordern */
216         Pool_Size = CONNECTION_POOL;
217         if( Conf_MaxConnections > 0 )
218         {
219                 /* konfiguriertes Limit beachten */
220                 if( Pool_Size > Conf_MaxConnections ) Pool_Size = Conf_MaxConnections;
221         }
222         
223         if (!array_alloc(&My_ConnArray, sizeof(CONNECTION), (size_t)Pool_Size)) {
224                 Log( LOG_EMERG, "Can't allocate memory! [Conn_Init]" );
225                 exit( 1 );
226         }
227
228         /* FIXME: My_Connetions/Pool_Size is needed by other parts of the
229          * code; remove them! */
230         My_Connections = (CONNECTION*) array_start(&My_ConnArray);
231
232         LogDebug("Allocated connection pool for %d items (%ld bytes).",
233                 array_length(&My_ConnArray, sizeof( CONNECTION )), array_bytes(&My_ConnArray));
234
235         assert( array_length(&My_ConnArray, sizeof( CONNECTION )) >= (size_t) Pool_Size);
236         
237         array_free( &My_Listeners );
238
239         /* Connection-Struktur initialisieren */
240         for( i = 0; i < Pool_Size; i++ ) Init_Conn_Struct( i );
241
242         /* Global write counter */
243         WCounter = 0;
244 } /* Conn_Init */
245
246
247 GLOBAL void
248 Conn_Exit( void )
249 {
250         /* Modul abmelden: alle noch offenen Connections
251          * schliessen und freigeben. */
252
253         CONN_ID idx;
254
255         LogDebug("Shutting down all connections ..." );
256
257         Conn_ExitListeners();
258
259         /* Sockets schliessen */
260         for( idx = 0; idx < Pool_Size; idx++ ) {
261                 if( My_Connections[idx].sock > NONE ) {
262                         Conn_Close( idx, NULL, NGIRCd_SignalRestart ?
263                                 "Server going down (restarting)":"Server going down", true );
264                 }
265         }
266
267         array_free(&My_ConnArray);
268         My_Connections = NULL;
269         Pool_Size = 0;
270         io_library_shutdown();
271 } /* Conn_Exit */
272
273
274 static unsigned int
275 ports_initlisteners(array *a, int af, void (*func)(int,short))
276 {
277         unsigned int created = 0;
278         size_t len;
279         int fd;
280         UINT16 *port;
281
282         len = array_length(a, sizeof (UINT16));
283         port = array_start(a);
284         while(len--) {
285                 fd = NewListener(af, *port);
286                 if (fd < 0) {
287                         port++;
288                         continue;
289                 }
290                 if (!io_event_create( fd, IO_WANTREAD, func )) {
291                         Log( LOG_ERR, "io_event_create(): Could not add listening fd %d (port %u): %s!",
292                                                         fd, (unsigned int) *port, strerror(errno));
293                         close(fd);
294                         port++;
295                         continue;
296                 }
297                 created++;
298                 port++;
299         }
300
301         return created;
302 }
303
304
305 GLOBAL unsigned int
306 Conn_InitListeners( void )
307 {
308         /* Initialize ports on which the server should accept connections */
309
310         unsigned int created = 0;
311
312         if (!io_library_init(CONNECTION_POOL)) {
313                 Log(LOG_EMERG, "Cannot initialize IO routines: %s", strerror(errno));
314                 return -1;
315         }
316
317 #ifdef WANT_IPV6
318         if (!Conf_NoListenIpv6)
319                 created = ports_initlisteners(&Conf_ListenPorts, AF_INET6, cb_listen);
320 #endif
321         created += ports_initlisteners(&Conf_ListenPorts, AF_INET, cb_listen);
322
323         return created;
324 } /* Conn_InitListeners */
325
326
327 GLOBAL void
328 Conn_ExitListeners( void )
329 {
330         /* Close down all listening sockets */
331         int *fd;
332         size_t arraylen;
333 #ifdef ZEROCONF
334         Rendezvous_UnregisterListeners( );
335 #endif
336
337         arraylen = array_length(&My_Listeners, sizeof (int));
338         Log( LOG_INFO, "Shutting down all listening sockets (%d total)...", arraylen );
339         fd = array_start(&My_Listeners);
340         while(arraylen--) {
341                 assert(fd != NULL);
342                 assert(*fd >= 0);
343                 io_close(*fd);
344                 LogDebug("Listening socket %d closed.", *fd );
345                 fd++;
346         }
347         array_free(&My_Listeners);
348 } /* Conn_ExitListeners */
349
350
351 static bool
352 InitSinaddrListenAddr(int af, ng_ipaddr_t *addr, UINT16 Port)
353 {
354         bool ret;
355         const char *listen_addrstr = NULL;
356 #ifdef WANT_IPV6
357         if (af == AF_INET)
358                 listen_addrstr = "0.0.0.0";
359 #else
360         (void)af;
361 #endif
362         if (Conf_ListenAddress[0]) /* overrides V4/V6 atm */
363                 listen_addrstr = Conf_ListenAddress;
364
365         ret = ng_ipaddr_init(addr, listen_addrstr, Port);
366         if (!ret) {
367                 if (!listen_addrstr)
368                         listen_addrstr = "";
369                 Log(LOG_CRIT, "Can't bind to %s:%u: can't convert ip address \"%s\"",
370                                         listen_addrstr, Port, listen_addrstr);
371         }
372         return ret;
373 }
374
375
376 static void
377 set_v6_only(int af, int sock)
378 {
379 #if defined(IPV6_V6ONLY) && defined(WANT_IPV6)
380         int on = 1;
381
382         if (af != AF_INET6)
383                 return;
384
385         if (setsockopt(sock, IPPROTO_IPV6, IPV6_V6ONLY, &on, sizeof(on)))
386                 Log(LOG_ERR, "Could not set IPV6_V6ONLY: %s", strerror(errno));
387 #else
388         (void)af;
389         (void)sock;
390 #endif
391 }
392
393
394 /* return new listening port file descriptor or -1 on failure */
395 static int
396 NewListener(int af, const UINT16 Port)
397 {
398         /* Create new listening socket on specified port */
399         ng_ipaddr_t addr;
400         int sock;
401 #ifdef ZEROCONF
402         char name[CLIENT_ID_LEN], *info;
403 #endif
404         if (!InitSinaddrListenAddr(af, &addr, Port))
405                 return -1;
406
407         sock = socket(ng_ipaddr_af(&addr), SOCK_STREAM, 0);
408         if( sock < 0 ) {
409                 Log( LOG_CRIT, "Can't create socket: %s!", strerror( errno ));
410                 return -1;
411         }
412
413         af = ng_ipaddr_af(&addr);
414
415         set_v6_only(af, sock);
416
417         if( ! Init_Socket( sock )) return -1;
418
419         if (bind(sock, (struct sockaddr *)&addr, ng_ipaddr_salen(&addr)) != 0) {
420                 Log( LOG_CRIT, "Can't bind socket (port %d) : %s!", Port, strerror( errno ));
421                 close( sock );
422                 return -1;
423         }
424
425         if( listen( sock, 10 ) != 0 ) {
426                 Log( LOG_CRIT, "Can't listen on socket: %s!", strerror( errno ));
427                 close( sock );
428                 return -1;
429         }
430
431         /* keep fd in list so we can close it when ngircd restarts/shuts down */
432         if (!array_catb( &My_Listeners,(char*) &sock, sizeof(int) )) {
433                 Log( LOG_CRIT, "Can't add socket to My_Listeners array: %s!", strerror( errno ));
434                 close( sock );
435                 return -1;
436         }
437
438 #ifdef WANT_IPV6
439         if (af == AF_INET6)
440                 Log(LOG_INFO, "Now listening on [%s]:%d (socket %d).", ng_ipaddr_tostr(&addr), Port, sock);
441         else
442 #endif
443                 Log(LOG_INFO, "Now listening on %s:%d (socket %d).", ng_ipaddr_tostr(&addr), Port, sock);
444
445 #ifdef ZEROCONF
446         /* Get best server description text */
447         if( ! Conf_ServerInfo[0] ) info = Conf_ServerName;
448         else
449         {
450                 /* Use server info string */
451                 info = NULL;
452                 if( Conf_ServerInfo[0] == '[' )
453                 {
454                         /* Cut off leading hostname part in "[]" */
455                         info = strchr( Conf_ServerInfo, ']' );
456                         if( info )
457                         {
458                                 info++;
459                                 while( *info == ' ' ) info++;
460                         }
461                 }
462                 if( ! info ) info = Conf_ServerInfo;
463         }
464
465         /* Add port number to description if non-standard */
466         if (Port != 6667)
467                 snprintf(name, sizeof name, "%s (port %u)", info,
468                          (unsigned int)Port);
469         else
470                 strlcpy(name, info, sizeof name);
471
472         /* Register service */
473         Rendezvous_Register( name, MDNS_TYPE, Port );
474 #endif
475         return sock;
476 } /* NewListener */
477
478
479 GLOBAL void
480 Conn_Handler( void )
481 {
482         /* "Main Loop.": Loop until a signal (for shutdown or restart) arrives.
483          * Call io_dispatch() to check for read/writeable sockets every second
484          * Wait for status change on pending connections (e.g: when the hostname has been resolved)
485          * check for penalty/timeouts
486          * handle input buffers
487          */
488         int i;
489         unsigned int wdatalen;
490         struct timeval tv;
491         time_t t;
492         bool timeout;
493
494         while(( ! NGIRCd_SignalQuit ) && ( ! NGIRCd_SignalRestart )) {
495                 timeout = true;
496
497 #ifdef ZEROCONF
498                 Rendezvous_Handler( );
499 #endif
500
501                 /* Should the configuration be reloaded? */
502                 if (NGIRCd_SignalRehash) {
503                         NGIRCd_Rehash( );
504                 }
505
506                 /* Check configured servers and established links */
507                 Check_Servers( );
508                 Check_Connections( );
509
510                 t = time( NULL );
511
512                 /* noch volle Lese-Buffer suchen */
513                 for( i = 0; i < Pool_Size; i++ ) {
514                         if(( My_Connections[i].sock > NONE ) && ( array_bytes(&My_Connections[i].rbuf) > 0 ) &&
515                          ( My_Connections[i].delaytime < t ))
516                         {
517                                 /* Kann aus dem Buffer noch ein Befehl extrahiert werden? */
518                                 if (Handle_Buffer( i )) timeout = false;
519                         }
520                 }
521
522                 /* noch volle Schreib-Puffer suchen */
523                 for( i = 0; i < Pool_Size; i++ ) {
524                         if ( My_Connections[i].sock <= NONE )
525                                 continue;
526
527                         wdatalen = (unsigned int)array_bytes(&My_Connections[i].wbuf);
528
529 #ifdef ZLIB
530                         if (( wdatalen > 0 ) || ( array_bytes(&My_Connections[i].zip.wbuf)> 0 ))
531 #else
532                         if ( wdatalen > 0 )
533 #endif
534                         {
535                                 /* Socket der Verbindung in Set aufnehmen */
536                                 io_event_add( My_Connections[i].sock, IO_WANTWRITE );
537                         }
538                 }
539
540                 /* von welchen Sockets koennte gelesen werden? */
541                 for (i = 0; i < Pool_Size; i++ ) {
542                         if ( My_Connections[i].sock <= NONE )
543                                 continue;
544
545                         if (Resolve_INPROGRESS(&My_Connections[i].res_stat)) {
546                                 /* wait for completion of Resolver Sub-Process */
547                                 io_event_del( My_Connections[i].sock, IO_WANTREAD );
548                                 continue;
549                         }
550
551                         if ( Conn_OPTION_ISSET( &My_Connections[i], CONN_ISCONNECTING ))
552                                 continue;       /* wait for completion of connect() */
553
554                         if( My_Connections[i].delaytime > t ) {
555                                 /* Fuer die Verbindung ist eine "Penalty-Zeit" gesetzt */
556                                 io_event_del( My_Connections[i].sock, IO_WANTREAD );
557                                 continue;
558                         }
559                         io_event_add( My_Connections[i].sock, IO_WANTREAD );
560                 }
561
562                 /* (re-)set timeout - tv_sec/usec are undefined after io_dispatch() returns */
563                 tv.tv_usec = 0;
564                 tv.tv_sec = timeout ? 1 : 0;
565
566                 /* wait for activity */
567                 i = io_dispatch( &tv );
568                 if (i == -1 && errno != EINTR ) {
569                         Log(LOG_EMERG, "Conn_Handler(): io_dispatch(): %s!", strerror(errno));
570                         Log(LOG_ALERT, "%s exiting due to fatal errors!", PACKAGE_NAME);
571                         exit( 1 );
572                 }
573         }
574
575         if( NGIRCd_SignalQuit ) Log( LOG_NOTICE|LOG_snotice, "Server going down NOW!" );
576         else if( NGIRCd_SignalRestart ) Log( LOG_NOTICE|LOG_snotice, "Server restarting NOW!" );
577 } /* Conn_Handler */
578
579
580 /**
581  * Write a text string into the socket of a connection.
582  * This function automatically appends CR+LF to the string and validates that
583  * the result is a valid IRC message (oversized messages are shortened, for
584  * example). Then it calls the Conn_Write() function to do the actual sending.
585  * @param Idx Index fo the connection.
586  * @param Format Format string, see printf().
587  * @return true on success, false otherwise.
588  */
589 #ifdef PROTOTYPES
590 GLOBAL bool
591 Conn_WriteStr( CONN_ID Idx, char *Format, ... )
592 #else
593 GLOBAL bool 
594 Conn_WriteStr( Idx, Format, va_alist )
595 CONN_ID Idx;
596 char *Format;
597 va_dcl
598 #endif
599 {
600         char buffer[COMMAND_LEN];
601         size_t len;
602         bool ok;
603         va_list ap;
604
605         assert( Idx > NONE );
606         assert( Format != NULL );
607
608 #ifdef PROTOTYPES
609         va_start( ap, Format );
610 #else
611         va_start( ap );
612 #endif
613         if (vsnprintf( buffer, COMMAND_LEN - 2, Format, ap ) >= COMMAND_LEN - 2 ) {
614                 /*
615                  * The string that should be written to the socket is longer
616                  * than the allowed size of COMMAND_LEN bytes (including both
617                  * the CR and LF characters). This can be caused by the
618                  * IRC_WriteXXX() functions when the prefix of this server had
619                  * to be added to an already "quite long" command line which
620                  * has been received from a regular IRC client, for example.
621                  * 
622                  * We are not allowed to send such "oversized" messages to
623                  * other servers and clients, see RFC 2812 2.3 and 2813 3.3
624                  * ("these messages SHALL NOT exceed 512 characters in length,
625                  * counting all characters including the trailing CR-LF").
626                  *
627                  * So we have a big problem here: we should send more bytes
628                  * to the network than we are allowed to and we don't know
629                  * the originator (any more). The "old" behaviour of blaming
630                  * the receiver ("next hop") is a bad idea (it could be just
631                  * an other server only routing the message!), so the only
632                  * option left is to shorten the string and to hope that the
633                  * result is still somewhat useful ...
634                  *                                                   -alex-
635                  */
636
637                 strcpy (buffer + sizeof(buffer) - strlen(CUT_TXTSUFFIX) - 2 - 1,
638                         CUT_TXTSUFFIX);
639         }
640
641 #ifdef SNIFFER
642         if (NGIRCd_Sniffer)
643                 Log(LOG_DEBUG, " -> connection %d: '%s'.", Idx, buffer);
644 #endif
645
646         len = strlcat( buffer, "\r\n", sizeof( buffer ));
647         ok = Conn_Write(Idx, buffer, len);
648         My_Connections[Idx].msg_out++;
649
650         va_end( ap );
651         return ok;
652 } /* Conn_WriteStr */
653
654
655 /**
656  * Append Data to the outbound write buffer of a connection.
657  * @param Idx Index of the connection.
658  * @param Data pointer to the data.
659  * @param Len length of Data.
660  * @return true on success, false otherwise.
661  */
662 static bool
663 Conn_Write( CONN_ID Idx, char *Data, size_t Len )
664 {
665         CLIENT *c;
666         size_t writebuf_limit = WRITEBUFFER_LEN;
667         assert( Idx > NONE );
668         assert( Data != NULL );
669         assert( Len > 0 );
670
671         c = Conn_GetClient(Idx);
672         assert( c != NULL);
673
674         /* Servers do get special write buffer limits, so they can generate
675          * all the messages that are required while peering. */
676         if (Client_Type(c) == CLIENT_SERVER)
677                 writebuf_limit = WRITEBUFFER_SLINK_LEN;
678
679         /* Is the socket still open? A previous call to Conn_Write()
680          * may have closed the connection due to a fatal error.
681          * In this case it is sufficient to return an error, as well. */
682         if( My_Connections[Idx].sock <= NONE ) {
683                 LogDebug("Skipped write on closed socket (connection %d).", Idx);
684                 return false;
685         }
686
687 #ifdef ZLIB
688         if ( Conn_OPTION_ISSET( &My_Connections[Idx], CONN_ZIP )) {
689                 /* Compressed link:
690                  * Zip_Buffer() does all the dirty work for us: it flushes
691                  * the (pre-)compression buffers if required and handles
692                  * all error conditions. */
693                 if (!Zip_Buffer(Idx, Data, Len))
694                         return false;
695         }
696         else
697 #endif
698         {
699                 /* Uncompressed link:
700                  * Check if outbound buffer has enough space for the data. */
701                 if (array_bytes(&My_Connections[Idx].wbuf) + Len >=
702                     writebuf_limit) {
703                         /* Buffer is full, flush it. Handle_Write deals with
704                          * low-level errors, if any. */
705                         if (!Handle_Write(Idx))
706                                 return false;
707                 }
708
709                 /* When the write buffer is still too big after flushing it,
710                  * the connection will be killed. */
711                 if (array_bytes(&My_Connections[Idx].wbuf) + Len >=
712                     writebuf_limit) {
713                         Log(LOG_NOTICE,
714                             "Write buffer overflow (connection %d, size %lu byte)!",
715                             Idx,
716                             (unsigned long)array_bytes(&My_Connections[Idx].wbuf));
717                         Conn_Close(Idx, "Write buffer overflow!", NULL, false);
718                         return false;
719                 }
720
721                 /* Copy data to write buffer */
722                 if (!array_catb(&My_Connections[Idx].wbuf, Data, Len))
723                         return false;
724
725                 My_Connections[Idx].bytes_out += Len;
726         }
727
728         /* Adjust global write counter */
729         WCounter += Len;
730
731         return true;
732 } /* Conn_Write */
733
734
735 GLOBAL void
736 Conn_Close( CONN_ID Idx, char *LogMsg, char *FwdMsg, bool InformClient )
737 {
738         /* Close connection. Open pipes of asyncronous resolver
739          * sub-processes are closed down. */
740
741         CLIENT *c;
742         char *txt;
743         double in_k, out_k;
744         UINT16 port;
745 #ifdef ZLIB
746         double in_z_k, out_z_k;
747         int in_p, out_p;
748 #endif
749
750         assert( Idx > NONE );
751
752         /* Is this link already shutting down? */
753         if( Conn_OPTION_ISSET( &My_Connections[Idx], CONN_ISCLOSING )) {
754                 /* Conn_Close() has been called recursively for this link;
755                  * probabe reason: Handle_Write() failed  -- see below. */
756                 LogDebug("Recursive request to close connection: %d", Idx );
757                 return;
758         }
759
760         assert( My_Connections[Idx].sock > NONE );
761
762         /* Mark link as "closing" */
763         Conn_OPTION_ADD( &My_Connections[Idx], CONN_ISCLOSING );
764
765         if (LogMsg)
766                 txt = LogMsg;
767         else
768                 txt = FwdMsg;
769         if (! txt)
770                 txt = "Reason unknown";
771
772         port = ng_ipaddr_getport(&My_Connections[Idx].addr);
773         Log(LOG_INFO, "Shutting down connection %d (%s) with %s:%d ...", Idx,
774             LogMsg ? LogMsg : FwdMsg, My_Connections[Idx].host, port);
775
776         /* Search client, if any */
777         c = Conn_GetClient( Idx );
778
779         /* Should the client be informed? */
780         if (InformClient) {
781 #ifndef STRICT_RFC
782                 /* Send statistics to client if registered as user: */
783                 if ((c != NULL) && (Client_Type(c) == CLIENT_USER)) {
784                         Conn_WriteStr( Idx,
785                          ":%s NOTICE %s :%sConnection statistics: client %.1f kb, server %.1f kb.",
786                          Client_ID(Client_ThisServer()), Client_ID(c),
787                          NOTICE_TXTPREFIX,
788                          (double)My_Connections[Idx].bytes_in / 1024,
789                          (double)My_Connections[Idx].bytes_out / 1024);
790                 }
791 #endif
792                 /* Send ERROR to client (see RFC!) */
793                 if (FwdMsg)
794                         Conn_WriteStr(Idx, "ERROR :%s", FwdMsg);
795                 else
796                         Conn_WriteStr(Idx, "ERROR :Closing connection.");
797         }
798
799         /* Try to write out the write buffer. Note: Handle_Write() eventually
800          * removes the CLIENT structure associated with this connection if an
801          * error occurs! So we have to re-check if there is still an valid
802          * CLIENT structure after calling Handle_Write() ...*/
803         (void)Handle_Write( Idx );
804
805         /* Search client, if any (re-check!) */
806         c = Conn_GetClient( Idx );
807
808         /* Shut down socket */
809         if (! io_close(My_Connections[Idx].sock)) {
810                 /* Oops, we can't close the socket!? This is ... ugly! */
811                 Log(LOG_CRIT,
812                     "Error closing connection %d (socket %d) with %s:%d - %s! (ignored)",
813                     Idx, My_Connections[Idx].sock, My_Connections[Idx].host,
814                     port, strerror(errno));
815         }
816
817         /* Mark socket as invalid: */
818         My_Connections[Idx].sock = NONE;
819
820         /* If there is still a client, unregister it now */
821         if (c)
822                 Client_Destroy(c, LogMsg, FwdMsg, true);
823
824         /* Calculate statistics and log information */
825         in_k = (double)My_Connections[Idx].bytes_in / 1024;
826         out_k = (double)My_Connections[Idx].bytes_out / 1024;
827 #ifdef ZLIB
828         if (Conn_OPTION_ISSET( &My_Connections[Idx], CONN_ZIP)) {
829                 in_z_k = (double)My_Connections[Idx].zip.bytes_in / 1024;
830                 out_z_k = (double)My_Connections[Idx].zip.bytes_out / 1024;
831                 /* Make sure that no division by zero can occur during
832                  * the calculation of in_p and out_p: in_z_k and out_z_k
833                  * are non-zero, that's guaranteed by the protocol until
834                  * compression can be enabled. */
835                 if (! in_z_k)
836                         in_z_k = in_k;
837                 if (! out_z_k)
838                         out_z_k = out_k;
839                 in_p = (int)(( in_k * 100 ) / in_z_k );
840                 out_p = (int)(( out_k * 100 ) / out_z_k );
841                 Log(LOG_INFO,
842                     "Connection %d with %s:%d closed (in: %.1fk/%.1fk/%d%%, out: %.1fk/%.1fk/%d%%).",
843                     Idx, My_Connections[Idx].host, port,
844                     in_k, in_z_k, in_p, out_k, out_z_k, out_p);
845         }
846         else
847 #endif
848         {
849                 Log(LOG_INFO,
850                     "Connection %d with %s:%d closed (in: %.1fk, out: %.1fk).",
851                     Idx, My_Connections[Idx].host, port,
852                     in_k, out_k);
853         }
854
855         /* cancel running resolver */
856         if (Resolve_INPROGRESS(&My_Connections[Idx].res_stat))
857                 Resolve_Shutdown(&My_Connections[Idx].res_stat);
858
859         /* Servers: Modify time of next connect attempt? */
860         Conf_UnsetServer( Idx );
861
862 #ifdef ZLIB
863         /* Clean up zlib, if link was compressed */
864         if ( Conn_OPTION_ISSET( &My_Connections[Idx], CONN_ZIP )) {
865                 inflateEnd( &My_Connections[Idx].zip.in );
866                 deflateEnd( &My_Connections[Idx].zip.out );
867                 array_free(&My_Connections[Idx].zip.rbuf);
868                 array_free(&My_Connections[Idx].zip.wbuf);
869         }
870 #endif
871
872         array_free(&My_Connections[Idx].rbuf);
873         array_free(&My_Connections[Idx].wbuf);
874
875         /* Clean up connection structure (=free it) */
876         Init_Conn_Struct( Idx );
877
878         LogDebug("Shutdown of connection %d completed.", Idx );
879 } /* Conn_Close */
880
881
882 GLOBAL void
883 Conn_SyncServerStruct( void )
884 {
885         /* Synchronize server structures (connection IDs):
886          * connections <-> configuration */
887
888         CLIENT *client;
889         CONN_ID i;
890         int c;
891
892         for( i = 0; i < Pool_Size; i++ ) {
893                 /* Established connection? */
894                 if (My_Connections[i].sock < 0)
895                         continue;
896
897                 /* Server connection? */
898                 client = Conn_GetClient( i );
899                 if(( ! client ) || ( Client_Type( client ) != CLIENT_SERVER )) continue;
900
901                 for( c = 0; c < MAX_SERVERS; c++ )
902                 {
903                         /* Configured server? */
904                         if( ! Conf_Server[c].host[0] ) continue;
905
906                         /* Duplicate? */
907                         if( strcmp( Conf_Server[c].name, Client_ID( client )) == 0 )
908                                 Conf_Server[c].conn_id = i;
909                 }
910         }
911 } /* SyncServerStruct */
912
913
914 /**
915  * Send out data of write buffer; connect new sockets.
916  */
917 static bool
918 Handle_Write( CONN_ID Idx )
919 {
920         ssize_t len;
921         size_t wdatalen;
922
923         assert( Idx > NONE );
924         if ( My_Connections[Idx].sock < 0 ) {
925                 LogDebug("Handle_Write() on closed socket, connection %d", Idx);
926                 return false;
927         }
928         assert( My_Connections[Idx].sock > NONE );
929
930         wdatalen = array_bytes(&My_Connections[Idx].wbuf );
931
932 #ifdef ZLIB
933         if (wdatalen == 0) {
934                 /* Write buffer is empty, so we try to flush the compression
935                  * buffer and get some data to work with from there :-) */
936                 if (!Zip_Flush(Idx))
937                         return false;
938
939                 /* Now the write buffer most probably has changed: */
940                 wdatalen = array_bytes(&My_Connections[Idx].wbuf);
941         }
942 #endif
943
944         if (wdatalen == 0) {
945                 /* Still no data, fine. */
946                 io_event_del(My_Connections[Idx].sock, IO_WANTWRITE );
947                 return true;
948         }
949
950         LogDebug
951             ("Handle_Write() called for connection %d, %ld bytes pending ...",
952              Idx, wdatalen);
953
954         len = write(My_Connections[Idx].sock,
955                     array_start(&My_Connections[Idx].wbuf), wdatalen );
956
957         if( len < 0 ) {
958                 if (errno == EAGAIN || errno == EINTR)
959                         return true;
960
961                 Log(LOG_ERR, "Write error on connection %d (socket %d): %s!",
962                     Idx, My_Connections[Idx].sock, strerror(errno));
963                 Conn_Close(Idx, "Write error!", NULL, false);
964                 return false;
965         }
966
967         /* move any data not yet written to beginning */
968         array_moveleft(&My_Connections[Idx].wbuf, 1, (size_t)len);
969
970         return true;
971 } /* Handle_Write */
972
973
974 static int
975 Count_Connections(ng_ipaddr_t *a)
976 {
977         int i, cnt;
978
979         cnt = 0;
980         for (i = 0; i < Pool_Size; i++) {
981                 if (My_Connections[i].sock <= NONE)
982                         continue;
983                 if (ng_ipaddr_ipequal(&My_Connections[i].addr, a))
984                         cnt++;
985         }
986         return cnt;
987 } /* Count_Connections */
988
989
990 static int
991 New_Connection( int Sock )
992 {
993         /* Neue Client-Verbindung von Listen-Socket annehmen und
994          * CLIENT-Struktur anlegen. */
995
996 #ifdef TCPWRAP
997         struct request_info req;
998 #endif
999         ng_ipaddr_t new_addr;
1000         char ip_str[NG_INET_ADDRSTRLEN];
1001         int new_sock, new_sock_len, new_Pool_Size;
1002         CLIENT *c;
1003         long cnt;
1004
1005         assert( Sock > NONE );
1006         /* Connection auf Listen-Socket annehmen */
1007         new_sock_len = (int)sizeof(new_addr);
1008
1009         new_sock = accept(Sock, (struct sockaddr *)&new_addr,
1010                           (socklen_t *)&new_sock_len);
1011         if (new_sock < 0) {
1012                 Log(LOG_CRIT, "Can't accept connection: %s!", strerror(errno));
1013                 return -1;
1014         }
1015
1016         if (!ng_ipaddr_tostr_r(&new_addr, ip_str)) {
1017                 Log(LOG_CRIT, "fd %d: Can't convert IP address!", new_sock);
1018                 Simple_Message(new_sock, "ERROR :Internal Server Error");
1019                 close(new_sock);
1020         }
1021
1022 #ifdef TCPWRAP
1023         /* Validate socket using TCP Wrappers */
1024         request_init( &req, RQ_DAEMON, PACKAGE_NAME, RQ_FILE, new_sock, RQ_CLIENT_SIN, &new_addr, NULL );
1025         fromhost(&req);
1026         if (!hosts_access(&req)) {
1027                 Log (deny_severity, "Refused connection from %s (by TCP Wrappers)!", ip_str);
1028                 Simple_Message( new_sock, "ERROR :Connection refused" );
1029                 close( new_sock );
1030                 return -1;
1031         }
1032 #endif
1033
1034         /* Socket initialisieren */
1035         if (!Init_Socket( new_sock ))
1036                 return -1;
1037
1038         /* Check IP-based connection limit */
1039         cnt = Count_Connections(&new_addr);
1040         if ((Conf_MaxConnectionsIP > 0) && (cnt >= Conf_MaxConnectionsIP)) {
1041                 /* Access denied, too many connections from this IP address! */
1042                 Log( LOG_ERR, "Refused connection from %s: too may connections (%ld) from this IP address!", ip_str, cnt);
1043                 Simple_Message( new_sock, "ERROR :Connection refused, too many connections from your IP address!" );
1044                 close( new_sock );
1045                 return -1;
1046         }
1047
1048         if( new_sock >= Pool_Size ) {
1049                 new_Pool_Size = new_sock + 1;
1050                 /* No free Connection Structures, check if we may accept further connections */
1051                 if ((( Conf_MaxConnections > 0) && Pool_Size >= Conf_MaxConnections) ||
1052                         (new_Pool_Size < Pool_Size))
1053                 {
1054                         Log( LOG_ALERT, "Can't accept connection: limit (%d) reached!", Pool_Size );
1055                         Simple_Message( new_sock, "ERROR :Connection limit reached" );
1056                         close( new_sock );
1057                         return -1;
1058                 }
1059
1060                 if (!array_alloc(&My_ConnArray, sizeof(CONNECTION),
1061                                  (size_t)new_sock)) {
1062                         Log( LOG_EMERG, "Can't allocate memory! [New_Connection]" );
1063                         Simple_Message( new_sock, "ERROR: Internal error" );
1064                         close( new_sock );
1065                         return -1;
1066                 }
1067                 LogDebug("Bumped connection pool to %ld items (internal: %ld items, %ld bytes)",
1068                         new_sock, array_length(&My_ConnArray, sizeof(CONNECTION)), array_bytes(&My_ConnArray));
1069
1070                 /* Adjust pointer to new block */
1071                 My_Connections = array_start(&My_ConnArray);
1072                 while (Pool_Size < new_Pool_Size)
1073                         Init_Conn_Struct(Pool_Size++);
1074         }
1075
1076         /* register callback */
1077         if (!io_event_create( new_sock, IO_WANTREAD, cb_clientserver)) {
1078                 Log(LOG_ALERT, "Can't accept connection: io_event_create failed!");
1079                 Simple_Message(new_sock, "ERROR :Internal error");
1080                 close(new_sock);
1081                 return -1;
1082         }
1083
1084         c = Client_NewLocal(new_sock, ip_str, CLIENT_UNKNOWN, false );
1085         if( ! c ) {
1086                 Log(LOG_ALERT, "Can't accept connection: can't create client structure!");
1087                 Simple_Message(new_sock, "ERROR :Internal error");
1088                 io_close(new_sock);
1089                 return -1;
1090         }
1091
1092         Init_Conn_Struct( new_sock );
1093         My_Connections[new_sock].sock = new_sock;
1094         My_Connections[new_sock].addr = new_addr;
1095         My_Connections[new_sock].client = c;
1096
1097         Log( LOG_INFO, "Accepted connection %d from %s:%d on socket %d.", new_sock,
1098                         ip_str, ng_ipaddr_getport(&new_addr), Sock);
1099
1100         /* Hostnamen ermitteln */
1101         strlcpy(My_Connections[new_sock].host, ip_str, sizeof(My_Connections[new_sock].host));
1102
1103         Client_SetHostname(c, My_Connections[new_sock].host);
1104
1105         if (!Conf_NoDNS)
1106                 Resolve_Addr(&My_Connections[new_sock].res_stat, &new_addr,
1107                         My_Connections[new_sock].sock, cb_Read_Resolver_Result);
1108
1109         Conn_SetPenalty(new_sock, 4);
1110         return new_sock;
1111 } /* New_Connection */
1112
1113
1114 static CONN_ID
1115 Socket2Index( int Sock )
1116 {
1117         /* zum Socket passende Connection suchen */
1118
1119         assert( Sock >= 0 );
1120
1121         if( Sock >= Pool_Size || My_Connections[Sock].sock != Sock ) {
1122                 /* die Connection wurde vermutlich (wegen eines
1123                  * Fehlers) bereits wieder abgebaut ... */
1124                 LogDebug("Socket2Index: can't get connection for socket %d!", Sock);
1125                 return NONE;
1126         }
1127         return Sock;
1128 } /* Socket2Index */
1129
1130
1131 /**
1132  * Read data from the network to the read buffer. If an error occures,
1133  * the socket of this connection will be shut down.
1134  */
1135 static void
1136 Read_Request( CONN_ID Idx )
1137 {
1138         ssize_t len;
1139         char readbuf[READBUFFER_LEN];
1140         CLIENT *c;
1141         assert( Idx > NONE );
1142         assert( My_Connections[Idx].sock > NONE );
1143
1144 #ifdef ZLIB
1145         if ((array_bytes(&My_Connections[Idx].rbuf) >= READBUFFER_LEN) ||
1146                 (array_bytes(&My_Connections[Idx].zip.rbuf) >= READBUFFER_LEN))
1147 #else
1148         if (array_bytes(&My_Connections[Idx].rbuf) >= READBUFFER_LEN)
1149 #endif
1150         {
1151                 /* Read buffer is full */
1152                 Log(LOG_ERR,
1153                     "Receive buffer overflow (connection %d): %d bytes!",
1154                     Idx, array_bytes(&My_Connections[Idx].rbuf));
1155                 Conn_Close( Idx, "Receive buffer overflow!", NULL, false );
1156                 return;
1157         }
1158
1159         len = read(My_Connections[Idx].sock, readbuf, sizeof(readbuf));
1160         if (len == 0) {
1161                 Log(LOG_INFO, "%s:%u (%s) is closing the connection ...",
1162                                 My_Connections[Idx].host,
1163                                 (unsigned int) ng_ipaddr_getport(&My_Connections[Idx].addr),
1164                                 ng_ipaddr_tostr(&My_Connections[Idx].addr));
1165                 Conn_Close(Idx,
1166                            "Socket closed!", "Client closed connection",
1167                            false);
1168                 return;
1169         }
1170
1171         if (len < 0) {
1172                 if( errno == EAGAIN ) return;
1173                 Log(LOG_ERR, "Read error on connection %d (socket %d): %s!",
1174                     Idx, My_Connections[Idx].sock, strerror(errno));
1175                 Conn_Close(Idx, "Read error!", "Client closed connection",
1176                            false);
1177                 return;
1178         }
1179 #ifdef ZLIB
1180         if (Conn_OPTION_ISSET(&My_Connections[Idx], CONN_ZIP)) {
1181                 if (!array_catb(&My_Connections[Idx].zip.rbuf, readbuf,
1182                                 (size_t) len)) {
1183                         Log(LOG_ERR,
1184                             "Could not append recieved data to zip input buffer (connn %d): %d bytes!",
1185                             Idx, len);
1186                         Conn_Close(Idx, "Receive buffer overflow!", NULL,
1187                                    false);
1188                         return;
1189                 }
1190         } else
1191 #endif
1192         {
1193                 if (!array_catb( &My_Connections[Idx].rbuf, readbuf, len)) {
1194                         Log( LOG_ERR, "Could not append recieved data to input buffer (connn %d): %d bytes!", Idx, len );
1195                         Conn_Close( Idx, "Receive buffer overflow!", NULL, false );
1196                 }
1197         }
1198
1199         /* Update connection statistics */
1200         My_Connections[Idx].bytes_in += len;
1201
1202         /* Update timestamp of last data received if this connection is
1203          * registered as a user, server or service connection. Don't update
1204          * otherwise, so users have at least Conf_PongTimeout seconds time to
1205          * register with the IRC server -- see Check_Connections().
1206          * Set "lastping", too, so we can handle time shifts backwards ... */
1207         c = Conn_GetClient(Idx);
1208         if (c && (Client_Type(c) == CLIENT_USER
1209                   || Client_Type(c) == CLIENT_SERVER
1210                   || Client_Type(c) == CLIENT_SERVICE)) {
1211                 My_Connections[Idx].lastdata = time(NULL);
1212                 My_Connections[Idx].lastping = My_Connections[Idx].lastdata;
1213         }
1214
1215         /* Look at the data in the (read-) buffer of this connection */
1216         Handle_Buffer(Idx);
1217 } /* Read_Request */
1218
1219
1220 static bool
1221 Handle_Buffer( CONN_ID Idx )
1222 {
1223         /* Handle Data in Connections Read-Buffer.
1224          * Return true if a reuqest was handled, false otherwise (also returned on errors). */
1225 #ifndef STRICT_RFC
1226         char *ptr1, *ptr2;
1227 #endif
1228         char *ptr;
1229         size_t len, delta;
1230         bool result;
1231         time_t starttime;
1232 #ifdef ZLIB
1233         bool old_z;
1234 #endif
1235
1236         starttime = time(NULL);
1237         result = false;
1238         for (;;) {
1239                 /* Check penalty */
1240                 if( My_Connections[Idx].delaytime > starttime) return result;
1241 #ifdef ZLIB
1242                 /* unpack compressed data */
1243                 if ( Conn_OPTION_ISSET( &My_Connections[Idx], CONN_ZIP ))
1244                         if( ! Unzip_Buffer( Idx )) return false;
1245 #endif
1246
1247                 if (0 == array_bytes(&My_Connections[Idx].rbuf))
1248                         break;
1249
1250                 if (!array_cat0_temporary(&My_Connections[Idx].rbuf)) /* make sure buf is NULL terminated */
1251                         return false;
1252
1253                 /* A Complete Request end with CR+LF, see RFC 2812. */
1254                 ptr = strstr( array_start(&My_Connections[Idx].rbuf), "\r\n" );
1255
1256                 if( ptr ) delta = 2; /* complete request */
1257 #ifndef STRICT_RFC
1258                 else {
1259                         /* Check for non-RFC-compliant request (only CR or LF)? Unfortunately,
1260                          * there are quite a few clients that do this (incl. "mIRC" :-( */
1261                         ptr1 = strchr( array_start(&My_Connections[Idx].rbuf), '\r' );
1262                         ptr2 = strchr( array_start(&My_Connections[Idx].rbuf), '\n' );
1263                         delta = 1;
1264                         if( ptr1 && ptr2 ) ptr = ptr1 > ptr2 ? ptr2 : ptr1;
1265                         else if( ptr1 ) ptr = ptr1;
1266                         else if( ptr2 ) ptr = ptr2;
1267                 }
1268 #endif
1269
1270                 if( ! ptr )
1271                         break;
1272
1273                 /* End of request found */
1274                 *ptr = '\0';
1275
1276                 len = ( ptr - (char*) array_start(&My_Connections[Idx].rbuf)) + delta;
1277
1278                 if( len > ( COMMAND_LEN - 1 )) {
1279                         /* Request must not exceed 512 chars (incl. CR+LF!), see
1280                          * RFC 2812. Disconnect Client if this happens. */
1281                         Log( LOG_ERR, "Request too long (connection %d): %d bytes (max. %d expected)!",
1282                                                 Idx, array_bytes(&My_Connections[Idx].rbuf), COMMAND_LEN - 1 );
1283                         Conn_Close( Idx, NULL, "Request too long", true );
1284                         return false;
1285                 }
1286
1287                 if (len <= 2) { /* request was empty (only '\r\n') */
1288                         array_moveleft(&My_Connections[Idx].rbuf, 1, delta); /* delta is either 1 or 2 */
1289                         break;
1290                 }
1291 #ifdef ZLIB
1292                 /* remember if stream is already compressed */
1293                 old_z = My_Connections[Idx].options & CONN_ZIP;
1294 #endif
1295
1296                 My_Connections[Idx].msg_in++;
1297                 if (!Parse_Request(Idx, (char*)array_start(&My_Connections[Idx].rbuf) ))
1298                         return false;
1299
1300                 result = true;
1301
1302                 array_moveleft(&My_Connections[Idx].rbuf, 1, len);
1303                 LogDebug("Connection %d: %d bytes left in read buffer.",
1304                     Idx, array_bytes(&My_Connections[Idx].rbuf));
1305 #ifdef ZLIB
1306                 if(( ! old_z ) && ( My_Connections[Idx].options & CONN_ZIP ) &&
1307                                 ( array_bytes(&My_Connections[Idx].rbuf) > 0 ))
1308                 {
1309                         /* The last Command activated Socket-Compression.
1310                          * Data that was read after that needs to be copied to Unzip-buf
1311                          * for decompression */
1312                         if (!array_copy( &My_Connections[Idx].zip.rbuf, &My_Connections[Idx].rbuf ))
1313                                 return false;
1314
1315                         array_trunc(&My_Connections[Idx].rbuf);
1316                         LogDebug("Moved already received data (%u bytes) to uncompression buffer.",
1317                                                                 array_bytes(&My_Connections[Idx].zip.rbuf));
1318                 }
1319 #endif /* ZLIB */
1320         }
1321         return result;
1322 } /* Handle_Buffer */
1323
1324
1325 static void
1326 Check_Connections(void)
1327 {
1328         /* check if connections are alive. if not, play PING-PONG first.
1329          * if this doesn't help either, disconnect client. */
1330         CLIENT *c;
1331         CONN_ID i;
1332
1333         for (i = 0; i < Pool_Size; i++) {
1334                 if (My_Connections[i].sock < 0)
1335                         continue;
1336
1337                 c = Conn_GetClient(i);
1338                 if (c && ((Client_Type(c) == CLIENT_USER)
1339                           || (Client_Type(c) == CLIENT_SERVER)
1340                           || (Client_Type(c) == CLIENT_SERVICE))) {
1341                         /* connected User, Server or Service */
1342                         if (My_Connections[i].lastping >
1343                             My_Connections[i].lastdata) {
1344                                 /* We already sent a ping */
1345                                 if (My_Connections[i].lastping <
1346                                     time(NULL) - Conf_PongTimeout) {
1347                                         /* Timeout */
1348                                         LogDebug
1349                                             ("Connection %d: Ping timeout: %d seconds.",
1350                                              i, Conf_PongTimeout);
1351                                         Conn_Close(i, NULL, "Ping timeout",
1352                                                    true);
1353                                 }
1354                         } else if (My_Connections[i].lastdata <
1355                                    time(NULL) - Conf_PingTimeout) {
1356                                 /* We need to send a PING ... */
1357                                 LogDebug("Connection %d: sending PING ...", i);
1358                                 My_Connections[i].lastping = time(NULL);
1359                                 Conn_WriteStr(i, "PING :%s",
1360                                               Client_ID(Client_ThisServer()));
1361                         }
1362                 } else {
1363                         /* The connection is not fully established yet, so
1364                          * we don't do the PING-PONG game here but instead
1365                          * disconnect the client after "a short time" if it's
1366                          * still not registered. */
1367
1368                         if (My_Connections[i].lastdata <
1369                             time(NULL) - Conf_PongTimeout) {
1370                                 LogDebug
1371                                     ("Unregistered connection %d timed out ...",
1372                                      i);
1373                                 Conn_Close(i, NULL, "Timeout", false);
1374                         }
1375                 }
1376         }
1377 } /* Check_Connections */
1378
1379
1380 static void
1381 Check_Servers( void )
1382 {
1383         /* Check if we can establish further server links */
1384
1385         int i, n;
1386         time_t time_now;
1387
1388         /* Check all configured servers */
1389         for( i = 0; i < MAX_SERVERS; i++ ) {
1390                 /* Valid outgoing server which isn't already connected or disabled? */
1391                 if(( ! Conf_Server[i].host[0] ) || ( ! Conf_Server[i].port > 0 ) ||
1392                         ( Conf_Server[i].conn_id > NONE ) || ( Conf_Server[i].flags & CONF_SFLAG_DISABLED ))
1393                                 continue;
1394
1395                 /* Is there already a connection in this group? */
1396                 if( Conf_Server[i].group > NONE ) {
1397                         for (n = 0; n < MAX_SERVERS; n++) {
1398                                 if (n == i) continue;
1399                                 if ((Conf_Server[n].conn_id != NONE) &&
1400                                         (Conf_Server[n].group == Conf_Server[i].group))
1401                                                 break;
1402                         }
1403                         if (n < MAX_SERVERS) continue;
1404                 }
1405
1406                 /* Check last connect attempt? */
1407                 time_now = time(NULL);
1408                 if( Conf_Server[i].lasttry > (time_now - Conf_ConnectRetry))
1409                         continue;
1410
1411                 /* Okay, try to connect now */
1412                 Conf_Server[i].lasttry = time_now;
1413                 Conf_Server[i].conn_id = SERVER_WAIT;
1414                 assert(Resolve_Getfd(&Conf_Server[i].res_stat) < 0);
1415                 Resolve_Name(&Conf_Server[i].res_stat, Conf_Server[i].host, cb_Connect_to_Server);
1416         }
1417 } /* Check_Servers */
1418
1419
1420 static void
1421 New_Server( int Server , ng_ipaddr_t *dest)
1422 {
1423         /* Establish new server link */
1424         char ip_str[NG_INET_ADDRSTRLEN];
1425         int af_dest, res, new_sock;
1426         CLIENT *c;
1427
1428         assert( Server > NONE );
1429
1430         if (!ng_ipaddr_tostr_r(dest, ip_str)) {
1431                 Log(LOG_WARNING, "New_Server: Could not convert IP to string");
1432                 return;
1433         }
1434
1435         Log( LOG_INFO, "Establishing connection to \"%s\", %s, port %d ... ",
1436                         Conf_Server[Server].host, ip_str, Conf_Server[Server].port );
1437
1438         af_dest = ng_ipaddr_af(dest);
1439         new_sock = socket(af_dest, SOCK_STREAM, 0);
1440         if (new_sock < 0) {
1441                 Log( LOG_CRIT, "Can't create socket: %s!", strerror( errno ));
1442                 return;
1443         }
1444
1445         if (!Init_Socket(new_sock))
1446                 return;
1447
1448         /* is a bind address configured? */
1449         res = ng_ipaddr_af(&Conf_Server[Server].bind_addr);
1450         /* if yes, bind now. If it fails, warn and let connect() pick a source address */
1451         if (res && bind(new_sock, (struct sockaddr *) &Conf_Server[Server].bind_addr,
1452                                 ng_ipaddr_salen(&Conf_Server[Server].bind_addr)))
1453         {
1454                 ng_ipaddr_tostr_r(&Conf_Server[Server].bind_addr, ip_str);
1455                 Log(LOG_WARNING, "Can't bind socket to %s: %s!", ip_str, strerror(errno));
1456         }
1457         ng_ipaddr_setport(dest, Conf_Server[Server].port);
1458         res = connect(new_sock, (struct sockaddr *) dest, ng_ipaddr_salen(dest));
1459         if(( res != 0 ) && ( errno != EINPROGRESS )) {
1460                 Log( LOG_CRIT, "Can't connect socket: %s!", strerror( errno ));
1461                 close( new_sock );
1462                 return;
1463         }
1464
1465         if (!array_alloc(&My_ConnArray, sizeof(CONNECTION), (size_t)new_sock)) {
1466                 Log(LOG_ALERT,
1467                     "Cannot allocate memory for server connection (socket %d)",
1468                     new_sock);
1469                 close( new_sock );
1470                 return;
1471         }
1472
1473         My_Connections = array_start(&My_ConnArray);
1474
1475         assert(My_Connections[new_sock].sock <= 0);
1476
1477         Init_Conn_Struct(new_sock);
1478
1479         ng_ipaddr_tostr_r(dest, ip_str);
1480         c = Client_NewLocal(new_sock, ip_str, CLIENT_UNKNOWNSERVER, false);
1481         if (!c) {
1482                 Log( LOG_ALERT, "Can't establish connection: can't create client structure!" );
1483                 close( new_sock );
1484                 return;
1485         }
1486
1487         Client_SetIntroducer( c, c );
1488         Client_SetToken( c, TOKEN_OUTBOUND );
1489
1490         /* Register connection */
1491         Conf_Server[Server].conn_id = new_sock;
1492         My_Connections[new_sock].sock = new_sock;
1493         My_Connections[new_sock].addr = *dest;
1494         My_Connections[new_sock].client = c;
1495         strlcpy( My_Connections[new_sock].host, Conf_Server[Server].host,
1496                                 sizeof(My_Connections[new_sock].host ));
1497
1498         /* Register new socket */
1499         if (!io_event_create( new_sock, IO_WANTWRITE, cb_connserver)) {
1500                 Log( LOG_ALERT, "io_event_create(): could not add fd %d", strerror(errno));
1501                 Conn_Close( new_sock, "io_event_create() failed", NULL, false );
1502                 Init_Conn_Struct( new_sock );
1503                 Conf_Server[Server].conn_id = NONE;
1504         }
1505
1506         LogDebug("Registered new connection %d on socket %d.",
1507                                 new_sock, My_Connections[new_sock].sock );
1508         Conn_OPTION_ADD( &My_Connections[new_sock], CONN_ISCONNECTING );
1509 } /* New_Server */
1510
1511
1512 /**
1513  * Initialize connection structure.
1514  */
1515 static void
1516 Init_Conn_Struct(CONN_ID Idx)
1517 {
1518         time_t now = time(NULL);
1519
1520         memset(&My_Connections[Idx], 0, sizeof(CONNECTION));
1521         My_Connections[Idx].sock = -1;
1522         My_Connections[Idx].signon = now;
1523         My_Connections[Idx].lastdata = now;
1524         My_Connections[Idx].lastprivmsg = now;
1525         Resolve_Init(&My_Connections[Idx].res_stat);
1526 } /* Init_Conn_Struct */
1527
1528
1529 static bool
1530 Init_Socket( int Sock )
1531 {
1532         /* Initialize socket (set options) */
1533
1534         int value;
1535
1536         if (!io_setnonblock(Sock)) {
1537                 Log( LOG_CRIT, "Can't enable non-blocking mode for socket: %s!", strerror( errno ));
1538                 close( Sock );
1539                 return false;
1540         }
1541
1542         /* Don't block this port after socket shutdown */
1543         value = 1;
1544         if( setsockopt( Sock, SOL_SOCKET, SO_REUSEADDR, &value, (socklen_t)sizeof( value )) != 0 )
1545         {
1546                 Log( LOG_ERR, "Can't set socket option SO_REUSEADDR: %s!", strerror( errno ));
1547                 /* ignore this error */
1548         }
1549
1550         /* Set type of service (TOS) */
1551 #if defined(IP_TOS) && defined(IPTOS_LOWDELAY)
1552         value = IPTOS_LOWDELAY;
1553         LogDebug("Setting option IP_TOS on socket %d to IPTOS_LOWDELAY (%d).", Sock, value );
1554         if( setsockopt( Sock, SOL_IP, IP_TOS, &value, (socklen_t)sizeof( value )) != 0 )
1555         {
1556                 Log( LOG_ERR, "Can't set socket option IP_TOS: %s!", strerror( errno ));
1557                 /* ignore this error */
1558         }
1559 #endif
1560
1561         return true;
1562 } /* Init_Socket */
1563
1564
1565
1566 static void
1567 cb_Connect_to_Server(int fd, UNUSED short events)
1568 {
1569         /* Read result of resolver sub-process from pipe and start connection */
1570         int i;
1571         size_t len;
1572         ng_ipaddr_t dest_addrs[4];      /* we can handle at most 3; but we read up to
1573                                            four so we can log the 'more than we can handle'
1574                                            condition */
1575
1576         LogDebug("Resolver: Got forward lookup callback on fd %d, events %d", fd, events);
1577
1578         for (i=0; i < MAX_SERVERS; i++) {
1579                   if (Resolve_Getfd(&Conf_Server[i].res_stat) == fd )
1580                           break;
1581         }
1582
1583         if( i >= MAX_SERVERS) {
1584                 /* Ops, no matching server found?! */
1585                 io_close( fd );
1586                 LogDebug("Resolver: Got Forward Lookup callback for unknown server!?");
1587                 return;
1588         }
1589
1590         /* Read result from pipe */
1591         len = Resolve_Read(&Conf_Server[i].res_stat, dest_addrs, sizeof(dest_addrs));
1592         if (len == 0)
1593                 return;
1594
1595         assert((len % sizeof(ng_ipaddr_t)) == 0);
1596
1597         LogDebug("Got result from resolver: %u structs (%u bytes).", len/sizeof(ng_ipaddr_t), len);
1598
1599         memset(&Conf_Server[i].dst_addr, 0, sizeof(&Conf_Server[i].dst_addr));
1600         if (len > sizeof(ng_ipaddr_t)) {
1601                 /* more than one address for this hostname, remember them
1602                  * in case first address is unreachable/not available */
1603                 len -= sizeof(ng_ipaddr_t);
1604                 if (len > sizeof(&Conf_Server[i].dst_addr)) {
1605                         len = sizeof(&Conf_Server[i].dst_addr);
1606                         Log(LOG_NOTICE, "Notice: Resolver returned more IP Addresses for host than we can handle,"
1607                                         " additional addresses dropped");
1608                 }
1609                 memcpy(&Conf_Server[i].dst_addr, &dest_addrs[1], len);
1610         }
1611         /* connect() */
1612         New_Server(i, dest_addrs);
1613 } /* cb_Read_Forward_Lookup */
1614
1615
1616 static void
1617 cb_Read_Resolver_Result( int r_fd, UNUSED short events )
1618 {
1619         /* Read result of resolver sub-process from pipe and update the
1620          * apropriate connection/client structure(s): hostname and/or
1621          * IDENT user name.*/
1622
1623         CLIENT *c;
1624         int i;
1625         size_t len;
1626         char *identptr;
1627 #ifdef IDENTAUTH
1628         char readbuf[HOST_LEN + 2 + CLIENT_USER_LEN];
1629 #else
1630         char readbuf[HOST_LEN + 1];
1631 #endif
1632
1633         LogDebug("Resolver: Got callback on fd %d, events %d", r_fd, events );
1634
1635         /* Search associated connection ... */
1636         for( i = 0; i < Pool_Size; i++ ) {
1637                 if(( My_Connections[i].sock != NONE )
1638                   && ( Resolve_Getfd(&My_Connections[i].res_stat) == r_fd ))
1639                         break;
1640         }
1641         if( i >= Pool_Size ) {
1642                 /* Ops, none found? Probably the connection has already
1643                  * been closed!? We'll ignore that ... */
1644                 io_close( r_fd );
1645                 LogDebug("Resolver: Got callback for unknown connection!?");
1646                 return;
1647         }
1648
1649         /* Read result from pipe */
1650         len = Resolve_Read(&My_Connections[i].res_stat, readbuf, sizeof readbuf -1);
1651         if (len == 0)
1652                 return;
1653
1654         readbuf[len] = '\0';
1655         identptr = strchr(readbuf, '\n');
1656         assert(identptr != NULL);
1657         if (!identptr) {
1658                 Log( LOG_CRIT, "Resolver: Got malformed result!");
1659                 return;
1660         }
1661
1662         *identptr = '\0';
1663         LogDebug("Got result from resolver: \"%s\" (%u bytes read).", readbuf, len);
1664         /* Okay, we got a complete result: this is a host name for outgoing
1665          * connections and a host name and IDENT user name (if enabled) for
1666          * incoming connections.*/
1667         assert ( My_Connections[i].sock >= 0 );
1668         /* Incoming connection. Search client ... */
1669         c = Conn_GetClient( i );
1670         assert( c != NULL );
1671
1672         /* Only update client information of unregistered clients */
1673         if( Client_Type( c ) == CLIENT_UNKNOWN ) {
1674                 strlcpy(My_Connections[i].host, readbuf, sizeof( My_Connections[i].host));
1675                 Client_SetHostname( c, readbuf);
1676 #ifdef IDENTAUTH
1677                 ++identptr;
1678                 if (*identptr) {
1679                         Log(LOG_INFO, "IDENT lookup for connection %d: \"%s\".", i, identptr);
1680                         Client_SetUser(c, identptr, true);
1681                 } else {
1682                         Log(LOG_INFO, "IDENT lookup for connection %d: no result.", i);
1683                 }
1684 #endif
1685         }
1686 #ifdef DEBUG
1687                 else Log( LOG_DEBUG, "Resolver: discarding result for already registered connection %d.", i );
1688 #endif
1689         /* Reset penalty time */
1690         Conn_ResetPenalty( i );
1691 } /* cb_Read_Resolver_Result */
1692
1693
1694 static void
1695 Simple_Message( int Sock, const char *Msg )
1696 {
1697         char buf[COMMAND_LEN];
1698         size_t len;
1699         /* Write "simple" message to socket, without using compression
1700          * or even the connection write buffers. Used e.g. for error
1701          * messages by New_Connection(). */
1702         assert( Sock > NONE );
1703         assert( Msg != NULL );
1704
1705         strlcpy( buf, Msg, sizeof buf - 2);
1706         len = strlcat( buf, "\r\n", sizeof buf);
1707         (void)write(Sock, buf, len);
1708 } /* Simple_Error */
1709
1710
1711 GLOBAL CLIENT *
1712 Conn_GetClient( CONN_ID Idx ) 
1713 {
1714         /* return Client-Structure that belongs to the local Connection Idx.
1715          * If none is found, return NULL.
1716          */
1717         CONNECTION *c;
1718         assert( Idx >= 0 );
1719
1720         c = array_get(&My_ConnArray, sizeof (CONNECTION), (size_t)Idx);
1721
1722         assert(c != NULL);
1723
1724         return c ? c->client : NULL;
1725 }
1726
1727 /* -eof- */