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