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