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