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