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