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