]> arthur.barton.de Git - ngircd-alex.git/blob - src/ngircd/conn.c
38a7dd529ef8dcc8dca69d8cad55f78e09e5d475
[ngircd-alex.git] / src / ngircd / conn.c
1 /*
2  * ngIRCd -- The Next Generation IRC Daemon
3  * Copyright (c)2001,2002 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 #include "portab.h"
16
17 static char UNUSED id[] = "$Id: conn.c,v 1.104 2002/12/12 12:24:18 alex Exp $";
18
19 #include "imp.h"
20 #include <assert.h>
21 #include <stdarg.h>
22 #include <stdio.h>
23 #include <stdlib.h>
24 #include <unistd.h>
25 #include <errno.h>
26 #include <fcntl.h>
27 #include <string.h>
28 #include <sys/socket.h>
29 #include <sys/time.h>
30 #include <sys/types.h>
31 #include <time.h>
32 #include <netinet/in.h>
33
34 #ifdef HAVE_ARPA_INET_H
35 #include <arpa/inet.h>
36 #else
37 #define PF_INET AF_INET
38 #endif
39
40 #ifdef HAVE_STDINT_H
41 #include <stdint.h>                     /* u.a. fuer Mac OS X */
42 #endif
43
44 #ifdef USE_ZLIB
45 #include <zlib.h>
46 #endif
47
48 #include "exp.h"
49 #include "conn.h"
50
51 #include "imp.h"
52 #include "ngircd.h"
53 #include "client.h"
54 #include "resolve.h"
55 #include "conf.h"
56 #include "log.h"
57 #include "parse.h"
58 #include "tool.h"
59
60 #include "exp.h"
61
62
63 #define SERVER_WAIT (NONE - 1)
64
65
66 #ifdef USE_ZLIB
67 typedef struct _ZipData
68 {
69         z_stream in;                    /* "Handle" fuer Input-Stream */
70         z_stream out;                   /* "Handle" fuer Output-Stream */
71         CHAR rbuf[READBUFFER_LEN];      /* Lesepuffer */
72         INT rdatalen;                   /* Laenge der Daten im Lesepuffer (komprimiert) */
73         CHAR wbuf[WRITEBUFFER_LEN];     /* Schreibpuffer */
74         INT wdatalen;                   /* Laenge der Daten im Schreibpuffer (unkomprimiert) */
75         LONG bytes_in, bytes_out;       /* Counter fuer Statistik (unkomprimiert!) */
76 } ZIPDATA;
77 #endif
78
79
80 typedef struct _Connection
81 {
82         INT sock;                       /* Socket Handle */
83         struct sockaddr_in addr;        /* Adresse des Client */
84         RES_STAT *res_stat;             /* "Resolver-Status", s.o. */
85         CHAR host[HOST_LEN];            /* Hostname */
86         CHAR rbuf[READBUFFER_LEN];      /* Lesepuffer */
87         INT rdatalen;                   /* Laenge der Daten im Lesepuffer */
88         CHAR wbuf[WRITEBUFFER_LEN];     /* Schreibpuffer */
89         INT wdatalen;                   /* Laenge der Daten im Schreibpuffer */
90         INT our_server;                 /* wenn von uns zu connectender Server: ID */
91         time_t starttime;               /* Startzeit des Links */
92         time_t lastdata;                /* Letzte Aktivitaet */
93         time_t lastping;                /* Letzter PING */
94         time_t lastprivmsg;             /* Letzte PRIVMSG */
95         time_t delaytime;               /* Nicht beachten bis ("penalty") */
96         LONG bytes_in, bytes_out;       /* Empfangene uns gesendete Bytes */
97         LONG msg_in, msg_out;           /* Empfangene uns gesendete Nachtichten */
98         INT flag;                       /* "Markierungs-Flag" (vgl. "irc-write"-Modul) */
99         INT options;                    /* Link-Optionen */
100 #ifdef USE_ZLIB
101         ZIPDATA zip;                    /* Kompressionsinformationen */
102 #endif
103 } CONNECTION;
104
105
106 LOCAL VOID Handle_Read PARAMS(( INT sock ));
107 LOCAL BOOLEAN Handle_Write PARAMS(( CONN_ID Idx ));
108 LOCAL VOID New_Connection PARAMS(( INT Sock ));
109 LOCAL CONN_ID Socket2Index PARAMS(( INT Sock ));
110 LOCAL VOID Read_Request PARAMS(( CONN_ID Idx ));
111 LOCAL BOOLEAN Try_Write PARAMS(( CONN_ID Idx ));
112 LOCAL BOOLEAN Handle_Buffer PARAMS(( CONN_ID Idx ));
113 LOCAL VOID Check_Connections PARAMS(( VOID ));
114 LOCAL VOID Check_Servers PARAMS(( VOID ));
115 LOCAL VOID Init_Conn_Struct PARAMS(( LONG Idx ));
116 LOCAL BOOLEAN Init_Socket PARAMS(( INT Sock ));
117 LOCAL VOID New_Server PARAMS(( INT Server, CONN_ID Idx ));
118 LOCAL VOID Read_Resolver_Result PARAMS(( INT r_fd ));
119
120 #ifdef USE_ZLIB
121 LOCAL BOOLEAN Zip_Buffer PARAMS(( CONN_ID Idx, CHAR *Data, INT Len ));
122 LOCAL BOOLEAN Zip_Flush PARAMS(( CONN_ID Idx ));
123 LOCAL BOOLEAN Unzip_Buffer PARAMS(( CONN_ID Idx ));
124 #endif
125
126
127 LOCAL fd_set My_Listeners;
128 LOCAL fd_set My_Sockets;
129 LOCAL fd_set My_Connects;
130
131 LOCAL CONNECTION *My_Connections;
132 LOCAL LONG Pool_Size;
133
134
135 GLOBAL VOID
136 Conn_Init( VOID )
137 {
138         /* Modul initialisieren: statische Strukturen "ausnullen". */
139
140         CONN_ID i;
141
142         /* Speicher fuer Verbindungs-Pool anfordern */
143         Pool_Size = CONNECTION_POOL;
144         if( Conf_MaxConnections > 0 )
145         {
146                 /* konfiguriertes Limit beachten */
147                 if( Pool_Size > Conf_MaxConnections ) Pool_Size = Conf_MaxConnections;
148         }
149         My_Connections = malloc( sizeof( CONNECTION ) * Pool_Size );
150         if( ! My_Connections )
151         {
152                 /* Speicher konnte nicht alloziert werden! */
153                 Log( LOG_EMERG, "Can't allocate memory! [Conn_Init]" );
154                 exit( 1 );
155         }
156         Log( LOG_DEBUG, "Allocted connection pool for %ld items.", Pool_Size );
157
158         /* zu Beginn haben wir keine Verbindungen */
159         FD_ZERO( &My_Listeners );
160         FD_ZERO( &My_Sockets );
161         FD_ZERO( &My_Connects );
162
163         /* Groesster File-Descriptor fuer select() */
164         Conn_MaxFD = 0;
165
166         /* Connection-Struktur initialisieren */
167         for( i = 0; i < Pool_Size; i++ ) Init_Conn_Struct( i );
168 } /* Conn_Init */
169
170
171 GLOBAL VOID
172 Conn_Exit( VOID )
173 {
174         /* Modul abmelden: alle noch offenen Connections
175          * schliessen und freigeben. */
176
177         CONN_ID idx;
178         INT i;
179
180         /* Sockets schliessen */
181         Log( LOG_DEBUG, "Shutting down all connections ..." );
182         for( i = 0; i < Conn_MaxFD + 1; i++ )
183         {
184                 if( FD_ISSET( i, &My_Sockets ))
185                 {
186                         for( idx = 0; idx < Pool_Size; idx++ )
187                         {
188                                 if( My_Connections[idx].sock == i ) break;
189                         }
190                         if( FD_ISSET( i, &My_Listeners ))
191                         {
192                                 close( i );
193                                 Log( LOG_DEBUG, "Listening socket %d closed.", i );
194                         }
195                         else if( FD_ISSET( i, &My_Connects ))
196                         {
197                                 close( i );
198                                 Log( LOG_DEBUG, "Connection %d closed during creation (socket %d).", idx, i );
199                         }
200                         else if( idx < Pool_Size )
201                         {
202                                 if( NGIRCd_Restart ) Conn_Close( idx, NULL, "Server going down (restarting)", TRUE );
203                                 else Conn_Close( idx, NULL, "Server going down", TRUE );
204                         }
205                         else
206                         {
207                                 Log( LOG_WARNING, "Closing unknown connection %d ...", i );
208                                 close( i );
209                         }
210                 }
211         }
212         
213         free( My_Connections );
214         My_Connections = NULL;
215         Pool_Size = 0;
216 } /* Conn_Exit */
217
218
219 GLOBAL INT
220 Conn_InitListeners( VOID )
221 {
222         /* Ports, auf denen der Server Verbindungen entgegennehmen
223         * soll, initialisieren */
224
225         INT created, i;
226
227         created = 0;
228         for( i = 0; i < Conf_ListenPorts_Count; i++ )
229         {
230                 if( Conn_NewListener( Conf_ListenPorts[i] )) created++;
231                 else Log( LOG_ERR, "Can't listen on port %u!", Conf_ListenPorts[i] );
232         }
233         return created;
234 } /* Conn_InitListeners */
235
236
237 GLOBAL VOID
238 Conn_ExitListeners( VOID )
239 {
240         /* Alle "Listen-Sockets" schliessen */
241
242         INT i;
243
244         Log( LOG_INFO, "Shutting down all listening sockets ..." );
245         for( i = 0; i < Conn_MaxFD + 1; i++ )
246         {
247                 if( FD_ISSET( i, &My_Sockets ) && FD_ISSET( i, &My_Listeners ))
248                 {
249                         close( i );
250                         Log( LOG_DEBUG, "Listening socket %d closed.", i );
251                 }
252         }
253 } /* Conn_ExitListeners */
254
255
256 GLOBAL BOOLEAN
257 Conn_NewListener( CONST UINT Port )
258 {
259         /* Neuen Listen-Socket erzeugen: der Server wartet dann auf
260          * dem angegebenen Port auf Verbindungen. Kann der Listen-
261          * Socket nicht erteugt werden, so wird NULL geliefert.*/
262
263         struct sockaddr_in addr;
264         INT sock;
265
266         /* Server-"Listen"-Socket initialisieren */
267         memset( &addr, 0, sizeof( addr ));
268         addr.sin_family = AF_INET;
269         addr.sin_port = htons( Port );
270         addr.sin_addr.s_addr = htonl( INADDR_ANY );
271
272         /* Socket erzeugen */
273         sock = socket( PF_INET, SOCK_STREAM, 0);
274         if( sock < 0 )
275         {
276                 Log( LOG_CRIT, "Can't create socket: %s!", strerror( errno ));
277                 return FALSE;
278         }
279
280         if( ! Init_Socket( sock )) return FALSE;
281
282         /* an Port binden */
283         if( bind( sock, (struct sockaddr *)&addr, (socklen_t)sizeof( addr )) != 0 )
284         {
285                 Log( LOG_CRIT, "Can't bind socket: %s!", strerror( errno ));
286                 close( sock );
287                 return FALSE;
288         }
289
290         /* in "listen mode" gehen :-) */
291         if( listen( sock, 10 ) != 0 )
292         {
293                 Log( LOG_CRIT, "Can't listen on soecket: %s!", strerror( errno ));
294                 close( sock );
295                 return FALSE;
296         }
297
298         /* Neuen Listener in Strukturen einfuegen */
299         FD_SET( sock, &My_Listeners );
300         FD_SET( sock, &My_Sockets );
301
302         if( sock > Conn_MaxFD ) Conn_MaxFD = sock;
303
304         Log( LOG_INFO, "Now listening on port %d (socket %d).", Port, sock );
305
306         return TRUE;
307 } /* Conn_NewListener */
308
309
310 GLOBAL VOID
311 Conn_Handler( VOID )
312 {
313         /* "Hauptschleife": Aktive Verbindungen ueberwachen. Folgende Aktionen
314          * werden dabei durchgefuehrt, bis der Server terminieren oder neu
315          * starten soll:
316          *
317          *  - neue Verbindungen annehmen,
318          *  - Server-Verbindungen aufbauen,
319          *  - geschlossene Verbindungen loeschen,
320          *  - volle Schreibpuffer versuchen zu schreiben,
321          *  - volle Lesepuffer versuchen zu verarbeiten,
322          *  - Antworten von Resolver Sub-Prozessen annehmen.
323          */
324
325         fd_set read_sockets, write_sockets;
326         struct timeval tv;
327         time_t start, t;
328         LONG i, idx;
329         BOOLEAN timeout;
330
331         start = time( NULL );
332         while(( ! NGIRCd_Quit ) && ( ! NGIRCd_Restart ))
333         {
334                 timeout = TRUE;
335         
336                 Check_Servers( );
337
338                 Check_Connections( );
339
340                 /* noch volle Lese-Buffer suchen */
341                 for( i = 0; i < Pool_Size; i++ )
342                 {
343                         if(( My_Connections[i].sock > NONE ) && ( My_Connections[i].rdatalen > 0 ))
344                         {
345                                 /* Kann aus dem Buffer noch ein Befehl extrahiert werden? */
346                                 if( Handle_Buffer( i )) timeout = FALSE;
347                         }
348                 }
349
350                 /* noch volle Schreib-Puffer suchen */
351                 FD_ZERO( &write_sockets );
352                 for( i = 0; i < Pool_Size; i++ )
353                 {
354 #ifdef USE_ZLIB
355                         if(( My_Connections[i].sock > NONE ) && (( My_Connections[i].wdatalen > 0 ) || ( My_Connections[i].zip.wdatalen > 0 )))
356 #else
357                         if(( My_Connections[i].sock > NONE ) && ( My_Connections[i].wdatalen > 0 ))
358 #endif
359                         {
360                                 /* Socket der Verbindung in Set aufnehmen */
361                                 FD_SET( My_Connections[i].sock, &write_sockets );
362                         }
363                 }
364                 /* Sockets mit im Aufbau befindlichen ausgehenden Verbindungen suchen */
365                 for( i = 0; i < Pool_Size; i++ )
366                 {
367                         if(( My_Connections[i].sock > NONE ) && ( FD_ISSET( My_Connections[i].sock, &My_Connects ))) FD_SET( My_Connections[i].sock, &write_sockets );
368                 }
369
370                 /* von welchen Sockets koennte gelesen werden? */
371                 t = time( NULL );
372                 read_sockets = My_Sockets;
373                 for( i = 0; i < Pool_Size; i++ )
374                 {
375                         if(( My_Connections[i].sock > NONE ) && ( My_Connections[i].host[0] == '\0' ))
376                         {
377                                 /* Hier muss noch auf den Resolver Sub-Prozess gewartet werden */
378                                 FD_CLR( My_Connections[i].sock, &read_sockets );
379                         }
380                         if(( My_Connections[i].sock > NONE ) && ( FD_ISSET( My_Connections[i].sock, &My_Connects )))
381                         {
382                                 /* Hier laeuft noch ein asyncrones connect() */
383                                 FD_CLR( My_Connections[i].sock, &read_sockets );
384                         }
385                         if( My_Connections[i].delaytime > t )
386                         {
387                                 /* Fuer die Verbindung ist eine "Penalty-Zeit" gesetzt */
388                                 FD_CLR( My_Connections[i].sock, &read_sockets );
389                                 FD_CLR( My_Connections[i].sock, &write_sockets );
390                         }
391                 }
392                 for( i = 0; i < Conn_MaxFD + 1; i++ )
393                 {
394                         /* Pipes von Resolver Sub-Prozessen aufnehmen */
395                         if( FD_ISSET( i, &Resolver_FDs ))
396                         {
397                                 FD_SET( i, &read_sockets );
398                         }
399                 }
400
401                 /* Timeout initialisieren */
402                 tv.tv_usec = 0;
403                 if( timeout ) tv.tv_sec = TIME_RES;
404                 else tv.tv_sec = 0;
405                 
406                 /* Auf Aktivitaet warten */
407                 i = select( Conn_MaxFD + 1, &read_sockets, &write_sockets, NULL, &tv );
408                 if( i == 0 )
409                 {
410                         /* keine Veraenderung an den Sockets */
411                         continue;
412                 }
413                 if( i == -1 )
414                 {
415                         /* Fehler (z.B. Interrupt) */
416                         if( errno != EINTR )
417                         {
418                                 Log( LOG_EMERG, "Conn_Handler(): select(): %s!", strerror( errno ));
419                                 Log( LOG_ALERT, "%s exiting due to fatal errors!", PACKAGE );
420                                 exit( 1 );
421                         }
422                         continue;
423                 }
424
425                 /* Koennen Daten geschrieben werden? */
426                 for( i = 0; i < Conn_MaxFD + 1; i++ )
427                 {
428                         if( ! FD_ISSET( i, &write_sockets )) continue;
429
430                         /* Es kann geschrieben werden ... */
431                         idx = Socket2Index( i );
432                         if( idx == NONE ) continue;
433                         
434                         if( ! Handle_Write( idx ))
435                         {
436                                 /* Fehler beim Schreiben! Diesen Socket nun
437                                  * auch aus dem Read-Set entfernen: */
438                                 FD_CLR( i, &read_sockets );
439                         }
440                 }
441
442                 /* Daten zum Lesen vorhanden? */
443                 for( i = 0; i < Conn_MaxFD + 1; i++ )
444                 {
445                         if( FD_ISSET( i, &read_sockets )) Handle_Read( i );
446                 }
447         }
448 } /* Conn_Handler */
449
450
451 #ifdef PROTOTYPES
452 GLOBAL BOOLEAN
453 Conn_WriteStr( CONN_ID Idx, CHAR *Format, ... )
454 #else
455 GLOBAL BOOLEAN
456 Conn_WriteStr( Idx, Format, va_alist )
457 CONN_ID Idx;
458 CHAR *Format;
459 va_dcl
460 #endif
461 {
462         /* String in Socket schreiben. CR+LF wird von dieser Funktion
463          * automatisch angehaengt. Im Fehlerfall wird dir Verbindung
464          * getrennt und FALSE geliefert. */
465
466         CHAR buffer[COMMAND_LEN];
467         BOOLEAN ok;
468         va_list ap;
469
470         assert( Idx > NONE );
471         assert( Format != NULL );
472
473 #ifdef PROTOTYPES
474         va_start( ap, Format );
475 #else
476         va_start( ap );
477 #endif
478         if( vsnprintf( buffer, COMMAND_LEN - 2, Format, ap ) == COMMAND_LEN - 2 )
479         {
480                 Log( LOG_CRIT, "Text too long to send (connection %d)!", Idx );
481                 Conn_Close( Idx, "Text too long to send!", NULL, FALSE );
482                 return FALSE;
483         }
484
485 #ifdef SNIFFER
486         if( NGIRCd_Sniffer ) Log( LOG_DEBUG, " -> connection %d: '%s'.", Idx, buffer );
487 #endif
488
489         strcat( buffer, "\r\n" );
490         ok = Conn_Write( Idx, buffer, strlen( buffer ));
491         My_Connections[Idx].msg_out++;
492
493         va_end( ap );
494         return ok;
495 } /* Conn_WriteStr */
496
497
498 GLOBAL BOOLEAN
499 Conn_Write( CONN_ID Idx, CHAR *Data, INT Len )
500 {
501         /* Daten in Socket schreiben. Bei "fatalen" Fehlern wird
502          * der Client disconnectiert und FALSE geliefert. */
503
504         assert( Idx > NONE );
505         assert( Data != NULL );
506         assert( Len > 0 );
507
508         /* Ist der entsprechende Socket ueberhaupt noch offen? In einem
509          * "Handler-Durchlauf" kann es passieren, dass dem nicht mehr so
510          * ist, wenn einer von mehreren Conn_Write()'s fehlgeschlagen ist.
511          * In diesem Fall wird hier einfach ein Fehler geliefert. */
512         if( My_Connections[Idx].sock <= NONE )
513         {
514                 Log( LOG_DEBUG, "Skipped write on closed socket (connection %d).", Idx );
515                 return FALSE;
516         }
517
518         /* Pruefen, ob im Schreibpuffer genuegend Platz ist. Ziel ist es,
519          * moeglichts viel im Puffer zu haben und _nicht_ gleich alles auf den
520          * Socket zu schreiben (u.a. wg. Komprimierung). */
521         if( WRITEBUFFER_LEN - My_Connections[Idx].wdatalen - Len <= 0 )
522         {
523                 /* Der Puffer ist dummerweise voll. Jetzt versuchen, den Puffer
524                  * zu schreiben, wenn das nicht klappt, haben wir ein Problem ... */
525                 if( ! Try_Write( Idx )) return FALSE;
526
527                 /* nun neu pruefen: */
528                 if( WRITEBUFFER_LEN - My_Connections[Idx].wdatalen - Len <= 0 )
529                 {
530                         Log( LOG_NOTICE, "Write buffer overflow (connection %d)!", Idx );
531                         Conn_Close( Idx, "Write buffer overflow!", NULL, FALSE );
532                         return FALSE;
533                 }
534         }
535
536 #ifdef USE_ZLIB
537         if( My_Connections[Idx].options & CONN_ZIP )
538         {
539                 /* Daten komprimieren und in Puffer kopieren */
540                 if( ! Zip_Buffer( Idx, Data, Len )) return FALSE;
541         }
542         else
543 #endif
544         {
545                 /* Daten in Puffer kopieren */
546                 memcpy( My_Connections[Idx].wbuf + My_Connections[Idx].wdatalen, Data, Len );
547                 My_Connections[Idx].wdatalen += Len;
548                 My_Connections[Idx].bytes_out += Len;
549         }
550
551         return TRUE;
552 } /* Conn_Write */
553
554
555 GLOBAL VOID
556 Conn_Close( CONN_ID Idx, CHAR *LogMsg, CHAR *FwdMsg, BOOLEAN InformClient )
557 {
558         /* Verbindung schliessen. Evtl. noch von Resolver
559          * Sub-Prozessen offene Pipes werden geschlossen. */
560
561         CLIENT *c;
562         DOUBLE in_k, out_k;
563 #ifdef USE_ZLIB
564         DOUBLE in_z_k, out_z_k;
565         INT in_p, out_p;
566 #endif
567
568         assert( Idx > NONE );
569         assert( My_Connections[Idx].sock > NONE );
570
571         c = Client_GetFromConn( Idx );
572
573         if( InformClient )
574         {
575 #ifndef STRICT_RFC
576                 /* Statistik an Client melden, wenn User */
577                 if(( c != NULL ) && ( Client_Type( c ) == CLIENT_USER ))
578                 {
579                         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 );
580                 }
581 #endif
582
583                 /* ERROR an Client schicken (von RFC so vorgesehen!) */
584                 if( FwdMsg ) Conn_WriteStr( Idx, "ERROR :%s", FwdMsg );
585                 else Conn_WriteStr( Idx, "ERROR :Closing connection." );
586                 if( My_Connections[Idx].sock == NONE ) return;
587         }
588
589         /* zunaechst versuchen, noch im Schreibpuffer vorhandene
590          * Daten auf den Socket zu schreiben ... */
591         Try_Write( Idx );
592
593         if( close( My_Connections[Idx].sock ) != 0 )
594         {
595                 Log( LOG_ERR, "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 ));
596         }
597         else
598         {
599                 in_k = (DOUBLE)My_Connections[Idx].bytes_in / 1024;
600                 out_k = (DOUBLE)My_Connections[Idx].bytes_out / 1024;
601 #ifdef USE_ZLIB
602                 if( My_Connections[Idx].options & CONN_ZIP )
603                 {
604                         in_z_k = (DOUBLE)My_Connections[Idx].zip.bytes_in / 1024;
605                         out_z_k = (DOUBLE)My_Connections[Idx].zip.bytes_out / 1024;
606                         in_p = (INT)(( in_k * 100 ) / in_z_k );
607                         out_p = (INT)(( out_k * 100 ) / out_z_k );
608                         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 );
609                 }
610                 else
611 #endif
612                 {
613                         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 );
614                 }
615         }
616         
617         /* Socket als "ungueltig" markieren */
618         FD_CLR( My_Connections[Idx].sock, &My_Sockets );
619         FD_CLR( My_Connections[Idx].sock, &My_Connects );
620         My_Connections[Idx].sock = NONE;
621
622         if( c ) Client_Destroy( c, LogMsg, FwdMsg, TRUE );
623
624         if( My_Connections[Idx].res_stat )
625         {
626                 /* Resolver-Strukturen freigeben, wenn noch nicht geschehen */
627                 FD_CLR( My_Connections[Idx].res_stat->pipe[0], &Resolver_FDs );
628                 close( My_Connections[Idx].res_stat->pipe[0] );
629                 close( My_Connections[Idx].res_stat->pipe[1] );
630                 free( My_Connections[Idx].res_stat );
631         }
632
633         /* Startzeit des naechsten Connect-Versuchs modifizieren? */
634         if(( My_Connections[Idx].our_server > NONE ) && ( Conf_Server[My_Connections[Idx].our_server].lasttry <  time( NULL ) - Conf_ConnectRetry ))
635         {
636                 /* Okay, die Verbindung stand schon "genuegend lange":
637                  * lasttry-Zeitpunkt so setzen, dass der naechste
638                  * Verbindungsversuch in RECONNECT_DELAY Sekunden
639                  * gestartet wird. */
640                 Conf_Server[My_Connections[Idx].our_server].lasttry = time( NULL ) - Conf_ConnectRetry + RECONNECT_DELAY;
641         }
642
643 #ifdef USE_ZLIB
644         /* Ggf. zlib abmelden */
645         if( Conn_Options( Idx ) & CONN_ZIP )
646         {
647                 inflateEnd( &My_Connections[Idx].zip.in );
648                 deflateEnd( &My_Connections[Idx].zip.out );
649         }
650 #endif
651
652         /* Connection-Struktur loeschen (=freigeben) */
653         Init_Conn_Struct( Idx );
654 } /* Conn_Close */
655
656
657 GLOBAL VOID
658 Conn_UpdateIdle( CONN_ID Idx )
659 {
660         /* Idle-Timer zuruecksetzen */
661
662         assert( Idx > NONE );
663         My_Connections[Idx].lastprivmsg = time( NULL );
664 }
665
666
667 GLOBAL time_t
668 Conn_GetIdle( CONN_ID Idx )
669 {
670         /* Idle-Time einer Verbindung liefern (in Sekunden) */
671
672         assert( Idx > NONE );
673         return time( NULL ) - My_Connections[Idx].lastprivmsg;
674 } /* Conn_GetIdle */
675
676
677 GLOBAL time_t
678 Conn_LastPing( CONN_ID Idx )
679 {
680         /* Zeitpunkt des letzten PING liefern */
681
682         assert( Idx > NONE );
683         return My_Connections[Idx].lastping;
684 } /* Conn_LastPing */
685
686
687 GLOBAL VOID
688 Conn_SetPenalty( CONN_ID Idx, time_t Seconds )
689 {
690         /* Penalty-Delay fuer eine Verbindung (in Sekunden) setzen;
691          * waehrend dieser Zeit wird der entsprechende Socket vom Server
692          * bei Lese-Operationen komplett ignoriert. Der Delay kann mit
693          * dieser Funktion nur erhoeht, nicht aber verringert werden. */
694         
695         time_t t;
696         
697         assert( Idx > NONE );
698         assert( Seconds >= 0 );
699         
700         t = time( NULL ) + Seconds;
701         if( t > My_Connections[Idx].delaytime ) My_Connections[Idx].delaytime = t;
702 } /* Conn_SetPenalty */
703
704
705 GLOBAL VOID
706 Conn_ResetPenalty( CONN_ID Idx )
707 {
708         assert( Idx > NONE );
709         My_Connections[Idx].delaytime = 0;
710 } /* Conn_ResetPenalty */
711
712
713 GLOBAL VOID
714 Conn_ClearFlags( VOID )
715 {
716         /* Alle Connection auf "nicht-markiert" setzen */
717
718         LONG i;
719
720         for( i = 0; i < Pool_Size; i++ ) My_Connections[i].flag = 0;
721 } /* Conn_ClearFlags */
722
723
724 GLOBAL INT
725 Conn_Flag( CONN_ID Idx )
726 {
727         /* Ist eine Connection markiert (TRUE) oder nicht? */
728
729         assert( Idx > NONE );
730         return My_Connections[Idx].flag;
731 } /* Conn_Flag */
732
733
734 GLOBAL VOID
735 Conn_SetFlag( CONN_ID Idx, INT Flag )
736 {
737         /* Connection markieren */
738
739         assert( Idx > NONE );
740         My_Connections[Idx].flag = Flag;
741 } /* Conn_SetFlag */
742
743
744 GLOBAL CONN_ID
745 Conn_First( VOID )
746 {
747         /* Connection-Struktur der ersten Verbindung liefern;
748          * Ist keine Verbindung vorhanden, wird NONE geliefert. */
749
750         LONG i;
751         
752         for( i = 0; i < Pool_Size; i++ )
753         {
754                 if( My_Connections[i].sock != NONE ) return i;
755         }
756         return NONE;
757 } /* Conn_First */
758
759
760 GLOBAL CONN_ID
761 Conn_Next( CONN_ID Idx )
762 {
763         /* Naechste Verbindungs-Struktur liefern; existiert keine
764          * weitere, so wird NONE geliefert. */
765
766         LONG i = NONE;
767
768         assert( Idx > NONE );
769         
770         for( i = Idx + 1; i < Pool_Size; i++ )
771         {
772                 if( My_Connections[i].sock != NONE ) return i;
773         }
774         return NONE;
775 } /* Conn_Next */
776
777
778 GLOBAL VOID
779 Conn_SetServer( CONN_ID Idx, INT ConfServer )
780 {
781         /* Connection als Server markieren: Index des konfigurierten
782          * Servers speichern. Verbindung muss bereits bestehen! */
783         
784         assert( Idx > NONE );
785         assert( My_Connections[Idx].sock > NONE );
786         
787         My_Connections[Idx].our_server = ConfServer;
788 } /* Conn_SetServer */
789
790
791 GLOBAL VOID
792 Conn_SetOption( CONN_ID Idx, INT Option )
793 {
794         /* Option fuer Verbindung setzen.
795          * Initial sind alle Optionen _nicht_ gesetzt. */
796
797         assert( Idx > NONE );
798         assert( Option != 0 );
799
800         My_Connections[Idx].options |= Option;
801 } /* Conn_SetOption */
802
803
804 GLOBAL VOID
805 Conn_UnsetOption( CONN_ID Idx, INT Option )
806 {
807         /* Option fuer Verbindung loeschen */
808
809         assert( Idx > NONE );
810         assert( Option != 0 );
811
812         My_Connections[Idx].options &= ~Option;
813 } /* Conn_UnsetOption */
814
815
816 GLOBAL INT
817 Conn_Options( CONN_ID Idx )
818 {
819         assert( Idx > NONE );
820         return My_Connections[Idx].options;
821 } /* Conn_Options */
822
823
824 #ifdef USE_ZLIB
825
826 GLOBAL BOOLEAN
827 Conn_InitZip( CONN_ID Idx )
828 {
829         /* Kompression fuer Link initialisieren */
830
831         assert( Idx > NONE );
832
833         My_Connections[Idx].zip.in.avail_in = 0;
834         My_Connections[Idx].zip.in.total_in = 0;
835         My_Connections[Idx].zip.in.total_out = 0;
836         My_Connections[Idx].zip.in.zalloc = NULL;
837         My_Connections[Idx].zip.in.zfree = NULL;
838         My_Connections[Idx].zip.in.data_type = Z_ASCII;
839
840         if( inflateInit( &My_Connections[Idx].zip.in ) != Z_OK )
841         {
842                 /* Fehler! */
843                 Log( LOG_ALERT, "Can't initialize compression on connection %d (zlib inflate)!", Idx );
844                 return FALSE;
845         }
846         
847         My_Connections[Idx].zip.out.total_in = 0;
848         My_Connections[Idx].zip.out.total_in = 0;
849         My_Connections[Idx].zip.out.zalloc = NULL;
850         My_Connections[Idx].zip.out.zfree = NULL;
851         My_Connections[Idx].zip.out.data_type = Z_ASCII;
852
853         if( deflateInit( &My_Connections[Idx].zip.out, Z_DEFAULT_COMPRESSION ) != Z_OK )
854         {
855                 /* Fehler! */
856                 Log( LOG_ALERT, "Can't initialize compression on connection %d (zlib deflate)!", Idx );
857                 return FALSE;
858         }
859
860         My_Connections[Idx].zip.bytes_in = My_Connections[Idx].bytes_in;
861         My_Connections[Idx].zip.bytes_out = My_Connections[Idx].bytes_out;
862
863         Log( LOG_INFO, "Enabled link compression (zlib) on connection %d.", Idx );
864         Conn_SetOption( Idx, CONN_ZIP );
865
866         return TRUE;
867 } /* Conn_InitZip */
868
869
870 GLOBAL LONG
871 Conn_SendBytesZip( CONN_ID Idx )
872 {
873         /* Anzahl gesendeter Bytes (komprimiert!) liefern */
874
875         assert( Idx > NONE );
876         return My_Connections[Idx].zip.bytes_out;
877 } /* Conn_SendBytesZip */
878
879
880 GLOBAL LONG
881 Conn_RecvBytesZip( CONN_ID Idx )
882 {
883         /* Anzahl gesendeter Bytes (komprimiert!) liefern */
884
885         assert( Idx > NONE );
886         return My_Connections[Idx].zip.bytes_in;
887 } /* Conn_RecvBytesZip */
888
889 #endif
890
891
892 GLOBAL time_t
893 Conn_StartTime( CONN_ID Idx )
894 {
895         /* Zeitpunkt des Link-Starts liefern (in Sekunden) */
896
897         assert( Idx > NONE );
898         return My_Connections[Idx].starttime;
899 } /* Conn_Uptime */
900
901
902 GLOBAL INT
903 Conn_SendQ( CONN_ID Idx )
904 {
905         /* Laenge der Daten im Schreibbuffer liefern */
906
907         assert( Idx > NONE );
908 #ifdef USE_ZLIB
909         if( My_Connections[Idx].options & CONN_ZIP ) return My_Connections[Idx].zip.wdatalen;
910         else
911 #endif
912         return My_Connections[Idx].wdatalen;
913 } /* Conn_SendQ */
914
915
916 GLOBAL LONG
917 Conn_SendMsg( CONN_ID Idx )
918 {
919         /* Anzahl gesendeter Nachrichten liefern */
920
921         assert( Idx > NONE );
922         return My_Connections[Idx].msg_out;
923 } /* Conn_SendMsg */
924
925
926 GLOBAL LONG
927 Conn_SendBytes( CONN_ID Idx )
928 {
929         /* Anzahl gesendeter Bytes (unkomprimiert) liefern */
930
931         assert( Idx > NONE );
932         return My_Connections[Idx].bytes_out;
933 } /* Conn_SendBytes */
934
935
936 GLOBAL INT
937 Conn_RecvQ( CONN_ID Idx )
938 {
939         /* Laenge der Daten im Lesebuffer liefern */
940
941         assert( Idx > NONE );
942 #ifdef USE_ZLIB
943         if( My_Connections[Idx].options & CONN_ZIP ) return My_Connections[Idx].zip.rdatalen;
944         else
945 #endif
946         return My_Connections[Idx].rdatalen;
947 } /* Conn_RecvQ */
948
949
950 GLOBAL LONG
951 Conn_RecvMsg( CONN_ID Idx )
952 {
953         /* Anzahl empfangener Nachrichten liefern */
954
955         assert( Idx > NONE );
956         return My_Connections[Idx].msg_in;
957 } /* Conn_RecvMsg */
958
959
960 GLOBAL LONG
961 Conn_RecvBytes( CONN_ID Idx )
962 {
963         /* Anzahl empfangener Bytes (unkomprimiert) liefern */
964
965         assert( Idx > NONE );
966         return My_Connections[Idx].bytes_in;
967 } /* Conn_RecvBytes */
968
969
970 LOCAL BOOLEAN
971 Try_Write( CONN_ID Idx )
972 {
973         /* Versuchen, Daten aus dem Schreib-Puffer in den Socket zu
974          * schreiben. TRUE wird geliefert, wenn entweder keine Daten
975          * zum Versenden vorhanden sind oder erfolgreich bearbeitet
976          * werden konnten. Im Fehlerfall wird FALSE geliefert und
977          * die Verbindung geschlossen. */
978
979         fd_set write_socket;
980         struct timeval tv;
981
982         assert( Idx > NONE );
983         assert( My_Connections[Idx].sock > NONE );
984
985         /* sind ueberhaupt Daten vorhanden? */
986 #ifdef USE_ZLIB
987         if(( ! My_Connections[Idx].wdatalen > 0 ) && ( ! My_Connections[Idx].zip.wdatalen )) return TRUE;
988 #else
989         if( ! My_Connections[Idx].wdatalen > 0 ) return TRUE;
990 #endif
991
992         /* Timeout initialisieren: 0 Sekunden, also nicht blockieren */
993         tv.tv_sec = 0; tv.tv_usec = 0;
994
995         FD_ZERO( &write_socket );
996         FD_SET( My_Connections[Idx].sock, &write_socket );
997         if( select( My_Connections[Idx].sock + 1, NULL, &write_socket, NULL, &tv ) == -1 )
998         {
999                 /* Fehler! */
1000                 if( errno != EINTR )
1001                 {
1002                         Log( LOG_ALERT, "Try_Write(): select() failed: %s (con=%d, sock=%d)!", strerror( errno ), Idx, My_Connections[Idx].sock );
1003                         Conn_Close( Idx, "Server error!", NULL, FALSE );
1004                         return FALSE;
1005                 }
1006         }
1007
1008         if( FD_ISSET( My_Connections[Idx].sock, &write_socket )) return Handle_Write( Idx );
1009         else return TRUE;
1010 } /* Try_Write */
1011
1012
1013 LOCAL VOID
1014 Handle_Read( INT Sock )
1015 {
1016         /* Aktivitaet auf einem Socket verarbeiten:
1017          *  - neue Clients annehmen,
1018          *  - Daten von Clients verarbeiten,
1019          *  - Resolver-Rueckmeldungen annehmen. */
1020
1021         CONN_ID idx;
1022
1023         assert( Sock > NONE );
1024
1025         if( FD_ISSET( Sock, &My_Listeners ))
1026         {
1027                 /* es ist einer unserer Listener-Sockets: es soll
1028                  * also eine neue Verbindung aufgebaut werden. */
1029
1030                 New_Connection( Sock );
1031         }
1032         else if( FD_ISSET( Sock, &Resolver_FDs ))
1033         {
1034                 /* Rueckmeldung von einem Resolver Sub-Prozess */
1035
1036                 Read_Resolver_Result( Sock );
1037         }
1038         else
1039         {
1040                 /* Ein Client Socket: entweder ein User oder Server */
1041
1042                 idx = Socket2Index( Sock );
1043                 if( idx > NONE ) Read_Request( idx );
1044         }
1045 } /* Handle_Read */
1046
1047
1048 LOCAL BOOLEAN
1049 Handle_Write( CONN_ID Idx )
1050 {
1051         /* Daten aus Schreibpuffer versenden bzw. Connection aufbauen */
1052
1053         INT len, res, err;
1054
1055         assert( Idx > NONE );
1056         assert( My_Connections[Idx].sock > NONE );
1057
1058         if( FD_ISSET( My_Connections[Idx].sock, &My_Connects ))
1059         {
1060                 /* es soll nichts geschrieben werden, sondern ein
1061                  * connect() hat ein Ergebnis geliefert */
1062
1063                 FD_CLR( My_Connections[Idx].sock, &My_Connects );
1064
1065                 /* Ergebnis des connect() ermitteln */
1066                 len = sizeof( err );
1067                 res = getsockopt( My_Connections[Idx].sock, SOL_SOCKET, SO_ERROR, &err, &len );
1068                 assert( len == sizeof( err ));
1069
1070                 /* Fehler aufgetreten? */
1071                 if(( res != 0 ) || ( err != 0 ))
1072                 {
1073                         /* Fehler! */
1074                         if( res != 0 ) Log( LOG_CRIT, "getsockopt (connection %d): %s!", Idx, strerror( errno ));
1075                         else Log( LOG_CRIT, "Can't connect socket to \"%s:%d\" (connection %d): %s!", My_Connections[Idx].host, Conf_Server[My_Connections[Idx].our_server].port, Idx, strerror( err ));
1076
1077                         /* Socket etc. pp. aufraeumen */
1078                         FD_CLR( My_Connections[Idx].sock, &My_Sockets );
1079                         close( My_Connections[Idx].sock );
1080                         Init_Conn_Struct( Idx );
1081
1082                         /* Bei Server-Verbindungen lasttry-Zeitpunkt auf "jetzt" setzen */
1083                         Conf_Server[My_Connections[Idx].our_server].lasttry = time( NULL );
1084
1085                         return FALSE;
1086                 }
1087                 Log( LOG_DEBUG, "Connection %d with \"%s:%d\" established, now sendig PASS and SERVER ...", Idx, My_Connections[Idx].host, Conf_Server[My_Connections[Idx].our_server].port );
1088
1089                 /* PASS und SERVER verschicken */
1090                 Conn_WriteStr( Idx, "PASS %s %s", Conf_Server[My_Connections[Idx].our_server].pwd_out, NGIRCd_ProtoID );
1091                 return Conn_WriteStr( Idx, "SERVER %s :%s", Conf_ServerName, Conf_ServerInfo );
1092         }
1093
1094 #ifdef USE_ZLIB
1095         /* Schreibpuffer leer, aber noch Daten im Kompressionsbuffer?
1096          * Dann muss dieser nun geflushed werden! */
1097         if( My_Connections[Idx].wdatalen == 0 ) Zip_Flush( Idx );
1098 #endif
1099
1100         assert( My_Connections[Idx].wdatalen > 0 );
1101
1102         /* Daten schreiben */
1103         len = send( My_Connections[Idx].sock, My_Connections[Idx].wbuf, My_Connections[Idx].wdatalen, 0 );
1104         if( len < 0 )
1105         {
1106                 /* Operation haette Socket "nur" blockiert ... */
1107                 if( errno == EAGAIN ) return TRUE;
1108
1109                 /* Oops, ein Fehler! */
1110                 Log( LOG_ERR, "Write error on connection %d (socket %d): %s!", Idx, My_Connections[Idx].sock, strerror( errno ));
1111                 Conn_Close( Idx, "Write error!", NULL, FALSE );
1112                 return FALSE;
1113         }
1114
1115         /* Puffer anpassen */
1116         My_Connections[Idx].wdatalen -= len;
1117         memmove( My_Connections[Idx].wbuf, My_Connections[Idx].wbuf + len, My_Connections[Idx].wdatalen );
1118
1119         return TRUE;
1120 } /* Handle_Write */
1121
1122
1123 LOCAL VOID
1124 New_Connection( INT Sock )
1125 {
1126         /* Neue Client-Verbindung von Listen-Socket annehmen und
1127          * CLIENT-Struktur anlegen. */
1128
1129         struct sockaddr_in new_addr;
1130         INT new_sock, new_sock_len;
1131         RES_STAT *s;
1132         CONN_ID idx;
1133         CLIENT *c;
1134         POINTER *ptr;
1135         LONG new_size;
1136
1137         assert( Sock > NONE );
1138
1139         /* Connection auf Listen-Socket annehmen */
1140         new_sock_len = sizeof( new_addr );
1141         new_sock = accept( Sock, (struct sockaddr *)&new_addr, (socklen_t *)&new_sock_len );
1142         if( new_sock < 0 )
1143         {
1144                 Log( LOG_CRIT, "Can't accept connection: %s!", strerror( errno ));
1145                 return;
1146         }
1147
1148         /* Socket initialisieren */
1149         Init_Socket( new_sock );
1150
1151         /* Freie Connection-Struktur suchen */
1152         for( idx = 0; idx < Pool_Size; idx++ ) if( My_Connections[idx].sock == NONE ) break;
1153         if( idx >= Pool_Size )
1154         {
1155                 new_size = Pool_Size + CONNECTION_POOL;
1156                 
1157                 /* Im bisherigen Pool wurde keine freie Connection-Struktur mehr gefunden.
1158                  * Wenn erlaubt und moeglich muss nun der Pool vergroessert werden: */
1159                 
1160                 if( Conf_MaxConnections > 0 )
1161                 {
1162                         /* Es ist ein Limit konfiguriert */
1163                         if( Pool_Size >= Conf_MaxConnections )
1164                         {
1165                                 /* Mehr Verbindungen duerfen wir leider nicht mehr annehmen ... */
1166                                 Log( LOG_ALERT, "Can't accept connection: limit (%d) reached!", Pool_Size );
1167                                 close( new_sock );
1168                                 return;
1169                         }
1170                         if( new_size > Conf_MaxConnections ) new_size = Conf_MaxConnections;
1171                 }
1172                 
1173                 /* zunaechst realloc() versuchen; wenn das scheitert, malloc() versuchen
1174                  * und Daten ggf. "haendisch" umkopieren. (Haesslich! Eine wirklich
1175                  * dynamische Verwaltung waere wohl _deutlich_ besser ...) */
1176                 ptr = realloc( My_Connections, sizeof( CONNECTION ) * new_size );
1177                 if( ! ptr )
1178                 {
1179                         /* realloc() ist fehlgeschlagen. Nun malloc() probieren: */
1180                         ptr = malloc( sizeof( CONNECTION ) * new_size );
1181                         if( ! ptr )
1182                         {
1183                                 /* Offenbar steht kein weiterer Sepeicher zur Verfuegung :-( */
1184                                 Log( LOG_EMERG, "Can't allocate memory! [New_Connection]" );
1185                                 close( new_sock );
1186                                 return;
1187                         }
1188                         
1189                         /* Struktur umkopieren ... */
1190                         memcpy( ptr, My_Connections, sizeof( CONNECTION ) * Pool_Size );
1191                         
1192                         Log( LOG_DEBUG, "Allocated new connection pool for %ld items. [malloc()/memcpy()]", new_size );
1193                 }
1194                 else Log( LOG_DEBUG, "Allocated new connection pool for %ld items. [realloc()]", new_size );
1195                 
1196                 My_Connections = ptr;
1197                 Pool_Size = new_size;
1198         }
1199
1200         /* Client-Struktur initialisieren */
1201         c = Client_NewLocal( idx, inet_ntoa( new_addr.sin_addr ), CLIENT_UNKNOWN, FALSE );
1202         if( ! c )
1203         {
1204                 Log( LOG_ALERT, "Can't accept connection: can't create client structure!" );
1205                 close( new_sock );
1206                 return;
1207         }
1208
1209         /* Verbindung registrieren */
1210         Init_Conn_Struct( idx );
1211         My_Connections[idx].sock = new_sock;
1212         My_Connections[idx].addr = new_addr;
1213
1214         /* Neuen Socket registrieren */
1215         FD_SET( new_sock, &My_Sockets );
1216         if( new_sock > Conn_MaxFD ) Conn_MaxFD = new_sock;
1217
1218         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 );
1219
1220         /* Hostnamen ermitteln */
1221         strcpy( My_Connections[idx].host, inet_ntoa( new_addr.sin_addr ));
1222         Client_SetHostname( c, My_Connections[idx].host );
1223         s = Resolve_Addr( &new_addr );
1224         if( s )
1225         {
1226                 /* Sub-Prozess wurde asyncron gestartet */
1227                 My_Connections[idx].res_stat = s;
1228         }
1229         
1230         /* Penalty-Zeit setzen */
1231         Conn_SetPenalty( idx, 4 );
1232 } /* New_Connection */
1233
1234
1235 LOCAL CONN_ID
1236 Socket2Index( INT Sock )
1237 {
1238         /* zum Socket passende Connection suchen */
1239
1240         CONN_ID idx;
1241
1242         assert( Sock > NONE );
1243
1244         for( idx = 0; idx < Pool_Size; idx++ ) if( My_Connections[idx].sock == Sock ) break;
1245
1246         if( idx >= Pool_Size )
1247         {
1248                 /* die Connection wurde vermutlich (wegen eines
1249                  * Fehlers) bereits wieder abgebaut ... */
1250                 Log( LOG_DEBUG, "Socket2Index: can't get connection for socket %d!", Sock );
1251                 return NONE;
1252         }
1253         else return idx;
1254 } /* Socket2Index */
1255
1256
1257 LOCAL VOID
1258 Read_Request( CONN_ID Idx )
1259 {
1260         /* Daten von Socket einlesen und entsprechend behandeln.
1261          * Tritt ein Fehler auf, so wird der Socket geschlossen. */
1262
1263         INT len, bsize;
1264 #ifdef USE_ZLIB
1265         CLIENT *c;
1266 #endif
1267
1268         assert( Idx > NONE );
1269         assert( My_Connections[Idx].sock > NONE );
1270
1271         /* wenn noch nicht registriert: maximal mit ZREADBUFFER_LEN arbeiten,
1272          * ansonsten koennen Daten ggf. nicht umkopiert werden. */
1273         bsize = READBUFFER_LEN;
1274 #ifdef USE_ZLIB
1275         c = Client_GetFromConn( Idx );
1276         if(( Client_Type( c ) != CLIENT_USER ) && ( Client_Type( c ) != CLIENT_SERVER ) && ( Client_Type( c ) != CLIENT_SERVICE ) && ( bsize > ZREADBUFFER_LEN )) bsize = ZREADBUFFER_LEN;
1277 #endif
1278
1279 #ifdef USE_ZLIB
1280         if(( bsize - My_Connections[Idx].rdatalen - 1 < 1 ) || ( ZREADBUFFER_LEN - My_Connections[Idx].zip.rdatalen < 1 ))
1281 #else
1282         if( bsize - My_Connections[Idx].rdatalen - 1 < 1 )
1283 #endif
1284         {
1285                 /* Der Lesepuffer ist voll */
1286                 Log( LOG_ERR, "Read buffer overflow (connection %d): %d bytes!", Idx, My_Connections[Idx].rdatalen );
1287                 Conn_Close( Idx, "Read buffer overflow!", NULL, FALSE );
1288                 return;
1289         }
1290
1291 #ifdef USE_ZLIB
1292         if( My_Connections[Idx].options & CONN_ZIP )
1293         {
1294                 len = recv( My_Connections[Idx].sock, My_Connections[Idx].zip.rbuf + My_Connections[Idx].zip.rdatalen, ( ZREADBUFFER_LEN - My_Connections[Idx].zip.rdatalen ), 0 );
1295                 if( len > 0 ) My_Connections[Idx].zip.rdatalen += len;
1296         }
1297         else
1298 #endif
1299         {
1300                 len = recv( My_Connections[Idx].sock, My_Connections[Idx].rbuf + My_Connections[Idx].rdatalen, bsize - My_Connections[Idx].rdatalen - 1, 0 );
1301                 if( len > 0 ) My_Connections[Idx].rdatalen += len;
1302         }
1303
1304         if( len == 0 )
1305         {
1306                 /* Socket wurde geschlossen */
1307                 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 ));
1308                 Conn_Close( Idx, "Socket closed!", "Client closed connection", FALSE );
1309                 return;
1310         }
1311
1312         if( len < 0 )
1313         {
1314                 /* Operation haette Socket "nur" blockiert ... */
1315                 if( errno == EAGAIN ) return;
1316
1317                 /* Fehler beim Lesen */
1318                 Log( LOG_ERR, "Read error on connection %d (socket %d): %s!", Idx, My_Connections[Idx].sock, strerror( errno ));
1319                 Conn_Close( Idx, "Read error!", "Client closed connection", FALSE );
1320                 return;
1321         }
1322
1323         /* Connection-Statistik aktualisieren */
1324         My_Connections[Idx].bytes_in += len;
1325
1326         /* Timestamp aktualisieren */
1327         My_Connections[Idx].lastdata = time( NULL );
1328
1329         Handle_Buffer( Idx );
1330 } /* Read_Request */
1331
1332
1333 LOCAL BOOLEAN
1334 Handle_Buffer( CONN_ID Idx )
1335 {
1336         /* Daten im Lese-Puffer einer Verbindung verarbeiten.
1337          * Wurde ein Request verarbeitet, so wird TRUE geliefert,
1338          * ansonsten FALSE (auch bei Fehlern). */
1339
1340 #ifndef STRICT_RFC
1341         CHAR *ptr1, *ptr2;
1342 #endif
1343         CHAR *ptr;
1344         INT len, delta;
1345         BOOLEAN action, result;
1346 #ifdef USE_ZLIB
1347         BOOLEAN old_z;
1348 #endif
1349
1350         result = FALSE;
1351         do
1352         {
1353 #ifdef USE_ZLIB
1354                 /* ggf. noch unkomprimiete Daten weiter entpacken */
1355                 if( My_Connections[Idx].options & CONN_ZIP )
1356                 {
1357                         if( ! Unzip_Buffer( Idx )) return FALSE;
1358                 }
1359 #endif
1360         
1361                 if( My_Connections[Idx].rdatalen < 1 ) break;
1362
1363                 /* Eine komplette Anfrage muss mit CR+LF enden, vgl.
1364                  * RFC 2812. Haben wir eine? */
1365                 My_Connections[Idx].rbuf[My_Connections[Idx].rdatalen] = '\0';
1366                 ptr = strstr( My_Connections[Idx].rbuf, "\r\n" );
1367         
1368                 if( ptr ) delta = 2;
1369 #ifndef STRICT_RFC
1370                 else
1371                 {
1372                         /* Nicht RFC-konforme Anfrage mit nur CR oder LF? Leider
1373                          * machen soetwas viele Clients, u.a. "mIRC" :-( */
1374                         ptr1 = strchr( My_Connections[Idx].rbuf, '\r' );
1375                         ptr2 = strchr( My_Connections[Idx].rbuf, '\n' );
1376                         delta = 1;
1377                         if( ptr1 && ptr2 ) ptr = ptr1 > ptr2 ? ptr2 : ptr1;
1378                         else if( ptr1 ) ptr = ptr1;
1379                         else if( ptr2 ) ptr = ptr2;
1380                 }
1381 #endif
1382         
1383                 action = FALSE;
1384                 if( ptr )
1385                 {
1386                         /* Ende der Anfrage wurde gefunden */
1387                         *ptr = '\0';
1388                         len = ( ptr - My_Connections[Idx].rbuf ) + delta;
1389                         if( len > ( COMMAND_LEN - 1 ))
1390                         {
1391                                 /* Eine Anfrage darf(!) nicht laenger als 512 Zeichen
1392                                  * (incl. CR+LF!) werden; vgl. RFC 2812. Wenn soetwas
1393                                  * empfangen wird, wird der Client disconnectiert. */
1394                                 Log( LOG_ERR, "Request too long (connection %d): %d bytes (max. %d expected)!", Idx, My_Connections[Idx].rdatalen, COMMAND_LEN - 1 );
1395                                 Conn_Close( Idx, NULL, "Request too long", TRUE );
1396                                 return FALSE;
1397                         }
1398
1399 #ifdef USE_ZLIB
1400                         /* merken, ob Stream bereits komprimiert wird */
1401                         old_z = My_Connections[Idx].options & CONN_ZIP;
1402 #endif
1403
1404                         if( len > delta )
1405                         {
1406                                 /* Es wurde ein Request gelesen */
1407                                 My_Connections[Idx].msg_in++;
1408                                 if( ! Parse_Request( Idx, My_Connections[Idx].rbuf )) return FALSE;
1409                                 else action = TRUE;
1410                         }
1411
1412                         /* Puffer anpassen */
1413                         My_Connections[Idx].rdatalen -= len;
1414                         memmove( My_Connections[Idx].rbuf, My_Connections[Idx].rbuf + len, My_Connections[Idx].rdatalen );
1415
1416 #ifdef USE_ZLIB
1417                         if(( ! old_z ) && ( My_Connections[Idx].options & CONN_ZIP ) && ( My_Connections[Idx].rdatalen > 0 ))
1418                         {
1419                                 /* Mit dem letzten Befehl wurde Socket-Kompression aktiviert.
1420                                  * Evtl. schon vom Socket gelesene Daten in den Unzip-Puffer
1421                                  * umkopieren, damit diese nun zunaechst entkomprimiert werden */
1422                                 {
1423                                         if( My_Connections[Idx].rdatalen > ZREADBUFFER_LEN )
1424                                         {
1425                                                 /* Hupsa! Soviel Platz haben wir aber gar nicht! */
1426                                                 Log( LOG_ALERT, "Can't move read buffer: No space left in unzip buffer (need %d bytes)!", My_Connections[Idx].rdatalen );
1427                                                 return FALSE;
1428                                         }
1429                                         memcpy( My_Connections[Idx].zip.rbuf, My_Connections[Idx].rbuf, My_Connections[Idx].rdatalen );
1430                                         My_Connections[Idx].zip.rdatalen = My_Connections[Idx].rdatalen;
1431                                         My_Connections[Idx].rdatalen = 0;
1432                                         Log( LOG_DEBUG, "Moved already received data (%d bytes) to uncompression buffer.", My_Connections[Idx].zip.rdatalen );
1433                                 }
1434                         }
1435 #endif
1436                 }
1437                 
1438                 if( action ) result = TRUE;
1439         } while( action );
1440         
1441         return result;
1442 } /* Handle_Buffer */
1443
1444
1445 LOCAL VOID
1446 Check_Connections( VOID )
1447 {
1448         /* Pruefen, ob Verbindungen noch "alive" sind. Ist dies
1449          * nicht der Fall, zunaechst PING-PONG spielen und, wenn
1450          * auch das nicht "hilft", Client disconnectieren. */
1451
1452         CLIENT *c;
1453         LONG i;
1454
1455         for( i = 0; i < Pool_Size; i++ )
1456         {
1457                 if( My_Connections[i].sock == NONE ) continue;
1458
1459                 c = Client_GetFromConn( i );
1460                 if( c && (( Client_Type( c ) == CLIENT_USER ) || ( Client_Type( c ) == CLIENT_SERVER ) || ( Client_Type( c ) == CLIENT_SERVICE )))
1461                 {
1462                         /* verbundener User, Server oder Service */
1463                         if( My_Connections[i].lastping > My_Connections[i].lastdata )
1464                         {
1465                                 /* es wurde bereits ein PING gesendet */
1466                                 if( My_Connections[i].lastping < time( NULL ) - Conf_PongTimeout )
1467                                 {
1468                                         /* Timeout */
1469                                         Log( LOG_DEBUG, "Connection %d: Ping timeout: %d seconds.", i, Conf_PongTimeout );
1470                                         Conn_Close( i, NULL, "Ping timeout", TRUE );
1471                                 }
1472                         }
1473                         else if( My_Connections[i].lastdata < time( NULL ) - Conf_PingTimeout )
1474                         {
1475                                 /* es muss ein PING gesendet werden */
1476                                 Log( LOG_DEBUG, "Connection %d: sending PING ...", i );
1477                                 My_Connections[i].lastping = time( NULL );
1478                                 Conn_WriteStr( i, "PING :%s", Client_ID( Client_ThisServer( )));
1479                         }
1480                 }
1481                 else
1482                 {
1483                         /* noch nicht vollstaendig aufgebaute Verbindung */
1484                         if( My_Connections[i].lastdata < time( NULL ) - Conf_PingTimeout )
1485                         {
1486                                 /* Timeout */
1487                                 Log( LOG_DEBUG, "Connection %d timed out ...", i );
1488                                 Conn_Close( i, NULL, "Timeout", FALSE );
1489                         }
1490                 }
1491         }
1492 } /* Check_Connections */
1493
1494
1495 LOCAL VOID
1496 Check_Servers( VOID )
1497 {
1498         /* Pruefen, ob Server-Verbindungen aufgebaut werden
1499          * muessen bzw. koennen */
1500
1501         RES_STAT *s;
1502         LONG idx, n;
1503         INT i;
1504
1505         /* Wenn "Passive-Mode" aktiv: nicht verbinden */
1506         if( NGIRCd_Passive ) return;
1507
1508         for( i = 0; i < Conf_Server_Count; i++ )
1509         {
1510                 /* Ist ein Hostname und Port definiert? */
1511                 if(( ! Conf_Server[i].host[0] ) || ( ! Conf_Server[i].port > 0 )) continue;
1512
1513                 /* Haben wir schon eine Verbindung? */
1514                 for( n = 0; n < Pool_Size; n++ )
1515                 {
1516                         if( My_Connections[n].sock == NONE ) continue;
1517                         
1518                         /* Verbindung zu diesem Server? */
1519                         if( My_Connections[n].our_server == i )
1520                         {
1521                                 /* Komplett aufgebaute Verbindung? */
1522                                 if( My_Connections[n].sock > NONE ) break;
1523
1524                                 /* IP schon aufgeloest? */
1525                                 if( My_Connections[n].res_stat == NULL ) New_Server( i, n );
1526                         }
1527
1528                         /* Verbindung in dieser Server-Gruppe? */
1529                         if(( My_Connections[n].our_server != NONE ) && ( Conf_Server[i].group != NONE ))
1530                         {
1531                                 if( Conf_Server[My_Connections[n].our_server].group == Conf_Server[i].group ) break;
1532                         }
1533                 }
1534                 if( n < Pool_Size ) continue;
1535
1536                 /* Wann war der letzte Connect-Versuch? */
1537                 if( Conf_Server[i].lasttry > time( NULL ) - Conf_ConnectRetry ) continue;
1538
1539                 /* Okay, Verbindungsaufbau versuchen */
1540                 Conf_Server[i].lasttry = time( NULL );
1541
1542                 /* Freie Connection-Struktur suschen */
1543                 for( idx = 0; idx < Pool_Size; idx++ ) if( My_Connections[idx].sock == NONE ) break;
1544                 if( idx >= Pool_Size )
1545                 {
1546                         Log( LOG_ALERT, "Can't establist server connection: connection limit reached (%d)!", Pool_Size );
1547                         return;
1548                 }
1549                 Log( LOG_DEBUG, "Preparing connection %d for \"%s\" ...", idx, Conf_Server[i].host );
1550
1551                 /* Verbindungs-Struktur initialisieren */
1552                 Init_Conn_Struct( idx );
1553                 My_Connections[idx].sock = SERVER_WAIT;
1554                 My_Connections[idx].our_server = i;
1555
1556                 /* Hostnamen in IP aufloesen (Default bzw. im Fehlerfall: versuchen, den
1557                  * konfigurierten Text direkt als IP-Adresse zu verwenden ... */
1558                 strcpy( Conf_Server[My_Connections[idx].our_server].ip, Conf_Server[i].host );
1559                 strcpy( My_Connections[idx].host, Conf_Server[i].host );
1560                 s = Resolve_Name( Conf_Server[i].host );
1561                 if( s )
1562                 {
1563                         /* Sub-Prozess wurde asyncron gestartet */
1564                         My_Connections[idx].res_stat = s;
1565                 }
1566         }
1567 } /* Check_Servers */
1568
1569
1570 LOCAL VOID
1571 New_Server( INT Server, CONN_ID Idx )
1572 {
1573         /* Neue Server-Verbindung aufbauen */
1574
1575         struct sockaddr_in new_addr;
1576         struct in_addr inaddr;
1577         INT res, new_sock;
1578         CLIENT *c;
1579
1580         assert( Server > NONE );
1581         assert( Idx > NONE );
1582
1583         /* Wurde eine gueltige IP-Adresse gefunden? */
1584         if( ! Conf_Server[Server].ip[0] )
1585         {
1586                 /* Nein. Verbindung wieder freigeben: */
1587                 Init_Conn_Struct( Idx );
1588                 Log( LOG_ERR, "Can't connect to \"%s\" (connection %d): ip address unknown!", Conf_Server[Server].host, Idx );
1589                 return;
1590         }
1591
1592         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 );
1593
1594 #ifdef HAVE_INET_ATON
1595         if( inet_aton( Conf_Server[Server].ip, &inaddr ) == 0 )
1596 #else
1597         memset( &inaddr, 0, sizeof( inaddr ));
1598         inaddr.s_addr = inet_addr( Conf_Server[Server].ip );
1599         if( inaddr.s_addr == (unsigned)-1 )
1600 #endif
1601         {
1602                 /* Konnte Adresse nicht konvertieren */
1603                 Init_Conn_Struct( Idx );
1604                 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 );
1605                 return;
1606         }
1607
1608         memset( &new_addr, 0, sizeof( new_addr ));
1609         new_addr.sin_family = AF_INET;
1610         new_addr.sin_addr = inaddr;
1611         new_addr.sin_port = htons( Conf_Server[Server].port );
1612
1613         new_sock = socket( PF_INET, SOCK_STREAM, 0 );
1614         if ( new_sock < 0 )
1615         {
1616                 Init_Conn_Struct( Idx );
1617                 Log( LOG_CRIT, "Can't create socket: %s!", strerror( errno ));
1618                 return;
1619         }
1620
1621         if( ! Init_Socket( new_sock )) return;
1622
1623         res = connect( new_sock, (struct sockaddr *)&new_addr, sizeof( new_addr ));
1624         if(( res != 0 ) && ( errno != EINPROGRESS ))
1625         {
1626                 Log( LOG_CRIT, "Can't connect socket: %s!", strerror( errno ));
1627                 close( new_sock );
1628                 Init_Conn_Struct( Idx );
1629                 return;
1630         }
1631
1632         /* Client-Struktur initialisieren */
1633         c = Client_NewLocal( Idx, inet_ntoa( new_addr.sin_addr ), CLIENT_UNKNOWNSERVER, FALSE );
1634         if( ! c )
1635         {
1636                 close( new_sock );
1637                 Init_Conn_Struct( Idx );
1638                 Log( LOG_ALERT, "Can't establish connection: can't create client structure!" );
1639                 return;
1640         }
1641         Client_SetIntroducer( c, c );
1642         Client_SetToken( c, TOKEN_OUTBOUND );
1643
1644         /* Verbindung registrieren */
1645         My_Connections[Idx].sock = new_sock;
1646         My_Connections[Idx].addr = new_addr;
1647         strcpy( My_Connections[Idx].host, Conf_Server[Server].host );
1648
1649         /* Neuen Socket registrieren */
1650         FD_SET( new_sock, &My_Sockets );
1651         FD_SET( new_sock, &My_Connects );
1652         if( new_sock > Conn_MaxFD ) Conn_MaxFD = new_sock;
1653         
1654         Log( LOG_DEBUG, "Registered new connection %d on socket %d.", Idx, My_Connections[Idx].sock );
1655 } /* New_Server */
1656
1657
1658 LOCAL VOID
1659 Init_Conn_Struct( LONG Idx )
1660 {
1661         /* Connection-Struktur initialisieren */
1662
1663         My_Connections[Idx].sock = NONE;
1664         My_Connections[Idx].res_stat = NULL;
1665         My_Connections[Idx].host[0] = '\0';
1666         My_Connections[Idx].rbuf[0] = '\0';
1667         My_Connections[Idx].rdatalen = 0;
1668         My_Connections[Idx].wbuf[0] = '\0';
1669         My_Connections[Idx].wdatalen = 0;
1670         My_Connections[Idx].our_server = NONE;
1671         My_Connections[Idx].starttime = time( NULL );
1672         My_Connections[Idx].lastdata = time( NULL );
1673         My_Connections[Idx].lastping = 0;
1674         My_Connections[Idx].lastprivmsg = time( NULL );
1675         My_Connections[Idx].delaytime = 0;
1676         My_Connections[Idx].bytes_in = 0;
1677         My_Connections[Idx].bytes_out = 0;
1678         My_Connections[Idx].msg_in = 0;
1679         My_Connections[Idx].msg_out = 0;
1680         My_Connections[Idx].flag = 0;
1681         My_Connections[Idx].options = 0;
1682
1683 #ifdef USE_ZLIB
1684         My_Connections[Idx].zip.rbuf[0] = '\0';
1685         My_Connections[Idx].zip.rdatalen = 0;
1686         My_Connections[Idx].zip.wbuf[0] = '\0';
1687         My_Connections[Idx].zip.wdatalen = 0;
1688         My_Connections[Idx].zip.bytes_in = 0;
1689         My_Connections[Idx].zip.bytes_out = 0;
1690 #endif
1691 } /* Init_Conn_Struct */
1692
1693
1694 LOCAL BOOLEAN
1695 Init_Socket( INT Sock )
1696 {
1697         /* Socket-Optionen setzen */
1698
1699         INT on = 1;
1700
1701 #ifdef O_NONBLOCK       /* A/UX kennt das nicht? */
1702         if( fcntl( Sock, F_SETFL, O_NONBLOCK ) != 0 )
1703         {
1704                 Log( LOG_CRIT, "Can't enable non-blocking mode: %s!", strerror( errno ));
1705                 close( Sock );
1706                 return FALSE;
1707         }
1708 #endif
1709         if( setsockopt( Sock, SOL_SOCKET, SO_REUSEADDR, &on, (socklen_t)sizeof( on )) != 0)
1710         {
1711                 Log( LOG_ERR, "Can't set socket options: %s!", strerror( errno ));
1712                 /* dieser Fehler kann ignoriert werden. */
1713         }
1714
1715         return TRUE;
1716 } /* Init_Socket */
1717
1718
1719 LOCAL VOID
1720 Read_Resolver_Result( INT r_fd )
1721 {
1722         /* Ergebnis von Resolver Sub-Prozess aus Pipe lesen
1723          * und entsprechende Connection aktualisieren */
1724
1725         CHAR result[HOST_LEN];
1726         CLIENT *c;
1727         INT len, i;
1728
1729         FD_CLR( r_fd, &Resolver_FDs );
1730
1731         /* Anfrage vom Parent lesen */
1732         len = read( r_fd, result, HOST_LEN - 1 );
1733         if( len < 0 )
1734         {
1735                 /* Fehler beim Lesen aus der Pipe */
1736                 close( r_fd );
1737                 Log( LOG_CRIT, "Resolver: Can't read result: %s!", strerror( errno ));
1738                 return;
1739         }
1740         result[len] = '\0';
1741
1742         /* zugehoerige Connection suchen */
1743         for( i = 0; i < Pool_Size; i++ )
1744         {
1745                 if(( My_Connections[i].sock != NONE ) && ( My_Connections[i].res_stat ) && ( My_Connections[i].res_stat->pipe[0] == r_fd )) break;
1746         }
1747         if( i >= Pool_Size )
1748         {
1749                 /* Opsa! Keine passende Connection gefunden!? Vermutlich
1750                  * wurde sie schon wieder geschlossen. */
1751                 close( r_fd );
1752                 Log( LOG_DEBUG, "Resolver: Got result for unknown connection!?" );
1753                 return;
1754         }
1755
1756         Log( LOG_DEBUG, "Resolver: %s is \"%s\".", My_Connections[i].host, result );
1757         
1758         /* Aufraeumen */
1759         close( My_Connections[i].res_stat->pipe[0] );
1760         close( My_Connections[i].res_stat->pipe[1] );
1761         free( My_Connections[i].res_stat );
1762         My_Connections[i].res_stat = NULL;
1763
1764         if( My_Connections[i].sock > NONE )
1765         {
1766                 /* Eingehende Verbindung: Hostnamen setzen */
1767                 c = Client_GetFromConn( i );
1768                 assert( c != NULL );
1769                 strcpy( My_Connections[i].host, result );
1770                 Client_SetHostname( c, result );
1771         }
1772         else
1773         {
1774                 /* Ausgehende Verbindung (=Server): IP setzen */
1775                 assert( My_Connections[i].our_server > NONE );
1776                 strcpy( Conf_Server[My_Connections[i].our_server].ip, result );
1777         }
1778
1779         /* Penalty-Zeit zurueck setzen */
1780         Conn_ResetPenalty( i );
1781 } /* Read_Resolver_Result */
1782
1783
1784 #ifdef USE_ZLIB
1785
1786 LOCAL BOOLEAN
1787 Zip_Buffer( CONN_ID Idx, CHAR *Data, INT Len )
1788 {
1789         /* Daten zum Komprimieren im "Kompressions-Puffer" sammeln.
1790          * Es wird TRUE bei Erfolg, sonst FALSE geliefert. */
1791
1792         assert( Idx > NONE );
1793         assert( Data != NULL );
1794         assert( Len > 0 );
1795
1796         /* Ist noch Platz im Kompressions-Puffer? */
1797         if( ZWRITEBUFFER_LEN - My_Connections[Idx].zip.wdatalen < Len + 50 )
1798         {
1799                 /* Nein! Puffer zunaechst leeren ...*/
1800                 if( ! Zip_Flush( Idx )) return FALSE;
1801         }
1802
1803         /* Daten kopieren */
1804         memmove( My_Connections[Idx].zip.wbuf + My_Connections[Idx].zip.wdatalen, Data, Len );
1805         My_Connections[Idx].zip.wdatalen += Len;
1806
1807         return TRUE;
1808 } /* Zip_Buffer */
1809
1810
1811 LOCAL BOOLEAN
1812 Zip_Flush( CONN_ID Idx )
1813 {
1814         /* Daten komprimieren und in Schreibpuffer kopieren.
1815          * Es wird TRUE bei Erfolg, sonst FALSE geliefert. */
1816
1817         INT result, out_len;
1818         z_stream *out;
1819
1820         out = &My_Connections[Idx].zip.out;
1821
1822         out->next_in = My_Connections[Idx].zip.wbuf;
1823         out->avail_in = My_Connections[Idx].zip.wdatalen;
1824         out->next_out = My_Connections[Idx].wbuf + My_Connections[Idx].wdatalen;
1825         out->avail_out = WRITEBUFFER_LEN - My_Connections[Idx].wdatalen;
1826
1827         result = deflate( out, Z_SYNC_FLUSH );
1828         if(( result != Z_OK ) || ( out->avail_in > 0 ))
1829         {
1830                 Log( LOG_ALERT, "Compression error: code %d!?", result );
1831                 Conn_Close( Idx, "Compression error!", NULL, FALSE );
1832                 return FALSE;
1833         }
1834
1835         out_len = WRITEBUFFER_LEN - My_Connections[Idx].wdatalen - out->avail_out;
1836         My_Connections[Idx].wdatalen += out_len;
1837         My_Connections[Idx].bytes_out += out_len;
1838         My_Connections[Idx].zip.bytes_out += My_Connections[Idx].zip.wdatalen;
1839         My_Connections[Idx].zip.wdatalen = 0;
1840         
1841         return TRUE;
1842 } /* Zip_Flush */
1843
1844
1845 LOCAL BOOLEAN
1846 Unzip_Buffer( CONN_ID Idx )
1847 {
1848         /* Daten entpacken und in Lesepuffer kopieren. Bei Fehlern
1849          * wird FALSE geliefert, ansonsten TRUE. Der Fall, dass keine
1850          * Daten mehr zu entpacken sind, ist _kein_ Fehler! */
1851
1852         INT result, in_len, out_len;
1853         z_stream *in;
1854
1855         assert( Idx > NONE );
1856
1857         if( My_Connections[Idx].zip.rdatalen <= 0 ) return TRUE;
1858
1859         in = &My_Connections[Idx].zip.in;
1860
1861         in->next_in = My_Connections[Idx].zip.rbuf;
1862         in->avail_in = My_Connections[Idx].zip.rdatalen;
1863         in->next_out = My_Connections[Idx].rbuf + My_Connections[Idx].rdatalen;
1864         in->avail_out = READBUFFER_LEN - My_Connections[Idx].rdatalen - 1;
1865
1866         result = inflate( in, Z_SYNC_FLUSH );
1867         if( result != Z_OK )
1868         {
1869                 Log( LOG_ALERT, "Decompression error: code %d (ni=%d, ai=%d, no=%d, ao=%d)!?", result, in->next_in, in->avail_in, in->next_out, in->avail_out );
1870                 Conn_Close( Idx, "Decompression error!", NULL, FALSE );
1871                 return FALSE;
1872         }
1873
1874         in_len = My_Connections[Idx].zip.rdatalen - in->avail_in;
1875         out_len = READBUFFER_LEN - My_Connections[Idx].rdatalen - 1 - in->avail_out;
1876         My_Connections[Idx].rdatalen += out_len;
1877
1878         if( in->avail_in > 0 )
1879         {
1880                 /* es konnten nicht alle Daten entpackt werden, vermutlich war
1881                  * im Ziel-Puffer kein Platz mehr. Umkopieren ... */
1882                 My_Connections[Idx].zip.rdatalen -= in_len;
1883                 memmove( My_Connections[Idx].zip.rbuf, My_Connections[Idx].zip.rbuf + in_len, My_Connections[Idx].zip.rdatalen );
1884         }
1885         else My_Connections[Idx].zip.rdatalen = 0;
1886         My_Connections[Idx].zip.bytes_in += out_len;
1887
1888         return TRUE;
1889 } /* Unzip_Buffer */
1890
1891
1892 #endif
1893
1894
1895 /* -eof- */