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