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