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