2 * ngIRCd -- The Next Generation IRC Daemon
3 * Copyright (c)2001-2010 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 # ifdef HAVE_NETINET_IN_SYSTM_H
41 # include <netinet/in_systm.h>
43 # include <netinet/ip.h>
47 # include <stdint.h> /* e.g. for Mac OS X */
51 # include <tcpd.h> /* for TCP Wrappers */
67 #include "conn-func.h"
69 #include "ng_ipaddr.h"
76 # include "rendezvous.h"
82 #define SERVER_WAIT (NONE - 1)
84 #define MAX_COMMANDS 3
85 #define MAX_COMMANDS_SERVER 10
88 static bool Handle_Write PARAMS(( CONN_ID Idx ));
89 static bool Conn_Write PARAMS(( CONN_ID Idx, char *Data, size_t Len ));
90 static int New_Connection PARAMS(( int Sock ));
91 static CONN_ID Socket2Index PARAMS(( int Sock ));
92 static void Read_Request PARAMS(( CONN_ID Idx ));
93 static unsigned int Handle_Buffer PARAMS(( CONN_ID Idx ));
94 static void Check_Connections PARAMS(( void ));
95 static void Check_Servers PARAMS(( void ));
96 static void Init_Conn_Struct PARAMS(( CONN_ID Idx ));
97 static bool Init_Socket PARAMS(( int Sock ));
98 static void New_Server PARAMS(( int Server, ng_ipaddr_t *dest ));
99 static void Simple_Message PARAMS(( int Sock, const char *Msg ));
100 static int NewListener PARAMS(( const char *listen_addr, UINT16 Port ));
101 static void Account_Connection PARAMS((void));
104 static array My_Listeners;
105 static array My_ConnArray;
106 static size_t NumConnections, NumConnectionsMax, NumConnectionsAccepted;
109 int allow_severity = LOG_INFO;
110 int deny_severity = LOG_ERR;
113 static void server_login PARAMS((CONN_ID idx));
116 extern struct SSLOptions Conf_SSLOptions;
117 static void cb_connserver_login_ssl PARAMS((int sock, short what));
118 static void cb_clientserver_ssl PARAMS((int sock, short what));
120 static void cb_Read_Resolver_Result PARAMS((int sock, UNUSED short what));
121 static void cb_Connect_to_Server PARAMS((int sock, UNUSED short what));
122 static void cb_clientserver PARAMS((int sock, short what));
126 * IO callback for listening sockets: handle new connections. This callback
127 * gets called when a new non-SSL connection should be accepted.
128 * @param sock Socket descriptor
129 * @param irrelevant (ignored IO specification)
132 cb_listen(int sock, short irrelevant)
135 (void) New_Connection(sock);
141 * IO callback for listening SSL sockets: handle new connections. This callback
142 * gets called when a new SSL-enabled connection should be accepted.
143 * @param sock Socket descriptor
144 * @param irrelevant (ignored IO specification)
147 cb_listen_ssl(int sock, short irrelevant)
152 fd = New_Connection(sock);
155 io_event_setcb(My_Connections[fd].sock, cb_clientserver_ssl);
161 * IO callback for new outgoing non-SSL server connections.
162 * @param sock Socket descriptor
163 * @param what IO specification (IO_WANTREAD/IO_WANTWRITE/...)
166 cb_connserver(int sock, UNUSED short what)
168 int res, err, server;
170 CONN_ID idx = Socket2Index( sock );
173 LogDebug("cb_connserver wants to write on unknown socket?!");
178 assert(what & IO_WANTWRITE);
180 /* Make sure that the server is still configured; it could have been
181 * removed in the meantime! */
182 server = Conf_GetServer(idx);
184 Log(LOG_ERR, "Connection on socket %d to \"%s\" aborted!",
185 sock, My_Connections[idx].host);
186 Conn_Close(idx, "Connection aborted!", NULL, false);
190 /* connect() finished, get result. */
191 sock_len = (socklen_t)sizeof(err);
192 res = getsockopt(My_Connections[idx].sock, SOL_SOCKET, SO_ERROR,
194 assert(sock_len == sizeof(err));
196 /* Error while connecting? */
197 if ((res != 0) || (err != 0)) {
199 Log(LOG_CRIT, "getsockopt (connection %d): %s!",
200 idx, strerror(errno));
203 "Can't connect socket to \"%s:%d\" (connection %d): %s!",
204 My_Connections[idx].host, Conf_Server[server].port,
207 Conn_Close(idx, "Can't connect!", NULL, false);
209 if (ng_ipaddr_af(&Conf_Server[server].dst_addr[0])) {
210 /* more addresses to try... */
211 New_Server(res, &Conf_Server[server].dst_addr[0]);
212 /* connection to dst_addr[0] is now in progress, so
213 * remove this address... */
214 Conf_Server[server].dst_addr[0] =
215 Conf_Server[server].dst_addr[1];
216 memset(&Conf_Server[server].dst_addr[1], 0,
217 sizeof(Conf_Server[server].dst_addr[1]));
222 /* connect() succeeded, remove all additional addresses */
223 memset(&Conf_Server[server].dst_addr, 0,
224 sizeof(Conf_Server[server].dst_addr));
226 Conn_OPTION_DEL( &My_Connections[idx], CONN_ISCONNECTING );
228 if ( Conn_OPTION_ISSET( &My_Connections[idx], CONN_SSL_CONNECT )) {
229 io_event_setcb( sock, cb_connserver_login_ssl );
230 io_event_add( sock, IO_WANTWRITE|IO_WANTREAD );
239 * Login to a remote server.
240 * @param idx Connection index
243 server_login(CONN_ID idx)
245 Log( LOG_INFO, "Connection %d with \"%s:%d\" established. Now logging in ...", idx,
246 My_Connections[idx].host, Conf_Server[Conf_GetServer( idx )].port );
248 io_event_setcb( My_Connections[idx].sock, cb_clientserver);
249 io_event_add( My_Connections[idx].sock, IO_WANTREAD|IO_WANTWRITE);
251 /* Send PASS and SERVER command to peer */
252 Conn_WriteStr( idx, "PASS %s %s", Conf_Server[Conf_GetServer( idx )].pwd_out, NGIRCd_ProtoID );
253 Conn_WriteStr( idx, "SERVER %s :%s", Conf_ServerName, Conf_ServerInfo );
259 * IO callback for new outgoing SSL-enabled server connections.
260 * @param sock Socket descriptor
261 * @param what IO specification (IO_WANTREAD/IO_WANTWRITE/...)
264 cb_connserver_login_ssl(int sock, short unused)
266 CONN_ID idx = Socket2Index(sock);
274 switch (ConnSSL_Connect( &My_Connections[idx])) {
276 case 0: LogDebug("ConnSSL_Connect: not ready");
279 Log(LOG_ERR, "SSL connection on socket %d failed!", sock);
280 Conn_Close(idx, "Can't connect!", NULL, false);
284 Log( LOG_INFO, "SSL connection %d with \"%s:%d\" established.", idx,
285 My_Connections[idx].host, Conf_Server[Conf_GetServer( idx )].port );
293 * IO callback for established non-SSL client and server connections.
294 * @param sock Socket descriptor
295 * @param what IO specification (IO_WANTREAD/IO_WANTWRITE/...)
298 cb_clientserver(int sock, short what)
300 CONN_ID idx = Socket2Index(sock);
309 if (what & IO_WANTREAD
310 || (Conn_OPTION_ISSET(&My_Connections[idx], CONN_SSL_WANT_WRITE))) {
311 /* if TLS layer needs to write additional data, call
312 * Read_Request() instead so that SSL/TLS can continue */
316 if (what & IO_WANTREAD)
319 if (what & IO_WANTWRITE)
326 * IO callback for established SSL-enabled client and server connections.
327 * @param sock Socket descriptor
328 * @param what IO specification (IO_WANTREAD/IO_WANTWRITE/...)
331 cb_clientserver_ssl(int sock, short what)
333 CONN_ID idx = Socket2Index(sock);
342 switch (ConnSSL_Accept(&My_Connections[idx])) {
346 return; /* EAGAIN: callback will be invoked again by IO layer */
348 Conn_Close(idx, "SSL accept error, closing socket", "SSL accept error", false);
351 if (what & IO_WANTREAD)
354 if (what & IO_WANTWRITE)
357 io_event_setcb(sock, cb_clientserver); /* SSL handshake completed */
363 * Initialite connecion module.
370 /* Speicher fuer Verbindungs-Pool anfordern */
371 Pool_Size = CONNECTION_POOL;
372 if ((Conf_MaxConnections > 0) &&
373 (Pool_Size > Conf_MaxConnections))
374 Pool_Size = Conf_MaxConnections;
376 if (!array_alloc(&My_ConnArray, sizeof(CONNECTION), (size_t)Pool_Size)) {
377 Log(LOG_EMERG, "Can't allocate memory! [Conn_Init]");
381 /* FIXME: My_Connetions/Pool_Size is needed by other parts of the
382 * code; remove them! */
383 My_Connections = (CONNECTION*) array_start(&My_ConnArray);
385 LogDebug("Allocated connection pool for %d items (%ld bytes).",
386 array_length(&My_ConnArray, sizeof(CONNECTION)),
387 array_bytes(&My_ConnArray));
389 assert(array_length(&My_ConnArray, sizeof(CONNECTION)) >= (size_t)Pool_Size);
391 array_free( &My_Listeners );
393 for (i = 0; i < Pool_Size; i++)
399 * Clean up connection module.
406 Conn_ExitListeners();
408 LogDebug("Shutting down all connections ..." );
409 for( idx = 0; idx < Pool_Size; idx++ ) {
410 if( My_Connections[idx].sock > NONE ) {
411 Conn_Close( idx, NULL, NGIRCd_SignalRestart ?
412 "Server going down (restarting)":"Server going down", true );
416 array_free(&My_ConnArray);
417 My_Connections = NULL;
419 io_library_shutdown();
424 ports_initlisteners(array *a, const char *listen_addr, void (*func)(int,short))
426 unsigned int created = 0;
431 len = array_length(a, sizeof (UINT16));
432 port = array_start(a);
434 fd = NewListener(listen_addr, *port);
439 if (!io_event_create( fd, IO_WANTREAD, func )) {
440 Log( LOG_ERR, "io_event_create(): Could not add listening fd %d (port %u): %s!",
441 fd, (unsigned int) *port, strerror(errno));
454 * Initialize all listening sockets.
455 * @return Number of created listening sockets
458 Conn_InitListeners( void )
460 /* Initialize ports on which the server should accept connections */
461 unsigned int created = 0;
462 char *copy, *listen_addr;
464 if (!io_library_init(CONNECTION_POOL)) {
465 Log(LOG_EMERG, "Cannot initialize IO routines: %s", strerror(errno));
469 assert(Conf_ListenAddress);
471 /* can't use Conf_ListenAddress directly, see below */
472 copy = strdup(Conf_ListenAddress);
474 Log(LOG_CRIT, "Cannot copy %s: %s", Conf_ListenAddress, strerror(errno));
477 listen_addr = strtok(copy, ",");
479 while (listen_addr) {
480 ngt_TrimStr(listen_addr);
482 created += ports_initlisteners(&Conf_ListenPorts, listen_addr, cb_listen);
484 created += ports_initlisteners(&Conf_SSLOptions.ListenPorts, listen_addr, cb_listen_ssl);
488 listen_addr = strtok(NULL, ",");
491 /* Can't free() Conf_ListenAddress here: on REHASH, if the config file
492 * cannot be re-loaded, we'd end up with a NULL Conf_ListenAddress.
493 * Instead, free() takes place in conf.c, before the config file
494 * is being parsed. */
498 } /* Conn_InitListeners */
502 Conn_ExitListeners( void )
504 /* Close down all listening sockets */
508 Rendezvous_UnregisterListeners( );
511 arraylen = array_length(&My_Listeners, sizeof (int));
513 "Shutting down all listening sockets (%d total) ...", arraylen);
514 fd = array_start(&My_Listeners);
519 LogDebug("Listening socket %d closed.", *fd );
522 array_free(&My_Listeners);
523 } /* Conn_ExitListeners */
527 InitSinaddrListenAddr(ng_ipaddr_t *addr, const char *listen_addrstr, UINT16 Port)
531 ret = ng_ipaddr_init(addr, listen_addrstr, Port);
533 assert(listen_addrstr);
534 Log(LOG_CRIT, "Can't bind to [%s]:%u: can't convert ip address \"%s\"",
535 listen_addrstr, Port, listen_addrstr);
542 set_v6_only(int af, int sock)
544 #if defined(IPV6_V6ONLY) && defined(WANT_IPV6)
550 if (setsockopt(sock, IPPROTO_IPV6, IPV6_V6ONLY, &on, (socklen_t)sizeof(on)))
551 Log(LOG_ERR, "Could not set IPV6_V6ONLY: %s", strerror(errno));
559 /* return new listening port file descriptor or -1 on failure */
561 NewListener(const char *listen_addr, UINT16 Port)
563 /* Create new listening socket on specified port */
567 char name[CLIENT_ID_LEN], *info;
569 if (!InitSinaddrListenAddr(&addr, listen_addr, Port))
572 af = ng_ipaddr_af(&addr);
573 sock = socket(af, SOCK_STREAM, 0);
575 Log(LOG_CRIT, "Can't create socket (af %d) : %s!", af, strerror(errno));
579 set_v6_only(af, sock);
581 if (!Init_Socket(sock))
584 if (bind(sock, (struct sockaddr *)&addr, ng_ipaddr_salen(&addr)) != 0) {
585 Log(LOG_CRIT, "Can't bind socket to address %s:%d - %s",
586 ng_ipaddr_tostr(&addr), Port, strerror(errno));
591 if( listen( sock, 10 ) != 0 ) {
592 Log( LOG_CRIT, "Can't listen on socket: %s!", strerror( errno ));
597 /* keep fd in list so we can close it when ngircd restarts/shuts down */
598 if (!array_catb( &My_Listeners,(char*) &sock, sizeof(int) )) {
599 Log( LOG_CRIT, "Can't add socket to My_Listeners array: %s!", strerror( errno ));
604 Log(LOG_INFO, "Now listening on [%s]:%d (socket %d).", ng_ipaddr_tostr(&addr), Port, sock);
607 /* Get best server description text */
608 if( ! Conf_ServerInfo[0] ) info = Conf_ServerName;
611 /* Use server info string */
613 if( Conf_ServerInfo[0] == '[' )
615 /* Cut off leading hostname part in "[]" */
616 info = strchr( Conf_ServerInfo, ']' );
620 while( *info == ' ' ) info++;
623 if( ! info ) info = Conf_ServerInfo;
626 /* Add port number to description if non-standard */
628 snprintf(name, sizeof name, "%s (port %u)", info,
631 strlcpy(name, info, sizeof name);
633 /* Register service */
634 Rendezvous_Register( name, MDNS_TYPE, Port );
642 * SSL/TLS connections require extra treatment:
643 * When either CONN_SSL_WANT_WRITE or CONN_SSL_WANT_READ is set, we
644 * need to take care of that first, before checking read/write buffers.
645 * For instance, while we might have data in our write buffer, the
646 * TLS/SSL protocol might need to read internal data first for TLS/SSL
649 * If this function returns true, such a condition is met and we have
650 * to reverse the condition (check for read even if we've data to write,
651 * do not check for read but writeability even if write-buffer is empty).
654 SSL_WantRead(const CONNECTION *c)
656 if (Conn_OPTION_ISSET(c, CONN_SSL_WANT_READ)) {
657 io_event_add(c->sock, IO_WANTREAD);
663 SSL_WantWrite(const CONNECTION *c)
665 if (Conn_OPTION_ISSET(c, CONN_SSL_WANT_WRITE)) {
666 io_event_add(c->sock, IO_WANTWRITE);
673 SSL_WantRead(UNUSED const CONNECTION *c) { return false; }
675 SSL_WantWrite(UNUSED const CONNECTION *c) { return false; }
680 * "Main Loop": Loop until shutdown or restart is signalled.
681 * This function loops until a shutdown or restart of ngIRCd is signalled and
682 * calls io_dispatch() to check for readable and writable sockets every second.
683 * It checks for status changes on pending connections (e. g. when a hostname
684 * has been resolved), checks for "penalties" and timeouts, and handles the
691 unsigned int wdatalen, bytes_processed;
695 while (!NGIRCd_SignalQuit && !NGIRCd_SignalRestart) {
699 Rendezvous_Handler();
702 /* Should the configuration be reloaded? */
703 if (NGIRCd_SignalRehash)
706 /* Check configured servers and established links */
710 /* Look for non-empty read buffers ... */
711 for (i = 0; i < Pool_Size; i++) {
712 if ((My_Connections[i].sock > NONE)
713 && (array_bytes(&My_Connections[i].rbuf) > 0)
714 && (My_Connections[i].delaytime <= t)) {
715 /* ... and try to handle the received data */
716 bytes_processed = Handle_Buffer(i);
717 /* if we processed data, and there might be
718 * more commands in the input buffer, do not
719 * try to read any more data now */
720 if (bytes_processed &&
721 array_bytes(&My_Connections[i].rbuf) > 2) {
723 ("Throttling connection %d: command limit reached!",
725 Conn_SetPenalty(i, 1);
730 /* Look for non-empty write buffers ... */
731 for (i = 0; i < Pool_Size; i++) {
732 if (My_Connections[i].sock <= NONE)
735 wdatalen = (unsigned int)array_bytes(&My_Connections[i].wbuf);
738 array_bytes(&My_Connections[i].zip.wbuf) > 0)
743 if (SSL_WantRead(&My_Connections[i]))
745 io_event_add(My_Connections[i].sock,
750 /* Check from which sockets we possibly could read ... */
751 for (i = 0; i < Pool_Size; i++) {
752 if (My_Connections[i].sock <= NONE)
755 if (SSL_WantWrite(&My_Connections[i]))
756 continue; /* TLS/SSL layer needs to write data; deal with this first */
758 if (Proc_InProgress(&My_Connections[i].res_stat)) {
759 /* Wait for completion of resolver sub-process ... */
760 io_event_del(My_Connections[i].sock,
765 if (Conn_OPTION_ISSET(&My_Connections[i], CONN_ISCONNECTING))
766 /* Wait for completion of connect() ... */
769 if (My_Connections[i].delaytime > t) {
770 /* There is a "penalty time" set: ignore socket! */
771 io_event_del(My_Connections[i].sock,
775 io_event_add(My_Connections[i].sock, IO_WANTREAD);
778 /* Set the timeout for reading from the network to 1 second,
779 * which is the granularity with witch we handle "penalty
780 * times" for example.
781 * Note: tv_sec/usec are undefined(!) after io_dispatch()
782 * returns, so we have to set it beforce each call to it! */
786 /* Wait for activity ... */
787 i = io_dispatch(&tv);
788 if (i == -1 && errno != EINTR) {
789 Log(LOG_EMERG, "Conn_Handler(): io_dispatch(): %s!",
791 Log(LOG_ALERT, "%s exiting due to fatal errors!",
797 if (NGIRCd_SignalQuit)
798 Log(LOG_NOTICE | LOG_snotice, "Server going down NOW!");
799 else if (NGIRCd_SignalRestart)
800 Log(LOG_NOTICE | LOG_snotice, "Server restarting NOW!");
805 * Write a text string into the socket of a connection.
806 * This function automatically appends CR+LF to the string and validates that
807 * the result is a valid IRC message (oversized messages are shortened, for
808 * example). Then it calls the Conn_Write() function to do the actual sending.
809 * @param Idx Index fo the connection.
810 * @param Format Format string, see printf().
811 * @return true on success, false otherwise.
815 Conn_WriteStr(CONN_ID Idx, const char *Format, ...)
818 Conn_WriteStr(Idx, Format, va_alist)
824 char buffer[COMMAND_LEN];
829 assert( Idx > NONE );
830 assert( Format != NULL );
833 va_start( ap, Format );
837 if (vsnprintf( buffer, COMMAND_LEN - 2, Format, ap ) >= COMMAND_LEN - 2 ) {
839 * The string that should be written to the socket is longer
840 * than the allowed size of COMMAND_LEN bytes (including both
841 * the CR and LF characters). This can be caused by the
842 * IRC_WriteXXX() functions when the prefix of this server had
843 * to be added to an already "quite long" command line which
844 * has been received from a regular IRC client, for example.
846 * We are not allowed to send such "oversized" messages to
847 * other servers and clients, see RFC 2812 2.3 and 2813 3.3
848 * ("these messages SHALL NOT exceed 512 characters in length,
849 * counting all characters including the trailing CR-LF").
851 * So we have a big problem here: we should send more bytes
852 * to the network than we are allowed to and we don't know
853 * the originator (any more). The "old" behaviour of blaming
854 * the receiver ("next hop") is a bad idea (it could be just
855 * an other server only routing the message!), so the only
856 * option left is to shorten the string and to hope that the
857 * result is still somewhat useful ...
861 strcpy (buffer + sizeof(buffer) - strlen(CUT_TXTSUFFIX) - 2 - 1,
867 Log(LOG_DEBUG, " -> connection %d: '%s'.", Idx, buffer);
870 len = strlcat( buffer, "\r\n", sizeof( buffer ));
871 ok = Conn_Write(Idx, buffer, len);
872 My_Connections[Idx].msg_out++;
876 } /* Conn_WriteStr */
880 * Append Data to the outbound write buffer of a connection.
881 * @param Idx Index of the connection.
882 * @param Data pointer to the data.
883 * @param Len length of Data.
884 * @return true on success, false otherwise.
887 Conn_Write( CONN_ID Idx, char *Data, size_t Len )
890 size_t writebuf_limit = WRITEBUFFER_LEN;
891 assert( Idx > NONE );
892 assert( Data != NULL );
895 c = Conn_GetClient(Idx);
898 /* Servers do get special write buffer limits, so they can generate
899 * all the messages that are required while peering. */
900 if (Client_Type(c) == CLIENT_SERVER)
901 writebuf_limit = WRITEBUFFER_SLINK_LEN;
903 /* Is the socket still open? A previous call to Conn_Write()
904 * may have closed the connection due to a fatal error.
905 * In this case it is sufficient to return an error, as well. */
906 if( My_Connections[Idx].sock <= NONE ) {
907 LogDebug("Skipped write on closed socket (connection %d).", Idx);
912 if ( Conn_OPTION_ISSET( &My_Connections[Idx], CONN_ZIP )) {
914 * Zip_Buffer() does all the dirty work for us: it flushes
915 * the (pre-)compression buffers if required and handles
916 * all error conditions. */
917 if (!Zip_Buffer(Idx, Data, Len))
923 /* Uncompressed link:
924 * Check if outbound buffer has enough space for the data. */
925 if (array_bytes(&My_Connections[Idx].wbuf) + Len >=
927 /* Buffer is full, flush it. Handle_Write deals with
928 * low-level errors, if any. */
929 if (!Handle_Write(Idx))
933 /* When the write buffer is still too big after flushing it,
934 * the connection will be killed. */
935 if (array_bytes(&My_Connections[Idx].wbuf) + Len >=
938 "Write buffer overflow (connection %d, size %lu byte)!",
940 (unsigned long)array_bytes(&My_Connections[Idx].wbuf));
941 Conn_Close(Idx, "Write buffer overflow!", NULL, false);
945 /* Copy data to write buffer */
946 if (!array_catb(&My_Connections[Idx].wbuf, Data, Len))
949 My_Connections[Idx].bytes_out += Len;
952 /* Adjust global write counter */
960 Conn_Close( CONN_ID Idx, const char *LogMsg, const char *FwdMsg, bool InformClient )
962 /* Close connection. Open pipes of asyncronous resolver
963 * sub-processes are closed down. */
969 double in_z_k, out_z_k;
973 assert( Idx > NONE );
975 /* Is this link already shutting down? */
976 if( Conn_OPTION_ISSET( &My_Connections[Idx], CONN_ISCLOSING )) {
977 /* Conn_Close() has been called recursively for this link;
978 * probabe reason: Handle_Write() failed -- see below. */
979 LogDebug("Recursive request to close connection: %d", Idx );
983 assert( My_Connections[Idx].sock > NONE );
985 /* Mark link as "closing" */
986 Conn_OPTION_ADD( &My_Connections[Idx], CONN_ISCLOSING );
988 port = ng_ipaddr_getport(&My_Connections[Idx].addr);
989 Log(LOG_INFO, "Shutting down connection %d (%s) with %s:%d ...", Idx,
990 LogMsg ? LogMsg : FwdMsg, My_Connections[Idx].host, port);
992 /* Search client, if any */
993 c = Conn_GetClient( Idx );
995 /* Should the client be informed? */
998 /* Send statistics to client if registered as user: */
999 if ((c != NULL) && (Client_Type(c) == CLIENT_USER)) {
1001 ":%s NOTICE %s :%sConnection statistics: client %.1f kb, server %.1f kb.",
1002 Client_ID(Client_ThisServer()), Client_ID(c),
1004 (double)My_Connections[Idx].bytes_in / 1024,
1005 (double)My_Connections[Idx].bytes_out / 1024);
1008 /* Send ERROR to client (see RFC 2812, section 3.1.7) */
1010 Conn_WriteStr(Idx, "ERROR :%s", FwdMsg);
1012 Conn_WriteStr(Idx, "ERROR :Closing connection.");
1015 /* Try to write out the write buffer. Note: Handle_Write() eventually
1016 * removes the CLIENT structure associated with this connection if an
1017 * error occurs! So we have to re-check if there is still an valid
1018 * CLIENT structure after calling Handle_Write() ...*/
1019 (void)Handle_Write( Idx );
1021 /* Search client, if any (re-check!) */
1022 c = Conn_GetClient( Idx );
1024 if ( Conn_OPTION_ISSET( &My_Connections[Idx], CONN_SSL )) {
1025 Log(LOG_INFO, "SSL connection %d shutting down ...", Idx);
1026 ConnSSL_Free(&My_Connections[Idx]);
1029 /* Shut down socket */
1030 if (! io_close(My_Connections[Idx].sock)) {
1031 /* Oops, we can't close the socket!? This is ... ugly! */
1033 "Error closing connection %d (socket %d) with %s:%d - %s! (ignored)",
1034 Idx, My_Connections[Idx].sock, My_Connections[Idx].host,
1035 port, strerror(errno));
1038 /* Mark socket as invalid: */
1039 My_Connections[Idx].sock = NONE;
1041 /* If there is still a client, unregister it now */
1043 Client_Destroy(c, LogMsg, FwdMsg, true);
1045 /* Calculate statistics and log information */
1046 in_k = (double)My_Connections[Idx].bytes_in / 1024;
1047 out_k = (double)My_Connections[Idx].bytes_out / 1024;
1049 if (Conn_OPTION_ISSET( &My_Connections[Idx], CONN_ZIP)) {
1050 in_z_k = (double)My_Connections[Idx].zip.bytes_in / 1024;
1051 out_z_k = (double)My_Connections[Idx].zip.bytes_out / 1024;
1052 /* Make sure that no division by zero can occur during
1053 * the calculation of in_p and out_p: in_z_k and out_z_k
1054 * are non-zero, that's guaranteed by the protocol until
1055 * compression can be enabled. */
1060 in_p = (int)(( in_k * 100 ) / in_z_k );
1061 out_p = (int)(( out_k * 100 ) / out_z_k );
1063 "Connection %d with %s:%d closed (in: %.1fk/%.1fk/%d%%, out: %.1fk/%.1fk/%d%%).",
1064 Idx, My_Connections[Idx].host, port,
1065 in_k, in_z_k, in_p, out_k, out_z_k, out_p);
1071 "Connection %d with %s:%d closed (in: %.1fk, out: %.1fk).",
1072 Idx, My_Connections[Idx].host, port,
1076 /* cancel running resolver */
1077 if (Proc_InProgress(&My_Connections[Idx].res_stat))
1078 Proc_Kill(&My_Connections[Idx].res_stat);
1080 /* Servers: Modify time of next connect attempt? */
1081 Conf_UnsetServer( Idx );
1084 /* Clean up zlib, if link was compressed */
1085 if ( Conn_OPTION_ISSET( &My_Connections[Idx], CONN_ZIP )) {
1086 inflateEnd( &My_Connections[Idx].zip.in );
1087 deflateEnd( &My_Connections[Idx].zip.out );
1088 array_free(&My_Connections[Idx].zip.rbuf);
1089 array_free(&My_Connections[Idx].zip.wbuf);
1093 array_free(&My_Connections[Idx].rbuf);
1094 array_free(&My_Connections[Idx].wbuf);
1096 /* Clean up connection structure (=free it) */
1097 Init_Conn_Struct( Idx );
1099 assert(NumConnections > 0);
1102 LogDebug("Shutdown of connection %d completed, %ld connection%s left.",
1103 Idx, NumConnections, NumConnections != 1 ? "s" : "");
1110 return NumConnections;
1117 return NumConnectionsMax;
1118 } /* Conn_CountMax */
1122 Conn_CountAccepted(void)
1124 return NumConnectionsAccepted;
1125 } /* Conn_CountAccepted */
1129 Conn_SyncServerStruct( void )
1131 /* Synchronize server structures (connection IDs):
1132 * connections <-> configuration */
1138 for( i = 0; i < Pool_Size; i++ ) {
1139 /* Established connection? */
1140 if (My_Connections[i].sock < 0)
1143 /* Server connection? */
1144 client = Conn_GetClient( i );
1145 if(( ! client ) || ( Client_Type( client ) != CLIENT_SERVER )) continue;
1147 for( c = 0; c < MAX_SERVERS; c++ )
1149 /* Configured server? */
1150 if( ! Conf_Server[c].host[0] ) continue;
1153 if( strcmp( Conf_Server[c].name, Client_ID( client )) == 0 )
1154 Conf_Server[c].conn_id = i;
1157 } /* SyncServerStruct */
1161 * Send out data of write buffer; connect new sockets.
1164 Handle_Write( CONN_ID Idx )
1169 assert( Idx > NONE );
1170 if ( My_Connections[Idx].sock < 0 ) {
1171 LogDebug("Handle_Write() on closed socket, connection %d", Idx);
1174 assert( My_Connections[Idx].sock > NONE );
1176 wdatalen = array_bytes(&My_Connections[Idx].wbuf );
1179 if (wdatalen == 0) {
1180 /* Write buffer is empty, so we try to flush the compression
1181 * buffer and get some data to work with from there :-) */
1182 if (!Zip_Flush(Idx))
1185 /* Now the write buffer most probably has changed: */
1186 wdatalen = array_bytes(&My_Connections[Idx].wbuf);
1190 if (wdatalen == 0) {
1191 /* Still no data, fine. */
1192 io_event_del(My_Connections[Idx].sock, IO_WANTWRITE );
1197 ("Handle_Write() called for connection %d, %ld bytes pending ...",
1201 if ( Conn_OPTION_ISSET( &My_Connections[Idx], CONN_SSL )) {
1202 len = ConnSSL_Write(&My_Connections[Idx], array_start(&My_Connections[Idx].wbuf), wdatalen);
1206 len = write(My_Connections[Idx].sock,
1207 array_start(&My_Connections[Idx].wbuf), wdatalen );
1210 if (errno == EAGAIN || errno == EINTR)
1213 Log(LOG_ERR, "Write error on connection %d (socket %d): %s!",
1214 Idx, My_Connections[Idx].sock, strerror(errno));
1215 Conn_Close(Idx, "Write error!", NULL, false);
1219 /* move any data not yet written to beginning */
1220 array_moveleft(&My_Connections[Idx].wbuf, 1, (size_t)len);
1223 } /* Handle_Write */
1227 Count_Connections(ng_ipaddr_t *a)
1232 for (i = 0; i < Pool_Size; i++) {
1233 if (My_Connections[i].sock <= NONE)
1235 if (ng_ipaddr_ipequal(&My_Connections[i].addr, a))
1239 } /* Count_Connections */
1243 * Initialize new client connection on a listening socket.
1244 * @param Sock Listening socket descriptor
1245 * @return Accepted socket descriptor or -1 on error
1248 New_Connection(int Sock)
1251 struct request_info req;
1253 ng_ipaddr_t new_addr;
1254 char ip_str[NG_INET_ADDRSTRLEN];
1255 int new_sock, new_sock_len, identsock;
1259 assert(Sock > NONE);
1261 new_sock_len = (int)sizeof(new_addr);
1262 new_sock = accept(Sock, (struct sockaddr *)&new_addr,
1263 (socklen_t *)&new_sock_len);
1265 Log(LOG_CRIT, "Can't accept connection: %s!", strerror(errno));
1268 NumConnectionsAccepted++;
1270 if (!ng_ipaddr_tostr_r(&new_addr, ip_str)) {
1271 Log(LOG_CRIT, "fd %d: Can't convert IP address!", new_sock);
1272 Simple_Message(new_sock, "ERROR :Internal Server Error");
1278 /* Validate socket using TCP Wrappers */
1279 request_init(&req, RQ_DAEMON, PACKAGE_NAME, RQ_FILE, new_sock,
1280 RQ_CLIENT_SIN, &new_addr, NULL);
1282 if (!hosts_access(&req)) {
1284 "Refused connection from %s (by TCP Wrappers)!", ip_str);
1285 Simple_Message(new_sock, "ERROR :Connection refused");
1291 if (!Init_Socket(new_sock))
1294 /* Check global connection limit */
1295 if ((Conf_MaxConnections > 0) &&
1296 (NumConnections >= (size_t) Conf_MaxConnections)) {
1297 Log(LOG_ALERT, "Can't accept connection: limit (%d) reached!",
1298 Conf_MaxConnections);
1299 Simple_Message(new_sock, "ERROR :Connection limit reached");
1304 /* Check IP-based connection limit */
1305 cnt = Count_Connections(&new_addr);
1306 if ((Conf_MaxConnectionsIP > 0) && (cnt >= Conf_MaxConnectionsIP)) {
1307 /* Access denied, too many connections from this IP address! */
1309 "Refused connection from %s: too may connections (%ld) from this IP address!",
1311 Simple_Message(new_sock,
1312 "ERROR :Connection refused, too many connections from your IP address!");
1317 if (new_sock >= Pool_Size) {
1318 if (!array_alloc(&My_ConnArray, sizeof(CONNECTION),
1319 (size_t) new_sock)) {
1321 "Can't allocate memory! [New_Connection]");
1322 Simple_Message(new_sock, "ERROR: Internal error");
1326 LogDebug("Bumped connection pool to %ld items (internal: %ld items, %ld bytes)",
1327 new_sock, array_length(&My_ConnArray,
1328 sizeof(CONNECTION)), array_bytes(&My_ConnArray));
1330 /* Adjust pointer to new block */
1331 My_Connections = array_start(&My_ConnArray);
1332 while (Pool_Size <= new_sock)
1333 Init_Conn_Struct(Pool_Size++);
1336 /* register callback */
1337 if (!io_event_create(new_sock, IO_WANTREAD, cb_clientserver)) {
1339 "Can't accept connection: io_event_create failed!");
1340 Simple_Message(new_sock, "ERROR :Internal error");
1345 c = Client_NewLocal(new_sock, ip_str, CLIENT_UNKNOWN, false);
1348 "Can't accept connection: can't create client structure!");
1349 Simple_Message(new_sock, "ERROR :Internal error");
1354 Init_Conn_Struct(new_sock);
1355 My_Connections[new_sock].sock = new_sock;
1356 My_Connections[new_sock].addr = new_addr;
1357 My_Connections[new_sock].client = c;
1359 /* Set initial hostname to IP address. This becomes overwritten when
1360 * the DNS lookup is enabled and succeeds, but is used otherwise. */
1361 if (ng_ipaddr_af(&new_addr) != AF_INET)
1362 snprintf(My_Connections[new_sock].host,
1363 sizeof(My_Connections[new_sock].host), "[%s]", ip_str);
1365 strlcpy(My_Connections[new_sock].host, ip_str,
1366 sizeof(My_Connections[new_sock].host));
1368 Client_SetHostname(c, My_Connections[new_sock].host);
1370 Log(LOG_INFO, "Accepted connection %d from %s:%d on socket %d.",
1371 new_sock, My_Connections[new_sock].host,
1372 ng_ipaddr_getport(&new_addr), Sock);
1374 identsock = new_sock;
1380 Resolve_Addr(&My_Connections[new_sock].res_stat, &new_addr,
1381 identsock, cb_Read_Resolver_Result);
1383 /* ngIRCd waits up to 4 seconds for the result of the asynchronous
1384 * DNS and IDENT resolver subprocess using the "penalty" mechanism.
1385 * If there are results earlier, the delay is aborted. */
1386 Conn_SetPenalty(new_sock, 4);
1388 Account_Connection();
1390 } /* New_Connection */
1394 Account_Connection(void)
1397 if (NumConnections > NumConnectionsMax)
1398 NumConnectionsMax = NumConnections;
1399 LogDebug("Total number of connections now %lu (max %lu).",
1400 NumConnections, NumConnectionsMax);
1401 } /* Account_Connection */
1405 Socket2Index( int Sock )
1407 assert( Sock >= 0 );
1409 if( Sock >= Pool_Size || My_Connections[Sock].sock != Sock ) {
1410 /* the Connection was already closed again, likely due to
1412 LogDebug("Socket2Index: can't get connection for socket %d!", Sock);
1416 } /* Socket2Index */
1420 * Read data from the network to the read buffer. If an error occures,
1421 * the socket of this connection will be shut down.
1424 Read_Request( CONN_ID Idx )
1427 static const unsigned int maxbps = COMMAND_LEN / 2;
1428 char readbuf[READBUFFER_LEN];
1431 assert( Idx > NONE );
1432 assert( My_Connections[Idx].sock > NONE );
1435 if ((array_bytes(&My_Connections[Idx].rbuf) >= READBUFFER_LEN) ||
1436 (array_bytes(&My_Connections[Idx].zip.rbuf) >= READBUFFER_LEN))
1438 if (array_bytes(&My_Connections[Idx].rbuf) >= READBUFFER_LEN)
1441 /* Read buffer is full */
1443 "Receive buffer overflow (connection %d): %d bytes!",
1444 Idx, array_bytes(&My_Connections[Idx].rbuf));
1445 Conn_Close( Idx, "Receive buffer overflow!", NULL, false );
1450 if (Conn_OPTION_ISSET(&My_Connections[Idx], CONN_SSL))
1451 len = ConnSSL_Read( &My_Connections[Idx], readbuf, sizeof(readbuf));
1454 len = read(My_Connections[Idx].sock, readbuf, sizeof(readbuf));
1456 Log(LOG_INFO, "%s:%u (%s) is closing the connection ...",
1457 My_Connections[Idx].host,
1458 (unsigned int) ng_ipaddr_getport(&My_Connections[Idx].addr),
1459 ng_ipaddr_tostr(&My_Connections[Idx].addr));
1461 "Socket closed!", "Client closed connection",
1467 if( errno == EAGAIN ) return;
1468 Log(LOG_ERR, "Read error on connection %d (socket %d): %s!",
1469 Idx, My_Connections[Idx].sock, strerror(errno));
1470 Conn_Close(Idx, "Read error!", "Client closed connection",
1475 if (Conn_OPTION_ISSET(&My_Connections[Idx], CONN_ZIP)) {
1476 if (!array_catb(&My_Connections[Idx].zip.rbuf, readbuf,
1479 "Could not append recieved data to zip input buffer (connn %d): %d bytes!",
1481 Conn_Close(Idx, "Receive buffer overflow!", NULL,
1488 if (!array_catb( &My_Connections[Idx].rbuf, readbuf, len)) {
1489 Log( LOG_ERR, "Could not append recieved data to input buffer (connn %d): %d bytes!", Idx, len );
1490 Conn_Close( Idx, "Receive buffer overflow!", NULL, false );
1494 /* Update connection statistics */
1495 My_Connections[Idx].bytes_in += len;
1497 /* Update timestamp of last data received if this connection is
1498 * registered as a user, server or service connection. Don't update
1499 * otherwise, so users have at least Conf_PongTimeout seconds time to
1500 * register with the IRC server -- see Check_Connections().
1501 * Set "lastping", too, so we can handle time shifts backwards ... */
1502 c = Conn_GetClient(Idx);
1503 if (c && (Client_Type(c) == CLIENT_USER
1504 || Client_Type(c) == CLIENT_SERVER
1505 || Client_Type(c) == CLIENT_SERVICE)) {
1507 if (My_Connections[Idx].lastdata != t)
1508 My_Connections[Idx].bps = 0;
1510 My_Connections[Idx].lastdata = t;
1511 My_Connections[Idx].lastping = My_Connections[Idx].lastdata;
1514 /* Look at the data in the (read-) buffer of this connection */
1515 My_Connections[Idx].bps += Handle_Buffer(Idx);
1516 if (Client_Type(c) != CLIENT_SERVER
1517 && My_Connections[Idx].bps >= maxbps) {
1518 LogDebug("Throttling connection %d: BPS exceeded! (%u >= %u)",
1519 Idx, My_Connections[Idx].bps, maxbps);
1520 Conn_SetPenalty(Idx, 1);
1522 } /* Read_Request */
1526 * Handle all data in the connection read-buffer.
1527 * Data is processed until no complete command is left in the read buffer,
1528 * or MAX_COMMANDS[_SERVER] commands were processed.
1529 * When a fatal error occurs, the connection is shut down.
1530 * @param Idx Index of the connection.
1531 * @return number of bytes processed.
1534 Handle_Buffer(CONN_ID Idx)
1537 char *ptr1, *ptr2, *first_eol;
1545 unsigned int i, maxcmd = MAX_COMMANDS, len_processed = 0;
1548 c = Conn_GetClient(Idx);
1551 /* Servers do get special command limits, so they can process
1552 * all the messages that are required while peering. */
1553 if (Client_Type(c) == CLIENT_SERVER)
1554 maxcmd = MAX_COMMANDS_SERVER;
1556 starttime = time(NULL);
1557 for (i=0; i < maxcmd; i++) {
1559 if (My_Connections[Idx].delaytime > starttime)
1562 /* Unpack compressed data, if compression is in use */
1563 if (Conn_OPTION_ISSET(&My_Connections[Idx], CONN_ZIP)) {
1564 /* When unzipping fails, Unzip_Buffer() shuts
1565 * down the connection itself */
1566 if (!Unzip_Buffer(Idx))
1571 if (0 == array_bytes(&My_Connections[Idx].rbuf))
1574 /* Make sure that the buffer is NULL terminated */
1575 if (!array_cat0_temporary(&My_Connections[Idx].rbuf)) {
1576 Conn_Close(Idx, NULL,
1577 "Can't allocate memory [Handle_Buffer]",
1582 /* RFC 2812, section "2.3 Messages", 5th paragraph:
1583 * "IRC messages are always lines of characters terminated
1584 * with a CR-LF (Carriage Return - Line Feed) pair [...]". */
1586 ptr = strstr(array_start(&My_Connections[Idx].rbuf), "\r\n");
1589 /* Check for non-RFC-compliant request (only CR or LF)?
1590 * Unfortunately, there are quite a few clients out there
1591 * that do this -- e. g. mIRC, BitchX, and Trillian :-( */
1592 ptr1 = strchr(array_start(&My_Connections[Idx].rbuf), '\r');
1593 ptr2 = strchr(array_start(&My_Connections[Idx].rbuf), '\n');
1595 /* Check if there is a single CR or LF _before_ the
1596 * corerct CR+LF line terminator: */
1597 first_eol = ptr1 < ptr2 ? ptr1 : ptr2;
1598 if (first_eol < ptr) {
1599 /* Single CR or LF before CR+LF found */
1603 } else if (ptr1 || ptr2) {
1604 /* No CR+LF terminated command found, but single
1605 * CR or LF found ... */
1607 ptr = ptr1 < ptr2 ? ptr1 : ptr2;
1609 ptr = ptr1 ? ptr1 : ptr2;
1617 /* Complete (=line terminated) request found, handle it! */
1620 len = ptr - (char *)array_start(&My_Connections[Idx].rbuf) + delta;
1622 if (len > (COMMAND_LEN - 1)) {
1623 /* Request must not exceed 512 chars (incl. CR+LF!),
1624 * see RFC 2812. Disconnect Client if this happens. */
1626 "Request too long (connection %d): %d bytes (max. %d expected)!",
1627 Idx, array_bytes(&My_Connections[Idx].rbuf),
1629 Conn_Close(Idx, NULL, "Request too long", true);
1633 len_processed += (unsigned int)len;
1635 /* Request is empty (only '\r\n', '\r' or '\n');
1636 * delta is 2 ('\r\n') or 1 ('\r' or '\n'), see above */
1637 array_moveleft(&My_Connections[Idx].rbuf, 1, len);
1641 /* remember if stream is already compressed */
1642 old_z = My_Connections[Idx].options & CONN_ZIP;
1645 My_Connections[Idx].msg_in++;
1647 (Idx, (char *)array_start(&My_Connections[Idx].rbuf)))
1648 return 0; /* error -> connection has been closed */
1650 array_moveleft(&My_Connections[Idx].rbuf, 1, len);
1651 LogDebug("Connection %d: %d bytes left in read buffer.",
1652 Idx, array_bytes(&My_Connections[Idx].rbuf));
1654 if ((!old_z) && (My_Connections[Idx].options & CONN_ZIP) &&
1655 (array_bytes(&My_Connections[Idx].rbuf) > 0)) {
1656 /* The last command activated socket compression.
1657 * Data that was read after that needs to be copied
1658 * to the unzip buffer for decompression: */
1660 (&My_Connections[Idx].zip.rbuf,
1661 &My_Connections[Idx].rbuf)) {
1662 Conn_Close(Idx, NULL,
1663 "Can't allocate memory [Handle_Buffer]",
1668 array_trunc(&My_Connections[Idx].rbuf);
1670 ("Moved already received data (%u bytes) to uncompression buffer.",
1671 array_bytes(&My_Connections[Idx].zip.rbuf));
1675 return len_processed;
1676 } /* Handle_Buffer */
1680 Check_Connections(void)
1682 /* check if connections are alive. if not, play PING-PONG first.
1683 * if this doesn't help either, disconnect client. */
1688 for (i = 0; i < Pool_Size; i++) {
1689 if (My_Connections[i].sock < 0)
1692 c = Conn_GetClient(i);
1693 if (c && ((Client_Type(c) == CLIENT_USER)
1694 || (Client_Type(c) == CLIENT_SERVER)
1695 || (Client_Type(c) == CLIENT_SERVICE))) {
1696 /* connected User, Server or Service */
1697 if (My_Connections[i].lastping >
1698 My_Connections[i].lastdata) {
1699 /* We already sent a ping */
1700 if (My_Connections[i].lastping <
1701 time(NULL) - Conf_PongTimeout) {
1704 ("Connection %d: Ping timeout: %d seconds.",
1705 i, Conf_PongTimeout);
1706 snprintf(msg, sizeof(msg), "Ping timeout: %d seconds", Conf_PongTimeout);
1707 Conn_Close(i, NULL, msg, true);
1709 } else if (My_Connections[i].lastdata <
1710 time(NULL) - Conf_PingTimeout) {
1711 /* We need to send a PING ... */
1712 LogDebug("Connection %d: sending PING ...", i);
1713 My_Connections[i].lastping = time(NULL);
1714 Conn_WriteStr(i, "PING :%s",
1715 Client_ID(Client_ThisServer()));
1718 /* The connection is not fully established yet, so
1719 * we don't do the PING-PONG game here but instead
1720 * disconnect the client after "a short time" if it's
1721 * still not registered. */
1723 if (My_Connections[i].lastdata <
1724 time(NULL) - Conf_PongTimeout) {
1726 ("Unregistered connection %d timed out ...",
1728 Conn_Close(i, NULL, "Timeout", false);
1732 } /* Check_Connections */
1736 Check_Servers( void )
1738 /* Check if we can establish further server links */
1743 /* Check all configured servers */
1744 for( i = 0; i < MAX_SERVERS; i++ ) {
1745 /* Valid outgoing server which isn't already connected or disabled? */
1746 if(( ! Conf_Server[i].host[0] ) || ( ! Conf_Server[i].port > 0 ) ||
1747 ( Conf_Server[i].conn_id > NONE ) || ( Conf_Server[i].flags & CONF_SFLAG_DISABLED ))
1750 /* Is there already a connection in this group? */
1751 if( Conf_Server[i].group > NONE ) {
1752 for (n = 0; n < MAX_SERVERS; n++) {
1753 if (n == i) continue;
1754 if ((Conf_Server[n].conn_id != NONE) &&
1755 (Conf_Server[n].group == Conf_Server[i].group))
1758 if (n < MAX_SERVERS) continue;
1761 /* Check last connect attempt? */
1762 time_now = time(NULL);
1763 if( Conf_Server[i].lasttry > (time_now - Conf_ConnectRetry))
1766 /* Okay, try to connect now */
1767 Conf_Server[i].lasttry = time_now;
1768 Conf_Server[i].conn_id = SERVER_WAIT;
1769 assert(Proc_GetPipeFd(&Conf_Server[i].res_stat) < 0);
1770 Resolve_Name(&Conf_Server[i].res_stat, Conf_Server[i].host, cb_Connect_to_Server);
1772 } /* Check_Servers */
1776 New_Server( int Server , ng_ipaddr_t *dest)
1778 /* Establish new server link */
1779 char ip_str[NG_INET_ADDRSTRLEN];
1780 int af_dest, res, new_sock;
1783 assert( Server > NONE );
1785 if (!ng_ipaddr_tostr_r(dest, ip_str)) {
1786 Log(LOG_WARNING, "New_Server: Could not convert IP to string");
1790 Log( LOG_INFO, "Establishing connection to \"%s\", %s, port %d ... ",
1791 Conf_Server[Server].host, ip_str, Conf_Server[Server].port );
1793 af_dest = ng_ipaddr_af(dest);
1794 new_sock = socket(af_dest, SOCK_STREAM, 0);
1796 Log( LOG_CRIT, "Can't create socket (af %d) : %s!", af_dest, strerror( errno ));
1800 if (!Init_Socket(new_sock))
1803 /* is a bind address configured? */
1804 res = ng_ipaddr_af(&Conf_Server[Server].bind_addr);
1805 /* if yes, bind now. If it fails, warn and let connect() pick a source address */
1806 if (res && bind(new_sock, (struct sockaddr *) &Conf_Server[Server].bind_addr,
1807 ng_ipaddr_salen(&Conf_Server[Server].bind_addr)))
1809 ng_ipaddr_tostr_r(&Conf_Server[Server].bind_addr, ip_str);
1810 Log(LOG_WARNING, "Can't bind socket to %s: %s!", ip_str, strerror(errno));
1812 ng_ipaddr_setport(dest, Conf_Server[Server].port);
1813 res = connect(new_sock, (struct sockaddr *) dest, ng_ipaddr_salen(dest));
1814 if(( res != 0 ) && ( errno != EINPROGRESS )) {
1815 Log( LOG_CRIT, "Can't connect socket: %s!", strerror( errno ));
1820 if (!array_alloc(&My_ConnArray, sizeof(CONNECTION), (size_t)new_sock)) {
1822 "Cannot allocate memory for server connection (socket %d)",
1828 My_Connections = array_start(&My_ConnArray);
1830 assert(My_Connections[new_sock].sock <= 0);
1832 Init_Conn_Struct(new_sock);
1834 ng_ipaddr_tostr_r(dest, ip_str);
1835 c = Client_NewLocal(new_sock, ip_str, CLIENT_UNKNOWNSERVER, false);
1837 Log( LOG_ALERT, "Can't establish connection: can't create client structure!" );
1842 /* Conn_Close() decrements this counter again */
1843 Account_Connection();
1844 Client_SetIntroducer( c, c );
1845 Client_SetToken( c, TOKEN_OUTBOUND );
1847 /* Register connection */
1848 Conf_Server[Server].conn_id = new_sock;
1849 My_Connections[new_sock].sock = new_sock;
1850 My_Connections[new_sock].addr = *dest;
1851 My_Connections[new_sock].client = c;
1852 strlcpy( My_Connections[new_sock].host, Conf_Server[Server].host,
1853 sizeof(My_Connections[new_sock].host ));
1855 /* Register new socket */
1856 if (!io_event_create( new_sock, IO_WANTWRITE, cb_connserver)) {
1857 Log( LOG_ALERT, "io_event_create(): could not add fd %d", strerror(errno));
1858 Conn_Close( new_sock, "io_event_create() failed", NULL, false );
1859 Init_Conn_Struct( new_sock );
1860 Conf_Server[Server].conn_id = NONE;
1863 if (Conf_Server[Server].SSLConnect && !ConnSSL_PrepareConnect( &My_Connections[new_sock],
1864 &Conf_Server[Server] ))
1866 Log(LOG_ALERT, "Could not initialize SSL for outgoing connection");
1867 Conn_Close( new_sock, "Could not initialize SSL for outgoing connection", NULL, false );
1868 Init_Conn_Struct( new_sock );
1869 Conf_Server[Server].conn_id = NONE;
1873 LogDebug("Registered new connection %d on socket %d (%ld in total).",
1874 new_sock, My_Connections[new_sock].sock, NumConnections);
1875 Conn_OPTION_ADD( &My_Connections[new_sock], CONN_ISCONNECTING );
1880 * Initialize connection structure.
1883 Init_Conn_Struct(CONN_ID Idx)
1885 time_t now = time(NULL);
1887 memset(&My_Connections[Idx], 0, sizeof(CONNECTION));
1888 My_Connections[Idx].sock = -1;
1889 My_Connections[Idx].signon = now;
1890 My_Connections[Idx].lastdata = now;
1891 My_Connections[Idx].lastprivmsg = now;
1892 Proc_InitStruct(&My_Connections[Idx].res_stat);
1893 } /* Init_Conn_Struct */
1897 Init_Socket( int Sock )
1899 /* Initialize socket (set options) */
1903 if (!io_setnonblock(Sock)) {
1904 Log( LOG_CRIT, "Can't enable non-blocking mode for socket: %s!", strerror( errno ));
1909 /* Don't block this port after socket shutdown */
1911 if( setsockopt( Sock, SOL_SOCKET, SO_REUSEADDR, &value, (socklen_t)sizeof( value )) != 0 )
1913 Log( LOG_ERR, "Can't set socket option SO_REUSEADDR: %s!", strerror( errno ));
1914 /* ignore this error */
1917 /* Set type of service (TOS) */
1918 #if defined(IPPROTO_IP) && defined(IPTOS_LOWDELAY)
1919 value = IPTOS_LOWDELAY;
1920 LogDebug("Setting IP_TOS on socket %d to IPTOS_LOWDELAY.", Sock);
1921 if (setsockopt(Sock, IPPROTO_IP, IP_TOS, &value,
1922 (socklen_t) sizeof(value))) {
1923 Log(LOG_ERR, "Can't set socket option IP_TOS: %s!",
1925 /* ignore this error */
1934 cb_Connect_to_Server(int fd, UNUSED short events)
1936 /* Read result of resolver sub-process from pipe and start connection */
1939 ng_ipaddr_t dest_addrs[4]; /* we can handle at most 3; but we read up to
1940 four so we can log the 'more than we can handle'
1941 condition. First result is tried immediately, rest
1942 is saved for later if needed. */
1944 LogDebug("Resolver: Got forward lookup callback on fd %d, events %d", fd, events);
1946 for (i=0; i < MAX_SERVERS; i++) {
1947 if (Proc_GetPipeFd(&Conf_Server[i].res_stat) == fd )
1951 if( i >= MAX_SERVERS) {
1952 /* Ops, no matching server found?! */
1954 LogDebug("Resolver: Got Forward Lookup callback for unknown server!?");
1958 /* Read result from pipe */
1959 len = Resolve_Read(&Conf_Server[i].res_stat, dest_addrs, sizeof(dest_addrs));
1963 assert((len % sizeof(ng_ipaddr_t)) == 0);
1965 LogDebug("Got result from resolver: %u structs (%u bytes).", len/sizeof(ng_ipaddr_t), len);
1967 memset(&Conf_Server[i].dst_addr, 0, sizeof(Conf_Server[i].dst_addr));
1968 if (len > sizeof(ng_ipaddr_t)) {
1969 /* more than one address for this hostname, remember them
1970 * in case first address is unreachable/not available */
1971 len -= sizeof(ng_ipaddr_t);
1972 if (len > sizeof(Conf_Server[i].dst_addr)) {
1973 len = sizeof(Conf_Server[i].dst_addr);
1975 "Notice: Resolver returned more IP Addresses for host than we can handle, additional addresses dropped.");
1977 memcpy(&Conf_Server[i].dst_addr, &dest_addrs[1], len);
1980 New_Server(i, dest_addrs);
1981 } /* cb_Read_Forward_Lookup */
1985 cb_Read_Resolver_Result( int r_fd, UNUSED short events )
1987 /* Read result of resolver sub-process from pipe and update the
1988 * apropriate connection/client structure(s): hostname and/or
1989 * IDENT user name.*/
1996 char readbuf[HOST_LEN + 2 + CLIENT_USER_LEN];
1998 char readbuf[HOST_LEN + 1];
2001 LogDebug("Resolver: Got callback on fd %d, events %d", r_fd, events );
2003 /* Search associated connection ... */
2004 for( i = 0; i < Pool_Size; i++ ) {
2005 if(( My_Connections[i].sock != NONE )
2006 && (Proc_GetPipeFd(&My_Connections[i].res_stat) == r_fd))
2009 if( i >= Pool_Size ) {
2010 /* Ops, none found? Probably the connection has already
2011 * been closed!? We'll ignore that ... */
2013 LogDebug("Resolver: Got callback for unknown connection!?");
2017 /* Read result from pipe */
2018 len = Resolve_Read(&My_Connections[i].res_stat, readbuf, sizeof readbuf -1);
2022 readbuf[len] = '\0';
2023 identptr = strchr(readbuf, '\n');
2024 assert(identptr != NULL);
2026 Log( LOG_CRIT, "Resolver: Got malformed result!");
2031 LogDebug("Got result from resolver: \"%s\" (%u bytes read).", readbuf, len);
2032 /* Okay, we got a complete result: this is a host name for outgoing
2033 * connections and a host name and IDENT user name (if enabled) for
2034 * incoming connections.*/
2035 assert ( My_Connections[i].sock >= 0 );
2036 /* Incoming connection. Search client ... */
2037 c = Conn_GetClient( i );
2038 assert( c != NULL );
2040 /* Only update client information of unregistered clients.
2041 * Note: user commands (e. g. WEBIRC) are always read _after_ reading
2042 * the resolver results, so we don't have to worry to override settings
2043 * from these commands here. */
2044 if(Client_Type(c) == CLIENT_UNKNOWN) {
2045 strlcpy(My_Connections[i].host, readbuf,
2046 sizeof(My_Connections[i].host));
2047 Client_SetHostname(c, readbuf);
2051 Log(LOG_INFO, "IDENT lookup for connection %d: \"%s\".", i, identptr);
2052 Client_SetUser(c, identptr, true);
2054 Log(LOG_INFO, "IDENT lookup for connection %d: no result.", i);
2059 else Log( LOG_DEBUG, "Resolver: discarding result for already registered connection %d.", i );
2061 /* Reset penalty time */
2062 Conn_ResetPenalty( i );
2063 } /* cb_Read_Resolver_Result */
2067 * Write a "simple" (error) message to a socket.
2068 * The message is sent without using the connection write buffers, without
2069 * compression/encryption, and even without any error reporting. It is
2070 * designed for error messages of e.g. New_Connection(). */
2072 Simple_Message(int Sock, const char *Msg)
2074 char buf[COMMAND_LEN];
2077 assert(Sock > NONE);
2078 assert(Msg != NULL);
2080 strlcpy(buf, Msg, sizeof buf - 2);
2081 len = strlcat(buf, "\r\n", sizeof buf);
2082 if (write(Sock, buf, len) < 0) {
2083 /* Because this function most probably got called to log
2084 * an error message, any write error is ignored here to
2085 * avoid an endless loop. But casting the result of write()
2086 * to "void" doesn't satisfy the GNU C code attribute
2087 * "warn_unused_result" which is used by some versions of
2088 * glibc (e.g. 2.11.1), therefore this silly error
2089 * "handling" code here :-( */
2092 } /* Simple_Error */
2096 * Get CLIENT structure that belongs to a local connection identified by its
2097 * index number. Each connection belongs to a client by definition, so it is
2098 * not required that the caller checks for NULL return values.
2099 * @param Idx Connection index number
2100 * @return Pointer to CLIENT structure
2103 Conn_GetClient( CONN_ID Idx )
2108 c = array_get(&My_ConnArray, sizeof (CONNECTION), (size_t)Idx);
2110 return c ? c->client : NULL;
2117 * Get information about used SSL chiper.
2118 * @param Idx Connection index number
2119 * @param buf Buffer for returned information text
2120 * @param len Size of return buffer "buf"
2121 * @return true on success, false otherwise
2124 Conn_GetCipherInfo(CONN_ID Idx, char *buf, size_t len)
2128 assert(Idx < (int) array_length(&My_ConnArray, sizeof(CONNECTION)));
2129 return ConnSSL_GetCipherInfo(&My_Connections[Idx], buf, len);
2134 * Check if a connection is SSL-enabled or not.
2135 * @param Idx Connection index number
2136 * @return true if connection is SSL-enabled, false otherwise.
2139 Conn_UsesSSL(CONN_ID Idx)
2143 assert(Idx < (int) array_length(&My_ConnArray, sizeof(CONNECTION)));
2144 return Conn_OPTION_ISSET(&My_Connections[Idx], CONN_SSL);