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