2 * ngIRCd -- The Next Generation IRC Daemon
3 * Copyright (c)2001-2007 Alexander Barton (alex@barton.de)
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.
11 * Connection management
20 static char UNUSED id[] = "$Id: conn.c,v 1.221 2008/02/26 22:04:17 fw Exp $";
34 #include <sys/socket.h>
36 #include <sys/types.h>
38 #include <netinet/in.h>
40 #ifdef HAVE_NETINET_IP_H
41 # include <netinet/ip.h>
45 # include <stdint.h> /* e.g. for Mac OS X */
49 # include <tcpd.h> /* for TCP Wrappers */
64 #include "conn-func.h"
70 # include "rendezvous.h"
76 #define SERVER_WAIT (NONE - 1)
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 bool 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(( int af, const UINT16 Port ));
93 static array My_Listeners;
94 static array My_ConnArray;
97 int allow_severity = LOG_INFO;
98 int deny_severity = LOG_ERR;
101 static void server_login PARAMS((CONN_ID idx));
103 static void cb_Read_Resolver_Result PARAMS(( int sock, UNUSED short what));
104 static void cb_Connect_to_Server PARAMS(( int sock, UNUSED short what));
105 static void cb_clientserver PARAMS((int sock, short what));
108 cb_listen(int sock, short irrelevant)
111 New_Connection( sock );
116 cb_connserver(int sock, UNUSED short what)
120 CONN_ID idx = Socket2Index( sock );
122 LogDebug("cb_connserver wants to write on unknown socket?!");
127 assert( what & IO_WANTWRITE);
129 /* connect() finished, get result. */
130 sock_len = sizeof( err );
131 res = getsockopt( My_Connections[idx].sock, SOL_SOCKET, SO_ERROR, &err, &sock_len );
132 assert( sock_len == sizeof( err ));
134 /* Error while connecting? */
135 if ((res != 0) || (err != 0)) {
137 Log(LOG_CRIT, "getsockopt (connection %d): %s!",
138 idx, strerror(errno));
141 "Can't connect socket to \"%s:%d\" (connection %d): %s!",
142 My_Connections[idx].host,
143 Conf_Server[Conf_GetServer(idx)].port,
146 res = Conf_GetServer(idx);
149 Conn_Close(idx, "Can't connect!", NULL, false);
153 if (ng_ipaddr_af(&Conf_Server[res].dst_addr[0])) {
154 /* more addresses to try... */
155 New_Server(res, &Conf_Server[res].dst_addr[0]);
156 /* connection to dst_addr[0] in progress, remove this address... */
157 Conf_Server[res].dst_addr[0] = Conf_Server[res].dst_addr[1];
159 memset(&Conf_Server[res].dst_addr[1], 0, sizeof(&Conf_Server[res].dst_addr[1]));
164 res = Conf_GetServer(idx);
166 if (res >= 0) /* connect succeeded, remove all additional addresses */
167 memset(&Conf_Server[res].dst_addr, 0, sizeof(&Conf_Server[res].dst_addr));
168 Conn_OPTION_DEL( &My_Connections[idx], CONN_ISCONNECTING );
174 server_login(CONN_ID idx)
176 Log( LOG_INFO, "Connection %d with \"%s:%d\" established. Now logging in ...", idx,
177 My_Connections[idx].host, Conf_Server[Conf_GetServer( idx )].port );
179 io_event_setcb( My_Connections[idx].sock, cb_clientserver);
180 io_event_add( My_Connections[idx].sock, IO_WANTREAD|IO_WANTWRITE);
182 /* Send PASS and SERVER command to peer */
183 Conn_WriteStr( idx, "PASS %s %s", Conf_Server[Conf_GetServer( idx )].pwd_out, NGIRCd_ProtoID );
184 Conn_WriteStr( idx, "SERVER %s :%s", Conf_ServerName, Conf_ServerInfo );
189 cb_clientserver(int sock, short what)
191 CONN_ID idx = Socket2Index( sock );
194 Log(LOG_WARNING, "WTF: cb_clientserver wants to write on unknown socket?!");
200 if (what & IO_WANTREAD)
203 if (what & IO_WANTWRITE)
211 /* Modul initialisieren: statische Strukturen "ausnullen". */
215 /* Speicher fuer Verbindungs-Pool anfordern */
216 Pool_Size = CONNECTION_POOL;
217 if( Conf_MaxConnections > 0 )
219 /* konfiguriertes Limit beachten */
220 if( Pool_Size > Conf_MaxConnections ) Pool_Size = Conf_MaxConnections;
223 if (!array_alloc(&My_ConnArray, sizeof(CONNECTION), (size_t)Pool_Size)) {
224 Log( LOG_EMERG, "Can't allocate memory! [Conn_Init]" );
228 /* FIXME: My_Connetions/Pool_Size is needed by other parts of the
229 * code; remove them! */
230 My_Connections = (CONNECTION*) array_start(&My_ConnArray);
232 LogDebug("Allocated connection pool for %d items (%ld bytes).",
233 array_length(&My_ConnArray, sizeof( CONNECTION )), array_bytes(&My_ConnArray));
235 assert( array_length(&My_ConnArray, sizeof( CONNECTION )) >= (size_t) Pool_Size);
237 array_free( &My_Listeners );
239 /* Connection-Struktur initialisieren */
240 for( i = 0; i < Pool_Size; i++ ) Init_Conn_Struct( i );
242 /* Global write counter */
250 /* Modul abmelden: alle noch offenen Connections
251 * schliessen und freigeben. */
255 LogDebug("Shutting down all connections ..." );
257 Conn_ExitListeners();
259 /* Sockets schliessen */
260 for( idx = 0; idx < Pool_Size; idx++ ) {
261 if( My_Connections[idx].sock > NONE ) {
262 Conn_Close( idx, NULL, NGIRCd_SignalRestart ?
263 "Server going down (restarting)":"Server going down", true );
267 array_free(&My_ConnArray);
268 My_Connections = NULL;
270 io_library_shutdown();
275 ports_initlisteners(array *a, int af, void (*func)(int,short))
277 unsigned int created = 0;
282 len = array_length(a, sizeof (UINT16));
283 port = array_start(a);
285 fd = NewListener(af, *port);
290 if (!io_event_create( fd, IO_WANTREAD, func )) {
291 Log( LOG_ERR, "io_event_create(): Could not add listening fd %d (port %u): %s!",
292 fd, (unsigned int) *port, strerror(errno));
306 Conn_InitListeners( void )
308 /* Initialize ports on which the server should accept connections */
310 unsigned int created = 0;
312 if (!io_library_init(CONNECTION_POOL)) {
313 Log(LOG_EMERG, "Cannot initialize IO routines: %s", strerror(errno));
319 created = ports_initlisteners(&Conf_ListenPorts, AF_INET6, cb_listen);
322 created += ports_initlisteners(&Conf_ListenPorts, AF_INET, cb_listen);
325 } /* Conn_InitListeners */
329 Conn_ExitListeners( void )
331 /* Close down all listening sockets */
335 Rendezvous_UnregisterListeners( );
338 arraylen = array_length(&My_Listeners, sizeof (int));
339 Log( LOG_INFO, "Shutting down all listening sockets (%d total)...", arraylen );
340 fd = array_start(&My_Listeners);
345 LogDebug("Listening socket %d closed.", *fd );
348 array_free(&My_Listeners);
349 } /* Conn_ExitListeners */
353 InitSinaddrListenAddr(int af, ng_ipaddr_t *addr, UINT16 Port)
356 const char *listen_addrstr = NULL;
359 listen_addrstr = "0.0.0.0";
363 if (Conf_ListenAddress[0]) /* overrides V4/V6 atm */
364 listen_addrstr = Conf_ListenAddress;
366 ret = ng_ipaddr_init(addr, listen_addrstr, Port);
370 Log(LOG_CRIT, "Can't bind to %s:%u: can't convert ip address \"%s\"",
371 listen_addrstr, Port, listen_addrstr);
378 set_v6_only(int af, int sock)
380 #if defined(IPV6_V6ONLY) && defined(WANT_IPV6)
386 if (setsockopt(sock, IPPROTO_IPV6, IPV6_V6ONLY, &on, sizeof(on)))
387 Log(LOG_ERR, "Could not set IPV6_V6ONLY: %s", strerror(errno));
395 /* return new listening port file descriptor or -1 on failure */
397 NewListener(int af, const UINT16 Port)
399 /* Create new listening socket on specified port */
403 char name[CLIENT_ID_LEN], *info;
405 if (!InitSinaddrListenAddr(af, &addr, Port))
408 sock = socket(ng_ipaddr_af(&addr), SOCK_STREAM, 0);
410 Log( LOG_CRIT, "Can't create socket: %s!", strerror( errno ));
414 af = ng_ipaddr_af(&addr);
416 set_v6_only(af, sock);
418 if( ! Init_Socket( sock )) return -1;
420 if (bind(sock, (struct sockaddr *)&addr, ng_ipaddr_salen(&addr)) != 0) {
421 Log( LOG_CRIT, "Can't bind socket (port %d) : %s!", Port, strerror( errno ));
426 if( listen( sock, 10 ) != 0 ) {
427 Log( LOG_CRIT, "Can't listen on socket: %s!", strerror( errno ));
432 /* keep fd in list so we can close it when ngircd restarts/shuts down */
433 if (!array_catb( &My_Listeners,(char*) &sock, sizeof(int) )) {
434 Log( LOG_CRIT, "Can't add socket to My_Listeners array: %s!", strerror( errno ));
441 Log(LOG_INFO, "Now listening on [%s]:%d (socket %d).", ng_ipaddr_tostr(&addr), Port, sock);
444 Log(LOG_INFO, "Now listening on %s:%d (socket %d).", ng_ipaddr_tostr(&addr), Port, sock);
447 /* Get best server description text */
448 if( ! Conf_ServerInfo[0] ) info = Conf_ServerName;
451 /* Use server info string */
453 if( Conf_ServerInfo[0] == '[' )
455 /* Cut off leading hostname part in "[]" */
456 info = strchr( Conf_ServerInfo, ']' );
460 while( *info == ' ' ) info++;
463 if( ! info ) info = Conf_ServerInfo;
466 /* Add port number to description if non-standard */
468 snprintf(name, sizeof name, "%s (port %u)", info,
471 strlcpy(name, info, sizeof name);
473 /* Register service */
474 Rendezvous_Register( name, MDNS_TYPE, Port );
483 /* "Main Loop.": Loop until a signal (for shutdown or restart) arrives.
484 * Call io_dispatch() to check for read/writeable sockets every second
485 * Wait for status change on pending connections (e.g: when the hostname has been resolved)
486 * check for penalty/timeouts
487 * handle input buffers
490 unsigned int wdatalen;
495 while(( ! NGIRCd_SignalQuit ) && ( ! NGIRCd_SignalRestart )) {
499 Rendezvous_Handler( );
502 /* Should the configuration be reloaded? */
503 if (NGIRCd_SignalRehash) {
507 /* Check configured servers and established links */
509 Check_Connections( );
513 /* noch volle Lese-Buffer suchen */
514 for( i = 0; i < Pool_Size; i++ ) {
515 if(( My_Connections[i].sock > NONE ) && ( array_bytes(&My_Connections[i].rbuf) > 0 ) &&
516 ( My_Connections[i].delaytime < t ))
518 /* Kann aus dem Buffer noch ein Befehl extrahiert werden? */
519 if (Handle_Buffer( i )) timeout = false;
523 /* noch volle Schreib-Puffer suchen */
524 for( i = 0; i < Pool_Size; i++ ) {
525 if ( My_Connections[i].sock <= NONE )
528 wdatalen = (unsigned int)array_bytes(&My_Connections[i].wbuf);
531 if (( wdatalen > 0 ) || ( array_bytes(&My_Connections[i].zip.wbuf)> 0 ))
536 /* Socket der Verbindung in Set aufnehmen */
537 io_event_add( My_Connections[i].sock, IO_WANTWRITE );
541 /* von welchen Sockets koennte gelesen werden? */
542 for (i = 0; i < Pool_Size; i++ ) {
543 if ( My_Connections[i].sock <= NONE )
546 if (Resolve_INPROGRESS(&My_Connections[i].res_stat)) {
547 /* wait for completion of Resolver Sub-Process */
548 io_event_del( My_Connections[i].sock, IO_WANTREAD );
552 if ( Conn_OPTION_ISSET( &My_Connections[i], CONN_ISCONNECTING ))
553 continue; /* wait for completion of connect() */
555 if( My_Connections[i].delaytime > t ) {
556 /* Fuer die Verbindung ist eine "Penalty-Zeit" gesetzt */
557 io_event_del( My_Connections[i].sock, IO_WANTREAD );
560 io_event_add( My_Connections[i].sock, IO_WANTREAD );
563 /* (re-)set timeout - tv_sec/usec are undefined after io_dispatch() returns */
565 tv.tv_sec = timeout ? 1 : 0;
567 /* wait for activity */
568 i = io_dispatch( &tv );
569 if (i == -1 && errno != EINTR ) {
570 Log(LOG_EMERG, "Conn_Handler(): io_dispatch(): %s!", strerror(errno));
571 Log(LOG_ALERT, "%s exiting due to fatal errors!", PACKAGE_NAME);
576 if( NGIRCd_SignalQuit ) Log( LOG_NOTICE|LOG_snotice, "Server going down NOW!" );
577 else if( NGIRCd_SignalRestart ) Log( LOG_NOTICE|LOG_snotice, "Server restarting NOW!" );
582 * Write a text string into the socket of a connection.
583 * This function automatically appends CR+LF to the string and validates that
584 * the result is a valid IRC message (oversized messages are shortened, for
585 * example). Then it calls the Conn_Write() function to do the actual sending.
586 * @param Idx Index fo the connection.
587 * @param Format Format string, see printf().
588 * @return true on success, false otherwise.
592 Conn_WriteStr( CONN_ID Idx, char *Format, ... )
595 Conn_WriteStr( Idx, Format, va_alist )
601 char buffer[COMMAND_LEN];
606 assert( Idx > NONE );
607 assert( Format != NULL );
610 va_start( ap, Format );
614 if (vsnprintf( buffer, COMMAND_LEN - 2, Format, ap ) >= COMMAND_LEN - 2 ) {
616 * The string that should be written to the socket is longer
617 * than the allowed size of COMMAND_LEN bytes (including both
618 * the CR and LF characters). This can be caused by the
619 * IRC_WriteXXX() functions when the prefix of this server had
620 * to be added to an already "quite long" command line which
621 * has been received from a regular IRC client, for example.
623 * We are not allowed to send such "oversized" messages to
624 * other servers and clients, see RFC 2812 2.3 and 2813 3.3
625 * ("these messages SHALL NOT exceed 512 characters in length,
626 * counting all characters including the trailing CR-LF").
628 * So we have a big problem here: we should send more bytes
629 * to the network than we are allowed to and we don't know
630 * the originator (any more). The "old" behaviour of blaming
631 * the receiver ("next hop") is a bad idea (it could be just
632 * an other server only routing the message!), so the only
633 * option left is to shorten the string and to hope that the
634 * result is still somewhat useful ...
638 strcpy (buffer + sizeof(buffer) - strlen(CUT_TXTSUFFIX) - 2 - 1,
644 Log(LOG_DEBUG, " -> connection %d: '%s'.", Idx, buffer);
647 len = strlcat( buffer, "\r\n", sizeof( buffer ));
648 ok = Conn_Write(Idx, buffer, len);
649 My_Connections[Idx].msg_out++;
653 } /* Conn_WriteStr */
657 * Append Data to the outbound write buffer of a connection.
658 * @param Idx Index of the connection.
659 * @param Data pointer to the data.
660 * @param Len length of Data.
661 * @return true on success, false otherwise.
664 Conn_Write( CONN_ID Idx, char *Data, size_t Len )
667 size_t writebuf_limit = WRITEBUFFER_LEN;
668 assert( Idx > NONE );
669 assert( Data != NULL );
672 c = Conn_GetClient(Idx);
675 /* Servers do get special write buffer limits, so they can generate
676 * all the messages that are required while peering. */
677 if (Client_Type(c) == CLIENT_SERVER)
678 writebuf_limit = WRITEBUFFER_SLINK_LEN;
680 /* Is the socket still open? A previous call to Conn_Write()
681 * may have closed the connection due to a fatal error.
682 * In this case it is sufficient to return an error, as well. */
683 if( My_Connections[Idx].sock <= NONE ) {
684 LogDebug("Skipped write on closed socket (connection %d).", Idx);
689 if ( Conn_OPTION_ISSET( &My_Connections[Idx], CONN_ZIP )) {
691 * Zip_Buffer() does all the dirty work for us: it flushes
692 * the (pre-)compression buffers if required and handles
693 * all error conditions. */
694 if (!Zip_Buffer(Idx, Data, Len))
700 /* Uncompressed link:
701 * Check if outbound buffer has enough space for the data. */
702 if (array_bytes(&My_Connections[Idx].wbuf) + Len >=
704 /* Buffer is full, flush it. Handle_Write deals with
705 * low-level errors, if any. */
706 if (!Handle_Write(Idx))
710 /* When the write buffer is still too big after flushing it,
711 * the connection will be killed. */
712 if (array_bytes(&My_Connections[Idx].wbuf) + Len >=
715 "Write buffer overflow (connection %d, size %lu byte)!",
717 (unsigned long)array_bytes(&My_Connections[Idx].wbuf));
718 Conn_Close(Idx, "Write buffer overflow!", NULL, false);
722 /* Copy data to write buffer */
723 if (!array_catb(&My_Connections[Idx].wbuf, Data, Len))
726 My_Connections[Idx].bytes_out += Len;
729 /* Adjust global write counter */
737 Conn_Close( CONN_ID Idx, char *LogMsg, char *FwdMsg, bool InformClient )
739 /* Close connection. Open pipes of asyncronous resolver
740 * sub-processes are closed down. */
747 double in_z_k, out_z_k;
751 assert( Idx > NONE );
753 /* Is this link already shutting down? */
754 if( Conn_OPTION_ISSET( &My_Connections[Idx], CONN_ISCLOSING )) {
755 /* Conn_Close() has been called recursively for this link;
756 * probabe reason: Handle_Write() failed -- see below. */
757 LogDebug("Recursive request to close connection: %d", Idx );
761 assert( My_Connections[Idx].sock > NONE );
763 /* Mark link as "closing" */
764 Conn_OPTION_ADD( &My_Connections[Idx], CONN_ISCLOSING );
771 txt = "Reason unknown";
773 port = ng_ipaddr_getport(&My_Connections[Idx].addr);
774 Log(LOG_INFO, "Shutting down connection %d (%s) with %s:%d ...", Idx,
775 LogMsg ? LogMsg : FwdMsg, My_Connections[Idx].host, port);
777 /* Search client, if any */
778 c = Conn_GetClient( Idx );
780 /* Should the client be informed? */
783 /* Send statistics to client if registered as user: */
784 if ((c != NULL) && (Client_Type(c) == CLIENT_USER)) {
786 ":%s NOTICE %s :%sConnection statistics: client %.1f kb, server %.1f kb.",
787 Client_ID(Client_ThisServer()), Client_ID(c),
789 (double)My_Connections[Idx].bytes_in / 1024,
790 (double)My_Connections[Idx].bytes_out / 1024);
793 /* Send ERROR to client (see RFC!) */
795 Conn_WriteStr(Idx, "ERROR :%s", FwdMsg);
797 Conn_WriteStr(Idx, "ERROR :Closing connection.");
800 /* Try to write out the write buffer. Note: Handle_Write() eventually
801 * removes the CLIENT structure associated with this connection if an
802 * error occurs! So we have to re-check if there is still an valid
803 * CLIENT structure after calling Handle_Write() ...*/
804 (void)Handle_Write( Idx );
806 /* Search client, if any (re-check!) */
807 c = Conn_GetClient( Idx );
809 /* Shut down socket */
810 if (! io_close(My_Connections[Idx].sock)) {
811 /* Oops, we can't close the socket!? This is ... ugly! */
813 "Error closing connection %d (socket %d) with %s:%d - %s! (ignored)",
814 Idx, My_Connections[Idx].sock, My_Connections[Idx].host,
815 port, strerror(errno));
818 /* Mark socket as invalid: */
819 My_Connections[Idx].sock = NONE;
821 /* If there is still a client, unregister it now */
823 Client_Destroy(c, LogMsg, FwdMsg, true);
825 /* Calculate statistics and log information */
826 in_k = (double)My_Connections[Idx].bytes_in / 1024;
827 out_k = (double)My_Connections[Idx].bytes_out / 1024;
829 if (Conn_OPTION_ISSET( &My_Connections[Idx], CONN_ZIP)) {
830 in_z_k = (double)My_Connections[Idx].zip.bytes_in / 1024;
831 out_z_k = (double)My_Connections[Idx].zip.bytes_out / 1024;
832 /* Make sure that no division by zero can occur during
833 * the calculation of in_p and out_p: in_z_k and out_z_k
834 * are non-zero, that's guaranteed by the protocol until
835 * compression can be enabled. */
840 in_p = (int)(( in_k * 100 ) / in_z_k );
841 out_p = (int)(( out_k * 100 ) / out_z_k );
843 "Connection %d with %s:%d closed (in: %.1fk/%.1fk/%d%%, out: %.1fk/%.1fk/%d%%).",
844 Idx, My_Connections[Idx].host, port,
845 in_k, in_z_k, in_p, out_k, out_z_k, out_p);
851 "Connection %d with %s:%d closed (in: %.1fk, out: %.1fk).",
852 Idx, My_Connections[Idx].host, port,
856 /* cancel running resolver */
857 if (Resolve_INPROGRESS(&My_Connections[Idx].res_stat))
858 Resolve_Shutdown(&My_Connections[Idx].res_stat);
860 /* Servers: Modify time of next connect attempt? */
861 Conf_UnsetServer( Idx );
864 /* Clean up zlib, if link was compressed */
865 if ( Conn_OPTION_ISSET( &My_Connections[Idx], CONN_ZIP )) {
866 inflateEnd( &My_Connections[Idx].zip.in );
867 deflateEnd( &My_Connections[Idx].zip.out );
868 array_free(&My_Connections[Idx].zip.rbuf);
869 array_free(&My_Connections[Idx].zip.wbuf);
873 array_free(&My_Connections[Idx].rbuf);
874 array_free(&My_Connections[Idx].wbuf);
876 /* Clean up connection structure (=free it) */
877 Init_Conn_Struct( Idx );
879 LogDebug("Shutdown of connection %d completed.", Idx );
884 Conn_SyncServerStruct( void )
886 /* Synchronize server structures (connection IDs):
887 * connections <-> configuration */
893 for( i = 0; i < Pool_Size; i++ ) {
894 /* Established connection? */
895 if (My_Connections[i].sock < 0)
898 /* Server connection? */
899 client = Conn_GetClient( i );
900 if(( ! client ) || ( Client_Type( client ) != CLIENT_SERVER )) continue;
902 for( c = 0; c < MAX_SERVERS; c++ )
904 /* Configured server? */
905 if( ! Conf_Server[c].host[0] ) continue;
908 if( strcmp( Conf_Server[c].name, Client_ID( client )) == 0 )
909 Conf_Server[c].conn_id = i;
912 } /* SyncServerStruct */
916 * Send out data of write buffer; connect new sockets.
919 Handle_Write( CONN_ID Idx )
924 assert( Idx > NONE );
925 if ( My_Connections[Idx].sock < 0 ) {
926 LogDebug("Handle_Write() on closed socket, connection %d", Idx);
929 assert( My_Connections[Idx].sock > NONE );
931 wdatalen = array_bytes(&My_Connections[Idx].wbuf );
935 /* Write buffer is empty, so we try to flush the compression
936 * buffer and get some data to work with from there :-) */
940 /* Now the write buffer most probably has changed: */
941 wdatalen = array_bytes(&My_Connections[Idx].wbuf);
946 /* Still no data, fine. */
947 io_event_del(My_Connections[Idx].sock, IO_WANTWRITE );
952 ("Handle_Write() called for connection %d, %ld bytes pending ...",
955 len = write(My_Connections[Idx].sock,
956 array_start(&My_Connections[Idx].wbuf), wdatalen );
959 if (errno == EAGAIN || errno == EINTR)
962 Log(LOG_ERR, "Write error on connection %d (socket %d): %s!",
963 Idx, My_Connections[Idx].sock, strerror(errno));
964 Conn_Close(Idx, "Write error!", NULL, false);
968 /* move any data not yet written to beginning */
969 array_moveleft(&My_Connections[Idx].wbuf, 1, (size_t)len);
976 Count_Connections(ng_ipaddr_t *a)
981 for (i = 0; i < Pool_Size; i++) {
982 if (My_Connections[i].sock <= NONE)
984 if (ng_ipaddr_ipequal(&My_Connections[i].addr, a))
988 } /* Count_Connections */
992 New_Connection( int Sock )
994 /* Neue Client-Verbindung von Listen-Socket annehmen und
995 * CLIENT-Struktur anlegen. */
998 struct request_info req;
1000 ng_ipaddr_t new_addr;
1001 char ip_str[NG_INET_ADDRSTRLEN];
1002 int new_sock, new_sock_len, new_Pool_Size;
1006 assert( Sock > NONE );
1007 /* Connection auf Listen-Socket annehmen */
1008 new_sock_len = (int)sizeof(new_addr);
1010 new_sock = accept(Sock, (struct sockaddr *)&new_addr,
1011 (socklen_t *)&new_sock_len);
1013 Log(LOG_CRIT, "Can't accept connection: %s!", strerror(errno));
1017 if (!ng_ipaddr_tostr_r(&new_addr, ip_str)) {
1018 Log(LOG_CRIT, "fd %d: Can't convert IP address!", new_sock);
1019 Simple_Message(new_sock, "ERROR :Internal Server Error");
1024 /* Validate socket using TCP Wrappers */
1025 request_init( &req, RQ_DAEMON, PACKAGE_NAME, RQ_FILE, new_sock, RQ_CLIENT_SIN, &new_addr, NULL );
1027 if (!hosts_access(&req)) {
1028 Log (deny_severity, "Refused connection from %s (by TCP Wrappers)!", ip_str);
1029 Simple_Message( new_sock, "ERROR :Connection refused" );
1035 /* Socket initialisieren */
1036 if (!Init_Socket( new_sock ))
1039 /* Check IP-based connection limit */
1040 cnt = Count_Connections(&new_addr);
1041 if ((Conf_MaxConnectionsIP > 0) && (cnt >= Conf_MaxConnectionsIP)) {
1042 /* Access denied, too many connections from this IP address! */
1043 Log( LOG_ERR, "Refused connection from %s: too may connections (%ld) from this IP address!", ip_str, cnt);
1044 Simple_Message( new_sock, "ERROR :Connection refused, too many connections from your IP address!" );
1049 if( new_sock >= Pool_Size ) {
1050 new_Pool_Size = new_sock + 1;
1051 /* No free Connection Structures, check if we may accept further connections */
1052 if ((( Conf_MaxConnections > 0) && Pool_Size >= Conf_MaxConnections) ||
1053 (new_Pool_Size < Pool_Size))
1055 Log( LOG_ALERT, "Can't accept connection: limit (%d) reached!", Pool_Size );
1056 Simple_Message( new_sock, "ERROR :Connection limit reached" );
1061 if (!array_alloc(&My_ConnArray, sizeof(CONNECTION),
1062 (size_t)new_sock)) {
1063 Log( LOG_EMERG, "Can't allocate memory! [New_Connection]" );
1064 Simple_Message( new_sock, "ERROR: Internal error" );
1068 LogDebug("Bumped connection pool to %ld items (internal: %ld items, %ld bytes)",
1069 new_sock, array_length(&My_ConnArray, sizeof(CONNECTION)), array_bytes(&My_ConnArray));
1071 /* Adjust pointer to new block */
1072 My_Connections = array_start(&My_ConnArray);
1073 while (Pool_Size < new_Pool_Size)
1074 Init_Conn_Struct(Pool_Size++);
1077 /* register callback */
1078 if (!io_event_create( new_sock, IO_WANTREAD, cb_clientserver)) {
1079 Log(LOG_ALERT, "Can't accept connection: io_event_create failed!");
1080 Simple_Message(new_sock, "ERROR :Internal error");
1085 c = Client_NewLocal(new_sock, ip_str, CLIENT_UNKNOWN, false );
1087 Log(LOG_ALERT, "Can't accept connection: can't create client structure!");
1088 Simple_Message(new_sock, "ERROR :Internal error");
1093 Init_Conn_Struct( new_sock );
1094 My_Connections[new_sock].sock = new_sock;
1095 My_Connections[new_sock].addr = new_addr;
1096 My_Connections[new_sock].client = c;
1098 Log( LOG_INFO, "Accepted connection %d from %s:%d on socket %d.", new_sock,
1099 ip_str, ng_ipaddr_getport(&new_addr), Sock);
1101 /* Hostnamen ermitteln */
1102 strlcpy(My_Connections[new_sock].host, ip_str, sizeof(My_Connections[new_sock].host));
1104 Client_SetHostname(c, My_Connections[new_sock].host);
1107 Resolve_Addr(&My_Connections[new_sock].res_stat, &new_addr,
1108 My_Connections[new_sock].sock, cb_Read_Resolver_Result);
1110 Conn_SetPenalty(new_sock, 4);
1112 } /* New_Connection */
1116 Socket2Index( int Sock )
1118 /* zum Socket passende Connection suchen */
1120 assert( Sock >= 0 );
1122 if( Sock >= Pool_Size || My_Connections[Sock].sock != Sock ) {
1123 /* die Connection wurde vermutlich (wegen eines
1124 * Fehlers) bereits wieder abgebaut ... */
1125 LogDebug("Socket2Index: can't get connection for socket %d!", Sock);
1129 } /* Socket2Index */
1133 * Read data from the network to the read buffer. If an error occures,
1134 * the socket of this connection will be shut down.
1137 Read_Request( CONN_ID Idx )
1140 char readbuf[READBUFFER_LEN];
1142 assert( Idx > NONE );
1143 assert( My_Connections[Idx].sock > NONE );
1146 if ((array_bytes(&My_Connections[Idx].rbuf) >= READBUFFER_LEN) ||
1147 (array_bytes(&My_Connections[Idx].zip.rbuf) >= READBUFFER_LEN))
1149 if (array_bytes(&My_Connections[Idx].rbuf) >= READBUFFER_LEN)
1152 /* Read buffer is full */
1154 "Receive buffer overflow (connection %d): %d bytes!",
1155 Idx, array_bytes(&My_Connections[Idx].rbuf));
1156 Conn_Close( Idx, "Receive buffer overflow!", NULL, false );
1160 len = read(My_Connections[Idx].sock, readbuf, sizeof(readbuf));
1162 Log(LOG_INFO, "%s:%u (%s) is closing the connection ...",
1163 My_Connections[Idx].host,
1164 (unsigned int) ng_ipaddr_getport(&My_Connections[Idx].addr),
1165 ng_ipaddr_tostr(&My_Connections[Idx].addr));
1167 "Socket closed!", "Client closed connection",
1173 if( errno == EAGAIN ) return;
1174 Log(LOG_ERR, "Read error on connection %d (socket %d): %s!",
1175 Idx, My_Connections[Idx].sock, strerror(errno));
1176 Conn_Close(Idx, "Read error!", "Client closed connection",
1181 if (Conn_OPTION_ISSET(&My_Connections[Idx], CONN_ZIP)) {
1182 if (!array_catb(&My_Connections[Idx].zip.rbuf, readbuf,
1185 "Could not append recieved data to zip input buffer (connn %d): %d bytes!",
1187 Conn_Close(Idx, "Receive buffer overflow!", NULL,
1194 if (!array_catb( &My_Connections[Idx].rbuf, readbuf, len)) {
1195 Log( LOG_ERR, "Could not append recieved data to input buffer (connn %d): %d bytes!", Idx, len );
1196 Conn_Close( Idx, "Receive buffer overflow!", NULL, false );
1200 /* Update connection statistics */
1201 My_Connections[Idx].bytes_in += len;
1203 /* Update timestamp of last data received if this connection is
1204 * registered as a user, server or service connection. Don't update
1205 * otherwise, so users have at least Conf_PongTimeout seconds time to
1206 * register with the IRC server -- see Check_Connections().
1207 * Set "lastping", too, so we can handle time shifts backwards ... */
1208 c = Conn_GetClient(Idx);
1209 if (c && (Client_Type(c) == CLIENT_USER
1210 || Client_Type(c) == CLIENT_SERVER
1211 || Client_Type(c) == CLIENT_SERVICE)) {
1212 My_Connections[Idx].lastdata = time(NULL);
1213 My_Connections[Idx].lastping = My_Connections[Idx].lastdata;
1216 /* Look at the data in the (read-) buffer of this connection */
1218 } /* Read_Request */
1222 * Handle data in connection read-buffer.
1223 * @return true if a reuqest was handled, false otherwise (and on errors).
1226 Handle_Buffer(CONN_ID Idx)
1239 starttime = time(NULL);
1243 if (My_Connections[Idx].delaytime > starttime)
1246 /* Unpack compressed data, if compression is in use */
1247 if (Conn_OPTION_ISSET(&My_Connections[Idx], CONN_ZIP)) {
1248 if (!Unzip_Buffer(Idx))
1253 if (0 == array_bytes(&My_Connections[Idx].rbuf))
1256 /* Make sure that the buffer is NULL terminated */
1257 if (!array_cat0_temporary(&My_Connections[Idx].rbuf))
1260 /* RFC 2812, section "2.3 Messages", 5th paragraph:
1261 * "IRC messages are always lines of characters terminated
1262 * with a CR-LF (Carriage Return - Line Feed) pair [...]". */
1264 ptr = strstr(array_start(&My_Connections[Idx].rbuf), "\r\n");
1268 /* Check for non-RFC-compliant request (only CR or
1269 * LF)? Unfortunately, there are quite a few clients
1270 * out there that do this -- incl. "mIRC" :-( */
1272 ptr1 = strchr(array_start(&My_Connections[Idx].rbuf), '\r');
1273 ptr2 = strchr(array_start(&My_Connections[Idx].rbuf), '\n');
1275 ptr = ptr1 > ptr2 ? ptr2 : ptr1;
1286 /* Complete (=line terminated) request found, handle it! */
1289 len = ptr - (char *)array_start(&My_Connections[Idx].rbuf) + delta;
1291 if (len > (COMMAND_LEN - 1)) {
1292 /* Request must not exceed 512 chars (incl. CR+LF!),
1293 * see RFC 2812. Disconnect Client if this happens. */
1295 "Request too long (connection %d): %d bytes (max. %d expected)!",
1296 Idx, array_bytes(&My_Connections[Idx].rbuf),
1298 Conn_Close(Idx, NULL, "Request too long", true);
1303 /* Request is empty (only '\r\n', '\r' or '\n');
1304 * delta is 2 ('\r\n') or 1 ('\r' or '\n'), see above */
1305 array_moveleft(&My_Connections[Idx].rbuf, 1, len);
1310 /* remember if stream is already compressed */
1311 old_z = My_Connections[Idx].options & CONN_ZIP;
1314 My_Connections[Idx].msg_in++;
1316 (Idx, (char *)array_start(&My_Connections[Idx].rbuf)))
1321 array_moveleft(&My_Connections[Idx].rbuf, 1, len);
1322 LogDebug("Connection %d: %d bytes left in read buffer.",
1323 Idx, array_bytes(&My_Connections[Idx].rbuf));
1325 if ((!old_z) && (My_Connections[Idx].options & CONN_ZIP) &&
1326 (array_bytes(&My_Connections[Idx].rbuf) > 0)) {
1327 /* The last command activated socket compression.
1328 * Data that was read after that needs to be copied
1329 * to the unzip buffer for decompression: */
1331 (&My_Connections[Idx].zip.rbuf,
1332 &My_Connections[Idx].rbuf))
1335 array_trunc(&My_Connections[Idx].rbuf);
1337 ("Moved already received data (%u bytes) to uncompression buffer.",
1338 array_bytes(&My_Connections[Idx].zip.rbuf));
1343 } /* Handle_Buffer */
1347 Check_Connections(void)
1349 /* check if connections are alive. if not, play PING-PONG first.
1350 * if this doesn't help either, disconnect client. */
1354 for (i = 0; i < Pool_Size; i++) {
1355 if (My_Connections[i].sock < 0)
1358 c = Conn_GetClient(i);
1359 if (c && ((Client_Type(c) == CLIENT_USER)
1360 || (Client_Type(c) == CLIENT_SERVER)
1361 || (Client_Type(c) == CLIENT_SERVICE))) {
1362 /* connected User, Server or Service */
1363 if (My_Connections[i].lastping >
1364 My_Connections[i].lastdata) {
1365 /* We already sent a ping */
1366 if (My_Connections[i].lastping <
1367 time(NULL) - Conf_PongTimeout) {
1370 ("Connection %d: Ping timeout: %d seconds.",
1371 i, Conf_PongTimeout);
1372 Conn_Close(i, NULL, "Ping timeout",
1375 } else if (My_Connections[i].lastdata <
1376 time(NULL) - Conf_PingTimeout) {
1377 /* We need to send a PING ... */
1378 LogDebug("Connection %d: sending PING ...", i);
1379 My_Connections[i].lastping = time(NULL);
1380 Conn_WriteStr(i, "PING :%s",
1381 Client_ID(Client_ThisServer()));
1384 /* The connection is not fully established yet, so
1385 * we don't do the PING-PONG game here but instead
1386 * disconnect the client after "a short time" if it's
1387 * still not registered. */
1389 if (My_Connections[i].lastdata <
1390 time(NULL) - Conf_PongTimeout) {
1392 ("Unregistered connection %d timed out ...",
1394 Conn_Close(i, NULL, "Timeout", false);
1398 } /* Check_Connections */
1402 Check_Servers( void )
1404 /* Check if we can establish further server links */
1409 /* Check all configured servers */
1410 for( i = 0; i < MAX_SERVERS; i++ ) {
1411 /* Valid outgoing server which isn't already connected or disabled? */
1412 if(( ! Conf_Server[i].host[0] ) || ( ! Conf_Server[i].port > 0 ) ||
1413 ( Conf_Server[i].conn_id > NONE ) || ( Conf_Server[i].flags & CONF_SFLAG_DISABLED ))
1416 /* Is there already a connection in this group? */
1417 if( Conf_Server[i].group > NONE ) {
1418 for (n = 0; n < MAX_SERVERS; n++) {
1419 if (n == i) continue;
1420 if ((Conf_Server[n].conn_id != NONE) &&
1421 (Conf_Server[n].group == Conf_Server[i].group))
1424 if (n < MAX_SERVERS) continue;
1427 /* Check last connect attempt? */
1428 time_now = time(NULL);
1429 if( Conf_Server[i].lasttry > (time_now - Conf_ConnectRetry))
1432 /* Okay, try to connect now */
1433 Conf_Server[i].lasttry = time_now;
1434 Conf_Server[i].conn_id = SERVER_WAIT;
1435 assert(Resolve_Getfd(&Conf_Server[i].res_stat) < 0);
1436 Resolve_Name(&Conf_Server[i].res_stat, Conf_Server[i].host, cb_Connect_to_Server);
1438 } /* Check_Servers */
1442 New_Server( int Server , ng_ipaddr_t *dest)
1444 /* Establish new server link */
1445 char ip_str[NG_INET_ADDRSTRLEN];
1446 int af_dest, res, new_sock;
1449 assert( Server > NONE );
1451 if (!ng_ipaddr_tostr_r(dest, ip_str)) {
1452 Log(LOG_WARNING, "New_Server: Could not convert IP to string");
1456 Log( LOG_INFO, "Establishing connection to \"%s\", %s, port %d ... ",
1457 Conf_Server[Server].host, ip_str, Conf_Server[Server].port );
1459 af_dest = ng_ipaddr_af(dest);
1460 new_sock = socket(af_dest, SOCK_STREAM, 0);
1462 Log( LOG_CRIT, "Can't create socket: %s!", strerror( errno ));
1466 if (!Init_Socket(new_sock))
1469 /* is a bind address configured? */
1470 res = ng_ipaddr_af(&Conf_Server[Server].bind_addr);
1471 /* if yes, bind now. If it fails, warn and let connect() pick a source address */
1472 if (res && bind(new_sock, (struct sockaddr *) &Conf_Server[Server].bind_addr,
1473 ng_ipaddr_salen(&Conf_Server[Server].bind_addr)))
1475 ng_ipaddr_tostr_r(&Conf_Server[Server].bind_addr, ip_str);
1476 Log(LOG_WARNING, "Can't bind socket to %s: %s!", ip_str, strerror(errno));
1478 ng_ipaddr_setport(dest, Conf_Server[Server].port);
1479 res = connect(new_sock, (struct sockaddr *) dest, ng_ipaddr_salen(dest));
1480 if(( res != 0 ) && ( errno != EINPROGRESS )) {
1481 Log( LOG_CRIT, "Can't connect socket: %s!", strerror( errno ));
1486 if (!array_alloc(&My_ConnArray, sizeof(CONNECTION), (size_t)new_sock)) {
1488 "Cannot allocate memory for server connection (socket %d)",
1494 My_Connections = array_start(&My_ConnArray);
1496 assert(My_Connections[new_sock].sock <= 0);
1498 Init_Conn_Struct(new_sock);
1500 ng_ipaddr_tostr_r(dest, ip_str);
1501 c = Client_NewLocal(new_sock, ip_str, CLIENT_UNKNOWNSERVER, false);
1503 Log( LOG_ALERT, "Can't establish connection: can't create client structure!" );
1508 Client_SetIntroducer( c, c );
1509 Client_SetToken( c, TOKEN_OUTBOUND );
1511 /* Register connection */
1512 Conf_Server[Server].conn_id = new_sock;
1513 My_Connections[new_sock].sock = new_sock;
1514 My_Connections[new_sock].addr = *dest;
1515 My_Connections[new_sock].client = c;
1516 strlcpy( My_Connections[new_sock].host, Conf_Server[Server].host,
1517 sizeof(My_Connections[new_sock].host ));
1519 /* Register new socket */
1520 if (!io_event_create( new_sock, IO_WANTWRITE, cb_connserver)) {
1521 Log( LOG_ALERT, "io_event_create(): could not add fd %d", strerror(errno));
1522 Conn_Close( new_sock, "io_event_create() failed", NULL, false );
1523 Init_Conn_Struct( new_sock );
1524 Conf_Server[Server].conn_id = NONE;
1527 LogDebug("Registered new connection %d on socket %d.",
1528 new_sock, My_Connections[new_sock].sock );
1529 Conn_OPTION_ADD( &My_Connections[new_sock], CONN_ISCONNECTING );
1534 * Initialize connection structure.
1537 Init_Conn_Struct(CONN_ID Idx)
1539 time_t now = time(NULL);
1541 memset(&My_Connections[Idx], 0, sizeof(CONNECTION));
1542 My_Connections[Idx].sock = -1;
1543 My_Connections[Idx].signon = now;
1544 My_Connections[Idx].lastdata = now;
1545 My_Connections[Idx].lastprivmsg = now;
1546 Resolve_Init(&My_Connections[Idx].res_stat);
1547 } /* Init_Conn_Struct */
1551 Init_Socket( int Sock )
1553 /* Initialize socket (set options) */
1557 if (!io_setnonblock(Sock)) {
1558 Log( LOG_CRIT, "Can't enable non-blocking mode for socket: %s!", strerror( errno ));
1563 /* Don't block this port after socket shutdown */
1565 if( setsockopt( Sock, SOL_SOCKET, SO_REUSEADDR, &value, (socklen_t)sizeof( value )) != 0 )
1567 Log( LOG_ERR, "Can't set socket option SO_REUSEADDR: %s!", strerror( errno ));
1568 /* ignore this error */
1571 /* Set type of service (TOS) */
1572 #if defined(IP_TOS) && defined(IPTOS_LOWDELAY)
1573 value = IPTOS_LOWDELAY;
1574 LogDebug("Setting option IP_TOS on socket %d to IPTOS_LOWDELAY (%d).", Sock, value );
1575 if( setsockopt( Sock, SOL_IP, IP_TOS, &value, (socklen_t)sizeof( value )) != 0 )
1577 Log( LOG_ERR, "Can't set socket option IP_TOS: %s!", strerror( errno ));
1578 /* ignore this error */
1588 cb_Connect_to_Server(int fd, UNUSED short events)
1590 /* Read result of resolver sub-process from pipe and start connection */
1593 ng_ipaddr_t dest_addrs[4]; /* we can handle at most 3; but we read up to
1594 four so we can log the 'more than we can handle'
1597 LogDebug("Resolver: Got forward lookup callback on fd %d, events %d", fd, events);
1599 for (i=0; i < MAX_SERVERS; i++) {
1600 if (Resolve_Getfd(&Conf_Server[i].res_stat) == fd )
1604 if( i >= MAX_SERVERS) {
1605 /* Ops, no matching server found?! */
1607 LogDebug("Resolver: Got Forward Lookup callback for unknown server!?");
1611 /* Read result from pipe */
1612 len = Resolve_Read(&Conf_Server[i].res_stat, dest_addrs, sizeof(dest_addrs));
1616 assert((len % sizeof(ng_ipaddr_t)) == 0);
1618 LogDebug("Got result from resolver: %u structs (%u bytes).", len/sizeof(ng_ipaddr_t), len);
1620 memset(&Conf_Server[i].dst_addr, 0, sizeof(&Conf_Server[i].dst_addr));
1621 if (len > sizeof(ng_ipaddr_t)) {
1622 /* more than one address for this hostname, remember them
1623 * in case first address is unreachable/not available */
1624 len -= sizeof(ng_ipaddr_t);
1625 if (len > sizeof(&Conf_Server[i].dst_addr)) {
1626 len = sizeof(&Conf_Server[i].dst_addr);
1627 Log(LOG_NOTICE, "Notice: Resolver returned more IP Addresses for host than we can handle,"
1628 " additional addresses dropped");
1630 memcpy(&Conf_Server[i].dst_addr, &dest_addrs[1], len);
1633 New_Server(i, dest_addrs);
1634 } /* cb_Read_Forward_Lookup */
1638 cb_Read_Resolver_Result( int r_fd, UNUSED short events )
1640 /* Read result of resolver sub-process from pipe and update the
1641 * apropriate connection/client structure(s): hostname and/or
1642 * IDENT user name.*/
1649 char readbuf[HOST_LEN + 2 + CLIENT_USER_LEN];
1651 char readbuf[HOST_LEN + 1];
1654 LogDebug("Resolver: Got callback on fd %d, events %d", r_fd, events );
1656 /* Search associated connection ... */
1657 for( i = 0; i < Pool_Size; i++ ) {
1658 if(( My_Connections[i].sock != NONE )
1659 && ( Resolve_Getfd(&My_Connections[i].res_stat) == r_fd ))
1662 if( i >= Pool_Size ) {
1663 /* Ops, none found? Probably the connection has already
1664 * been closed!? We'll ignore that ... */
1666 LogDebug("Resolver: Got callback for unknown connection!?");
1670 /* Read result from pipe */
1671 len = Resolve_Read(&My_Connections[i].res_stat, readbuf, sizeof readbuf -1);
1675 readbuf[len] = '\0';
1676 identptr = strchr(readbuf, '\n');
1677 assert(identptr != NULL);
1679 Log( LOG_CRIT, "Resolver: Got malformed result!");
1684 LogDebug("Got result from resolver: \"%s\" (%u bytes read).", readbuf, len);
1685 /* Okay, we got a complete result: this is a host name for outgoing
1686 * connections and a host name and IDENT user name (if enabled) for
1687 * incoming connections.*/
1688 assert ( My_Connections[i].sock >= 0 );
1689 /* Incoming connection. Search client ... */
1690 c = Conn_GetClient( i );
1691 assert( c != NULL );
1693 /* Only update client information of unregistered clients */
1694 if( Client_Type( c ) == CLIENT_UNKNOWN ) {
1695 strlcpy(My_Connections[i].host, readbuf, sizeof( My_Connections[i].host));
1696 Client_SetHostname( c, readbuf);
1700 Log(LOG_INFO, "IDENT lookup for connection %d: \"%s\".", i, identptr);
1701 Client_SetUser(c, identptr, true);
1703 Log(LOG_INFO, "IDENT lookup for connection %d: no result.", i);
1708 else Log( LOG_DEBUG, "Resolver: discarding result for already registered connection %d.", i );
1710 /* Reset penalty time */
1711 Conn_ResetPenalty( i );
1712 } /* cb_Read_Resolver_Result */
1716 Simple_Message( int Sock, const char *Msg )
1718 char buf[COMMAND_LEN];
1720 /* Write "simple" message to socket, without using compression
1721 * or even the connection write buffers. Used e.g. for error
1722 * messages by New_Connection(). */
1723 assert( Sock > NONE );
1724 assert( Msg != NULL );
1726 strlcpy( buf, Msg, sizeof buf - 2);
1727 len = strlcat( buf, "\r\n", sizeof buf);
1728 (void)write(Sock, buf, len);
1729 } /* Simple_Error */
1733 Conn_GetClient( CONN_ID Idx )
1735 /* return Client-Structure that belongs to the local Connection Idx.
1736 * If none is found, return NULL.
1741 c = array_get(&My_ConnArray, sizeof (CONNECTION), (size_t)Idx);
1745 return c ? c->client : NULL;