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