]> arthur.barton.de Git - ngircd-alex.git/blob - src/ngircd/conn.c
Output connection status when dumping the internal server state
[ngircd-alex.git] / src / ngircd / conn.c
1 /*
2  * ngIRCd -- The Next Generation IRC Daemon
3  * Copyright (c)2001-2010 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 "conf-ssl.h"
19 #include "io.h"
20
21 #include "imp.h"
22 #include <assert.h>
23 #ifdef PROTOTYPES
24 # include <stdarg.h>
25 #else
26 # include <varargs.h>
27 #endif
28 #include <stdio.h>
29 #include <stdlib.h>
30 #include <unistd.h>
31 #include <errno.h>
32 #include <string.h>
33 #include <sys/socket.h>
34 #include <sys/time.h>
35 #include <sys/types.h>
36 #include <time.h>
37 #include <netinet/in.h>
38
39 #ifdef HAVE_NETINET_IP_H
40 # ifdef HAVE_NETINET_IN_SYSTM_H
41 #  include <netinet/in_systm.h>
42 # endif
43 # include <netinet/ip.h>
44 #endif
45
46 #ifdef HAVE_STDINT_H
47 # include <stdint.h>                    /* e.g. for Mac OS X */
48 #endif
49
50 #ifdef TCPWRAP
51 # include <tcpd.h>                      /* for TCP Wrappers */
52 #endif
53
54 #include "array.h"
55 #include "defines.h"
56
57 #include "exp.h"
58 #include "conn.h"
59
60 #include "imp.h"
61 #include "ngircd.h"
62 #include "array.h"
63 #include "client.h"
64 #include "conf.h"
65 #include "conn-ssl.h"
66 #include "conn-zip.h"
67 #include "conn-func.h"
68 #include "log.h"
69 #include "ng_ipaddr.h"
70 #include "parse.h"
71 #include "resolve.h"
72 #include "tool.h"
73
74 #ifdef ZEROCONF
75 # include "rendezvous.h"
76 #endif
77
78 #include "exp.h"
79
80
81 #define SERVER_WAIT (NONE - 1)
82
83 #define MAX_COMMANDS 3
84 #define MAX_COMMANDS_SERVER 10
85
86
87 static bool Handle_Write PARAMS(( CONN_ID Idx ));
88 static bool Conn_Write PARAMS(( CONN_ID Idx, char *Data, size_t Len ));
89 static int New_Connection PARAMS(( int Sock ));
90 static CONN_ID Socket2Index PARAMS(( int Sock ));
91 static void Read_Request PARAMS(( CONN_ID Idx ));
92 static unsigned int Handle_Buffer PARAMS(( CONN_ID Idx ));
93 static void Check_Connections PARAMS(( void ));
94 static void Check_Servers PARAMS(( void ));
95 static void Init_Conn_Struct PARAMS(( CONN_ID Idx ));
96 static bool Init_Socket PARAMS(( int Sock ));
97 static void New_Server PARAMS(( int Server, ng_ipaddr_t *dest ));
98 static void Simple_Message PARAMS(( int Sock, const char *Msg ));
99 static int NewListener PARAMS(( const char *listen_addr, UINT16 Port ));
100 static void Account_Connection PARAMS((void));
101
102
103 static array My_Listeners;
104 static array My_ConnArray;
105 static size_t NumConnections, NumConnectionsMax, NumConnectionsAccepted;
106
107 #ifdef TCPWRAP
108 int allow_severity = LOG_INFO;
109 int deny_severity = LOG_ERR;
110 #endif
111
112 static void server_login PARAMS((CONN_ID idx));
113
114 #ifdef SSL_SUPPORT
115 extern struct SSLOptions Conf_SSLOptions;
116 static void cb_connserver_login_ssl PARAMS((int sock, short what));
117 static void cb_clientserver_ssl PARAMS((int sock, short what));
118 #endif
119 static void cb_Read_Resolver_Result PARAMS((int sock, UNUSED short what));
120 static void cb_Connect_to_Server PARAMS((int sock, UNUSED short what));
121 static void cb_clientserver PARAMS((int sock, short what));
122
123
124 /**
125  * IO callback for listening sockets: handle new connections. This callback
126  * gets called when a new non-SSL connection should be accepted.
127  * @param sock Socket descriptor
128  * @param irrelevant (ignored IO specification)
129  */
130 static void
131 cb_listen(int sock, short irrelevant)
132 {
133         (void) irrelevant;
134         (void) New_Connection(sock);
135 }
136
137
138 #ifdef SSL_SUPPORT
139 /**
140  * IO callback for listening SSL sockets: handle new connections. This callback
141  * gets called when a new SSL-enabled connection should be accepted.
142  * @param sock Socket descriptor
143  * @param irrelevant (ignored IO specification)
144  */
145 static void
146 cb_listen_ssl(int sock, short irrelevant)
147 {
148         int fd;
149
150         (void) irrelevant;
151         fd = New_Connection(sock);
152         if (fd < 0)
153                 return;
154         io_event_setcb(My_Connections[fd].sock, cb_clientserver_ssl);
155 }
156 #endif
157
158
159 /**
160  * IO callback for new outgoing non-SSL server connections.
161  * @param sock Socket descriptor
162  * @param what IO specification (IO_WANTREAD/IO_WANTWRITE/...)
163  */
164 static void
165 cb_connserver(int sock, UNUSED short what)
166 {
167         int res, err, server;
168         socklen_t sock_len;
169         CONN_ID idx = Socket2Index( sock );
170
171         if (idx <= NONE) {
172                 LogDebug("cb_connserver wants to write on unknown socket?!");
173                 io_close(sock);
174                 return;
175         }
176
177         assert(what & IO_WANTWRITE);
178
179         /* Make sure that the server is still configured; it could have been
180          * removed in the meantime! */
181         server = Conf_GetServer(idx);
182         if (server < 0) {
183                 Log(LOG_ERR, "Connection on socket %d to \"%s\" aborted!",
184                     sock, My_Connections[idx].host);
185                 Conn_Close(idx, "Connection aborted!", NULL, false);
186                 return;
187         }
188
189         /* connect() finished, get result. */
190         sock_len = (socklen_t)sizeof(err);
191         res = getsockopt(My_Connections[idx].sock, SOL_SOCKET, SO_ERROR,
192                          &err, &sock_len );
193         assert(sock_len == sizeof(err));
194
195         /* Error while connecting? */
196         if ((res != 0) || (err != 0)) {
197                 if (res != 0)
198                         Log(LOG_CRIT, "getsockopt (connection %d): %s!",
199                             idx, strerror(errno));
200                 else
201                         Log(LOG_CRIT,
202                             "Can't connect socket to \"%s:%d\" (connection %d): %s!",
203                             My_Connections[idx].host, Conf_Server[server].port,
204                             idx, strerror(err));
205
206                 Conn_Close(idx, "Can't connect!", NULL, false);
207
208                 if (ng_ipaddr_af(&Conf_Server[server].dst_addr[0])) {
209                         /* more addresses to try... */
210                         New_Server(res, &Conf_Server[server].dst_addr[0]);
211                         /* connection to dst_addr[0] is now in progress, so
212                          * remove this address... */
213                         Conf_Server[server].dst_addr[0] =
214                                 Conf_Server[server].dst_addr[1];
215                         memset(&Conf_Server[server].dst_addr[1], 0,
216                                sizeof(Conf_Server[server].dst_addr[1]));
217                 }
218                 return;
219         }
220
221         /* connect() succeeded, remove all additional addresses */
222         memset(&Conf_Server[server].dst_addr, 0,
223                sizeof(Conf_Server[server].dst_addr));
224
225         Conn_OPTION_DEL( &My_Connections[idx], CONN_ISCONNECTING );
226 #ifdef SSL_SUPPORT
227         if ( Conn_OPTION_ISSET( &My_Connections[idx], CONN_SSL_CONNECT )) {
228                 io_event_setcb( sock, cb_connserver_login_ssl );
229                 io_event_add( sock, IO_WANTWRITE|IO_WANTREAD );
230                 return;
231         }
232 #endif
233         server_login(idx);
234 }
235
236
237 /**
238  * Login to a remote server.
239  * @param idx Connection index
240  */
241 static void
242 server_login(CONN_ID idx)
243 {
244         Log( LOG_INFO, "Connection %d with \"%s:%d\" established. Now logging in ...", idx,
245                         My_Connections[idx].host, Conf_Server[Conf_GetServer( idx )].port );
246
247         io_event_setcb( My_Connections[idx].sock, cb_clientserver);
248         io_event_add( My_Connections[idx].sock, IO_WANTREAD|IO_WANTWRITE);
249
250         /* Send PASS and SERVER command to peer */
251         Conn_WriteStr( idx, "PASS %s %s", Conf_Server[Conf_GetServer( idx )].pwd_out, NGIRCd_ProtoID );
252         Conn_WriteStr( idx, "SERVER %s :%s", Conf_ServerName, Conf_ServerInfo );
253 }
254
255
256 #ifdef SSL_SUPPORT
257 /**
258  * IO callback for new outgoing SSL-enabled server connections.
259  * @param sock Socket descriptor
260  * @param what IO specification (IO_WANTREAD/IO_WANTWRITE/...)
261  */
262 static void
263 cb_connserver_login_ssl(int sock, short unused)
264 {
265         CONN_ID idx = Socket2Index(sock);
266
267         assert(idx >= 0);
268         if (idx < 0) {
269                 io_close(sock);
270                 return;
271         }
272         (void) unused;
273         switch (ConnSSL_Connect( &My_Connections[idx])) {
274         case 1: break;
275         case 0: LogDebug("ConnSSL_Connect: not ready");
276                 return;
277         case -1:
278                 Log(LOG_ERR, "SSL connection on socket %d failed!", sock);
279                 Conn_Close(idx, "Can't connect!", NULL, false);
280                 return;
281         }
282
283         Log( LOG_INFO, "SSL connection %d with \"%s:%d\" established.", idx,
284                         My_Connections[idx].host, Conf_Server[Conf_GetServer( idx )].port );
285
286         server_login(idx);
287 }
288 #endif
289
290
291 /**
292  * IO callback for established non-SSL client and server connections.
293  * @param sock Socket descriptor
294  * @param what IO specification (IO_WANTREAD/IO_WANTWRITE/...)
295  */
296 static void
297 cb_clientserver(int sock, short what)
298 {
299         CONN_ID idx = Socket2Index(sock);
300
301         assert(idx >= 0);
302
303         if (idx < 0) {
304                 io_close(sock);
305                 return;
306         }
307 #ifdef SSL_SUPPORT
308         if (what & IO_WANTREAD
309             || (Conn_OPTION_ISSET(&My_Connections[idx], CONN_SSL_WANT_WRITE))) {
310                 /* if TLS layer needs to write additional data, call
311                  * Read_Request() instead so that SSL/TLS can continue */
312                 Read_Request(idx);
313         }
314 #else
315         if (what & IO_WANTREAD)
316                 Read_Request(idx);
317 #endif
318         if (what & IO_WANTWRITE)
319                 Handle_Write(idx);
320 }
321
322
323 #ifdef SSL_SUPPORT
324 /**
325  * IO callback for established SSL-enabled client and server connections.
326  * @param sock Socket descriptor
327  * @param what IO specification (IO_WANTREAD/IO_WANTWRITE/...)
328  */
329 static void
330 cb_clientserver_ssl(int sock, short what)
331 {
332         CONN_ID idx = Socket2Index(sock);
333
334         assert(idx >= 0);
335
336         if (idx < 0) {
337                 io_close(sock);
338                 return;
339         }
340
341         switch (ConnSSL_Accept(&My_Connections[idx])) {
342         case 1:
343                 break;  /* OK */
344         case 0:
345                 return; /* EAGAIN: callback will be invoked again by IO layer */
346         default:
347                 Conn_Close(idx, "SSL accept error, closing socket", "SSL accept error", false);
348                 return;
349         }
350         if (what & IO_WANTREAD)
351                 Read_Request(idx);
352
353         if (what & IO_WANTWRITE)
354                 Handle_Write(idx);
355
356         io_event_setcb(sock, cb_clientserver);  /* SSL handshake completed */
357 }
358 #endif
359
360
361 /**
362  * Initialite connecion module.
363  */
364 GLOBAL void
365 Conn_Init( void )
366 {
367         CONN_ID i;
368
369         /* Speicher fuer Verbindungs-Pool anfordern */
370         Pool_Size = CONNECTION_POOL;
371         if ((Conf_MaxConnections > 0) &&
372                 (Pool_Size > Conf_MaxConnections))
373                         Pool_Size = Conf_MaxConnections;
374
375         if (!array_alloc(&My_ConnArray, sizeof(CONNECTION), (size_t)Pool_Size)) {
376                 Log(LOG_EMERG, "Can't allocate memory! [Conn_Init]");
377                 exit(1);
378         }
379
380         /* FIXME: My_Connetions/Pool_Size is needed by other parts of the
381          * code; remove them! */
382         My_Connections = (CONNECTION*) array_start(&My_ConnArray);
383
384         LogDebug("Allocated connection pool for %d items (%ld bytes).",
385                 array_length(&My_ConnArray, sizeof(CONNECTION)),
386                 array_bytes(&My_ConnArray));
387
388         assert(array_length(&My_ConnArray, sizeof(CONNECTION)) >= (size_t)Pool_Size);
389         
390         array_free( &My_Listeners );
391
392         for (i = 0; i < Pool_Size; i++)
393                 Init_Conn_Struct(i);
394 } /* Conn_Init */
395
396
397 /**
398  * Clean up connection module.
399  */
400 GLOBAL void
401 Conn_Exit( void )
402 {
403         CONN_ID idx;
404
405         Conn_ExitListeners();
406
407         LogDebug("Shutting down all connections ..." );
408         for( idx = 0; idx < Pool_Size; idx++ ) {
409                 if( My_Connections[idx].sock > NONE ) {
410                         Conn_Close( idx, NULL, NGIRCd_SignalRestart ?
411                                 "Server going down (restarting)":"Server going down", true );
412                 }
413         }
414
415         array_free(&My_ConnArray);
416         My_Connections = NULL;
417         Pool_Size = 0;
418         io_library_shutdown();
419 } /* Conn_Exit */
420
421
422 /**
423  * Close all sockets (file descriptors) of open connections.
424  * This is useful in forked child processes, for example, to make sure that
425  * they don't hold connections open that the main process wants to close.
426  */
427 GLOBAL void
428 Conn_CloseAllSockets(void)
429 {
430         CONN_ID idx;
431
432         for(idx = 0; idx < Pool_Size; idx++) {
433                 if(My_Connections[idx].sock > NONE)
434                         close(My_Connections[idx].sock);
435         }
436 }
437
438
439 static unsigned int
440 ports_initlisteners(array *a, const char *listen_addr, void (*func)(int,short))
441 {
442         unsigned int created = 0;
443         size_t len;
444         int fd;
445         UINT16 *port;
446
447         len = array_length(a, sizeof (UINT16));
448         port = array_start(a);
449         while (len--) {
450                 fd = NewListener(listen_addr, *port);
451                 if (fd < 0) {
452                         port++;
453                         continue;
454                 }
455                 if (!io_event_create( fd, IO_WANTREAD, func )) {
456                         Log( LOG_ERR, "io_event_create(): Could not add listening fd %d (port %u): %s!",
457                                                 fd, (unsigned int) *port, strerror(errno));
458                         close(fd);
459                         port++;
460                         continue;
461                 }
462                 created++;
463                 port++;
464         }
465         return created;
466 }
467
468
469 /**
470  * Initialize all listening sockets.
471  * @return Number of created listening sockets
472  */
473 GLOBAL unsigned int
474 Conn_InitListeners( void )
475 {
476         /* Initialize ports on which the server should accept connections */
477         unsigned int created = 0;
478         char *copy, *listen_addr;
479
480         assert(Conf_ListenAddress);
481
482         /* can't use Conf_ListenAddress directly, see below */
483         copy = strdup(Conf_ListenAddress);
484         if (!copy) {
485                 Log(LOG_CRIT, "Cannot copy %s: %s", Conf_ListenAddress, strerror(errno));
486                 return 0;
487         }
488         listen_addr = strtok(copy, ",");
489
490         while (listen_addr) {
491                 ngt_TrimStr(listen_addr);
492                 if (*listen_addr) {
493                         created += ports_initlisteners(&Conf_ListenPorts, listen_addr, cb_listen);
494 #ifdef SSL_SUPPORT
495                         created += ports_initlisteners(&Conf_SSLOptions.ListenPorts, listen_addr, cb_listen_ssl);
496 #endif
497                 }
498
499                 listen_addr = strtok(NULL, ",");
500         }
501
502         /* Can't free() Conf_ListenAddress here: on REHASH, if the config file
503          * cannot be re-loaded, we'd end up with a NULL Conf_ListenAddress.
504          * Instead, free() takes place in conf.c, before the config file
505          * is being parsed. */
506         free(copy);
507
508         return created;
509 } /* Conn_InitListeners */
510
511
512 GLOBAL void
513 Conn_ExitListeners( void )
514 {
515         /* Close down all listening sockets */
516         int *fd;
517         size_t arraylen;
518 #ifdef ZEROCONF
519         Rendezvous_UnregisterListeners( );
520 #endif
521
522         arraylen = array_length(&My_Listeners, sizeof (int));
523         Log(LOG_INFO,
524             "Shutting down all listening sockets (%d total) ...", arraylen);
525         fd = array_start(&My_Listeners);
526         while(arraylen--) {
527                 assert(fd != NULL);
528                 assert(*fd >= 0);
529                 io_close(*fd);
530                 LogDebug("Listening socket %d closed.", *fd );
531                 fd++;
532         }
533         array_free(&My_Listeners);
534 } /* Conn_ExitListeners */
535
536
537 static bool
538 InitSinaddrListenAddr(ng_ipaddr_t *addr, const char *listen_addrstr, UINT16 Port)
539 {
540         bool ret;
541
542         ret = ng_ipaddr_init(addr, listen_addrstr, Port);
543         if (!ret) {
544                 assert(listen_addrstr);
545                 Log(LOG_CRIT, "Can't bind to [%s]:%u: can't convert ip address \"%s\"",
546                                                 listen_addrstr, Port, listen_addrstr);
547         }
548         return ret;
549 }
550
551
552 static void
553 set_v6_only(int af, int sock)
554 {
555 #if defined(IPV6_V6ONLY) && defined(WANT_IPV6)
556         int on = 1;
557
558         if (af != AF_INET6)
559                 return;
560
561         if (setsockopt(sock, IPPROTO_IPV6, IPV6_V6ONLY, &on, (socklen_t)sizeof(on)))
562                 Log(LOG_ERR, "Could not set IPV6_V6ONLY: %s", strerror(errno));
563 #else
564         (void)af;
565         (void)sock;
566 #endif
567 }
568
569
570 /* return new listening port file descriptor or -1 on failure */
571 static int
572 NewListener(const char *listen_addr, UINT16 Port)
573 {
574         /* Create new listening socket on specified port */
575         ng_ipaddr_t addr;
576         int sock, af;
577 #ifdef ZEROCONF
578         char name[CLIENT_ID_LEN], *info;
579 #endif
580         if (!InitSinaddrListenAddr(&addr, listen_addr, Port))
581                 return -1;
582
583         af = ng_ipaddr_af(&addr);
584         sock = socket(af, SOCK_STREAM, 0);
585         if( sock < 0 ) {
586                 Log(LOG_CRIT, "Can't create socket (af %d) : %s!", af, strerror(errno));
587                 return -1;
588         }
589
590         set_v6_only(af, sock);
591
592         if (!Init_Socket(sock))
593                 return -1;
594
595         if (bind(sock, (struct sockaddr *)&addr, ng_ipaddr_salen(&addr)) != 0) {
596                 Log(LOG_CRIT, "Can't bind socket to address %s:%d - %s",
597                         ng_ipaddr_tostr(&addr), Port, strerror(errno));
598                 close(sock);
599                 return -1;
600         }
601
602         if( listen( sock, 10 ) != 0 ) {
603                 Log( LOG_CRIT, "Can't listen on socket: %s!", strerror( errno ));
604                 close( sock );
605                 return -1;
606         }
607
608         /* keep fd in list so we can close it when ngircd restarts/shuts down */
609         if (!array_catb( &My_Listeners,(char*) &sock, sizeof(int) )) {
610                 Log( LOG_CRIT, "Can't add socket to My_Listeners array: %s!", strerror( errno ));
611                 close( sock );
612                 return -1;
613         }
614
615         Log(LOG_INFO, "Now listening on [%s]:%d (socket %d).", ng_ipaddr_tostr(&addr), Port, sock);
616
617 #ifdef ZEROCONF
618         /* Get best server description text */
619         if( ! Conf_ServerInfo[0] ) info = Conf_ServerName;
620         else
621         {
622                 /* Use server info string */
623                 info = NULL;
624                 if( Conf_ServerInfo[0] == '[' )
625                 {
626                         /* Cut off leading hostname part in "[]" */
627                         info = strchr( Conf_ServerInfo, ']' );
628                         if( info )
629                         {
630                                 info++;
631                                 while( *info == ' ' ) info++;
632                         }
633                 }
634                 if( ! info ) info = Conf_ServerInfo;
635         }
636
637         /* Add port number to description if non-standard */
638         if (Port != 6667)
639                 snprintf(name, sizeof name, "%s (port %u)", info,
640                          (unsigned int)Port);
641         else
642                 strlcpy(name, info, sizeof name);
643
644         /* Register service */
645         Rendezvous_Register( name, MDNS_TYPE, Port );
646 #endif
647         return sock;
648 } /* NewListener */
649
650
651 #ifdef SSL_SUPPORT
652 /*
653  * SSL/TLS connections require extra treatment:
654  * When either CONN_SSL_WANT_WRITE or CONN_SSL_WANT_READ is set, we
655  * need to take care of that first, before checking read/write buffers.
656  * For instance, while we might have data in our write buffer, the
657  * TLS/SSL protocol might need to read internal data first for TLS/SSL
658  * writes to succeed.
659  *
660  * If this function returns true, such a condition is met and we have
661  * to reverse the condition (check for read even if we've data to write,
662  * do not check for read but writeability even if write-buffer is empty).
663  */
664 static bool
665 SSL_WantRead(const CONNECTION *c)
666 {
667         if (Conn_OPTION_ISSET(c, CONN_SSL_WANT_READ)) {
668                 io_event_add(c->sock, IO_WANTREAD);
669                 return true;
670         }
671         return false;
672 }
673 static bool
674 SSL_WantWrite(const CONNECTION *c)
675 {
676         if (Conn_OPTION_ISSET(c, CONN_SSL_WANT_WRITE)) {
677                 io_event_add(c->sock, IO_WANTWRITE);
678                 return true;
679         }
680         return false;
681 }
682 #else
683 static inline bool
684 SSL_WantRead(UNUSED const CONNECTION *c) { return false; }
685 static inline bool
686 SSL_WantWrite(UNUSED const CONNECTION *c) { return false; }
687 #endif
688
689
690 /**
691  * "Main Loop": Loop until shutdown or restart is signalled.
692  * This function loops until a shutdown or restart of ngIRCd is signalled and
693  * calls io_dispatch() to check for readable and writable sockets every second.
694  * It checks for status changes on pending connections (e. g. when a hostname
695  * has been resolved), checks for "penalties" and timeouts, and handles the
696  * input buffers.
697  */
698 GLOBAL void
699 Conn_Handler(void)
700 {
701         int i;
702         unsigned int wdatalen, bytes_processed;
703         struct timeval tv;
704         time_t t;
705
706         while (!NGIRCd_SignalQuit && !NGIRCd_SignalRestart) {
707                 t = time(NULL);
708
709 #ifdef ZEROCONF
710                 Rendezvous_Handler();
711 #endif
712
713                 /* Check configured servers and established links */
714                 Check_Servers();
715                 Check_Connections();
716
717                 /* Look for non-empty read buffers ... */
718                 for (i = 0; i < Pool_Size; i++) {
719                         if ((My_Connections[i].sock > NONE)
720                             && (array_bytes(&My_Connections[i].rbuf) > 0)
721                             && (My_Connections[i].delaytime <= t)) {
722                                 /* ... and try to handle the received data */
723                                 bytes_processed = Handle_Buffer(i);
724                                 /* if we processed data, and there might be
725                                  * more commands in the input buffer, do not
726                                  * try to read any more data now */
727                                 if (bytes_processed &&
728                                     array_bytes(&My_Connections[i].rbuf) > 2) {
729                                         LogDebug
730                                             ("Throttling connection %d: command limit reached!",
731                                              i);
732                                         Conn_SetPenalty(i, 1);
733                                 }
734                         }
735                 }
736
737                 /* Look for non-empty write buffers ... */
738                 for (i = 0; i < Pool_Size; i++) {
739                         if (My_Connections[i].sock <= NONE)
740                                 continue;
741
742                         wdatalen = (unsigned int)array_bytes(&My_Connections[i].wbuf);
743 #ifdef ZLIB
744                         if (wdatalen > 0 ||
745                             array_bytes(&My_Connections[i].zip.wbuf) > 0)
746 #else
747                         if (wdatalen > 0)
748 #endif
749                         {
750                                 if (SSL_WantRead(&My_Connections[i]))
751                                         continue;
752                                 io_event_add(My_Connections[i].sock,
753                                              IO_WANTWRITE);
754                         }
755                 }
756
757                 /* Check from which sockets we possibly could read ... */
758                 for (i = 0; i < Pool_Size; i++) {
759                         if (My_Connections[i].sock <= NONE)
760                                 continue;
761 #ifdef SSL_SUPPORT
762                         if (SSL_WantWrite(&My_Connections[i]))
763                                 continue; /* TLS/SSL layer needs to write data; deal with this first */
764 #endif
765                         if (Proc_InProgress(&My_Connections[i].proc_stat)) {
766                                 /* Wait for completion of forked subprocess
767                                  * and ignore the socket in the meantime ... */
768                                 io_event_del(My_Connections[i].sock,
769                                              IO_WANTREAD);
770                                 continue;
771                         }
772
773                         if (Conn_OPTION_ISSET(&My_Connections[i], CONN_ISCONNECTING))
774                                 /* Wait for completion of connect() ... */
775                                 continue;
776
777                         if (My_Connections[i].delaytime > t) {
778                                 /* There is a "penalty time" set: ignore socket! */
779                                 io_event_del(My_Connections[i].sock,
780                                              IO_WANTREAD);
781                                 continue;
782                         }
783
784                         io_event_add(My_Connections[i].sock, IO_WANTREAD);
785                 }
786
787                 /* Set the timeout for reading from the network to 1 second,
788                  * which is the granularity with witch we handle "penalty
789                  * times" for example.
790                  * Note: tv_sec/usec are undefined(!) after io_dispatch()
791                  * returns, so we have to set it beforce each call to it! */
792                 tv.tv_usec = 0;
793                 tv.tv_sec = 1;
794
795                 /* Wait for activity ... */
796                 i = io_dispatch(&tv);
797                 if (i == -1 && errno != EINTR) {
798                         Log(LOG_EMERG, "Conn_Handler(): io_dispatch(): %s!",
799                             strerror(errno));
800                         Log(LOG_ALERT, "%s exiting due to fatal errors!",
801                             PACKAGE_NAME);
802                         exit(1);
803                 }
804         }
805
806         if (NGIRCd_SignalQuit)
807                 Log(LOG_NOTICE | LOG_snotice, "Server going down NOW!");
808         else if (NGIRCd_SignalRestart)
809                 Log(LOG_NOTICE | LOG_snotice, "Server restarting NOW!");
810 } /* Conn_Handler */
811
812
813 /**
814  * Write a text string into the socket of a connection.
815  * This function automatically appends CR+LF to the string and validates that
816  * the result is a valid IRC message (oversized messages are shortened, for
817  * example). Then it calls the Conn_Write() function to do the actual sending.
818  * @param Idx Index fo the connection.
819  * @param Format Format string, see printf().
820  * @return true on success, false otherwise.
821  */
822 #ifdef PROTOTYPES
823 GLOBAL bool
824 Conn_WriteStr(CONN_ID Idx, const char *Format, ...)
825 #else
826 GLOBAL bool 
827 Conn_WriteStr(Idx, Format, va_alist)
828 CONN_ID Idx;
829 const char *Format;
830 va_dcl
831 #endif
832 {
833         char buffer[COMMAND_LEN];
834         size_t len;
835         bool ok;
836         va_list ap;
837
838         assert( Idx > NONE );
839         assert( Format != NULL );
840
841 #ifdef PROTOTYPES
842         va_start( ap, Format );
843 #else
844         va_start( ap );
845 #endif
846         if (vsnprintf( buffer, COMMAND_LEN - 2, Format, ap ) >= COMMAND_LEN - 2 ) {
847                 /*
848                  * The string that should be written to the socket is longer
849                  * than the allowed size of COMMAND_LEN bytes (including both
850                  * the CR and LF characters). This can be caused by the
851                  * IRC_WriteXXX() functions when the prefix of this server had
852                  * to be added to an already "quite long" command line which
853                  * has been received from a regular IRC client, for example.
854                  * 
855                  * We are not allowed to send such "oversized" messages to
856                  * other servers and clients, see RFC 2812 2.3 and 2813 3.3
857                  * ("these messages SHALL NOT exceed 512 characters in length,
858                  * counting all characters including the trailing CR-LF").
859                  *
860                  * So we have a big problem here: we should send more bytes
861                  * to the network than we are allowed to and we don't know
862                  * the originator (any more). The "old" behaviour of blaming
863                  * the receiver ("next hop") is a bad idea (it could be just
864                  * an other server only routing the message!), so the only
865                  * option left is to shorten the string and to hope that the
866                  * result is still somewhat useful ...
867                  *                                                   -alex-
868                  */
869
870                 strcpy (buffer + sizeof(buffer) - strlen(CUT_TXTSUFFIX) - 2 - 1,
871                         CUT_TXTSUFFIX);
872         }
873
874 #ifdef SNIFFER
875         if (NGIRCd_Sniffer)
876                 Log(LOG_DEBUG, " -> connection %d: '%s'.", Idx, buffer);
877 #endif
878
879         len = strlcat( buffer, "\r\n", sizeof( buffer ));
880         ok = Conn_Write(Idx, buffer, len);
881         My_Connections[Idx].msg_out++;
882
883         va_end( ap );
884         return ok;
885 } /* Conn_WriteStr */
886
887
888 /**
889  * Append Data to the outbound write buffer of a connection.
890  * @param Idx Index of the connection.
891  * @param Data pointer to the data.
892  * @param Len length of Data.
893  * @return true on success, false otherwise.
894  */
895 static bool
896 Conn_Write( CONN_ID Idx, char *Data, size_t Len )
897 {
898         CLIENT *c;
899         size_t writebuf_limit = WRITEBUFFER_LEN;
900         assert( Idx > NONE );
901         assert( Data != NULL );
902         assert( Len > 0 );
903
904         c = Conn_GetClient(Idx);
905         assert( c != NULL);
906
907         /* Servers do get special write buffer limits, so they can generate
908          * all the messages that are required while peering. */
909         if (Client_Type(c) == CLIENT_SERVER)
910                 writebuf_limit = WRITEBUFFER_SLINK_LEN;
911
912         /* Is the socket still open? A previous call to Conn_Write()
913          * may have closed the connection due to a fatal error.
914          * In this case it is sufficient to return an error, as well. */
915         if( My_Connections[Idx].sock <= NONE ) {
916                 LogDebug("Skipped write on closed socket (connection %d).", Idx);
917                 return false;
918         }
919
920 #ifdef ZLIB
921         if ( Conn_OPTION_ISSET( &My_Connections[Idx], CONN_ZIP )) {
922                 /* Compressed link:
923                  * Zip_Buffer() does all the dirty work for us: it flushes
924                  * the (pre-)compression buffers if required and handles
925                  * all error conditions. */
926                 if (!Zip_Buffer(Idx, Data, Len))
927                         return false;
928         }
929         else
930 #endif
931         {
932                 /* Uncompressed link:
933                  * Check if outbound buffer has enough space for the data. */
934                 if (array_bytes(&My_Connections[Idx].wbuf) + Len >=
935                     writebuf_limit) {
936                         /* Buffer is full, flush it. Handle_Write deals with
937                          * low-level errors, if any. */
938                         if (!Handle_Write(Idx))
939                                 return false;
940                 }
941
942                 /* When the write buffer is still too big after flushing it,
943                  * the connection will be killed. */
944                 if (array_bytes(&My_Connections[Idx].wbuf) + Len >=
945                     writebuf_limit) {
946                         Log(LOG_NOTICE,
947                             "Write buffer overflow (connection %d, size %lu byte)!",
948                             Idx,
949                             (unsigned long)array_bytes(&My_Connections[Idx].wbuf));
950                         Conn_Close(Idx, "Write buffer overflow!", NULL, false);
951                         return false;
952                 }
953
954                 /* Copy data to write buffer */
955                 if (!array_catb(&My_Connections[Idx].wbuf, Data, Len))
956                         return false;
957
958                 My_Connections[Idx].bytes_out += Len;
959         }
960
961         /* Adjust global write counter */
962         WCounter += Len;
963
964         return true;
965 } /* Conn_Write */
966
967
968 GLOBAL void
969 Conn_Close( CONN_ID Idx, const char *LogMsg, const char *FwdMsg, bool InformClient )
970 {
971         /* Close connection. Open pipes of asyncronous resolver
972          * sub-processes are closed down. */
973
974         CLIENT *c;
975         double in_k, out_k;
976         UINT16 port;
977 #ifdef ZLIB
978         double in_z_k, out_z_k;
979         int in_p, out_p;
980 #endif
981
982         assert( Idx > NONE );
983
984         /* Is this link already shutting down? */
985         if( Conn_OPTION_ISSET( &My_Connections[Idx], CONN_ISCLOSING )) {
986                 /* Conn_Close() has been called recursively for this link;
987                  * probabe reason: Handle_Write() failed  -- see below. */
988                 LogDebug("Recursive request to close connection: %d", Idx );
989                 return;
990         }
991
992         assert( My_Connections[Idx].sock > NONE );
993
994         /* Mark link as "closing" */
995         Conn_OPTION_ADD( &My_Connections[Idx], CONN_ISCLOSING );
996
997         port = ng_ipaddr_getport(&My_Connections[Idx].addr);
998         Log(LOG_INFO, "Shutting down connection %d (%s) with %s:%d ...", Idx,
999             LogMsg ? LogMsg : FwdMsg, My_Connections[Idx].host, port);
1000
1001         /* Search client, if any */
1002         c = Conn_GetClient( Idx );
1003
1004         /* Should the client be informed? */
1005         if (InformClient) {
1006 #ifndef STRICT_RFC
1007                 /* Send statistics to client if registered as user: */
1008                 if ((c != NULL) && (Client_Type(c) == CLIENT_USER)) {
1009                         Conn_WriteStr( Idx,
1010                          ":%s NOTICE %s :%sConnection statistics: client %.1f kb, server %.1f kb.",
1011                          Client_ID(Client_ThisServer()), Client_ID(c),
1012                          NOTICE_TXTPREFIX,
1013                          (double)My_Connections[Idx].bytes_in / 1024,
1014                          (double)My_Connections[Idx].bytes_out / 1024);
1015                 }
1016 #endif
1017                 /* Send ERROR to client (see RFC 2812, section 3.1.7) */
1018                 if (FwdMsg)
1019                         Conn_WriteStr(Idx, "ERROR :%s", FwdMsg);
1020                 else
1021                         Conn_WriteStr(Idx, "ERROR :Closing connection.");
1022         }
1023
1024         /* Try to write out the write buffer. Note: Handle_Write() eventually
1025          * removes the CLIENT structure associated with this connection if an
1026          * error occurs! So we have to re-check if there is still an valid
1027          * CLIENT structure after calling Handle_Write() ...*/
1028         (void)Handle_Write( Idx );
1029
1030         /* Search client, if any (re-check!) */
1031         c = Conn_GetClient( Idx );
1032 #ifdef SSL_SUPPORT
1033         if ( Conn_OPTION_ISSET( &My_Connections[Idx], CONN_SSL )) {
1034                 Log(LOG_INFO, "SSL connection %d shutting down ...", Idx);
1035                 ConnSSL_Free(&My_Connections[Idx]);
1036         }
1037 #endif
1038         /* Shut down socket */
1039         if (! io_close(My_Connections[Idx].sock)) {
1040                 /* Oops, we can't close the socket!? This is ... ugly! */
1041                 Log(LOG_CRIT,
1042                     "Error closing connection %d (socket %d) with %s:%d - %s! (ignored)",
1043                     Idx, My_Connections[Idx].sock, My_Connections[Idx].host,
1044                     port, strerror(errno));
1045         }
1046
1047         /* Mark socket as invalid: */
1048         My_Connections[Idx].sock = NONE;
1049
1050         /* If there is still a client, unregister it now */
1051         if (c)
1052                 Client_Destroy(c, LogMsg, FwdMsg, true);
1053
1054         /* Calculate statistics and log information */
1055         in_k = (double)My_Connections[Idx].bytes_in / 1024;
1056         out_k = (double)My_Connections[Idx].bytes_out / 1024;
1057 #ifdef ZLIB
1058         if (Conn_OPTION_ISSET( &My_Connections[Idx], CONN_ZIP)) {
1059                 in_z_k = (double)My_Connections[Idx].zip.bytes_in / 1024;
1060                 out_z_k = (double)My_Connections[Idx].zip.bytes_out / 1024;
1061                 /* Make sure that no division by zero can occur during
1062                  * the calculation of in_p and out_p: in_z_k and out_z_k
1063                  * are non-zero, that's guaranteed by the protocol until
1064                  * compression can be enabled. */
1065                 if (! in_z_k)
1066                         in_z_k = in_k;
1067                 if (! out_z_k)
1068                         out_z_k = out_k;
1069                 in_p = (int)(( in_k * 100 ) / in_z_k );
1070                 out_p = (int)(( out_k * 100 ) / out_z_k );
1071                 Log(LOG_INFO,
1072                     "Connection %d with %s:%d closed (in: %.1fk/%.1fk/%d%%, out: %.1fk/%.1fk/%d%%).",
1073                     Idx, My_Connections[Idx].host, port,
1074                     in_k, in_z_k, in_p, out_k, out_z_k, out_p);
1075         }
1076         else
1077 #endif
1078         {
1079                 Log(LOG_INFO,
1080                     "Connection %d with %s:%d closed (in: %.1fk, out: %.1fk).",
1081                     Idx, My_Connections[Idx].host, port,
1082                     in_k, out_k);
1083         }
1084
1085         /* Servers: Modify time of next connect attempt? */
1086         Conf_UnsetServer( Idx );
1087
1088 #ifdef ZLIB
1089         /* Clean up zlib, if link was compressed */
1090         if ( Conn_OPTION_ISSET( &My_Connections[Idx], CONN_ZIP )) {
1091                 inflateEnd( &My_Connections[Idx].zip.in );
1092                 deflateEnd( &My_Connections[Idx].zip.out );
1093                 array_free(&My_Connections[Idx].zip.rbuf);
1094                 array_free(&My_Connections[Idx].zip.wbuf);
1095         }
1096 #endif
1097
1098         array_free(&My_Connections[Idx].rbuf);
1099         array_free(&My_Connections[Idx].wbuf);
1100
1101         /* Clean up connection structure (=free it) */
1102         Init_Conn_Struct( Idx );
1103
1104         assert(NumConnections > 0);
1105         if (NumConnections)
1106                 NumConnections--;
1107         LogDebug("Shutdown of connection %d completed, %ld connection%s left.",
1108                  Idx, NumConnections, NumConnections != 1 ? "s" : "");
1109 } /* Conn_Close */
1110
1111
1112 GLOBAL long
1113 Conn_Count(void)
1114 {
1115         return NumConnections;
1116 } /* Conn_Count */
1117
1118
1119 GLOBAL long
1120 Conn_CountMax(void)
1121 {
1122         return NumConnectionsMax;
1123 } /* Conn_CountMax */
1124
1125
1126 GLOBAL long
1127 Conn_CountAccepted(void)
1128 {
1129         return NumConnectionsAccepted;
1130 } /* Conn_CountAccepted */
1131
1132
1133 /**
1134  * Synchronize established connections and configured server structures
1135  * after a configuration update and store the correct connection IDs, if any.
1136  */
1137 GLOBAL void
1138 Conn_SyncServerStruct(void)
1139 {
1140         CLIENT *client;
1141         CONN_ID i;
1142         int c;
1143
1144         for (i = 0; i < Pool_Size; i++) {
1145                 if (My_Connections[i].sock == NONE)
1146                         continue;
1147
1148                 /* Server link? */
1149                 client = Conn_GetClient(i);
1150                 if (!client || Client_Type(client) != CLIENT_SERVER)
1151                         continue;
1152
1153                 for (c = 0; c < MAX_SERVERS; c++) {
1154                         /* Configured server? */
1155                         if (!Conf_Server[c].host[0])
1156                                 continue;
1157
1158                         if (strcasecmp(Conf_Server[c].name, Client_ID(client)) == 0)
1159                                 Conf_Server[c].conn_id = i;
1160                 }
1161         }
1162 } /* SyncServerStruct */
1163
1164
1165 /**
1166  * Send out data of write buffer; connect new sockets.
1167  */
1168 static bool
1169 Handle_Write( CONN_ID Idx )
1170 {
1171         ssize_t len;
1172         size_t wdatalen;
1173
1174         assert( Idx > NONE );
1175         if ( My_Connections[Idx].sock < 0 ) {
1176                 LogDebug("Handle_Write() on closed socket, connection %d", Idx);
1177                 return false;
1178         }
1179         assert( My_Connections[Idx].sock > NONE );
1180
1181         wdatalen = array_bytes(&My_Connections[Idx].wbuf );
1182
1183 #ifdef ZLIB
1184         if (wdatalen == 0) {
1185                 /* Write buffer is empty, so we try to flush the compression
1186                  * buffer and get some data to work with from there :-) */
1187                 if (!Zip_Flush(Idx))
1188                         return false;
1189
1190                 /* Now the write buffer most probably has changed: */
1191                 wdatalen = array_bytes(&My_Connections[Idx].wbuf);
1192         }
1193 #endif
1194
1195         if (wdatalen == 0) {
1196                 /* Still no data, fine. */
1197                 io_event_del(My_Connections[Idx].sock, IO_WANTWRITE );
1198                 return true;
1199         }
1200
1201         LogDebug
1202             ("Handle_Write() called for connection %d, %ld bytes pending ...",
1203              Idx, wdatalen);
1204
1205 #ifdef SSL_SUPPORT
1206         if ( Conn_OPTION_ISSET( &My_Connections[Idx], CONN_SSL )) {
1207                 len = ConnSSL_Write(&My_Connections[Idx], array_start(&My_Connections[Idx].wbuf), wdatalen);
1208         } else
1209 #endif
1210         {
1211                 len = write(My_Connections[Idx].sock,
1212                             array_start(&My_Connections[Idx].wbuf), wdatalen );
1213         }
1214         if( len < 0 ) {
1215                 if (errno == EAGAIN || errno == EINTR)
1216                         return true;
1217
1218                 Log(LOG_ERR, "Write error on connection %d (socket %d): %s!",
1219                     Idx, My_Connections[Idx].sock, strerror(errno));
1220                 Conn_Close(Idx, "Write error!", NULL, false);
1221                 return false;
1222         }
1223
1224         /* move any data not yet written to beginning */
1225         array_moveleft(&My_Connections[Idx].wbuf, 1, (size_t)len);
1226
1227         return true;
1228 } /* Handle_Write */
1229
1230
1231 static int
1232 Count_Connections(ng_ipaddr_t *a)
1233 {
1234         int i, cnt;
1235
1236         cnt = 0;
1237         for (i = 0; i < Pool_Size; i++) {
1238                 if (My_Connections[i].sock <= NONE)
1239                         continue;
1240                 if (ng_ipaddr_ipequal(&My_Connections[i].addr, a))
1241                         cnt++;
1242         }
1243         return cnt;
1244 } /* Count_Connections */
1245
1246
1247 /**
1248  * Initialize new client connection on a listening socket.
1249  * @param Sock Listening socket descriptor
1250  * @return Accepted socket descriptor or -1 on error
1251  */
1252 static int
1253 New_Connection(int Sock)
1254 {
1255 #ifdef TCPWRAP
1256         struct request_info req;
1257 #endif
1258         ng_ipaddr_t new_addr;
1259         char ip_str[NG_INET_ADDRSTRLEN];
1260         int new_sock, new_sock_len, identsock;
1261         CLIENT *c;
1262         long cnt;
1263
1264         assert(Sock > NONE);
1265
1266         new_sock_len = (int)sizeof(new_addr);
1267         new_sock = accept(Sock, (struct sockaddr *)&new_addr,
1268                           (socklen_t *)&new_sock_len);
1269         if (new_sock < 0) {
1270                 Log(LOG_CRIT, "Can't accept connection: %s!", strerror(errno));
1271                 return -1;
1272         }
1273         NumConnectionsAccepted++;
1274
1275         if (!ng_ipaddr_tostr_r(&new_addr, ip_str)) {
1276                 Log(LOG_CRIT, "fd %d: Can't convert IP address!", new_sock);
1277                 Simple_Message(new_sock, "ERROR :Internal Server Error");
1278                 close(new_sock);
1279                 return -1;
1280         }
1281
1282 #ifdef TCPWRAP
1283         /* Validate socket using TCP Wrappers */
1284         request_init(&req, RQ_DAEMON, PACKAGE_NAME, RQ_FILE, new_sock,
1285                      RQ_CLIENT_SIN, &new_addr, NULL);
1286         fromhost(&req);
1287         if (!hosts_access(&req)) {
1288                 Log(deny_severity,
1289                     "Refused connection from %s (by TCP Wrappers)!", ip_str);
1290                 Simple_Message(new_sock, "ERROR :Connection refused");
1291                 close(new_sock);
1292                 return -1;
1293         }
1294 #endif
1295
1296         if (!Init_Socket(new_sock))
1297                 return -1;
1298
1299         /* Check global connection limit */
1300         if ((Conf_MaxConnections > 0) &&
1301             (NumConnections >= (size_t) Conf_MaxConnections)) {
1302                 Log(LOG_ALERT, "Can't accept connection: limit (%d) reached!",
1303                     Conf_MaxConnections);
1304                 Simple_Message(new_sock, "ERROR :Connection limit reached");
1305                 close(new_sock);
1306                 return -1;
1307         }
1308
1309         /* Check IP-based connection limit */
1310         cnt = Count_Connections(&new_addr);
1311         if ((Conf_MaxConnectionsIP > 0) && (cnt >= Conf_MaxConnectionsIP)) {
1312                 /* Access denied, too many connections from this IP address! */
1313                 Log(LOG_ERR,
1314                     "Refused connection from %s: too may connections (%ld) from this IP address!",
1315                     ip_str, cnt);
1316                 Simple_Message(new_sock,
1317                                "ERROR :Connection refused, too many connections from your IP address!");
1318                 close(new_sock);
1319                 return -1;
1320         }
1321
1322         if (new_sock >= Pool_Size) {
1323                 if (!array_alloc(&My_ConnArray, sizeof(CONNECTION),
1324                                  (size_t) new_sock)) {
1325                         Log(LOG_EMERG,
1326                             "Can't allocate memory! [New_Connection]");
1327                         Simple_Message(new_sock, "ERROR: Internal error");
1328                         close(new_sock);
1329                         return -1;
1330                 }
1331                 LogDebug("Bumped connection pool to %ld items (internal: %ld items, %ld bytes)",
1332                          new_sock, array_length(&My_ConnArray,
1333                          sizeof(CONNECTION)), array_bytes(&My_ConnArray));
1334
1335                 /* Adjust pointer to new block */
1336                 My_Connections = array_start(&My_ConnArray);
1337                 while (Pool_Size <= new_sock)
1338                         Init_Conn_Struct(Pool_Size++);
1339         }
1340
1341         /* register callback */
1342         if (!io_event_create(new_sock, IO_WANTREAD, cb_clientserver)) {
1343                 Log(LOG_ALERT,
1344                     "Can't accept connection: io_event_create failed!");
1345                 Simple_Message(new_sock, "ERROR :Internal error");
1346                 close(new_sock);
1347                 return -1;
1348         }
1349
1350         c = Client_NewLocal(new_sock, ip_str, CLIENT_UNKNOWN, false);
1351         if (!c) {
1352                 Log(LOG_ALERT,
1353                     "Can't accept connection: can't create client structure!");
1354                 Simple_Message(new_sock, "ERROR :Internal error");
1355                 io_close(new_sock);
1356                 return -1;
1357         }
1358
1359         Init_Conn_Struct(new_sock);
1360         My_Connections[new_sock].sock = new_sock;
1361         My_Connections[new_sock].addr = new_addr;
1362         My_Connections[new_sock].client = c;
1363
1364         /* Set initial hostname to IP address. This becomes overwritten when
1365          * the DNS lookup is enabled and succeeds, but is used otherwise. */
1366         if (ng_ipaddr_af(&new_addr) != AF_INET)
1367                 snprintf(My_Connections[new_sock].host,
1368                          sizeof(My_Connections[new_sock].host), "[%s]", ip_str);
1369         else
1370                 strlcpy(My_Connections[new_sock].host, ip_str,
1371                         sizeof(My_Connections[new_sock].host));
1372
1373         Client_SetHostname(c, My_Connections[new_sock].host);
1374
1375         Log(LOG_INFO, "Accepted connection %d from %s:%d on socket %d.",
1376             new_sock, My_Connections[new_sock].host,
1377             ng_ipaddr_getport(&new_addr), Sock);
1378
1379         identsock = new_sock;
1380 #ifdef IDENTAUTH
1381         if (Conf_NoIdent)
1382                 identsock = -1;
1383 #endif
1384         if (!Conf_NoDNS)
1385                 Resolve_Addr(&My_Connections[new_sock].proc_stat, &new_addr,
1386                              identsock, cb_Read_Resolver_Result);
1387
1388         Account_Connection();
1389         return new_sock;
1390 } /* New_Connection */
1391
1392
1393 static void
1394 Account_Connection(void)
1395 {
1396         NumConnections++;
1397         if (NumConnections > NumConnectionsMax)
1398                 NumConnectionsMax = NumConnections;
1399         LogDebug("Total number of connections now %lu (max %lu).",
1400                  NumConnections, NumConnectionsMax);
1401 } /* Account_Connection */
1402
1403
1404 static CONN_ID
1405 Socket2Index( int Sock )
1406 {
1407         assert( Sock >= 0 );
1408
1409         if( Sock >= Pool_Size || My_Connections[Sock].sock != Sock ) {
1410                 /* the Connection was already closed again, likely due to
1411                  * an error. */
1412                 LogDebug("Socket2Index: can't get connection for socket %d!", Sock);
1413                 return NONE;
1414         }
1415         return Sock;
1416 } /* Socket2Index */
1417
1418
1419 /**
1420  * Read data from the network to the read buffer. If an error occures,
1421  * the socket of this connection will be shut down.
1422  */
1423 static void
1424 Read_Request( CONN_ID Idx )
1425 {
1426         ssize_t len;
1427         static const unsigned int maxbps = COMMAND_LEN / 2;
1428         char readbuf[READBUFFER_LEN];
1429         time_t t;
1430         CLIENT *c;
1431         assert( Idx > NONE );
1432         assert( My_Connections[Idx].sock > NONE );
1433
1434 #ifdef ZLIB
1435         if ((array_bytes(&My_Connections[Idx].rbuf) >= READBUFFER_LEN) ||
1436                 (array_bytes(&My_Connections[Idx].zip.rbuf) >= READBUFFER_LEN))
1437 #else
1438         if (array_bytes(&My_Connections[Idx].rbuf) >= READBUFFER_LEN)
1439 #endif
1440         {
1441                 /* Read buffer is full */
1442                 Log(LOG_ERR,
1443                     "Receive buffer overflow (connection %d): %d bytes!",
1444                     Idx, array_bytes(&My_Connections[Idx].rbuf));
1445                 Conn_Close( Idx, "Receive buffer overflow!", NULL, false );
1446                 return;
1447         }
1448
1449 #ifdef SSL_SUPPORT
1450         if (Conn_OPTION_ISSET(&My_Connections[Idx], CONN_SSL))
1451                 len = ConnSSL_Read( &My_Connections[Idx], readbuf, sizeof(readbuf));
1452         else
1453 #endif
1454         len = read(My_Connections[Idx].sock, readbuf, sizeof(readbuf));
1455         if (len == 0) {
1456                 Log(LOG_INFO, "%s:%u (%s) is closing the connection ...",
1457                                 My_Connections[Idx].host,
1458                                 (unsigned int) ng_ipaddr_getport(&My_Connections[Idx].addr),
1459                                 ng_ipaddr_tostr(&My_Connections[Idx].addr));
1460                 Conn_Close(Idx,
1461                            "Socket closed!", "Client closed connection",
1462                            false);
1463                 return;
1464         }
1465
1466         if (len < 0) {
1467                 if( errno == EAGAIN ) return;
1468                 Log(LOG_ERR, "Read error on connection %d (socket %d): %s!",
1469                     Idx, My_Connections[Idx].sock, strerror(errno));
1470                 Conn_Close(Idx, "Read error!", "Client closed connection",
1471                            false);
1472                 return;
1473         }
1474 #ifdef ZLIB
1475         if (Conn_OPTION_ISSET(&My_Connections[Idx], CONN_ZIP)) {
1476                 if (!array_catb(&My_Connections[Idx].zip.rbuf, readbuf,
1477                                 (size_t) len)) {
1478                         Log(LOG_ERR,
1479                             "Could not append recieved data to zip input buffer (connn %d): %d bytes!",
1480                             Idx, len);
1481                         Conn_Close(Idx, "Receive buffer overflow!", NULL,
1482                                    false);
1483                         return;
1484                 }
1485         } else
1486 #endif
1487         {
1488                 if (!array_catb( &My_Connections[Idx].rbuf, readbuf, len)) {
1489                         Log( LOG_ERR, "Could not append recieved data to input buffer (connn %d): %d bytes!", Idx, len );
1490                         Conn_Close( Idx, "Receive buffer overflow!", NULL, false );
1491                 }
1492         }
1493
1494         /* Update connection statistics */
1495         My_Connections[Idx].bytes_in += len;
1496
1497         /* Update timestamp of last data received if this connection is
1498          * registered as a user, server or service connection. Don't update
1499          * otherwise, so users have at least Conf_PongTimeout seconds time to
1500          * register with the IRC server -- see Check_Connections().
1501          * Update "lastping", too, if time shifted backwards ... */
1502         c = Conn_GetClient(Idx);
1503         if (c && (Client_Type(c) == CLIENT_USER
1504                   || Client_Type(c) == CLIENT_SERVER
1505                   || Client_Type(c) == CLIENT_SERVICE)) {
1506                 t = time(NULL);
1507                 if (My_Connections[Idx].lastdata != t)
1508                         My_Connections[Idx].bps = 0;
1509
1510                 My_Connections[Idx].lastdata = t;
1511                 if (My_Connections[Idx].lastping > t)
1512                         My_Connections[Idx].lastping = t;
1513         }
1514
1515         /* Look at the data in the (read-) buffer of this connection */
1516         My_Connections[Idx].bps += Handle_Buffer(Idx);
1517         if (Client_Type(c) != CLIENT_SERVER
1518             && My_Connections[Idx].bps >= maxbps) {
1519                 LogDebug("Throttling connection %d: BPS exceeded! (%u >= %u)",
1520                          Idx, My_Connections[Idx].bps, maxbps);
1521                 Conn_SetPenalty(Idx, 1);
1522         }
1523 } /* Read_Request */
1524
1525
1526 /**
1527  * Handle all data in the connection read-buffer.
1528  * Data is processed until no complete command is left in the read buffer,
1529  * or MAX_COMMANDS[_SERVER] commands were processed.
1530  * When a fatal error occurs, the connection is shut down.
1531  * @param Idx Index of the connection.
1532  * @return number of bytes processed.
1533  */
1534 static unsigned int
1535 Handle_Buffer(CONN_ID Idx)
1536 {
1537 #ifndef STRICT_RFC
1538         char *ptr1, *ptr2, *first_eol;
1539 #endif
1540         char *ptr;
1541         size_t len, delta;
1542         time_t starttime;
1543 #ifdef ZLIB
1544         bool old_z;
1545 #endif
1546         unsigned int i, maxcmd = MAX_COMMANDS, len_processed = 0;
1547         CLIENT *c;
1548
1549         c = Conn_GetClient(Idx);
1550         assert( c != NULL);
1551
1552         /* Servers do get special command limits, so they can process
1553          * all the messages that are required while peering. */
1554         if (Client_Type(c) == CLIENT_SERVER)
1555                 maxcmd = MAX_COMMANDS_SERVER;
1556
1557         starttime = time(NULL);
1558         for (i=0; i < maxcmd; i++) {
1559                 /* Check penalty */
1560                 if (My_Connections[Idx].delaytime > starttime)
1561                         return 0;
1562 #ifdef ZLIB
1563                 /* Unpack compressed data, if compression is in use */
1564                 if (Conn_OPTION_ISSET(&My_Connections[Idx], CONN_ZIP)) {
1565                         /* When unzipping fails, Unzip_Buffer() shuts
1566                          * down the connection itself */
1567                         if (!Unzip_Buffer(Idx))
1568                                 return 0;
1569                 }
1570 #endif
1571
1572                 if (0 == array_bytes(&My_Connections[Idx].rbuf))
1573                         break;
1574
1575                 /* Make sure that the buffer is NULL terminated */
1576                 if (!array_cat0_temporary(&My_Connections[Idx].rbuf)) {
1577                         Conn_Close(Idx, NULL,
1578                                    "Can't allocate memory [Handle_Buffer]",
1579                                    true);
1580                         return 0;
1581                 }
1582
1583                 /* RFC 2812, section "2.3 Messages", 5th paragraph:
1584                  * "IRC messages are always lines of characters terminated
1585                  * with a CR-LF (Carriage Return - Line Feed) pair [...]". */
1586                 delta = 2;
1587                 ptr = strstr(array_start(&My_Connections[Idx].rbuf), "\r\n");
1588
1589 #ifndef STRICT_RFC
1590                 /* Check for non-RFC-compliant request (only CR or LF)?
1591                  * Unfortunately, there are quite a few clients out there
1592                  * that do this -- e. g. mIRC, BitchX, and Trillian :-( */
1593                 ptr1 = strchr(array_start(&My_Connections[Idx].rbuf), '\r');
1594                 ptr2 = strchr(array_start(&My_Connections[Idx].rbuf), '\n');
1595                 if (ptr) {
1596                         /* Check if there is a single CR or LF _before_ the
1597                          * corerct CR+LF line terminator:  */
1598                         first_eol = ptr1 < ptr2 ? ptr1 : ptr2;
1599                         if (first_eol < ptr) {
1600                                 /* Single CR or LF before CR+LF found */
1601                                 ptr = first_eol;
1602                                 delta = 1;
1603                         }
1604                 } else if (ptr1 || ptr2) {
1605                         /* No CR+LF terminated command found, but single
1606                          * CR or LF found ... */
1607                         if (ptr1 && ptr2)
1608                                 ptr = ptr1 < ptr2 ? ptr1 : ptr2;
1609                         else
1610                                 ptr = ptr1 ? ptr1 : ptr2;
1611                         delta = 1;
1612                 }
1613 #endif
1614
1615                 if (!ptr)
1616                         break;
1617
1618                 /* Complete (=line terminated) request found, handle it! */
1619                 *ptr = '\0';
1620
1621                 len = ptr - (char *)array_start(&My_Connections[Idx].rbuf) + delta;
1622
1623                 if (len > (COMMAND_LEN - 1)) {
1624                         /* Request must not exceed 512 chars (incl. CR+LF!),
1625                          * see RFC 2812. Disconnect Client if this happens. */
1626                         Log(LOG_ERR,
1627                             "Request too long (connection %d): %d bytes (max. %d expected)!",
1628                             Idx, array_bytes(&My_Connections[Idx].rbuf),
1629                             COMMAND_LEN - 1);
1630                         Conn_Close(Idx, NULL, "Request too long", true);
1631                         return 0;
1632                 }
1633
1634                 len_processed += (unsigned int)len;
1635                 if (len <= delta) {
1636                         /* Request is empty (only '\r\n', '\r' or '\n');
1637                          * delta is 2 ('\r\n') or 1 ('\r' or '\n'), see above */
1638                         array_moveleft(&My_Connections[Idx].rbuf, 1, len);
1639                         continue;
1640                 }
1641 #ifdef ZLIB
1642                 /* remember if stream is already compressed */
1643                 old_z = My_Connections[Idx].options & CONN_ZIP;
1644 #endif
1645
1646                 My_Connections[Idx].msg_in++;
1647                 if (!Parse_Request
1648                     (Idx, (char *)array_start(&My_Connections[Idx].rbuf)))
1649                         return 0; /* error -> connection has been closed */
1650
1651                 array_moveleft(&My_Connections[Idx].rbuf, 1, len);
1652                 LogDebug("Connection %d: %d bytes left in read buffer.",
1653                          Idx, array_bytes(&My_Connections[Idx].rbuf));
1654 #ifdef ZLIB
1655                 if ((!old_z) && (My_Connections[Idx].options & CONN_ZIP) &&
1656                     (array_bytes(&My_Connections[Idx].rbuf) > 0)) {
1657                         /* The last command activated socket compression.
1658                          * Data that was read after that needs to be copied
1659                          * to the unzip buffer for decompression: */
1660                         if (!array_copy
1661                             (&My_Connections[Idx].zip.rbuf,
1662                              &My_Connections[Idx].rbuf)) {
1663                                 Conn_Close(Idx, NULL,
1664                                            "Can't allocate memory [Handle_Buffer]",
1665                                            true);
1666                                 return 0;
1667                         }
1668
1669                         array_trunc(&My_Connections[Idx].rbuf);
1670                         LogDebug
1671                             ("Moved already received data (%u bytes) to uncompression buffer.",
1672                              array_bytes(&My_Connections[Idx].zip.rbuf));
1673                 }
1674 #endif
1675         }
1676         return len_processed;
1677 } /* Handle_Buffer */
1678
1679
1680 /**
1681  * Check whether established connections are still alive or not.
1682  * If not, play PING-PONG first; and if that doesn't help either,
1683  * disconnect the respective peer.
1684  */
1685 static void
1686 Check_Connections(void)
1687 {
1688         CLIENT *c;
1689         CONN_ID i;
1690         char msg[64];
1691
1692         for (i = 0; i < Pool_Size; i++) {
1693                 if (My_Connections[i].sock < 0)
1694                         continue;
1695
1696                 c = Conn_GetClient(i);
1697                 if (c && ((Client_Type(c) == CLIENT_USER)
1698                           || (Client_Type(c) == CLIENT_SERVER)
1699                           || (Client_Type(c) == CLIENT_SERVICE))) {
1700                         /* connected User, Server or Service */
1701                         if (My_Connections[i].lastping >
1702                             My_Connections[i].lastdata) {
1703                                 /* We already sent a ping */
1704                                 if (My_Connections[i].lastping <
1705                                     time(NULL) - Conf_PongTimeout) {
1706                                         /* Timeout */
1707                                         LogDebug
1708                                             ("Connection %d: Ping timeout: %d seconds.",
1709                                              i, Conf_PongTimeout);
1710                                         snprintf(msg, sizeof(msg), "Ping timeout: %d seconds", Conf_PongTimeout);
1711                                         Conn_Close(i, NULL, msg, true);
1712                                 }
1713                         } else if (My_Connections[i].lastdata <
1714                                    time(NULL) - Conf_PingTimeout) {
1715                                 /* We need to send a PING ... */
1716                                 LogDebug("Connection %d: sending PING ...", i);
1717                                 My_Connections[i].lastping = time(NULL);
1718                                 Conn_WriteStr(i, "PING :%s",
1719                                               Client_ID(Client_ThisServer()));
1720                         }
1721                 } else {
1722                         /* The connection is not fully established yet, so
1723                          * we don't do the PING-PONG game here but instead
1724                          * disconnect the client after "a short time" if it's
1725                          * still not registered. */
1726
1727                         if (My_Connections[i].lastdata <
1728                             time(NULL) - Conf_PongTimeout) {
1729                                 LogDebug
1730                                     ("Unregistered connection %d timed out ...",
1731                                      i);
1732                                 Conn_Close(i, NULL, "Timeout", false);
1733                         }
1734                 }
1735         }
1736 } /* Check_Connections */
1737
1738
1739 /**
1740  * Check if further server links should be established.
1741  */
1742 static void
1743 Check_Servers(void)
1744 {
1745         int i, n;
1746         time_t time_now;
1747
1748         time_now = time(NULL);
1749
1750         /* Check all configured servers */
1751         for (i = 0; i < MAX_SERVERS; i++) {
1752                 if (Conf_Server[i].conn_id != NONE)
1753                         continue;       /* Already establishing or connected */
1754                 if (!Conf_Server[i].host[0] || !Conf_Server[i].port > 0)
1755                         continue;       /* No host and/or port configured */
1756                 if (Conf_Server[i].flags & CONF_SFLAG_DISABLED)
1757                         continue;       /* Disabled configuration entry */
1758                 if (Conf_Server[i].lasttry > (time_now - Conf_ConnectRetry))
1759                         continue;       /* We have to wait a little bit ... */
1760
1761                 /* Is there already a connection in this group? */
1762                 if (Conf_Server[i].group > NONE) {
1763                         for (n = 0; n < MAX_SERVERS; n++) {
1764                                 if (n == i)
1765                                         continue;
1766                                 if ((Conf_Server[n].conn_id != NONE) &&
1767                                     (Conf_Server[n].group == Conf_Server[i].group))
1768                                         break;
1769                         }
1770                         if (n < MAX_SERVERS)
1771                                 continue;
1772                 }
1773
1774                 /* Okay, try to connect now */
1775                 Conf_Server[i].lasttry = time_now;
1776                 Conf_Server[i].conn_id = SERVER_WAIT;
1777                 assert(Proc_GetPipeFd(&Conf_Server[i].res_stat) < 0);
1778                 Resolve_Name(&Conf_Server[i].res_stat, Conf_Server[i].host,
1779                              cb_Connect_to_Server);
1780         }
1781 } /* Check_Servers */
1782
1783
1784 static void
1785 New_Server( int Server , ng_ipaddr_t *dest)
1786 {
1787         /* Establish new server link */
1788         char ip_str[NG_INET_ADDRSTRLEN];
1789         int af_dest, res, new_sock;
1790         CLIENT *c;
1791
1792         assert( Server > NONE );
1793
1794         if (!ng_ipaddr_tostr_r(dest, ip_str)) {
1795                 Log(LOG_WARNING, "New_Server: Could not convert IP to string");
1796                 return;
1797         }
1798
1799         Log( LOG_INFO, "Establishing connection to \"%s\", %s, port %d ... ",
1800                         Conf_Server[Server].host, ip_str, Conf_Server[Server].port );
1801
1802         af_dest = ng_ipaddr_af(dest);
1803         new_sock = socket(af_dest, SOCK_STREAM, 0);
1804         if (new_sock < 0) {
1805                 Log( LOG_CRIT, "Can't create socket (af %d) : %s!", af_dest, strerror( errno ));
1806                 return;
1807         }
1808
1809         if (!Init_Socket(new_sock))
1810                 return;
1811
1812         /* is a bind address configured? */
1813         res = ng_ipaddr_af(&Conf_Server[Server].bind_addr);
1814         /* if yes, bind now. If it fails, warn and let connect() pick a source address */
1815         if (res && bind(new_sock, (struct sockaddr *) &Conf_Server[Server].bind_addr,
1816                                 ng_ipaddr_salen(&Conf_Server[Server].bind_addr)))
1817         {
1818                 ng_ipaddr_tostr_r(&Conf_Server[Server].bind_addr, ip_str);
1819                 Log(LOG_WARNING, "Can't bind socket to %s: %s!", ip_str, strerror(errno));
1820         }
1821         ng_ipaddr_setport(dest, Conf_Server[Server].port);
1822         res = connect(new_sock, (struct sockaddr *) dest, ng_ipaddr_salen(dest));
1823         if(( res != 0 ) && ( errno != EINPROGRESS )) {
1824                 Log( LOG_CRIT, "Can't connect socket: %s!", strerror( errno ));
1825                 close( new_sock );
1826                 return;
1827         }
1828
1829         if (!array_alloc(&My_ConnArray, sizeof(CONNECTION), (size_t)new_sock)) {
1830                 Log(LOG_ALERT,
1831                     "Cannot allocate memory for server connection (socket %d)",
1832                     new_sock);
1833                 close( new_sock );
1834                 return;
1835         }
1836
1837         My_Connections = array_start(&My_ConnArray);
1838
1839         assert(My_Connections[new_sock].sock <= 0);
1840
1841         Init_Conn_Struct(new_sock);
1842
1843         ng_ipaddr_tostr_r(dest, ip_str);
1844         c = Client_NewLocal(new_sock, ip_str, CLIENT_UNKNOWNSERVER, false);
1845         if (!c) {
1846                 Log( LOG_ALERT, "Can't establish connection: can't create client structure!" );
1847                 close( new_sock );
1848                 return;
1849         }
1850
1851         /* Conn_Close() decrements this counter again */
1852         Account_Connection();
1853         Client_SetIntroducer( c, c );
1854         Client_SetToken( c, TOKEN_OUTBOUND );
1855
1856         /* Register connection */
1857         Conf_Server[Server].conn_id = new_sock;
1858         My_Connections[new_sock].sock = new_sock;
1859         My_Connections[new_sock].addr = *dest;
1860         My_Connections[new_sock].client = c;
1861         strlcpy( My_Connections[new_sock].host, Conf_Server[Server].host,
1862                                 sizeof(My_Connections[new_sock].host ));
1863
1864         /* Register new socket */
1865         if (!io_event_create( new_sock, IO_WANTWRITE, cb_connserver)) {
1866                 Log( LOG_ALERT, "io_event_create(): could not add fd %d", strerror(errno));
1867                 Conn_Close( new_sock, "io_event_create() failed", NULL, false );
1868                 Init_Conn_Struct( new_sock );
1869                 Conf_Server[Server].conn_id = NONE;
1870         }
1871 #ifdef SSL_SUPPORT
1872         if (Conf_Server[Server].SSLConnect && !ConnSSL_PrepareConnect( &My_Connections[new_sock],
1873                                                                 &Conf_Server[Server] ))
1874         {
1875                 Log(LOG_ALERT, "Could not initialize SSL for outgoing connection");
1876                 Conn_Close( new_sock, "Could not initialize SSL for outgoing connection", NULL, false );
1877                 Init_Conn_Struct( new_sock );
1878                 Conf_Server[Server].conn_id = NONE;
1879                 return;
1880         }
1881 #endif
1882         LogDebug("Registered new connection %d on socket %d (%ld in total).",
1883                  new_sock, My_Connections[new_sock].sock, NumConnections);
1884         Conn_OPTION_ADD( &My_Connections[new_sock], CONN_ISCONNECTING );
1885 } /* New_Server */
1886
1887
1888 /**
1889  * Initialize connection structure.
1890  */
1891 static void
1892 Init_Conn_Struct(CONN_ID Idx)
1893 {
1894         time_t now = time(NULL);
1895
1896         memset(&My_Connections[Idx], 0, sizeof(CONNECTION));
1897         My_Connections[Idx].sock = -1;
1898         My_Connections[Idx].signon = now;
1899         My_Connections[Idx].lastdata = now;
1900         My_Connections[Idx].lastprivmsg = now;
1901         Proc_InitStruct(&My_Connections[Idx].proc_stat);
1902 } /* Init_Conn_Struct */
1903
1904
1905 static bool
1906 Init_Socket( int Sock )
1907 {
1908         /* Initialize socket (set options) */
1909
1910         int value;
1911
1912         if (!io_setnonblock(Sock)) {
1913                 Log( LOG_CRIT, "Can't enable non-blocking mode for socket: %s!", strerror( errno ));
1914                 close( Sock );
1915                 return false;
1916         }
1917
1918         /* Don't block this port after socket shutdown */
1919         value = 1;
1920         if( setsockopt( Sock, SOL_SOCKET, SO_REUSEADDR, &value, (socklen_t)sizeof( value )) != 0 )
1921         {
1922                 Log( LOG_ERR, "Can't set socket option SO_REUSEADDR: %s!", strerror( errno ));
1923                 /* ignore this error */
1924         }
1925
1926         /* Set type of service (TOS) */
1927 #if defined(IPPROTO_IP) && defined(IPTOS_LOWDELAY)
1928         value = IPTOS_LOWDELAY;
1929         LogDebug("Setting IP_TOS on socket %d to IPTOS_LOWDELAY.", Sock);
1930         if (setsockopt(Sock, IPPROTO_IP, IP_TOS, &value,
1931                        (socklen_t) sizeof(value))) {
1932                 Log(LOG_ERR, "Can't set socket option IP_TOS: %s!",
1933                     strerror(errno));
1934                 /* ignore this error */
1935         }
1936 #endif
1937
1938         return true;
1939 } /* Init_Socket */
1940
1941
1942 static void
1943 cb_Connect_to_Server(int fd, UNUSED short events)
1944 {
1945         /* Read result of resolver sub-process from pipe and start connection */
1946         int i;
1947         size_t len;
1948         ng_ipaddr_t dest_addrs[4];      /* we can handle at most 3; but we read up to
1949                                            four so we can log the 'more than we can handle'
1950                                            condition. First result is tried immediately, rest
1951                                            is saved for later if needed. */
1952
1953         LogDebug("Resolver: Got forward lookup callback on fd %d, events %d", fd, events);
1954
1955         for (i=0; i < MAX_SERVERS; i++) {
1956                   if (Proc_GetPipeFd(&Conf_Server[i].res_stat) == fd )
1957                           break;
1958         }
1959
1960         if( i >= MAX_SERVERS) {
1961                 /* Ops, no matching server found?! */
1962                 io_close( fd );
1963                 LogDebug("Resolver: Got Forward Lookup callback for unknown server!?");
1964                 return;
1965         }
1966
1967         /* Read result from pipe */
1968         len = Proc_Read(&Conf_Server[i].res_stat, dest_addrs, sizeof(dest_addrs));
1969         if (len == 0)
1970                 return;
1971
1972         assert((len % sizeof(ng_ipaddr_t)) == 0);
1973
1974         LogDebug("Got result from resolver: %u structs (%u bytes).", len/sizeof(ng_ipaddr_t), len);
1975
1976         memset(&Conf_Server[i].dst_addr, 0, sizeof(Conf_Server[i].dst_addr));
1977         if (len > sizeof(ng_ipaddr_t)) {
1978                 /* more than one address for this hostname, remember them
1979                  * in case first address is unreachable/not available */
1980                 len -= sizeof(ng_ipaddr_t);
1981                 if (len > sizeof(Conf_Server[i].dst_addr)) {
1982                         len = sizeof(Conf_Server[i].dst_addr);
1983                         Log(LOG_NOTICE,
1984                                 "Notice: Resolver returned more IP Addresses for host than we can handle, additional addresses dropped.");
1985                 }
1986                 memcpy(&Conf_Server[i].dst_addr, &dest_addrs[1], len);
1987         }
1988         /* connect() */
1989         New_Server(i, dest_addrs);
1990 } /* cb_Read_Forward_Lookup */
1991
1992
1993 static void
1994 cb_Read_Resolver_Result( int r_fd, UNUSED short events )
1995 {
1996         /* Read result of resolver sub-process from pipe and update the
1997          * apropriate connection/client structure(s): hostname and/or
1998          * IDENT user name.*/
1999
2000         CLIENT *c;
2001         CONN_ID i;
2002         size_t len;
2003         char *identptr;
2004 #ifdef IDENTAUTH
2005         char readbuf[HOST_LEN + 2 + CLIENT_USER_LEN];
2006 #else
2007         char readbuf[HOST_LEN + 1];
2008 #endif
2009
2010         LogDebug("Resolver: Got callback on fd %d, events %d", r_fd, events );
2011         i = Conn_GetFromProc(r_fd);
2012         if (i == NONE) {
2013                 /* Ops, none found? Probably the connection has already
2014                  * been closed!? We'll ignore that ... */
2015                 io_close( r_fd );
2016                 LogDebug("Resolver: Got callback for unknown connection!?");
2017                 return;
2018         }
2019
2020         /* Read result from pipe */
2021         len = Proc_Read(&My_Connections[i].proc_stat, readbuf, sizeof readbuf -1);
2022         if (len == 0)
2023                 return;
2024
2025         readbuf[len] = '\0';
2026         identptr = strchr(readbuf, '\n');
2027         assert(identptr != NULL);
2028         if (!identptr) {
2029                 Log( LOG_CRIT, "Resolver: Got malformed result!");
2030                 return;
2031         }
2032
2033         *identptr = '\0';
2034         LogDebug("Got result from resolver: \"%s\" (%u bytes read).", readbuf, len);
2035         /* Okay, we got a complete result: this is a host name for outgoing
2036          * connections and a host name and IDENT user name (if enabled) for
2037          * incoming connections.*/
2038         assert ( My_Connections[i].sock >= 0 );
2039         /* Incoming connection. Search client ... */
2040         c = Conn_GetClient( i );
2041         assert( c != NULL );
2042
2043         /* Only update client information of unregistered clients.
2044          * Note: user commands (e. g. WEBIRC) are always read _after_ reading
2045          * the resolver results, so we don't have to worry to override settings
2046          * from these commands here. */
2047         if(Client_Type(c) == CLIENT_UNKNOWN) {
2048                 strlcpy(My_Connections[i].host, readbuf,
2049                         sizeof(My_Connections[i].host));
2050                 Client_SetHostname(c, readbuf);
2051 #ifdef IDENTAUTH
2052                 ++identptr;
2053                 if (*identptr) {
2054                         Log(LOG_INFO, "IDENT lookup for connection %d: \"%s\".", i, identptr);
2055                         Client_SetUser(c, identptr, true);
2056                 } else {
2057                         Log(LOG_INFO, "IDENT lookup for connection %d: no result.", i);
2058                 }
2059 #endif
2060         }
2061 #ifdef DEBUG
2062                 else Log( LOG_DEBUG, "Resolver: discarding result for already registered connection %d.", i );
2063 #endif
2064 } /* cb_Read_Resolver_Result */
2065
2066
2067 /**
2068  * Write a "simple" (error) message to a socket.
2069  * The message is sent without using the connection write buffers, without
2070  * compression/encryption, and even without any error reporting. It is
2071  * designed for error messages of e.g. New_Connection(). */
2072 static void
2073 Simple_Message(int Sock, const char *Msg)
2074 {
2075         char buf[COMMAND_LEN];
2076         size_t len;
2077
2078         assert(Sock > NONE);
2079         assert(Msg != NULL);
2080
2081         strlcpy(buf, Msg, sizeof buf - 2);
2082         len = strlcat(buf, "\r\n", sizeof buf);
2083         if (write(Sock, buf, len) < 0) {
2084                 /* Because this function most probably got called to log
2085                  * an error message, any write error is ignored here to
2086                  * avoid an endless loop. But casting the result of write()
2087                  * to "void" doesn't satisfy the GNU C code attribute
2088                  * "warn_unused_result" which is used by some versions of
2089                  * glibc (e.g. 2.11.1), therefore this silly error
2090                  * "handling" code here :-( */
2091                 return;
2092         }
2093 } /* Simple_Error */
2094
2095
2096 /**
2097  * Get CLIENT structure that belongs to a local connection identified by its
2098  * index number. Each connection belongs to a client by definition, so it is
2099  * not required that the caller checks for NULL return values.
2100  * @param Idx Connection index number
2101  * @return Pointer to CLIENT structure
2102  */
2103 GLOBAL CLIENT *
2104 Conn_GetClient( CONN_ID Idx ) 
2105 {
2106         CONNECTION *c;
2107
2108         assert(Idx >= 0);
2109         c = array_get(&My_ConnArray, sizeof (CONNECTION), (size_t)Idx);
2110         assert(c != NULL);
2111         return c ? c->client : NULL;
2112 }
2113
2114 /**
2115  * Get PROC_STAT sub-process structure of a connection.
2116  * @param Idx Connection index number
2117  * @return PROC_STAT structure
2118  */
2119 GLOBAL PROC_STAT *
2120 Conn_GetProcStat(CONN_ID Idx)
2121 {
2122         CONNECTION *c;
2123
2124         assert(Idx >= 0);
2125         c = array_get(&My_ConnArray, sizeof (CONNECTION), (size_t)Idx);
2126         assert(c != NULL);
2127         return &c->proc_stat;
2128 } /* Conn_GetProcStat */
2129
2130
2131 /**
2132  * Get CONN_ID from file descriptor associated to a subprocess structure.
2133  * @param fd File descriptor
2134  * @return CONN_ID or NONE (-1)
2135  */
2136 GLOBAL CONN_ID
2137 Conn_GetFromProc(int fd)
2138 {
2139         int i;
2140
2141         assert(fd > 0);
2142         for (i = 0; i < Pool_Size; i++) {
2143                 if ((My_Connections[i].sock != NONE)
2144                     && (Proc_GetPipeFd(&My_Connections[i].proc_stat) == fd))
2145                         return i;
2146         }
2147         return NONE;
2148 } /* Conn_GetFromProc */
2149
2150
2151 #ifdef SSL_SUPPORT
2152
2153 /**
2154  * Get information about used SSL chiper.
2155  * @param Idx Connection index number
2156  * @param buf Buffer for returned information text
2157  * @param len Size of return buffer "buf"
2158  * @return true on success, false otherwise
2159  */
2160 GLOBAL bool
2161 Conn_GetCipherInfo(CONN_ID Idx, char *buf, size_t len)
2162 {
2163         if (Idx < 0)
2164                 return false;
2165         assert(Idx < (int) array_length(&My_ConnArray, sizeof(CONNECTION)));
2166         return ConnSSL_GetCipherInfo(&My_Connections[Idx], buf, len);
2167 }
2168
2169
2170 /**
2171  * Check if a connection is SSL-enabled or not.
2172  * @param Idx Connection index number
2173  * @return true if connection is SSL-enabled, false otherwise.
2174  */
2175 GLOBAL bool
2176 Conn_UsesSSL(CONN_ID Idx)
2177 {
2178         if (Idx < 0)
2179                 return false;
2180         assert(Idx < (int) array_length(&My_ConnArray, sizeof(CONNECTION)));
2181         return Conn_OPTION_ISSET(&My_Connections[Idx], CONN_SSL);
2182 }
2183
2184 #endif
2185
2186
2187 #ifdef DEBUG
2188
2189 GLOBAL void
2190 Conn_DebugDump(void)
2191 {
2192         int i;
2193
2194         Log(LOG_DEBUG, "Connection status:");
2195         for (i = 0; i < Pool_Size; i++) {
2196                 if (My_Connections[i].sock == NONE)
2197                         continue;
2198                 Log(LOG_DEBUG,
2199                     " - %d: host=%s, lastdata=%ld, lastping=%ld, delaytime=%ld, flag=%d, options=%d, bps=%d, client=%s",
2200                     My_Connections[i].sock, My_Connections[i].host,
2201                     My_Connections[i].lastdata, My_Connections[i].lastping,
2202                     My_Connections[i].delaytime, My_Connections[i].flag,
2203                     My_Connections[i].options, My_Connections[i].bps,
2204                     My_Connections[i].client ? Client_ID(My_Connections[i].client) : "-");
2205         }
2206 } /* Conn_DumpClients */
2207
2208 #endif
2209
2210
2211 /* -eof- */