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