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