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