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