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