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
33 #include <sys/socket.h>
35 #include <sys/types.h>
37 #include <netinet/in.h>
39 #ifdef HAVE_NETINET_IP_H
40 # include <netinet/ip.h>
44 # include <stdint.h> /* e.g. for Mac OS X */
48 # 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 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 ));
93 static array My_Listeners;
94 static array My_ConnArray;
95 static size_t NumConnections;
98 int allow_severity = LOG_INFO;
99 int deny_severity = LOG_ERR;
102 static void server_login PARAMS((CONN_ID idx));
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));
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));
114 cb_listen(int sock, short irrelevant)
117 if (New_Connection( sock ) >= 0)
119 LogDebug("Total number of connections now %ld.", NumConnections);
125 cb_listen_ssl(int sock, short irrelevant)
129 fd = New_Connection(sock);
134 LogDebug("Total number of connections now %ld.", NumConnections);
135 io_event_setcb(My_Connections[fd].sock, cb_clientserver_ssl);
141 cb_connserver(int sock, UNUSED short what)
145 CONN_ID idx = Socket2Index( sock );
147 LogDebug("cb_connserver wants to write on unknown socket?!");
152 assert( what & IO_WANTWRITE);
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 ));
159 /* Error while connecting? */
160 if ((res != 0) || (err != 0)) {
162 Log(LOG_CRIT, "getsockopt (connection %d): %s!",
163 idx, strerror(errno));
166 "Can't connect socket to \"%s:%d\" (connection %d): %s!",
167 My_Connections[idx].host,
168 Conf_Server[Conf_GetServer(idx)].port,
171 res = Conf_GetServer(idx);
174 Conn_Close(idx, "Can't connect!", NULL, false);
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];
184 memset(&Conf_Server[res].dst_addr[1], 0, sizeof(&Conf_Server[res].dst_addr[1]));
189 res = Conf_GetServer(idx);
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 );
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 );
206 server_login(CONN_ID idx)
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 );
211 io_event_setcb( My_Connections[idx].sock, cb_clientserver);
212 io_event_add( My_Connections[idx].sock, IO_WANTREAD|IO_WANTWRITE);
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 );
222 cb_connserver_login_ssl(int sock, short unused)
224 CONN_ID idx = Socket2Index(sock);
232 switch (ConnSSL_Connect( &My_Connections[idx])) {
234 case 0: LogDebug("ConnSSL_Connect: not ready");
237 Log(LOG_INFO, "SSL connection on socket %d failed", sock);
238 Conn_Close(idx, "Can't connect!", NULL, false);
242 Log( LOG_INFO, "SSL Connection %d with \"%s:%d\" established.", idx,
243 My_Connections[idx].host, Conf_Server[Conf_GetServer( idx )].port );
251 cb_clientserver(int sock, short what)
253 CONN_ID idx = Socket2Index(sock);
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 */
265 if (what & IO_WANTREAD)
268 if (what & IO_WANTWRITE)
275 cb_clientserver_ssl(int sock, short what)
277 CONN_ID idx = Socket2Index(sock);
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 */
290 Conn_Close( idx, "Socket closed!", "SSL accept error", false );
293 if (what & IO_WANTREAD)
296 if (what & IO_WANTWRITE)
299 io_event_setcb(sock, cb_clientserver); /* SSL handshake completed */
307 /* Modul initialisieren: statische Strukturen "ausnullen". */
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;
317 if (!array_alloc(&My_ConnArray, sizeof(CONNECTION), (size_t)Pool_Size)) {
318 Log( LOG_EMERG, "Can't allocate memory! [Conn_Init]" );
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);
326 LogDebug("Allocated connection pool for %d items (%ld bytes).",
327 array_length(&My_ConnArray, sizeof( CONNECTION )), array_bytes(&My_ConnArray));
329 assert( array_length(&My_ConnArray, sizeof( CONNECTION )) >= (size_t) Pool_Size);
331 array_free( &My_Listeners );
333 /* Connection-Struktur initialisieren */
334 for( i = 0; i < Pool_Size; i++ ) Init_Conn_Struct( i );
336 /* Global write counter */
344 /* Modul abmelden: alle noch offenen Connections
345 * schliessen und freigeben. */
349 LogDebug("Shutting down all connections ..." );
351 Conn_ExitListeners();
353 /* Sockets schliessen */
354 for( idx = 0; idx < Pool_Size; idx++ ) {
355 if( My_Connections[idx].sock > NONE ) {
356 Conn_Close( idx, NULL, NGIRCd_SignalRestart ?
357 "Server going down (restarting)":"Server going down", true );
361 array_free(&My_ConnArray);
362 My_Connections = NULL;
364 io_library_shutdown();
369 ports_initlisteners(array *a, const char *listen_addr, void (*func)(int,short))
371 unsigned int created = 0;
376 len = array_length(a, sizeof (UINT16));
377 port = array_start(a);
379 fd = NewListener(listen_addr, *port);
384 if (!io_event_create( fd, IO_WANTREAD, func )) {
385 Log( LOG_ERR, "io_event_create(): Could not add listening fd %d (port %u): %s!",
386 fd, (unsigned int) *port, strerror(errno));
399 Conn_InitListeners( void )
401 /* Initialize ports on which the server should accept connections */
402 unsigned int created = 0;
403 char *copy, *listen_addr;
405 if (!io_library_init(CONNECTION_POOL)) {
406 Log(LOG_EMERG, "Cannot initialize IO routines: %s", strerror(errno));
410 assert(Conf_ListenAddress);
412 /* can't use Conf_ListenAddress directly, see below */
413 copy = strdup(Conf_ListenAddress);
415 Log(LOG_CRIT, "Cannot copy %s: %s", Conf_ListenAddress, strerror(errno));
418 listen_addr = strtok(copy, ",");
420 while (listen_addr) {
421 ngt_TrimStr(listen_addr);
423 created += ports_initlisteners(&Conf_ListenPorts, listen_addr, cb_listen);
425 created += ports_initlisteners(&Conf_SSLOptions.ListenPorts, listen_addr, cb_listen_ssl);
429 listen_addr = strtok(NULL, ",");
433 * can't free() Conf_ListenAddress here. On /REHASH, if the config file
434 * cannot be re-loaded, we'd end up with a NULL Conf_ListenAddress.
435 * Instead, free() takes place in conf.c, before the config file
440 } /* Conn_InitListeners */
444 Conn_ExitListeners( void )
446 /* Close down all listening sockets */
450 Rendezvous_UnregisterListeners( );
453 arraylen = array_length(&My_Listeners, sizeof (int));
454 Log( LOG_INFO, "Shutting down all listening sockets (%d total)...", arraylen );
455 fd = array_start(&My_Listeners);
460 LogDebug("Listening socket %d closed.", *fd );
463 array_free(&My_Listeners);
464 } /* Conn_ExitListeners */
468 InitSinaddrListenAddr(ng_ipaddr_t *addr, const char *listen_addrstr, UINT16 Port)
472 ret = ng_ipaddr_init(addr, listen_addrstr, Port);
474 assert(listen_addrstr);
475 Log(LOG_CRIT, "Can't bind to [%s]:%u: can't convert ip address \"%s\"",
476 listen_addrstr, Port, listen_addrstr);
483 set_v6_only(int af, int sock)
485 #if defined(IPV6_V6ONLY) && defined(WANT_IPV6)
491 if (setsockopt(sock, IPPROTO_IPV6, IPV6_V6ONLY, &on, sizeof(on)))
492 Log(LOG_ERR, "Could not set IPV6_V6ONLY: %s", strerror(errno));
500 /* return new listening port file descriptor or -1 on failure */
502 NewListener(const char *listen_addr, UINT16 Port)
504 /* Create new listening socket on specified port */
508 char name[CLIENT_ID_LEN], *info;
510 if (!InitSinaddrListenAddr(&addr, listen_addr, Port))
513 af = ng_ipaddr_af(&addr);
514 sock = socket(af, SOCK_STREAM, 0);
516 Log(LOG_CRIT, "Can't create socket (af %d) : %s!", af, strerror(errno));
520 set_v6_only(af, sock);
522 if (!Init_Socket(sock))
525 if (bind(sock, (struct sockaddr *)&addr, ng_ipaddr_salen(&addr)) != 0) {
526 Log(LOG_CRIT, "Can't bind socket to address %s:%d - %s",
527 ng_ipaddr_tostr(&addr), Port, strerror(errno));
532 if( listen( sock, 10 ) != 0 ) {
533 Log( LOG_CRIT, "Can't listen on socket: %s!", strerror( errno ));
538 /* keep fd in list so we can close it when ngircd restarts/shuts down */
539 if (!array_catb( &My_Listeners,(char*) &sock, sizeof(int) )) {
540 Log( LOG_CRIT, "Can't add socket to My_Listeners array: %s!", strerror( errno ));
545 Log(LOG_INFO, "Now listening on [%s]:%d (socket %d).", ng_ipaddr_tostr(&addr), Port, sock);
548 /* Get best server description text */
549 if( ! Conf_ServerInfo[0] ) info = Conf_ServerName;
552 /* Use server info string */
554 if( Conf_ServerInfo[0] == '[' )
556 /* Cut off leading hostname part in "[]" */
557 info = strchr( Conf_ServerInfo, ']' );
561 while( *info == ' ' ) info++;
564 if( ! info ) info = Conf_ServerInfo;
567 /* Add port number to description if non-standard */
569 snprintf(name, sizeof name, "%s (port %u)", info,
572 strlcpy(name, info, sizeof name);
574 /* Register service */
575 Rendezvous_Register( name, MDNS_TYPE, Port );
582 * SSL/TLS connections require extra treatment:
583 * When either CONN_SSL_WANT_WRITE or CONN_SSL_WANT_READ is set, we
584 * need to take care of that first, before checking read/write buffers.
585 * For instance, while we might have data in our write buffer, the
586 * TLS/SSL protocol might need to read internal data first for TLS/SSL
589 * If this function returns true, such a condition is met and we have
590 * to reverse the condition (check for read even if we've data to write,
591 * do not check for read but writeability even if write-buffer is empty).
594 SSL_WantRead(const CONNECTION *c)
596 if (Conn_OPTION_ISSET(c, CONN_SSL_WANT_READ)) {
597 io_event_add(c->sock, IO_WANTREAD);
603 SSL_WantWrite(const CONNECTION *c)
605 if (Conn_OPTION_ISSET(c, CONN_SSL_WANT_WRITE)) {
606 io_event_add(c->sock, IO_WANTWRITE);
613 SSL_WantRead(UNUSED const CONNECTION *c) { return false; }
615 SSL_WantWrite(UNUSED const CONNECTION *c) { return false; }
620 * "Main Loop": Loop until shutdown or restart is signalled.
621 * This function loops until a shutdown or restart of ngIRCd is signalled and
622 * calls io_dispatch() to check for readable and writable sockets every second.
623 * It checks for status changes on pending connections (e. g. when a hostname
624 * has been resolved), checks for "penalties" and timeouts, and handles the
631 unsigned int wdatalen;
635 while (!NGIRCd_SignalQuit && !NGIRCd_SignalRestart) {
639 Rendezvous_Handler();
642 /* Should the configuration be reloaded? */
643 if (NGIRCd_SignalRehash)
646 /* Check configured servers and established links */
650 /* Look for non-empty read buffers ... */
651 for (i = 0; i < Pool_Size; i++) {
652 if ((My_Connections[i].sock > NONE)
653 && (array_bytes(&My_Connections[i].rbuf) > 0)
654 && (My_Connections[i].delaytime < t)) {
655 /* ... and try to handle the received data */
660 /* Look for non-empty write buffers ... */
661 for (i = 0; i < Pool_Size; i++) {
662 if (My_Connections[i].sock <= NONE)
665 wdatalen = (unsigned int)array_bytes(&My_Connections[i].wbuf);
668 array_bytes(&My_Connections[i].zip.wbuf) > 0)
673 if (SSL_WantRead(&My_Connections[i]))
675 io_event_add(My_Connections[i].sock,
680 /* Check from which sockets we possibly could read ... */
681 for (i = 0; i < Pool_Size; i++) {
682 if (My_Connections[i].sock <= NONE)
685 if (SSL_WantWrite(&My_Connections[i]))
686 continue; /* TLS/SSL layer needs to write data; deal with this first */
688 if (Resolve_INPROGRESS(&My_Connections[i].res_stat)) {
689 /* Wait for completion of resolver sub-process ... */
690 io_event_del(My_Connections[i].sock,
695 if (Conn_OPTION_ISSET(&My_Connections[i], CONN_ISCONNECTING))
696 /* Wait for completion of connect() ... */
699 if (My_Connections[i].delaytime > t) {
700 /* There is a "penalty time" set: ignore socket! */
701 io_event_del(My_Connections[i].sock,
705 io_event_add(My_Connections[i].sock, IO_WANTREAD);
708 /* Set the timeout for reading from the network to 1 second,
709 * which is the granularity with witch we handle "penalty
710 * times" for example.
711 * Note: tv_sec/usec are undefined(!) after io_dispatch()
712 * returns, so we have to set it beforce each call to it! */
716 /* Wait for activity ... */
717 i = io_dispatch(&tv);
718 if (i == -1 && errno != EINTR) {
719 Log(LOG_EMERG, "Conn_Handler(): io_dispatch(): %s!",
721 Log(LOG_ALERT, "%s exiting due to fatal errors!",
727 if (NGIRCd_SignalQuit)
728 Log(LOG_NOTICE | LOG_snotice, "Server going down NOW!");
729 else if (NGIRCd_SignalRestart)
730 Log(LOG_NOTICE | LOG_snotice, "Server restarting NOW!");
735 * Write a text string into the socket of a connection.
736 * This function automatically appends CR+LF to the string and validates that
737 * the result is a valid IRC message (oversized messages are shortened, for
738 * example). Then it calls the Conn_Write() function to do the actual sending.
739 * @param Idx Index fo the connection.
740 * @param Format Format string, see printf().
741 * @return true on success, false otherwise.
745 Conn_WriteStr( CONN_ID Idx, char *Format, ... )
748 Conn_WriteStr( Idx, Format, va_alist )
754 char buffer[COMMAND_LEN];
759 assert( Idx > NONE );
760 assert( Format != NULL );
763 va_start( ap, Format );
767 if (vsnprintf( buffer, COMMAND_LEN - 2, Format, ap ) >= COMMAND_LEN - 2 ) {
769 * The string that should be written to the socket is longer
770 * than the allowed size of COMMAND_LEN bytes (including both
771 * the CR and LF characters). This can be caused by the
772 * IRC_WriteXXX() functions when the prefix of this server had
773 * to be added to an already "quite long" command line which
774 * has been received from a regular IRC client, for example.
776 * We are not allowed to send such "oversized" messages to
777 * other servers and clients, see RFC 2812 2.3 and 2813 3.3
778 * ("these messages SHALL NOT exceed 512 characters in length,
779 * counting all characters including the trailing CR-LF").
781 * So we have a big problem here: we should send more bytes
782 * to the network than we are allowed to and we don't know
783 * the originator (any more). The "old" behaviour of blaming
784 * the receiver ("next hop") is a bad idea (it could be just
785 * an other server only routing the message!), so the only
786 * option left is to shorten the string and to hope that the
787 * result is still somewhat useful ...
791 strcpy (buffer + sizeof(buffer) - strlen(CUT_TXTSUFFIX) - 2 - 1,
797 Log(LOG_DEBUG, " -> connection %d: '%s'.", Idx, buffer);
800 len = strlcat( buffer, "\r\n", sizeof( buffer ));
801 ok = Conn_Write(Idx, buffer, len);
802 My_Connections[Idx].msg_out++;
806 } /* Conn_WriteStr */
810 * Append Data to the outbound write buffer of a connection.
811 * @param Idx Index of the connection.
812 * @param Data pointer to the data.
813 * @param Len length of Data.
814 * @return true on success, false otherwise.
817 Conn_Write( CONN_ID Idx, char *Data, size_t Len )
820 size_t writebuf_limit = WRITEBUFFER_LEN;
821 assert( Idx > NONE );
822 assert( Data != NULL );
825 c = Conn_GetClient(Idx);
828 /* Servers do get special write buffer limits, so they can generate
829 * all the messages that are required while peering. */
830 if (Client_Type(c) == CLIENT_SERVER)
831 writebuf_limit = WRITEBUFFER_SLINK_LEN;
833 /* Is the socket still open? A previous call to Conn_Write()
834 * may have closed the connection due to a fatal error.
835 * In this case it is sufficient to return an error, as well. */
836 if( My_Connections[Idx].sock <= NONE ) {
837 LogDebug("Skipped write on closed socket (connection %d).", Idx);
842 if ( Conn_OPTION_ISSET( &My_Connections[Idx], CONN_ZIP )) {
844 * Zip_Buffer() does all the dirty work for us: it flushes
845 * the (pre-)compression buffers if required and handles
846 * all error conditions. */
847 if (!Zip_Buffer(Idx, Data, Len))
853 /* Uncompressed link:
854 * Check if outbound buffer has enough space for the data. */
855 if (array_bytes(&My_Connections[Idx].wbuf) + Len >=
857 /* Buffer is full, flush it. Handle_Write deals with
858 * low-level errors, if any. */
859 if (!Handle_Write(Idx))
863 /* When the write buffer is still too big after flushing it,
864 * the connection will be killed. */
865 if (array_bytes(&My_Connections[Idx].wbuf) + Len >=
868 "Write buffer overflow (connection %d, size %lu byte)!",
870 (unsigned long)array_bytes(&My_Connections[Idx].wbuf));
871 Conn_Close(Idx, "Write buffer overflow!", NULL, false);
875 /* Copy data to write buffer */
876 if (!array_catb(&My_Connections[Idx].wbuf, Data, Len))
879 My_Connections[Idx].bytes_out += Len;
882 /* Adjust global write counter */
890 Conn_Close( CONN_ID Idx, char *LogMsg, char *FwdMsg, bool InformClient )
892 /* Close connection. Open pipes of asyncronous resolver
893 * sub-processes are closed down. */
900 double in_z_k, out_z_k;
904 assert( Idx > NONE );
906 /* Is this link already shutting down? */
907 if( Conn_OPTION_ISSET( &My_Connections[Idx], CONN_ISCLOSING )) {
908 /* Conn_Close() has been called recursively for this link;
909 * probabe reason: Handle_Write() failed -- see below. */
910 LogDebug("Recursive request to close connection: %d", Idx );
914 assert( My_Connections[Idx].sock > NONE );
916 /* Mark link as "closing" */
917 Conn_OPTION_ADD( &My_Connections[Idx], CONN_ISCLOSING );
924 txt = "Reason unknown";
926 port = ng_ipaddr_getport(&My_Connections[Idx].addr);
927 Log(LOG_INFO, "Shutting down connection %d (%s) with %s:%d ...", Idx,
928 LogMsg ? LogMsg : FwdMsg, My_Connections[Idx].host, port);
930 /* Search client, if any */
931 c = Conn_GetClient( Idx );
933 /* Should the client be informed? */
936 /* Send statistics to client if registered as user: */
937 if ((c != NULL) && (Client_Type(c) == CLIENT_USER)) {
939 ":%s NOTICE %s :%sConnection statistics: client %.1f kb, server %.1f kb.",
940 Client_ID(Client_ThisServer()), Client_ID(c),
942 (double)My_Connections[Idx].bytes_in / 1024,
943 (double)My_Connections[Idx].bytes_out / 1024);
946 /* Send ERROR to client (see RFC!) */
948 Conn_WriteStr(Idx, "ERROR :%s", FwdMsg);
950 Conn_WriteStr(Idx, "ERROR :Closing connection.");
953 /* Try to write out the write buffer. Note: Handle_Write() eventually
954 * removes the CLIENT structure associated with this connection if an
955 * error occurs! So we have to re-check if there is still an valid
956 * CLIENT structure after calling Handle_Write() ...*/
957 (void)Handle_Write( Idx );
959 /* Search client, if any (re-check!) */
960 c = Conn_GetClient( Idx );
962 if ( Conn_OPTION_ISSET( &My_Connections[Idx], CONN_SSL )) {
963 Log( LOG_INFO, "SSL Connection %d shutting down", Idx );
964 ConnSSL_Free(&My_Connections[Idx]);
967 /* Shut down socket */
968 if (! io_close(My_Connections[Idx].sock)) {
969 /* Oops, we can't close the socket!? This is ... ugly! */
971 "Error closing connection %d (socket %d) with %s:%d - %s! (ignored)",
972 Idx, My_Connections[Idx].sock, My_Connections[Idx].host,
973 port, strerror(errno));
976 /* Mark socket as invalid: */
977 My_Connections[Idx].sock = NONE;
979 /* If there is still a client, unregister it now */
981 Client_Destroy(c, LogMsg, FwdMsg, true);
983 /* Calculate statistics and log information */
984 in_k = (double)My_Connections[Idx].bytes_in / 1024;
985 out_k = (double)My_Connections[Idx].bytes_out / 1024;
987 if (Conn_OPTION_ISSET( &My_Connections[Idx], CONN_ZIP)) {
988 in_z_k = (double)My_Connections[Idx].zip.bytes_in / 1024;
989 out_z_k = (double)My_Connections[Idx].zip.bytes_out / 1024;
990 /* Make sure that no division by zero can occur during
991 * the calculation of in_p and out_p: in_z_k and out_z_k
992 * are non-zero, that's guaranteed by the protocol until
993 * compression can be enabled. */
998 in_p = (int)(( in_k * 100 ) / in_z_k );
999 out_p = (int)(( out_k * 100 ) / out_z_k );
1001 "Connection %d with %s:%d closed (in: %.1fk/%.1fk/%d%%, out: %.1fk/%.1fk/%d%%).",
1002 Idx, My_Connections[Idx].host, port,
1003 in_k, in_z_k, in_p, out_k, out_z_k, out_p);
1009 "Connection %d with %s:%d closed (in: %.1fk, out: %.1fk).",
1010 Idx, My_Connections[Idx].host, port,
1014 /* cancel running resolver */
1015 if (Resolve_INPROGRESS(&My_Connections[Idx].res_stat))
1016 Resolve_Shutdown(&My_Connections[Idx].res_stat);
1018 /* Servers: Modify time of next connect attempt? */
1019 Conf_UnsetServer( Idx );
1022 /* Clean up zlib, if link was compressed */
1023 if ( Conn_OPTION_ISSET( &My_Connections[Idx], CONN_ZIP )) {
1024 inflateEnd( &My_Connections[Idx].zip.in );
1025 deflateEnd( &My_Connections[Idx].zip.out );
1026 array_free(&My_Connections[Idx].zip.rbuf);
1027 array_free(&My_Connections[Idx].zip.wbuf);
1031 array_free(&My_Connections[Idx].rbuf);
1032 array_free(&My_Connections[Idx].wbuf);
1034 /* Clean up connection structure (=free it) */
1035 Init_Conn_Struct( Idx );
1037 assert(NumConnections > 0);
1040 LogDebug("Shutdown of connection %d completed, %ld connection%s left.",
1041 Idx, NumConnections, NumConnections != 1 ? "s" : "");
1046 Conn_SyncServerStruct( void )
1048 /* Synchronize server structures (connection IDs):
1049 * connections <-> configuration */
1055 for( i = 0; i < Pool_Size; i++ ) {
1056 /* Established connection? */
1057 if (My_Connections[i].sock < 0)
1060 /* Server connection? */
1061 client = Conn_GetClient( i );
1062 if(( ! client ) || ( Client_Type( client ) != CLIENT_SERVER )) continue;
1064 for( c = 0; c < MAX_SERVERS; c++ )
1066 /* Configured server? */
1067 if( ! Conf_Server[c].host[0] ) continue;
1070 if( strcmp( Conf_Server[c].name, Client_ID( client )) == 0 )
1071 Conf_Server[c].conn_id = i;
1074 } /* SyncServerStruct */
1078 * Send out data of write buffer; connect new sockets.
1081 Handle_Write( CONN_ID Idx )
1086 assert( Idx > NONE );
1087 if ( My_Connections[Idx].sock < 0 ) {
1088 LogDebug("Handle_Write() on closed socket, connection %d", Idx);
1091 assert( My_Connections[Idx].sock > NONE );
1093 wdatalen = array_bytes(&My_Connections[Idx].wbuf );
1096 if (wdatalen == 0) {
1097 /* Write buffer is empty, so we try to flush the compression
1098 * buffer and get some data to work with from there :-) */
1099 if (!Zip_Flush(Idx))
1102 /* Now the write buffer most probably has changed: */
1103 wdatalen = array_bytes(&My_Connections[Idx].wbuf);
1107 if (wdatalen == 0) {
1108 /* Still no data, fine. */
1109 io_event_del(My_Connections[Idx].sock, IO_WANTWRITE );
1114 ("Handle_Write() called for connection %d, %ld bytes pending ...",
1118 if ( Conn_OPTION_ISSET( &My_Connections[Idx], CONN_SSL )) {
1119 len = ConnSSL_Write(&My_Connections[Idx], array_start(&My_Connections[Idx].wbuf), wdatalen);
1123 len = write(My_Connections[Idx].sock,
1124 array_start(&My_Connections[Idx].wbuf), wdatalen );
1127 if (errno == EAGAIN || errno == EINTR)
1130 Log(LOG_ERR, "Write error on connection %d (socket %d): %s!",
1131 Idx, My_Connections[Idx].sock, strerror(errno));
1132 Conn_Close(Idx, "Write error!", NULL, false);
1136 /* move any data not yet written to beginning */
1137 array_moveleft(&My_Connections[Idx].wbuf, 1, (size_t)len);
1140 } /* Handle_Write */
1144 Count_Connections(ng_ipaddr_t *a)
1149 for (i = 0; i < Pool_Size; i++) {
1150 if (My_Connections[i].sock <= NONE)
1152 if (ng_ipaddr_ipequal(&My_Connections[i].addr, a))
1156 } /* Count_Connections */
1160 New_Connection( int Sock )
1162 /* Neue Client-Verbindung von Listen-Socket annehmen und
1163 * CLIENT-Struktur anlegen. */
1166 struct request_info req;
1168 ng_ipaddr_t new_addr;
1169 char ip_str[NG_INET_ADDRSTRLEN];
1170 int new_sock, new_sock_len, identsock;
1174 assert( Sock > NONE );
1175 /* Connection auf Listen-Socket annehmen */
1176 new_sock_len = (int)sizeof(new_addr);
1178 new_sock = accept(Sock, (struct sockaddr *)&new_addr,
1179 (socklen_t *)&new_sock_len);
1181 Log(LOG_CRIT, "Can't accept connection: %s!", strerror(errno));
1185 if (!ng_ipaddr_tostr_r(&new_addr, ip_str)) {
1186 Log(LOG_CRIT, "fd %d: Can't convert IP address!", new_sock);
1187 Simple_Message(new_sock, "ERROR :Internal Server Error");
1193 /* Validate socket using TCP Wrappers */
1194 request_init( &req, RQ_DAEMON, PACKAGE_NAME, RQ_FILE, new_sock, RQ_CLIENT_SIN, &new_addr, NULL );
1196 if (!hosts_access(&req)) {
1197 Log (deny_severity, "Refused connection from %s (by TCP Wrappers)!", ip_str);
1198 Simple_Message( new_sock, "ERROR :Connection refused" );
1204 /* Socket initialisieren */
1205 if (!Init_Socket( new_sock ))
1208 /* Check IP-based connection limit */
1209 cnt = Count_Connections(&new_addr);
1210 if ((Conf_MaxConnectionsIP > 0) && (cnt >= Conf_MaxConnectionsIP)) {
1211 /* Access denied, too many connections from this IP address! */
1212 Log( LOG_ERR, "Refused connection from %s: too may connections (%ld) from this IP address!", ip_str, cnt);
1213 Simple_Message( new_sock, "ERROR :Connection refused, too many connections from your IP address!" );
1218 if ((Conf_MaxConnections > 0) &&
1219 (NumConnections >= (size_t) Conf_MaxConnections))
1221 Log( LOG_ALERT, "Can't accept connection: limit (%d) reached!", Conf_MaxConnections);
1222 Simple_Message( new_sock, "ERROR :Connection limit reached" );
1227 if( new_sock >= Pool_Size ) {
1228 if (!array_alloc(&My_ConnArray, sizeof(CONNECTION),
1229 (size_t)new_sock)) {
1230 Log( LOG_EMERG, "Can't allocate memory! [New_Connection]" );
1231 Simple_Message( new_sock, "ERROR: Internal error" );
1235 LogDebug("Bumped connection pool to %ld items (internal: %ld items, %ld bytes)",
1236 new_sock, array_length(&My_ConnArray, sizeof(CONNECTION)), array_bytes(&My_ConnArray));
1238 /* Adjust pointer to new block */
1239 My_Connections = array_start(&My_ConnArray);
1240 while (Pool_Size <= new_sock)
1241 Init_Conn_Struct(Pool_Size++);
1244 /* register callback */
1245 if (!io_event_create( new_sock, IO_WANTREAD, cb_clientserver)) {
1246 Log(LOG_ALERT, "Can't accept connection: io_event_create failed!");
1247 Simple_Message(new_sock, "ERROR :Internal error");
1252 c = Client_NewLocal(new_sock, ip_str, CLIENT_UNKNOWN, false );
1254 Log(LOG_ALERT, "Can't accept connection: can't create client structure!");
1255 Simple_Message(new_sock, "ERROR :Internal error");
1260 Init_Conn_Struct( new_sock );
1261 My_Connections[new_sock].sock = new_sock;
1262 My_Connections[new_sock].addr = new_addr;
1263 My_Connections[new_sock].client = c;
1265 Log( LOG_INFO, "Accepted connection %d from %s:%d on socket %d.", new_sock,
1266 ip_str, ng_ipaddr_getport(&new_addr), Sock);
1268 /* Hostnamen ermitteln */
1269 strlcpy(My_Connections[new_sock].host, ip_str, sizeof(My_Connections[new_sock].host));
1271 Client_SetHostname(c, My_Connections[new_sock].host);
1273 identsock = new_sock;
1279 Resolve_Addr(&My_Connections[new_sock].res_stat, &new_addr,
1280 identsock, cb_Read_Resolver_Result);
1281 Conn_SetPenalty(new_sock, 4);
1283 } /* New_Connection */
1287 Socket2Index( int Sock )
1289 /* zum Socket passende Connection suchen */
1291 assert( Sock >= 0 );
1293 if( Sock >= Pool_Size || My_Connections[Sock].sock != Sock ) {
1294 /* die Connection wurde vermutlich (wegen eines
1295 * Fehlers) bereits wieder abgebaut ... */
1296 LogDebug("Socket2Index: can't get connection for socket %d!", Sock);
1300 } /* Socket2Index */
1304 * Read data from the network to the read buffer. If an error occures,
1305 * the socket of this connection will be shut down.
1308 Read_Request( CONN_ID Idx )
1311 char readbuf[READBUFFER_LEN];
1313 assert( Idx > NONE );
1314 assert( My_Connections[Idx].sock > NONE );
1317 if ((array_bytes(&My_Connections[Idx].rbuf) >= READBUFFER_LEN) ||
1318 (array_bytes(&My_Connections[Idx].zip.rbuf) >= READBUFFER_LEN))
1320 if (array_bytes(&My_Connections[Idx].rbuf) >= READBUFFER_LEN)
1323 /* Read buffer is full */
1325 "Receive buffer overflow (connection %d): %d bytes!",
1326 Idx, array_bytes(&My_Connections[Idx].rbuf));
1327 Conn_Close( Idx, "Receive buffer overflow!", NULL, false );
1332 if (Conn_OPTION_ISSET(&My_Connections[Idx], CONN_SSL))
1333 len = ConnSSL_Read( &My_Connections[Idx], readbuf, sizeof(readbuf));
1336 len = read(My_Connections[Idx].sock, readbuf, sizeof(readbuf));
1338 Log(LOG_INFO, "%s:%u (%s) is closing the connection ...",
1339 My_Connections[Idx].host,
1340 (unsigned int) ng_ipaddr_getport(&My_Connections[Idx].addr),
1341 ng_ipaddr_tostr(&My_Connections[Idx].addr));
1343 "Socket closed!", "Client closed connection",
1349 if( errno == EAGAIN ) return;
1350 Log(LOG_ERR, "Read error on connection %d (socket %d): %s!",
1351 Idx, My_Connections[Idx].sock, strerror(errno));
1352 Conn_Close(Idx, "Read error!", "Client closed connection",
1357 if (Conn_OPTION_ISSET(&My_Connections[Idx], CONN_ZIP)) {
1358 if (!array_catb(&My_Connections[Idx].zip.rbuf, readbuf,
1361 "Could not append recieved data to zip input buffer (connn %d): %d bytes!",
1363 Conn_Close(Idx, "Receive buffer overflow!", NULL,
1370 if (!array_catb( &My_Connections[Idx].rbuf, readbuf, len)) {
1371 Log( LOG_ERR, "Could not append recieved data to input buffer (connn %d): %d bytes!", Idx, len );
1372 Conn_Close( Idx, "Receive buffer overflow!", NULL, false );
1376 /* Update connection statistics */
1377 My_Connections[Idx].bytes_in += len;
1379 /* Update timestamp of last data received if this connection is
1380 * registered as a user, server or service connection. Don't update
1381 * otherwise, so users have at least Conf_PongTimeout seconds time to
1382 * register with the IRC server -- see Check_Connections().
1383 * Set "lastping", too, so we can handle time shifts backwards ... */
1384 c = Conn_GetClient(Idx);
1385 if (c && (Client_Type(c) == CLIENT_USER
1386 || Client_Type(c) == CLIENT_SERVER
1387 || Client_Type(c) == CLIENT_SERVICE)) {
1388 My_Connections[Idx].lastdata = time(NULL);
1389 My_Connections[Idx].lastping = My_Connections[Idx].lastdata;
1392 /* Look at the data in the (read-) buffer of this connection */
1394 } /* Read_Request */
1398 * Handle all data in the connection read-buffer.
1399 * All data is precessed until no complete command is left. When a fatal
1400 * error occurs, the connection is shut down.
1403 Handle_Buffer(CONN_ID Idx)
1406 char *ptr1, *ptr2, *first_eol;
1415 starttime = time(NULL);
1418 if (My_Connections[Idx].delaytime > starttime)
1421 /* Unpack compressed data, if compression is in use */
1422 if (Conn_OPTION_ISSET(&My_Connections[Idx], CONN_ZIP)) {
1423 /* When unzipping fails, Unzip_Buffer() shuts
1424 * down the connection itself */
1425 if (!Unzip_Buffer(Idx))
1430 if (0 == array_bytes(&My_Connections[Idx].rbuf))
1433 /* Make sure that the buffer is NULL terminated */
1434 if (!array_cat0_temporary(&My_Connections[Idx].rbuf)) {
1435 Conn_Close(Idx, NULL,
1436 "Can't allocate memory [Handle_Buffer]",
1441 /* RFC 2812, section "2.3 Messages", 5th paragraph:
1442 * "IRC messages are always lines of characters terminated
1443 * with a CR-LF (Carriage Return - Line Feed) pair [...]". */
1445 ptr = strstr(array_start(&My_Connections[Idx].rbuf), "\r\n");
1448 /* Check for non-RFC-compliant request (only CR or LF)?
1449 * Unfortunately, there are quite a few clients out there
1450 * that do this -- e. g. mIRC, BitchX, and Trillian :-( */
1451 ptr1 = strchr(array_start(&My_Connections[Idx].rbuf), '\r');
1452 ptr2 = strchr(array_start(&My_Connections[Idx].rbuf), '\n');
1454 /* Check if there is a single CR or LF _before_ the
1455 * corerct CR+LF line terminator: */
1456 first_eol = ptr1 < ptr2 ? ptr1 : ptr2;
1457 if (first_eol < ptr) {
1458 /* Single CR or LF before CR+LF found */
1462 } else if (ptr1 || ptr2) {
1463 /* No CR+LF terminated command found, but single
1464 * CR or LF found ... */
1466 ptr = ptr1 < ptr2 ? ptr1 : ptr2;
1468 ptr = ptr1 ? ptr1 : ptr2;
1476 /* Complete (=line terminated) request found, handle it! */
1479 len = ptr - (char *)array_start(&My_Connections[Idx].rbuf) + delta;
1481 if (len > (COMMAND_LEN - 1)) {
1482 /* Request must not exceed 512 chars (incl. CR+LF!),
1483 * see RFC 2812. Disconnect Client if this happens. */
1485 "Request too long (connection %d): %d bytes (max. %d expected)!",
1486 Idx, array_bytes(&My_Connections[Idx].rbuf),
1488 Conn_Close(Idx, NULL, "Request too long", true);
1493 /* Request is empty (only '\r\n', '\r' or '\n');
1494 * delta is 2 ('\r\n') or 1 ('\r' or '\n'), see above */
1495 array_moveleft(&My_Connections[Idx].rbuf, 1, len);
1500 /* remember if stream is already compressed */
1501 old_z = My_Connections[Idx].options & CONN_ZIP;
1504 My_Connections[Idx].msg_in++;
1506 (Idx, (char *)array_start(&My_Connections[Idx].rbuf)))
1509 array_moveleft(&My_Connections[Idx].rbuf, 1, len);
1510 LogDebug("Connection %d: %d bytes left in read buffer.",
1511 Idx, array_bytes(&My_Connections[Idx].rbuf));
1513 if ((!old_z) && (My_Connections[Idx].options & CONN_ZIP) &&
1514 (array_bytes(&My_Connections[Idx].rbuf) > 0)) {
1515 /* The last command activated socket compression.
1516 * Data that was read after that needs to be copied
1517 * to the unzip buffer for decompression: */
1519 (&My_Connections[Idx].zip.rbuf,
1520 &My_Connections[Idx].rbuf)) {
1521 Conn_Close(Idx, NULL,
1522 "Can't allocate memory [Handle_Buffer]",
1527 array_trunc(&My_Connections[Idx].rbuf);
1529 ("Moved already received data (%u bytes) to uncompression buffer.",
1530 array_bytes(&My_Connections[Idx].zip.rbuf));
1534 } /* Handle_Buffer */
1538 Check_Connections(void)
1540 /* check if connections are alive. if not, play PING-PONG first.
1541 * if this doesn't help either, disconnect client. */
1545 for (i = 0; i < Pool_Size; i++) {
1546 if (My_Connections[i].sock < 0)
1549 c = Conn_GetClient(i);
1550 if (c && ((Client_Type(c) == CLIENT_USER)
1551 || (Client_Type(c) == CLIENT_SERVER)
1552 || (Client_Type(c) == CLIENT_SERVICE))) {
1553 /* connected User, Server or Service */
1554 if (My_Connections[i].lastping >
1555 My_Connections[i].lastdata) {
1556 /* We already sent a ping */
1557 if (My_Connections[i].lastping <
1558 time(NULL) - Conf_PongTimeout) {
1561 ("Connection %d: Ping timeout: %d seconds.",
1562 i, Conf_PongTimeout);
1563 Conn_Close(i, NULL, "Ping timeout",
1566 } else if (My_Connections[i].lastdata <
1567 time(NULL) - Conf_PingTimeout) {
1568 /* We need to send a PING ... */
1569 LogDebug("Connection %d: sending PING ...", i);
1570 My_Connections[i].lastping = time(NULL);
1571 Conn_WriteStr(i, "PING :%s",
1572 Client_ID(Client_ThisServer()));
1575 /* The connection is not fully established yet, so
1576 * we don't do the PING-PONG game here but instead
1577 * disconnect the client after "a short time" if it's
1578 * still not registered. */
1580 if (My_Connections[i].lastdata <
1581 time(NULL) - Conf_PongTimeout) {
1583 ("Unregistered connection %d timed out ...",
1585 Conn_Close(i, NULL, "Timeout", false);
1589 } /* Check_Connections */
1593 Check_Servers( void )
1595 /* Check if we can establish further server links */
1600 /* Check all configured servers */
1601 for( i = 0; i < MAX_SERVERS; i++ ) {
1602 /* Valid outgoing server which isn't already connected or disabled? */
1603 if(( ! Conf_Server[i].host[0] ) || ( ! Conf_Server[i].port > 0 ) ||
1604 ( Conf_Server[i].conn_id > NONE ) || ( Conf_Server[i].flags & CONF_SFLAG_DISABLED ))
1607 /* Is there already a connection in this group? */
1608 if( Conf_Server[i].group > NONE ) {
1609 for (n = 0; n < MAX_SERVERS; n++) {
1610 if (n == i) continue;
1611 if ((Conf_Server[n].conn_id != NONE) &&
1612 (Conf_Server[n].group == Conf_Server[i].group))
1615 if (n < MAX_SERVERS) continue;
1618 /* Check last connect attempt? */
1619 time_now = time(NULL);
1620 if( Conf_Server[i].lasttry > (time_now - Conf_ConnectRetry))
1623 /* Okay, try to connect now */
1624 Conf_Server[i].lasttry = time_now;
1625 Conf_Server[i].conn_id = SERVER_WAIT;
1626 assert(Resolve_Getfd(&Conf_Server[i].res_stat) < 0);
1627 Resolve_Name(&Conf_Server[i].res_stat, Conf_Server[i].host, cb_Connect_to_Server);
1629 } /* Check_Servers */
1633 New_Server( int Server , ng_ipaddr_t *dest)
1635 /* Establish new server link */
1636 char ip_str[NG_INET_ADDRSTRLEN];
1637 int af_dest, res, new_sock;
1640 assert( Server > NONE );
1642 if (!ng_ipaddr_tostr_r(dest, ip_str)) {
1643 Log(LOG_WARNING, "New_Server: Could not convert IP to string");
1647 Log( LOG_INFO, "Establishing connection to \"%s\", %s, port %d ... ",
1648 Conf_Server[Server].host, ip_str, Conf_Server[Server].port );
1650 af_dest = ng_ipaddr_af(dest);
1651 new_sock = socket(af_dest, SOCK_STREAM, 0);
1653 Log( LOG_CRIT, "Can't create socket (af %d) : %s!", af_dest, strerror( errno ));
1657 if (!Init_Socket(new_sock))
1660 /* is a bind address configured? */
1661 res = ng_ipaddr_af(&Conf_Server[Server].bind_addr);
1662 /* if yes, bind now. If it fails, warn and let connect() pick a source address */
1663 if (res && bind(new_sock, (struct sockaddr *) &Conf_Server[Server].bind_addr,
1664 ng_ipaddr_salen(&Conf_Server[Server].bind_addr)))
1666 ng_ipaddr_tostr_r(&Conf_Server[Server].bind_addr, ip_str);
1667 Log(LOG_WARNING, "Can't bind socket to %s: %s!", ip_str, strerror(errno));
1669 ng_ipaddr_setport(dest, Conf_Server[Server].port);
1670 res = connect(new_sock, (struct sockaddr *) dest, ng_ipaddr_salen(dest));
1671 if(( res != 0 ) && ( errno != EINPROGRESS )) {
1672 Log( LOG_CRIT, "Can't connect socket: %s!", strerror( errno ));
1677 if (!array_alloc(&My_ConnArray, sizeof(CONNECTION), (size_t)new_sock)) {
1679 "Cannot allocate memory for server connection (socket %d)",
1685 My_Connections = array_start(&My_ConnArray);
1687 assert(My_Connections[new_sock].sock <= 0);
1689 Init_Conn_Struct(new_sock);
1691 ng_ipaddr_tostr_r(dest, ip_str);
1692 c = Client_NewLocal(new_sock, ip_str, CLIENT_UNKNOWNSERVER, false);
1694 Log( LOG_ALERT, "Can't establish connection: can't create client structure!" );
1699 Client_SetIntroducer( c, c );
1700 Client_SetToken( c, TOKEN_OUTBOUND );
1702 /* Register connection */
1703 Conf_Server[Server].conn_id = new_sock;
1704 My_Connections[new_sock].sock = new_sock;
1705 My_Connections[new_sock].addr = *dest;
1706 My_Connections[new_sock].client = c;
1707 strlcpy( My_Connections[new_sock].host, Conf_Server[Server].host,
1708 sizeof(My_Connections[new_sock].host ));
1710 /* Register new socket */
1711 if (!io_event_create( new_sock, IO_WANTWRITE, cb_connserver)) {
1712 Log( LOG_ALERT, "io_event_create(): could not add fd %d", strerror(errno));
1713 Conn_Close( new_sock, "io_event_create() failed", NULL, false );
1714 Init_Conn_Struct( new_sock );
1715 Conf_Server[Server].conn_id = NONE;
1718 if (Conf_Server[Server].SSLConnect && !ConnSSL_PrepareConnect( &My_Connections[new_sock],
1719 &Conf_Server[Server] ))
1721 Log(LOG_ALERT, "Could not initialize SSL for outgoing connection");
1722 Conn_Close( new_sock, "Could not initialize SSL for outgoing connection", NULL, false );
1723 Init_Conn_Struct( new_sock );
1724 Conf_Server[Server].conn_id = NONE;
1728 LogDebug("Registered new connection %d on socket %d (%ld in total).",
1729 new_sock, My_Connections[new_sock].sock, NumConnections);
1730 Conn_OPTION_ADD( &My_Connections[new_sock], CONN_ISCONNECTING );
1735 * Initialize connection structure.
1738 Init_Conn_Struct(CONN_ID Idx)
1740 time_t now = time(NULL);
1742 memset(&My_Connections[Idx], 0, sizeof(CONNECTION));
1743 My_Connections[Idx].sock = -1;
1744 My_Connections[Idx].signon = now;
1745 My_Connections[Idx].lastdata = now;
1746 My_Connections[Idx].lastprivmsg = now;
1747 Resolve_Init(&My_Connections[Idx].res_stat);
1748 } /* Init_Conn_Struct */
1752 Init_Socket( int Sock )
1754 /* Initialize socket (set options) */
1758 if (!io_setnonblock(Sock)) {
1759 Log( LOG_CRIT, "Can't enable non-blocking mode for socket: %s!", strerror( errno ));
1764 /* Don't block this port after socket shutdown */
1766 if( setsockopt( Sock, SOL_SOCKET, SO_REUSEADDR, &value, (socklen_t)sizeof( value )) != 0 )
1768 Log( LOG_ERR, "Can't set socket option SO_REUSEADDR: %s!", strerror( errno ));
1769 /* ignore this error */
1772 /* Set type of service (TOS) */
1773 #if defined(IP_TOS) && defined(IPTOS_LOWDELAY)
1774 value = IPTOS_LOWDELAY;
1775 LogDebug("Setting option IP_TOS on socket %d to IPTOS_LOWDELAY (%d).", Sock, value );
1776 if( setsockopt( Sock, SOL_IP, IP_TOS, &value, (socklen_t)sizeof( value )) != 0 )
1778 Log( LOG_ERR, "Can't set socket option IP_TOS: %s!", strerror( errno ));
1779 /* ignore this error */
1789 cb_Connect_to_Server(int fd, UNUSED short events)
1791 /* Read result of resolver sub-process from pipe and start connection */
1794 ng_ipaddr_t dest_addrs[4]; /* we can handle at most 3; but we read up to
1795 four so we can log the 'more than we can handle'
1798 LogDebug("Resolver: Got forward lookup callback on fd %d, events %d", fd, events);
1800 for (i=0; i < MAX_SERVERS; i++) {
1801 if (Resolve_Getfd(&Conf_Server[i].res_stat) == fd )
1805 if( i >= MAX_SERVERS) {
1806 /* Ops, no matching server found?! */
1808 LogDebug("Resolver: Got Forward Lookup callback for unknown server!?");
1812 /* Read result from pipe */
1813 len = Resolve_Read(&Conf_Server[i].res_stat, dest_addrs, sizeof(dest_addrs));
1817 assert((len % sizeof(ng_ipaddr_t)) == 0);
1819 LogDebug("Got result from resolver: %u structs (%u bytes).", len/sizeof(ng_ipaddr_t), len);
1821 memset(&Conf_Server[i].dst_addr, 0, sizeof(&Conf_Server[i].dst_addr));
1822 if (len > sizeof(ng_ipaddr_t)) {
1823 /* more than one address for this hostname, remember them
1824 * in case first address is unreachable/not available */
1825 len -= sizeof(ng_ipaddr_t);
1826 if (len > sizeof(&Conf_Server[i].dst_addr)) {
1827 len = sizeof(&Conf_Server[i].dst_addr);
1828 Log(LOG_NOTICE, "Notice: Resolver returned more IP Addresses for host than we can handle,"
1829 " additional addresses dropped");
1831 memcpy(&Conf_Server[i].dst_addr, &dest_addrs[1], len);
1834 New_Server(i, dest_addrs);
1835 } /* cb_Read_Forward_Lookup */
1839 cb_Read_Resolver_Result( int r_fd, UNUSED short events )
1841 /* Read result of resolver sub-process from pipe and update the
1842 * apropriate connection/client structure(s): hostname and/or
1843 * IDENT user name.*/
1850 char readbuf[HOST_LEN + 2 + CLIENT_USER_LEN];
1852 char readbuf[HOST_LEN + 1];
1855 LogDebug("Resolver: Got callback on fd %d, events %d", r_fd, events );
1857 /* Search associated connection ... */
1858 for( i = 0; i < Pool_Size; i++ ) {
1859 if(( My_Connections[i].sock != NONE )
1860 && ( Resolve_Getfd(&My_Connections[i].res_stat) == r_fd ))
1863 if( i >= Pool_Size ) {
1864 /* Ops, none found? Probably the connection has already
1865 * been closed!? We'll ignore that ... */
1867 LogDebug("Resolver: Got callback for unknown connection!?");
1871 /* Read result from pipe */
1872 len = Resolve_Read(&My_Connections[i].res_stat, readbuf, sizeof readbuf -1);
1876 readbuf[len] = '\0';
1877 identptr = strchr(readbuf, '\n');
1878 assert(identptr != NULL);
1880 Log( LOG_CRIT, "Resolver: Got malformed result!");
1885 LogDebug("Got result from resolver: \"%s\" (%u bytes read).", readbuf, len);
1886 /* Okay, we got a complete result: this is a host name for outgoing
1887 * connections and a host name and IDENT user name (if enabled) for
1888 * incoming connections.*/
1889 assert ( My_Connections[i].sock >= 0 );
1890 /* Incoming connection. Search client ... */
1891 c = Conn_GetClient( i );
1892 assert( c != NULL );
1894 /* Only update client information of unregistered clients */
1895 if( Client_Type( c ) == CLIENT_UNKNOWN ) {
1896 strlcpy(My_Connections[i].host, readbuf, sizeof( My_Connections[i].host));
1897 Client_SetHostname( c, readbuf);
1901 Log(LOG_INFO, "IDENT lookup for connection %d: \"%s\".", i, identptr);
1902 Client_SetUser(c, identptr, true);
1904 Log(LOG_INFO, "IDENT lookup for connection %d: no result.", i);
1909 else Log( LOG_DEBUG, "Resolver: discarding result for already registered connection %d.", i );
1911 /* Reset penalty time */
1912 Conn_ResetPenalty( i );
1913 } /* cb_Read_Resolver_Result */
1917 Simple_Message( int Sock, const char *Msg )
1919 char buf[COMMAND_LEN];
1921 /* Write "simple" message to socket, without using compression
1922 * or even the connection write buffers. Used e.g. for error
1923 * messages by New_Connection(). */
1924 assert( Sock > NONE );
1925 assert( Msg != NULL );
1927 strlcpy( buf, Msg, sizeof buf - 2);
1928 len = strlcat( buf, "\r\n", sizeof buf);
1929 (void)write(Sock, buf, len);
1930 } /* Simple_Error */
1934 Conn_GetClient( CONN_ID Idx )
1936 /* return Client-Structure that belongs to the local Connection Idx.
1937 * If none is found, return NULL.
1942 c = array_get(&My_ConnArray, sizeof (CONNECTION), (size_t)Idx);
1946 return c ? c->client : NULL;
1950 /* we cannot access My_Connections in irc-info.c */
1952 Conn_GetCipherInfo(CONN_ID Idx, char *buf, size_t len)
1954 return ConnSSL_GetCipherInfo(&My_Connections[Idx], buf, len);
1959 Conn_UsesSSL(CONN_ID Idx)
1961 return Conn_OPTION_ISSET(&My_Connections[Idx], CONN_SSL);