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