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