]> arthur.barton.de Git - ngircd-alex.git/blob - src/ngircd/conn.c
TLS/SSL support: code changes.
[ngircd-alex.git] / src / ngircd / conn.c
1 /*
2  * ngIRCd -- The Next Generation IRC Daemon
3  * Copyright (c)2001-2007 Alexander Barton (alex@barton.de)
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  * Connection management
12  */
13
14
15 #define CONN_MODULE
16
17 #include "portab.h"
18 #include "conf-ssl.h"
19 #include "io.h"
20
21 #include "imp.h"
22 #include <assert.h>
23 #ifdef PROTOTYPES
24 #       include <stdarg.h>
25 #else
26 #       include <varargs.h>
27 #endif
28 #include <stdio.h>
29 #include <stdlib.h>
30 #include <unistd.h>
31 #include <errno.h>
32 #include <string.h>
33 #include <sys/socket.h>
34 #include <sys/time.h>
35 #include <sys/types.h>
36 #include <time.h>
37 #include <netinet/in.h>
38
39 #ifdef HAVE_NETINET_IP_H
40 # include <netinet/ip.h>
41 #endif
42
43 #ifdef HAVE_STDINT_H
44 # include <stdint.h>                    /* e.g. for Mac OS X */
45 #endif
46
47 #ifdef TCPWRAP
48 # include <tcpd.h>                      /* for TCP Wrappers */
49 #endif
50
51 #include "array.h"
52 #include "defines.h"
53 #include "resolve.h"
54
55 #include "exp.h"
56 #include "conn.h"
57
58 #include "imp.h"
59 #include "ngircd.h"
60 #include "client.h"
61 #include "conf.h"
62 #include "conn-ssl.h"
63 #include "conn-zip.h"
64 #include "conn-func.h"
65 #include "log.h"
66 #include "parse.h"
67 #include "tool.h"
68
69 #ifdef ZEROCONF
70 # include "rendezvous.h"
71 #endif
72
73 #include "exp.h"
74
75
76 #define SERVER_WAIT (NONE - 1)
77
78
79 static bool Handle_Write PARAMS(( CONN_ID Idx ));
80 static bool Conn_Write PARAMS(( CONN_ID Idx, char *Data, size_t Len ));
81 static int New_Connection PARAMS(( int Sock ));
82 static CONN_ID Socket2Index PARAMS(( int Sock ));
83 static void Read_Request PARAMS(( CONN_ID Idx ));
84 static void Handle_Buffer PARAMS(( CONN_ID Idx ));
85 static void Check_Connections PARAMS(( void ));
86 static void Check_Servers PARAMS(( void ));
87 static void Init_Conn_Struct PARAMS(( CONN_ID Idx ));
88 static bool Init_Socket PARAMS(( int Sock ));
89 static void New_Server PARAMS(( int Server, ng_ipaddr_t *dest ));
90 static void Simple_Message PARAMS(( int Sock, const char *Msg ));
91 static int NewListener PARAMS(( const char *listen_addr, UINT16 Port ));
92
93 static array My_Listeners;
94 static array My_ConnArray;
95 static size_t NumConnections;
96
97 #ifdef TCPWRAP
98 int allow_severity = LOG_INFO;
99 int deny_severity = LOG_ERR;
100 #endif
101
102 static void server_login PARAMS((CONN_ID idx));
103
104 #ifdef SSL_SUPPORT
105 extern struct SSLOptions Conf_SSLOptions;
106 static void cb_connserver_login_ssl PARAMS((int sock, short what));
107 static void cb_clientserver_ssl PARAMS((int sock, short what));
108 #endif
109 static void cb_Read_Resolver_Result PARAMS(( int sock, UNUSED short what));
110 static void cb_Connect_to_Server PARAMS(( int sock, UNUSED short what));
111 static void cb_clientserver PARAMS((int sock, short what));
112
113 static void
114 cb_listen(int sock, short irrelevant)
115 {
116         (void) irrelevant;
117         if (New_Connection( sock ) >= 0)
118                 NumConnections++;
119 }
120
121
122 #ifdef SSL_SUPPORT
123 static void
124 cb_listen_ssl(int sock, short irrelevant)
125 {
126         int fd;
127         (void) irrelevant;
128         fd = New_Connection(sock);
129         if (fd < 0)
130                 return;
131
132         NumConnections++;
133         io_event_setcb(My_Connections[fd].sock, cb_clientserver_ssl);
134 }
135 #endif
136
137
138 static void
139 cb_connserver(int sock, UNUSED short what)
140 {
141         int res, err;
142         socklen_t sock_len;
143         CONN_ID idx = Socket2Index( sock );
144         if (idx <= NONE) {
145                 LogDebug("cb_connserver wants to write on unknown socket?!");
146                 io_close(sock);
147                 return;
148         }
149
150         assert( what & IO_WANTWRITE);
151
152         /* connect() finished, get result. */
153         sock_len = sizeof( err );
154         res = getsockopt( My_Connections[idx].sock, SOL_SOCKET, SO_ERROR, &err, &sock_len );
155         assert( sock_len == sizeof( err ));
156
157         /* Error while connecting? */
158         if ((res != 0) || (err != 0)) {
159                 if (res != 0)
160                         Log(LOG_CRIT, "getsockopt (connection %d): %s!",
161                             idx, strerror(errno));
162                 else
163                         Log(LOG_CRIT,
164                             "Can't connect socket to \"%s:%d\" (connection %d): %s!",
165                             My_Connections[idx].host,
166                             Conf_Server[Conf_GetServer(idx)].port,
167                             idx, strerror(err));
168
169                 res = Conf_GetServer(idx);
170                 assert(res >= 0);
171
172                 Conn_Close(idx, "Can't connect!", NULL, false);
173
174                 if (res < 0)
175                         return;
176                 if (ng_ipaddr_af(&Conf_Server[res].dst_addr[0])) {
177                         /* more addresses to try... */
178                         New_Server(res, &Conf_Server[res].dst_addr[0]);
179                         /* connection to dst_addr[0] in progress, remove this address... */
180                         Conf_Server[res].dst_addr[0] = Conf_Server[res].dst_addr[1];
181
182                         memset(&Conf_Server[res].dst_addr[1], 0, sizeof(&Conf_Server[res].dst_addr[1]));
183                 }
184                 return;
185         }
186
187         res = Conf_GetServer(idx);
188         assert(res >= 0);
189         if (res >= 0) /* connect succeeded, remove all additional addresses */
190                 memset(&Conf_Server[res].dst_addr, 0, sizeof(&Conf_Server[res].dst_addr));
191         Conn_OPTION_DEL( &My_Connections[idx], CONN_ISCONNECTING );
192 #ifdef SSL_SUPPORT
193         if ( Conn_OPTION_ISSET( &My_Connections[idx], CONN_SSL_CONNECT )) {
194                 io_event_setcb( sock, cb_connserver_login_ssl );
195                 io_event_add( sock, IO_WANTWRITE|IO_WANTREAD );
196                 return;
197         }
198 #endif
199         server_login(idx);
200 }
201
202
203 static void
204 server_login(CONN_ID idx)
205 {
206         Log( LOG_INFO, "Connection %d with \"%s:%d\" established. Now logging in ...", idx,
207                         My_Connections[idx].host, Conf_Server[Conf_GetServer( idx )].port );
208
209         io_event_setcb( My_Connections[idx].sock, cb_clientserver);
210         io_event_add( My_Connections[idx].sock, IO_WANTREAD|IO_WANTWRITE);
211
212         /* Send PASS and SERVER command to peer */
213         Conn_WriteStr( idx, "PASS %s %s", Conf_Server[Conf_GetServer( idx )].pwd_out, NGIRCd_ProtoID );
214         Conn_WriteStr( idx, "SERVER %s :%s", Conf_ServerName, Conf_ServerInfo );
215 }
216
217
218 #ifdef SSL_SUPPORT
219 static void
220 cb_connserver_login_ssl(int sock, short unused)
221 {
222         CONN_ID idx = Socket2Index(sock);
223
224         assert(idx >= 0);
225         if (idx < 0) {
226                 io_close(sock);
227                 return;
228         }
229         (void) unused;
230         switch (ConnSSL_Connect( &My_Connections[idx])) {
231         case 1: break;
232         case 0: LogDebug("ConnSSL_Connect: not ready");
233                 return;
234         case -1:
235                 Log(LOG_INFO, "SSL connection on socket %d failed", sock);
236                 Conn_Close(idx, "Can't connect!", NULL, false);
237                 return;
238         }
239
240         Log( LOG_INFO, "SSL Connection %d with \"%s:%d\" established.", idx,
241                         My_Connections[idx].host, Conf_Server[Conf_GetServer( idx )].port );
242
243         server_login(idx);
244 }
245 #endif
246
247
248 static void
249 cb_clientserver(int sock, short what)
250 {
251         CONN_ID idx = Socket2Index(sock);
252
253         assert(idx >= 0);
254
255         if (idx < 0) {
256                 io_close(sock);
257                 return;
258         }
259 #ifdef SSL_SUPPORT
260         if (what & IO_WANTREAD || (Conn_OPTION_ISSET(&My_Connections[idx], CONN_SSL_WANT_WRITE)))
261                 Read_Request( idx ); /* if TLS layer needs to write additional data, call Read_Request instead so SSL/TLS can continue */
262 #else
263         if (what & IO_WANTREAD)
264                 Read_Request( idx );
265 #endif
266         if (what & IO_WANTWRITE)
267                 Handle_Write( idx );
268 }
269
270
271 #ifdef SSL_SUPPORT
272 static void
273 cb_clientserver_ssl(int sock, short what)
274 {
275         CONN_ID idx = Socket2Index(sock);
276
277         assert(idx >= 0);
278
279         if (idx < 0) {
280                 io_close(sock);
281                 return;
282         }
283
284         switch (ConnSSL_Accept(&My_Connections[idx])) {
285                 case 1: break;  /* OK */
286                 case 0: return; /* EAGAIN: this callback will be invoked again by the io layer */
287                 default:
288                         Conn_Close( idx, "Socket closed!", "SSL accept error", false );
289                         return;
290         }
291         if (what & IO_WANTREAD)
292                 Read_Request(idx);
293
294         if (what & IO_WANTWRITE)
295                 Handle_Write(idx);
296
297         io_event_setcb(sock, cb_clientserver);  /* SSL handshake completed */
298 }
299 #endif
300
301
302 GLOBAL void
303 Conn_Init( void )
304 {
305         /* Modul initialisieren: statische Strukturen "ausnullen". */
306
307         CONN_ID i;
308
309         /* Speicher fuer Verbindungs-Pool anfordern */
310         Pool_Size = CONNECTION_POOL;
311         if ((Conf_MaxConnections > 0) &&
312                 (Pool_Size > Conf_MaxConnections))
313                         Pool_Size = Conf_MaxConnections;
314
315         if (!array_alloc(&My_ConnArray, sizeof(CONNECTION), (size_t)Pool_Size)) {
316                 Log( LOG_EMERG, "Can't allocate memory! [Conn_Init]" );
317                 exit( 1 );
318         }
319
320         /* FIXME: My_Connetions/Pool_Size is needed by other parts of the
321          * code; remove them! */
322         My_Connections = (CONNECTION*) array_start(&My_ConnArray);
323
324         LogDebug("Allocated connection pool for %d items (%ld bytes).",
325                 array_length(&My_ConnArray, sizeof( CONNECTION )), array_bytes(&My_ConnArray));
326
327         assert( array_length(&My_ConnArray, sizeof( CONNECTION )) >= (size_t) Pool_Size);
328         
329         array_free( &My_Listeners );
330
331         /* Connection-Struktur initialisieren */
332         for( i = 0; i < Pool_Size; i++ ) Init_Conn_Struct( i );
333
334         /* Global write counter */
335         WCounter = 0;
336 } /* Conn_Init */
337
338
339 GLOBAL void
340 Conn_Exit( void )
341 {
342         /* Modul abmelden: alle noch offenen Connections
343          * schliessen und freigeben. */
344
345         CONN_ID idx;
346
347         LogDebug("Shutting down all connections ..." );
348
349         Conn_ExitListeners();
350
351         /* Sockets schliessen */
352         for( idx = 0; idx < Pool_Size; idx++ ) {
353                 if( My_Connections[idx].sock > NONE ) {
354                         Conn_Close( idx, NULL, NGIRCd_SignalRestart ?
355                                 "Server going down (restarting)":"Server going down", true );
356                 }
357         }
358
359         array_free(&My_ConnArray);
360         My_Connections = NULL;
361         Pool_Size = 0;
362         io_library_shutdown();
363 } /* Conn_Exit */
364
365
366 static unsigned int
367 ports_initlisteners(array *a, const char *listen_addr, void (*func)(int,short))
368 {
369         unsigned int created = 0;
370         size_t len;
371         int fd;
372         UINT16 *port;
373
374         len = array_length(a, sizeof (UINT16));
375         port = array_start(a);
376         while (len--) {
377                 fd = NewListener(listen_addr, *port);
378                 if (fd < 0) {
379                         port++;
380                         continue;
381                 }
382                 if (!io_event_create( fd, IO_WANTREAD, func )) {
383                         Log( LOG_ERR, "io_event_create(): Could not add listening fd %d (port %u): %s!",
384                                                 fd, (unsigned int) *port, strerror(errno));
385                         close(fd);
386                         port++;
387                         continue;
388                 }
389                 created++;
390                 port++;
391         }
392         return created;
393 }
394
395
396 GLOBAL unsigned int
397 Conn_InitListeners( void )
398 {
399         /* Initialize ports on which the server should accept connections */
400         unsigned int created = 0;
401         char *copy, *listen_addr;
402
403         if (!io_library_init(CONNECTION_POOL)) {
404                 Log(LOG_EMERG, "Cannot initialize IO routines: %s", strerror(errno));
405                 return -1;
406         }
407
408         assert(Conf_ListenAddress);
409
410         /* can't use Conf_ListenAddress directly, see below */
411         copy = strdup(Conf_ListenAddress);
412         if (!copy) {
413                 Log(LOG_CRIT, "Cannot copy %s: %s", Conf_ListenAddress, strerror(errno));
414                 return 0;
415         }
416         listen_addr = strtok(copy, ",");
417
418         while (listen_addr) {
419                 ngt_TrimStr(listen_addr);
420                 if (*listen_addr) {
421                         created += ports_initlisteners(&Conf_ListenPorts, listen_addr, cb_listen);
422 #ifdef SSL_SUPPORT
423                         created += ports_initlisteners(&Conf_SSLOptions.ListenPorts, listen_addr, cb_listen_ssl);
424 #endif
425                 }
426
427                 listen_addr = strtok(NULL, ",");
428         }
429
430         /*
431          * can't free() Conf_ListenAddress here. On /REHASH, if the config file
432          * cannot be re-loaded, we'd end up with a NULL Conf_ListenAddress.
433          * Instead, free() takes place in conf.c, before the config file
434          * is being parsed.
435          */
436         free(copy);
437         return created;
438 } /* Conn_InitListeners */
439
440
441 GLOBAL void
442 Conn_ExitListeners( void )
443 {
444         /* Close down all listening sockets */
445         int *fd;
446         size_t arraylen;
447 #ifdef ZEROCONF
448         Rendezvous_UnregisterListeners( );
449 #endif
450
451         arraylen = array_length(&My_Listeners, sizeof (int));
452         Log( LOG_INFO, "Shutting down all listening sockets (%d total)...", arraylen );
453         fd = array_start(&My_Listeners);
454         while(arraylen--) {
455                 assert(fd != NULL);
456                 assert(*fd >= 0);
457                 io_close(*fd);
458                 LogDebug("Listening socket %d closed.", *fd );
459                 fd++;
460         }
461         array_free(&My_Listeners);
462 } /* Conn_ExitListeners */
463
464
465 static bool
466 InitSinaddrListenAddr(ng_ipaddr_t *addr, const char *listen_addrstr, UINT16 Port)
467 {
468         bool ret;
469
470         ret = ng_ipaddr_init(addr, listen_addrstr, Port);
471         if (!ret) {
472                 assert(listen_addrstr);
473                 Log(LOG_CRIT, "Can't bind to [%s]:%u: can't convert ip address \"%s\"",
474                                                 listen_addrstr, Port, listen_addrstr);
475         }
476         return ret;
477 }
478
479
480 static void
481 set_v6_only(int af, int sock)
482 {
483 #if defined(IPV6_V6ONLY) && defined(WANT_IPV6)
484         int on = 1;
485
486         if (af != AF_INET6)
487                 return;
488
489         if (setsockopt(sock, IPPROTO_IPV6, IPV6_V6ONLY, &on, sizeof(on)))
490                 Log(LOG_ERR, "Could not set IPV6_V6ONLY: %s", strerror(errno));
491 #else
492         (void)af;
493         (void)sock;
494 #endif
495 }
496
497
498 /* return new listening port file descriptor or -1 on failure */
499 static int
500 NewListener(const char *listen_addr, UINT16 Port)
501 {
502         /* Create new listening socket on specified port */
503         ng_ipaddr_t addr;
504         int sock, af;
505 #ifdef ZEROCONF
506         char name[CLIENT_ID_LEN], *info;
507 #endif
508         if (!InitSinaddrListenAddr(&addr, listen_addr, Port))
509                 return -1;
510
511         af = ng_ipaddr_af(&addr);
512         sock = socket(af, SOCK_STREAM, 0);
513         if( sock < 0 ) {
514                 Log(LOG_CRIT, "Can't create socket (af %d) : %s!", af, strerror(errno));
515                 return -1;
516         }
517
518         set_v6_only(af, sock);
519
520         if (!Init_Socket(sock))
521                 return -1;
522
523         if (bind(sock, (struct sockaddr *)&addr, ng_ipaddr_salen(&addr)) != 0) {
524                 Log(LOG_CRIT, "Can't bind socket to address %s:%d - %s",
525                         ng_ipaddr_tostr(&addr), Port, strerror(errno));
526                 close(sock);
527                 return -1;
528         }
529
530         if( listen( sock, 10 ) != 0 ) {
531                 Log( LOG_CRIT, "Can't listen on socket: %s!", strerror( errno ));
532                 close( sock );
533                 return -1;
534         }
535
536         /* keep fd in list so we can close it when ngircd restarts/shuts down */
537         if (!array_catb( &My_Listeners,(char*) &sock, sizeof(int) )) {
538                 Log( LOG_CRIT, "Can't add socket to My_Listeners array: %s!", strerror( errno ));
539                 close( sock );
540                 return -1;
541         }
542
543         Log(LOG_INFO, "Now listening on [%s]:%d (socket %d).", ng_ipaddr_tostr(&addr), Port, sock);
544
545 #ifdef ZEROCONF
546         /* Get best server description text */
547         if( ! Conf_ServerInfo[0] ) info = Conf_ServerName;
548         else
549         {
550                 /* Use server info string */
551                 info = NULL;
552                 if( Conf_ServerInfo[0] == '[' )
553                 {
554                         /* Cut off leading hostname part in "[]" */
555                         info = strchr( Conf_ServerInfo, ']' );
556                         if( info )
557                         {
558                                 info++;
559                                 while( *info == ' ' ) info++;
560                         }
561                 }
562                 if( ! info ) info = Conf_ServerInfo;
563         }
564
565         /* Add port number to description if non-standard */
566         if (Port != 6667)
567                 snprintf(name, sizeof name, "%s (port %u)", info,
568                          (unsigned int)Port);
569         else
570                 strlcpy(name, info, sizeof name);
571
572         /* Register service */
573         Rendezvous_Register( name, MDNS_TYPE, Port );
574 #endif
575         return sock;
576 } /* NewListener */
577
578 #ifdef SSL_SUPPORT
579 /*
580  * SSL/TLS connections require extra treatment:
581  * When either CONN_SSL_WANT_WRITE or CONN_SSL_WANT_READ is set, we
582  * need to take care of that first, before checking read/write buffers.
583  * For instance, while we might have data in our write buffer, the
584  * TLS/SSL protocol might need to read internal data first for TLS/SSL
585  * writes to succeed.
586  *
587  * If this function returns true, such a condition is met and we have
588  * to reverse the condition (check for read even if we've data to write,
589  * do not check for read but writeability even if write-buffer is empty).
590  */
591 static bool
592 SSL_WantRead(const CONNECTION *c)
593 {
594         if (Conn_OPTION_ISSET(c, CONN_SSL_WANT_READ)) {
595                 io_event_add(c->sock, IO_WANTREAD);
596                 return true;
597         }
598         return false;
599 }
600 static bool
601 SSL_WantWrite(const CONNECTION *c)
602 {
603         if (Conn_OPTION_ISSET(c, CONN_SSL_WANT_WRITE)) {
604                 io_event_add(c->sock, IO_WANTWRITE);
605                 return true;
606         }
607         return false;
608 }
609 #else
610 static inline bool
611 SSL_WantRead(UNUSED const CONNECTION *c) { return false; }
612 static inline bool
613 SSL_WantWrite(UNUSED const CONNECTION *c) { return false; }
614 #endif
615
616
617 /**
618  * "Main Loop": Loop until shutdown or restart is signalled.
619  * This function loops until a shutdown or restart of ngIRCd is signalled and
620  * calls io_dispatch() to check for readable and writable sockets every second.
621  * It checks for status changes on pending connections (e. g. when a hostname
622  * has been resolved), checks for "penalties" and timeouts, and handles the
623  * input buffers.
624  */
625 GLOBAL void
626 Conn_Handler(void)
627 {
628         int i;
629         unsigned int wdatalen;
630         struct timeval tv;
631         time_t t;
632
633         while (!NGIRCd_SignalQuit && !NGIRCd_SignalRestart) {
634                 t = time(NULL);
635
636 #ifdef ZEROCONF
637                 Rendezvous_Handler();
638 #endif
639
640                 /* Should the configuration be reloaded? */
641                 if (NGIRCd_SignalRehash)
642                         NGIRCd_Rehash();
643
644                 /* Check configured servers and established links */
645                 Check_Servers();
646                 Check_Connections();
647
648                 /* Look for non-empty read buffers ... */
649                 for (i = 0; i < Pool_Size; i++) {
650                         if ((My_Connections[i].sock > NONE)
651                             && (array_bytes(&My_Connections[i].rbuf) > 0)
652                             && (My_Connections[i].delaytime < t)) {
653                                 /* ... and try to handle the received data */
654                                 Handle_Buffer(i);
655                         }
656                 }
657
658                 /* Look for non-empty write buffers ... */
659                 for (i = 0; i < Pool_Size; i++) {
660                         if (My_Connections[i].sock <= NONE)
661                                 continue;
662
663                         wdatalen = (unsigned int)array_bytes(&My_Connections[i].wbuf);
664 #ifdef ZLIB
665                         if (wdatalen > 0 ||
666                             array_bytes(&My_Connections[i].zip.wbuf) > 0)
667 #else
668                         if (wdatalen > 0)
669 #endif
670                         {
671                                 if (SSL_WantRead(&My_Connections[i]))
672                                         continue;
673                                 io_event_add(My_Connections[i].sock,
674                                              IO_WANTWRITE);
675                         }
676                 }
677
678                 /* Check from which sockets we possibly could read ... */
679                 for (i = 0; i < Pool_Size; i++) {
680                         if (My_Connections[i].sock <= NONE)
681                                 continue;
682 #ifdef SSL_SUPPORT
683                         if (SSL_WantWrite(&My_Connections[i]))
684                                 continue; /* TLS/SSL layer needs to write data; deal with this first */
685 #endif
686                         if (Resolve_INPROGRESS(&My_Connections[i].res_stat)) {
687                                 /* Wait for completion of resolver sub-process ... */
688                                 io_event_del(My_Connections[i].sock,
689                                              IO_WANTREAD);
690                                 continue;
691                         }
692
693                         if (Conn_OPTION_ISSET(&My_Connections[i], CONN_ISCONNECTING))
694                                 /* Wait for completion of connect() ... */
695                                 continue;
696
697                         if (My_Connections[i].delaytime > t) {
698                                 /* There is a "penalty time" set: ignore socket! */
699                                 io_event_del(My_Connections[i].sock,
700                                              IO_WANTREAD);
701                                 continue;
702                         }
703                         io_event_add(My_Connections[i].sock, IO_WANTREAD);
704                 }
705
706                 /* Set the timeout for reading from the network to 1 second,
707                  * which is the granularity with witch we handle "penalty
708                  * times" for example.
709                  * Note: tv_sec/usec are undefined(!) after io_dispatch()
710                  * returns, so we have to set it beforce each call to it! */
711                 tv.tv_usec = 0;
712                 tv.tv_sec = 1;
713
714                 /* Wait for activity ... */
715                 i = io_dispatch(&tv);
716                 if (i == -1 && errno != EINTR) {
717                         Log(LOG_EMERG, "Conn_Handler(): io_dispatch(): %s!",
718                             strerror(errno));
719                         Log(LOG_ALERT, "%s exiting due to fatal errors!",
720                             PACKAGE_NAME);
721                         exit(1);
722                 }
723         }
724
725         if (NGIRCd_SignalQuit)
726                 Log(LOG_NOTICE | LOG_snotice, "Server going down NOW!");
727         else if (NGIRCd_SignalRestart)
728                 Log(LOG_NOTICE | LOG_snotice, "Server restarting NOW!");
729 } /* Conn_Handler */
730
731
732 /**
733  * Write a text string into the socket of a connection.
734  * This function automatically appends CR+LF to the string and validates that
735  * the result is a valid IRC message (oversized messages are shortened, for
736  * example). Then it calls the Conn_Write() function to do the actual sending.
737  * @param Idx Index fo the connection.
738  * @param Format Format string, see printf().
739  * @return true on success, false otherwise.
740  */
741 #ifdef PROTOTYPES
742 GLOBAL bool
743 Conn_WriteStr( CONN_ID Idx, char *Format, ... )
744 #else
745 GLOBAL bool 
746 Conn_WriteStr( Idx, Format, va_alist )
747 CONN_ID Idx;
748 char *Format;
749 va_dcl
750 #endif
751 {
752         char buffer[COMMAND_LEN];
753         size_t len;
754         bool ok;
755         va_list ap;
756
757         assert( Idx > NONE );
758         assert( Format != NULL );
759
760 #ifdef PROTOTYPES
761         va_start( ap, Format );
762 #else
763         va_start( ap );
764 #endif
765         if (vsnprintf( buffer, COMMAND_LEN - 2, Format, ap ) >= COMMAND_LEN - 2 ) {
766                 /*
767                  * The string that should be written to the socket is longer
768                  * than the allowed size of COMMAND_LEN bytes (including both
769                  * the CR and LF characters). This can be caused by the
770                  * IRC_WriteXXX() functions when the prefix of this server had
771                  * to be added to an already "quite long" command line which
772                  * has been received from a regular IRC client, for example.
773                  * 
774                  * We are not allowed to send such "oversized" messages to
775                  * other servers and clients, see RFC 2812 2.3 and 2813 3.3
776                  * ("these messages SHALL NOT exceed 512 characters in length,
777                  * counting all characters including the trailing CR-LF").
778                  *
779                  * So we have a big problem here: we should send more bytes
780                  * to the network than we are allowed to and we don't know
781                  * the originator (any more). The "old" behaviour of blaming
782                  * the receiver ("next hop") is a bad idea (it could be just
783                  * an other server only routing the message!), so the only
784                  * option left is to shorten the string and to hope that the
785                  * result is still somewhat useful ...
786                  *                                                   -alex-
787                  */
788
789                 strcpy (buffer + sizeof(buffer) - strlen(CUT_TXTSUFFIX) - 2 - 1,
790                         CUT_TXTSUFFIX);
791         }
792
793 #ifdef SNIFFER
794         if (NGIRCd_Sniffer)
795                 Log(LOG_DEBUG, " -> connection %d: '%s'.", Idx, buffer);
796 #endif
797
798         len = strlcat( buffer, "\r\n", sizeof( buffer ));
799         ok = Conn_Write(Idx, buffer, len);
800         My_Connections[Idx].msg_out++;
801
802         va_end( ap );
803         return ok;
804 } /* Conn_WriteStr */
805
806
807 /**
808  * Append Data to the outbound write buffer of a connection.
809  * @param Idx Index of the connection.
810  * @param Data pointer to the data.
811  * @param Len length of Data.
812  * @return true on success, false otherwise.
813  */
814 static bool
815 Conn_Write( CONN_ID Idx, char *Data, size_t Len )
816 {
817         CLIENT *c;
818         size_t writebuf_limit = WRITEBUFFER_LEN;
819         assert( Idx > NONE );
820         assert( Data != NULL );
821         assert( Len > 0 );
822
823         c = Conn_GetClient(Idx);
824         assert( c != NULL);
825
826         /* Servers do get special write buffer limits, so they can generate
827          * all the messages that are required while peering. */
828         if (Client_Type(c) == CLIENT_SERVER)
829                 writebuf_limit = WRITEBUFFER_SLINK_LEN;
830
831         /* Is the socket still open? A previous call to Conn_Write()
832          * may have closed the connection due to a fatal error.
833          * In this case it is sufficient to return an error, as well. */
834         if( My_Connections[Idx].sock <= NONE ) {
835                 LogDebug("Skipped write on closed socket (connection %d).", Idx);
836                 return false;
837         }
838
839 #ifdef ZLIB
840         if ( Conn_OPTION_ISSET( &My_Connections[Idx], CONN_ZIP )) {
841                 /* Compressed link:
842                  * Zip_Buffer() does all the dirty work for us: it flushes
843                  * the (pre-)compression buffers if required and handles
844                  * all error conditions. */
845                 if (!Zip_Buffer(Idx, Data, Len))
846                         return false;
847         }
848         else
849 #endif
850         {
851                 /* Uncompressed link:
852                  * Check if outbound buffer has enough space for the data. */
853                 if (array_bytes(&My_Connections[Idx].wbuf) + Len >=
854                     writebuf_limit) {
855                         /* Buffer is full, flush it. Handle_Write deals with
856                          * low-level errors, if any. */
857                         if (!Handle_Write(Idx))
858                                 return false;
859                 }
860
861                 /* When the write buffer is still too big after flushing it,
862                  * the connection will be killed. */
863                 if (array_bytes(&My_Connections[Idx].wbuf) + Len >=
864                     writebuf_limit) {
865                         Log(LOG_NOTICE,
866                             "Write buffer overflow (connection %d, size %lu byte)!",
867                             Idx,
868                             (unsigned long)array_bytes(&My_Connections[Idx].wbuf));
869                         Conn_Close(Idx, "Write buffer overflow!", NULL, false);
870                         return false;
871                 }
872
873                 /* Copy data to write buffer */
874                 if (!array_catb(&My_Connections[Idx].wbuf, Data, Len))
875                         return false;
876
877                 My_Connections[Idx].bytes_out += Len;
878         }
879
880         /* Adjust global write counter */
881         WCounter += Len;
882
883         return true;
884 } /* Conn_Write */
885
886
887 GLOBAL void
888 Conn_Close( CONN_ID Idx, char *LogMsg, char *FwdMsg, bool InformClient )
889 {
890         /* Close connection. Open pipes of asyncronous resolver
891          * sub-processes are closed down. */
892
893         CLIENT *c;
894         char *txt;
895         double in_k, out_k;
896         UINT16 port;
897 #ifdef ZLIB
898         double in_z_k, out_z_k;
899         int in_p, out_p;
900 #endif
901
902         assert( Idx > NONE );
903
904         /* Is this link already shutting down? */
905         if( Conn_OPTION_ISSET( &My_Connections[Idx], CONN_ISCLOSING )) {
906                 /* Conn_Close() has been called recursively for this link;
907                  * probabe reason: Handle_Write() failed  -- see below. */
908                 LogDebug("Recursive request to close connection: %d", Idx );
909                 return;
910         }
911
912         assert( My_Connections[Idx].sock > NONE );
913
914         /* Mark link as "closing" */
915         Conn_OPTION_ADD( &My_Connections[Idx], CONN_ISCLOSING );
916
917         if (LogMsg)
918                 txt = LogMsg;
919         else
920                 txt = FwdMsg;
921         if (! txt)
922                 txt = "Reason unknown";
923
924         port = ng_ipaddr_getport(&My_Connections[Idx].addr);
925         Log(LOG_INFO, "Shutting down connection %d (%s) with %s:%d ...", Idx,
926             LogMsg ? LogMsg : FwdMsg, My_Connections[Idx].host, port);
927
928         /* Search client, if any */
929         c = Conn_GetClient( Idx );
930
931         /* Should the client be informed? */
932         if (InformClient) {
933 #ifndef STRICT_RFC
934                 /* Send statistics to client if registered as user: */
935                 if ((c != NULL) && (Client_Type(c) == CLIENT_USER)) {
936                         Conn_WriteStr( Idx,
937                          ":%s NOTICE %s :%sConnection statistics: client %.1f kb, server %.1f kb.",
938                          Client_ID(Client_ThisServer()), Client_ID(c),
939                          NOTICE_TXTPREFIX,
940                          (double)My_Connections[Idx].bytes_in / 1024,
941                          (double)My_Connections[Idx].bytes_out / 1024);
942                 }
943 #endif
944                 /* Send ERROR to client (see RFC!) */
945                 if (FwdMsg)
946                         Conn_WriteStr(Idx, "ERROR :%s", FwdMsg);
947                 else
948                         Conn_WriteStr(Idx, "ERROR :Closing connection.");
949         }
950
951         /* Try to write out the write buffer. Note: Handle_Write() eventually
952          * removes the CLIENT structure associated with this connection if an
953          * error occurs! So we have to re-check if there is still an valid
954          * CLIENT structure after calling Handle_Write() ...*/
955         (void)Handle_Write( Idx );
956
957         /* Search client, if any (re-check!) */
958         c = Conn_GetClient( Idx );
959 #ifdef SSL_SUPPORT
960         if ( Conn_OPTION_ISSET( &My_Connections[Idx], CONN_SSL )) {
961                 Log( LOG_INFO, "SSL Connection %d shutting down", Idx );
962                 ConnSSL_Free(&My_Connections[Idx]);
963         }
964 #endif
965         /* Shut down socket */
966         if (! io_close(My_Connections[Idx].sock)) {
967                 /* Oops, we can't close the socket!? This is ... ugly! */
968                 Log(LOG_CRIT,
969                     "Error closing connection %d (socket %d) with %s:%d - %s! (ignored)",
970                     Idx, My_Connections[Idx].sock, My_Connections[Idx].host,
971                     port, strerror(errno));
972         }
973
974         /* Mark socket as invalid: */
975         My_Connections[Idx].sock = NONE;
976
977         /* If there is still a client, unregister it now */
978         if (c)
979                 Client_Destroy(c, LogMsg, FwdMsg, true);
980
981         /* Calculate statistics and log information */
982         in_k = (double)My_Connections[Idx].bytes_in / 1024;
983         out_k = (double)My_Connections[Idx].bytes_out / 1024;
984 #ifdef ZLIB
985         if (Conn_OPTION_ISSET( &My_Connections[Idx], CONN_ZIP)) {
986                 in_z_k = (double)My_Connections[Idx].zip.bytes_in / 1024;
987                 out_z_k = (double)My_Connections[Idx].zip.bytes_out / 1024;
988                 /* Make sure that no division by zero can occur during
989                  * the calculation of in_p and out_p: in_z_k and out_z_k
990                  * are non-zero, that's guaranteed by the protocol until
991                  * compression can be enabled. */
992                 if (! in_z_k)
993                         in_z_k = in_k;
994                 if (! out_z_k)
995                         out_z_k = out_k;
996                 in_p = (int)(( in_k * 100 ) / in_z_k );
997                 out_p = (int)(( out_k * 100 ) / out_z_k );
998                 Log(LOG_INFO,
999                     "Connection %d with %s:%d closed (in: %.1fk/%.1fk/%d%%, out: %.1fk/%.1fk/%d%%).",
1000                     Idx, My_Connections[Idx].host, port,
1001                     in_k, in_z_k, in_p, out_k, out_z_k, out_p);
1002         }
1003         else
1004 #endif
1005         {
1006                 Log(LOG_INFO,
1007                     "Connection %d with %s:%d closed (in: %.1fk, out: %.1fk).",
1008                     Idx, My_Connections[Idx].host, port,
1009                     in_k, out_k);
1010         }
1011
1012         /* cancel running resolver */
1013         if (Resolve_INPROGRESS(&My_Connections[Idx].res_stat))
1014                 Resolve_Shutdown(&My_Connections[Idx].res_stat);
1015
1016         /* Servers: Modify time of next connect attempt? */
1017         Conf_UnsetServer( Idx );
1018
1019 #ifdef ZLIB
1020         /* Clean up zlib, if link was compressed */
1021         if ( Conn_OPTION_ISSET( &My_Connections[Idx], CONN_ZIP )) {
1022                 inflateEnd( &My_Connections[Idx].zip.in );
1023                 deflateEnd( &My_Connections[Idx].zip.out );
1024                 array_free(&My_Connections[Idx].zip.rbuf);
1025                 array_free(&My_Connections[Idx].zip.wbuf);
1026         }
1027 #endif
1028
1029         array_free(&My_Connections[Idx].rbuf);
1030         array_free(&My_Connections[Idx].wbuf);
1031
1032         /* Clean up connection structure (=free it) */
1033         Init_Conn_Struct( Idx );
1034
1035         assert(NumConnections > 0);
1036         if (NumConnections)
1037                 NumConnections--;
1038         LogDebug("Shutdown of connection %d completed", Idx );
1039 } /* Conn_Close */
1040
1041
1042 GLOBAL void
1043 Conn_SyncServerStruct( void )
1044 {
1045         /* Synchronize server structures (connection IDs):
1046          * connections <-> configuration */
1047
1048         CLIENT *client;
1049         CONN_ID i;
1050         int c;
1051
1052         for( i = 0; i < Pool_Size; i++ ) {
1053                 /* Established connection? */
1054                 if (My_Connections[i].sock < 0)
1055                         continue;
1056
1057                 /* Server connection? */
1058                 client = Conn_GetClient( i );
1059                 if(( ! client ) || ( Client_Type( client ) != CLIENT_SERVER )) continue;
1060
1061                 for( c = 0; c < MAX_SERVERS; c++ )
1062                 {
1063                         /* Configured server? */
1064                         if( ! Conf_Server[c].host[0] ) continue;
1065
1066                         /* Duplicate? */
1067                         if( strcmp( Conf_Server[c].name, Client_ID( client )) == 0 )
1068                                 Conf_Server[c].conn_id = i;
1069                 }
1070         }
1071 } /* SyncServerStruct */
1072
1073
1074 /**
1075  * Send out data of write buffer; connect new sockets.
1076  */
1077 static bool
1078 Handle_Write( CONN_ID Idx )
1079 {
1080         ssize_t len;
1081         size_t wdatalen;
1082
1083         assert( Idx > NONE );
1084         if ( My_Connections[Idx].sock < 0 ) {
1085                 LogDebug("Handle_Write() on closed socket, connection %d", Idx);
1086                 return false;
1087         }
1088         assert( My_Connections[Idx].sock > NONE );
1089
1090         wdatalen = array_bytes(&My_Connections[Idx].wbuf );
1091
1092 #ifdef ZLIB
1093         if (wdatalen == 0) {
1094                 /* Write buffer is empty, so we try to flush the compression
1095                  * buffer and get some data to work with from there :-) */
1096                 if (!Zip_Flush(Idx))
1097                         return false;
1098
1099                 /* Now the write buffer most probably has changed: */
1100                 wdatalen = array_bytes(&My_Connections[Idx].wbuf);
1101         }
1102 #endif
1103
1104         if (wdatalen == 0) {
1105                 /* Still no data, fine. */
1106                 io_event_del(My_Connections[Idx].sock, IO_WANTWRITE );
1107                 return true;
1108         }
1109
1110         LogDebug
1111             ("Handle_Write() called for connection %d, %ld bytes pending ...",
1112              Idx, wdatalen);
1113
1114 #ifdef SSL_SUPPORT
1115         if ( Conn_OPTION_ISSET( &My_Connections[Idx], CONN_SSL )) {
1116                 len = ConnSSL_Write(&My_Connections[Idx], array_start(&My_Connections[Idx].wbuf), wdatalen);
1117         } else
1118 #endif
1119         {
1120                 len = write(My_Connections[Idx].sock,
1121                             array_start(&My_Connections[Idx].wbuf), wdatalen );
1122         }
1123         if( len < 0 ) {
1124                 if (errno == EAGAIN || errno == EINTR)
1125                         return true;
1126
1127                 Log(LOG_ERR, "Write error on connection %d (socket %d): %s!",
1128                     Idx, My_Connections[Idx].sock, strerror(errno));
1129                 Conn_Close(Idx, "Write error!", NULL, false);
1130                 return false;
1131         }
1132
1133         /* move any data not yet written to beginning */
1134         array_moveleft(&My_Connections[Idx].wbuf, 1, (size_t)len);
1135
1136         return true;
1137 } /* Handle_Write */
1138
1139
1140 static int
1141 Count_Connections(ng_ipaddr_t *a)
1142 {
1143         int i, cnt;
1144
1145         cnt = 0;
1146         for (i = 0; i < Pool_Size; i++) {
1147                 if (My_Connections[i].sock <= NONE)
1148                         continue;
1149                 if (ng_ipaddr_ipequal(&My_Connections[i].addr, a))
1150                         cnt++;
1151         }
1152         return cnt;
1153 } /* Count_Connections */
1154
1155
1156 static int
1157 New_Connection( int Sock )
1158 {
1159         /* Neue Client-Verbindung von Listen-Socket annehmen und
1160          * CLIENT-Struktur anlegen. */
1161
1162 #ifdef TCPWRAP
1163         struct request_info req;
1164 #endif
1165         ng_ipaddr_t new_addr;
1166         char ip_str[NG_INET_ADDRSTRLEN];
1167         int new_sock, new_sock_len;
1168         CLIENT *c;
1169         long cnt;
1170
1171         assert( Sock > NONE );
1172         /* Connection auf Listen-Socket annehmen */
1173         new_sock_len = (int)sizeof(new_addr);
1174
1175         new_sock = accept(Sock, (struct sockaddr *)&new_addr,
1176                           (socklen_t *)&new_sock_len);
1177         if (new_sock < 0) {
1178                 Log(LOG_CRIT, "Can't accept connection: %s!", strerror(errno));
1179                 return -1;
1180         }
1181
1182         if (!ng_ipaddr_tostr_r(&new_addr, ip_str)) {
1183                 Log(LOG_CRIT, "fd %d: Can't convert IP address!", new_sock);
1184                 Simple_Message(new_sock, "ERROR :Internal Server Error");
1185                 close(new_sock);
1186                 return -1;
1187         }
1188
1189 #ifdef TCPWRAP
1190         /* Validate socket using TCP Wrappers */
1191         request_init( &req, RQ_DAEMON, PACKAGE_NAME, RQ_FILE, new_sock, RQ_CLIENT_SIN, &new_addr, NULL );
1192         fromhost(&req);
1193         if (!hosts_access(&req)) {
1194                 Log (deny_severity, "Refused connection from %s (by TCP Wrappers)!", ip_str);
1195                 Simple_Message( new_sock, "ERROR :Connection refused" );
1196                 close( new_sock );
1197                 return -1;
1198         }
1199 #endif
1200
1201         /* Socket initialisieren */
1202         if (!Init_Socket( new_sock ))
1203                 return -1;
1204
1205         /* Check IP-based connection limit */
1206         cnt = Count_Connections(&new_addr);
1207         if ((Conf_MaxConnectionsIP > 0) && (cnt >= Conf_MaxConnectionsIP)) {
1208                 /* Access denied, too many connections from this IP address! */
1209                 Log( LOG_ERR, "Refused connection from %s: too may connections (%ld) from this IP address!", ip_str, cnt);
1210                 Simple_Message( new_sock, "ERROR :Connection refused, too many connections from your IP address!" );
1211                 close( new_sock );
1212                 return -1;
1213         }
1214
1215         if ((Conf_MaxConnections > 0) &&
1216                 (NumConnections >= (size_t) Conf_MaxConnections))
1217         {
1218                 Log( LOG_ALERT, "Can't accept connection: limit (%d) reached!", Conf_MaxConnections);
1219                 Simple_Message( new_sock, "ERROR :Connection limit reached" );
1220                 close( new_sock );
1221                 return -1;
1222         }
1223
1224         if( new_sock >= Pool_Size ) {
1225                 if (!array_alloc(&My_ConnArray, sizeof(CONNECTION),
1226                                  (size_t)new_sock)) {
1227                         Log( LOG_EMERG, "Can't allocate memory! [New_Connection]" );
1228                         Simple_Message( new_sock, "ERROR: Internal error" );
1229                         close( new_sock );
1230                         return -1;
1231                 }
1232                 LogDebug("Bumped connection pool to %ld items (internal: %ld items, %ld bytes)",
1233                         new_sock, array_length(&My_ConnArray, sizeof(CONNECTION)), array_bytes(&My_ConnArray));
1234
1235                 /* Adjust pointer to new block */
1236                 My_Connections = array_start(&My_ConnArray);
1237                 while (Pool_Size <= new_sock)
1238                         Init_Conn_Struct(Pool_Size++);
1239         }
1240
1241         /* register callback */
1242         if (!io_event_create( new_sock, IO_WANTREAD, cb_clientserver)) {
1243                 Log(LOG_ALERT, "Can't accept connection: io_event_create failed!");
1244                 Simple_Message(new_sock, "ERROR :Internal error");
1245                 close(new_sock);
1246                 return -1;
1247         }
1248
1249         c = Client_NewLocal(new_sock, ip_str, CLIENT_UNKNOWN, false );
1250         if( ! c ) {
1251                 Log(LOG_ALERT, "Can't accept connection: can't create client structure!");
1252                 Simple_Message(new_sock, "ERROR :Internal error");
1253                 io_close(new_sock);
1254                 return -1;
1255         }
1256
1257         Init_Conn_Struct( new_sock );
1258         My_Connections[new_sock].sock = new_sock;
1259         My_Connections[new_sock].addr = new_addr;
1260         My_Connections[new_sock].client = c;
1261
1262         Log( LOG_INFO, "Accepted connection %d from %s:%d on socket %d.", new_sock,
1263                         ip_str, ng_ipaddr_getport(&new_addr), Sock);
1264
1265         /* Hostnamen ermitteln */
1266         strlcpy(My_Connections[new_sock].host, ip_str, sizeof(My_Connections[new_sock].host));
1267
1268         Client_SetHostname(c, My_Connections[new_sock].host);
1269
1270         if (!Conf_NoDNS)
1271                 Resolve_Addr(&My_Connections[new_sock].res_stat, &new_addr,
1272                         My_Connections[new_sock].sock, cb_Read_Resolver_Result);
1273
1274         Conn_SetPenalty(new_sock, 4);
1275         return new_sock;
1276 } /* New_Connection */
1277
1278
1279 static CONN_ID
1280 Socket2Index( int Sock )
1281 {
1282         /* zum Socket passende Connection suchen */
1283
1284         assert( Sock >= 0 );
1285
1286         if( Sock >= Pool_Size || My_Connections[Sock].sock != Sock ) {
1287                 /* die Connection wurde vermutlich (wegen eines
1288                  * Fehlers) bereits wieder abgebaut ... */
1289                 LogDebug("Socket2Index: can't get connection for socket %d!", Sock);
1290                 return NONE;
1291         }
1292         return Sock;
1293 } /* Socket2Index */
1294
1295
1296 /**
1297  * Read data from the network to the read buffer. If an error occures,
1298  * the socket of this connection will be shut down.
1299  */
1300 static void
1301 Read_Request( CONN_ID Idx )
1302 {
1303         ssize_t len;
1304         char readbuf[READBUFFER_LEN];
1305         CLIENT *c;
1306         assert( Idx > NONE );
1307         assert( My_Connections[Idx].sock > NONE );
1308
1309 #ifdef ZLIB
1310         if ((array_bytes(&My_Connections[Idx].rbuf) >= READBUFFER_LEN) ||
1311                 (array_bytes(&My_Connections[Idx].zip.rbuf) >= READBUFFER_LEN))
1312 #else
1313         if (array_bytes(&My_Connections[Idx].rbuf) >= READBUFFER_LEN)
1314 #endif
1315         {
1316                 /* Read buffer is full */
1317                 Log(LOG_ERR,
1318                     "Receive buffer overflow (connection %d): %d bytes!",
1319                     Idx, array_bytes(&My_Connections[Idx].rbuf));
1320                 Conn_Close( Idx, "Receive buffer overflow!", NULL, false );
1321                 return;
1322         }
1323
1324 #ifdef SSL_SUPPORT
1325         if (Conn_OPTION_ISSET(&My_Connections[Idx], CONN_SSL))
1326                 len = ConnSSL_Read( &My_Connections[Idx], readbuf, sizeof(readbuf));
1327         else
1328 #endif
1329         len = read(My_Connections[Idx].sock, readbuf, sizeof(readbuf));
1330         if (len == 0) {
1331                 Log(LOG_INFO, "%s:%u (%s) is closing the connection ...",
1332                                 My_Connections[Idx].host,
1333                                 (unsigned int) ng_ipaddr_getport(&My_Connections[Idx].addr),
1334                                 ng_ipaddr_tostr(&My_Connections[Idx].addr));
1335                 Conn_Close(Idx,
1336                            "Socket closed!", "Client closed connection",
1337                            false);
1338                 return;
1339         }
1340
1341         if (len < 0) {
1342                 if( errno == EAGAIN ) return;
1343                 Log(LOG_ERR, "Read error on connection %d (socket %d): %s!",
1344                     Idx, My_Connections[Idx].sock, strerror(errno));
1345                 Conn_Close(Idx, "Read error!", "Client closed connection",
1346                            false);
1347                 return;
1348         }
1349 #ifdef ZLIB
1350         if (Conn_OPTION_ISSET(&My_Connections[Idx], CONN_ZIP)) {
1351                 if (!array_catb(&My_Connections[Idx].zip.rbuf, readbuf,
1352                                 (size_t) len)) {
1353                         Log(LOG_ERR,
1354                             "Could not append recieved data to zip input buffer (connn %d): %d bytes!",
1355                             Idx, len);
1356                         Conn_Close(Idx, "Receive buffer overflow!", NULL,
1357                                    false);
1358                         return;
1359                 }
1360         } else
1361 #endif
1362         {
1363                 if (!array_catb( &My_Connections[Idx].rbuf, readbuf, len)) {
1364                         Log( LOG_ERR, "Could not append recieved data to input buffer (connn %d): %d bytes!", Idx, len );
1365                         Conn_Close( Idx, "Receive buffer overflow!", NULL, false );
1366                 }
1367         }
1368
1369         /* Update connection statistics */
1370         My_Connections[Idx].bytes_in += len;
1371
1372         /* Update timestamp of last data received if this connection is
1373          * registered as a user, server or service connection. Don't update
1374          * otherwise, so users have at least Conf_PongTimeout seconds time to
1375          * register with the IRC server -- see Check_Connections().
1376          * Set "lastping", too, so we can handle time shifts backwards ... */
1377         c = Conn_GetClient(Idx);
1378         if (c && (Client_Type(c) == CLIENT_USER
1379                   || Client_Type(c) == CLIENT_SERVER
1380                   || Client_Type(c) == CLIENT_SERVICE)) {
1381                 My_Connections[Idx].lastdata = time(NULL);
1382                 My_Connections[Idx].lastping = My_Connections[Idx].lastdata;
1383         }
1384
1385         /* Look at the data in the (read-) buffer of this connection */
1386         Handle_Buffer(Idx);
1387 } /* Read_Request */
1388
1389
1390 /**
1391  * Handle all data in the connection read-buffer.
1392  * All data is precessed until no complete command is left. When a fatal
1393  * error occurs, the connection is shut down.
1394  */
1395 static void
1396 Handle_Buffer(CONN_ID Idx)
1397 {
1398 #ifndef STRICT_RFC
1399         char *ptr1, *ptr2, *first_eol;
1400 #endif
1401         char *ptr;
1402         size_t len, delta;
1403         time_t starttime;
1404 #ifdef ZLIB
1405         bool old_z;
1406 #endif
1407
1408         starttime = time(NULL);
1409         for (;;) {
1410                 /* Check penalty */
1411                 if (My_Connections[Idx].delaytime > starttime)
1412                         return;
1413 #ifdef ZLIB
1414                 /* Unpack compressed data, if compression is in use */
1415                 if (Conn_OPTION_ISSET(&My_Connections[Idx], CONN_ZIP)) {
1416                         /* When unzipping fails, Unzip_Buffer() shuts
1417                          * down the connection itself */
1418                         if (!Unzip_Buffer(Idx))
1419                                 return;
1420                 }
1421 #endif
1422
1423                 if (0 == array_bytes(&My_Connections[Idx].rbuf))
1424                         return;
1425
1426                 /* Make sure that the buffer is NULL terminated */
1427                 if (!array_cat0_temporary(&My_Connections[Idx].rbuf)) {
1428                         Conn_Close(Idx, NULL,
1429                                    "Can't allocate memory [Handle_Buffer]",
1430                                    true);
1431                         return;
1432                 }
1433
1434                 /* RFC 2812, section "2.3 Messages", 5th paragraph:
1435                  * "IRC messages are always lines of characters terminated
1436                  * with a CR-LF (Carriage Return - Line Feed) pair [...]". */
1437                 delta = 2;
1438                 ptr = strstr(array_start(&My_Connections[Idx].rbuf), "\r\n");
1439
1440 #ifndef STRICT_RFC
1441                 /* Check for non-RFC-compliant request (only CR or LF)?
1442                  * Unfortunately, there are quite a few clients out there
1443                  * that do this -- e. g. mIRC, BitchX, and Trillian :-( */
1444                 ptr1 = strchr(array_start(&My_Connections[Idx].rbuf), '\r');
1445                 ptr2 = strchr(array_start(&My_Connections[Idx].rbuf), '\n');
1446                 if (ptr) {
1447                         /* Check if there is a single CR or LF _before_ the
1448                          * corerct CR+LF line terminator:  */
1449                         first_eol = ptr1 < ptr2 ? ptr1 : ptr2;
1450                         if (first_eol < ptr) {
1451                                 /* Single CR or LF before CR+LF found */
1452                                 ptr = first_eol;
1453                                 delta = 1;
1454                         }
1455                 } else if (ptr1 || ptr2) {
1456                         /* No CR+LF terminated command found, but single
1457                          * CR or LF found ... */
1458                         if (ptr1 && ptr2)
1459                                 ptr = ptr1 < ptr2 ? ptr1 : ptr2;
1460                         else
1461                                 ptr = ptr1 ? ptr1 : ptr2;
1462                         delta = 1;
1463                 }
1464 #endif
1465
1466                 if (!ptr)
1467                         return;
1468
1469                 /* Complete (=line terminated) request found, handle it! */
1470                 *ptr = '\0';
1471
1472                 len = ptr - (char *)array_start(&My_Connections[Idx].rbuf) + delta;
1473
1474                 if (len > (COMMAND_LEN - 1)) {
1475                         /* Request must not exceed 512 chars (incl. CR+LF!),
1476                          * see RFC 2812. Disconnect Client if this happens. */
1477                         Log(LOG_ERR,
1478                             "Request too long (connection %d): %d bytes (max. %d expected)!",
1479                             Idx, array_bytes(&My_Connections[Idx].rbuf),
1480                             COMMAND_LEN - 1);
1481                         Conn_Close(Idx, NULL, "Request too long", true);
1482                         return;
1483                 }
1484
1485                 if (len <= delta) {
1486                         /* Request is empty (only '\r\n', '\r' or '\n');
1487                          * delta is 2 ('\r\n') or 1 ('\r' or '\n'), see above */
1488                         array_moveleft(&My_Connections[Idx].rbuf, 1, len);
1489                         return;
1490                 }
1491
1492 #ifdef ZLIB
1493                 /* remember if stream is already compressed */
1494                 old_z = My_Connections[Idx].options & CONN_ZIP;
1495 #endif
1496
1497                 My_Connections[Idx].msg_in++;
1498                 if (!Parse_Request
1499                     (Idx, (char *)array_start(&My_Connections[Idx].rbuf)))
1500                         return;
1501
1502                 array_moveleft(&My_Connections[Idx].rbuf, 1, len);
1503                 LogDebug("Connection %d: %d bytes left in read buffer.",
1504                          Idx, array_bytes(&My_Connections[Idx].rbuf));
1505 #ifdef ZLIB
1506                 if ((!old_z) && (My_Connections[Idx].options & CONN_ZIP) &&
1507                     (array_bytes(&My_Connections[Idx].rbuf) > 0)) {
1508                         /* The last command activated socket compression.
1509                          * Data that was read after that needs to be copied
1510                          * to the unzip buffer for decompression: */
1511                         if (!array_copy
1512                             (&My_Connections[Idx].zip.rbuf,
1513                              &My_Connections[Idx].rbuf)) {
1514                                 Conn_Close(Idx, NULL,
1515                                            "Can't allocate memory [Handle_Buffer]",
1516                                            true);
1517                                 return;
1518                         }
1519
1520                         array_trunc(&My_Connections[Idx].rbuf);
1521                         LogDebug
1522                             ("Moved already received data (%u bytes) to uncompression buffer.",
1523                              array_bytes(&My_Connections[Idx].zip.rbuf));
1524                 }
1525 #endif
1526         }
1527 } /* Handle_Buffer */
1528
1529
1530 static void
1531 Check_Connections(void)
1532 {
1533         /* check if connections are alive. if not, play PING-PONG first.
1534          * if this doesn't help either, disconnect client. */
1535         CLIENT *c;
1536         CONN_ID i;
1537
1538         for (i = 0; i < Pool_Size; i++) {
1539                 if (My_Connections[i].sock < 0)
1540                         continue;
1541
1542                 c = Conn_GetClient(i);
1543                 if (c && ((Client_Type(c) == CLIENT_USER)
1544                           || (Client_Type(c) == CLIENT_SERVER)
1545                           || (Client_Type(c) == CLIENT_SERVICE))) {
1546                         /* connected User, Server or Service */
1547                         if (My_Connections[i].lastping >
1548                             My_Connections[i].lastdata) {
1549                                 /* We already sent a ping */
1550                                 if (My_Connections[i].lastping <
1551                                     time(NULL) - Conf_PongTimeout) {
1552                                         /* Timeout */
1553                                         LogDebug
1554                                             ("Connection %d: Ping timeout: %d seconds.",
1555                                              i, Conf_PongTimeout);
1556                                         Conn_Close(i, NULL, "Ping timeout",
1557                                                    true);
1558                                 }
1559                         } else if (My_Connections[i].lastdata <
1560                                    time(NULL) - Conf_PingTimeout) {
1561                                 /* We need to send a PING ... */
1562                                 LogDebug("Connection %d: sending PING ...", i);
1563                                 My_Connections[i].lastping = time(NULL);
1564                                 Conn_WriteStr(i, "PING :%s",
1565                                               Client_ID(Client_ThisServer()));
1566                         }
1567                 } else {
1568                         /* The connection is not fully established yet, so
1569                          * we don't do the PING-PONG game here but instead
1570                          * disconnect the client after "a short time" if it's
1571                          * still not registered. */
1572
1573                         if (My_Connections[i].lastdata <
1574                             time(NULL) - Conf_PongTimeout) {
1575                                 LogDebug
1576                                     ("Unregistered connection %d timed out ...",
1577                                      i);
1578                                 Conn_Close(i, NULL, "Timeout", false);
1579                         }
1580                 }
1581         }
1582 } /* Check_Connections */
1583
1584
1585 static void
1586 Check_Servers( void )
1587 {
1588         /* Check if we can establish further server links */
1589
1590         int i, n;
1591         time_t time_now;
1592
1593         /* Check all configured servers */
1594         for( i = 0; i < MAX_SERVERS; i++ ) {
1595                 /* Valid outgoing server which isn't already connected or disabled? */
1596                 if(( ! Conf_Server[i].host[0] ) || ( ! Conf_Server[i].port > 0 ) ||
1597                         ( Conf_Server[i].conn_id > NONE ) || ( Conf_Server[i].flags & CONF_SFLAG_DISABLED ))
1598                                 continue;
1599
1600                 /* Is there already a connection in this group? */
1601                 if( Conf_Server[i].group > NONE ) {
1602                         for (n = 0; n < MAX_SERVERS; n++) {
1603                                 if (n == i) continue;
1604                                 if ((Conf_Server[n].conn_id != NONE) &&
1605                                         (Conf_Server[n].group == Conf_Server[i].group))
1606                                                 break;
1607                         }
1608                         if (n < MAX_SERVERS) continue;
1609                 }
1610
1611                 /* Check last connect attempt? */
1612                 time_now = time(NULL);
1613                 if( Conf_Server[i].lasttry > (time_now - Conf_ConnectRetry))
1614                         continue;
1615
1616                 /* Okay, try to connect now */
1617                 Conf_Server[i].lasttry = time_now;
1618                 Conf_Server[i].conn_id = SERVER_WAIT;
1619                 assert(Resolve_Getfd(&Conf_Server[i].res_stat) < 0);
1620                 Resolve_Name(&Conf_Server[i].res_stat, Conf_Server[i].host, cb_Connect_to_Server);
1621         }
1622 } /* Check_Servers */
1623
1624
1625 static void
1626 New_Server( int Server , ng_ipaddr_t *dest)
1627 {
1628         /* Establish new server link */
1629         char ip_str[NG_INET_ADDRSTRLEN];
1630         int af_dest, res, new_sock;
1631         CLIENT *c;
1632
1633         assert( Server > NONE );
1634
1635         if (!ng_ipaddr_tostr_r(dest, ip_str)) {
1636                 Log(LOG_WARNING, "New_Server: Could not convert IP to string");
1637                 return;
1638         }
1639
1640         Log( LOG_INFO, "Establishing connection to \"%s\", %s, port %d ... ",
1641                         Conf_Server[Server].host, ip_str, Conf_Server[Server].port );
1642
1643         af_dest = ng_ipaddr_af(dest);
1644         new_sock = socket(af_dest, SOCK_STREAM, 0);
1645         if (new_sock < 0) {
1646                 Log( LOG_CRIT, "Can't create socket (af %d) : %s!", af_dest, strerror( errno ));
1647                 return;
1648         }
1649
1650         if (!Init_Socket(new_sock))
1651                 return;
1652
1653         /* is a bind address configured? */
1654         res = ng_ipaddr_af(&Conf_Server[Server].bind_addr);
1655         /* if yes, bind now. If it fails, warn and let connect() pick a source address */
1656         if (res && bind(new_sock, (struct sockaddr *) &Conf_Server[Server].bind_addr,
1657                                 ng_ipaddr_salen(&Conf_Server[Server].bind_addr)))
1658         {
1659                 ng_ipaddr_tostr_r(&Conf_Server[Server].bind_addr, ip_str);
1660                 Log(LOG_WARNING, "Can't bind socket to %s: %s!", ip_str, strerror(errno));
1661         }
1662         ng_ipaddr_setport(dest, Conf_Server[Server].port);
1663         res = connect(new_sock, (struct sockaddr *) dest, ng_ipaddr_salen(dest));
1664         if(( res != 0 ) && ( errno != EINPROGRESS )) {
1665                 Log( LOG_CRIT, "Can't connect socket: %s!", strerror( errno ));
1666                 close( new_sock );
1667                 return;
1668         }
1669
1670         if (!array_alloc(&My_ConnArray, sizeof(CONNECTION), (size_t)new_sock)) {
1671                 Log(LOG_ALERT,
1672                     "Cannot allocate memory for server connection (socket %d)",
1673                     new_sock);
1674                 close( new_sock );
1675                 return;
1676         }
1677
1678         My_Connections = array_start(&My_ConnArray);
1679
1680         assert(My_Connections[new_sock].sock <= 0);
1681
1682         Init_Conn_Struct(new_sock);
1683
1684         ng_ipaddr_tostr_r(dest, ip_str);
1685         c = Client_NewLocal(new_sock, ip_str, CLIENT_UNKNOWNSERVER, false);
1686         if (!c) {
1687                 Log( LOG_ALERT, "Can't establish connection: can't create client structure!" );
1688                 close( new_sock );
1689                 return;
1690         }
1691
1692         Client_SetIntroducer( c, c );
1693         Client_SetToken( c, TOKEN_OUTBOUND );
1694
1695         /* Register connection */
1696         Conf_Server[Server].conn_id = new_sock;
1697         My_Connections[new_sock].sock = new_sock;
1698         My_Connections[new_sock].addr = *dest;
1699         My_Connections[new_sock].client = c;
1700         strlcpy( My_Connections[new_sock].host, Conf_Server[Server].host,
1701                                 sizeof(My_Connections[new_sock].host ));
1702
1703         /* Register new socket */
1704         if (!io_event_create( new_sock, IO_WANTWRITE, cb_connserver)) {
1705                 Log( LOG_ALERT, "io_event_create(): could not add fd %d", strerror(errno));
1706                 Conn_Close( new_sock, "io_event_create() failed", NULL, false );
1707                 Init_Conn_Struct( new_sock );
1708                 Conf_Server[Server].conn_id = NONE;
1709         }
1710 #ifdef SSL_SUPPORT
1711         if (Conf_Server[Server].SSLConnect && !ConnSSL_PrepareConnect( &My_Connections[new_sock],
1712                                                                 &Conf_Server[Server] ))
1713         {
1714                 Log(LOG_ALERT, "Could not initialize SSL for outgoing connection");
1715                 Conn_Close( new_sock, "Could not initialize SSL for outgoing connection", NULL, false );
1716                 Init_Conn_Struct( new_sock );
1717                 Conf_Server[Server].conn_id = NONE;
1718         }
1719 #endif
1720         LogDebug("Registered new connection %d on socket %d.",
1721                                 new_sock, My_Connections[new_sock].sock );
1722         Conn_OPTION_ADD( &My_Connections[new_sock], CONN_ISCONNECTING );
1723 } /* New_Server */
1724
1725
1726 /**
1727  * Initialize connection structure.
1728  */
1729 static void
1730 Init_Conn_Struct(CONN_ID Idx)
1731 {
1732         time_t now = time(NULL);
1733
1734         memset(&My_Connections[Idx], 0, sizeof(CONNECTION));
1735         My_Connections[Idx].sock = -1;
1736         My_Connections[Idx].signon = now;
1737         My_Connections[Idx].lastdata = now;
1738         My_Connections[Idx].lastprivmsg = now;
1739         Resolve_Init(&My_Connections[Idx].res_stat);
1740 } /* Init_Conn_Struct */
1741
1742
1743 static bool
1744 Init_Socket( int Sock )
1745 {
1746         /* Initialize socket (set options) */
1747
1748         int value;
1749
1750         if (!io_setnonblock(Sock)) {
1751                 Log( LOG_CRIT, "Can't enable non-blocking mode for socket: %s!", strerror( errno ));
1752                 close( Sock );
1753                 return false;
1754         }
1755
1756         /* Don't block this port after socket shutdown */
1757         value = 1;
1758         if( setsockopt( Sock, SOL_SOCKET, SO_REUSEADDR, &value, (socklen_t)sizeof( value )) != 0 )
1759         {
1760                 Log( LOG_ERR, "Can't set socket option SO_REUSEADDR: %s!", strerror( errno ));
1761                 /* ignore this error */
1762         }
1763
1764         /* Set type of service (TOS) */
1765 #if defined(IP_TOS) && defined(IPTOS_LOWDELAY)
1766         value = IPTOS_LOWDELAY;
1767         LogDebug("Setting option IP_TOS on socket %d to IPTOS_LOWDELAY (%d).", Sock, value );
1768         if( setsockopt( Sock, SOL_IP, IP_TOS, &value, (socklen_t)sizeof( value )) != 0 )
1769         {
1770                 Log( LOG_ERR, "Can't set socket option IP_TOS: %s!", strerror( errno ));
1771                 /* ignore this error */
1772         }
1773 #endif
1774
1775         return true;
1776 } /* Init_Socket */
1777
1778
1779
1780 static void
1781 cb_Connect_to_Server(int fd, UNUSED short events)
1782 {
1783         /* Read result of resolver sub-process from pipe and start connection */
1784         int i;
1785         size_t len;
1786         ng_ipaddr_t dest_addrs[4];      /* we can handle at most 3; but we read up to
1787                                            four so we can log the 'more than we can handle'
1788                                            condition */
1789
1790         LogDebug("Resolver: Got forward lookup callback on fd %d, events %d", fd, events);
1791
1792         for (i=0; i < MAX_SERVERS; i++) {
1793                   if (Resolve_Getfd(&Conf_Server[i].res_stat) == fd )
1794                           break;
1795         }
1796
1797         if( i >= MAX_SERVERS) {
1798                 /* Ops, no matching server found?! */
1799                 io_close( fd );
1800                 LogDebug("Resolver: Got Forward Lookup callback for unknown server!?");
1801                 return;
1802         }
1803
1804         /* Read result from pipe */
1805         len = Resolve_Read(&Conf_Server[i].res_stat, dest_addrs, sizeof(dest_addrs));
1806         if (len == 0)
1807                 return;
1808
1809         assert((len % sizeof(ng_ipaddr_t)) == 0);
1810
1811         LogDebug("Got result from resolver: %u structs (%u bytes).", len/sizeof(ng_ipaddr_t), len);
1812
1813         memset(&Conf_Server[i].dst_addr, 0, sizeof(&Conf_Server[i].dst_addr));
1814         if (len > sizeof(ng_ipaddr_t)) {
1815                 /* more than one address for this hostname, remember them
1816                  * in case first address is unreachable/not available */
1817                 len -= sizeof(ng_ipaddr_t);
1818                 if (len > sizeof(&Conf_Server[i].dst_addr)) {
1819                         len = sizeof(&Conf_Server[i].dst_addr);
1820                         Log(LOG_NOTICE, "Notice: Resolver returned more IP Addresses for host than we can handle,"
1821                                         " additional addresses dropped");
1822                 }
1823                 memcpy(&Conf_Server[i].dst_addr, &dest_addrs[1], len);
1824         }
1825         /* connect() */
1826         New_Server(i, dest_addrs);
1827 } /* cb_Read_Forward_Lookup */
1828
1829
1830 static void
1831 cb_Read_Resolver_Result( int r_fd, UNUSED short events )
1832 {
1833         /* Read result of resolver sub-process from pipe and update the
1834          * apropriate connection/client structure(s): hostname and/or
1835          * IDENT user name.*/
1836
1837         CLIENT *c;
1838         int i;
1839         size_t len;
1840         char *identptr;
1841 #ifdef IDENTAUTH
1842         char readbuf[HOST_LEN + 2 + CLIENT_USER_LEN];
1843 #else
1844         char readbuf[HOST_LEN + 1];
1845 #endif
1846
1847         LogDebug("Resolver: Got callback on fd %d, events %d", r_fd, events );
1848
1849         /* Search associated connection ... */
1850         for( i = 0; i < Pool_Size; i++ ) {
1851                 if(( My_Connections[i].sock != NONE )
1852                   && ( Resolve_Getfd(&My_Connections[i].res_stat) == r_fd ))
1853                         break;
1854         }
1855         if( i >= Pool_Size ) {
1856                 /* Ops, none found? Probably the connection has already
1857                  * been closed!? We'll ignore that ... */
1858                 io_close( r_fd );
1859                 LogDebug("Resolver: Got callback for unknown connection!?");
1860                 return;
1861         }
1862
1863         /* Read result from pipe */
1864         len = Resolve_Read(&My_Connections[i].res_stat, readbuf, sizeof readbuf -1);
1865         if (len == 0)
1866                 return;
1867
1868         readbuf[len] = '\0';
1869         identptr = strchr(readbuf, '\n');
1870         assert(identptr != NULL);
1871         if (!identptr) {
1872                 Log( LOG_CRIT, "Resolver: Got malformed result!");
1873                 return;
1874         }
1875
1876         *identptr = '\0';
1877         LogDebug("Got result from resolver: \"%s\" (%u bytes read).", readbuf, len);
1878         /* Okay, we got a complete result: this is a host name for outgoing
1879          * connections and a host name and IDENT user name (if enabled) for
1880          * incoming connections.*/
1881         assert ( My_Connections[i].sock >= 0 );
1882         /* Incoming connection. Search client ... */
1883         c = Conn_GetClient( i );
1884         assert( c != NULL );
1885
1886         /* Only update client information of unregistered clients */
1887         if( Client_Type( c ) == CLIENT_UNKNOWN ) {
1888                 strlcpy(My_Connections[i].host, readbuf, sizeof( My_Connections[i].host));
1889                 Client_SetHostname( c, readbuf);
1890 #ifdef IDENTAUTH
1891                 ++identptr;
1892                 if (*identptr) {
1893                         Log(LOG_INFO, "IDENT lookup for connection %d: \"%s\".", i, identptr);
1894                         Client_SetUser(c, identptr, true);
1895                 } else {
1896                         Log(LOG_INFO, "IDENT lookup for connection %d: no result.", i);
1897                 }
1898 #endif
1899         }
1900 #ifdef DEBUG
1901                 else Log( LOG_DEBUG, "Resolver: discarding result for already registered connection %d.", i );
1902 #endif
1903         /* Reset penalty time */
1904         Conn_ResetPenalty( i );
1905 } /* cb_Read_Resolver_Result */
1906
1907
1908 static void
1909 Simple_Message( int Sock, const char *Msg )
1910 {
1911         char buf[COMMAND_LEN];
1912         size_t len;
1913         /* Write "simple" message to socket, without using compression
1914          * or even the connection write buffers. Used e.g. for error
1915          * messages by New_Connection(). */
1916         assert( Sock > NONE );
1917         assert( Msg != NULL );
1918
1919         strlcpy( buf, Msg, sizeof buf - 2);
1920         len = strlcat( buf, "\r\n", sizeof buf);
1921         (void)write(Sock, buf, len);
1922 } /* Simple_Error */
1923
1924
1925 GLOBAL CLIENT *
1926 Conn_GetClient( CONN_ID Idx ) 
1927 {
1928         /* return Client-Structure that belongs to the local Connection Idx.
1929          * If none is found, return NULL.
1930          */
1931         CONNECTION *c;
1932         assert( Idx >= 0 );
1933
1934         c = array_get(&My_ConnArray, sizeof (CONNECTION), (size_t)Idx);
1935
1936         assert(c != NULL);
1937
1938         return c ? c->client : NULL;
1939 }
1940
1941 #ifdef SSL_SUPPORT
1942 /* we cannot access My_Connections in irc-info.c */
1943 GLOBAL bool
1944 Conn_GetCipherInfo(CONN_ID Idx, char *buf, size_t len)
1945 {
1946         return ConnSSL_GetCipherInfo(&My_Connections[Idx], buf, len);
1947 }
1948
1949
1950 GLOBAL bool
1951 Conn_UsesSSL(CONN_ID Idx)
1952 {
1953         return Conn_OPTION_ISSET(&My_Connections[Idx], CONN_SSL);
1954 }
1955 #endif
1956 /* -eof- */