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