]> arthur.barton.de Git - ngircd-alex.git/blob - src/ngircd/conn.c
Added support for TCP Wrappers.
[ngircd-alex.git] / src / ngircd / conn.c
1 /*
2  * ngIRCd -- The Next Generation IRC Daemon
3  * Copyright (c)2001-2003 by 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
19 static char UNUSED id[] = "$Id: conn.c,v 1.118 2003/03/07 14:35:52 alex Exp $";
20
21 #include "imp.h"
22 #include <assert.h>
23 #include <stdarg.h>
24 #include <stdio.h>
25 #include <stdlib.h>
26 #include <unistd.h>
27 #include <errno.h>
28 #include <fcntl.h>
29 #include <string.h>
30 #include <sys/socket.h>
31 #include <sys/time.h>
32 #include <sys/types.h>
33 #include <time.h>
34 #include <netinet/in.h>
35
36 #ifdef HAVE_ARPA_INET_H
37 #include <arpa/inet.h>
38 #else
39 #define PF_INET AF_INET
40 #endif
41
42 #ifdef HAVE_STDINT_H
43 #include <stdint.h>                     /* e.g. for Mac OS X */
44 #endif
45
46 #ifdef USE_TCPWRAP
47 #include <tcpd.h>                       /* for TCP Wrappers */
48 #endif
49
50 #include "defines.h"
51 #include "resolve.h"
52
53 #include "exp.h"
54 #include "conn.h"
55
56 #include "imp.h"
57 #include "ngircd.h"
58 #include "client.h"
59 #include "conf.h"
60 #include "conn-zip.h"
61 #include "conn-func.h"
62 #include "log.h"
63 #include "parse.h"
64 #include "tool.h"
65
66 #ifdef RENDEZVOUS
67 #include "rendezvous.h"
68 #endif
69
70 #include "exp.h"
71
72
73 #define SERVER_WAIT (NONE - 1)
74
75
76 LOCAL VOID Handle_Read PARAMS(( INT sock ));
77 LOCAL BOOLEAN Handle_Write PARAMS(( CONN_ID Idx ));
78 LOCAL VOID New_Connection PARAMS(( INT Sock ));
79 LOCAL CONN_ID Socket2Index PARAMS(( INT Sock ));
80 LOCAL VOID Read_Request PARAMS(( CONN_ID Idx ));
81 LOCAL BOOLEAN Try_Write PARAMS(( CONN_ID Idx ));
82 LOCAL BOOLEAN Handle_Buffer PARAMS(( CONN_ID Idx ));
83 LOCAL VOID Check_Connections PARAMS(( VOID ));
84 LOCAL VOID Check_Servers PARAMS(( VOID ));
85 LOCAL VOID Init_Conn_Struct PARAMS(( CONN_ID Idx ));
86 LOCAL BOOLEAN Init_Socket PARAMS(( INT Sock ));
87 LOCAL VOID New_Server PARAMS(( INT Server, CONN_ID Idx ));
88 LOCAL VOID Read_Resolver_Result PARAMS(( INT r_fd ));
89
90 LOCAL fd_set My_Listeners;
91 LOCAL fd_set My_Sockets;
92 LOCAL fd_set My_Connects;
93
94 #ifdef USE_TCPWRAP
95 INT allow_severity = LOG_INFO;
96 INT deny_severity = LOG_ERR;
97 #endif
98
99
100 GLOBAL VOID
101 Conn_Init( VOID )
102 {
103         /* Modul initialisieren: statische Strukturen "ausnullen". */
104
105         CONN_ID i;
106
107         /* Speicher fuer Verbindungs-Pool anfordern */
108         Pool_Size = CONNECTION_POOL;
109         if( Conf_MaxConnections > 0 )
110         {
111                 /* konfiguriertes Limit beachten */
112                 if( Pool_Size > Conf_MaxConnections ) Pool_Size = Conf_MaxConnections;
113         }
114         My_Connections = malloc( sizeof( CONNECTION ) * Pool_Size );
115         if( ! My_Connections )
116         {
117                 /* Speicher konnte nicht alloziert werden! */
118                 Log( LOG_EMERG, "Can't allocate memory! [Conn_Init]" );
119                 exit( 1 );
120         }
121         Log( LOG_DEBUG, "Allocted connection pool for %d items (%ld bytes).", Pool_Size, sizeof( CONNECTION ) * Pool_Size );
122
123         /* zu Beginn haben wir keine Verbindungen */
124         FD_ZERO( &My_Listeners );
125         FD_ZERO( &My_Sockets );
126         FD_ZERO( &My_Connects );
127
128         /* Groesster File-Descriptor fuer select() */
129         Conn_MaxFD = 0;
130
131         /* Connection-Struktur initialisieren */
132         for( i = 0; i < Pool_Size; i++ ) Init_Conn_Struct( i );
133
134         /* Global write counter */
135         WCounter = 0;
136 } /* Conn_Init */
137
138
139 GLOBAL VOID
140 Conn_Exit( VOID )
141 {
142         /* Modul abmelden: alle noch offenen Connections
143          * schliessen und freigeben. */
144
145         CONN_ID idx;
146         INT i;
147
148         Log( LOG_DEBUG, "Shutting down all connections ..." );
149
150 #ifdef RENDEZVOUS
151         Rendezvous_UnregisterListeners( );
152 #endif
153         
154         /* Sockets schliessen */
155         for( i = 0; i < Conn_MaxFD + 1; i++ )
156         {
157                 if( FD_ISSET( i, &My_Sockets ))
158                 {
159                         for( idx = 0; idx < Pool_Size; idx++ )
160                         {
161                                 if( My_Connections[idx].sock == i ) break;
162                         }
163                         if( FD_ISSET( i, &My_Listeners ))
164                         {
165                                 close( i );
166                                 Log( LOG_DEBUG, "Listening socket %d closed.", i );
167                         }
168                         else if( FD_ISSET( i, &My_Connects ))
169                         {
170                                 close( i );
171                                 Log( LOG_DEBUG, "Connection %d closed during creation (socket %d).", idx, i );
172                         }
173                         else if( idx < Pool_Size )
174                         {
175                                 if( NGIRCd_SignalRestart ) Conn_Close( idx, NULL, "Server going down (restarting)", TRUE );
176                                 else Conn_Close( idx, NULL, "Server going down", TRUE );
177                         }
178                         else
179                         {
180                                 Log( LOG_WARNING, "Closing unknown connection %d ...", i );
181                                 close( i );
182                         }
183                 }
184         }
185         
186         free( My_Connections );
187         My_Connections = NULL;
188         Pool_Size = 0;
189 } /* Conn_Exit */
190
191
192 GLOBAL INT
193 Conn_InitListeners( VOID )
194 {
195         /* Initialize ports on which the server should accept connections */
196
197         INT created, i;
198
199         created = 0;
200         for( i = 0; i < Conf_ListenPorts_Count; i++ )
201         {
202                 if( Conn_NewListener( Conf_ListenPorts[i] )) created++;
203                 else Log( LOG_ERR, "Can't listen on port %u!", Conf_ListenPorts[i] );
204         }
205         return created;
206 } /* Conn_InitListeners */
207
208
209 GLOBAL VOID
210 Conn_ExitListeners( VOID )
211 {
212         /* Close down all listening sockets */
213
214         INT i;
215
216 #ifdef RENDEZVOUS
217         Rendezvous_UnregisterListeners( );
218 #endif
219         
220         Log( LOG_INFO, "Shutting down all listening sockets ..." );
221         for( i = 0; i < Conn_MaxFD + 1; i++ )
222         {
223                 if( FD_ISSET( i, &My_Sockets ) && FD_ISSET( i, &My_Listeners ))
224                 {
225                         close( i );
226                         Log( LOG_DEBUG, "Listening socket %d closed.", i );
227                 }
228         }
229 } /* Conn_ExitListeners */
230
231
232 GLOBAL BOOLEAN
233 Conn_NewListener( CONST UINT Port )
234 {
235         /* Create new listening socket on specified port */
236
237         struct sockaddr_in addr;
238         INT sock;
239 #ifdef RENDEZVOUS
240         CHAR name[CLIENT_ID_LEN], *info;
241 #endif
242         
243         /* Server-"Listen"-Socket initialisieren */
244         memset( &addr, 0, sizeof( addr ));
245         addr.sin_family = AF_INET;
246         addr.sin_port = htons( Port );
247         addr.sin_addr.s_addr = htonl( INADDR_ANY );
248
249         /* Socket erzeugen */
250         sock = socket( PF_INET, SOCK_STREAM, 0);
251         if( sock < 0 )
252         {
253                 Log( LOG_CRIT, "Can't create socket: %s!", strerror( errno ));
254                 return FALSE;
255         }
256
257         if( ! Init_Socket( sock )) return FALSE;
258
259         /* an Port binden */
260         if( bind( sock, (struct sockaddr *)&addr, (socklen_t)sizeof( addr )) != 0 )
261         {
262                 Log( LOG_CRIT, "Can't bind socket: %s!", strerror( errno ));
263                 close( sock );
264                 return FALSE;
265         }
266
267         /* in "listen mode" gehen :-) */
268         if( listen( sock, 10 ) != 0 )
269         {
270                 Log( LOG_CRIT, "Can't listen on soecket: %s!", strerror( errno ));
271                 close( sock );
272                 return FALSE;
273         }
274
275         /* Neuen Listener in Strukturen einfuegen */
276         FD_SET( sock, &My_Listeners );
277         FD_SET( sock, &My_Sockets );
278
279         if( sock > Conn_MaxFD ) Conn_MaxFD = sock;
280
281         Log( LOG_INFO, "Now listening on port %d (socket %d).", Port, sock );
282
283 #ifdef RENDEZVOUS
284         /* Get best server description text */
285         if( ! Conf_ServerInfo[0] ) info = Conf_ServerName;
286         else
287         {
288                 /* Use server info string */
289                 info = NULL;
290                 if( Conf_ServerInfo[0] == '[' )
291                 {
292                         /* Cut off leading hostname part in "[]" */
293                         info = strchr( Conf_ServerInfo, ']' );
294                         if( info )
295                         {
296                                 info++;
297                                 while( *info == ' ' ) info++;
298                         }
299                 }
300                 if( ! info ) info = Conf_ServerInfo;
301         }
302
303         /* Add port number to description if non-standard */
304         if( Port != 6667 ) snprintf( name, sizeof( name ), "%s (port %u)", info, Port );
305         else strlcpy( name, info, sizeof( name ));
306
307         /* Register service */
308         Rendezvous_Register( name, RENDEZVOUS_TYPE, Port );
309 #endif
310
311         return TRUE;
312 } /* Conn_NewListener */
313
314
315 GLOBAL VOID
316 Conn_Handler( VOID )
317 {
318         /* "Hauptschleife": Aktive Verbindungen ueberwachen. Folgende Aktionen
319          * werden dabei durchgefuehrt, bis der Server terminieren oder neu
320          * starten soll:
321          *
322          *  - neue Verbindungen annehmen,
323          *  - Server-Verbindungen aufbauen,
324          *  - geschlossene Verbindungen loeschen,
325          *  - volle Schreibpuffer versuchen zu schreiben,
326          *  - volle Lesepuffer versuchen zu verarbeiten,
327          *  - Antworten von Resolver Sub-Prozessen annehmen.
328          */
329
330         fd_set read_sockets, write_sockets;
331         struct timeval tv;
332         time_t start, t;
333         CONN_ID i, idx;
334         BOOLEAN timeout;
335
336         start = time( NULL );
337         while(( ! NGIRCd_SignalQuit ) && ( ! NGIRCd_SignalRestart ))
338         {
339                 timeout = TRUE;
340
341 #ifdef RENDEZVOUS
342                 Rendezvous_Handler( );
343 #endif
344
345                 /* Should the configuration be reloaded? */
346                 if( NGIRCd_SignalRehash ) NGIRCd_Rehash( );
347
348                 /* Check configured servers and established links */
349                 Check_Servers( );
350                 Check_Connections( );
351
352                 /* noch volle Lese-Buffer suchen */
353                 for( i = 0; i < Pool_Size; i++ )
354                 {
355                         if(( My_Connections[i].sock > NONE ) && ( My_Connections[i].rdatalen > 0 ))
356                         {
357                                 /* Kann aus dem Buffer noch ein Befehl extrahiert werden? */
358                                 if( Handle_Buffer( i )) timeout = FALSE;
359                         }
360                 }
361
362                 /* noch volle Schreib-Puffer suchen */
363                 FD_ZERO( &write_sockets );
364                 for( i = 0; i < Pool_Size; i++ )
365                 {
366 #ifdef USE_ZLIB
367                         if(( My_Connections[i].sock > NONE ) && (( My_Connections[i].wdatalen > 0 ) || ( My_Connections[i].zip.wdatalen > 0 )))
368 #else
369                         if(( My_Connections[i].sock > NONE ) && ( My_Connections[i].wdatalen > 0 ))
370 #endif
371                         {
372                                 /* Socket der Verbindung in Set aufnehmen */
373                                 FD_SET( My_Connections[i].sock, &write_sockets );
374                         }
375                 }
376
377                 /* Sockets mit im Aufbau befindlichen ausgehenden Verbindungen suchen */
378                 for( i = 0; i < Pool_Size; i++ )
379                 {
380                         if(( My_Connections[i].sock > NONE ) && ( FD_ISSET( My_Connections[i].sock, &My_Connects ))) FD_SET( My_Connections[i].sock, &write_sockets );
381                 }
382
383                 /* von welchen Sockets koennte gelesen werden? */
384                 t = time( NULL );
385                 read_sockets = My_Sockets;
386                 for( i = 0; i < Pool_Size; i++ )
387                 {
388                         if(( My_Connections[i].sock > NONE ) && ( My_Connections[i].host[0] == '\0' ))
389                         {
390                                 /* Hier muss noch auf den Resolver Sub-Prozess gewartet werden */
391                                 FD_CLR( My_Connections[i].sock, &read_sockets );
392                         }
393                         if(( My_Connections[i].sock > NONE ) && ( FD_ISSET( My_Connections[i].sock, &My_Connects )))
394                         {
395                                 /* Hier laeuft noch ein asyncrones connect() */
396                                 FD_CLR( My_Connections[i].sock, &read_sockets );
397                         }
398                         if( My_Connections[i].delaytime > t )
399                         {
400                                 /* Fuer die Verbindung ist eine "Penalty-Zeit" gesetzt */
401                                 FD_CLR( My_Connections[i].sock, &read_sockets );
402                         }
403                 }
404                 for( i = 0; i < Conn_MaxFD + 1; i++ )
405                 {
406                         /* Pipes von Resolver Sub-Prozessen aufnehmen */
407                         if( FD_ISSET( i, &Resolver_FDs ))
408                         {
409                                 FD_SET( i, &read_sockets );
410                         }
411                 }
412
413                 /* Timeout initialisieren */
414                 tv.tv_usec = 0;
415                 if( timeout ) tv.tv_sec = TIME_RES;
416                 else tv.tv_sec = 0;
417                 
418                 /* Auf Aktivitaet warten */
419                 i = select( Conn_MaxFD + 1, &read_sockets, &write_sockets, NULL, &tv );
420                 if( i == 0 )
421                 {
422                         /* keine Veraenderung an den Sockets */
423                         continue;
424                 }
425                 if( i == -1 )
426                 {
427                         /* Fehler (z.B. Interrupt) */
428                         if( errno != EINTR )
429                         {
430                                 Log( LOG_EMERG, "Conn_Handler(): select(): %s!", strerror( errno ));
431                                 Log( LOG_ALERT, "%s exiting due to fatal errors!", PACKAGE );
432                                 exit( 1 );
433                         }
434                         continue;
435                 }
436
437                 /* Koennen Daten geschrieben werden? */
438                 for( i = 0; i < Conn_MaxFD + 1; i++ )
439                 {
440                         if( ! FD_ISSET( i, &write_sockets )) continue;
441
442                         /* Es kann geschrieben werden ... */
443                         idx = Socket2Index( i );
444                         if( idx == NONE ) continue;
445                         
446                         if( ! Handle_Write( idx ))
447                         {
448                                 /* Fehler beim Schreiben! Diesen Socket nun
449                                  * auch aus dem Read-Set entfernen: */
450                                 FD_CLR( i, &read_sockets );
451                         }
452                 }
453
454                 /* Daten zum Lesen vorhanden? */
455                 for( i = 0; i < Conn_MaxFD + 1; i++ )
456                 {
457                         if( FD_ISSET( i, &read_sockets )) Handle_Read( i );
458                 }
459         }
460
461         if( NGIRCd_SignalQuit ) Log( LOG_NOTICE|LOG_snotice, "Server going down NOW!" );
462         else if( NGIRCd_SignalRestart ) Log( LOG_NOTICE|LOG_snotice, "Server restarting NOW!" );
463 } /* Conn_Handler */
464
465
466 #ifdef PROTOTYPES
467 GLOBAL BOOLEAN
468 Conn_WriteStr( CONN_ID Idx, CHAR *Format, ... )
469 #else
470 GLOBAL BOOLEAN
471 Conn_WriteStr( Idx, Format, va_alist )
472 CONN_ID Idx;
473 CHAR *Format;
474 va_dcl
475 #endif
476 {
477         /* String in Socket schreiben. CR+LF wird von dieser Funktion
478          * automatisch angehaengt. Im Fehlerfall wird dir Verbindung
479          * getrennt und FALSE geliefert. */
480
481         CHAR buffer[COMMAND_LEN];
482         BOOLEAN ok;
483         va_list ap;
484
485         assert( Idx > NONE );
486         assert( Format != NULL );
487
488 #ifdef PROTOTYPES
489         va_start( ap, Format );
490 #else
491         va_start( ap );
492 #endif
493         if( vsnprintf( buffer, COMMAND_LEN - 2, Format, ap ) == COMMAND_LEN - 2 )
494         {
495                 Log( LOG_CRIT, "Text too long to send (connection %d)!", Idx );
496                 Conn_Close( Idx, "Text too long to send!", NULL, FALSE );
497                 return FALSE;
498         }
499
500 #ifdef SNIFFER
501         if( NGIRCd_Sniffer ) Log( LOG_DEBUG, " -> connection %d: '%s'.", Idx, buffer );
502 #endif
503
504         strlcat( buffer, "\r\n", sizeof( buffer ));
505         ok = Conn_Write( Idx, buffer, strlen( buffer ));
506         My_Connections[Idx].msg_out++;
507
508         va_end( ap );
509         return ok;
510 } /* Conn_WriteStr */
511
512
513 GLOBAL BOOLEAN
514 Conn_Write( CONN_ID Idx, CHAR *Data, INT Len )
515 {
516         /* Daten in Socket schreiben. Bei "fatalen" Fehlern wird
517          * der Client disconnectiert und FALSE geliefert. */
518
519         assert( Idx > NONE );
520         assert( Data != NULL );
521         assert( Len > 0 );
522
523         /* Ist der entsprechende Socket ueberhaupt noch offen? In einem
524          * "Handler-Durchlauf" kann es passieren, dass dem nicht mehr so
525          * ist, wenn einer von mehreren Conn_Write()'s fehlgeschlagen ist.
526          * In diesem Fall wird hier einfach ein Fehler geliefert. */
527         if( My_Connections[Idx].sock <= NONE )
528         {
529                 Log( LOG_DEBUG, "Skipped write on closed socket (connection %d).", Idx );
530                 return FALSE;
531         }
532
533         /* Pruefen, ob im Schreibpuffer genuegend Platz ist. Ziel ist es,
534          * moeglichts viel im Puffer zu haben und _nicht_ gleich alles auf den
535          * Socket zu schreiben (u.a. wg. Komprimierung). */
536         if( WRITEBUFFER_LEN - My_Connections[Idx].wdatalen - Len <= 0 )
537         {
538                 /* Der Puffer ist dummerweise voll. Jetzt versuchen, den Puffer
539                  * zu schreiben, wenn das nicht klappt, haben wir ein Problem ... */
540                 if( ! Try_Write( Idx )) return FALSE;
541
542                 /* nun neu pruefen: */
543                 if( WRITEBUFFER_LEN - My_Connections[Idx].wdatalen - Len <= 0 )
544                 {
545                         Log( LOG_NOTICE, "Write buffer overflow (connection %d)!", Idx );
546                         Conn_Close( Idx, "Write buffer overflow!", NULL, FALSE );
547                         return FALSE;
548                 }
549         }
550
551 #ifdef USE_ZLIB
552         if( My_Connections[Idx].options & CONN_ZIP )
553         {
554                 /* Daten komprimieren und in Puffer kopieren */
555                 if( ! Zip_Buffer( Idx, Data, Len )) return FALSE;
556         }
557         else
558 #endif
559         {
560                 /* Daten in Puffer kopieren */
561                 memcpy( My_Connections[Idx].wbuf + My_Connections[Idx].wdatalen, Data, Len );
562                 My_Connections[Idx].wdatalen += Len;
563                 My_Connections[Idx].bytes_out += Len;
564         }
565
566         /* Adjust global write counter */
567         WCounter += Len;
568
569         return TRUE;
570 } /* Conn_Write */
571
572
573 GLOBAL VOID
574 Conn_Close( CONN_ID Idx, CHAR *LogMsg, CHAR *FwdMsg, BOOLEAN InformClient )
575 {
576         /* Close connection. Open pipes of asyncronous resolver
577          * sub-processes are closed down. */
578
579         CLIENT *c;
580         DOUBLE in_k, out_k;
581 #ifdef USE_ZLIB
582         DOUBLE in_z_k, out_z_k;
583         INT in_p, out_p;
584 #endif
585
586         assert( Idx > NONE );
587         assert( My_Connections[Idx].sock > NONE );
588
589         /* Is this link already shutting down? */
590         if( My_Connections[Idx].options & CONN_ISCLOSING )
591         {
592                 /* Conn_Close() has been called recursively for this link;
593                  * probabe reason: Try_Write() failed  -- see below. */
594                 return;
595         }
596
597         /* Mark link as "closing" */
598         My_Connections[Idx].options |= CONN_ISCLOSING;
599
600         /* Search client, if any */
601         c = Client_GetFromConn( Idx );
602
603         /* Should the client be informed? */
604         if( InformClient )
605         {
606 #ifndef STRICT_RFC
607                 /* Send statistics to client if registered as user: */
608                 if(( c != NULL ) && ( Client_Type( c ) == CLIENT_USER ))
609                 {
610                         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 );
611                 }
612 #endif
613
614                 /* Send ERROR to client (see RFC!) */
615                 if( FwdMsg ) Conn_WriteStr( Idx, "ERROR :%s", FwdMsg );
616                 else Conn_WriteStr( Idx, "ERROR :Closing connection." );
617                 if( My_Connections[Idx].sock == NONE ) return;
618         }
619
620         /* Try to write out the write buffer */
621         (VOID)Try_Write( Idx );
622
623         /* Shut down socket */
624         if( close( My_Connections[Idx].sock ) != 0 )
625         {
626                 /* Oops, we can't close the socket!? This is fatal! */
627                 Log( LOG_EMERG, "Error closing connection %d (socket %d) with %s:%d - %s!", Idx, My_Connections[Idx].sock, My_Connections[Idx].host, ntohs( My_Connections[Idx].addr.sin_port), strerror( errno ));
628                 Log( LOG_ALERT, "%s exiting due to fatal errors!", PACKAGE );
629                 exit( 1 );
630         }
631
632         /* Mark socket as invalid: */
633         FD_CLR( My_Connections[Idx].sock, &My_Sockets );
634         FD_CLR( My_Connections[Idx].sock, &My_Connects );
635         My_Connections[Idx].sock = NONE;
636
637         /* If there is still a client, unregister it now */
638         if( c ) Client_Destroy( c, LogMsg, FwdMsg, TRUE );
639
640         /* Calculate statistics and log information */
641         in_k = (DOUBLE)My_Connections[Idx].bytes_in / 1024;
642         out_k = (DOUBLE)My_Connections[Idx].bytes_out / 1024;
643 #ifdef USE_ZLIB
644         if( My_Connections[Idx].options & CONN_ZIP )
645         {
646                 in_z_k = (DOUBLE)My_Connections[Idx].zip.bytes_in / 1024;
647                 out_z_k = (DOUBLE)My_Connections[Idx].zip.bytes_out / 1024;
648                 in_p = (INT)(( in_k * 100 ) / in_z_k );
649                 out_p = (INT)(( out_k * 100 ) / out_z_k );
650                 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 );
651         }
652         else
653 #endif
654         {
655                 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 );
656         }
657
658         /* Is there a resolver sub-process running? */
659         if( My_Connections[Idx].res_stat )
660         {
661                 /* Free resolver structures */
662                 FD_CLR( My_Connections[Idx].res_stat->pipe[0], &Resolver_FDs );
663                 close( My_Connections[Idx].res_stat->pipe[0] );
664                 close( My_Connections[Idx].res_stat->pipe[1] );
665                 free( My_Connections[Idx].res_stat );
666         }
667
668         /* Servers: Modify time of next connect attempt? */
669         Conf_UnsetServer( Idx );
670
671 #ifdef USE_ZLIB
672         /* Clean up zlib, if link was compressed */
673         if( Conn_Options( Idx ) & CONN_ZIP )
674         {
675                 inflateEnd( &My_Connections[Idx].zip.in );
676                 deflateEnd( &My_Connections[Idx].zip.out );
677         }
678 #endif
679
680         /* Clean up connection structure (=free it) */
681         Init_Conn_Struct( Idx );
682 } /* Conn_Close */
683
684
685 LOCAL BOOLEAN
686 Try_Write( CONN_ID Idx )
687 {
688         /* Versuchen, Daten aus dem Schreib-Puffer in den Socket zu
689          * schreiben. TRUE wird geliefert, wenn entweder keine Daten
690          * zum Versenden vorhanden sind oder erfolgreich bearbeitet
691          * werden konnten. Im Fehlerfall wird FALSE geliefert und
692          * die Verbindung geschlossen. */
693
694         fd_set write_socket;
695         struct timeval tv;
696
697         assert( Idx > NONE );
698         assert( My_Connections[Idx].sock > NONE );
699
700         /* sind ueberhaupt Daten vorhanden? */
701 #ifdef USE_ZLIB
702         if(( ! My_Connections[Idx].wdatalen > 0 ) && ( ! My_Connections[Idx].zip.wdatalen )) return TRUE;
703 #else
704         if( ! My_Connections[Idx].wdatalen > 0 ) return TRUE;
705 #endif
706
707         /* Timeout initialisieren: 0 Sekunden, also nicht blockieren */
708         tv.tv_sec = 0; tv.tv_usec = 0;
709
710         FD_ZERO( &write_socket );
711         FD_SET( My_Connections[Idx].sock, &write_socket );
712         if( select( My_Connections[Idx].sock + 1, NULL, &write_socket, NULL, &tv ) == -1 )
713         {
714                 /* Fehler! */
715                 if( errno != EINTR )
716                 {
717                         Log( LOG_ALERT, "Try_Write(): select() failed: %s (con=%d, sock=%d)!", strerror( errno ), Idx, My_Connections[Idx].sock );
718                         Conn_Close( Idx, "Server error!", NULL, FALSE );
719                         return FALSE;
720                 }
721         }
722
723         if( FD_ISSET( My_Connections[Idx].sock, &write_socket )) return Handle_Write( Idx );
724         else return TRUE;
725 } /* Try_Write */
726
727
728 LOCAL VOID
729 Handle_Read( INT Sock )
730 {
731         /* Aktivitaet auf einem Socket verarbeiten:
732          *  - neue Clients annehmen,
733          *  - Daten von Clients verarbeiten,
734          *  - Resolver-Rueckmeldungen annehmen. */
735
736         CONN_ID idx;
737
738         assert( Sock > NONE );
739
740         if( FD_ISSET( Sock, &My_Listeners ))
741         {
742                 /* es ist einer unserer Listener-Sockets: es soll
743                  * also eine neue Verbindung aufgebaut werden. */
744
745                 New_Connection( Sock );
746         }
747         else if( FD_ISSET( Sock, &Resolver_FDs ))
748         {
749                 /* Rueckmeldung von einem Resolver Sub-Prozess */
750
751                 Read_Resolver_Result( Sock );
752         }
753         else
754         {
755                 /* Ein Client Socket: entweder ein User oder Server */
756
757                 idx = Socket2Index( Sock );
758                 if( idx > NONE ) Read_Request( idx );
759         }
760 } /* Handle_Read */
761
762
763 LOCAL BOOLEAN
764 Handle_Write( CONN_ID Idx )
765 {
766         /* Daten aus Schreibpuffer versenden bzw. Connection aufbauen */
767
768         INT len, res, err;
769         CLIENT *c;
770
771         assert( Idx > NONE );
772         assert( My_Connections[Idx].sock > NONE );
773
774         if( FD_ISSET( My_Connections[Idx].sock, &My_Connects ))
775         {
776                 /* es soll nichts geschrieben werden, sondern ein
777                  * connect() hat ein Ergebnis geliefert */
778
779                 FD_CLR( My_Connections[Idx].sock, &My_Connects );
780
781                 /* Ergebnis des connect() ermitteln */
782                 len = sizeof( err );
783                 res = getsockopt( My_Connections[Idx].sock, SOL_SOCKET, SO_ERROR, &err, &len );
784                 assert( len == sizeof( err ));
785
786                 /* Fehler aufgetreten? */
787                 if(( res != 0 ) || ( err != 0 ))
788                 {
789                         /* Fehler! */
790                         if( res != 0 ) Log( LOG_CRIT, "getsockopt (connection %d): %s!", Idx, strerror( errno ));
791                         else Log( LOG_CRIT, "Can't connect socket to \"%s:%d\" (connection %d): %s!", My_Connections[Idx].host, Conf_Server[Conf_GetServer( Idx )].port, Idx, strerror( err ));
792
793                         /* Clean up socket, connection and client structures */
794                         FD_CLR( My_Connections[Idx].sock, &My_Sockets );
795                         c = Client_GetFromConn( Idx );
796                         if( c ) Client_DestroyNow( c );
797                         close( My_Connections[Idx].sock );
798                         Init_Conn_Struct( Idx );
799
800                         /* Bei Server-Verbindungen lasttry-Zeitpunkt auf "jetzt" setzen */
801                         Conf_Server[Conf_GetServer( Idx )].lasttry = time( NULL );
802                         Conf_UnsetServer( Idx );
803
804                         return FALSE;
805                 }
806                 Log( LOG_DEBUG, "Connection %d with \"%s:%d\" established, now sendig PASS and SERVER ...", Idx, My_Connections[Idx].host, Conf_Server[Conf_GetServer( Idx )].port );
807
808                 /* PASS und SERVER verschicken */
809                 Conn_WriteStr( Idx, "PASS %s %s", Conf_Server[Conf_GetServer( Idx )].pwd_out, NGIRCd_ProtoID );
810                 return Conn_WriteStr( Idx, "SERVER %s :%s", Conf_ServerName, Conf_ServerInfo );
811         }
812
813 #ifdef USE_ZLIB
814         /* Schreibpuffer leer, aber noch Daten im Kompressionsbuffer?
815          * Dann muss dieser nun geflushed werden! */
816         if( My_Connections[Idx].wdatalen == 0 ) Zip_Flush( Idx );
817 #endif
818
819         assert( My_Connections[Idx].wdatalen > 0 );
820
821         /* Daten schreiben */
822         len = send( My_Connections[Idx].sock, My_Connections[Idx].wbuf, My_Connections[Idx].wdatalen, 0 );
823         if( len < 0 )
824         {
825                 /* Operation haette Socket "nur" blockiert ... */
826                 if( errno == EAGAIN ) return TRUE;
827
828                 /* Oops, ein Fehler! */
829                 Log( LOG_ERR, "Write error on connection %d (socket %d): %s!", Idx, My_Connections[Idx].sock, strerror( errno ));
830                 Conn_Close( Idx, "Write error!", NULL, FALSE );
831                 return FALSE;
832         }
833
834         /* Puffer anpassen */
835         My_Connections[Idx].wdatalen -= len;
836         memmove( My_Connections[Idx].wbuf, My_Connections[Idx].wbuf + len, My_Connections[Idx].wdatalen );
837
838         return TRUE;
839 } /* Handle_Write */
840
841
842 LOCAL VOID
843 New_Connection( INT Sock )
844 {
845         /* Neue Client-Verbindung von Listen-Socket annehmen und
846          * CLIENT-Struktur anlegen. */
847
848 #ifdef USE_TCPWRAP
849         struct request_info req;
850 #endif
851         struct sockaddr_in new_addr;
852         INT new_sock, new_sock_len;
853         RES_STAT *s;
854         CONN_ID idx;
855         CLIENT *c;
856         POINTER *ptr;
857         LONG new_size;
858
859         assert( Sock > NONE );
860
861         /* Connection auf Listen-Socket annehmen */
862         new_sock_len = sizeof( new_addr );
863         new_sock = accept( Sock, (struct sockaddr *)&new_addr, (socklen_t *)&new_sock_len );
864         if( new_sock < 0 )
865         {
866                 Log( LOG_CRIT, "Can't accept connection: %s!", strerror( errno ));
867                 return;
868         }
869         
870 #ifdef USE_TCPWRAP
871         /* Validate socket using TCP Wrappers */
872         request_init( &req, RQ_DAEMON, PACKAGE, RQ_FILE, new_sock, RQ_CLIENT_SIN, &new_addr, NULL );
873         if( ! hosts_access( &req ))
874         {
875                 /* Access denied! */
876                 Log( deny_severity, "Refused connection from %s (by TCP Wrappers)!", inet_ntoa( new_addr.sin_addr ));
877                 close( new_sock );
878                 return;
879         }
880 #endif
881
882         /* Socket initialisieren */
883         Init_Socket( new_sock );
884
885         /* Freie Connection-Struktur suchen */
886         for( idx = 0; idx < Pool_Size; idx++ ) if( My_Connections[idx].sock == NONE ) break;
887         if( idx >= Pool_Size )
888         {
889                 new_size = Pool_Size + CONNECTION_POOL;
890                 
891                 /* Im bisherigen Pool wurde keine freie Connection-Struktur mehr gefunden.
892                  * Wenn erlaubt und moeglich muss nun der Pool vergroessert werden: */
893                 
894                 if( Conf_MaxConnections > 0 )
895                 {
896                         /* Es ist ein Limit konfiguriert */
897                         if( Pool_Size >= Conf_MaxConnections )
898                         {
899                                 /* Mehr Verbindungen duerfen wir leider nicht mehr annehmen ... */
900                                 Log( LOG_ALERT, "Can't accept connection: limit (%d) reached!", Pool_Size );
901                                 close( new_sock );
902                                 return;
903                         }
904                         if( new_size > Conf_MaxConnections ) new_size = Conf_MaxConnections;
905                 }
906                 if( new_size < Pool_Size )
907                 {
908                         Log( LOG_ALERT, "Can't accespt connection: limit (%d) reached -- overflow!", Pool_Size );
909                         close( new_sock );
910                         return;
911                 }
912                 
913                 /* zunaechst realloc() versuchen; wenn das scheitert, malloc() versuchen
914                  * und Daten ggf. "haendisch" umkopieren. (Haesslich! Eine wirklich
915                  * dynamische Verwaltung waere wohl _deutlich_ besser ...) */
916                 ptr = realloc( My_Connections, sizeof( CONNECTION ) * new_size );
917                 if( ! ptr )
918                 {
919                         /* realloc() ist fehlgeschlagen. Nun malloc() probieren: */
920                         ptr = malloc( sizeof( CONNECTION ) * new_size );
921                         if( ! ptr )
922                         {
923                                 /* Offenbar steht kein weiterer Sepeicher zur Verfuegung :-( */
924                                 Log( LOG_EMERG, "Can't allocate memory! [New_Connection]" );
925                                 close( new_sock );
926                                 return;
927                         }
928                         
929                         /* Struktur umkopieren ... */
930                         memcpy( ptr, My_Connections, sizeof( CONNECTION ) * Pool_Size );
931                         
932                         Log( LOG_DEBUG, "Allocated new connection pool for %ld items (%ld bytes). [malloc()/memcpy()]", new_size, sizeof( CONNECTION ) * new_size );
933                 }
934                 else Log( LOG_DEBUG, "Allocated new connection pool for %ld items (%ld bytes). [realloc()]", new_size, sizeof( CONNECTION ) * new_size );
935                 
936                 /* Adjust pointer to new block */
937                 My_Connections = ptr;
938                 
939                 /* Initialize new items */
940                 for( idx = Pool_Size; idx < new_size; idx++ ) Init_Conn_Struct( idx );
941                 idx = Pool_Size;
942                 
943                 /* Adjust new pool size */
944                 Pool_Size = new_size;
945         }
946
947         /* Client-Struktur initialisieren */
948         c = Client_NewLocal( idx, inet_ntoa( new_addr.sin_addr ), CLIENT_UNKNOWN, FALSE );
949         if( ! c )
950         {
951                 Log( LOG_ALERT, "Can't accept connection: can't create client structure!" );
952                 close( new_sock );
953                 return;
954         }
955
956         /* Verbindung registrieren */
957         Init_Conn_Struct( idx );
958         My_Connections[idx].sock = new_sock;
959         My_Connections[idx].addr = new_addr;
960
961         /* Neuen Socket registrieren */
962         FD_SET( new_sock, &My_Sockets );
963         if( new_sock > Conn_MaxFD ) Conn_MaxFD = new_sock;
964
965         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 );
966
967         /* Hostnamen ermitteln */
968         strlcpy( My_Connections[idx].host, inet_ntoa( new_addr.sin_addr ), sizeof( My_Connections[idx].host ));
969         Client_SetHostname( c, My_Connections[idx].host );
970         s = Resolve_Addr( &new_addr );
971         if( s )
972         {
973                 /* Sub-Prozess wurde asyncron gestartet */
974                 My_Connections[idx].res_stat = s;
975         }
976         
977         /* Penalty-Zeit setzen */
978         Conn_SetPenalty( idx, 4 );
979 } /* New_Connection */
980
981
982 LOCAL CONN_ID
983 Socket2Index( INT Sock )
984 {
985         /* zum Socket passende Connection suchen */
986
987         CONN_ID idx;
988
989         assert( Sock > NONE );
990
991         for( idx = 0; idx < Pool_Size; idx++ ) if( My_Connections[idx].sock == Sock ) break;
992
993         if( idx >= Pool_Size )
994         {
995                 /* die Connection wurde vermutlich (wegen eines
996                  * Fehlers) bereits wieder abgebaut ... */
997                 Log( LOG_DEBUG, "Socket2Index: can't get connection for socket %d!", Sock );
998                 return NONE;
999         }
1000         else return idx;
1001 } /* Socket2Index */
1002
1003
1004 LOCAL VOID
1005 Read_Request( CONN_ID Idx )
1006 {
1007         /* Daten von Socket einlesen und entsprechend behandeln.
1008          * Tritt ein Fehler auf, so wird der Socket geschlossen. */
1009
1010         INT len, bsize;
1011 #ifdef USE_ZLIB
1012         CLIENT *c;
1013 #endif
1014
1015         assert( Idx > NONE );
1016         assert( My_Connections[Idx].sock > NONE );
1017
1018         /* wenn noch nicht registriert: maximal mit ZREADBUFFER_LEN arbeiten,
1019          * ansonsten koennen Daten ggf. nicht umkopiert werden. */
1020         bsize = READBUFFER_LEN;
1021 #ifdef USE_ZLIB
1022         c = Client_GetFromConn( Idx );
1023         if(( Client_Type( c ) != CLIENT_USER ) && ( Client_Type( c ) != CLIENT_SERVER ) && ( Client_Type( c ) != CLIENT_SERVICE ) && ( bsize > ZREADBUFFER_LEN )) bsize = ZREADBUFFER_LEN;
1024 #endif
1025
1026 #ifdef USE_ZLIB
1027         if(( bsize - My_Connections[Idx].rdatalen - 1 < 1 ) || ( ZREADBUFFER_LEN - My_Connections[Idx].zip.rdatalen < 1 ))
1028 #else
1029         if( bsize - My_Connections[Idx].rdatalen - 1 < 1 )
1030 #endif
1031         {
1032                 /* Der Lesepuffer ist voll */
1033                 Log( LOG_ERR, "Read buffer overflow (connection %d): %d bytes!", Idx, My_Connections[Idx].rdatalen );
1034                 Conn_Close( Idx, "Read buffer overflow!", NULL, FALSE );
1035                 return;
1036         }
1037
1038 #ifdef USE_ZLIB
1039         if( My_Connections[Idx].options & CONN_ZIP )
1040         {
1041                 len = recv( My_Connections[Idx].sock, My_Connections[Idx].zip.rbuf + My_Connections[Idx].zip.rdatalen, ( ZREADBUFFER_LEN - My_Connections[Idx].zip.rdatalen ), 0 );
1042                 if( len > 0 ) My_Connections[Idx].zip.rdatalen += len;
1043         }
1044         else
1045 #endif
1046         {
1047                 len = recv( My_Connections[Idx].sock, My_Connections[Idx].rbuf + My_Connections[Idx].rdatalen, bsize - My_Connections[Idx].rdatalen - 1, 0 );
1048                 if( len > 0 ) My_Connections[Idx].rdatalen += len;
1049         }
1050
1051         if( len == 0 )
1052         {
1053                 /* Socket wurde geschlossen */
1054                 Log( LOG_INFO, "%s:%d (%s) is closing the connection ...", My_Connections[Idx].host, ntohs( My_Connections[Idx].addr.sin_port), inet_ntoa( My_Connections[Idx].addr.sin_addr ));
1055                 Conn_Close( Idx, "Socket closed!", "Client closed connection", FALSE );
1056                 return;
1057         }
1058
1059         if( len < 0 )
1060         {
1061                 /* Operation haette Socket "nur" blockiert ... */
1062                 if( errno == EAGAIN ) return;
1063
1064                 /* Fehler beim Lesen */
1065                 Log( LOG_ERR, "Read error on connection %d (socket %d): %s!", Idx, My_Connections[Idx].sock, strerror( errno ));
1066                 Conn_Close( Idx, "Read error!", "Client closed connection", FALSE );
1067                 return;
1068         }
1069
1070         /* Connection-Statistik aktualisieren */
1071         My_Connections[Idx].bytes_in += len;
1072
1073         /* Timestamp aktualisieren */
1074         My_Connections[Idx].lastdata = time( NULL );
1075
1076         Handle_Buffer( Idx );
1077 } /* Read_Request */
1078
1079
1080 LOCAL BOOLEAN
1081 Handle_Buffer( CONN_ID Idx )
1082 {
1083         /* Daten im Lese-Puffer einer Verbindung verarbeiten.
1084          * Wurde ein Request verarbeitet, so wird TRUE geliefert,
1085          * ansonsten FALSE (auch bei Fehlern). */
1086
1087 #ifndef STRICT_RFC
1088         CHAR *ptr1, *ptr2;
1089 #endif
1090         CHAR *ptr;
1091         INT len, delta;
1092         BOOLEAN action, result;
1093 #ifdef USE_ZLIB
1094         BOOLEAN old_z;
1095 #endif
1096
1097         result = FALSE;
1098         do
1099         {
1100 #ifdef USE_ZLIB
1101                 /* ggf. noch unkomprimiete Daten weiter entpacken */
1102                 if( My_Connections[Idx].options & CONN_ZIP )
1103                 {
1104                         if( ! Unzip_Buffer( Idx )) return FALSE;
1105                 }
1106 #endif
1107         
1108                 if( My_Connections[Idx].rdatalen < 1 ) break;
1109
1110                 /* Eine komplette Anfrage muss mit CR+LF enden, vgl.
1111                  * RFC 2812. Haben wir eine? */
1112                 My_Connections[Idx].rbuf[My_Connections[Idx].rdatalen] = '\0';
1113                 ptr = strstr( My_Connections[Idx].rbuf, "\r\n" );
1114         
1115                 if( ptr ) delta = 2;
1116 #ifndef STRICT_RFC
1117                 else
1118                 {
1119                         /* Nicht RFC-konforme Anfrage mit nur CR oder LF? Leider
1120                          * machen soetwas viele Clients, u.a. "mIRC" :-( */
1121                         ptr1 = strchr( My_Connections[Idx].rbuf, '\r' );
1122                         ptr2 = strchr( My_Connections[Idx].rbuf, '\n' );
1123                         delta = 1;
1124                         if( ptr1 && ptr2 ) ptr = ptr1 > ptr2 ? ptr2 : ptr1;
1125                         else if( ptr1 ) ptr = ptr1;
1126                         else if( ptr2 ) ptr = ptr2;
1127                 }
1128 #endif
1129         
1130                 action = FALSE;
1131                 if( ptr )
1132                 {
1133                         /* Ende der Anfrage wurde gefunden */
1134                         *ptr = '\0';
1135                         len = ( ptr - My_Connections[Idx].rbuf ) + delta;
1136                         if( len > ( COMMAND_LEN - 1 ))
1137                         {
1138                                 /* Eine Anfrage darf(!) nicht laenger als 512 Zeichen
1139                                  * (incl. CR+LF!) werden; vgl. RFC 2812. Wenn soetwas
1140                                  * empfangen wird, wird der Client disconnectiert. */
1141                                 Log( LOG_ERR, "Request too long (connection %d): %d bytes (max. %d expected)!", Idx, My_Connections[Idx].rdatalen, COMMAND_LEN - 1 );
1142                                 Conn_Close( Idx, NULL, "Request too long", TRUE );
1143                                 return FALSE;
1144                         }
1145
1146 #ifdef USE_ZLIB
1147                         /* merken, ob Stream bereits komprimiert wird */
1148                         old_z = My_Connections[Idx].options & CONN_ZIP;
1149 #endif
1150
1151                         if( len > delta )
1152                         {
1153                                 /* Es wurde ein Request gelesen */
1154                                 My_Connections[Idx].msg_in++;
1155                                 if( ! Parse_Request( Idx, My_Connections[Idx].rbuf )) return FALSE;
1156                                 else action = TRUE;
1157                         }
1158
1159                         /* Puffer anpassen */
1160                         My_Connections[Idx].rdatalen -= len;
1161                         memmove( My_Connections[Idx].rbuf, My_Connections[Idx].rbuf + len, My_Connections[Idx].rdatalen );
1162
1163 #ifdef USE_ZLIB
1164                         if(( ! old_z ) && ( My_Connections[Idx].options & CONN_ZIP ) && ( My_Connections[Idx].rdatalen > 0 ))
1165                         {
1166                                 /* Mit dem letzten Befehl wurde Socket-Kompression aktiviert.
1167                                  * Evtl. schon vom Socket gelesene Daten in den Unzip-Puffer
1168                                  * umkopieren, damit diese nun zunaechst entkomprimiert werden */
1169                                 {
1170                                         if( My_Connections[Idx].rdatalen > ZREADBUFFER_LEN )
1171                                         {
1172                                                 /* Hupsa! Soviel Platz haben wir aber gar nicht! */
1173                                                 Log( LOG_ALERT, "Can't move read buffer: No space left in unzip buffer (need %d bytes)!", My_Connections[Idx].rdatalen );
1174                                                 return FALSE;
1175                                         }
1176                                         memcpy( My_Connections[Idx].zip.rbuf, My_Connections[Idx].rbuf, My_Connections[Idx].rdatalen );
1177                                         My_Connections[Idx].zip.rdatalen = My_Connections[Idx].rdatalen;
1178                                         My_Connections[Idx].rdatalen = 0;
1179                                         Log( LOG_DEBUG, "Moved already received data (%d bytes) to uncompression buffer.", My_Connections[Idx].zip.rdatalen );
1180                                 }
1181                         }
1182 #endif
1183                 }
1184                 
1185                 if( action ) result = TRUE;
1186         } while( action );
1187         
1188         return result;
1189 } /* Handle_Buffer */
1190
1191
1192 LOCAL VOID
1193 Check_Connections( VOID )
1194 {
1195         /* Pruefen, ob Verbindungen noch "alive" sind. Ist dies
1196          * nicht der Fall, zunaechst PING-PONG spielen und, wenn
1197          * auch das nicht "hilft", Client disconnectieren. */
1198
1199         CLIENT *c;
1200         CONN_ID i;
1201
1202         for( i = 0; i < Pool_Size; i++ )
1203         {
1204                 if( My_Connections[i].sock == NONE ) continue;
1205
1206                 c = Client_GetFromConn( i );
1207                 if( c && (( Client_Type( c ) == CLIENT_USER ) || ( Client_Type( c ) == CLIENT_SERVER ) || ( Client_Type( c ) == CLIENT_SERVICE )))
1208                 {
1209                         /* verbundener User, Server oder Service */
1210                         if( My_Connections[i].lastping > My_Connections[i].lastdata )
1211                         {
1212                                 /* es wurde bereits ein PING gesendet */
1213                                 if( My_Connections[i].lastping < time( NULL ) - Conf_PongTimeout )
1214                                 {
1215                                         /* Timeout */
1216                                         Log( LOG_DEBUG, "Connection %d: Ping timeout: %d seconds.", i, Conf_PongTimeout );
1217                                         Conn_Close( i, NULL, "Ping timeout", TRUE );
1218                                 }
1219                         }
1220                         else if( My_Connections[i].lastdata < time( NULL ) - Conf_PingTimeout )
1221                         {
1222                                 /* es muss ein PING gesendet werden */
1223                                 Log( LOG_DEBUG, "Connection %d: sending PING ...", i );
1224                                 My_Connections[i].lastping = time( NULL );
1225                                 Conn_WriteStr( i, "PING :%s", Client_ID( Client_ThisServer( )));
1226                         }
1227                 }
1228                 else
1229                 {
1230                         /* noch nicht vollstaendig aufgebaute Verbindung */
1231                         if( My_Connections[i].lastdata < time( NULL ) - Conf_PingTimeout )
1232                         {
1233                                 /* Timeout */
1234                                 Log( LOG_DEBUG, "Connection %d timed out ...", i );
1235                                 Conn_Close( i, NULL, "Timeout", FALSE );
1236                         }
1237                 }
1238         }
1239 } /* Check_Connections */
1240
1241
1242 LOCAL VOID
1243 Check_Servers( VOID )
1244 {
1245         /* Check if we can establish further server links */
1246
1247         RES_STAT *s;
1248         CONN_ID idx;
1249         INT i, n;
1250
1251         /* Serach all connections, are there results from the resolver? */
1252         for( idx = 0; idx < Pool_Size; idx++ )
1253         {
1254                 if( My_Connections[idx].sock != SERVER_WAIT ) continue;
1255
1256                 /* IP resolved? */
1257                 if( My_Connections[idx].res_stat == NULL ) New_Server( Conf_GetServer( idx ), idx );
1258         }
1259
1260         /* Check all configured servers */
1261         for( i = 0; i < MAX_SERVERS; i++ )
1262         {
1263                 /* Valid outgoing server which isn't already connected or disabled? */
1264                 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;
1265
1266                 /* Is there already a connection in this group? */
1267                 if( Conf_Server[i].group > NONE )
1268                 {
1269                         for( n = 0; n < MAX_SERVERS; n++ )
1270                         {
1271                                 if( n == i ) continue;
1272                                 if(( Conf_Server[n].conn_id > NONE ) && ( Conf_Server[n].group == Conf_Server[i].group )) break;
1273                         }
1274                         if( n < MAX_SERVERS ) continue;
1275                 }
1276
1277                 /* Check last connect attempt? */
1278                 if( Conf_Server[i].lasttry > time( NULL ) - Conf_ConnectRetry ) continue;
1279
1280                 /* Okay, try to connect now */
1281                 Conf_Server[i].lasttry = time( NULL );
1282
1283                 /* Search free connection structure */
1284                 for( idx = 0; idx < Pool_Size; idx++ ) if( My_Connections[idx].sock == NONE ) break;
1285                 if( idx >= Pool_Size )
1286                 {
1287                         Log( LOG_ALERT, "Can't establist server connection: connection limit reached (%d)!", Pool_Size );
1288                         return;
1289                 }
1290                 Log( LOG_DEBUG, "Preparing connection %d for \"%s\" ...", idx, Conf_Server[i].host );
1291
1292                 /* Verbindungs-Struktur initialisieren */
1293                 Init_Conn_Struct( idx );
1294                 My_Connections[idx].sock = SERVER_WAIT;
1295                 Conf_Server[i].conn_id = idx;
1296
1297                 /* Resolve Hostname. If this fails, try to use it as an IP address */
1298                 strlcpy( Conf_Server[i].ip, Conf_Server[i].host, sizeof( Conf_Server[i].ip ));
1299                 strlcpy( My_Connections[idx].host, Conf_Server[i].host, sizeof( My_Connections[idx].host ));
1300                 s = Resolve_Name( Conf_Server[i].host );
1301                 if( s )
1302                 {
1303                         /* Sub-Prozess wurde asyncron gestartet */
1304                         My_Connections[idx].res_stat = s;
1305                 }
1306         }
1307 } /* Check_Servers */
1308
1309
1310 LOCAL VOID
1311 New_Server( INT Server, CONN_ID Idx )
1312 {
1313         /* Neue Server-Verbindung aufbauen */
1314
1315         struct sockaddr_in new_addr;
1316         struct in_addr inaddr;
1317         INT res, new_sock;
1318         CLIENT *c;
1319
1320         assert( Server > NONE );
1321         assert( Idx > NONE );
1322
1323         /* Wurde eine gueltige IP-Adresse gefunden? */
1324         if( ! Conf_Server[Server].ip[0] )
1325         {
1326                 /* Nein. Verbindung wieder freigeben: */
1327                 Init_Conn_Struct( Idx );
1328                 Log( LOG_ERR, "Can't connect to \"%s\" (connection %d): ip address unknown!", Conf_Server[Server].host, Idx );
1329                 return;
1330         }
1331
1332         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 );
1333
1334 #ifdef HAVE_INET_ATON
1335         if( inet_aton( Conf_Server[Server].ip, &inaddr ) == 0 )
1336 #else
1337         memset( &inaddr, 0, sizeof( inaddr ));
1338         inaddr.s_addr = inet_addr( Conf_Server[Server].ip );
1339         if( inaddr.s_addr == (unsigned)-1 )
1340 #endif
1341         {
1342                 /* Konnte Adresse nicht konvertieren */
1343                 Init_Conn_Struct( Idx );
1344                 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 );
1345                 return;
1346         }
1347
1348         memset( &new_addr, 0, sizeof( new_addr ));
1349         new_addr.sin_family = AF_INET;
1350         new_addr.sin_addr = inaddr;
1351         new_addr.sin_port = htons( Conf_Server[Server].port );
1352
1353         new_sock = socket( PF_INET, SOCK_STREAM, 0 );
1354         if ( new_sock < 0 )
1355         {
1356                 Init_Conn_Struct( Idx );
1357                 Log( LOG_CRIT, "Can't create socket: %s!", strerror( errno ));
1358                 return;
1359         }
1360
1361         if( ! Init_Socket( new_sock )) return;
1362
1363         res = connect( new_sock, (struct sockaddr *)&new_addr, sizeof( new_addr ));
1364         if(( res != 0 ) && ( errno != EINPROGRESS ))
1365         {
1366                 Log( LOG_CRIT, "Can't connect socket: %s!", strerror( errno ));
1367                 close( new_sock );
1368                 Init_Conn_Struct( Idx );
1369                 return;
1370         }
1371
1372         /* Client-Struktur initialisieren */
1373         c = Client_NewLocal( Idx, inet_ntoa( new_addr.sin_addr ), CLIENT_UNKNOWNSERVER, FALSE );
1374         if( ! c )
1375         {
1376                 close( new_sock );
1377                 Init_Conn_Struct( Idx );
1378                 Log( LOG_ALERT, "Can't establish connection: can't create client structure!" );
1379                 return;
1380         }
1381         Client_SetIntroducer( c, c );
1382         Client_SetToken( c, TOKEN_OUTBOUND );
1383
1384         /* Verbindung registrieren */
1385         My_Connections[Idx].sock = new_sock;
1386         My_Connections[Idx].addr = new_addr;
1387         strlcpy( My_Connections[Idx].host, Conf_Server[Server].host, sizeof( My_Connections[Idx].host ));
1388
1389         /* Neuen Socket registrieren */
1390         FD_SET( new_sock, &My_Sockets );
1391         FD_SET( new_sock, &My_Connects );
1392         if( new_sock > Conn_MaxFD ) Conn_MaxFD = new_sock;
1393         
1394         Log( LOG_DEBUG, "Registered new connection %d on socket %d.", Idx, My_Connections[Idx].sock );
1395 } /* New_Server */
1396
1397
1398 LOCAL VOID
1399 Init_Conn_Struct( CONN_ID Idx )
1400 {
1401         /* Connection-Struktur initialisieren */
1402
1403         My_Connections[Idx].sock = NONE;
1404         My_Connections[Idx].res_stat = NULL;
1405         My_Connections[Idx].host[0] = '\0';
1406         My_Connections[Idx].rbuf[0] = '\0';
1407         My_Connections[Idx].rdatalen = 0;
1408         My_Connections[Idx].wbuf[0] = '\0';
1409         My_Connections[Idx].wdatalen = 0;
1410         My_Connections[Idx].starttime = time( NULL );
1411         My_Connections[Idx].lastdata = time( NULL );
1412         My_Connections[Idx].lastping = 0;
1413         My_Connections[Idx].lastprivmsg = time( NULL );
1414         My_Connections[Idx].delaytime = 0;
1415         My_Connections[Idx].bytes_in = 0;
1416         My_Connections[Idx].bytes_out = 0;
1417         My_Connections[Idx].msg_in = 0;
1418         My_Connections[Idx].msg_out = 0;
1419         My_Connections[Idx].flag = 0;
1420         My_Connections[Idx].options = 0;
1421
1422 #ifdef USE_ZLIB
1423         My_Connections[Idx].zip.rbuf[0] = '\0';
1424         My_Connections[Idx].zip.rdatalen = 0;
1425         My_Connections[Idx].zip.wbuf[0] = '\0';
1426         My_Connections[Idx].zip.wdatalen = 0;
1427         My_Connections[Idx].zip.bytes_in = 0;
1428         My_Connections[Idx].zip.bytes_out = 0;
1429 #endif
1430 } /* Init_Conn_Struct */
1431
1432
1433 LOCAL BOOLEAN
1434 Init_Socket( INT Sock )
1435 {
1436         /* Socket-Optionen setzen */
1437
1438         INT on = 1;
1439
1440 #ifdef O_NONBLOCK       /* A/UX kennt das nicht? */
1441         if( fcntl( Sock, F_SETFL, O_NONBLOCK ) != 0 )
1442         {
1443                 Log( LOG_CRIT, "Can't enable non-blocking mode: %s!", strerror( errno ));
1444                 close( Sock );
1445                 return FALSE;
1446         }
1447 #endif
1448         if( setsockopt( Sock, SOL_SOCKET, SO_REUSEADDR, &on, (socklen_t)sizeof( on )) != 0)
1449         {
1450                 Log( LOG_ERR, "Can't set socket options: %s!", strerror( errno ));
1451                 /* dieser Fehler kann ignoriert werden. */
1452         }
1453
1454         return TRUE;
1455 } /* Init_Socket */
1456
1457
1458 LOCAL VOID
1459 Read_Resolver_Result( INT r_fd )
1460 {
1461         /* Ergebnis von Resolver Sub-Prozess aus Pipe lesen
1462          * und entsprechende Connection aktualisieren */
1463
1464         CHAR result[HOST_LEN];
1465         CLIENT *c;
1466         INT len, i, n;
1467
1468         FD_CLR( r_fd, &Resolver_FDs );
1469
1470         /* Anfrage vom Parent lesen */
1471         len = read( r_fd, result, HOST_LEN - 1 );
1472         if( len < 0 )
1473         {
1474                 /* Fehler beim Lesen aus der Pipe */
1475                 close( r_fd );
1476                 Log( LOG_CRIT, "Resolver: Can't read result: %s!", strerror( errno ));
1477                 return;
1478         }
1479         result[len] = '\0';
1480
1481         /* zugehoerige Connection suchen */
1482         for( i = 0; i < Pool_Size; i++ )
1483         {
1484                 if(( My_Connections[i].sock != NONE ) && ( My_Connections[i].res_stat ) && ( My_Connections[i].res_stat->pipe[0] == r_fd )) break;
1485         }
1486         if( i >= Pool_Size )
1487         {
1488                 /* Opsa! Keine passende Connection gefunden!? Vermutlich
1489                  * wurde sie schon wieder geschlossen. */
1490                 close( r_fd );
1491                 Log( LOG_DEBUG, "Resolver: Got result for unknown connection!?" );
1492                 return;
1493         }
1494
1495         Log( LOG_DEBUG, "Resolver: %s is \"%s\".", My_Connections[i].host, result );
1496         
1497         /* Aufraeumen */
1498         close( My_Connections[i].res_stat->pipe[0] );
1499         close( My_Connections[i].res_stat->pipe[1] );
1500         free( My_Connections[i].res_stat );
1501         My_Connections[i].res_stat = NULL;
1502
1503         if( My_Connections[i].sock > NONE )
1504         {
1505                 /* Eingehende Verbindung: Hostnamen setzen */
1506                 c = Client_GetFromConn( i );
1507                 assert( c != NULL );
1508                 strlcpy( My_Connections[i].host, result, sizeof( My_Connections[i].host ));
1509                 Client_SetHostname( c, result );
1510         }
1511         else
1512         {
1513                 /* Ausgehende Verbindung (=Server): IP setzen */
1514                 n = Conf_GetServer( i );
1515                 if( n > NONE ) strlcpy( Conf_Server[n].ip, result, sizeof( Conf_Server[n].ip ));
1516                 else Log( LOG_ERR, "Got resolver result for non-configured server!?" );
1517         }
1518
1519         /* Penalty-Zeit zurueck setzen */
1520         Conn_ResetPenalty( i );
1521 } /* Read_Resolver_Result */
1522
1523
1524 /* -eof- */