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
32 #include <sys/socket.h>
34 #include <sys/types.h>
36 #include <netinet/in.h>
38 #ifdef HAVE_NETINET_IP_H
39 # include <netinet/ip.h>
43 # include <stdint.h> /* e.g. for Mac OS X */
47 # include <tcpd.h> /* for TCP Wrappers */
62 #include "conn-func.h"
68 # include "rendezvous.h"
74 #define SERVER_WAIT (NONE - 1)
77 static bool Handle_Write PARAMS(( CONN_ID Idx ));
78 static bool Conn_Write PARAMS(( CONN_ID Idx, char *Data, size_t Len ));
79 static int New_Connection PARAMS(( int Sock ));
80 static CONN_ID Socket2Index PARAMS(( int Sock ));
81 static void Read_Request PARAMS(( CONN_ID Idx ));
82 static void Handle_Buffer PARAMS(( CONN_ID Idx ));
83 static void Check_Connections PARAMS(( void ));
84 static void Check_Servers PARAMS(( void ));
85 static void Init_Conn_Struct PARAMS(( CONN_ID Idx ));
86 static bool Init_Socket PARAMS(( int Sock ));
87 static void New_Server PARAMS(( int Server, ng_ipaddr_t *dest ));
88 static void Simple_Message PARAMS(( int Sock, const char *Msg ));
89 static int NewListener PARAMS(( const char *listen_addr, UINT16 Port ));
91 static array My_Listeners;
92 static array My_ConnArray;
93 static size_t NumConnections;
96 int allow_severity = LOG_INFO;
97 int deny_severity = LOG_ERR;
100 static void server_login PARAMS((CONN_ID idx));
102 static void cb_Read_Resolver_Result PARAMS(( int sock, UNUSED short what));
103 static void cb_Connect_to_Server PARAMS(( int sock, UNUSED short what));
104 static void cb_clientserver PARAMS((int sock, short what));
107 cb_listen(int sock, short irrelevant)
110 if (New_Connection( sock ) >= 0)
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) &&
218 (Pool_Size > Conf_MaxConnections))
219 Pool_Size = Conf_MaxConnections;
221 if (!array_alloc(&My_ConnArray, sizeof(CONNECTION), (size_t)Pool_Size)) {
222 Log( LOG_EMERG, "Can't allocate memory! [Conn_Init]" );
226 /* FIXME: My_Connetions/Pool_Size is needed by other parts of the
227 * code; remove them! */
228 My_Connections = (CONNECTION*) array_start(&My_ConnArray);
230 LogDebug("Allocated connection pool for %d items (%ld bytes).",
231 array_length(&My_ConnArray, sizeof( CONNECTION )), array_bytes(&My_ConnArray));
233 assert( array_length(&My_ConnArray, sizeof( CONNECTION )) >= (size_t) Pool_Size);
235 array_free( &My_Listeners );
237 /* Connection-Struktur initialisieren */
238 for( i = 0; i < Pool_Size; i++ ) Init_Conn_Struct( i );
240 /* Global write counter */
248 /* Modul abmelden: alle noch offenen Connections
249 * schliessen und freigeben. */
253 LogDebug("Shutting down all connections ..." );
255 Conn_ExitListeners();
257 /* Sockets schliessen */
258 for( idx = 0; idx < Pool_Size; idx++ ) {
259 if( My_Connections[idx].sock > NONE ) {
260 Conn_Close( idx, NULL, NGIRCd_SignalRestart ?
261 "Server going down (restarting)":"Server going down", true );
265 array_free(&My_ConnArray);
266 My_Connections = NULL;
268 io_library_shutdown();
273 ports_initlisteners(array *a, const char *listen_addr, void (*func)(int,short))
275 unsigned int created = 0;
280 len = array_length(a, sizeof (UINT16));
281 port = array_start(a);
283 fd = NewListener(listen_addr, *port);
288 if (!io_event_create( fd, IO_WANTREAD, func )) {
289 Log( LOG_ERR, "io_event_create(): Could not add listening fd %d (port %u): %s!",
290 fd, (unsigned int) *port, strerror(errno));
303 Conn_InitListeners( void )
305 /* Initialize ports on which the server should accept connections */
306 unsigned int created = 0;
307 char *copy, *listen_addr;
309 if (!io_library_init(CONNECTION_POOL)) {
310 Log(LOG_EMERG, "Cannot initialize IO routines: %s", strerror(errno));
314 assert(Conf_ListenAddress);
316 /* can't use Conf_ListenAddress directly, see below */
317 copy = strdup(Conf_ListenAddress);
319 Log(LOG_CRIT, "Cannot copy %s: %s", Conf_ListenAddress, strerror(errno));
322 listen_addr = strtok(copy, ",");
324 while (listen_addr) {
325 ngt_TrimStr(listen_addr);
327 created += ports_initlisteners(&Conf_ListenPorts, listen_addr, cb_listen);
329 listen_addr = strtok(NULL, ",");
333 * can't free() Conf_ListenAddress here. On /REHASH, if the config file
334 * cannot be re-loaded, we'd end up with a NULL Conf_ListenAddress.
335 * Instead, free() takes place in conf.c, before the config file
340 } /* Conn_InitListeners */
344 Conn_ExitListeners( void )
346 /* Close down all listening sockets */
350 Rendezvous_UnregisterListeners( );
353 arraylen = array_length(&My_Listeners, sizeof (int));
354 Log( LOG_INFO, "Shutting down all listening sockets (%d total)...", arraylen );
355 fd = array_start(&My_Listeners);
360 LogDebug("Listening socket %d closed.", *fd );
363 array_free(&My_Listeners);
364 } /* Conn_ExitListeners */
368 InitSinaddrListenAddr(ng_ipaddr_t *addr, const char *listen_addrstr, UINT16 Port)
372 ret = ng_ipaddr_init(addr, listen_addrstr, Port);
374 assert(listen_addrstr);
375 Log(LOG_CRIT, "Can't bind to [%s]:%u: can't convert ip address \"%s\"",
376 listen_addrstr, Port, listen_addrstr);
383 set_v6_only(int af, int sock)
385 #if defined(IPV6_V6ONLY) && defined(WANT_IPV6)
391 if (setsockopt(sock, IPPROTO_IPV6, IPV6_V6ONLY, &on, sizeof(on)))
392 Log(LOG_ERR, "Could not set IPV6_V6ONLY: %s", strerror(errno));
400 /* return new listening port file descriptor or -1 on failure */
402 NewListener(const char *listen_addr, UINT16 Port)
404 /* Create new listening socket on specified port */
408 char name[CLIENT_ID_LEN], *info;
410 if (!InitSinaddrListenAddr(&addr, listen_addr, Port))
413 af = ng_ipaddr_af(&addr);
414 sock = socket(af, SOCK_STREAM, 0);
416 Log(LOG_CRIT, "Can't create socket (af %d) : %s!", af, strerror(errno));
420 set_v6_only(af, sock);
422 if (!Init_Socket(sock))
425 if (bind(sock, (struct sockaddr *)&addr, ng_ipaddr_salen(&addr)) != 0) {
426 Log(LOG_CRIT, "Can't bind socket to address %s:%d - %s",
427 ng_ipaddr_tostr(&addr), Port, strerror(errno));
432 if( listen( sock, 10 ) != 0 ) {
433 Log( LOG_CRIT, "Can't listen on socket: %s!", strerror( errno ));
438 /* keep fd in list so we can close it when ngircd restarts/shuts down */
439 if (!array_catb( &My_Listeners,(char*) &sock, sizeof(int) )) {
440 Log( LOG_CRIT, "Can't add socket to My_Listeners array: %s!", strerror( errno ));
445 Log(LOG_INFO, "Now listening on [%s]:%d (socket %d).", ng_ipaddr_tostr(&addr), Port, sock);
448 /* Get best server description text */
449 if( ! Conf_ServerInfo[0] ) info = Conf_ServerName;
452 /* Use server info string */
454 if( Conf_ServerInfo[0] == '[' )
456 /* Cut off leading hostname part in "[]" */
457 info = strchr( Conf_ServerInfo, ']' );
461 while( *info == ' ' ) info++;
464 if( ! info ) info = Conf_ServerInfo;
467 /* Add port number to description if non-standard */
469 snprintf(name, sizeof name, "%s (port %u)", info,
472 strlcpy(name, info, sizeof name);
474 /* Register service */
475 Rendezvous_Register( name, MDNS_TYPE, Port );
482 * "Main Loop": Loop until shutdown or restart is signalled.
483 * This function loops until a shutdown or restart of ngIRCd is signalled and
484 * calls io_dispatch() to check for readable and writable sockets every second.
485 * It checks for status changes on pending connections (e. g. when a hostname
486 * has been resolved), checks for "penalties" and timeouts, and handles the
493 unsigned int wdatalen;
497 while (!NGIRCd_SignalQuit && !NGIRCd_SignalRestart) {
501 Rendezvous_Handler();
504 /* Should the configuration be reloaded? */
505 if (NGIRCd_SignalRehash)
508 /* Check configured servers and established links */
512 /* Look for non-empty read buffers ... */
513 for (i = 0; i < Pool_Size; i++) {
514 if ((My_Connections[i].sock > NONE)
515 && (array_bytes(&My_Connections[i].rbuf) > 0)
516 && (My_Connections[i].delaytime < t)) {
517 /* ... and try to handle the received data */
522 /* Look for non-empty write buffers ... */
523 for (i = 0; i < Pool_Size; i++) {
524 if (My_Connections[i].sock <= NONE)
527 wdatalen = (unsigned int)array_bytes(&My_Connections[i].wbuf);
530 array_bytes(&My_Connections[i].zip.wbuf) > 0)
535 /* Set the "WANTWRITE" flag on this socket */
536 io_event_add(My_Connections[i].sock,
541 /* Check from which sockets we possibly could read ... */
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,
553 if (Conn_OPTION_ISSET(&My_Connections[i], CONN_ISCONNECTING))
554 /* Wait for completion of connect() ... */
557 if (My_Connections[i].delaytime > t) {
558 /* There is a "penalty time" set: ignore socket! */
559 io_event_del(My_Connections[i].sock,
563 io_event_add(My_Connections[i].sock, IO_WANTREAD);
566 /* Set the timeout for reading from the network to 1 second,
567 * which is the granularity with witch we handle "penalty
568 * times" for example.
569 * Note: tv_sec/usec are undefined(!) after io_dispatch()
570 * returns, so we have to set it beforce each call to it! */
574 /* Wait for activity ... */
575 i = io_dispatch(&tv);
576 if (i == -1 && errno != EINTR) {
577 Log(LOG_EMERG, "Conn_Handler(): io_dispatch(): %s!",
579 Log(LOG_ALERT, "%s exiting due to fatal errors!",
585 if (NGIRCd_SignalQuit)
586 Log(LOG_NOTICE | LOG_snotice, "Server going down NOW!");
587 else if (NGIRCd_SignalRestart)
588 Log(LOG_NOTICE | LOG_snotice, "Server restarting NOW!");
593 * Write a text string into the socket of a connection.
594 * This function automatically appends CR+LF to the string and validates that
595 * the result is a valid IRC message (oversized messages are shortened, for
596 * example). Then it calls the Conn_Write() function to do the actual sending.
597 * @param Idx Index fo the connection.
598 * @param Format Format string, see printf().
599 * @return true on success, false otherwise.
603 Conn_WriteStr( CONN_ID Idx, char *Format, ... )
606 Conn_WriteStr( Idx, Format, va_alist )
612 char buffer[COMMAND_LEN];
617 assert( Idx > NONE );
618 assert( Format != NULL );
621 va_start( ap, Format );
625 if (vsnprintf( buffer, COMMAND_LEN - 2, Format, ap ) >= COMMAND_LEN - 2 ) {
627 * The string that should be written to the socket is longer
628 * than the allowed size of COMMAND_LEN bytes (including both
629 * the CR and LF characters). This can be caused by the
630 * IRC_WriteXXX() functions when the prefix of this server had
631 * to be added to an already "quite long" command line which
632 * has been received from a regular IRC client, for example.
634 * We are not allowed to send such "oversized" messages to
635 * other servers and clients, see RFC 2812 2.3 and 2813 3.3
636 * ("these messages SHALL NOT exceed 512 characters in length,
637 * counting all characters including the trailing CR-LF").
639 * So we have a big problem here: we should send more bytes
640 * to the network than we are allowed to and we don't know
641 * the originator (any more). The "old" behaviour of blaming
642 * the receiver ("next hop") is a bad idea (it could be just
643 * an other server only routing the message!), so the only
644 * option left is to shorten the string and to hope that the
645 * result is still somewhat useful ...
649 strcpy (buffer + sizeof(buffer) - strlen(CUT_TXTSUFFIX) - 2 - 1,
655 Log(LOG_DEBUG, " -> connection %d: '%s'.", Idx, buffer);
658 len = strlcat( buffer, "\r\n", sizeof( buffer ));
659 ok = Conn_Write(Idx, buffer, len);
660 My_Connections[Idx].msg_out++;
664 } /* Conn_WriteStr */
668 * Append Data to the outbound write buffer of a connection.
669 * @param Idx Index of the connection.
670 * @param Data pointer to the data.
671 * @param Len length of Data.
672 * @return true on success, false otherwise.
675 Conn_Write( CONN_ID Idx, char *Data, size_t Len )
678 size_t writebuf_limit = WRITEBUFFER_LEN;
679 assert( Idx > NONE );
680 assert( Data != NULL );
683 c = Conn_GetClient(Idx);
686 /* Servers do get special write buffer limits, so they can generate
687 * all the messages that are required while peering. */
688 if (Client_Type(c) == CLIENT_SERVER)
689 writebuf_limit = WRITEBUFFER_SLINK_LEN;
691 /* Is the socket still open? A previous call to Conn_Write()
692 * may have closed the connection due to a fatal error.
693 * In this case it is sufficient to return an error, as well. */
694 if( My_Connections[Idx].sock <= NONE ) {
695 LogDebug("Skipped write on closed socket (connection %d).", Idx);
700 if ( Conn_OPTION_ISSET( &My_Connections[Idx], CONN_ZIP )) {
702 * Zip_Buffer() does all the dirty work for us: it flushes
703 * the (pre-)compression buffers if required and handles
704 * all error conditions. */
705 if (!Zip_Buffer(Idx, Data, Len))
711 /* Uncompressed link:
712 * Check if outbound buffer has enough space for the data. */
713 if (array_bytes(&My_Connections[Idx].wbuf) + Len >=
715 /* Buffer is full, flush it. Handle_Write deals with
716 * low-level errors, if any. */
717 if (!Handle_Write(Idx))
721 /* When the write buffer is still too big after flushing it,
722 * the connection will be killed. */
723 if (array_bytes(&My_Connections[Idx].wbuf) + Len >=
726 "Write buffer overflow (connection %d, size %lu byte)!",
728 (unsigned long)array_bytes(&My_Connections[Idx].wbuf));
729 Conn_Close(Idx, "Write buffer overflow!", NULL, false);
733 /* Copy data to write buffer */
734 if (!array_catb(&My_Connections[Idx].wbuf, Data, Len))
737 My_Connections[Idx].bytes_out += Len;
740 /* Adjust global write counter */
748 Conn_Close( CONN_ID Idx, char *LogMsg, char *FwdMsg, bool InformClient )
750 /* Close connection. Open pipes of asyncronous resolver
751 * sub-processes are closed down. */
758 double in_z_k, out_z_k;
762 assert( Idx > NONE );
764 /* Is this link already shutting down? */
765 if( Conn_OPTION_ISSET( &My_Connections[Idx], CONN_ISCLOSING )) {
766 /* Conn_Close() has been called recursively for this link;
767 * probabe reason: Handle_Write() failed -- see below. */
768 LogDebug("Recursive request to close connection: %d", Idx );
772 assert( My_Connections[Idx].sock > NONE );
774 /* Mark link as "closing" */
775 Conn_OPTION_ADD( &My_Connections[Idx], CONN_ISCLOSING );
782 txt = "Reason unknown";
784 port = ng_ipaddr_getport(&My_Connections[Idx].addr);
785 Log(LOG_INFO, "Shutting down connection %d (%s) with %s:%d ...", Idx,
786 LogMsg ? LogMsg : FwdMsg, My_Connections[Idx].host, port);
788 /* Search client, if any */
789 c = Conn_GetClient( Idx );
791 /* Should the client be informed? */
794 /* Send statistics to client if registered as user: */
795 if ((c != NULL) && (Client_Type(c) == CLIENT_USER)) {
797 ":%s NOTICE %s :%sConnection statistics: client %.1f kb, server %.1f kb.",
798 Client_ID(Client_ThisServer()), Client_ID(c),
800 (double)My_Connections[Idx].bytes_in / 1024,
801 (double)My_Connections[Idx].bytes_out / 1024);
804 /* Send ERROR to client (see RFC!) */
806 Conn_WriteStr(Idx, "ERROR :%s", FwdMsg);
808 Conn_WriteStr(Idx, "ERROR :Closing connection.");
811 /* Try to write out the write buffer. Note: Handle_Write() eventually
812 * removes the CLIENT structure associated with this connection if an
813 * error occurs! So we have to re-check if there is still an valid
814 * CLIENT structure after calling Handle_Write() ...*/
815 (void)Handle_Write( Idx );
817 /* Search client, if any (re-check!) */
818 c = Conn_GetClient( Idx );
820 /* Shut down socket */
821 if (! io_close(My_Connections[Idx].sock)) {
822 /* Oops, we can't close the socket!? This is ... ugly! */
824 "Error closing connection %d (socket %d) with %s:%d - %s! (ignored)",
825 Idx, My_Connections[Idx].sock, My_Connections[Idx].host,
826 port, strerror(errno));
829 /* Mark socket as invalid: */
830 My_Connections[Idx].sock = NONE;
832 /* If there is still a client, unregister it now */
834 Client_Destroy(c, LogMsg, FwdMsg, true);
836 /* Calculate statistics and log information */
837 in_k = (double)My_Connections[Idx].bytes_in / 1024;
838 out_k = (double)My_Connections[Idx].bytes_out / 1024;
840 if (Conn_OPTION_ISSET( &My_Connections[Idx], CONN_ZIP)) {
841 in_z_k = (double)My_Connections[Idx].zip.bytes_in / 1024;
842 out_z_k = (double)My_Connections[Idx].zip.bytes_out / 1024;
843 /* Make sure that no division by zero can occur during
844 * the calculation of in_p and out_p: in_z_k and out_z_k
845 * are non-zero, that's guaranteed by the protocol until
846 * compression can be enabled. */
851 in_p = (int)(( in_k * 100 ) / in_z_k );
852 out_p = (int)(( out_k * 100 ) / out_z_k );
854 "Connection %d with %s:%d closed (in: %.1fk/%.1fk/%d%%, out: %.1fk/%.1fk/%d%%).",
855 Idx, My_Connections[Idx].host, port,
856 in_k, in_z_k, in_p, out_k, out_z_k, out_p);
862 "Connection %d with %s:%d closed (in: %.1fk, out: %.1fk).",
863 Idx, My_Connections[Idx].host, port,
867 /* cancel running resolver */
868 if (Resolve_INPROGRESS(&My_Connections[Idx].res_stat))
869 Resolve_Shutdown(&My_Connections[Idx].res_stat);
871 /* Servers: Modify time of next connect attempt? */
872 Conf_UnsetServer( Idx );
875 /* Clean up zlib, if link was compressed */
876 if ( Conn_OPTION_ISSET( &My_Connections[Idx], CONN_ZIP )) {
877 inflateEnd( &My_Connections[Idx].zip.in );
878 deflateEnd( &My_Connections[Idx].zip.out );
879 array_free(&My_Connections[Idx].zip.rbuf);
880 array_free(&My_Connections[Idx].zip.wbuf);
884 array_free(&My_Connections[Idx].rbuf);
885 array_free(&My_Connections[Idx].wbuf);
887 /* Clean up connection structure (=free it) */
888 Init_Conn_Struct( Idx );
890 assert(NumConnections > 0);
893 LogDebug("Shutdown of connection %d completed", Idx );
898 Conn_SyncServerStruct( void )
900 /* Synchronize server structures (connection IDs):
901 * connections <-> configuration */
907 for( i = 0; i < Pool_Size; i++ ) {
908 /* Established connection? */
909 if (My_Connections[i].sock < 0)
912 /* Server connection? */
913 client = Conn_GetClient( i );
914 if(( ! client ) || ( Client_Type( client ) != CLIENT_SERVER )) continue;
916 for( c = 0; c < MAX_SERVERS; c++ )
918 /* Configured server? */
919 if( ! Conf_Server[c].host[0] ) continue;
922 if( strcmp( Conf_Server[c].name, Client_ID( client )) == 0 )
923 Conf_Server[c].conn_id = i;
926 } /* SyncServerStruct */
930 * Send out data of write buffer; connect new sockets.
933 Handle_Write( CONN_ID Idx )
938 assert( Idx > NONE );
939 if ( My_Connections[Idx].sock < 0 ) {
940 LogDebug("Handle_Write() on closed socket, connection %d", Idx);
943 assert( My_Connections[Idx].sock > NONE );
945 wdatalen = array_bytes(&My_Connections[Idx].wbuf );
949 /* Write buffer is empty, so we try to flush the compression
950 * buffer and get some data to work with from there :-) */
954 /* Now the write buffer most probably has changed: */
955 wdatalen = array_bytes(&My_Connections[Idx].wbuf);
960 /* Still no data, fine. */
961 io_event_del(My_Connections[Idx].sock, IO_WANTWRITE );
966 ("Handle_Write() called for connection %d, %ld bytes pending ...",
969 len = write(My_Connections[Idx].sock,
970 array_start(&My_Connections[Idx].wbuf), wdatalen );
973 if (errno == EAGAIN || errno == EINTR)
976 Log(LOG_ERR, "Write error on connection %d (socket %d): %s!",
977 Idx, My_Connections[Idx].sock, strerror(errno));
978 Conn_Close(Idx, "Write error!", NULL, false);
982 /* move any data not yet written to beginning */
983 array_moveleft(&My_Connections[Idx].wbuf, 1, (size_t)len);
990 Count_Connections(ng_ipaddr_t *a)
995 for (i = 0; i < Pool_Size; i++) {
996 if (My_Connections[i].sock <= NONE)
998 if (ng_ipaddr_ipequal(&My_Connections[i].addr, a))
1002 } /* Count_Connections */
1006 New_Connection( int Sock )
1008 /* Neue Client-Verbindung von Listen-Socket annehmen und
1009 * CLIENT-Struktur anlegen. */
1012 struct request_info req;
1014 ng_ipaddr_t new_addr;
1015 char ip_str[NG_INET_ADDRSTRLEN];
1016 int new_sock, new_sock_len;
1020 assert( Sock > NONE );
1021 /* Connection auf Listen-Socket annehmen */
1022 new_sock_len = (int)sizeof(new_addr);
1024 new_sock = accept(Sock, (struct sockaddr *)&new_addr,
1025 (socklen_t *)&new_sock_len);
1027 Log(LOG_CRIT, "Can't accept connection: %s!", strerror(errno));
1031 if (!ng_ipaddr_tostr_r(&new_addr, ip_str)) {
1032 Log(LOG_CRIT, "fd %d: Can't convert IP address!", new_sock);
1033 Simple_Message(new_sock, "ERROR :Internal Server Error");
1039 /* Validate socket using TCP Wrappers */
1040 request_init( &req, RQ_DAEMON, PACKAGE_NAME, RQ_FILE, new_sock, RQ_CLIENT_SIN, &new_addr, NULL );
1042 if (!hosts_access(&req)) {
1043 Log (deny_severity, "Refused connection from %s (by TCP Wrappers)!", ip_str);
1044 Simple_Message( new_sock, "ERROR :Connection refused" );
1050 /* Socket initialisieren */
1051 if (!Init_Socket( new_sock ))
1054 /* Check IP-based connection limit */
1055 cnt = Count_Connections(&new_addr);
1056 if ((Conf_MaxConnectionsIP > 0) && (cnt >= Conf_MaxConnectionsIP)) {
1057 /* Access denied, too many connections from this IP address! */
1058 Log( LOG_ERR, "Refused connection from %s: too may connections (%ld) from this IP address!", ip_str, cnt);
1059 Simple_Message( new_sock, "ERROR :Connection refused, too many connections from your IP address!" );
1064 if ((Conf_MaxConnections > 0) &&
1065 (NumConnections >= (size_t) Conf_MaxConnections))
1067 Log( LOG_ALERT, "Can't accept connection: limit (%d) reached!", Conf_MaxConnections);
1068 Simple_Message( new_sock, "ERROR :Connection limit reached" );
1073 if( new_sock >= Pool_Size ) {
1074 if (!array_alloc(&My_ConnArray, sizeof(CONNECTION),
1075 (size_t)new_sock)) {
1076 Log( LOG_EMERG, "Can't allocate memory! [New_Connection]" );
1077 Simple_Message( new_sock, "ERROR: Internal error" );
1081 LogDebug("Bumped connection pool to %ld items (internal: %ld items, %ld bytes)",
1082 new_sock, array_length(&My_ConnArray, sizeof(CONNECTION)), array_bytes(&My_ConnArray));
1084 /* Adjust pointer to new block */
1085 My_Connections = array_start(&My_ConnArray);
1086 while (Pool_Size <= new_sock)
1087 Init_Conn_Struct(Pool_Size++);
1090 /* register callback */
1091 if (!io_event_create( new_sock, IO_WANTREAD, cb_clientserver)) {
1092 Log(LOG_ALERT, "Can't accept connection: io_event_create failed!");
1093 Simple_Message(new_sock, "ERROR :Internal error");
1098 c = Client_NewLocal(new_sock, ip_str, CLIENT_UNKNOWN, false );
1100 Log(LOG_ALERT, "Can't accept connection: can't create client structure!");
1101 Simple_Message(new_sock, "ERROR :Internal error");
1106 Init_Conn_Struct( new_sock );
1107 My_Connections[new_sock].sock = new_sock;
1108 My_Connections[new_sock].addr = new_addr;
1109 My_Connections[new_sock].client = c;
1111 Log( LOG_INFO, "Accepted connection %d from %s:%d on socket %d.", new_sock,
1112 ip_str, ng_ipaddr_getport(&new_addr), Sock);
1114 /* Hostnamen ermitteln */
1115 strlcpy(My_Connections[new_sock].host, ip_str, sizeof(My_Connections[new_sock].host));
1117 Client_SetHostname(c, My_Connections[new_sock].host);
1120 Resolve_Addr(&My_Connections[new_sock].res_stat, &new_addr,
1121 My_Connections[new_sock].sock, cb_Read_Resolver_Result);
1123 Conn_SetPenalty(new_sock, 4);
1125 } /* New_Connection */
1129 Socket2Index( int Sock )
1131 /* zum Socket passende Connection suchen */
1133 assert( Sock >= 0 );
1135 if( Sock >= Pool_Size || My_Connections[Sock].sock != Sock ) {
1136 /* die Connection wurde vermutlich (wegen eines
1137 * Fehlers) bereits wieder abgebaut ... */
1138 LogDebug("Socket2Index: can't get connection for socket %d!", Sock);
1142 } /* Socket2Index */
1146 * Read data from the network to the read buffer. If an error occures,
1147 * the socket of this connection will be shut down.
1150 Read_Request( CONN_ID Idx )
1153 char readbuf[READBUFFER_LEN];
1155 assert( Idx > NONE );
1156 assert( My_Connections[Idx].sock > NONE );
1159 if ((array_bytes(&My_Connections[Idx].rbuf) >= READBUFFER_LEN) ||
1160 (array_bytes(&My_Connections[Idx].zip.rbuf) >= READBUFFER_LEN))
1162 if (array_bytes(&My_Connections[Idx].rbuf) >= READBUFFER_LEN)
1165 /* Read buffer is full */
1167 "Receive buffer overflow (connection %d): %d bytes!",
1168 Idx, array_bytes(&My_Connections[Idx].rbuf));
1169 Conn_Close( Idx, "Receive buffer overflow!", NULL, false );
1173 len = read(My_Connections[Idx].sock, readbuf, sizeof(readbuf));
1175 Log(LOG_INFO, "%s:%u (%s) is closing the connection ...",
1176 My_Connections[Idx].host,
1177 (unsigned int) ng_ipaddr_getport(&My_Connections[Idx].addr),
1178 ng_ipaddr_tostr(&My_Connections[Idx].addr));
1180 "Socket closed!", "Client closed connection",
1186 if( errno == EAGAIN ) return;
1187 Log(LOG_ERR, "Read error on connection %d (socket %d): %s!",
1188 Idx, My_Connections[Idx].sock, strerror(errno));
1189 Conn_Close(Idx, "Read error!", "Client closed connection",
1194 if (Conn_OPTION_ISSET(&My_Connections[Idx], CONN_ZIP)) {
1195 if (!array_catb(&My_Connections[Idx].zip.rbuf, readbuf,
1198 "Could not append recieved data to zip input buffer (connn %d): %d bytes!",
1200 Conn_Close(Idx, "Receive buffer overflow!", NULL,
1207 if (!array_catb( &My_Connections[Idx].rbuf, readbuf, len)) {
1208 Log( LOG_ERR, "Could not append recieved data to input buffer (connn %d): %d bytes!", Idx, len );
1209 Conn_Close( Idx, "Receive buffer overflow!", NULL, false );
1213 /* Update connection statistics */
1214 My_Connections[Idx].bytes_in += len;
1216 /* Update timestamp of last data received if this connection is
1217 * registered as a user, server or service connection. Don't update
1218 * otherwise, so users have at least Conf_PongTimeout seconds time to
1219 * register with the IRC server -- see Check_Connections().
1220 * Set "lastping", too, so we can handle time shifts backwards ... */
1221 c = Conn_GetClient(Idx);
1222 if (c && (Client_Type(c) == CLIENT_USER
1223 || Client_Type(c) == CLIENT_SERVER
1224 || Client_Type(c) == CLIENT_SERVICE)) {
1225 My_Connections[Idx].lastdata = time(NULL);
1226 My_Connections[Idx].lastping = My_Connections[Idx].lastdata;
1229 /* Look at the data in the (read-) buffer of this connection */
1231 } /* Read_Request */
1235 * Handle all data in the connection read-buffer.
1236 * All data is precessed until no complete command is left. When a fatal
1237 * error occurs, the connection is shut down.
1240 Handle_Buffer(CONN_ID Idx)
1243 char *ptr1, *ptr2, *first_eol;
1252 starttime = time(NULL);
1255 if (My_Connections[Idx].delaytime > starttime)
1258 /* Unpack compressed data, if compression is in use */
1259 if (Conn_OPTION_ISSET(&My_Connections[Idx], CONN_ZIP)) {
1260 /* When unzipping fails, Unzip_Buffer() shuts
1261 * down the connection itself */
1262 if (!Unzip_Buffer(Idx))
1267 if (0 == array_bytes(&My_Connections[Idx].rbuf))
1270 /* Make sure that the buffer is NULL terminated */
1271 if (!array_cat0_temporary(&My_Connections[Idx].rbuf)) {
1272 Conn_Close(Idx, NULL,
1273 "Can't allocate memory [Handle_Buffer]",
1278 /* RFC 2812, section "2.3 Messages", 5th paragraph:
1279 * "IRC messages are always lines of characters terminated
1280 * with a CR-LF (Carriage Return - Line Feed) pair [...]". */
1282 ptr = strstr(array_start(&My_Connections[Idx].rbuf), "\r\n");
1285 /* Check for non-RFC-compliant request (only CR or LF)?
1286 * Unfortunately, there are quite a few clients out there
1287 * that do this -- e. g. mIRC, BitchX, and Trillian :-( */
1288 ptr1 = strchr(array_start(&My_Connections[Idx].rbuf), '\r');
1289 ptr2 = strchr(array_start(&My_Connections[Idx].rbuf), '\n');
1291 /* Check if there is a single CR or LF _before_ the
1292 * corerct CR+LF line terminator: */
1293 first_eol = ptr1 < ptr2 ? ptr1 : ptr2;
1294 if (first_eol < ptr) {
1295 /* Single CR or LF before CR+LF found */
1299 } else if (ptr1 || ptr2) {
1300 /* No CR+LF terminated command found, but single
1301 * CR or LF found ... */
1303 ptr = ptr1 < ptr2 ? ptr1 : ptr2;
1305 ptr = ptr1 ? ptr1 : ptr2;
1313 /* Complete (=line terminated) request found, handle it! */
1316 len = ptr - (char *)array_start(&My_Connections[Idx].rbuf) + delta;
1318 if (len > (COMMAND_LEN - 1)) {
1319 /* Request must not exceed 512 chars (incl. CR+LF!),
1320 * see RFC 2812. Disconnect Client if this happens. */
1322 "Request too long (connection %d): %d bytes (max. %d expected)!",
1323 Idx, array_bytes(&My_Connections[Idx].rbuf),
1325 Conn_Close(Idx, NULL, "Request too long", true);
1330 /* Request is empty (only '\r\n', '\r' or '\n');
1331 * delta is 2 ('\r\n') or 1 ('\r' or '\n'), see above */
1332 array_moveleft(&My_Connections[Idx].rbuf, 1, len);
1337 /* remember if stream is already compressed */
1338 old_z = My_Connections[Idx].options & CONN_ZIP;
1341 My_Connections[Idx].msg_in++;
1343 (Idx, (char *)array_start(&My_Connections[Idx].rbuf)))
1346 array_moveleft(&My_Connections[Idx].rbuf, 1, len);
1347 LogDebug("Connection %d: %d bytes left in read buffer.",
1348 Idx, array_bytes(&My_Connections[Idx].rbuf));
1350 if ((!old_z) && (My_Connections[Idx].options & CONN_ZIP) &&
1351 (array_bytes(&My_Connections[Idx].rbuf) > 0)) {
1352 /* The last command activated socket compression.
1353 * Data that was read after that needs to be copied
1354 * to the unzip buffer for decompression: */
1356 (&My_Connections[Idx].zip.rbuf,
1357 &My_Connections[Idx].rbuf)) {
1358 Conn_Close(Idx, NULL,
1359 "Can't allocate memory [Handle_Buffer]",
1364 array_trunc(&My_Connections[Idx].rbuf);
1366 ("Moved already received data (%u bytes) to uncompression buffer.",
1367 array_bytes(&My_Connections[Idx].zip.rbuf));
1371 } /* Handle_Buffer */
1375 Check_Connections(void)
1377 /* check if connections are alive. if not, play PING-PONG first.
1378 * if this doesn't help either, disconnect client. */
1382 for (i = 0; i < Pool_Size; i++) {
1383 if (My_Connections[i].sock < 0)
1386 c = Conn_GetClient(i);
1387 if (c && ((Client_Type(c) == CLIENT_USER)
1388 || (Client_Type(c) == CLIENT_SERVER)
1389 || (Client_Type(c) == CLIENT_SERVICE))) {
1390 /* connected User, Server or Service */
1391 if (My_Connections[i].lastping >
1392 My_Connections[i].lastdata) {
1393 /* We already sent a ping */
1394 if (My_Connections[i].lastping <
1395 time(NULL) - Conf_PongTimeout) {
1398 ("Connection %d: Ping timeout: %d seconds.",
1399 i, Conf_PongTimeout);
1400 Conn_Close(i, NULL, "Ping timeout",
1403 } else if (My_Connections[i].lastdata <
1404 time(NULL) - Conf_PingTimeout) {
1405 /* We need to send a PING ... */
1406 LogDebug("Connection %d: sending PING ...", i);
1407 My_Connections[i].lastping = time(NULL);
1408 Conn_WriteStr(i, "PING :%s",
1409 Client_ID(Client_ThisServer()));
1412 /* The connection is not fully established yet, so
1413 * we don't do the PING-PONG game here but instead
1414 * disconnect the client after "a short time" if it's
1415 * still not registered. */
1417 if (My_Connections[i].lastdata <
1418 time(NULL) - Conf_PongTimeout) {
1420 ("Unregistered connection %d timed out ...",
1422 Conn_Close(i, NULL, "Timeout", false);
1426 } /* Check_Connections */
1430 Check_Servers( void )
1432 /* Check if we can establish further server links */
1437 /* Check all configured servers */
1438 for( i = 0; i < MAX_SERVERS; i++ ) {
1439 /* Valid outgoing server which isn't already connected or disabled? */
1440 if(( ! Conf_Server[i].host[0] ) || ( ! Conf_Server[i].port > 0 ) ||
1441 ( Conf_Server[i].conn_id > NONE ) || ( Conf_Server[i].flags & CONF_SFLAG_DISABLED ))
1444 /* Is there already a connection in this group? */
1445 if( Conf_Server[i].group > NONE ) {
1446 for (n = 0; n < MAX_SERVERS; n++) {
1447 if (n == i) continue;
1448 if ((Conf_Server[n].conn_id != NONE) &&
1449 (Conf_Server[n].group == Conf_Server[i].group))
1452 if (n < MAX_SERVERS) continue;
1455 /* Check last connect attempt? */
1456 time_now = time(NULL);
1457 if( Conf_Server[i].lasttry > (time_now - Conf_ConnectRetry))
1460 /* Okay, try to connect now */
1461 Conf_Server[i].lasttry = time_now;
1462 Conf_Server[i].conn_id = SERVER_WAIT;
1463 assert(Resolve_Getfd(&Conf_Server[i].res_stat) < 0);
1464 Resolve_Name(&Conf_Server[i].res_stat, Conf_Server[i].host, cb_Connect_to_Server);
1466 } /* Check_Servers */
1470 New_Server( int Server , ng_ipaddr_t *dest)
1472 /* Establish new server link */
1473 char ip_str[NG_INET_ADDRSTRLEN];
1474 int af_dest, res, new_sock;
1477 assert( Server > NONE );
1479 if (!ng_ipaddr_tostr_r(dest, ip_str)) {
1480 Log(LOG_WARNING, "New_Server: Could not convert IP to string");
1484 Log( LOG_INFO, "Establishing connection to \"%s\", %s, port %d ... ",
1485 Conf_Server[Server].host, ip_str, Conf_Server[Server].port );
1487 af_dest = ng_ipaddr_af(dest);
1488 new_sock = socket(af_dest, SOCK_STREAM, 0);
1490 Log( LOG_CRIT, "Can't create socket (af %d) : %s!", af_dest, strerror( errno ));
1494 if (!Init_Socket(new_sock))
1497 /* is a bind address configured? */
1498 res = ng_ipaddr_af(&Conf_Server[Server].bind_addr);
1499 /* if yes, bind now. If it fails, warn and let connect() pick a source address */
1500 if (res && bind(new_sock, (struct sockaddr *) &Conf_Server[Server].bind_addr,
1501 ng_ipaddr_salen(&Conf_Server[Server].bind_addr)))
1503 ng_ipaddr_tostr_r(&Conf_Server[Server].bind_addr, ip_str);
1504 Log(LOG_WARNING, "Can't bind socket to %s: %s!", ip_str, strerror(errno));
1506 ng_ipaddr_setport(dest, Conf_Server[Server].port);
1507 res = connect(new_sock, (struct sockaddr *) dest, ng_ipaddr_salen(dest));
1508 if(( res != 0 ) && ( errno != EINPROGRESS )) {
1509 Log( LOG_CRIT, "Can't connect socket: %s!", strerror( errno ));
1514 if (!array_alloc(&My_ConnArray, sizeof(CONNECTION), (size_t)new_sock)) {
1516 "Cannot allocate memory for server connection (socket %d)",
1522 My_Connections = array_start(&My_ConnArray);
1524 assert(My_Connections[new_sock].sock <= 0);
1526 Init_Conn_Struct(new_sock);
1528 ng_ipaddr_tostr_r(dest, ip_str);
1529 c = Client_NewLocal(new_sock, ip_str, CLIENT_UNKNOWNSERVER, false);
1531 Log( LOG_ALERT, "Can't establish connection: can't create client structure!" );
1536 Client_SetIntroducer( c, c );
1537 Client_SetToken( c, TOKEN_OUTBOUND );
1539 /* Register connection */
1540 Conf_Server[Server].conn_id = new_sock;
1541 My_Connections[new_sock].sock = new_sock;
1542 My_Connections[new_sock].addr = *dest;
1543 My_Connections[new_sock].client = c;
1544 strlcpy( My_Connections[new_sock].host, Conf_Server[Server].host,
1545 sizeof(My_Connections[new_sock].host ));
1547 /* Register new socket */
1548 if (!io_event_create( new_sock, IO_WANTWRITE, cb_connserver)) {
1549 Log( LOG_ALERT, "io_event_create(): could not add fd %d", strerror(errno));
1550 Conn_Close( new_sock, "io_event_create() failed", NULL, false );
1551 Init_Conn_Struct( new_sock );
1552 Conf_Server[Server].conn_id = NONE;
1555 LogDebug("Registered new connection %d on socket %d.",
1556 new_sock, My_Connections[new_sock].sock );
1557 Conn_OPTION_ADD( &My_Connections[new_sock], CONN_ISCONNECTING );
1562 * Initialize connection structure.
1565 Init_Conn_Struct(CONN_ID Idx)
1567 time_t now = time(NULL);
1569 memset(&My_Connections[Idx], 0, sizeof(CONNECTION));
1570 My_Connections[Idx].sock = -1;
1571 My_Connections[Idx].signon = now;
1572 My_Connections[Idx].lastdata = now;
1573 My_Connections[Idx].lastprivmsg = now;
1574 Resolve_Init(&My_Connections[Idx].res_stat);
1575 } /* Init_Conn_Struct */
1579 Init_Socket( int Sock )
1581 /* Initialize socket (set options) */
1585 if (!io_setnonblock(Sock)) {
1586 Log( LOG_CRIT, "Can't enable non-blocking mode for socket: %s!", strerror( errno ));
1591 /* Don't block this port after socket shutdown */
1593 if( setsockopt( Sock, SOL_SOCKET, SO_REUSEADDR, &value, (socklen_t)sizeof( value )) != 0 )
1595 Log( LOG_ERR, "Can't set socket option SO_REUSEADDR: %s!", strerror( errno ));
1596 /* ignore this error */
1599 /* Set type of service (TOS) */
1600 #if defined(IP_TOS) && defined(IPTOS_LOWDELAY)
1601 value = IPTOS_LOWDELAY;
1602 LogDebug("Setting option IP_TOS on socket %d to IPTOS_LOWDELAY (%d).", Sock, value );
1603 if( setsockopt( Sock, SOL_IP, IP_TOS, &value, (socklen_t)sizeof( value )) != 0 )
1605 Log( LOG_ERR, "Can't set socket option IP_TOS: %s!", strerror( errno ));
1606 /* ignore this error */
1616 cb_Connect_to_Server(int fd, UNUSED short events)
1618 /* Read result of resolver sub-process from pipe and start connection */
1621 ng_ipaddr_t dest_addrs[4]; /* we can handle at most 3; but we read up to
1622 four so we can log the 'more than we can handle'
1625 LogDebug("Resolver: Got forward lookup callback on fd %d, events %d", fd, events);
1627 for (i=0; i < MAX_SERVERS; i++) {
1628 if (Resolve_Getfd(&Conf_Server[i].res_stat) == fd )
1632 if( i >= MAX_SERVERS) {
1633 /* Ops, no matching server found?! */
1635 LogDebug("Resolver: Got Forward Lookup callback for unknown server!?");
1639 /* Read result from pipe */
1640 len = Resolve_Read(&Conf_Server[i].res_stat, dest_addrs, sizeof(dest_addrs));
1644 assert((len % sizeof(ng_ipaddr_t)) == 0);
1646 LogDebug("Got result from resolver: %u structs (%u bytes).", len/sizeof(ng_ipaddr_t), len);
1648 memset(&Conf_Server[i].dst_addr, 0, sizeof(&Conf_Server[i].dst_addr));
1649 if (len > sizeof(ng_ipaddr_t)) {
1650 /* more than one address for this hostname, remember them
1651 * in case first address is unreachable/not available */
1652 len -= sizeof(ng_ipaddr_t);
1653 if (len > sizeof(&Conf_Server[i].dst_addr)) {
1654 len = sizeof(&Conf_Server[i].dst_addr);
1655 Log(LOG_NOTICE, "Notice: Resolver returned more IP Addresses for host than we can handle,"
1656 " additional addresses dropped");
1658 memcpy(&Conf_Server[i].dst_addr, &dest_addrs[1], len);
1661 New_Server(i, dest_addrs);
1662 } /* cb_Read_Forward_Lookup */
1666 cb_Read_Resolver_Result( int r_fd, UNUSED short events )
1668 /* Read result of resolver sub-process from pipe and update the
1669 * apropriate connection/client structure(s): hostname and/or
1670 * IDENT user name.*/
1677 char readbuf[HOST_LEN + 2 + CLIENT_USER_LEN];
1679 char readbuf[HOST_LEN + 1];
1682 LogDebug("Resolver: Got callback on fd %d, events %d", r_fd, events );
1684 /* Search associated connection ... */
1685 for( i = 0; i < Pool_Size; i++ ) {
1686 if(( My_Connections[i].sock != NONE )
1687 && ( Resolve_Getfd(&My_Connections[i].res_stat) == r_fd ))
1690 if( i >= Pool_Size ) {
1691 /* Ops, none found? Probably the connection has already
1692 * been closed!? We'll ignore that ... */
1694 LogDebug("Resolver: Got callback for unknown connection!?");
1698 /* Read result from pipe */
1699 len = Resolve_Read(&My_Connections[i].res_stat, readbuf, sizeof readbuf -1);
1703 readbuf[len] = '\0';
1704 identptr = strchr(readbuf, '\n');
1705 assert(identptr != NULL);
1707 Log( LOG_CRIT, "Resolver: Got malformed result!");
1712 LogDebug("Got result from resolver: \"%s\" (%u bytes read).", readbuf, len);
1713 /* Okay, we got a complete result: this is a host name for outgoing
1714 * connections and a host name and IDENT user name (if enabled) for
1715 * incoming connections.*/
1716 assert ( My_Connections[i].sock >= 0 );
1717 /* Incoming connection. Search client ... */
1718 c = Conn_GetClient( i );
1719 assert( c != NULL );
1721 /* Only update client information of unregistered clients */
1722 if( Client_Type( c ) == CLIENT_UNKNOWN ) {
1723 strlcpy(My_Connections[i].host, readbuf, sizeof( My_Connections[i].host));
1724 Client_SetHostname( c, readbuf);
1728 Log(LOG_INFO, "IDENT lookup for connection %d: \"%s\".", i, identptr);
1729 Client_SetUser(c, identptr, true);
1731 Log(LOG_INFO, "IDENT lookup for connection %d: no result.", i);
1736 else Log( LOG_DEBUG, "Resolver: discarding result for already registered connection %d.", i );
1738 /* Reset penalty time */
1739 Conn_ResetPenalty( i );
1740 } /* cb_Read_Resolver_Result */
1744 Simple_Message( int Sock, const char *Msg )
1746 char buf[COMMAND_LEN];
1748 /* Write "simple" message to socket, without using compression
1749 * or even the connection write buffers. Used e.g. for error
1750 * messages by New_Connection(). */
1751 assert( Sock > NONE );
1752 assert( Msg != NULL );
1754 strlcpy( buf, Msg, sizeof buf - 2);
1755 len = strlcat( buf, "\r\n", sizeof buf);
1756 (void)write(Sock, buf, len);
1757 } /* Simple_Error */
1761 Conn_GetClient( CONN_ID Idx )
1763 /* return Client-Structure that belongs to the local Connection Idx.
1764 * If none is found, return NULL.
1769 c = array_get(&My_ConnArray, sizeof (CONNECTION), (size_t)Idx);
1773 return c ? c->client : NULL;