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