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