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