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