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