]> arthur.barton.de Git - ngircd-alex.git/blob - src/ngircd/conn.c
New config option NoDNS: disables all DNS queries.
[ngircd-alex.git] / src / ngircd / conn.c
1 /*
2  * ngIRCd -- The Next Generation IRC Daemon
3  * Copyright (c)2001-2007 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.213 2007/10/25 11:01:19 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 the outbound write buffer of a connection.
613  * @param Idx Index of the connection.
614  * @param Data pointer to the 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
630         /* Servers do get special write buffer limits, so they can generate
631          * all the messages that are required while peering. */
632         if (Client_Type(c) == CLIENT_SERVER)
633                 writebuf_limit = WRITEBUFFER_SLINK_LEN;
634
635         /* Is the socket still open? A previous call to Conn_Write()
636          * may have closed the connection due to a fatal error.
637          * In this case it is sufficient to return an error, as well. */
638         if( My_Connections[Idx].sock <= NONE ) {
639                 LogDebug("Skipped write on closed socket (connection %d).", Idx);
640                 return false;
641         }
642
643 #ifdef ZLIB
644         if ( Conn_OPTION_ISSET( &My_Connections[Idx], CONN_ZIP )) {
645                 /* Compressed link:
646                  * Zip_Buffer() does all the dirty work for us: it flushes
647                  * the (pre-)compression buffers if required and handles
648                  * all error conditions. */
649                 if (!Zip_Buffer(Idx, Data, Len))
650                         return false;
651         }
652         else
653 #endif
654         {
655                 /* Uncompressed link:
656                  * Check if outbound buffer has enough space for the data. */
657                 if (array_bytes(&My_Connections[Idx].wbuf) + Len >=
658                     writebuf_limit) {
659                         /* Buffer is full, flush it. Handle_Write deals with
660                          * low-level errors, if any. */
661                         if (!Handle_Write(Idx))
662                                 return false;
663                 }
664
665                 /* When the write buffer is still too big after flushing it,
666                  * the connection will be killed. */
667                 if (array_bytes(&My_Connections[Idx].wbuf) + Len >=
668                     writebuf_limit) {
669                         Log(LOG_NOTICE,
670                             "Write buffer overflow (connection %d, size %lu byte)!",
671                             Idx,
672                             (unsigned long)array_bytes(&My_Connections[Idx].wbuf));
673                         Conn_Close(Idx, "Write buffer overflow!", NULL, false);
674                         return false;
675                 }
676
677                 /* Copy data to write buffer */
678                 if (!array_catb(&My_Connections[Idx].wbuf, Data, Len))
679                         return false;
680
681                 My_Connections[Idx].bytes_out += Len;
682         }
683
684         /* Adjust global write counter */
685         WCounter += Len;
686
687         return true;
688 } /* Conn_Write */
689
690
691 GLOBAL void
692 Conn_Close( CONN_ID Idx, char *LogMsg, char *FwdMsg, bool InformClient )
693 {
694         /* Close connection. Open pipes of asyncronous resolver
695          * sub-processes are closed down. */
696
697         CLIENT *c;
698         char *txt;
699         double in_k, out_k;
700 #ifdef ZLIB
701         double in_z_k, out_z_k;
702         int in_p, out_p;
703 #endif
704
705         assert( Idx > NONE );
706
707         /* Is this link already shutting down? */
708         if( Conn_OPTION_ISSET( &My_Connections[Idx], CONN_ISCLOSING )) {
709                 /* Conn_Close() has been called recursively for this link;
710                  * probabe reason: Handle_Write() failed  -- see below. */
711                 LogDebug("Recursive request to close connection: %d", Idx );
712                 return;
713         }
714
715         assert( My_Connections[Idx].sock > NONE );
716
717         /* Mark link as "closing" */
718         Conn_OPTION_ADD( &My_Connections[Idx], CONN_ISCLOSING );
719
720         if (LogMsg)
721                 txt = LogMsg;
722         else
723                 txt = FwdMsg;
724         if (! txt)
725                 txt = "Reason unknown";
726
727         Log(LOG_INFO, "Shutting down connection %d (%s) with %s:%d ...", Idx,
728             LogMsg ? LogMsg : FwdMsg, My_Connections[Idx].host,
729             ntohs(My_Connections[Idx].addr.sin_port));
730
731         /* Search client, if any */
732         c = Conn_GetClient( Idx );
733
734         /* Should the client be informed? */
735         if (InformClient) {
736 #ifndef STRICT_RFC
737                 /* Send statistics to client if registered as user: */
738                 if ((c != NULL) && (Client_Type(c) == CLIENT_USER)) {
739                         Conn_WriteStr( Idx,
740                          ":%s NOTICE %s :%sConnection statistics: client %.1f kb, server %.1f kb.",
741                          Client_ID(Client_ThisServer()), Client_ID(c),
742                          NOTICE_TXTPREFIX,
743                          (double)My_Connections[Idx].bytes_in / 1024,
744                          (double)My_Connections[Idx].bytes_out / 1024);
745                 }
746 #endif
747                 /* Send ERROR to client (see RFC!) */
748                 if (FwdMsg)
749                         Conn_WriteStr(Idx, "ERROR :%s", FwdMsg);
750                 else
751                         Conn_WriteStr(Idx, "ERROR :Closing connection.");
752         }
753
754         /* Try to write out the write buffer. Note: Handle_Write() eventually
755          * removes the CLIENT structure associated with this connection if an
756          * error occurs! So we have to re-check if there is still an valid
757          * CLIENT structure after calling Handle_Write() ...*/
758         (void)Handle_Write( Idx );
759
760         /* Search client, if any (re-check!) */
761         c = Conn_GetClient( Idx );
762
763         /* Shut down socket */
764         if (! io_close(My_Connections[Idx].sock)) {
765                 /* Oops, we can't close the socket!? This is ... ugly! */
766                 Log(LOG_CRIT,
767                     "Error closing connection %d (socket %d) with %s:%d - %s! (ignored)",
768                     Idx, My_Connections[Idx].sock, My_Connections[Idx].host,
769                     ntohs(My_Connections[Idx].addr.sin_port), strerror(errno));
770         }
771
772         /* Mark socket as invalid: */
773         My_Connections[Idx].sock = NONE;
774
775         /* If there is still a client, unregister it now */
776         if (c)
777                 Client_Destroy(c, LogMsg, FwdMsg, true);
778
779         /* Calculate statistics and log information */
780         in_k = (double)My_Connections[Idx].bytes_in / 1024;
781         out_k = (double)My_Connections[Idx].bytes_out / 1024;
782 #ifdef ZLIB
783         if (Conn_OPTION_ISSET( &My_Connections[Idx], CONN_ZIP)) {
784                 in_z_k = (double)My_Connections[Idx].zip.bytes_in / 1024;
785                 out_z_k = (double)My_Connections[Idx].zip.bytes_out / 1024;
786                 /* Make sure that no division by zero can occur during
787                  * the calculation of in_p and out_p: in_z_k and out_z_k
788                  * are non-zero, that's guaranteed by the protocol until
789                  * compression can be enabled. */
790                 if (! in_z_k)
791                         in_z_k = in_k;
792                 if (! out_z_k)
793                         out_z_k = out_k;
794                 in_p = (int)(( in_k * 100 ) / in_z_k );
795                 out_p = (int)(( out_k * 100 ) / out_z_k );
796                 Log(LOG_INFO,
797                     "Connection %d with %s:%d closed (in: %.1fk/%.1fk/%d%%, out: %.1fk/%.1fk/%d%%).",
798                     Idx, My_Connections[Idx].host,
799                     ntohs(My_Connections[Idx].addr.sin_port),
800                     in_k, in_z_k, in_p, out_k, out_z_k, out_p);
801         }
802         else
803 #endif
804         {
805                 Log(LOG_INFO,
806                     "Connection %d with %s:%d closed (in: %.1fk, out: %.1fk).",
807                     Idx, My_Connections[Idx].host,
808                     ntohs(My_Connections[Idx].addr.sin_port),
809                     in_k, out_k);
810         }
811
812         /* cancel running resolver */
813         if (Resolve_INPROGRESS(&My_Connections[Idx].res_stat))
814                 Resolve_Shutdown(&My_Connections[Idx].res_stat);
815
816         /* Servers: Modify time of next connect attempt? */
817         Conf_UnsetServer( Idx );
818
819 #ifdef ZLIB
820         /* Clean up zlib, if link was compressed */
821         if ( Conn_OPTION_ISSET( &My_Connections[Idx], CONN_ZIP )) {
822                 inflateEnd( &My_Connections[Idx].zip.in );
823                 deflateEnd( &My_Connections[Idx].zip.out );
824                 array_free(&My_Connections[Idx].zip.rbuf);
825                 array_free(&My_Connections[Idx].zip.wbuf);
826         }
827 #endif
828
829         array_free(&My_Connections[Idx].rbuf);
830         array_free(&My_Connections[Idx].wbuf);
831
832         /* Clean up connection structure (=free it) */
833         Init_Conn_Struct( Idx );
834
835         LogDebug("Shutdown of connection %d completed.", Idx );
836 } /* Conn_Close */
837
838
839 GLOBAL void
840 Conn_SyncServerStruct( void )
841 {
842         /* Synchronize server structures (connection IDs):
843          * connections <-> configuration */
844
845         CLIENT *client;
846         CONN_ID i;
847         int c;
848
849         for( i = 0; i < Pool_Size; i++ ) {
850                 /* Established connection? */
851                 if (My_Connections[i].sock < 0)
852                         continue;
853
854                 /* Server connection? */
855                 client = Conn_GetClient( i );
856                 if(( ! client ) || ( Client_Type( client ) != CLIENT_SERVER )) continue;
857
858                 for( c = 0; c < MAX_SERVERS; c++ )
859                 {
860                         /* Configured server? */
861                         if( ! Conf_Server[c].host[0] ) continue;
862
863                         /* Duplicate? */
864                         if( strcmp( Conf_Server[c].name, Client_ID( client )) == 0 )
865                                 Conf_Server[c].conn_id = i;
866                 }
867         }
868 } /* SyncServerStruct */
869
870
871 /**
872  * Send out data of write buffer; connect new sockets.
873  */
874 static bool
875 Handle_Write( CONN_ID Idx )
876 {
877         ssize_t len;
878         size_t wdatalen;
879
880         assert( Idx > NONE );
881         if ( My_Connections[Idx].sock < 0 ) {
882                 LogDebug("Handle_Write() on closed socket, connection %d", Idx);
883                 return false;
884         }
885         assert( My_Connections[Idx].sock > NONE );
886
887         wdatalen = array_bytes(&My_Connections[Idx].wbuf );
888
889 #ifdef ZLIB
890         if (wdatalen == 0) {
891                 /* Write buffer is empty, so we try to flush the compression
892                  * buffer and get some data to work with from there :-) */
893                 if (!Zip_Flush(Idx))
894                         return false;
895
896                 /* Now the write buffer most probably has changed: */
897                 wdatalen = array_bytes(&My_Connections[Idx].wbuf);
898         }
899 #endif
900
901         if (wdatalen == 0) {
902                 /* Still no data, fine. */
903                 io_event_del(My_Connections[Idx].sock, IO_WANTWRITE );
904                 return true;
905         }
906
907         LogDebug
908             ("Handle_Write() called for connection %d, %ld bytes pending ...",
909              Idx, wdatalen);
910
911         len = write(My_Connections[Idx].sock,
912                     array_start(&My_Connections[Idx].wbuf), wdatalen );
913
914         if( len < 0 ) {
915                 if (errno == EAGAIN || errno == EINTR)
916                         return true;
917
918                 Log(LOG_ERR, "Write error on connection %d (socket %d): %s!",
919                     Idx, My_Connections[Idx].sock, strerror(errno));
920                 Conn_Close(Idx, "Write error!", NULL, false);
921                 return false;
922         }
923
924         /* move any data not yet written to beginning */
925         array_moveleft(&My_Connections[Idx].wbuf, 1, (size_t)len);
926
927         return true;
928 } /* Handle_Write */
929
930
931 static int
932 New_Connection( int Sock )
933 {
934         /* Neue Client-Verbindung von Listen-Socket annehmen und
935          * CLIENT-Struktur anlegen. */
936
937 #ifdef TCPWRAP
938         struct request_info req;
939 #endif
940         struct sockaddr_in new_addr;
941         int new_sock, new_sock_len, new_Pool_Size;
942         CLIENT *c;
943         long cnt;
944
945         assert( Sock > NONE );
946         /* Connection auf Listen-Socket annehmen */
947         new_sock_len = (int)sizeof new_addr;
948         new_sock = accept(Sock, (struct sockaddr *)&new_addr,
949                           (socklen_t *)&new_sock_len);
950         if (new_sock < 0) {
951                 Log(LOG_CRIT, "Can't accept connection: %s!", strerror(errno));
952                 return -1;
953         }
954
955 #ifdef TCPWRAP
956         /* Validate socket using TCP Wrappers */
957         request_init( &req, RQ_DAEMON, PACKAGE_NAME, RQ_FILE, new_sock, RQ_CLIENT_SIN, &new_addr, NULL );
958         fromhost(&req);
959         if( ! hosts_access( &req ))
960         {
961                 /* Access denied! */
962                 Log( deny_severity, "Refused connection from %s (by TCP Wrappers)!", inet_ntoa( new_addr.sin_addr ));
963                 Simple_Message( new_sock, "ERROR :Connection refused" );
964                 close( new_sock );
965                 return -1;
966         }
967 #endif
968
969         /* Socket initialisieren */
970         if (!Init_Socket( new_sock ))
971                 return -1;
972         
973         /* Check IP-based connection limit */
974         cnt = Count_Connections( new_addr );
975         if(( Conf_MaxConnectionsIP > 0 ) && ( cnt >= Conf_MaxConnectionsIP ))
976         {
977                 /* Access denied, too many connections from this IP address! */
978                 Log( LOG_ERR, "Refused connection from %s: too may connections (%ld) from this IP address!", inet_ntoa( new_addr.sin_addr ), cnt);
979                 Simple_Message( new_sock, "ERROR :Connection refused, too many connections from your IP address!" );
980                 close( new_sock );
981                 return -1;
982         }
983
984         if( new_sock >= Pool_Size ) {
985                 new_Pool_Size = new_sock + 1;
986                 /* No free Connection Structures, check if we may accept further connections */
987                 if ((( Conf_MaxConnections > 0) && Pool_Size >= Conf_MaxConnections) ||
988                         (new_Pool_Size < Pool_Size))
989                 {
990                         Log( LOG_ALERT, "Can't accept connection: limit (%d) reached!", Pool_Size );
991                         Simple_Message( new_sock, "ERROR :Connection limit reached" );
992                         close( new_sock );
993                         return -1;
994                 }
995
996                 if (!array_alloc(&My_ConnArray, sizeof(CONNECTION),
997                                  (size_t)new_sock)) {
998                         Log( LOG_EMERG, "Can't allocate memory! [New_Connection]" );
999                         Simple_Message( new_sock, "ERROR: Internal error" );
1000                         close( new_sock );
1001                         return -1;
1002                 }
1003                 LogDebug("Bumped connection pool to %ld items (internal: %ld items, %ld bytes)",
1004                         new_sock, array_length(&My_ConnArray, sizeof(CONNECTION)), array_bytes(&My_ConnArray));
1005
1006                 /* Adjust pointer to new block */
1007                 My_Connections = array_start(&My_ConnArray);
1008                 while (Pool_Size < new_Pool_Size)
1009                         Init_Conn_Struct(Pool_Size++);
1010         }
1011
1012         /* register callback */
1013         if (!io_event_create( new_sock, IO_WANTREAD, cb_clientserver)) {
1014                 Log(LOG_ALERT, "Can't accept connection: io_event_create failed!");
1015                 Simple_Message(new_sock, "ERROR :Internal error");
1016                 close(new_sock);
1017                 return -1;
1018         }
1019
1020         c = Client_NewLocal( new_sock, inet_ntoa( new_addr.sin_addr ), CLIENT_UNKNOWN, false );
1021         if( ! c ) {
1022                 Log(LOG_ALERT, "Can't accept connection: can't create client structure!");
1023                 Simple_Message(new_sock, "ERROR :Internal error");
1024                 io_close(new_sock);
1025                 return -1;
1026         }
1027
1028         Init_Conn_Struct( new_sock );
1029         My_Connections[new_sock].sock = new_sock;
1030         My_Connections[new_sock].addr = new_addr;
1031         My_Connections[new_sock].client = c;
1032
1033         Log( LOG_INFO, "Accepted connection %d from %s:%d on socket %d.", new_sock,
1034                         inet_ntoa( new_addr.sin_addr ), ntohs( new_addr.sin_port), Sock );
1035
1036         /* Hostnamen ermitteln */
1037         strlcpy( My_Connections[new_sock].host, inet_ntoa( new_addr.sin_addr ),
1038                                                 sizeof( My_Connections[new_sock].host ));
1039
1040         Client_SetHostname( c, My_Connections[new_sock].host );
1041
1042         if (!Conf_NoDNS)
1043                 Resolve_Addr(&My_Connections[new_sock].res_stat, &new_addr,
1044                         My_Connections[new_sock].sock, cb_Read_Resolver_Result);
1045
1046         Conn_SetPenalty(new_sock, 4);
1047         return new_sock;
1048 } /* New_Connection */
1049
1050
1051 static CONN_ID
1052 Socket2Index( int Sock )
1053 {
1054         /* zum Socket passende Connection suchen */
1055
1056         assert( Sock >= 0 );
1057
1058         if( Sock >= Pool_Size || My_Connections[Sock].sock != Sock ) {
1059                 /* die Connection wurde vermutlich (wegen eines
1060                  * Fehlers) bereits wieder abgebaut ... */
1061                 LogDebug("Socket2Index: can't get connection for socket %d!", Sock);
1062                 return NONE;
1063         }
1064         return Sock;
1065 } /* Socket2Index */
1066
1067
1068 /**
1069  * Read data from the network to the read buffer. If an error occures,
1070  * the socket of this connection will be shut down.
1071  */
1072 static void
1073 Read_Request( CONN_ID Idx )
1074 {
1075         ssize_t len;
1076         char readbuf[READBUFFER_LEN];
1077         CLIENT *c;
1078         assert( Idx > NONE );
1079         assert( My_Connections[Idx].sock > NONE );
1080
1081 #ifdef ZLIB
1082         if ((array_bytes(&My_Connections[Idx].rbuf) >= READBUFFER_LEN) ||
1083                 (array_bytes(&My_Connections[Idx].zip.rbuf) >= READBUFFER_LEN))
1084 #else
1085         if (array_bytes(&My_Connections[Idx].rbuf) >= READBUFFER_LEN)
1086 #endif
1087         {
1088                 /* Read buffer is full */
1089                 Log(LOG_ERR,
1090                     "Receive buffer overflow (connection %d): %d bytes!",
1091                     Idx, array_bytes(&My_Connections[Idx].rbuf));
1092                 Conn_Close( Idx, "Receive buffer overflow!", NULL, false );
1093                 return;
1094         }
1095
1096         len = read(My_Connections[Idx].sock, readbuf, sizeof(readbuf));
1097         if (len == 0) {
1098                 Log(LOG_INFO, "%s:%d (%s) is closing the connection ...",
1099                     My_Connections[Idx].host,
1100                     ntohs(My_Connections[Idx].addr.sin_port),
1101                     inet_ntoa( My_Connections[Idx].addr.sin_addr));
1102                 Conn_Close(Idx,
1103                            "Socket closed!", "Client closed connection",
1104                            false);
1105                 return;
1106         }
1107
1108         if (len < 0) {
1109                 if( errno == EAGAIN ) return;
1110                 Log(LOG_ERR, "Read error on connection %d (socket %d): %s!",
1111                     Idx, My_Connections[Idx].sock, strerror(errno));
1112                 Conn_Close(Idx, "Read error!", "Client closed connection",
1113                            false);
1114                 return;
1115         }
1116 #ifdef ZLIB
1117         if (Conn_OPTION_ISSET(&My_Connections[Idx], CONN_ZIP)) {
1118                 if (!array_catb(&My_Connections[Idx].zip.rbuf, readbuf,
1119                                 (size_t) len)) {
1120                         Log(LOG_ERR,
1121                             "Could not append recieved data to zip input buffer (connn %d): %d bytes!",
1122                             Idx, len);
1123                         Conn_Close(Idx, "Receive buffer overflow!", NULL,
1124                                    false);
1125                         return;
1126                 }
1127         } else
1128 #endif
1129         {
1130                 if (!array_catb( &My_Connections[Idx].rbuf, readbuf, len)) {
1131                         Log( LOG_ERR, "Could not append recieved data to input buffer (connn %d): %d bytes!", Idx, len );
1132                         Conn_Close( Idx, "Receive buffer overflow!", NULL, false );
1133                 }
1134         }
1135
1136         /* Update connection statistics */
1137         My_Connections[Idx].bytes_in += len;
1138
1139         /* Update timestamp of last data received if this connection is
1140          * registered as a user, server or service connection. Don't update
1141          * otherwise, so users have at least Conf_PongTimeout seconds time to
1142          * register with the IRC server -- see Check_Connections().
1143          * Set "lastping", too, so we can handle time shifts backwards ... */
1144         c = Conn_GetClient(Idx);
1145         if (c && (Client_Type(c) == CLIENT_USER
1146                   || Client_Type(c) == CLIENT_SERVER
1147                   || Client_Type(c) == CLIENT_SERVICE)) {
1148                 My_Connections[Idx].lastdata = time(NULL);
1149                 My_Connections[Idx].lastping = My_Connections[Idx].lastdata;
1150         }
1151
1152         /* Look at the data in the (read-) buffer of this connection */
1153         Handle_Buffer(Idx);
1154 } /* Read_Request */
1155
1156
1157 static bool
1158 Handle_Buffer( CONN_ID Idx )
1159 {
1160         /* Handle Data in Connections Read-Buffer.
1161          * Return true if a reuqest was handled, false otherwise (also returned on errors). */
1162 #ifndef STRICT_RFC
1163         char *ptr1, *ptr2;
1164 #endif
1165         char *ptr;
1166         size_t len, delta;
1167         bool result;
1168         time_t starttime;
1169 #ifdef ZLIB
1170         bool old_z;
1171 #endif
1172
1173         starttime = time(NULL);
1174         result = false;
1175         for (;;) {
1176                 /* Check penalty */
1177                 if( My_Connections[Idx].delaytime > starttime) return result;
1178 #ifdef ZLIB
1179                 /* unpack compressed data */
1180                 if ( Conn_OPTION_ISSET( &My_Connections[Idx], CONN_ZIP ))
1181                         if( ! Unzip_Buffer( Idx )) return false;
1182 #endif
1183
1184                 if (0 == array_bytes(&My_Connections[Idx].rbuf))
1185                         break;
1186
1187                 if (!array_cat0_temporary(&My_Connections[Idx].rbuf)) /* make sure buf is NULL terminated */
1188                         return false;
1189
1190                 /* A Complete Request end with CR+LF, see RFC 2812. */
1191                 ptr = strstr( array_start(&My_Connections[Idx].rbuf), "\r\n" );
1192
1193                 if( ptr ) delta = 2; /* complete request */
1194 #ifndef STRICT_RFC
1195                 else {
1196                         /* Check for non-RFC-compliant request (only CR or LF)? Unfortunately,
1197                          * there are quite a few clients that do this (incl. "mIRC" :-( */
1198                         ptr1 = strchr( array_start(&My_Connections[Idx].rbuf), '\r' );
1199                         ptr2 = strchr( array_start(&My_Connections[Idx].rbuf), '\n' );
1200                         delta = 1;
1201                         if( ptr1 && ptr2 ) ptr = ptr1 > ptr2 ? ptr2 : ptr1;
1202                         else if( ptr1 ) ptr = ptr1;
1203                         else if( ptr2 ) ptr = ptr2;
1204                 }
1205 #endif
1206
1207                 if( ! ptr )
1208                         break;
1209
1210                 /* End of request found */
1211                 *ptr = '\0';
1212
1213                 len = ( ptr - (char*) array_start(&My_Connections[Idx].rbuf)) + delta;
1214
1215                 if( len > ( COMMAND_LEN - 1 )) {
1216                         /* Request must not exceed 512 chars (incl. CR+LF!), see
1217                          * RFC 2812. Disconnect Client if this happens. */
1218                         Log( LOG_ERR, "Request too long (connection %d): %d bytes (max. %d expected)!",
1219                                                 Idx, array_bytes(&My_Connections[Idx].rbuf), COMMAND_LEN - 1 );
1220                         Conn_Close( Idx, NULL, "Request too long", true );
1221                         return false;
1222                 }
1223
1224                 if (len <= 2) { /* request was empty (only '\r\n') */
1225                         array_moveleft(&My_Connections[Idx].rbuf, 1, delta); /* delta is either 1 or 2 */
1226                         break;
1227                 }
1228 #ifdef ZLIB
1229                 /* remember if stream is already compressed */
1230                 old_z = My_Connections[Idx].options & CONN_ZIP;
1231 #endif
1232
1233                 My_Connections[Idx].msg_in++;
1234                 if (!Parse_Request(Idx, (char*)array_start(&My_Connections[Idx].rbuf) ))
1235                         return false;
1236
1237                 result = true;
1238
1239                 array_moveleft(&My_Connections[Idx].rbuf, 1, len);
1240                 LogDebug("Connection %d: %d bytes left in read buffer.",
1241                     Idx, array_bytes(&My_Connections[Idx].rbuf));
1242 #ifdef ZLIB
1243                 if(( ! old_z ) && ( My_Connections[Idx].options & CONN_ZIP ) &&
1244                                 ( array_bytes(&My_Connections[Idx].rbuf) > 0 ))
1245                 {
1246                         /* The last Command activated Socket-Compression.
1247                          * Data that was read after that needs to be copied to Unzip-buf
1248                          * for decompression */
1249                         if (!array_copy( &My_Connections[Idx].zip.rbuf, &My_Connections[Idx].rbuf ))
1250                                 return false;
1251
1252                         array_trunc(&My_Connections[Idx].rbuf);
1253                         LogDebug("Moved already received data (%u bytes) to uncompression buffer.",
1254                                                                 array_bytes(&My_Connections[Idx].zip.rbuf));
1255                 }
1256 #endif /* ZLIB */
1257         }
1258         return result;
1259 } /* Handle_Buffer */
1260
1261
1262 static void
1263 Check_Connections(void)
1264 {
1265         /* check if connections are alive. if not, play PING-PONG first.
1266          * if this doesn't help either, disconnect client. */
1267         CLIENT *c;
1268         CONN_ID i;
1269
1270         for (i = 0; i < Pool_Size; i++) {
1271                 if (My_Connections[i].sock < 0)
1272                         continue;
1273
1274                 c = Conn_GetClient(i);
1275                 if (c && ((Client_Type(c) == CLIENT_USER)
1276                           || (Client_Type(c) == CLIENT_SERVER)
1277                           || (Client_Type(c) == CLIENT_SERVICE))) {
1278                         /* connected User, Server or Service */
1279                         if (My_Connections[i].lastping >
1280                             My_Connections[i].lastdata) {
1281                                 /* We already sent a ping */
1282                                 if (My_Connections[i].lastping <
1283                                     time(NULL) - Conf_PongTimeout) {
1284                                         /* Timeout */
1285                                         LogDebug
1286                                             ("Connection %d: Ping timeout: %d seconds.",
1287                                              i, Conf_PongTimeout);
1288                                         Conn_Close(i, NULL, "Ping timeout",
1289                                                    true);
1290                                 }
1291                         } else if (My_Connections[i].lastdata <
1292                                    time(NULL) - Conf_PingTimeout) {
1293                                 /* We need to send a PING ... */
1294                                 LogDebug("Connection %d: sending PING ...", i);
1295                                 My_Connections[i].lastping = time(NULL);
1296                                 Conn_WriteStr(i, "PING :%s",
1297                                               Client_ID(Client_ThisServer()));
1298                         }
1299                 } else {
1300                         /* The connection is not fully established yet, so
1301                          * we don't do the PING-PONG game here but instead
1302                          * disconnect the client after "a short time" if it's
1303                          * still not registered. */
1304
1305                         if (My_Connections[i].lastdata <
1306                             time(NULL) - Conf_PongTimeout) {
1307                                 LogDebug
1308                                     ("Unregistered connection %d timed out ...",
1309                                      i);
1310                                 Conn_Close(i, NULL, "Timeout", false);
1311                         }
1312                 }
1313         }
1314 } /* Check_Connections */
1315
1316
1317 static void
1318 Check_Servers( void )
1319 {
1320         /* Check if we can establish further server links */
1321
1322         int i, n;
1323         time_t time_now;
1324
1325         /* Check all configured servers */
1326         for( i = 0; i < MAX_SERVERS; i++ ) {
1327                 /* Valid outgoing server which isn't already connected or disabled? */
1328                 if(( ! Conf_Server[i].host[0] ) || ( ! Conf_Server[i].port > 0 ) ||
1329                         ( Conf_Server[i].conn_id > NONE ) || ( Conf_Server[i].flags & CONF_SFLAG_DISABLED ))
1330                                 continue;
1331
1332                 /* Is there already a connection in this group? */
1333                 if( Conf_Server[i].group > NONE ) {
1334                         for (n = 0; n < MAX_SERVERS; n++) {
1335                                 if (n == i) continue;
1336                                 if ((Conf_Server[n].conn_id != NONE) &&
1337                                         (Conf_Server[n].group == Conf_Server[i].group))
1338                                                 break;
1339                         }
1340                         if (n < MAX_SERVERS) continue;
1341                 }
1342
1343                 /* Check last connect attempt? */
1344                 time_now = time(NULL);
1345                 if( Conf_Server[i].lasttry > (time_now - Conf_ConnectRetry))
1346                         continue;
1347
1348                 /* Okay, try to connect now */
1349                 Conf_Server[i].lasttry = time_now;
1350                 Conf_Server[i].conn_id = SERVER_WAIT;
1351                 assert(Resolve_Getfd(&Conf_Server[i].res_stat) < 0);
1352                 Resolve_Name(&Conf_Server[i].res_stat, Conf_Server[i].host, cb_Connect_to_Server);
1353         }
1354 } /* Check_Servers */
1355
1356
1357 static void
1358 New_Server( int Server )
1359 {
1360         /* Establish new server link */
1361
1362         struct sockaddr_in new_addr;
1363         struct in_addr inaddr;
1364         int res, new_sock;
1365         CLIENT *c;
1366
1367         assert( Server > NONE );
1368
1369         Log( LOG_INFO, "Establishing connection to \"%s\", %s, port %d ... ", Conf_Server[Server].host,
1370                                                         Conf_Server[Server].ip, Conf_Server[Server].port );
1371
1372 #ifdef HAVE_INET_ATON
1373         if( inet_aton( Conf_Server[Server].ip, &inaddr ) == 0 )
1374 #else
1375         memset( &inaddr, 0, sizeof( inaddr ));
1376         inaddr.s_addr = inet_addr( Conf_Server[Server].ip );
1377         if( inaddr.s_addr == (unsigned)-1 )
1378 #endif
1379         {
1380                 Log( LOG_ERR, "Can't connect to \"%s\": can't convert ip address %s!",
1381                                 Conf_Server[Server].host, Conf_Server[Server].ip );
1382                 return;
1383         }
1384
1385         memset( &new_addr, 0, sizeof( new_addr ));
1386         new_addr.sin_family = (sa_family_t)AF_INET;
1387         new_addr.sin_addr = inaddr;
1388         new_addr.sin_port = htons( Conf_Server[Server].port );
1389
1390         new_sock = socket( PF_INET, SOCK_STREAM, 0 );
1391         if ( new_sock < 0 ) {
1392                 Log( LOG_CRIT, "Can't create socket: %s!", strerror( errno ));
1393                 return;
1394         }
1395
1396         if( ! Init_Socket( new_sock )) return;
1397
1398         res = connect(new_sock, (struct sockaddr *)&new_addr,
1399                         (socklen_t)sizeof(new_addr));
1400         if(( res != 0 ) && ( errno != EINPROGRESS )) {
1401                 Log( LOG_CRIT, "Can't connect socket: %s!", strerror( errno ));
1402                 close( new_sock );
1403                 return;
1404         }
1405         
1406         if (!array_alloc(&My_ConnArray, sizeof(CONNECTION), (size_t)new_sock)) {
1407                 Log(LOG_ALERT,
1408                     "Cannot allocate memory for server connection (socket %d)",
1409                     new_sock);
1410                 close( new_sock );
1411                 return;
1412         }
1413
1414         My_Connections = array_start(&My_ConnArray);
1415
1416         assert(My_Connections[new_sock].sock <= 0);
1417
1418         Init_Conn_Struct(new_sock);
1419
1420         c = Client_NewLocal( new_sock, inet_ntoa( new_addr.sin_addr ), CLIENT_UNKNOWNSERVER, false );
1421         if( ! c ) {
1422                 Log( LOG_ALERT, "Can't establish connection: can't create client structure!" );
1423                 close( new_sock );
1424                 return;
1425         }
1426
1427         Client_SetIntroducer( c, c );
1428         Client_SetToken( c, TOKEN_OUTBOUND );
1429
1430         /* Register connection */
1431         Conf_Server[Server].conn_id = new_sock;
1432         My_Connections[new_sock].sock = new_sock;
1433         My_Connections[new_sock].addr = new_addr;
1434         My_Connections[new_sock].client = c;
1435         strlcpy( My_Connections[new_sock].host, Conf_Server[Server].host,
1436                                 sizeof(My_Connections[new_sock].host ));
1437
1438         /* Register new socket */
1439         if (!io_event_create( new_sock, IO_WANTWRITE, cb_connserver)) {
1440                 Log( LOG_ALERT, "io_event_create(): could not add fd %d", strerror(errno));
1441                 Conn_Close( new_sock, "io_event_create() failed", NULL, false );
1442                 Init_Conn_Struct( new_sock );
1443                 Conf_Server[Server].conn_id = NONE;
1444         }
1445
1446         LogDebug("Registered new connection %d on socket %d.",
1447                                 new_sock, My_Connections[new_sock].sock );
1448         Conn_OPTION_ADD( &My_Connections[new_sock], CONN_ISCONNECTING );
1449 } /* New_Server */
1450
1451
1452 /**
1453  * Initialize connection structure.
1454  */
1455 static void
1456 Init_Conn_Struct(CONN_ID Idx)
1457 {
1458         time_t now = time(NULL);
1459
1460         memset(&My_Connections[Idx], 0, sizeof(CONNECTION));
1461         My_Connections[Idx].sock = -1;
1462         My_Connections[Idx].signon = now;
1463         My_Connections[Idx].lastdata = now;
1464         My_Connections[Idx].lastprivmsg = now;
1465         Resolve_Init(&My_Connections[Idx].res_stat);
1466 } /* Init_Conn_Struct */
1467
1468
1469 static bool
1470 Init_Socket( int Sock )
1471 {
1472         /* Initialize socket (set options) */
1473
1474         int value;
1475
1476         if (!io_setnonblock(Sock)) {
1477                 Log( LOG_CRIT, "Can't enable non-blocking mode for socket: %s!", strerror( errno ));
1478                 close( Sock );
1479                 return false;
1480         }
1481
1482         /* Don't block this port after socket shutdown */
1483         value = 1;
1484         if( setsockopt( Sock, SOL_SOCKET, SO_REUSEADDR, &value, (socklen_t)sizeof( value )) != 0 )
1485         {
1486                 Log( LOG_ERR, "Can't set socket option SO_REUSEADDR: %s!", strerror( errno ));
1487                 /* ignore this error */
1488         }
1489
1490         /* Set type of service (TOS) */
1491 #if defined(IP_TOS) && defined(IPTOS_LOWDELAY)
1492         value = IPTOS_LOWDELAY;
1493         LogDebug("Setting option IP_TOS on socket %d to IPTOS_LOWDELAY (%d).", Sock, value );
1494         if( setsockopt( Sock, SOL_IP, IP_TOS, &value, (socklen_t)sizeof( value )) != 0 )
1495         {
1496                 Log( LOG_ERR, "Can't set socket option IP_TOS: %s!", strerror( errno ));
1497                 /* ignore this error */
1498         }
1499 #endif
1500
1501         return true;
1502 } /* Init_Socket */
1503
1504
1505
1506 static void
1507 cb_Connect_to_Server(int fd, UNUSED short events)
1508 {
1509         /* Read result of resolver sub-process from pipe and start connection */
1510         int i;
1511         size_t len;
1512         char readbuf[HOST_LEN + 1];
1513
1514         LogDebug("Resolver: Got forward lookup callback on fd %d, events %d", fd, events);
1515
1516         for (i=0; i < MAX_SERVERS; i++) {
1517                   if (Resolve_Getfd(&Conf_Server[i].res_stat) == fd )
1518                           break;
1519         }
1520         
1521         if( i >= MAX_SERVERS) {
1522                 /* Ops, no matching server found?! */
1523                 io_close( fd );
1524                 LogDebug("Resolver: Got Forward Lookup callback for unknown server!?");
1525                 return;
1526         }
1527
1528         /* Read result from pipe */
1529         len = Resolve_Read(&Conf_Server[i].res_stat, readbuf, sizeof readbuf -1);
1530         if (len == 0)
1531                 return;
1532         
1533         readbuf[len] = '\0';
1534         LogDebug("Got result from resolver: \"%s\" (%u bytes read).", readbuf, len);
1535         strlcpy( Conf_Server[i].ip, readbuf, sizeof( Conf_Server[i].ip ));
1536
1537         /* connect() */
1538         New_Server(i);
1539 } /* cb_Read_Forward_Lookup */
1540
1541
1542 static void
1543 cb_Read_Resolver_Result( int r_fd, UNUSED short events )
1544 {
1545         /* Read result of resolver sub-process from pipe and update the
1546          * apropriate connection/client structure(s): hostname and/or
1547          * IDENT user name.*/
1548
1549         CLIENT *c;
1550         int i;
1551         size_t len;
1552         char *identptr;
1553 #ifdef IDENTAUTH
1554         char readbuf[HOST_LEN + 2 + CLIENT_USER_LEN];
1555 #else
1556         char readbuf[HOST_LEN + 1];
1557 #endif
1558
1559         LogDebug("Resolver: Got callback on fd %d, events %d", r_fd, events );
1560
1561         /* Search associated connection ... */
1562         for( i = 0; i < Pool_Size; i++ ) {
1563                 if(( My_Connections[i].sock != NONE )
1564                   && ( Resolve_Getfd(&My_Connections[i].res_stat) == r_fd ))
1565                         break;
1566         }
1567         if( i >= Pool_Size ) {
1568                 /* Ops, none found? Probably the connection has already
1569                  * been closed!? We'll ignore that ... */
1570                 io_close( r_fd );
1571                 LogDebug("Resolver: Got callback for unknown connection!?");
1572                 return;
1573         }
1574
1575         /* Read result from pipe */
1576         len = Resolve_Read(&My_Connections[i].res_stat, readbuf, sizeof readbuf -1);
1577         if (len == 0)
1578                 return;
1579
1580         readbuf[len] = '\0';
1581         identptr = strchr(readbuf, '\n');
1582         assert(identptr != NULL);
1583         if (!identptr) {
1584                 Log( LOG_CRIT, "Resolver: Got malformed result!");
1585                 return;
1586         }
1587
1588         *identptr = '\0';
1589         LogDebug("Got result from resolver: \"%s\" (%u bytes read).", readbuf, len);
1590         /* Okay, we got a complete result: this is a host name for outgoing
1591          * connections and a host name and IDENT user name (if enabled) for
1592          * incoming connections.*/
1593         assert ( My_Connections[i].sock >= 0 );
1594         /* Incoming connection. Search client ... */
1595         c = Conn_GetClient( i );
1596         assert( c != NULL );
1597
1598         /* Only update client information of unregistered clients */
1599         if( Client_Type( c ) == CLIENT_UNKNOWN ) {
1600                 strlcpy(My_Connections[i].host, readbuf, sizeof( My_Connections[i].host));
1601                 Client_SetHostname( c, readbuf);
1602 #ifdef IDENTAUTH
1603                 ++identptr;
1604                 if (*identptr) {
1605                         Log( LOG_INFO, "IDENT lookup for connection %ld: \"%s\".", i, identptr);
1606                         Client_SetUser( c, identptr, true );
1607                 } else {
1608                         Log( LOG_INFO, "IDENT lookup for connection %ld: no result.", i );
1609                 }
1610 #endif
1611         }
1612 #ifdef DEBUG
1613                 else Log( LOG_DEBUG, "Resolver: discarding result for already registered connection %d.", i );
1614 #endif
1615         /* Reset penalty time */
1616         Conn_ResetPenalty( i );
1617 } /* cb_Read_Resolver_Result */
1618
1619
1620 static void
1621 Simple_Message( int Sock, const char *Msg )
1622 {
1623         char buf[COMMAND_LEN];
1624         size_t len;
1625         /* Write "simple" message to socket, without using compression
1626          * or even the connection write buffers. Used e.g. for error
1627          * messages by New_Connection(). */
1628         assert( Sock > NONE );
1629         assert( Msg != NULL );
1630
1631         strlcpy( buf, Msg, sizeof buf - 2);
1632         len = strlcat( buf, "\r\n", sizeof buf);
1633         (void)write(Sock, buf, len);
1634 } /* Simple_Error */
1635
1636
1637 static int
1638 Count_Connections( struct sockaddr_in addr_in )
1639 {
1640         int i, cnt;
1641         
1642         cnt = 0;
1643         for( i = 0; i < Pool_Size; i++ ) {
1644                 if(( My_Connections[i].sock > NONE ) && ( My_Connections[i].addr.sin_addr.s_addr == addr_in.sin_addr.s_addr )) cnt++;
1645         }
1646         return cnt;
1647 } /* Count_Connections */
1648
1649
1650 GLOBAL CLIENT *
1651 Conn_GetClient( CONN_ID Idx ) 
1652 {
1653         /* return Client-Structure that belongs to the local Connection Idx.
1654          * If none is found, return NULL.
1655          */
1656         CONNECTION *c;
1657         assert( Idx >= 0 );
1658
1659         c = array_get(&My_ConnArray, sizeof (CONNECTION), (size_t)Idx);
1660
1661         assert(c != NULL);
1662
1663         return c ? c->client : NULL;
1664 }
1665
1666 /* -eof- */