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