]> arthur.barton.de Git - ngircd-alex.git/blob - src/ngircd/conn.c
Made ngIRCd compile on HP/UX 10.20 with native HP pre-ANSI C compiler and
[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.140 2004/10/20 13:47:32 alex 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 BOOLEAN 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 BOOLEAN Try_Write PARAMS(( CONN_ID Idx ));
90 LOCAL BOOLEAN 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 BOOLEAN 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 BOOLEAN
253 Conn_NewListener( CONST UINT 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         BOOLEAN 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 BOOLEAN
507 Conn_WriteStr( CONN_ID Idx, CHAR *Format, ... )
508 #else
509 GLOBAL BOOLEAN
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         BOOLEAN 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 BOOLEAN
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, BOOLEAN 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                 return;
636         }
637
638         assert( My_Connections[Idx].sock > NONE );
639
640         /* Mark link as "closing" */
641         My_Connections[Idx].options |= CONN_ISCLOSING;
642                 
643         if( LogMsg ) txt = LogMsg;
644         else txt = FwdMsg;
645         if( ! txt ) txt = "Reason unknown";
646
647         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 ));
648
649         /* Search client, if any */
650         c = Client_GetFromConn( Idx );
651
652         /* Should the client be informed? */
653         if( InformClient )
654         {
655 #ifndef STRICT_RFC
656                 /* Send statistics to client if registered as user: */
657                 if(( c != NULL ) && ( Client_Type( c ) == CLIENT_USER ))
658                 {
659                         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 );
660                 }
661 #endif
662
663                 /* Send ERROR to client (see RFC!) */
664                 if( FwdMsg ) Conn_WriteStr( Idx, "ERROR :%s", FwdMsg );
665                 else Conn_WriteStr( Idx, "ERROR :Closing connection." );
666         }
667
668         /* Try to write out the write buffer */
669         (VOID)Try_Write( Idx );
670
671         /* Shut down socket */
672         if( close( My_Connections[Idx].sock ) != 0 )
673         {
674                 /* Oops, we can't close the socket!? This is fatal! */
675                 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 ));
676                 Log( LOG_ALERT, "%s exiting due to fatal errors!", PACKAGE_NAME );
677                 exit( 1 );
678         }
679
680         /* Mark socket as invalid: */
681         FD_CLR( My_Connections[Idx].sock, &My_Sockets );
682         FD_CLR( My_Connections[Idx].sock, &My_Connects );
683         My_Connections[Idx].sock = NONE;
684
685         /* If there is still a client, unregister it now */
686         if( c ) Client_Destroy( c, LogMsg, FwdMsg, TRUE );
687
688         /* Calculate statistics and log information */
689         in_k = (DOUBLE)My_Connections[Idx].bytes_in / 1024;
690         out_k = (DOUBLE)My_Connections[Idx].bytes_out / 1024;
691 #ifdef ZLIB
692         if( My_Connections[Idx].options & CONN_ZIP )
693         {
694                 in_z_k = (DOUBLE)My_Connections[Idx].zip.bytes_in / 1024;
695                 out_z_k = (DOUBLE)My_Connections[Idx].zip.bytes_out / 1024;
696                 in_p = (INT)(( in_k * 100 ) / in_z_k );
697                 out_p = (INT)(( out_k * 100 ) / out_z_k );
698                 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 );
699         }
700         else
701 #endif
702         {
703                 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 );
704         }
705
706         /* Is there a resolver sub-process running? */
707         if( My_Connections[Idx].res_stat )
708         {
709                 /* Free resolver structures */
710                 FD_CLR( My_Connections[Idx].res_stat->pipe[0], &Resolver_FDs );
711                 close( My_Connections[Idx].res_stat->pipe[0] );
712                 close( My_Connections[Idx].res_stat->pipe[1] );
713                 free( My_Connections[Idx].res_stat );
714         }
715
716         /* Servers: Modify time of next connect attempt? */
717         Conf_UnsetServer( Idx );
718
719 #ifdef ZLIB
720         /* Clean up zlib, if link was compressed */
721         if( Conn_Options( Idx ) & CONN_ZIP )
722         {
723                 inflateEnd( &My_Connections[Idx].zip.in );
724                 deflateEnd( &My_Connections[Idx].zip.out );
725         }
726 #endif
727
728         /* Clean up connection structure (=free it) */
729         Init_Conn_Struct( Idx );
730 } /* Conn_Close */
731
732
733 GLOBAL VOID
734 Conn_SyncServerStruct( VOID )
735 {
736         /* Synchronize server structures (connection IDs):
737          * connections <-> configuration */
738
739         CLIENT *client;
740         CONN_ID i;
741         INT c;
742
743         for( i = 0; i < Pool_Size; i++ )
744         {
745                 /* Established connection? */
746                 if( My_Connections[i].sock <= NONE ) continue;
747
748                 /* Server connection? */
749                 client = Client_GetFromConn( i );
750                 if(( ! client ) || ( Client_Type( client ) != CLIENT_SERVER )) continue;
751
752                 for( c = 0; c < MAX_SERVERS; c++ )
753                 {
754                         /* Configured server? */
755                         if( ! Conf_Server[c].host[0] ) continue;
756
757                         /* Duplicate? */
758                         if( strcmp( Conf_Server[c].name, Client_ID( client )) == 0 ) Conf_Server[c].conn_id = i;
759                 }
760         }
761 } /* SyncServerStruct */
762
763
764 LOCAL BOOLEAN
765 Try_Write( CONN_ID Idx )
766 {
767         /* Versuchen, Daten aus dem Schreib-Puffer in den Socket zu
768          * schreiben. TRUE wird geliefert, wenn entweder keine Daten
769          * zum Versenden vorhanden sind oder erfolgreich bearbeitet
770          * werden konnten. Im Fehlerfall wird FALSE geliefert und
771          * die Verbindung geschlossen. */
772
773         fd_set write_socket;
774         struct timeval tv;
775
776         assert( Idx > NONE );
777         assert( My_Connections[Idx].sock > NONE );
778
779         /* sind ueberhaupt Daten vorhanden? */
780 #ifdef ZLIB
781         if(( ! My_Connections[Idx].wdatalen > 0 ) && ( ! My_Connections[Idx].zip.wdatalen )) return TRUE;
782 #else
783         if( ! My_Connections[Idx].wdatalen > 0 ) return TRUE;
784 #endif
785
786         /* Timeout initialisieren: 0 Sekunden, also nicht blockieren */
787         tv.tv_sec = 0; tv.tv_usec = 0;
788
789         FD_ZERO( &write_socket );
790         FD_SET( My_Connections[Idx].sock, &write_socket );
791         if( select( My_Connections[Idx].sock + 1, NULL, &write_socket, NULL, &tv ) == -1 )
792         {
793                 /* Fehler! */
794                 if( errno != EINTR )
795                 {
796                         Log( LOG_ALERT, "Try_Write(): select() failed: %s (con=%d, sock=%d)!", strerror( errno ), Idx, My_Connections[Idx].sock );
797                         Conn_Close( Idx, "Server error!", NULL, FALSE );
798                         return FALSE;
799                 }
800         }
801
802         if( FD_ISSET( My_Connections[Idx].sock, &write_socket )) return Handle_Write( Idx );
803         else return TRUE;
804 } /* Try_Write */
805
806
807 LOCAL VOID
808 Handle_Read( INT Sock )
809 {
810         /* Aktivitaet auf einem Socket verarbeiten:
811          *  - neue Clients annehmen,
812          *  - Daten von Clients verarbeiten,
813          *  - Resolver-Rueckmeldungen annehmen. */
814
815         CONN_ID idx;
816
817         assert( Sock > NONE );
818
819         if( FD_ISSET( Sock, &My_Listeners ))
820         {
821                 /* es ist einer unserer Listener-Sockets: es soll
822                  * also eine neue Verbindung aufgebaut werden. */
823
824                 New_Connection( Sock );
825         }
826         else if( FD_ISSET( Sock, &Resolver_FDs ))
827         {
828                 /* Rueckmeldung von einem Resolver Sub-Prozess */
829
830                 Read_Resolver_Result( Sock );
831         }
832         else
833         {
834                 /* Ein Client Socket: entweder ein User oder Server */
835
836                 idx = Socket2Index( Sock );
837                 if( idx > NONE ) Read_Request( idx );
838         }
839 } /* Handle_Read */
840
841
842 LOCAL BOOLEAN
843 Handle_Write( CONN_ID Idx )
844 {
845         /* Daten aus Schreibpuffer versenden bzw. Connection aufbauen */
846
847         INT len, res, err;
848         socklen_t sock_len;
849         CLIENT *c;
850
851         assert( Idx > NONE );
852         assert( My_Connections[Idx].sock > NONE );
853
854         if( FD_ISSET( My_Connections[Idx].sock, &My_Connects ))
855         {
856                 /* es soll nichts geschrieben werden, sondern ein
857                  * connect() hat ein Ergebnis geliefert */
858
859                 FD_CLR( My_Connections[Idx].sock, &My_Connects );
860
861                 /* Ergebnis des connect() ermitteln */
862                 sock_len = sizeof( err );
863                 res = getsockopt( My_Connections[Idx].sock, SOL_SOCKET, SO_ERROR, &err, &sock_len );
864                 assert( sock_len == sizeof( err ));
865
866                 /* Fehler aufgetreten? */
867                 if(( res != 0 ) || ( err != 0 ))
868                 {
869                         /* Fehler! */
870                         if( res != 0 ) Log( LOG_CRIT, "getsockopt (connection %d): %s!", Idx, strerror( errno ));
871                         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 ));
872
873                         /* Clean up socket, connection and client structures */
874                         FD_CLR( My_Connections[Idx].sock, &My_Sockets );
875                         c = Client_GetFromConn( Idx );
876                         if( c ) Client_DestroyNow( c );
877                         close( My_Connections[Idx].sock );
878                         Init_Conn_Struct( Idx );
879
880                         /* Bei Server-Verbindungen lasttry-Zeitpunkt auf "jetzt" setzen */
881                         Conf_Server[Conf_GetServer( Idx )].lasttry = time( NULL );
882                         Conf_UnsetServer( Idx );
883
884                         return FALSE;
885                 }
886                 Log( LOG_INFO, "Connection %d with \"%s:%d\" established. Now logging in ...", Idx, My_Connections[Idx].host, Conf_Server[Conf_GetServer( Idx )].port );
887
888                 /* Send PASS and SERVER command to peer */
889                 Conn_WriteStr( Idx, "PASS %s %s", Conf_Server[Conf_GetServer( Idx )].pwd_out, NGIRCd_ProtoID );
890                 return Conn_WriteStr( Idx, "SERVER %s :%s", Conf_ServerName, Conf_ServerInfo );
891         }
892
893 #ifdef ZLIB
894         /* Schreibpuffer leer, aber noch Daten im Kompressionsbuffer?
895          * Dann muss dieser nun geflushed werden! */
896         if( My_Connections[Idx].wdatalen == 0 ) Zip_Flush( Idx );
897 #endif
898
899         assert( My_Connections[Idx].wdatalen > 0 );
900
901         /* Daten schreiben */
902         len = send( My_Connections[Idx].sock, My_Connections[Idx].wbuf, My_Connections[Idx].wdatalen, 0 );
903         if( len < 0 )
904         {
905                 /* Operation haette Socket "nur" blockiert ... */
906                 if( errno == EAGAIN ) return TRUE;
907
908                 /* Oops, ein Fehler! */
909                 Log( LOG_ERR, "Write error on connection %d (socket %d): %s!", Idx, My_Connections[Idx].sock, strerror( errno ));
910                 Conn_Close( Idx, "Write error!", NULL, FALSE );
911                 return FALSE;
912         }
913
914         /* Puffer anpassen */
915         My_Connections[Idx].wdatalen -= len;
916         memmove( My_Connections[Idx].wbuf, My_Connections[Idx].wbuf + len, My_Connections[Idx].wdatalen );
917
918         return TRUE;
919 } /* Handle_Write */
920
921
922 LOCAL VOID
923 New_Connection( INT Sock )
924 {
925         /* Neue Client-Verbindung von Listen-Socket annehmen und
926          * CLIENT-Struktur anlegen. */
927
928 #ifdef TCPWRAP
929         struct request_info req;
930 #endif
931         struct sockaddr_in new_addr;
932         INT new_sock, new_sock_len;
933         RES_STAT *s;
934         CONN_ID idx;
935         CLIENT *c;
936         POINTER *ptr;
937         LONG new_size, cnt;
938
939         assert( Sock > NONE );
940
941         /* Connection auf Listen-Socket annehmen */
942         new_sock_len = sizeof( new_addr );
943         new_sock = accept( Sock, (struct sockaddr *)&new_addr, (socklen_t *)&new_sock_len );
944         if( new_sock < 0 )
945         {
946                 Log( LOG_CRIT, "Can't accept connection: %s!", strerror( errno ));
947                 return;
948         }
949
950 #ifdef TCPWRAP
951         /* Validate socket using TCP Wrappers */
952         request_init( &req, RQ_DAEMON, PACKAGE_NAME, RQ_FILE, new_sock, RQ_CLIENT_SIN, &new_addr, NULL );
953         fromhost(&req);
954         if( ! hosts_access( &req ))
955         {
956                 /* Access denied! */
957                 Log( deny_severity, "Refused connection from %s (by TCP Wrappers)!", inet_ntoa( new_addr.sin_addr ));
958                 Simple_Message( new_sock, "ERROR :Connection refused" );
959                 close( new_sock );
960                 return;
961         }
962 #endif
963
964         /* Socket initialisieren */
965         Init_Socket( new_sock );
966         
967         /* Check IP-based connection limit */
968         cnt = Count_Connections( new_addr );
969         if(( Conf_MaxConnectionsIP > 0 ) && ( cnt >= Conf_MaxConnectionsIP ))
970         {
971                 /* Access denied, too many connections from this IP address! */
972                 Log( LOG_ERR, "Refused connection from %s: too may connections (%ld) from this IP address!", inet_ntoa( new_addr.sin_addr ), cnt);
973                 Simple_Message( new_sock, "ERROR :Connection refused, too many connections from your IP address!" );
974                 close( new_sock );
975                 return;
976         }
977
978         /* Freie Connection-Struktur suchen */
979         for( idx = 0; idx < Pool_Size; idx++ ) if( My_Connections[idx].sock == NONE ) break;
980         if( idx >= Pool_Size )
981         {
982                 new_size = Pool_Size + CONNECTION_POOL;
983
984                 /* Im bisherigen Pool wurde keine freie Connection-Struktur mehr gefunden.
985                  * Wenn erlaubt und moeglich muss nun der Pool vergroessert werden: */
986
987                 if( Conf_MaxConnections > 0 )
988                 {
989                         /* Es ist ein Limit konfiguriert */
990                         if( Pool_Size >= Conf_MaxConnections )
991                         {
992                                 /* Mehr Verbindungen duerfen wir leider nicht mehr annehmen ... */
993                                 Log( LOG_ALERT, "Can't accept connection: limit (%d) reached!", Pool_Size );
994                                 Simple_Message( new_sock, "ERROR :Connection limit reached" );
995                                 close( new_sock );
996                                 return;
997                         }
998                         if( new_size > Conf_MaxConnections ) new_size = Conf_MaxConnections;
999                 }
1000                 if( new_size < Pool_Size )
1001                 {
1002                         Log( LOG_ALERT, "Can't accespt connection: limit (%d) reached -- overflow!", Pool_Size );
1003                         Simple_Message( new_sock, "ERROR :Connection limit reached" );
1004                         close( new_sock );
1005                         return;
1006                 }
1007
1008                 /* zunaechst realloc() versuchen; wenn das scheitert, malloc() versuchen
1009                  * und Daten ggf. "haendisch" umkopieren. (Haesslich! Eine wirklich
1010                  * dynamische Verwaltung waere wohl _deutlich_ besser ...) */
1011                 ptr = (POINTER *)realloc( My_Connections, sizeof( CONNECTION ) * new_size );
1012                 if( ! ptr )
1013                 {
1014                         /* realloc() ist fehlgeschlagen. Nun malloc() probieren: */
1015                         ptr = (POINTER *)malloc( sizeof( CONNECTION ) * new_size );
1016                         if( ! ptr )
1017                         {
1018                                 /* Offenbar steht kein weiterer Sepeicher zur Verfuegung :-( */
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                         /* Struktur umkopieren ... */
1026                         memcpy( ptr, My_Connections, sizeof( CONNECTION ) * Pool_Size );
1027
1028 #ifdef DEBUG
1029                         Log( LOG_DEBUG, "Allocated new connection pool for %ld items (%ld bytes). [malloc()/memcpy()]", new_size, sizeof( CONNECTION ) * new_size );
1030 #endif
1031                 }
1032 #ifdef DEBUG
1033                 else Log( LOG_DEBUG, "Allocated new connection pool for %ld items (%ld bytes). [realloc()]", new_size, sizeof( CONNECTION ) * new_size );
1034 #endif
1035
1036                 /* Adjust pointer to new block */
1037                 My_Connections = (CONNECTION *)ptr;
1038
1039                 /* Initialize new items */
1040                 for( idx = Pool_Size; idx < new_size; idx++ ) Init_Conn_Struct( idx );
1041                 idx = Pool_Size;
1042
1043                 /* Adjust new pool size */
1044                 Pool_Size = new_size;
1045         }
1046
1047         /* Client-Struktur initialisieren */
1048         c = Client_NewLocal( idx, inet_ntoa( new_addr.sin_addr ), CLIENT_UNKNOWN, FALSE );
1049         if( ! c )
1050         {
1051                 Log( LOG_ALERT, "Can't accept connection: can't create client structure!" );
1052                 Simple_Message( new_sock, "ERROR :Internal error" );
1053                 close( new_sock );
1054                 return;
1055         }
1056
1057         /* Verbindung registrieren */
1058         Init_Conn_Struct( idx );
1059         My_Connections[idx].sock = new_sock;
1060         My_Connections[idx].addr = new_addr;
1061
1062         /* Neuen Socket registrieren */
1063         FD_SET( new_sock, &My_Sockets );
1064         if( new_sock > Conn_MaxFD ) Conn_MaxFD = new_sock;
1065
1066         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 );
1067
1068         /* Hostnamen ermitteln */
1069         strlcpy( My_Connections[idx].host, inet_ntoa( new_addr.sin_addr ), sizeof( My_Connections[idx].host ));
1070         Client_SetHostname( c, My_Connections[idx].host );
1071 #ifdef IDENTAUTH
1072         s = Resolve_Addr( &new_addr, My_Connections[idx].sock );
1073 #else
1074         s = Resolve_Addr( &new_addr );
1075 #endif
1076         if( s )
1077         {
1078                 /* Sub-Prozess wurde asyncron gestartet */
1079                 My_Connections[idx].res_stat = s;
1080         }
1081
1082         /* Penalty-Zeit setzen */
1083         Conn_SetPenalty( idx, 4 );
1084 } /* New_Connection */
1085
1086
1087 LOCAL CONN_ID
1088 Socket2Index( INT Sock )
1089 {
1090         /* zum Socket passende Connection suchen */
1091
1092         CONN_ID idx;
1093
1094         assert( Sock > NONE );
1095
1096         for( idx = 0; idx < Pool_Size; idx++ ) if( My_Connections[idx].sock == Sock ) break;
1097
1098         if( idx >= Pool_Size )
1099         {
1100                 /* die Connection wurde vermutlich (wegen eines
1101                  * Fehlers) bereits wieder abgebaut ... */
1102 #ifdef DEBUG
1103                 Log( LOG_DEBUG, "Socket2Index: can't get connection for socket %d!", Sock );
1104 #endif
1105                 return NONE;
1106         }
1107         else return idx;
1108 } /* Socket2Index */
1109
1110
1111 LOCAL VOID
1112 Read_Request( CONN_ID Idx )
1113 {
1114         /* Daten von Socket einlesen und entsprechend behandeln.
1115          * Tritt ein Fehler auf, so wird der Socket geschlossen. */
1116
1117         INT len, bsize;
1118 #ifdef ZLIB
1119         CLIENT *c;
1120 #endif
1121
1122         assert( Idx > NONE );
1123         assert( My_Connections[Idx].sock > NONE );
1124
1125         /* wenn noch nicht registriert: maximal mit ZREADBUFFER_LEN arbeiten,
1126          * ansonsten koennen Daten ggf. nicht umkopiert werden. */
1127         bsize = READBUFFER_LEN;
1128 #ifdef ZLIB
1129         c = Client_GetFromConn( Idx );
1130         if(( Client_Type( c ) != CLIENT_USER ) && ( Client_Type( c ) != CLIENT_SERVER ) && ( Client_Type( c ) != CLIENT_SERVICE ) && ( bsize > ZREADBUFFER_LEN )) bsize = ZREADBUFFER_LEN;
1131 #endif
1132
1133 #ifdef ZLIB
1134         if(( bsize - My_Connections[Idx].rdatalen - 1 < 1 ) || ( ZREADBUFFER_LEN - My_Connections[Idx].zip.rdatalen < 1 ))
1135 #else
1136         if( bsize - My_Connections[Idx].rdatalen - 1 < 1 )
1137 #endif
1138         {
1139                 /* Der Lesepuffer ist voll */
1140                 Log( LOG_ERR, "Receive buffer overflow (connection %d): %d bytes!", Idx, My_Connections[Idx].rdatalen );
1141                 Conn_Close( Idx, "Receive buffer overflow!", NULL, FALSE );
1142                 return;
1143         }
1144
1145 #ifdef ZLIB
1146         if( My_Connections[Idx].options & CONN_ZIP )
1147         {
1148                 len = recv( My_Connections[Idx].sock, My_Connections[Idx].zip.rbuf + My_Connections[Idx].zip.rdatalen, ( ZREADBUFFER_LEN - My_Connections[Idx].zip.rdatalen ), 0 );
1149                 if( len > 0 ) My_Connections[Idx].zip.rdatalen += len;
1150         }
1151         else
1152 #endif
1153         {
1154                 len = recv( My_Connections[Idx].sock, My_Connections[Idx].rbuf + My_Connections[Idx].rdatalen, bsize - My_Connections[Idx].rdatalen - 1, 0 );
1155                 if( len > 0 ) My_Connections[Idx].rdatalen += len;
1156         }
1157
1158         if( len == 0 )
1159         {
1160                 /* Socket wurde geschlossen */
1161                 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 ));
1162                 Conn_Close( Idx, "Socket closed!", "Client closed connection", FALSE );
1163                 return;
1164         }
1165
1166         if( len < 0 )
1167         {
1168                 /* Operation haette Socket "nur" blockiert ... */
1169                 if( errno == EAGAIN ) return;
1170
1171                 /* Fehler beim Lesen */
1172                 Log( LOG_ERR, "Read error on connection %d (socket %d): %s!", Idx, My_Connections[Idx].sock, strerror( errno ));
1173                 Conn_Close( Idx, "Read error!", "Client closed connection", FALSE );
1174                 return;
1175         }
1176
1177         /* Connection-Statistik aktualisieren */
1178         My_Connections[Idx].bytes_in += len;
1179
1180         /* Timestamp aktualisieren */
1181         My_Connections[Idx].lastdata = time( NULL );
1182
1183         Handle_Buffer( Idx );
1184 } /* Read_Request */
1185
1186
1187 LOCAL BOOLEAN
1188 Handle_Buffer( CONN_ID Idx )
1189 {
1190         /* Daten im Lese-Puffer einer Verbindung verarbeiten.
1191          * Wurde ein Request verarbeitet, so wird TRUE geliefert,
1192          * ansonsten FALSE (auch bei Fehlern). */
1193
1194 #ifndef STRICT_RFC
1195         CHAR *ptr1, *ptr2;
1196 #endif
1197         CHAR *ptr;
1198         INT len, delta;
1199         BOOLEAN action, result;
1200 #ifdef ZLIB
1201         BOOLEAN old_z;
1202 #endif
1203
1204         result = FALSE;
1205         do
1206         {
1207                 /* Check penalty */
1208                 if( My_Connections[Idx].delaytime > time( NULL )) return result;
1209                 
1210 #ifdef ZLIB
1211                 /* ggf. noch unkomprimiete Daten weiter entpacken */
1212                 if( My_Connections[Idx].options & CONN_ZIP )
1213                 {
1214                         if( ! Unzip_Buffer( Idx )) return FALSE;
1215                 }
1216 #endif
1217
1218                 if( My_Connections[Idx].rdatalen < 1 ) break;
1219
1220                 /* Eine komplette Anfrage muss mit CR+LF enden, vgl.
1221                  * RFC 2812. Haben wir eine? */
1222                 My_Connections[Idx].rbuf[My_Connections[Idx].rdatalen] = '\0';
1223                 ptr = strstr( My_Connections[Idx].rbuf, "\r\n" );
1224
1225                 if( ptr ) delta = 2;
1226 #ifndef STRICT_RFC
1227                 else
1228                 {
1229                         /* Nicht RFC-konforme Anfrage mit nur CR oder LF? Leider
1230                          * machen soetwas viele Clients, u.a. "mIRC" :-( */
1231                         ptr1 = strchr( My_Connections[Idx].rbuf, '\r' );
1232                         ptr2 = strchr( My_Connections[Idx].rbuf, '\n' );
1233                         delta = 1;
1234                         if( ptr1 && ptr2 ) ptr = ptr1 > ptr2 ? ptr2 : ptr1;
1235                         else if( ptr1 ) ptr = ptr1;
1236                         else if( ptr2 ) ptr = ptr2;
1237                 }
1238 #endif
1239
1240                 action = FALSE;
1241                 if( ptr )
1242                 {
1243                         /* Ende der Anfrage wurde gefunden */
1244                         *ptr = '\0';
1245                         len = ( ptr - My_Connections[Idx].rbuf ) + delta;
1246                         if( len > ( COMMAND_LEN - 1 ))
1247                         {
1248                                 /* Eine Anfrage darf(!) nicht laenger als 512 Zeichen
1249                                  * (incl. CR+LF!) werden; vgl. RFC 2812. Wenn soetwas
1250                                  * empfangen wird, wird der Client disconnectiert. */
1251                                 Log( LOG_ERR, "Request too long (connection %d): %d bytes (max. %d expected)!", Idx, My_Connections[Idx].rdatalen, COMMAND_LEN - 1 );
1252                                 Conn_Close( Idx, NULL, "Request too long", TRUE );
1253                                 return FALSE;
1254                         }
1255
1256 #ifdef ZLIB
1257                         /* merken, ob Stream bereits komprimiert wird */
1258                         old_z = My_Connections[Idx].options & CONN_ZIP;
1259 #endif
1260
1261                         if( len > delta )
1262                         {
1263                                 /* Es wurde ein Request gelesen */
1264                                 My_Connections[Idx].msg_in++;
1265                                 if( ! Parse_Request( Idx, My_Connections[Idx].rbuf )) return FALSE;
1266                                 else action = TRUE;
1267                         }
1268
1269                         /* Puffer anpassen */
1270                         My_Connections[Idx].rdatalen -= len;
1271                         memmove( My_Connections[Idx].rbuf, My_Connections[Idx].rbuf + len, My_Connections[Idx].rdatalen );
1272
1273 #ifdef ZLIB
1274                         if(( ! old_z ) && ( My_Connections[Idx].options & CONN_ZIP ) && ( My_Connections[Idx].rdatalen > 0 ))
1275                         {
1276                                 /* Mit dem letzten Befehl wurde Socket-Kompression aktiviert.
1277                                  * Evtl. schon vom Socket gelesene Daten in den Unzip-Puffer
1278                                  * umkopieren, damit diese nun zunaechst entkomprimiert werden */
1279                                 {
1280                                         if( My_Connections[Idx].rdatalen > ZREADBUFFER_LEN )
1281                                         {
1282                                                 /* Hupsa! Soviel Platz haben wir aber gar nicht! */
1283                                                 Log( LOG_ALERT, "Can't move receive buffer: No space left in unzip buffer (need %d bytes)!", My_Connections[Idx].rdatalen );
1284                                                 return FALSE;
1285                                         }
1286                                         memcpy( My_Connections[Idx].zip.rbuf, My_Connections[Idx].rbuf, My_Connections[Idx].rdatalen );
1287                                         My_Connections[Idx].zip.rdatalen = My_Connections[Idx].rdatalen;
1288                                         My_Connections[Idx].rdatalen = 0;
1289 #ifdef DEBUG
1290                                         Log( LOG_DEBUG, "Moved already received data (%d bytes) to uncompression buffer.", My_Connections[Idx].zip.rdatalen );
1291 #endif
1292                                 }
1293                         }
1294 #endif
1295                 }
1296
1297                 if( action ) result = TRUE;
1298         } while( action );
1299
1300         return result;
1301 } /* Handle_Buffer */
1302
1303
1304 LOCAL VOID
1305 Check_Connections( VOID )
1306 {
1307         /* Pruefen, ob Verbindungen noch "alive" sind. Ist dies
1308          * nicht der Fall, zunaechst PING-PONG spielen und, wenn
1309          * auch das nicht "hilft", Client disconnectieren. */
1310
1311         CLIENT *c;
1312         CONN_ID i;
1313
1314         for( i = 0; i < Pool_Size; i++ )
1315         {
1316                 if( My_Connections[i].sock == NONE ) continue;
1317
1318                 c = Client_GetFromConn( i );
1319                 if( c && (( Client_Type( c ) == CLIENT_USER ) || ( Client_Type( c ) == CLIENT_SERVER ) || ( Client_Type( c ) == CLIENT_SERVICE )))
1320                 {
1321                         /* verbundener User, Server oder Service */
1322                         if( My_Connections[i].lastping > My_Connections[i].lastdata )
1323                         {
1324                                 /* es wurde bereits ein PING gesendet */
1325                                 if( My_Connections[i].lastping < time( NULL ) - Conf_PongTimeout )
1326                                 {
1327                                         /* Timeout */
1328 #ifdef DEBUG
1329                                         Log( LOG_DEBUG, "Connection %d: Ping timeout: %d seconds.", i, Conf_PongTimeout );
1330 #endif
1331                                         Conn_Close( i, NULL, "Ping timeout", TRUE );
1332                                 }
1333                         }
1334                         else if( My_Connections[i].lastdata < time( NULL ) - Conf_PingTimeout )
1335                         {
1336                                 /* es muss ein PING gesendet werden */
1337 #ifdef DEBUG
1338                                 Log( LOG_DEBUG, "Connection %d: sending PING ...", i );
1339 #endif
1340                                 My_Connections[i].lastping = time( NULL );
1341                                 Conn_WriteStr( i, "PING :%s", Client_ID( Client_ThisServer( )));
1342                         }
1343                 }
1344                 else
1345                 {
1346                         /* noch nicht vollstaendig aufgebaute Verbindung */
1347                         if( My_Connections[i].lastdata < time( NULL ) - Conf_PingTimeout )
1348                         {
1349                                 /* Timeout */
1350 #ifdef DEBUG
1351                                 Log( LOG_DEBUG, "Connection %d timed out ...", i );
1352 #endif
1353                                 Conn_Close( i, NULL, "Timeout", FALSE );
1354                         }
1355                 }
1356         }
1357 } /* Check_Connections */
1358
1359
1360 LOCAL VOID
1361 Check_Servers( VOID )
1362 {
1363         /* Check if we can establish further server links */
1364
1365         RES_STAT *s;
1366         CONN_ID idx;
1367         INT i, n;
1368
1369         /* Serach all connections, are there results from the resolver? */
1370         for( idx = 0; idx < Pool_Size; idx++ )
1371         {
1372                 if( My_Connections[idx].sock != SERVER_WAIT ) continue;
1373
1374                 /* IP resolved? */
1375                 if( My_Connections[idx].res_stat == NULL ) New_Server( Conf_GetServer( idx ), idx );
1376         }
1377
1378         /* Check all configured servers */
1379         for( i = 0; i < MAX_SERVERS; i++ )
1380         {
1381                 /* Valid outgoing server which isn't already connected or disabled? */
1382                 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;
1383
1384                 /* Is there already a connection in this group? */
1385                 if( Conf_Server[i].group > NONE )
1386                 {
1387                         for( n = 0; n < MAX_SERVERS; n++ )
1388                         {
1389                                 if( n == i ) continue;
1390                                 if(( Conf_Server[n].conn_id > NONE ) && ( Conf_Server[n].group == Conf_Server[i].group )) break;
1391                         }
1392                         if( n < MAX_SERVERS ) continue;
1393                 }
1394
1395                 /* Check last connect attempt? */
1396                 if( Conf_Server[i].lasttry > time( NULL ) - Conf_ConnectRetry ) continue;
1397
1398                 /* Okay, try to connect now */
1399                 Conf_Server[i].lasttry = time( NULL );
1400
1401                 /* Search free connection structure */
1402                 for( idx = 0; idx < Pool_Size; idx++ ) if( My_Connections[idx].sock == NONE ) break;
1403                 if( idx >= Pool_Size )
1404                 {
1405                         Log( LOG_ALERT, "Can't establist server connection: connection limit reached (%d)!", Pool_Size );
1406                         return;
1407                 }
1408 #ifdef DEBUG
1409                 Log( LOG_DEBUG, "Preparing connection %d for \"%s\" ...", idx, Conf_Server[i].host );
1410 #endif
1411
1412                 /* Verbindungs-Struktur initialisieren */
1413                 Init_Conn_Struct( idx );
1414                 My_Connections[idx].sock = SERVER_WAIT;
1415                 Conf_Server[i].conn_id = idx;
1416
1417                 /* Resolve Hostname. If this fails, try to use it as an IP address */
1418                 strlcpy( Conf_Server[i].ip, Conf_Server[i].host, sizeof( Conf_Server[i].ip ));
1419                 strlcpy( My_Connections[idx].host, Conf_Server[i].host, sizeof( My_Connections[idx].host ));
1420                 s = Resolve_Name( Conf_Server[i].host );
1421                 if( s )
1422                 {
1423                         /* Sub-Prozess wurde asyncron gestartet */
1424                         My_Connections[idx].res_stat = s;
1425                 }
1426         }
1427 } /* Check_Servers */
1428
1429
1430 LOCAL VOID
1431 New_Server( INT Server, CONN_ID Idx )
1432 {
1433         /* Establish new server link */
1434
1435         struct sockaddr_in new_addr;
1436         struct in_addr inaddr;
1437         INT res, new_sock;
1438         CLIENT *c;
1439
1440         assert( Server > NONE );
1441         assert( Idx > NONE );
1442
1443         /* Did we get a valid IP address? */
1444         if( ! Conf_Server[Server].ip[0] )
1445         {
1446                 /* No. Free connection structure and abort: */
1447                 Init_Conn_Struct( Idx );
1448                 Conf_Server[Server].conn_id = NONE;
1449                 Log( LOG_ERR, "Can't connect to \"%s\" (connection %d): ip address unknown!", Conf_Server[Server].host, Idx );
1450                 return;
1451         }
1452
1453         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 );
1454
1455 #ifdef HAVE_INET_ATON
1456         if( inet_aton( Conf_Server[Server].ip, &inaddr ) == 0 )
1457 #else
1458         memset( &inaddr, 0, sizeof( inaddr ));
1459         inaddr.s_addr = inet_addr( Conf_Server[Server].ip );
1460         if( inaddr.s_addr == (unsigned)-1 )
1461 #endif
1462         {
1463                 /* Can't convert IP address */
1464                 Init_Conn_Struct( Idx );
1465                 Conf_Server[Server].conn_id = NONE;
1466                 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 );
1467                 return;
1468         }
1469
1470         memset( &new_addr, 0, sizeof( new_addr ));
1471         new_addr.sin_family = AF_INET;
1472         new_addr.sin_addr = inaddr;
1473         new_addr.sin_port = htons( Conf_Server[Server].port );
1474
1475         new_sock = socket( PF_INET, SOCK_STREAM, 0 );
1476         if ( new_sock < 0 )
1477         {
1478                 /* Can't create socket */
1479                 Init_Conn_Struct( Idx );
1480                 Conf_Server[Server].conn_id = NONE;
1481                 Log( LOG_CRIT, "Can't create socket: %s!", strerror( errno ));
1482                 return;
1483         }
1484
1485         if( ! Init_Socket( new_sock )) return;
1486
1487         res = connect( new_sock, (struct sockaddr *)&new_addr, sizeof( new_addr ));
1488         if(( res != 0 ) && ( errno != EINPROGRESS ))
1489         {
1490                 /* Can't connect socket */
1491                 Log( LOG_CRIT, "Can't connect socket: %s!", strerror( errno ));
1492                 close( new_sock );
1493                 Init_Conn_Struct( Idx );
1494                 Conf_Server[Server].conn_id = NONE;
1495                 return;
1496         }
1497
1498         /* Client-Struktur initialisieren */
1499         c = Client_NewLocal( Idx, inet_ntoa( new_addr.sin_addr ), CLIENT_UNKNOWNSERVER, FALSE );
1500         if( ! c )
1501         {
1502                 /* Can't create new client structure */
1503                 close( new_sock );
1504                 Init_Conn_Struct( Idx );
1505                 Conf_Server[Server].conn_id = NONE;
1506                 Log( LOG_ALERT, "Can't establish connection: can't create client structure!" );
1507                 return;
1508         }
1509         Client_SetIntroducer( c, c );
1510         Client_SetToken( c, TOKEN_OUTBOUND );
1511
1512         /* Register connection */
1513         My_Connections[Idx].sock = new_sock;
1514         My_Connections[Idx].addr = new_addr;
1515         strlcpy( My_Connections[Idx].host, Conf_Server[Server].host, sizeof( My_Connections[Idx].host ));
1516
1517         /* Register new socket */
1518         FD_SET( new_sock, &My_Sockets );
1519         FD_SET( new_sock, &My_Connects );
1520         if( new_sock > Conn_MaxFD ) Conn_MaxFD = new_sock;
1521
1522 #ifdef DEBUG
1523         Log( LOG_DEBUG, "Registered new connection %d on socket %d.", Idx, My_Connections[Idx].sock );
1524 #endif
1525 } /* New_Server */
1526
1527
1528 LOCAL VOID
1529 Init_Conn_Struct( CONN_ID Idx )
1530 {
1531         /* Connection-Struktur initialisieren */
1532
1533         My_Connections[Idx].sock = NONE;
1534         My_Connections[Idx].res_stat = NULL;
1535         My_Connections[Idx].host[0] = '\0';
1536         My_Connections[Idx].rbuf[0] = '\0';
1537         My_Connections[Idx].rdatalen = 0;
1538         My_Connections[Idx].wbuf[0] = '\0';
1539         My_Connections[Idx].wdatalen = 0;
1540         My_Connections[Idx].starttime = time( NULL );
1541         My_Connections[Idx].lastdata = time( NULL );
1542         My_Connections[Idx].lastping = 0;
1543         My_Connections[Idx].lastprivmsg = time( NULL );
1544         My_Connections[Idx].delaytime = 0;
1545         My_Connections[Idx].bytes_in = 0;
1546         My_Connections[Idx].bytes_out = 0;
1547         My_Connections[Idx].msg_in = 0;
1548         My_Connections[Idx].msg_out = 0;
1549         My_Connections[Idx].flag = 0;
1550         My_Connections[Idx].options = 0;
1551
1552 #ifdef ZLIB
1553         My_Connections[Idx].zip.rbuf[0] = '\0';
1554         My_Connections[Idx].zip.rdatalen = 0;
1555         My_Connections[Idx].zip.wbuf[0] = '\0';
1556         My_Connections[Idx].zip.wdatalen = 0;
1557         My_Connections[Idx].zip.bytes_in = 0;
1558         My_Connections[Idx].zip.bytes_out = 0;
1559 #endif
1560 } /* Init_Conn_Struct */
1561
1562
1563 LOCAL BOOLEAN
1564 Init_Socket( INT Sock )
1565 {
1566         /* Initialize socket (set options) */
1567
1568         INT value;
1569
1570 #ifdef O_NONBLOCK       /* unknown on A/UX */
1571         if( fcntl( Sock, F_SETFL, O_NONBLOCK ) != 0 )
1572         {
1573                 Log( LOG_CRIT, "Can't enable non-blocking mode for socket: %s!", strerror( errno ));
1574                 close( Sock );
1575                 return FALSE;
1576         }
1577 #endif
1578
1579         /* Don't block this port after socket shutdown */
1580         value = 1;
1581         if( setsockopt( Sock, SOL_SOCKET, SO_REUSEADDR, &value, (socklen_t)sizeof( value )) != 0 )
1582         {
1583                 Log( LOG_ERR, "Can't set socket option SO_REUSEADDR: %s!", strerror( errno ));
1584                 /* ignore this error */
1585         }
1586
1587         /* Set type of service (TOS) */
1588 #if defined(IP_TOS) && defined(IPTOS_LOWDELAY)
1589         value = IPTOS_LOWDELAY;
1590 #ifdef DEBUG
1591         Log( LOG_DEBUG, "Setting option IP_TOS on socket %d to IPTOS_LOWDELAY (%d).", Sock, value );
1592 #endif
1593         if( setsockopt( Sock, SOL_IP, IP_TOS, &value, (socklen_t)sizeof( value )) != 0 )
1594         {
1595                 Log( LOG_ERR, "Can't set socket option IP_TOS: %s!", strerror( errno ));
1596                 /* ignore this error */
1597         }
1598 #endif
1599
1600         return TRUE;
1601 } /* Init_Socket */
1602
1603
1604 LOCAL VOID
1605 Read_Resolver_Result( INT r_fd )
1606 {
1607         /* Read result of resolver sub-process from pipe and update the
1608          * apropriate connection/client structure(s): hostname and/or
1609          * IDENT user name.*/
1610
1611         CLIENT *c;
1612         INT len, i, n;
1613         RES_STAT *s;
1614         CHAR *ptr;
1615
1616         /* Search associated connection ... */
1617         for( i = 0; i < Pool_Size; i++ )
1618         {
1619                 if(( My_Connections[i].sock != NONE )
1620                   && ( My_Connections[i].res_stat != NULL )
1621                   && ( My_Connections[i].res_stat->pipe[0] == r_fd ))
1622                         break;
1623         }
1624         if( i >= Pool_Size )
1625         {
1626                 /* Ops, none found? Probably the connection has already
1627                  * been closed!? We'll ignore that ... */
1628                 FD_CLR( r_fd, &Resolver_FDs );
1629                 close( r_fd );
1630 #ifdef DEBUG
1631                 Log( LOG_DEBUG, "Resolver: Got result for unknown connection!?" );
1632 #endif
1633                 return;
1634         }
1635
1636         /* Get resolver structure */
1637         s = My_Connections[i].res_stat;
1638         assert( s != NULL );
1639
1640         /* Read result from pipe */
1641         len = read( r_fd, s->buffer + s->bufpos, sizeof( s->buffer ) - s->bufpos - 1 );
1642         if( len < 0 )
1643         {
1644                 /* Error! */
1645                 close( r_fd );
1646                 Log( LOG_CRIT, "Resolver: Can't read result: %s!", strerror( errno ));
1647                 return;
1648         }
1649         s->bufpos += len;
1650         s->buffer[s->bufpos] = '\0';
1651
1652         /* If the result string is incomplete, return to main loop and
1653          * wait until we can read in more bytes. */
1654 #ifdef IDENTAUTH
1655 try_resolve:
1656 #endif
1657         ptr = strchr( s->buffer, '\n' );
1658         if( ! ptr ) return;
1659         *ptr = '\0';
1660
1661 #ifdef DEBUG
1662         Log( LOG_DEBUG, "Got result from resolver: \"%s\" (%d bytes), stage %d.", s->buffer, len, s->stage );
1663 #endif
1664
1665         /* Okay, we got a complete result: this is a host name for outgoing
1666          * connections and a host name or IDENT user name (if enabled) for
1667          * incoming conneciions.*/
1668         if( My_Connections[i].sock > NONE )
1669         {
1670                 /* Incoming connection */
1671
1672                 /* Search client ... */
1673                 c = Client_GetFromConn( i );
1674                 assert( c != NULL );
1675
1676                 /* Only update client information of unregistered clients */
1677                 if( Client_Type( c ) == CLIENT_UNKNOWN )
1678                 {
1679                         if( s->stage == 0 )
1680                         {
1681                                 /* host name */
1682                                 strlcpy( My_Connections[i].host, s->buffer, sizeof( My_Connections[i].host ));
1683                                 Client_SetHostname( c, s->buffer );
1684
1685 #ifdef IDENTAUTH
1686                                 /* clean up buffer for IDENT result */
1687                                 len = strlen( s->buffer ) + 1;
1688                                 memmove( s->buffer, s->buffer + len, sizeof( s->buffer ) - len );
1689                                 s->bufpos -= len;
1690
1691                                 /* Don't close pipe and clean up, but
1692                                  * instead wait for IDENT result */
1693                                 s->stage = 1;
1694                                 goto try_resolve;
1695                         }
1696                         else if( s->stage == 1 )
1697                         {
1698                                 /* IDENT user name */
1699                                 if( s->buffer[0] )
1700                                 {
1701                                         Log( LOG_INFO, "IDENT lookup for connection %ld: \"%s\".", i, s->buffer );
1702                                         Client_SetUser( c, s->buffer, TRUE );
1703                                 }
1704                                 else Log( LOG_INFO, "IDENT lookup for connection %ld: no result.", i );
1705 #endif
1706                         }
1707                         else Log( LOG_ERR, "Resolver: got result for unknown stage %d!?", s->stage );
1708                 }
1709 #ifdef DEBUG
1710                 else Log( LOG_DEBUG, "Resolver: discarding result for already registered connection %d.", i );
1711 #endif
1712         }
1713         else
1714         {
1715                 /* Outgoing connection (server link): set the IP address
1716                  * so that we can connect to it in the main loop. */
1717
1718                 /* Search server ... */
1719                 n = Conf_GetServer( i );
1720                 assert( n > NONE );
1721
1722                 strlcpy( Conf_Server[n].ip, s->buffer, sizeof( Conf_Server[n].ip ));
1723         }
1724
1725         /* Clean up ... */
1726         FD_CLR( r_fd, &Resolver_FDs );
1727         close( My_Connections[i].res_stat->pipe[0] );
1728         close( My_Connections[i].res_stat->pipe[1] );
1729         free( My_Connections[i].res_stat );
1730         My_Connections[i].res_stat = NULL;
1731
1732         /* Reset penalty time */
1733         Conn_ResetPenalty( i );
1734 } /* Read_Resolver_Result */
1735
1736
1737 LOCAL VOID
1738 Simple_Message( INT Sock, CHAR *Msg )
1739 {
1740         /* Write "simple" message to socket, without using compression
1741          * or even the connection write buffers. Used e.g. for error
1742          * messages by New_Connection(). */
1743
1744         assert( Sock > NONE );
1745         assert( Msg != NULL );
1746
1747         (VOID)send( Sock, Msg, strlen( Msg ), 0 );
1748         (VOID)send( Sock, "\r\n", 2, 0 );
1749 } /* Simple_Error */
1750
1751
1752 LOCAL INT
1753 Count_Connections( struct sockaddr_in addr_in )
1754 {
1755         INT i, cnt;
1756         
1757         cnt = 0;
1758         for( i = 0; i < Pool_Size; i++ )
1759         {
1760                 if(( My_Connections[i].sock > NONE ) && ( My_Connections[i].addr.sin_addr.s_addr == addr_in.sin_addr.s_addr )) cnt++;
1761         }
1762         return cnt;
1763 } /* Count_Connections */
1764
1765
1766 /* -eof- */