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