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