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