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_ERR, "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 */
309 /* Speicher fuer Verbindungs-Pool anfordern */
310 Pool_Size = CONNECTION_POOL;
311 if ((Conf_MaxConnections > 0) &&
312 (Pool_Size > Conf_MaxConnections))
313 Pool_Size = Conf_MaxConnections;
315 if (!array_alloc(&My_ConnArray, sizeof(CONNECTION), (size_t)Pool_Size)) {
316 Log( LOG_EMERG, "Can't allocate memory! [Conn_Init]" );
320 /* FIXME: My_Connetions/Pool_Size is needed by other parts of the
321 * code; remove them! */
322 My_Connections = (CONNECTION*) array_start(&My_ConnArray);
324 LogDebug("Allocated connection pool for %d items (%ld bytes).",
325 array_length(&My_ConnArray, sizeof( CONNECTION )), array_bytes(&My_ConnArray));
327 assert( array_length(&My_ConnArray, sizeof( CONNECTION )) >= (size_t) Pool_Size);
329 array_free( &My_Listeners );
331 /* Connection-Struktur initialisieren */
332 for( i = 0; i < Pool_Size; i++ ) Init_Conn_Struct( i );
334 /* Global write counter */
344 Conn_ExitListeners();
346 LogDebug("Shutting down all connections ..." );
347 for( idx = 0; idx < Pool_Size; idx++ ) {
348 if( My_Connections[idx].sock > NONE ) {
349 Conn_Close( idx, NULL, NGIRCd_SignalRestart ?
350 "Server going down (restarting)":"Server going down", true );
354 array_free(&My_ConnArray);
355 My_Connections = NULL;
357 io_library_shutdown();
362 ports_initlisteners(array *a, const char *listen_addr, void (*func)(int,short))
364 unsigned int created = 0;
369 len = array_length(a, sizeof (UINT16));
370 port = array_start(a);
372 fd = NewListener(listen_addr, *port);
377 if (!io_event_create( fd, IO_WANTREAD, func )) {
378 Log( LOG_ERR, "io_event_create(): Could not add listening fd %d (port %u): %s!",
379 fd, (unsigned int) *port, strerror(errno));
392 Conn_InitListeners( void )
394 /* Initialize ports on which the server should accept connections */
395 unsigned int created = 0;
396 char *copy, *listen_addr;
398 if (!io_library_init(CONNECTION_POOL)) {
399 Log(LOG_EMERG, "Cannot initialize IO routines: %s", strerror(errno));
403 assert(Conf_ListenAddress);
405 /* can't use Conf_ListenAddress directly, see below */
406 copy = strdup(Conf_ListenAddress);
408 Log(LOG_CRIT, "Cannot copy %s: %s", Conf_ListenAddress, strerror(errno));
411 listen_addr = strtok(copy, ",");
413 while (listen_addr) {
414 ngt_TrimStr(listen_addr);
416 created += ports_initlisteners(&Conf_ListenPorts, listen_addr, cb_listen);
418 created += ports_initlisteners(&Conf_SSLOptions.ListenPorts, listen_addr, cb_listen_ssl);
422 listen_addr = strtok(NULL, ",");
426 * can't free() Conf_ListenAddress here. On /REHASH, if the config file
427 * cannot be re-loaded, we'd end up with a NULL Conf_ListenAddress.
428 * Instead, free() takes place in conf.c, before the config file
433 } /* Conn_InitListeners */
437 Conn_ExitListeners( void )
439 /* Close down all listening sockets */
443 Rendezvous_UnregisterListeners( );
446 arraylen = array_length(&My_Listeners, sizeof (int));
448 "Shutting down all listening sockets (%d total) ...", arraylen);
449 fd = array_start(&My_Listeners);
454 LogDebug("Listening socket %d closed.", *fd );
457 array_free(&My_Listeners);
458 } /* Conn_ExitListeners */
462 InitSinaddrListenAddr(ng_ipaddr_t *addr, const char *listen_addrstr, UINT16 Port)
466 ret = ng_ipaddr_init(addr, listen_addrstr, Port);
468 assert(listen_addrstr);
469 Log(LOG_CRIT, "Can't bind to [%s]:%u: can't convert ip address \"%s\"",
470 listen_addrstr, Port, listen_addrstr);
477 set_v6_only(int af, int sock)
479 #if defined(IPV6_V6ONLY) && defined(WANT_IPV6)
485 if (setsockopt(sock, IPPROTO_IPV6, IPV6_V6ONLY, &on, sizeof(on)))
486 Log(LOG_ERR, "Could not set IPV6_V6ONLY: %s", strerror(errno));
494 /* return new listening port file descriptor or -1 on failure */
496 NewListener(const char *listen_addr, UINT16 Port)
498 /* Create new listening socket on specified port */
502 char name[CLIENT_ID_LEN], *info;
504 if (!InitSinaddrListenAddr(&addr, listen_addr, Port))
507 af = ng_ipaddr_af(&addr);
508 sock = socket(af, SOCK_STREAM, 0);
510 Log(LOG_CRIT, "Can't create socket (af %d) : %s!", af, strerror(errno));
514 set_v6_only(af, sock);
516 if (!Init_Socket(sock))
519 if (bind(sock, (struct sockaddr *)&addr, ng_ipaddr_salen(&addr)) != 0) {
520 Log(LOG_CRIT, "Can't bind socket to address %s:%d - %s",
521 ng_ipaddr_tostr(&addr), Port, strerror(errno));
526 if( listen( sock, 10 ) != 0 ) {
527 Log( LOG_CRIT, "Can't listen on socket: %s!", strerror( errno ));
532 /* keep fd in list so we can close it when ngircd restarts/shuts down */
533 if (!array_catb( &My_Listeners,(char*) &sock, sizeof(int) )) {
534 Log( LOG_CRIT, "Can't add socket to My_Listeners array: %s!", strerror( errno ));
539 Log(LOG_INFO, "Now listening on [%s]:%d (socket %d).", ng_ipaddr_tostr(&addr), Port, sock);
542 /* Get best server description text */
543 if( ! Conf_ServerInfo[0] ) info = Conf_ServerName;
546 /* Use server info string */
548 if( Conf_ServerInfo[0] == '[' )
550 /* Cut off leading hostname part in "[]" */
551 info = strchr( Conf_ServerInfo, ']' );
555 while( *info == ' ' ) info++;
558 if( ! info ) info = Conf_ServerInfo;
561 /* Add port number to description if non-standard */
563 snprintf(name, sizeof name, "%s (port %u)", info,
566 strlcpy(name, info, sizeof name);
568 /* Register service */
569 Rendezvous_Register( name, MDNS_TYPE, Port );
576 * SSL/TLS connections require extra treatment:
577 * When either CONN_SSL_WANT_WRITE or CONN_SSL_WANT_READ is set, we
578 * need to take care of that first, before checking read/write buffers.
579 * For instance, while we might have data in our write buffer, the
580 * TLS/SSL protocol might need to read internal data first for TLS/SSL
583 * If this function returns true, such a condition is met and we have
584 * to reverse the condition (check for read even if we've data to write,
585 * do not check for read but writeability even if write-buffer is empty).
588 SSL_WantRead(const CONNECTION *c)
590 if (Conn_OPTION_ISSET(c, CONN_SSL_WANT_READ)) {
591 io_event_add(c->sock, IO_WANTREAD);
597 SSL_WantWrite(const CONNECTION *c)
599 if (Conn_OPTION_ISSET(c, CONN_SSL_WANT_WRITE)) {
600 io_event_add(c->sock, IO_WANTWRITE);
607 SSL_WantRead(UNUSED const CONNECTION *c) { return false; }
609 SSL_WantWrite(UNUSED const CONNECTION *c) { return false; }
614 * "Main Loop": Loop until shutdown or restart is signalled.
615 * This function loops until a shutdown or restart of ngIRCd is signalled and
616 * calls io_dispatch() to check for readable and writable sockets every second.
617 * It checks for status changes on pending connections (e. g. when a hostname
618 * has been resolved), checks for "penalties" and timeouts, and handles the
625 unsigned int wdatalen;
629 while (!NGIRCd_SignalQuit && !NGIRCd_SignalRestart) {
633 Rendezvous_Handler();
636 /* Should the configuration be reloaded? */
637 if (NGIRCd_SignalRehash)
640 /* Check configured servers and established links */
644 /* Look for non-empty read buffers ... */
645 for (i = 0; i < Pool_Size; i++) {
646 if ((My_Connections[i].sock > NONE)
647 && (array_bytes(&My_Connections[i].rbuf) > 0)
648 && (My_Connections[i].delaytime < t)) {
649 /* ... and try to handle the received data */
654 /* Look for non-empty write buffers ... */
655 for (i = 0; i < Pool_Size; i++) {
656 if (My_Connections[i].sock <= NONE)
659 wdatalen = (unsigned int)array_bytes(&My_Connections[i].wbuf);
662 array_bytes(&My_Connections[i].zip.wbuf) > 0)
667 if (SSL_WantRead(&My_Connections[i]))
669 io_event_add(My_Connections[i].sock,
674 /* Check from which sockets we possibly could read ... */
675 for (i = 0; i < Pool_Size; i++) {
676 if (My_Connections[i].sock <= NONE)
679 if (SSL_WantWrite(&My_Connections[i]))
680 continue; /* TLS/SSL layer needs to write data; deal with this first */
682 if (Resolve_INPROGRESS(&My_Connections[i].res_stat)) {
683 /* Wait for completion of resolver sub-process ... */
684 io_event_del(My_Connections[i].sock,
689 if (Conn_OPTION_ISSET(&My_Connections[i], CONN_ISCONNECTING))
690 /* Wait for completion of connect() ... */
693 if (My_Connections[i].delaytime > t) {
694 /* There is a "penalty time" set: ignore socket! */
695 io_event_del(My_Connections[i].sock,
699 io_event_add(My_Connections[i].sock, IO_WANTREAD);
702 /* Set the timeout for reading from the network to 1 second,
703 * which is the granularity with witch we handle "penalty
704 * times" for example.
705 * Note: tv_sec/usec are undefined(!) after io_dispatch()
706 * returns, so we have to set it beforce each call to it! */
710 /* Wait for activity ... */
711 i = io_dispatch(&tv);
712 if (i == -1 && errno != EINTR) {
713 Log(LOG_EMERG, "Conn_Handler(): io_dispatch(): %s!",
715 Log(LOG_ALERT, "%s exiting due to fatal errors!",
721 if (NGIRCd_SignalQuit)
722 Log(LOG_NOTICE | LOG_snotice, "Server going down NOW!");
723 else if (NGIRCd_SignalRestart)
724 Log(LOG_NOTICE | LOG_snotice, "Server restarting NOW!");
729 * Write a text string into the socket of a connection.
730 * This function automatically appends CR+LF to the string and validates that
731 * the result is a valid IRC message (oversized messages are shortened, for
732 * example). Then it calls the Conn_Write() function to do the actual sending.
733 * @param Idx Index fo the connection.
734 * @param Format Format string, see printf().
735 * @return true on success, false otherwise.
739 Conn_WriteStr( CONN_ID Idx, char *Format, ... )
742 Conn_WriteStr( Idx, Format, va_alist )
748 char buffer[COMMAND_LEN];
753 assert( Idx > NONE );
754 assert( Format != NULL );
757 va_start( ap, Format );
761 if (vsnprintf( buffer, COMMAND_LEN - 2, Format, ap ) >= COMMAND_LEN - 2 ) {
763 * The string that should be written to the socket is longer
764 * than the allowed size of COMMAND_LEN bytes (including both
765 * the CR and LF characters). This can be caused by the
766 * IRC_WriteXXX() functions when the prefix of this server had
767 * to be added to an already "quite long" command line which
768 * has been received from a regular IRC client, for example.
770 * We are not allowed to send such "oversized" messages to
771 * other servers and clients, see RFC 2812 2.3 and 2813 3.3
772 * ("these messages SHALL NOT exceed 512 characters in length,
773 * counting all characters including the trailing CR-LF").
775 * So we have a big problem here: we should send more bytes
776 * to the network than we are allowed to and we don't know
777 * the originator (any more). The "old" behaviour of blaming
778 * the receiver ("next hop") is a bad idea (it could be just
779 * an other server only routing the message!), so the only
780 * option left is to shorten the string and to hope that the
781 * result is still somewhat useful ...
785 strcpy (buffer + sizeof(buffer) - strlen(CUT_TXTSUFFIX) - 2 - 1,
791 Log(LOG_DEBUG, " -> connection %d: '%s'.", Idx, buffer);
794 len = strlcat( buffer, "\r\n", sizeof( buffer ));
795 ok = Conn_Write(Idx, buffer, len);
796 My_Connections[Idx].msg_out++;
800 } /* Conn_WriteStr */
804 * Append Data to the outbound write buffer of a connection.
805 * @param Idx Index of the connection.
806 * @param Data pointer to the data.
807 * @param Len length of Data.
808 * @return true on success, false otherwise.
811 Conn_Write( CONN_ID Idx, char *Data, size_t Len )
814 size_t writebuf_limit = WRITEBUFFER_LEN;
815 assert( Idx > NONE );
816 assert( Data != NULL );
819 c = Conn_GetClient(Idx);
822 /* Servers do get special write buffer limits, so they can generate
823 * all the messages that are required while peering. */
824 if (Client_Type(c) == CLIENT_SERVER)
825 writebuf_limit = WRITEBUFFER_SLINK_LEN;
827 /* Is the socket still open? A previous call to Conn_Write()
828 * may have closed the connection due to a fatal error.
829 * In this case it is sufficient to return an error, as well. */
830 if( My_Connections[Idx].sock <= NONE ) {
831 LogDebug("Skipped write on closed socket (connection %d).", Idx);
836 if ( Conn_OPTION_ISSET( &My_Connections[Idx], CONN_ZIP )) {
838 * Zip_Buffer() does all the dirty work for us: it flushes
839 * the (pre-)compression buffers if required and handles
840 * all error conditions. */
841 if (!Zip_Buffer(Idx, Data, Len))
847 /* Uncompressed link:
848 * Check if outbound buffer has enough space for the data. */
849 if (array_bytes(&My_Connections[Idx].wbuf) + Len >=
851 /* Buffer is full, flush it. Handle_Write deals with
852 * low-level errors, if any. */
853 if (!Handle_Write(Idx))
857 /* When the write buffer is still too big after flushing it,
858 * the connection will be killed. */
859 if (array_bytes(&My_Connections[Idx].wbuf) + Len >=
862 "Write buffer overflow (connection %d, size %lu byte)!",
864 (unsigned long)array_bytes(&My_Connections[Idx].wbuf));
865 Conn_Close(Idx, "Write buffer overflow!", NULL, false);
869 /* Copy data to write buffer */
870 if (!array_catb(&My_Connections[Idx].wbuf, Data, Len))
873 My_Connections[Idx].bytes_out += Len;
876 /* Adjust global write counter */
884 Conn_Close( CONN_ID Idx, const char *LogMsg, const char *FwdMsg, bool InformClient )
886 /* Close connection. Open pipes of asyncronous resolver
887 * sub-processes are closed down. */
894 double in_z_k, out_z_k;
898 assert( Idx > NONE );
900 /* Is this link already shutting down? */
901 if( Conn_OPTION_ISSET( &My_Connections[Idx], CONN_ISCLOSING )) {
902 /* Conn_Close() has been called recursively for this link;
903 * probabe reason: Handle_Write() failed -- see below. */
904 LogDebug("Recursive request to close connection: %d", Idx );
908 assert( My_Connections[Idx].sock > NONE );
910 /* Mark link as "closing" */
911 Conn_OPTION_ADD( &My_Connections[Idx], CONN_ISCLOSING );
918 txt = "Reason unknown";
920 port = ng_ipaddr_getport(&My_Connections[Idx].addr);
921 Log(LOG_INFO, "Shutting down connection %d (%s) with %s:%d ...", Idx,
922 LogMsg ? LogMsg : FwdMsg, My_Connections[Idx].host, port);
924 /* Search client, if any */
925 c = Conn_GetClient( Idx );
927 /* Should the client be informed? */
930 /* Send statistics to client if registered as user: */
931 if ((c != NULL) && (Client_Type(c) == CLIENT_USER)) {
933 ":%s NOTICE %s :%sConnection statistics: client %.1f kb, server %.1f kb.",
934 Client_ID(Client_ThisServer()), Client_ID(c),
936 (double)My_Connections[Idx].bytes_in / 1024,
937 (double)My_Connections[Idx].bytes_out / 1024);
940 /* Send ERROR to client (see RFC!) */
942 Conn_WriteStr(Idx, "ERROR :%s", FwdMsg);
944 Conn_WriteStr(Idx, "ERROR :Closing connection.");
947 /* Try to write out the write buffer. Note: Handle_Write() eventually
948 * removes the CLIENT structure associated with this connection if an
949 * error occurs! So we have to re-check if there is still an valid
950 * CLIENT structure after calling Handle_Write() ...*/
951 (void)Handle_Write( Idx );
953 /* Search client, if any (re-check!) */
954 c = Conn_GetClient( Idx );
956 if ( Conn_OPTION_ISSET( &My_Connections[Idx], CONN_SSL )) {
957 Log(LOG_INFO, "SSL connection %d shutting down ...", Idx);
958 ConnSSL_Free(&My_Connections[Idx]);
961 /* Shut down socket */
962 if (! io_close(My_Connections[Idx].sock)) {
963 /* Oops, we can't close the socket!? This is ... ugly! */
965 "Error closing connection %d (socket %d) with %s:%d - %s! (ignored)",
966 Idx, My_Connections[Idx].sock, My_Connections[Idx].host,
967 port, strerror(errno));
970 /* Mark socket as invalid: */
971 My_Connections[Idx].sock = NONE;
973 /* If there is still a client, unregister it now */
975 Client_Destroy(c, LogMsg, FwdMsg, true);
977 /* Calculate statistics and log information */
978 in_k = (double)My_Connections[Idx].bytes_in / 1024;
979 out_k = (double)My_Connections[Idx].bytes_out / 1024;
981 if (Conn_OPTION_ISSET( &My_Connections[Idx], CONN_ZIP)) {
982 in_z_k = (double)My_Connections[Idx].zip.bytes_in / 1024;
983 out_z_k = (double)My_Connections[Idx].zip.bytes_out / 1024;
984 /* Make sure that no division by zero can occur during
985 * the calculation of in_p and out_p: in_z_k and out_z_k
986 * are non-zero, that's guaranteed by the protocol until
987 * compression can be enabled. */
992 in_p = (int)(( in_k * 100 ) / in_z_k );
993 out_p = (int)(( out_k * 100 ) / out_z_k );
995 "Connection %d with %s:%d closed (in: %.1fk/%.1fk/%d%%, out: %.1fk/%.1fk/%d%%).",
996 Idx, My_Connections[Idx].host, port,
997 in_k, in_z_k, in_p, out_k, out_z_k, out_p);
1003 "Connection %d with %s:%d closed (in: %.1fk, out: %.1fk).",
1004 Idx, My_Connections[Idx].host, port,
1008 /* cancel running resolver */
1009 if (Resolve_INPROGRESS(&My_Connections[Idx].res_stat))
1010 Resolve_Shutdown(&My_Connections[Idx].res_stat);
1012 /* Servers: Modify time of next connect attempt? */
1013 Conf_UnsetServer( Idx );
1016 /* Clean up zlib, if link was compressed */
1017 if ( Conn_OPTION_ISSET( &My_Connections[Idx], CONN_ZIP )) {
1018 inflateEnd( &My_Connections[Idx].zip.in );
1019 deflateEnd( &My_Connections[Idx].zip.out );
1020 array_free(&My_Connections[Idx].zip.rbuf);
1021 array_free(&My_Connections[Idx].zip.wbuf);
1025 array_free(&My_Connections[Idx].rbuf);
1026 array_free(&My_Connections[Idx].wbuf);
1028 /* Clean up connection structure (=free it) */
1029 Init_Conn_Struct( Idx );
1031 assert(NumConnections > 0);
1034 LogDebug("Shutdown of connection %d completed, %ld connection%s left.",
1035 Idx, NumConnections, NumConnections != 1 ? "s" : "");
1040 Conn_SyncServerStruct( void )
1042 /* Synchronize server structures (connection IDs):
1043 * connections <-> configuration */
1049 for( i = 0; i < Pool_Size; i++ ) {
1050 /* Established connection? */
1051 if (My_Connections[i].sock < 0)
1054 /* Server connection? */
1055 client = Conn_GetClient( i );
1056 if(( ! client ) || ( Client_Type( client ) != CLIENT_SERVER )) continue;
1058 for( c = 0; c < MAX_SERVERS; c++ )
1060 /* Configured server? */
1061 if( ! Conf_Server[c].host[0] ) continue;
1064 if( strcmp( Conf_Server[c].name, Client_ID( client )) == 0 )
1065 Conf_Server[c].conn_id = i;
1068 } /* SyncServerStruct */
1072 * Send out data of write buffer; connect new sockets.
1075 Handle_Write( CONN_ID Idx )
1080 assert( Idx > NONE );
1081 if ( My_Connections[Idx].sock < 0 ) {
1082 LogDebug("Handle_Write() on closed socket, connection %d", Idx);
1085 assert( My_Connections[Idx].sock > NONE );
1087 wdatalen = array_bytes(&My_Connections[Idx].wbuf );
1090 if (wdatalen == 0) {
1091 /* Write buffer is empty, so we try to flush the compression
1092 * buffer and get some data to work with from there :-) */
1093 if (!Zip_Flush(Idx))
1096 /* Now the write buffer most probably has changed: */
1097 wdatalen = array_bytes(&My_Connections[Idx].wbuf);
1101 if (wdatalen == 0) {
1102 /* Still no data, fine. */
1103 io_event_del(My_Connections[Idx].sock, IO_WANTWRITE );
1108 ("Handle_Write() called for connection %d, %ld bytes pending ...",
1112 if ( Conn_OPTION_ISSET( &My_Connections[Idx], CONN_SSL )) {
1113 len = ConnSSL_Write(&My_Connections[Idx], array_start(&My_Connections[Idx].wbuf), wdatalen);
1117 len = write(My_Connections[Idx].sock,
1118 array_start(&My_Connections[Idx].wbuf), wdatalen );
1121 if (errno == EAGAIN || errno == EINTR)
1124 Log(LOG_ERR, "Write error on connection %d (socket %d): %s!",
1125 Idx, My_Connections[Idx].sock, strerror(errno));
1126 Conn_Close(Idx, "Write error!", NULL, false);
1130 /* move any data not yet written to beginning */
1131 array_moveleft(&My_Connections[Idx].wbuf, 1, (size_t)len);
1134 } /* Handle_Write */
1138 Count_Connections(ng_ipaddr_t *a)
1143 for (i = 0; i < Pool_Size; i++) {
1144 if (My_Connections[i].sock <= NONE)
1146 if (ng_ipaddr_ipequal(&My_Connections[i].addr, a))
1150 } /* Count_Connections */
1154 New_Connection( int Sock )
1156 /* Neue Client-Verbindung von Listen-Socket annehmen und
1157 * CLIENT-Struktur anlegen. */
1160 struct request_info req;
1162 ng_ipaddr_t new_addr;
1163 char ip_str[NG_INET_ADDRSTRLEN];
1164 int new_sock, new_sock_len, identsock;
1168 assert( Sock > NONE );
1169 /* Connection auf Listen-Socket annehmen */
1170 new_sock_len = (int)sizeof(new_addr);
1172 new_sock = accept(Sock, (struct sockaddr *)&new_addr,
1173 (socklen_t *)&new_sock_len);
1175 Log(LOG_CRIT, "Can't accept connection: %s!", strerror(errno));
1179 if (!ng_ipaddr_tostr_r(&new_addr, ip_str)) {
1180 Log(LOG_CRIT, "fd %d: Can't convert IP address!", new_sock);
1181 Simple_Message(new_sock, "ERROR :Internal Server Error");
1187 /* Validate socket using TCP Wrappers */
1188 request_init( &req, RQ_DAEMON, PACKAGE_NAME, RQ_FILE, new_sock, RQ_CLIENT_SIN, &new_addr, NULL );
1190 if (!hosts_access(&req)) {
1191 Log (deny_severity, "Refused connection from %s (by TCP Wrappers)!", ip_str);
1192 Simple_Message( new_sock, "ERROR :Connection refused" );
1198 /* Socket initialisieren */
1199 if (!Init_Socket( new_sock ))
1202 /* Check IP-based connection limit */
1203 cnt = Count_Connections(&new_addr);
1204 if ((Conf_MaxConnectionsIP > 0) && (cnt >= Conf_MaxConnectionsIP)) {
1205 /* Access denied, too many connections from this IP address! */
1206 Log( LOG_ERR, "Refused connection from %s: too may connections (%ld) from this IP address!", ip_str, cnt);
1207 Simple_Message( new_sock, "ERROR :Connection refused, too many connections from your IP address!" );
1212 if ((Conf_MaxConnections > 0) &&
1213 (NumConnections >= (size_t) Conf_MaxConnections))
1215 Log( LOG_ALERT, "Can't accept connection: limit (%d) reached!", Conf_MaxConnections);
1216 Simple_Message( new_sock, "ERROR :Connection limit reached" );
1221 if( new_sock >= Pool_Size ) {
1222 if (!array_alloc(&My_ConnArray, sizeof(CONNECTION),
1223 (size_t)new_sock)) {
1224 Log( LOG_EMERG, "Can't allocate memory! [New_Connection]" );
1225 Simple_Message( new_sock, "ERROR: Internal error" );
1229 LogDebug("Bumped connection pool to %ld items (internal: %ld items, %ld bytes)",
1230 new_sock, array_length(&My_ConnArray, sizeof(CONNECTION)), array_bytes(&My_ConnArray));
1232 /* Adjust pointer to new block */
1233 My_Connections = array_start(&My_ConnArray);
1234 while (Pool_Size <= new_sock)
1235 Init_Conn_Struct(Pool_Size++);
1238 /* register callback */
1239 if (!io_event_create( new_sock, IO_WANTREAD, cb_clientserver)) {
1240 Log(LOG_ALERT, "Can't accept connection: io_event_create failed!");
1241 Simple_Message(new_sock, "ERROR :Internal error");
1246 c = Client_NewLocal(new_sock, ip_str, CLIENT_UNKNOWN, false );
1248 Log(LOG_ALERT, "Can't accept connection: can't create client structure!");
1249 Simple_Message(new_sock, "ERROR :Internal error");
1254 Init_Conn_Struct( new_sock );
1255 My_Connections[new_sock].sock = new_sock;
1256 My_Connections[new_sock].addr = new_addr;
1257 My_Connections[new_sock].client = c;
1259 /* Set initial hostname to IP address. This becomes overwritten when
1260 * the DNS lookup is enabled and succeeds, but is used otherwise. */
1261 if (ng_ipaddr_af(&new_addr) != AF_INET)
1262 snprintf(My_Connections[new_sock].host,
1263 sizeof(My_Connections[new_sock].host), "[%s]", ip_str);
1265 strlcpy(My_Connections[new_sock].host, ip_str,
1266 sizeof(My_Connections[new_sock].host));
1268 Client_SetHostname(c, My_Connections[new_sock].host);
1270 Log(LOG_INFO, "Accepted connection %d from %s:%d on socket %d.",
1271 new_sock, My_Connections[new_sock].host,
1272 ng_ipaddr_getport(&new_addr), Sock);
1274 identsock = new_sock;
1280 Resolve_Addr(&My_Connections[new_sock].res_stat, &new_addr,
1281 identsock, cb_Read_Resolver_Result);
1282 Conn_SetPenalty(new_sock, 4);
1284 } /* New_Connection */
1288 Socket2Index( int Sock )
1290 assert( Sock >= 0 );
1292 if( Sock >= Pool_Size || My_Connections[Sock].sock != Sock ) {
1293 /* the Connection was already closed again, likely due to
1295 LogDebug("Socket2Index: can't get connection for socket %d!", Sock);
1299 } /* Socket2Index */
1303 * Read data from the network to the read buffer. If an error occures,
1304 * the socket of this connection will be shut down.
1307 Read_Request( CONN_ID Idx )
1310 char readbuf[READBUFFER_LEN];
1312 assert( Idx > NONE );
1313 assert( My_Connections[Idx].sock > NONE );
1316 if ((array_bytes(&My_Connections[Idx].rbuf) >= READBUFFER_LEN) ||
1317 (array_bytes(&My_Connections[Idx].zip.rbuf) >= READBUFFER_LEN))
1319 if (array_bytes(&My_Connections[Idx].rbuf) >= READBUFFER_LEN)
1322 /* Read buffer is full */
1324 "Receive buffer overflow (connection %d): %d bytes!",
1325 Idx, array_bytes(&My_Connections[Idx].rbuf));
1326 Conn_Close( Idx, "Receive buffer overflow!", NULL, false );
1331 if (Conn_OPTION_ISSET(&My_Connections[Idx], CONN_SSL))
1332 len = ConnSSL_Read( &My_Connections[Idx], readbuf, sizeof(readbuf));
1335 len = read(My_Connections[Idx].sock, readbuf, sizeof(readbuf));
1337 Log(LOG_INFO, "%s:%u (%s) is closing the connection ...",
1338 My_Connections[Idx].host,
1339 (unsigned int) ng_ipaddr_getport(&My_Connections[Idx].addr),
1340 ng_ipaddr_tostr(&My_Connections[Idx].addr));
1342 "Socket closed!", "Client closed connection",
1348 if( errno == EAGAIN ) return;
1349 Log(LOG_ERR, "Read error on connection %d (socket %d): %s!",
1350 Idx, My_Connections[Idx].sock, strerror(errno));
1351 Conn_Close(Idx, "Read error!", "Client closed connection",
1356 if (Conn_OPTION_ISSET(&My_Connections[Idx], CONN_ZIP)) {
1357 if (!array_catb(&My_Connections[Idx].zip.rbuf, readbuf,
1360 "Could not append recieved data to zip input buffer (connn %d): %d bytes!",
1362 Conn_Close(Idx, "Receive buffer overflow!", NULL,
1369 if (!array_catb( &My_Connections[Idx].rbuf, readbuf, len)) {
1370 Log( LOG_ERR, "Could not append recieved data to input buffer (connn %d): %d bytes!", Idx, len );
1371 Conn_Close( Idx, "Receive buffer overflow!", NULL, false );
1375 /* Update connection statistics */
1376 My_Connections[Idx].bytes_in += len;
1378 /* Update timestamp of last data received if this connection is
1379 * registered as a user, server or service connection. Don't update
1380 * otherwise, so users have at least Conf_PongTimeout seconds time to
1381 * register with the IRC server -- see Check_Connections().
1382 * Set "lastping", too, so we can handle time shifts backwards ... */
1383 c = Conn_GetClient(Idx);
1384 if (c && (Client_Type(c) == CLIENT_USER
1385 || Client_Type(c) == CLIENT_SERVER
1386 || Client_Type(c) == CLIENT_SERVICE)) {
1387 My_Connections[Idx].lastdata = time(NULL);
1388 My_Connections[Idx].lastping = My_Connections[Idx].lastdata;
1391 /* Look at the data in the (read-) buffer of this connection */
1393 } /* Read_Request */
1397 * Handle all data in the connection read-buffer.
1398 * All data is precessed until no complete command is left. When a fatal
1399 * error occurs, the connection is shut down.
1402 Handle_Buffer(CONN_ID Idx)
1405 char *ptr1, *ptr2, *first_eol;
1414 starttime = time(NULL);
1417 if (My_Connections[Idx].delaytime > starttime)
1420 /* Unpack compressed data, if compression is in use */
1421 if (Conn_OPTION_ISSET(&My_Connections[Idx], CONN_ZIP)) {
1422 /* When unzipping fails, Unzip_Buffer() shuts
1423 * down the connection itself */
1424 if (!Unzip_Buffer(Idx))
1429 if (0 == array_bytes(&My_Connections[Idx].rbuf))
1432 /* Make sure that the buffer is NULL terminated */
1433 if (!array_cat0_temporary(&My_Connections[Idx].rbuf)) {
1434 Conn_Close(Idx, NULL,
1435 "Can't allocate memory [Handle_Buffer]",
1440 /* RFC 2812, section "2.3 Messages", 5th paragraph:
1441 * "IRC messages are always lines of characters terminated
1442 * with a CR-LF (Carriage Return - Line Feed) pair [...]". */
1444 ptr = strstr(array_start(&My_Connections[Idx].rbuf), "\r\n");
1447 /* Check for non-RFC-compliant request (only CR or LF)?
1448 * Unfortunately, there are quite a few clients out there
1449 * that do this -- e. g. mIRC, BitchX, and Trillian :-( */
1450 ptr1 = strchr(array_start(&My_Connections[Idx].rbuf), '\r');
1451 ptr2 = strchr(array_start(&My_Connections[Idx].rbuf), '\n');
1453 /* Check if there is a single CR or LF _before_ the
1454 * corerct CR+LF line terminator: */
1455 first_eol = ptr1 < ptr2 ? ptr1 : ptr2;
1456 if (first_eol < ptr) {
1457 /* Single CR or LF before CR+LF found */
1461 } else if (ptr1 || ptr2) {
1462 /* No CR+LF terminated command found, but single
1463 * CR or LF found ... */
1465 ptr = ptr1 < ptr2 ? ptr1 : ptr2;
1467 ptr = ptr1 ? ptr1 : ptr2;
1475 /* Complete (=line terminated) request found, handle it! */
1478 len = ptr - (char *)array_start(&My_Connections[Idx].rbuf) + delta;
1480 if (len > (COMMAND_LEN - 1)) {
1481 /* Request must not exceed 512 chars (incl. CR+LF!),
1482 * see RFC 2812. Disconnect Client if this happens. */
1484 "Request too long (connection %d): %d bytes (max. %d expected)!",
1485 Idx, array_bytes(&My_Connections[Idx].rbuf),
1487 Conn_Close(Idx, NULL, "Request too long", true);
1492 /* Request is empty (only '\r\n', '\r' or '\n');
1493 * delta is 2 ('\r\n') or 1 ('\r' or '\n'), see above */
1494 array_moveleft(&My_Connections[Idx].rbuf, 1, len);
1499 /* remember if stream is already compressed */
1500 old_z = My_Connections[Idx].options & CONN_ZIP;
1503 My_Connections[Idx].msg_in++;
1505 (Idx, (char *)array_start(&My_Connections[Idx].rbuf)))
1508 array_moveleft(&My_Connections[Idx].rbuf, 1, len);
1509 LogDebug("Connection %d: %d bytes left in read buffer.",
1510 Idx, array_bytes(&My_Connections[Idx].rbuf));
1512 if ((!old_z) && (My_Connections[Idx].options & CONN_ZIP) &&
1513 (array_bytes(&My_Connections[Idx].rbuf) > 0)) {
1514 /* The last command activated socket compression.
1515 * Data that was read after that needs to be copied
1516 * to the unzip buffer for decompression: */
1518 (&My_Connections[Idx].zip.rbuf,
1519 &My_Connections[Idx].rbuf)) {
1520 Conn_Close(Idx, NULL,
1521 "Can't allocate memory [Handle_Buffer]",
1526 array_trunc(&My_Connections[Idx].rbuf);
1528 ("Moved already received data (%u bytes) to uncompression buffer.",
1529 array_bytes(&My_Connections[Idx].zip.rbuf));
1533 } /* Handle_Buffer */
1537 Check_Connections(void)
1539 /* check if connections are alive. if not, play PING-PONG first.
1540 * 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 snprintf(msg, sizeof(msg), "Ping timeout: %d seconds", Conf_PongTimeout);
1564 Conn_Close(i, NULL, msg, true);
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 /* Conn_Close() decrements this counter again */
1701 Client_SetIntroducer( c, c );
1702 Client_SetToken( c, TOKEN_OUTBOUND );
1704 /* Register connection */
1705 Conf_Server[Server].conn_id = new_sock;
1706 My_Connections[new_sock].sock = new_sock;
1707 My_Connections[new_sock].addr = *dest;
1708 My_Connections[new_sock].client = c;
1709 strlcpy( My_Connections[new_sock].host, Conf_Server[Server].host,
1710 sizeof(My_Connections[new_sock].host ));
1712 /* Register new socket */
1713 if (!io_event_create( new_sock, IO_WANTWRITE, cb_connserver)) {
1714 Log( LOG_ALERT, "io_event_create(): could not add fd %d", strerror(errno));
1715 Conn_Close( new_sock, "io_event_create() failed", NULL, false );
1716 Init_Conn_Struct( new_sock );
1717 Conf_Server[Server].conn_id = NONE;
1720 if (Conf_Server[Server].SSLConnect && !ConnSSL_PrepareConnect( &My_Connections[new_sock],
1721 &Conf_Server[Server] ))
1723 Log(LOG_ALERT, "Could not initialize SSL for outgoing connection");
1724 Conn_Close( new_sock, "Could not initialize SSL for outgoing connection", NULL, false );
1725 Init_Conn_Struct( new_sock );
1726 Conf_Server[Server].conn_id = NONE;
1730 LogDebug("Registered new connection %d on socket %d (%ld in total).",
1731 new_sock, My_Connections[new_sock].sock, NumConnections);
1732 Conn_OPTION_ADD( &My_Connections[new_sock], CONN_ISCONNECTING );
1737 * Initialize connection structure.
1740 Init_Conn_Struct(CONN_ID Idx)
1742 time_t now = time(NULL);
1744 memset(&My_Connections[Idx], 0, sizeof(CONNECTION));
1745 My_Connections[Idx].sock = -1;
1746 My_Connections[Idx].signon = now;
1747 My_Connections[Idx].lastdata = now;
1748 My_Connections[Idx].lastprivmsg = now;
1749 Resolve_Init(&My_Connections[Idx].res_stat);
1750 } /* Init_Conn_Struct */
1754 Init_Socket( int Sock )
1756 /* Initialize socket (set options) */
1760 if (!io_setnonblock(Sock)) {
1761 Log( LOG_CRIT, "Can't enable non-blocking mode for socket: %s!", strerror( errno ));
1766 /* Don't block this port after socket shutdown */
1768 if( setsockopt( Sock, SOL_SOCKET, SO_REUSEADDR, &value, (socklen_t)sizeof( value )) != 0 )
1770 Log( LOG_ERR, "Can't set socket option SO_REUSEADDR: %s!", strerror( errno ));
1771 /* ignore this error */
1774 /* Set type of service (TOS) */
1775 #if defined(IP_TOS) && defined(IPTOS_LOWDELAY)
1776 value = IPTOS_LOWDELAY;
1777 LogDebug("Setting option IP_TOS on socket %d to IPTOS_LOWDELAY (%d).", Sock, value );
1778 if( setsockopt( Sock, SOL_IP, IP_TOS, &value, (socklen_t)sizeof( value )) != 0 )
1780 Log( LOG_ERR, "Can't set socket option IP_TOS: %s!", strerror( errno ));
1781 /* ignore this error */
1791 cb_Connect_to_Server(int fd, UNUSED short events)
1793 /* Read result of resolver sub-process from pipe and start connection */
1796 ng_ipaddr_t dest_addrs[4]; /* we can handle at most 3; but we read up to
1797 four so we can log the 'more than we can handle'
1800 LogDebug("Resolver: Got forward lookup callback on fd %d, events %d", fd, events);
1802 for (i=0; i < MAX_SERVERS; i++) {
1803 if (Resolve_Getfd(&Conf_Server[i].res_stat) == fd )
1807 if( i >= MAX_SERVERS) {
1808 /* Ops, no matching server found?! */
1810 LogDebug("Resolver: Got Forward Lookup callback for unknown server!?");
1814 /* Read result from pipe */
1815 len = Resolve_Read(&Conf_Server[i].res_stat, dest_addrs, sizeof(dest_addrs));
1819 assert((len % sizeof(ng_ipaddr_t)) == 0);
1821 LogDebug("Got result from resolver: %u structs (%u bytes).", len/sizeof(ng_ipaddr_t), len);
1823 memset(&Conf_Server[i].dst_addr, 0, sizeof(&Conf_Server[i].dst_addr));
1824 if (len > sizeof(ng_ipaddr_t)) {
1825 /* more than one address for this hostname, remember them
1826 * in case first address is unreachable/not available */
1827 len -= sizeof(ng_ipaddr_t);
1828 if (len > sizeof(&Conf_Server[i].dst_addr)) {
1829 len = sizeof(&Conf_Server[i].dst_addr);
1831 "Notice: Resolver returned more IP Addresses for host than we can handle, additional addresses dropped.");
1833 memcpy(&Conf_Server[i].dst_addr, &dest_addrs[1], len);
1836 New_Server(i, dest_addrs);
1837 } /* cb_Read_Forward_Lookup */
1841 cb_Read_Resolver_Result( int r_fd, UNUSED short events )
1843 /* Read result of resolver sub-process from pipe and update the
1844 * apropriate connection/client structure(s): hostname and/or
1845 * IDENT user name.*/
1852 char readbuf[HOST_LEN + 2 + CLIENT_USER_LEN];
1854 char readbuf[HOST_LEN + 1];
1857 LogDebug("Resolver: Got callback on fd %d, events %d", r_fd, events );
1859 /* Search associated connection ... */
1860 for( i = 0; i < Pool_Size; i++ ) {
1861 if(( My_Connections[i].sock != NONE )
1862 && ( Resolve_Getfd(&My_Connections[i].res_stat) == r_fd ))
1865 if( i >= Pool_Size ) {
1866 /* Ops, none found? Probably the connection has already
1867 * been closed!? We'll ignore that ... */
1869 LogDebug("Resolver: Got callback for unknown connection!?");
1873 /* Read result from pipe */
1874 len = Resolve_Read(&My_Connections[i].res_stat, readbuf, sizeof readbuf -1);
1878 readbuf[len] = '\0';
1879 identptr = strchr(readbuf, '\n');
1880 assert(identptr != NULL);
1882 Log( LOG_CRIT, "Resolver: Got malformed result!");
1887 LogDebug("Got result from resolver: \"%s\" (%u bytes read).", readbuf, len);
1888 /* Okay, we got a complete result: this is a host name for outgoing
1889 * connections and a host name and IDENT user name (if enabled) for
1890 * incoming connections.*/
1891 assert ( My_Connections[i].sock >= 0 );
1892 /* Incoming connection. Search client ... */
1893 c = Conn_GetClient( i );
1894 assert( c != NULL );
1896 /* Only update client information of unregistered clients */
1897 if( Client_Type( c ) == CLIENT_UNKNOWN ) {
1898 strlcpy(My_Connections[i].host, readbuf, sizeof( My_Connections[i].host));
1899 Client_SetHostname( c, readbuf);
1903 Log(LOG_INFO, "IDENT lookup for connection %d: \"%s\".", i, identptr);
1904 Client_SetUser(c, identptr, true);
1906 Log(LOG_INFO, "IDENT lookup for connection %d: no result.", i);
1911 else Log( LOG_DEBUG, "Resolver: discarding result for already registered connection %d.", i );
1913 /* Reset penalty time */
1914 Conn_ResetPenalty( i );
1915 } /* cb_Read_Resolver_Result */
1919 Simple_Message( int Sock, const char *Msg )
1921 char buf[COMMAND_LEN];
1923 /* Write "simple" message to socket, without using compression
1924 * or even the connection write buffers. Used e.g. for error
1925 * messages by New_Connection(). */
1926 assert( Sock > NONE );
1927 assert( Msg != NULL );
1929 strlcpy( buf, Msg, sizeof buf - 2);
1930 len = strlcat( buf, "\r\n", sizeof buf);
1931 (void)write(Sock, buf, len);
1932 } /* Simple_Error */
1936 Conn_GetClient( CONN_ID Idx )
1938 /* return Client-Structure that belongs to the local Connection Idx.
1939 * If none is found, return NULL.
1944 c = array_get(&My_ConnArray, sizeof (CONNECTION), (size_t)Idx);
1948 return c ? c->client : NULL;
1952 /* we cannot access My_Connections in irc-info.c */
1954 Conn_GetCipherInfo(CONN_ID Idx, char *buf, size_t len)
1958 assert(Idx < (int) array_length(&My_ConnArray, sizeof(CONNECTION)));
1959 return ConnSSL_GetCipherInfo(&My_Connections[Idx], buf, len);
1964 Conn_UsesSSL(CONN_ID Idx)
1968 assert(Idx < (int) array_length(&My_ConnArray, sizeof(CONNECTION)));
1969 return Conn_OPTION_ISSET(&My_Connections[Idx], CONN_SSL);