2 * ngIRCd -- The Next Generation IRC Daemon
3 * Copyright (c)2001-2007 Alexander Barton (alex@barton.de)
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
9 * Please read the file COPYING, README and AUTHORS for more information.
11 * Connection management
20 static char UNUSED id[] = "$Id: conn.c,v 1.220 2007/12/13 01:30:16 fw Exp $";
34 #include <sys/socket.h>
36 #include <sys/types.h>
38 #include <netinet/in.h>
40 #ifdef HAVE_NETINET_IP_H
41 # include <netinet/ip.h>
45 # include <stdint.h> /* e.g. for Mac OS X */
49 # include <tcpd.h> /* for TCP Wrappers */
64 #include "conn-func.h"
70 # include "rendezvous.h"
76 #define SERVER_WAIT (NONE - 1)
79 static bool Handle_Write PARAMS(( CONN_ID Idx ));
80 static bool Conn_Write PARAMS(( CONN_ID Idx, char *Data, size_t Len ));
81 static int New_Connection PARAMS(( int Sock ));
82 static CONN_ID Socket2Index PARAMS(( int Sock ));
83 static void Read_Request PARAMS(( CONN_ID Idx ));
84 static bool Handle_Buffer PARAMS(( CONN_ID Idx ));
85 static void Check_Connections PARAMS(( void ));
86 static void Check_Servers PARAMS(( void ));
87 static void Init_Conn_Struct PARAMS(( CONN_ID Idx ));
88 static bool Init_Socket PARAMS(( int Sock ));
89 static void New_Server PARAMS(( int Server, struct in_addr *dest));
90 static void Simple_Message PARAMS(( int Sock, const char *Msg ));
91 static int Count_Connections PARAMS(( struct sockaddr_in addr ));
92 static int NewListener PARAMS(( const UINT16 Port ));
94 static array My_Listeners;
95 static array My_ConnArray;
98 int allow_severity = LOG_INFO;
99 int deny_severity = LOG_ERR;
102 static void server_login PARAMS((CONN_ID idx));
104 static void cb_Read_Resolver_Result PARAMS(( int sock, UNUSED short what));
105 static void cb_Connect_to_Server PARAMS(( int sock, UNUSED short what));
106 static void cb_clientserver PARAMS((int sock, short what));
109 cb_listen(int sock, short irrelevant)
112 New_Connection( sock );
117 cb_connserver(int sock, UNUSED short what)
121 CONN_ID idx = Socket2Index( sock );
123 LogDebug("cb_connserver wants to write on unknown socket?!");
128 assert( what & IO_WANTWRITE);
130 /* connect() finished, get result. */
131 sock_len = sizeof( err );
132 res = getsockopt( My_Connections[idx].sock, SOL_SOCKET, SO_ERROR, &err, &sock_len );
133 assert( sock_len == sizeof( err ));
135 /* Error while connecting? */
136 if ((res != 0) || (err != 0)) {
138 Log(LOG_CRIT, "getsockopt (connection %d): %s!",
139 idx, strerror(errno));
142 "Can't connect socket to \"%s:%d\" (connection %d): %s!",
143 My_Connections[idx].host,
144 Conf_Server[Conf_GetServer(idx)].port,
147 Conn_Close(idx, "Can't connect!", NULL, false);
151 Conn_OPTION_DEL( &My_Connections[idx], CONN_ISCONNECTING );
157 server_login(CONN_ID idx)
159 Log( LOG_INFO, "Connection %d with \"%s:%d\" established. Now logging in ...", idx,
160 My_Connections[idx].host, Conf_Server[Conf_GetServer( idx )].port );
162 io_event_setcb( My_Connections[idx].sock, cb_clientserver);
163 io_event_add( My_Connections[idx].sock, IO_WANTREAD|IO_WANTWRITE);
165 /* Send PASS and SERVER command to peer */
166 Conn_WriteStr( idx, "PASS %s %s", Conf_Server[Conf_GetServer( idx )].pwd_out, NGIRCd_ProtoID );
167 Conn_WriteStr( idx, "SERVER %s :%s", Conf_ServerName, Conf_ServerInfo );
172 cb_clientserver(int sock, short what)
174 CONN_ID idx = Socket2Index( sock );
177 Log(LOG_WARNING, "WTF: cb_clientserver wants to write on unknown socket?!");
183 if (what & IO_WANTREAD)
186 if (what & IO_WANTWRITE)
194 /* Modul initialisieren: statische Strukturen "ausnullen". */
198 /* Speicher fuer Verbindungs-Pool anfordern */
199 Pool_Size = CONNECTION_POOL;
200 if( Conf_MaxConnections > 0 )
202 /* konfiguriertes Limit beachten */
203 if( Pool_Size > Conf_MaxConnections ) Pool_Size = Conf_MaxConnections;
206 if (!array_alloc(&My_ConnArray, sizeof(CONNECTION), (size_t)Pool_Size)) {
207 Log( LOG_EMERG, "Can't allocate memory! [Conn_Init]" );
211 /* FIXME: My_Connetions/Pool_Size is needed by other parts of the
212 * code; remove them! */
213 My_Connections = (CONNECTION*) array_start(&My_ConnArray);
215 LogDebug("Allocated connection pool for %d items (%ld bytes).",
216 array_length(&My_ConnArray, sizeof( CONNECTION )), array_bytes(&My_ConnArray));
218 assert( array_length(&My_ConnArray, sizeof( CONNECTION )) >= (size_t) Pool_Size);
220 array_free( &My_Listeners );
222 /* Connection-Struktur initialisieren */
223 for( i = 0; i < Pool_Size; i++ ) Init_Conn_Struct( i );
225 /* Global write counter */
233 /* Modul abmelden: alle noch offenen Connections
234 * schliessen und freigeben. */
238 LogDebug("Shutting down all connections ..." );
240 Conn_ExitListeners();
242 /* Sockets schliessen */
243 for( idx = 0; idx < Pool_Size; idx++ ) {
244 if( My_Connections[idx].sock > NONE ) {
245 Conn_Close( idx, NULL, NGIRCd_SignalRestart ?
246 "Server going down (restarting)":"Server going down", true );
250 array_free(&My_ConnArray);
251 My_Connections = NULL;
253 io_library_shutdown();
258 ports_initlisteners(array *a, void (*func)(int,short))
260 unsigned int created = 0;
265 len = array_length(a, sizeof (UINT16));
266 port = array_start(a);
268 fd = NewListener( *port );
273 if (!io_event_create( fd, IO_WANTREAD, func )) {
274 Log( LOG_ERR, "io_event_create(): Could not add listening fd %d (port %u): %s!",
275 fd, (unsigned int) *port, strerror(errno));
289 Conn_InitListeners( void )
291 /* Initialize ports on which the server should accept connections */
293 unsigned int created;
295 if (!io_library_init(CONNECTION_POOL)) {
296 Log(LOG_EMERG, "Cannot initialize IO routines: %s", strerror(errno));
300 created = ports_initlisteners(&Conf_ListenPorts, cb_listen);
303 } /* Conn_InitListeners */
307 Conn_ExitListeners( void )
309 /* Close down all listening sockets */
313 Rendezvous_UnregisterListeners( );
316 arraylen = array_length(&My_Listeners, sizeof (int));
317 Log( LOG_INFO, "Shutting down all listening sockets (%d total)...", arraylen );
318 fd = array_start(&My_Listeners);
323 LogDebug("Listening socket %d closed.", *fd );
326 array_free(&My_Listeners);
327 } /* Conn_ExitListeners */
331 InitSinaddr(struct sockaddr_in *addr, UINT16 Port)
333 struct in_addr inaddr;
335 memset(addr, 0, sizeof(*addr));
336 memset( &inaddr, 0, sizeof(inaddr));
338 addr->sin_family = AF_INET;
339 addr->sin_port = htons(Port);
340 inaddr.s_addr = htonl(INADDR_ANY);
341 addr->sin_addr = inaddr;
346 InitSinaddrListenAddr(struct sockaddr_in *addr, UINT16 Port)
348 struct in_addr inaddr;
350 InitSinaddr(addr, Port);
352 if (!Conf_ListenAddress[0])
355 if (!ngt_IPStrToBin(Conf_ListenAddress, &inaddr)) {
356 Log( LOG_CRIT, "Can't bind to %s:%u: can't convert ip address \"%s\"",
357 Conf_ListenAddress, Port, Conf_ListenAddress);
361 addr->sin_addr = inaddr;
366 /* return new listening port file descriptor or -1 on failure */
368 NewListener( const UINT16 Port )
370 /* Create new listening socket on specified port */
372 struct sockaddr_in addr;
375 char name[CLIENT_ID_LEN], *info;
378 InitSinaddrListenAddr(&addr, Port);
380 addr.sin_family = AF_INET;
381 addr.sin_port = htons( Port );
383 sock = socket( PF_INET, SOCK_STREAM, 0);
385 Log( LOG_CRIT, "Can't create socket: %s!", strerror( errno ));
389 if( ! Init_Socket( sock )) return -1;
391 if (bind(sock, (struct sockaddr *)&addr, (socklen_t)sizeof(addr)) != 0) {
392 Log( LOG_CRIT, "Can't bind socket (port %d) : %s!", Port, strerror( errno ));
397 if( listen( sock, 10 ) != 0 ) {
398 Log( LOG_CRIT, "Can't listen on socket: %s!", strerror( errno ));
403 /* keep fd in list so we can close it when ngircd restarts/shuts down */
404 if (!array_catb( &My_Listeners,(char*) &sock, sizeof(int) )) {
405 Log( LOG_CRIT, "Can't add socket to My_Listeners array: %s!", strerror( errno ));
410 if( Conf_ListenAddress[0]) Log( LOG_INFO, "Now listening on %s:%d (socket %d).", Conf_ListenAddress, Port, sock );
411 else Log( LOG_INFO, "Now listening on 0.0.0.0:%d (socket %d).", Port, sock );
414 /* Get best server description text */
415 if( ! Conf_ServerInfo[0] ) info = Conf_ServerName;
418 /* Use server info string */
420 if( Conf_ServerInfo[0] == '[' )
422 /* Cut off leading hostname part in "[]" */
423 info = strchr( Conf_ServerInfo, ']' );
427 while( *info == ' ' ) info++;
430 if( ! info ) info = Conf_ServerInfo;
433 /* Add port number to description if non-standard */
435 snprintf(name, sizeof name, "%s (port %u)", info,
438 strlcpy(name, info, sizeof name);
440 /* Register service */
441 Rendezvous_Register( name, MDNS_TYPE, Port );
450 /* "Main Loop.": Loop until a signal (for shutdown or restart) arrives.
451 * Call io_dispatch() to check for read/writeable sockets every second
452 * Wait for status change on pending connections (e.g: when the hostname has been resolved)
453 * check for penalty/timeouts
454 * handle input buffers
457 unsigned int wdatalen;
462 while(( ! NGIRCd_SignalQuit ) && ( ! NGIRCd_SignalRestart )) {
466 Rendezvous_Handler( );
469 /* Should the configuration be reloaded? */
470 if (NGIRCd_SignalRehash) {
474 /* Check configured servers and established links */
476 Check_Connections( );
480 /* noch volle Lese-Buffer suchen */
481 for( i = 0; i < Pool_Size; i++ ) {
482 if(( My_Connections[i].sock > NONE ) && ( array_bytes(&My_Connections[i].rbuf) > 0 ) &&
483 ( My_Connections[i].delaytime < t ))
485 /* Kann aus dem Buffer noch ein Befehl extrahiert werden? */
486 if (Handle_Buffer( i )) timeout = false;
490 /* noch volle Schreib-Puffer suchen */
491 for( i = 0; i < Pool_Size; i++ ) {
492 if ( My_Connections[i].sock <= NONE )
495 wdatalen = (unsigned int)array_bytes(&My_Connections[i].wbuf);
498 if (( wdatalen > 0 ) || ( array_bytes(&My_Connections[i].zip.wbuf)> 0 ))
503 /* Socket der Verbindung in Set aufnehmen */
504 io_event_add( My_Connections[i].sock, IO_WANTWRITE );
508 /* von welchen Sockets koennte gelesen werden? */
509 for (i = 0; i < Pool_Size; i++ ) {
510 if ( My_Connections[i].sock <= NONE )
513 if (Resolve_INPROGRESS(&My_Connections[i].res_stat)) {
514 /* wait for completion of Resolver Sub-Process */
515 io_event_del( My_Connections[i].sock, IO_WANTREAD );
519 if ( Conn_OPTION_ISSET( &My_Connections[i], CONN_ISCONNECTING ))
520 continue; /* wait for completion of connect() */
522 if( My_Connections[i].delaytime > t ) {
523 /* Fuer die Verbindung ist eine "Penalty-Zeit" gesetzt */
524 io_event_del( My_Connections[i].sock, IO_WANTREAD );
527 io_event_add( My_Connections[i].sock, IO_WANTREAD );
530 /* (re-)set timeout - tv_sec/usec are undefined after io_dispatch() returns */
532 tv.tv_sec = timeout ? 1 : 0;
534 /* wait for activity */
535 i = io_dispatch( &tv );
536 if (i == -1 && errno != EINTR ) {
537 Log(LOG_EMERG, "Conn_Handler(): io_dispatch(): %s!", strerror(errno));
538 Log(LOG_ALERT, "%s exiting due to fatal errors!", PACKAGE_NAME);
543 if( NGIRCd_SignalQuit ) Log( LOG_NOTICE|LOG_snotice, "Server going down NOW!" );
544 else if( NGIRCd_SignalRestart ) Log( LOG_NOTICE|LOG_snotice, "Server restarting NOW!" );
549 * Write a text string into the socket of a connection.
550 * This function automatically appends CR+LF to the string and validates that
551 * the result is a valid IRC message (oversized messages are shortened, for
552 * example). Then it calls the Conn_Write() function to do the actual sending.
553 * @param Idx Index fo the connection.
554 * @param Format Format string, see printf().
555 * @return true on success, false otherwise.
559 Conn_WriteStr( CONN_ID Idx, char *Format, ... )
562 Conn_WriteStr( Idx, Format, va_alist )
568 char buffer[COMMAND_LEN];
573 assert( Idx > NONE );
574 assert( Format != NULL );
577 va_start( ap, Format );
581 if (vsnprintf( buffer, COMMAND_LEN - 2, Format, ap ) >= COMMAND_LEN - 2 ) {
583 * The string that should be written to the socket is longer
584 * than the allowed size of COMMAND_LEN bytes (including both
585 * the CR and LF characters). This can be caused by the
586 * IRC_WriteXXX() functions when the prefix of this server had
587 * to be added to an already "quite long" command line which
588 * has been received from a regular IRC client, for example.
590 * We are not allowed to send such "oversized" messages to
591 * other servers and clients, see RFC 2812 2.3 and 2813 3.3
592 * ("these messages SHALL NOT exceed 512 characters in length,
593 * counting all characters including the trailing CR-LF").
595 * So we have a big problem here: we should send more bytes
596 * to the network than we are allowed to and we don't know
597 * the originator (any more). The "old" behaviour of blaming
598 * the receiver ("next hop") is a bad idea (it could be just
599 * an other server only routing the message!), so the only
600 * option left is to shorten the string and to hope that the
601 * result is still somewhat useful ...
605 strcpy (buffer + sizeof(buffer) - strlen(CUT_TXTSUFFIX) - 2 - 1,
611 Log(LOG_DEBUG, " -> connection %d: '%s'.", Idx, buffer);
614 len = strlcat( buffer, "\r\n", sizeof( buffer ));
615 ok = Conn_Write(Idx, buffer, len);
616 My_Connections[Idx].msg_out++;
620 } /* Conn_WriteStr */
624 * Append Data to the outbound write buffer of a connection.
625 * @param Idx Index of the connection.
626 * @param Data pointer to the data.
627 * @param Len length of Data.
628 * @return true on success, false otherwise.
631 Conn_Write( CONN_ID Idx, char *Data, size_t Len )
634 size_t writebuf_limit = WRITEBUFFER_LEN;
635 assert( Idx > NONE );
636 assert( Data != NULL );
639 c = Conn_GetClient(Idx);
642 /* Servers do get special write buffer limits, so they can generate
643 * all the messages that are required while peering. */
644 if (Client_Type(c) == CLIENT_SERVER)
645 writebuf_limit = WRITEBUFFER_SLINK_LEN;
647 /* Is the socket still open? A previous call to Conn_Write()
648 * may have closed the connection due to a fatal error.
649 * In this case it is sufficient to return an error, as well. */
650 if( My_Connections[Idx].sock <= NONE ) {
651 LogDebug("Skipped write on closed socket (connection %d).", Idx);
656 if ( Conn_OPTION_ISSET( &My_Connections[Idx], CONN_ZIP )) {
658 * Zip_Buffer() does all the dirty work for us: it flushes
659 * the (pre-)compression buffers if required and handles
660 * all error conditions. */
661 if (!Zip_Buffer(Idx, Data, Len))
667 /* Uncompressed link:
668 * Check if outbound buffer has enough space for the data. */
669 if (array_bytes(&My_Connections[Idx].wbuf) + Len >=
671 /* Buffer is full, flush it. Handle_Write deals with
672 * low-level errors, if any. */
673 if (!Handle_Write(Idx))
677 /* When the write buffer is still too big after flushing it,
678 * the connection will be killed. */
679 if (array_bytes(&My_Connections[Idx].wbuf) + Len >=
682 "Write buffer overflow (connection %d, size %lu byte)!",
684 (unsigned long)array_bytes(&My_Connections[Idx].wbuf));
685 Conn_Close(Idx, "Write buffer overflow!", NULL, false);
689 /* Copy data to write buffer */
690 if (!array_catb(&My_Connections[Idx].wbuf, Data, Len))
693 My_Connections[Idx].bytes_out += Len;
696 /* Adjust global write counter */
704 Conn_Close( CONN_ID Idx, char *LogMsg, char *FwdMsg, bool InformClient )
706 /* Close connection. Open pipes of asyncronous resolver
707 * sub-processes are closed down. */
713 double in_z_k, out_z_k;
717 assert( Idx > NONE );
719 /* Is this link already shutting down? */
720 if( Conn_OPTION_ISSET( &My_Connections[Idx], CONN_ISCLOSING )) {
721 /* Conn_Close() has been called recursively for this link;
722 * probabe reason: Handle_Write() failed -- see below. */
723 LogDebug("Recursive request to close connection: %d", Idx );
727 assert( My_Connections[Idx].sock > NONE );
729 /* Mark link as "closing" */
730 Conn_OPTION_ADD( &My_Connections[Idx], CONN_ISCLOSING );
737 txt = "Reason unknown";
739 Log(LOG_INFO, "Shutting down connection %d (%s) with %s:%d ...", Idx,
740 LogMsg ? LogMsg : FwdMsg, My_Connections[Idx].host,
741 ntohs(My_Connections[Idx].addr.sin_port));
743 /* Search client, if any */
744 c = Conn_GetClient( Idx );
746 /* Should the client be informed? */
749 /* Send statistics to client if registered as user: */
750 if ((c != NULL) && (Client_Type(c) == CLIENT_USER)) {
752 ":%s NOTICE %s :%sConnection statistics: client %.1f kb, server %.1f kb.",
753 Client_ID(Client_ThisServer()), Client_ID(c),
755 (double)My_Connections[Idx].bytes_in / 1024,
756 (double)My_Connections[Idx].bytes_out / 1024);
759 /* Send ERROR to client (see RFC!) */
761 Conn_WriteStr(Idx, "ERROR :%s", FwdMsg);
763 Conn_WriteStr(Idx, "ERROR :Closing connection.");
766 /* Try to write out the write buffer. Note: Handle_Write() eventually
767 * removes the CLIENT structure associated with this connection if an
768 * error occurs! So we have to re-check if there is still an valid
769 * CLIENT structure after calling Handle_Write() ...*/
770 (void)Handle_Write( Idx );
772 /* Search client, if any (re-check!) */
773 c = Conn_GetClient( Idx );
775 /* Shut down socket */
776 if (! io_close(My_Connections[Idx].sock)) {
777 /* Oops, we can't close the socket!? This is ... ugly! */
779 "Error closing connection %d (socket %d) with %s:%d - %s! (ignored)",
780 Idx, My_Connections[Idx].sock, My_Connections[Idx].host,
781 ntohs(My_Connections[Idx].addr.sin_port), strerror(errno));
784 /* Mark socket as invalid: */
785 My_Connections[Idx].sock = NONE;
787 /* If there is still a client, unregister it now */
789 Client_Destroy(c, LogMsg, FwdMsg, true);
791 /* Calculate statistics and log information */
792 in_k = (double)My_Connections[Idx].bytes_in / 1024;
793 out_k = (double)My_Connections[Idx].bytes_out / 1024;
795 if (Conn_OPTION_ISSET( &My_Connections[Idx], CONN_ZIP)) {
796 in_z_k = (double)My_Connections[Idx].zip.bytes_in / 1024;
797 out_z_k = (double)My_Connections[Idx].zip.bytes_out / 1024;
798 /* Make sure that no division by zero can occur during
799 * the calculation of in_p and out_p: in_z_k and out_z_k
800 * are non-zero, that's guaranteed by the protocol until
801 * compression can be enabled. */
806 in_p = (int)(( in_k * 100 ) / in_z_k );
807 out_p = (int)(( out_k * 100 ) / out_z_k );
809 "Connection %d with %s:%d closed (in: %.1fk/%.1fk/%d%%, out: %.1fk/%.1fk/%d%%).",
810 Idx, My_Connections[Idx].host,
811 ntohs(My_Connections[Idx].addr.sin_port),
812 in_k, in_z_k, in_p, out_k, out_z_k, out_p);
818 "Connection %d with %s:%d closed (in: %.1fk, out: %.1fk).",
819 Idx, My_Connections[Idx].host,
820 ntohs(My_Connections[Idx].addr.sin_port),
824 /* cancel running resolver */
825 if (Resolve_INPROGRESS(&My_Connections[Idx].res_stat))
826 Resolve_Shutdown(&My_Connections[Idx].res_stat);
828 /* Servers: Modify time of next connect attempt? */
829 Conf_UnsetServer( Idx );
832 /* Clean up zlib, if link was compressed */
833 if ( Conn_OPTION_ISSET( &My_Connections[Idx], CONN_ZIP )) {
834 inflateEnd( &My_Connections[Idx].zip.in );
835 deflateEnd( &My_Connections[Idx].zip.out );
836 array_free(&My_Connections[Idx].zip.rbuf);
837 array_free(&My_Connections[Idx].zip.wbuf);
841 array_free(&My_Connections[Idx].rbuf);
842 array_free(&My_Connections[Idx].wbuf);
844 /* Clean up connection structure (=free it) */
845 Init_Conn_Struct( Idx );
847 LogDebug("Shutdown of connection %d completed.", Idx );
852 Conn_SyncServerStruct( void )
854 /* Synchronize server structures (connection IDs):
855 * connections <-> configuration */
861 for( i = 0; i < Pool_Size; i++ ) {
862 /* Established connection? */
863 if (My_Connections[i].sock < 0)
866 /* Server connection? */
867 client = Conn_GetClient( i );
868 if(( ! client ) || ( Client_Type( client ) != CLIENT_SERVER )) continue;
870 for( c = 0; c < MAX_SERVERS; c++ )
872 /* Configured server? */
873 if( ! Conf_Server[c].host[0] ) continue;
876 if( strcmp( Conf_Server[c].name, Client_ID( client )) == 0 )
877 Conf_Server[c].conn_id = i;
880 } /* SyncServerStruct */
884 * Send out data of write buffer; connect new sockets.
887 Handle_Write( CONN_ID Idx )
892 assert( Idx > NONE );
893 if ( My_Connections[Idx].sock < 0 ) {
894 LogDebug("Handle_Write() on closed socket, connection %d", Idx);
897 assert( My_Connections[Idx].sock > NONE );
899 wdatalen = array_bytes(&My_Connections[Idx].wbuf );
903 /* Write buffer is empty, so we try to flush the compression
904 * buffer and get some data to work with from there :-) */
908 /* Now the write buffer most probably has changed: */
909 wdatalen = array_bytes(&My_Connections[Idx].wbuf);
914 /* Still no data, fine. */
915 io_event_del(My_Connections[Idx].sock, IO_WANTWRITE );
920 ("Handle_Write() called for connection %d, %ld bytes pending ...",
923 len = write(My_Connections[Idx].sock,
924 array_start(&My_Connections[Idx].wbuf), wdatalen );
927 if (errno == EAGAIN || errno == EINTR)
930 Log(LOG_ERR, "Write error on connection %d (socket %d): %s!",
931 Idx, My_Connections[Idx].sock, strerror(errno));
932 Conn_Close(Idx, "Write error!", NULL, false);
936 /* move any data not yet written to beginning */
937 array_moveleft(&My_Connections[Idx].wbuf, 1, (size_t)len);
944 New_Connection( int Sock )
946 /* Neue Client-Verbindung von Listen-Socket annehmen und
947 * CLIENT-Struktur anlegen. */
950 struct request_info req;
952 struct sockaddr_in new_addr;
953 int new_sock, new_sock_len, new_Pool_Size;
957 assert( Sock > NONE );
958 /* Connection auf Listen-Socket annehmen */
959 new_sock_len = (int)sizeof new_addr;
960 new_sock = accept(Sock, (struct sockaddr *)&new_addr,
961 (socklen_t *)&new_sock_len);
963 Log(LOG_CRIT, "Can't accept connection: %s!", strerror(errno));
968 /* Validate socket using TCP Wrappers */
969 request_init( &req, RQ_DAEMON, PACKAGE_NAME, RQ_FILE, new_sock, RQ_CLIENT_SIN, &new_addr, NULL );
971 if( ! hosts_access( &req ))
974 Log( deny_severity, "Refused connection from %s (by TCP Wrappers)!", inet_ntoa( new_addr.sin_addr ));
975 Simple_Message( new_sock, "ERROR :Connection refused" );
981 /* Socket initialisieren */
982 if (!Init_Socket( new_sock ))
985 /* Check IP-based connection limit */
986 cnt = Count_Connections( new_addr );
987 if(( Conf_MaxConnectionsIP > 0 ) && ( cnt >= Conf_MaxConnectionsIP ))
989 /* Access denied, too many connections from this IP address! */
990 Log( LOG_ERR, "Refused connection from %s: too may connections (%ld) from this IP address!", inet_ntoa( new_addr.sin_addr ), cnt);
991 Simple_Message( new_sock, "ERROR :Connection refused, too many connections from your IP address!" );
996 if( new_sock >= Pool_Size ) {
997 new_Pool_Size = new_sock + 1;
998 /* No free Connection Structures, check if we may accept further connections */
999 if ((( Conf_MaxConnections > 0) && Pool_Size >= Conf_MaxConnections) ||
1000 (new_Pool_Size < Pool_Size))
1002 Log( LOG_ALERT, "Can't accept connection: limit (%d) reached!", Pool_Size );
1003 Simple_Message( new_sock, "ERROR :Connection limit reached" );
1008 if (!array_alloc(&My_ConnArray, sizeof(CONNECTION),
1009 (size_t)new_sock)) {
1010 Log( LOG_EMERG, "Can't allocate memory! [New_Connection]" );
1011 Simple_Message( new_sock, "ERROR: Internal error" );
1015 LogDebug("Bumped connection pool to %ld items (internal: %ld items, %ld bytes)",
1016 new_sock, array_length(&My_ConnArray, sizeof(CONNECTION)), array_bytes(&My_ConnArray));
1018 /* Adjust pointer to new block */
1019 My_Connections = array_start(&My_ConnArray);
1020 while (Pool_Size < new_Pool_Size)
1021 Init_Conn_Struct(Pool_Size++);
1024 /* register callback */
1025 if (!io_event_create( new_sock, IO_WANTREAD, cb_clientserver)) {
1026 Log(LOG_ALERT, "Can't accept connection: io_event_create failed!");
1027 Simple_Message(new_sock, "ERROR :Internal error");
1032 c = Client_NewLocal( new_sock, inet_ntoa( new_addr.sin_addr ), CLIENT_UNKNOWN, false );
1034 Log(LOG_ALERT, "Can't accept connection: can't create client structure!");
1035 Simple_Message(new_sock, "ERROR :Internal error");
1040 Init_Conn_Struct( new_sock );
1041 My_Connections[new_sock].sock = new_sock;
1042 My_Connections[new_sock].addr = new_addr;
1043 My_Connections[new_sock].client = c;
1045 Log( LOG_INFO, "Accepted connection %d from %s:%d on socket %d.", new_sock,
1046 inet_ntoa( new_addr.sin_addr ), ntohs( new_addr.sin_port), Sock );
1048 /* Hostnamen ermitteln */
1049 strlcpy( My_Connections[new_sock].host, inet_ntoa( new_addr.sin_addr ),
1050 sizeof( My_Connections[new_sock].host ));
1052 Client_SetHostname( c, My_Connections[new_sock].host );
1055 Resolve_Addr(&My_Connections[new_sock].res_stat, &new_addr,
1056 My_Connections[new_sock].sock, cb_Read_Resolver_Result);
1058 Conn_SetPenalty(new_sock, 4);
1060 } /* New_Connection */
1064 Socket2Index( int Sock )
1066 /* zum Socket passende Connection suchen */
1068 assert( Sock >= 0 );
1070 if( Sock >= Pool_Size || My_Connections[Sock].sock != Sock ) {
1071 /* die Connection wurde vermutlich (wegen eines
1072 * Fehlers) bereits wieder abgebaut ... */
1073 LogDebug("Socket2Index: can't get connection for socket %d!", Sock);
1077 } /* Socket2Index */
1081 * Read data from the network to the read buffer. If an error occures,
1082 * the socket of this connection will be shut down.
1085 Read_Request( CONN_ID Idx )
1088 char readbuf[READBUFFER_LEN];
1090 assert( Idx > NONE );
1091 assert( My_Connections[Idx].sock > NONE );
1094 if ((array_bytes(&My_Connections[Idx].rbuf) >= READBUFFER_LEN) ||
1095 (array_bytes(&My_Connections[Idx].zip.rbuf) >= READBUFFER_LEN))
1097 if (array_bytes(&My_Connections[Idx].rbuf) >= READBUFFER_LEN)
1100 /* Read buffer is full */
1102 "Receive buffer overflow (connection %d): %d bytes!",
1103 Idx, array_bytes(&My_Connections[Idx].rbuf));
1104 Conn_Close( Idx, "Receive buffer overflow!", NULL, false );
1108 len = read(My_Connections[Idx].sock, readbuf, sizeof(readbuf));
1110 Log(LOG_INFO, "%s:%d (%s) is closing the connection ...",
1111 My_Connections[Idx].host,
1112 ntohs(My_Connections[Idx].addr.sin_port),
1113 inet_ntoa( My_Connections[Idx].addr.sin_addr));
1115 "Socket closed!", "Client closed connection",
1121 if( errno == EAGAIN ) return;
1122 Log(LOG_ERR, "Read error on connection %d (socket %d): %s!",
1123 Idx, My_Connections[Idx].sock, strerror(errno));
1124 Conn_Close(Idx, "Read error!", "Client closed connection",
1129 if (Conn_OPTION_ISSET(&My_Connections[Idx], CONN_ZIP)) {
1130 if (!array_catb(&My_Connections[Idx].zip.rbuf, readbuf,
1133 "Could not append recieved data to zip input buffer (connn %d): %d bytes!",
1135 Conn_Close(Idx, "Receive buffer overflow!", NULL,
1142 if (!array_catb( &My_Connections[Idx].rbuf, readbuf, len)) {
1143 Log( LOG_ERR, "Could not append recieved data to input buffer (connn %d): %d bytes!", Idx, len );
1144 Conn_Close( Idx, "Receive buffer overflow!", NULL, false );
1148 /* Update connection statistics */
1149 My_Connections[Idx].bytes_in += len;
1151 /* Update timestamp of last data received if this connection is
1152 * registered as a user, server or service connection. Don't update
1153 * otherwise, so users have at least Conf_PongTimeout seconds time to
1154 * register with the IRC server -- see Check_Connections().
1155 * Set "lastping", too, so we can handle time shifts backwards ... */
1156 c = Conn_GetClient(Idx);
1157 if (c && (Client_Type(c) == CLIENT_USER
1158 || Client_Type(c) == CLIENT_SERVER
1159 || Client_Type(c) == CLIENT_SERVICE)) {
1160 My_Connections[Idx].lastdata = time(NULL);
1161 My_Connections[Idx].lastping = My_Connections[Idx].lastdata;
1164 /* Look at the data in the (read-) buffer of this connection */
1166 } /* Read_Request */
1170 Handle_Buffer( CONN_ID Idx )
1172 /* Handle Data in Connections Read-Buffer.
1173 * Return true if a reuqest was handled, false otherwise (also returned on errors). */
1185 starttime = time(NULL);
1189 if( My_Connections[Idx].delaytime > starttime) return result;
1191 /* unpack compressed data */
1192 if ( Conn_OPTION_ISSET( &My_Connections[Idx], CONN_ZIP ))
1193 if( ! Unzip_Buffer( Idx )) return false;
1196 if (0 == array_bytes(&My_Connections[Idx].rbuf))
1199 if (!array_cat0_temporary(&My_Connections[Idx].rbuf)) /* make sure buf is NULL terminated */
1202 /* A Complete Request end with CR+LF, see RFC 2812. */
1203 ptr = strstr( array_start(&My_Connections[Idx].rbuf), "\r\n" );
1205 if( ptr ) delta = 2; /* complete request */
1208 /* Check for non-RFC-compliant request (only CR or LF)? Unfortunately,
1209 * there are quite a few clients that do this (incl. "mIRC" :-( */
1210 ptr1 = strchr( array_start(&My_Connections[Idx].rbuf), '\r' );
1211 ptr2 = strchr( array_start(&My_Connections[Idx].rbuf), '\n' );
1213 if( ptr1 && ptr2 ) ptr = ptr1 > ptr2 ? ptr2 : ptr1;
1214 else if( ptr1 ) ptr = ptr1;
1215 else if( ptr2 ) ptr = ptr2;
1222 /* End of request found */
1225 len = ( ptr - (char*) array_start(&My_Connections[Idx].rbuf)) + delta;
1227 if( len > ( COMMAND_LEN - 1 )) {
1228 /* Request must not exceed 512 chars (incl. CR+LF!), see
1229 * RFC 2812. Disconnect Client if this happens. */
1230 Log( LOG_ERR, "Request too long (connection %d): %d bytes (max. %d expected)!",
1231 Idx, array_bytes(&My_Connections[Idx].rbuf), COMMAND_LEN - 1 );
1232 Conn_Close( Idx, NULL, "Request too long", true );
1236 if (len <= 2) { /* request was empty (only '\r\n') */
1237 array_moveleft(&My_Connections[Idx].rbuf, 1, delta); /* delta is either 1 or 2 */
1241 /* remember if stream is already compressed */
1242 old_z = My_Connections[Idx].options & CONN_ZIP;
1245 My_Connections[Idx].msg_in++;
1246 if (!Parse_Request(Idx, (char*)array_start(&My_Connections[Idx].rbuf) ))
1251 array_moveleft(&My_Connections[Idx].rbuf, 1, len);
1252 LogDebug("Connection %d: %d bytes left in read buffer.",
1253 Idx, array_bytes(&My_Connections[Idx].rbuf));
1255 if(( ! old_z ) && ( My_Connections[Idx].options & CONN_ZIP ) &&
1256 ( array_bytes(&My_Connections[Idx].rbuf) > 0 ))
1258 /* The last Command activated Socket-Compression.
1259 * Data that was read after that needs to be copied to Unzip-buf
1260 * for decompression */
1261 if (!array_copy( &My_Connections[Idx].zip.rbuf, &My_Connections[Idx].rbuf ))
1264 array_trunc(&My_Connections[Idx].rbuf);
1265 LogDebug("Moved already received data (%u bytes) to uncompression buffer.",
1266 array_bytes(&My_Connections[Idx].zip.rbuf));
1271 } /* Handle_Buffer */
1275 Check_Connections(void)
1277 /* check if connections are alive. if not, play PING-PONG first.
1278 * if this doesn't help either, disconnect client. */
1282 for (i = 0; i < Pool_Size; i++) {
1283 if (My_Connections[i].sock < 0)
1286 c = Conn_GetClient(i);
1287 if (c && ((Client_Type(c) == CLIENT_USER)
1288 || (Client_Type(c) == CLIENT_SERVER)
1289 || (Client_Type(c) == CLIENT_SERVICE))) {
1290 /* connected User, Server or Service */
1291 if (My_Connections[i].lastping >
1292 My_Connections[i].lastdata) {
1293 /* We already sent a ping */
1294 if (My_Connections[i].lastping <
1295 time(NULL) - Conf_PongTimeout) {
1298 ("Connection %d: Ping timeout: %d seconds.",
1299 i, Conf_PongTimeout);
1300 Conn_Close(i, NULL, "Ping timeout",
1303 } else if (My_Connections[i].lastdata <
1304 time(NULL) - Conf_PingTimeout) {
1305 /* We need to send a PING ... */
1306 LogDebug("Connection %d: sending PING ...", i);
1307 My_Connections[i].lastping = time(NULL);
1308 Conn_WriteStr(i, "PING :%s",
1309 Client_ID(Client_ThisServer()));
1312 /* The connection is not fully established yet, so
1313 * we don't do the PING-PONG game here but instead
1314 * disconnect the client after "a short time" if it's
1315 * still not registered. */
1317 if (My_Connections[i].lastdata <
1318 time(NULL) - Conf_PongTimeout) {
1320 ("Unregistered connection %d timed out ...",
1322 Conn_Close(i, NULL, "Timeout", false);
1326 } /* Check_Connections */
1330 Check_Servers( void )
1332 /* Check if we can establish further server links */
1337 /* Check all configured servers */
1338 for( i = 0; i < MAX_SERVERS; i++ ) {
1339 /* Valid outgoing server which isn't already connected or disabled? */
1340 if(( ! Conf_Server[i].host[0] ) || ( ! Conf_Server[i].port > 0 ) ||
1341 ( Conf_Server[i].conn_id > NONE ) || ( Conf_Server[i].flags & CONF_SFLAG_DISABLED ))
1344 /* Is there already a connection in this group? */
1345 if( Conf_Server[i].group > NONE ) {
1346 for (n = 0; n < MAX_SERVERS; n++) {
1347 if (n == i) continue;
1348 if ((Conf_Server[n].conn_id != NONE) &&
1349 (Conf_Server[n].group == Conf_Server[i].group))
1352 if (n < MAX_SERVERS) continue;
1355 /* Check last connect attempt? */
1356 time_now = time(NULL);
1357 if( Conf_Server[i].lasttry > (time_now - Conf_ConnectRetry))
1360 /* Okay, try to connect now */
1361 Conf_Server[i].lasttry = time_now;
1362 Conf_Server[i].conn_id = SERVER_WAIT;
1363 assert(Resolve_Getfd(&Conf_Server[i].res_stat) < 0);
1364 Resolve_Name(&Conf_Server[i].res_stat, Conf_Server[i].host, cb_Connect_to_Server);
1366 } /* Check_Servers */
1370 New_Server( int Server , struct in_addr *dest)
1372 /* Establish new server link */
1373 struct sockaddr_in local_addr;
1374 struct sockaddr_in new_addr;
1378 assert( Server > NONE );
1380 memset(&new_addr, 0, sizeof( new_addr ));
1381 new_addr.sin_family = AF_INET;
1382 new_addr.sin_addr = *dest;
1383 new_addr.sin_port = htons( Conf_Server[Server].port );
1385 new_sock = socket( PF_INET, SOCK_STREAM, 0 );
1386 if ( new_sock < 0 ) {
1387 Log( LOG_CRIT, "Can't create socket: %s!", strerror( errno ));
1391 if( ! Init_Socket( new_sock )) return;
1393 /* if we fail to bind, just continue and let connect() pick a source address */
1394 InitSinaddr(&local_addr, 0);
1395 local_addr.sin_addr = Conf_Server[Server].bind_addr;
1396 if (bind(new_sock, (struct sockaddr *)&local_addr, (socklen_t)sizeof(local_addr)))
1397 Log(LOG_WARNING, "Can't bind socket to %s: %s!", inet_ntoa(Conf_Server[Server].bind_addr), strerror( errno ));
1399 res = connect(new_sock, (struct sockaddr *)&new_addr,
1400 (socklen_t)sizeof(new_addr));
1401 if(( res != 0 ) && ( errno != EINPROGRESS )) {
1402 Log( LOG_CRIT, "Can't connect socket: %s!", strerror( errno ));
1407 if (!array_alloc(&My_ConnArray, sizeof(CONNECTION), (size_t)new_sock)) {
1409 "Cannot allocate memory for server connection (socket %d)",
1415 My_Connections = array_start(&My_ConnArray);
1417 assert(My_Connections[new_sock].sock <= 0);
1419 Init_Conn_Struct(new_sock);
1421 c = Client_NewLocal( new_sock, inet_ntoa( new_addr.sin_addr ), CLIENT_UNKNOWNSERVER, false );
1423 Log( LOG_ALERT, "Can't establish connection: can't create client structure!" );
1428 Client_SetIntroducer( c, c );
1429 Client_SetToken( c, TOKEN_OUTBOUND );
1431 /* Register connection */
1432 Conf_Server[Server].conn_id = new_sock;
1433 My_Connections[new_sock].sock = new_sock;
1434 My_Connections[new_sock].addr = new_addr;
1435 My_Connections[new_sock].client = c;
1436 strlcpy( My_Connections[new_sock].host, Conf_Server[Server].host,
1437 sizeof(My_Connections[new_sock].host ));
1439 /* Register new socket */
1440 if (!io_event_create( new_sock, IO_WANTWRITE, cb_connserver)) {
1441 Log( LOG_ALERT, "io_event_create(): could not add fd %d", strerror(errno));
1442 Conn_Close( new_sock, "io_event_create() failed", NULL, false );
1443 Init_Conn_Struct( new_sock );
1444 Conf_Server[Server].conn_id = NONE;
1447 LogDebug("Registered new connection %d on socket %d.",
1448 new_sock, My_Connections[new_sock].sock );
1449 Conn_OPTION_ADD( &My_Connections[new_sock], CONN_ISCONNECTING );
1454 * Initialize connection structure.
1457 Init_Conn_Struct(CONN_ID Idx)
1459 time_t now = time(NULL);
1461 memset(&My_Connections[Idx], 0, sizeof(CONNECTION));
1462 My_Connections[Idx].sock = -1;
1463 My_Connections[Idx].signon = now;
1464 My_Connections[Idx].lastdata = now;
1465 My_Connections[Idx].lastprivmsg = now;
1466 Resolve_Init(&My_Connections[Idx].res_stat);
1467 } /* Init_Conn_Struct */
1471 Init_Socket( int Sock )
1473 /* Initialize socket (set options) */
1477 if (!io_setnonblock(Sock)) {
1478 Log( LOG_CRIT, "Can't enable non-blocking mode for socket: %s!", strerror( errno ));
1483 /* Don't block this port after socket shutdown */
1485 if( setsockopt( Sock, SOL_SOCKET, SO_REUSEADDR, &value, (socklen_t)sizeof( value )) != 0 )
1487 Log( LOG_ERR, "Can't set socket option SO_REUSEADDR: %s!", strerror( errno ));
1488 /* ignore this error */
1491 /* Set type of service (TOS) */
1492 #if defined(IP_TOS) && defined(IPTOS_LOWDELAY)
1493 value = IPTOS_LOWDELAY;
1494 LogDebug("Setting option IP_TOS on socket %d to IPTOS_LOWDELAY (%d).", Sock, value );
1495 if( setsockopt( Sock, SOL_IP, IP_TOS, &value, (socklen_t)sizeof( value )) != 0 )
1497 Log( LOG_ERR, "Can't set socket option IP_TOS: %s!", strerror( errno ));
1498 /* ignore this error */
1508 cb_Connect_to_Server(int fd, UNUSED short events)
1510 /* Read result of resolver sub-process from pipe and start connection */
1513 struct in_addr dest_addr;
1514 char readbuf[HOST_LEN + 1];
1516 LogDebug("Resolver: Got forward lookup callback on fd %d, events %d", fd, events);
1518 for (i=0; i < MAX_SERVERS; i++) {
1519 if (Resolve_Getfd(&Conf_Server[i].res_stat) == fd )
1523 if( i >= MAX_SERVERS) {
1524 /* Ops, no matching server found?! */
1526 LogDebug("Resolver: Got Forward Lookup callback for unknown server!?");
1530 /* Read result from pipe */
1531 len = Resolve_Read(&Conf_Server[i].res_stat, readbuf, sizeof(readbuf)-1);
1535 readbuf[len] = '\0';
1536 LogDebug("Got result from resolver: \"%s\" (%u bytes read).", readbuf, len);
1538 if (!ngt_IPStrToBin(readbuf, &dest_addr)) {
1539 Log(LOG_ERR, "Can't connect to \"%s\": can't convert ip address %s!",
1540 Conf_Server[i].host, readbuf);
1544 Log( LOG_INFO, "Establishing connection to \"%s\", %s, port %d ... ",
1545 Conf_Server[i].host, readbuf, Conf_Server[i].port );
1547 New_Server(i, &dest_addr);
1548 } /* cb_Read_Forward_Lookup */
1552 cb_Read_Resolver_Result( int r_fd, UNUSED short events )
1554 /* Read result of resolver sub-process from pipe and update the
1555 * apropriate connection/client structure(s): hostname and/or
1556 * IDENT user name.*/
1563 char readbuf[HOST_LEN + 2 + CLIENT_USER_LEN];
1565 char readbuf[HOST_LEN + 1];
1568 LogDebug("Resolver: Got callback on fd %d, events %d", r_fd, events );
1570 /* Search associated connection ... */
1571 for( i = 0; i < Pool_Size; i++ ) {
1572 if(( My_Connections[i].sock != NONE )
1573 && ( Resolve_Getfd(&My_Connections[i].res_stat) == r_fd ))
1576 if( i >= Pool_Size ) {
1577 /* Ops, none found? Probably the connection has already
1578 * been closed!? We'll ignore that ... */
1580 LogDebug("Resolver: Got callback for unknown connection!?");
1584 /* Read result from pipe */
1585 len = Resolve_Read(&My_Connections[i].res_stat, readbuf, sizeof readbuf -1);
1589 readbuf[len] = '\0';
1590 identptr = strchr(readbuf, '\n');
1591 assert(identptr != NULL);
1593 Log( LOG_CRIT, "Resolver: Got malformed result!");
1598 LogDebug("Got result from resolver: \"%s\" (%u bytes read).", readbuf, len);
1599 /* Okay, we got a complete result: this is a host name for outgoing
1600 * connections and a host name and IDENT user name (if enabled) for
1601 * incoming connections.*/
1602 assert ( My_Connections[i].sock >= 0 );
1603 /* Incoming connection. Search client ... */
1604 c = Conn_GetClient( i );
1605 assert( c != NULL );
1607 /* Only update client information of unregistered clients */
1608 if( Client_Type( c ) == CLIENT_UNKNOWN ) {
1609 strlcpy(My_Connections[i].host, readbuf, sizeof( My_Connections[i].host));
1610 Client_SetHostname( c, readbuf);
1614 Log(LOG_INFO, "IDENT lookup for connection %d: \"%s\".", i, identptr);
1615 Client_SetUser(c, identptr, true);
1617 Log(LOG_INFO, "IDENT lookup for connection %d: no result.", i);
1622 else Log( LOG_DEBUG, "Resolver: discarding result for already registered connection %d.", i );
1624 /* Reset penalty time */
1625 Conn_ResetPenalty( i );
1626 } /* cb_Read_Resolver_Result */
1630 Simple_Message( int Sock, const char *Msg )
1632 char buf[COMMAND_LEN];
1634 /* Write "simple" message to socket, without using compression
1635 * or even the connection write buffers. Used e.g. for error
1636 * messages by New_Connection(). */
1637 assert( Sock > NONE );
1638 assert( Msg != NULL );
1640 strlcpy( buf, Msg, sizeof buf - 2);
1641 len = strlcat( buf, "\r\n", sizeof buf);
1642 (void)write(Sock, buf, len);
1643 } /* Simple_Error */
1647 Count_Connections( struct sockaddr_in addr_in )
1652 for( i = 0; i < Pool_Size; i++ ) {
1653 if(( My_Connections[i].sock > NONE ) && ( My_Connections[i].addr.sin_addr.s_addr == addr_in.sin_addr.s_addr )) cnt++;
1656 } /* Count_Connections */
1660 Conn_GetClient( CONN_ID Idx )
1662 /* return Client-Structure that belongs to the local Connection Idx.
1663 * If none is found, return NULL.
1668 c = array_get(&My_ConnArray, sizeof (CONNECTION), (size_t)Idx);
1672 return c ? c->client : NULL;