2 * ngIRCd -- The Next Generation IRC Daemon
3 * Copyright (c)2001-2005 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.204 2007/04/04 21:52:12 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>
44 #ifdef HAVE_ARPA_INET_H
45 # include <arpa/inet.h>
47 # define PF_INET AF_INET
51 # include <stdint.h> /* e.g. for Mac OS X */
55 # include <tcpd.h> /* for TCP Wrappers */
70 #include "conn-func.h"
76 # include "rendezvous.h"
82 #define SERVER_WAIT (NONE - 1)
85 static bool Handle_Write PARAMS(( CONN_ID Idx ));
86 static int New_Connection PARAMS(( int Sock ));
87 static CONN_ID Socket2Index PARAMS(( int Sock ));
88 static void Read_Request PARAMS(( CONN_ID Idx ));
89 static bool Handle_Buffer PARAMS(( CONN_ID Idx ));
90 static void Check_Connections PARAMS(( void ));
91 static void Check_Servers PARAMS(( void ));
92 static void Init_Conn_Struct PARAMS(( CONN_ID Idx ));
93 static bool Init_Socket PARAMS(( int Sock ));
94 static void New_Server PARAMS(( int Server ));
95 static void Simple_Message PARAMS(( int Sock, const char *Msg ));
96 static int Count_Connections PARAMS(( struct sockaddr_in addr ));
97 static int NewListener PARAMS(( const UINT16 Port ));
99 static array My_Listeners;
100 static array My_ConnArray;
103 int allow_severity = LOG_INFO;
104 int deny_severity = LOG_ERR;
107 static void server_login PARAMS((CONN_ID idx));
109 static void cb_Read_Resolver_Result PARAMS(( int sock, UNUSED short what));
110 static void cb_Connect_to_Server PARAMS(( int sock, UNUSED short what));
111 static void cb_clientserver PARAMS((int sock, short what));
114 cb_listen(int sock, short irrelevant)
117 New_Connection( sock );
122 cb_connserver(int sock, UNUSED short what)
126 CONN_ID idx = Socket2Index( sock );
128 LogDebug("cb_connserver wants to write on unknown socket?!");
133 assert( what & IO_WANTWRITE);
135 /* connect() finished, get result. */
136 sock_len = sizeof( err );
137 res = getsockopt( My_Connections[idx].sock, SOL_SOCKET, SO_ERROR, &err, &sock_len );
138 assert( sock_len == sizeof( err ));
140 /* Error while connecting? */
141 if ((res != 0) || (err != 0)) {
143 Log(LOG_CRIT, "getsockopt (connection %d): %s!",
144 idx, strerror(errno));
147 "Can't connect socket to \"%s:%d\" (connection %d): %s!",
148 My_Connections[idx].host,
149 Conf_Server[Conf_GetServer(idx)].port,
152 Conn_Close(idx, "Can't connect!", NULL, false);
156 Conn_OPTION_DEL( &My_Connections[idx], CONN_ISCONNECTING );
162 server_login(CONN_ID idx)
164 Log( LOG_INFO, "Connection %d with \"%s:%d\" established. Now logging in ...", idx,
165 My_Connections[idx].host, Conf_Server[Conf_GetServer( idx )].port );
167 io_event_setcb( My_Connections[idx].sock, cb_clientserver);
168 io_event_add( My_Connections[idx].sock, IO_WANTREAD|IO_WANTWRITE);
170 /* Send PASS and SERVER command to peer */
171 Conn_WriteStr( idx, "PASS %s %s", Conf_Server[Conf_GetServer( idx )].pwd_out, NGIRCd_ProtoID );
172 Conn_WriteStr( idx, "SERVER %s :%s", Conf_ServerName, Conf_ServerInfo );
177 cb_clientserver(int sock, short what)
179 CONN_ID idx = Socket2Index( sock );
182 Log(LOG_WARNING, "WTF: cb_clientserver wants to write on unknown socket?!");
188 if (what & IO_WANTREAD)
191 if (what & IO_WANTWRITE)
199 /* Modul initialisieren: statische Strukturen "ausnullen". */
203 /* Speicher fuer Verbindungs-Pool anfordern */
204 Pool_Size = CONNECTION_POOL;
205 if( Conf_MaxConnections > 0 )
207 /* konfiguriertes Limit beachten */
208 if( Pool_Size > Conf_MaxConnections ) Pool_Size = Conf_MaxConnections;
211 if (!array_alloc(&My_ConnArray, sizeof(CONNECTION), (size_t)Pool_Size)) {
212 Log( LOG_EMERG, "Can't allocate memory! [Conn_Init]" );
216 /* FIXME: My_Connetions/Pool_Size is needed by other parts of the
217 * code; remove them! */
218 My_Connections = (CONNECTION*) array_start(&My_ConnArray);
220 LogDebug("Allocated connection pool for %d items (%ld bytes).",
221 array_length(&My_ConnArray, sizeof( CONNECTION )), array_bytes(&My_ConnArray));
223 assert( array_length(&My_ConnArray, sizeof( CONNECTION )) >= (size_t) Pool_Size);
225 array_free( &My_Listeners );
227 /* Connection-Struktur initialisieren */
228 for( i = 0; i < Pool_Size; i++ ) Init_Conn_Struct( i );
230 /* Global write counter */
238 /* Modul abmelden: alle noch offenen Connections
239 * schliessen und freigeben. */
243 LogDebug("Shutting down all connections ..." );
245 Conn_ExitListeners();
247 /* Sockets schliessen */
248 for( idx = 0; idx < Pool_Size; idx++ ) {
249 if( My_Connections[idx].sock > NONE ) {
250 Conn_Close( idx, NULL, NGIRCd_SignalRestart ?
251 "Server going down (restarting)":"Server going down", true );
255 array_free(&My_ConnArray);
256 My_Connections = NULL;
258 io_library_shutdown();
263 ports_initlisteners(array *a, void (*func)(int,short))
265 unsigned int created = 0;
270 len = array_length(a, sizeof (UINT16));
271 port = array_start(a);
273 fd = NewListener( *port );
278 if (!io_event_create( fd, IO_WANTREAD, func )) {
279 Log( LOG_ERR, "io_event_create(): Could not add listening fd %d (port %u): %s!",
280 fd, (unsigned int) *port, strerror(errno));
294 Conn_InitListeners( void )
296 /* Initialize ports on which the server should accept connections */
298 unsigned int created;
300 if (!io_library_init(CONNECTION_POOL)) {
301 Log(LOG_EMERG, "Cannot initialize IO routines: %s", strerror(errno));
305 created = ports_initlisteners(&Conf_ListenPorts, cb_listen);
308 } /* Conn_InitListeners */
312 Conn_ExitListeners( void )
314 /* Close down all listening sockets */
318 Rendezvous_UnregisterListeners( );
321 arraylen = array_length(&My_Listeners, sizeof (int));
322 Log( LOG_INFO, "Shutting down all listening sockets (%d total)...", arraylen );
323 fd = array_start(&My_Listeners);
328 LogDebug("Listening socket %d closed.", *fd );
331 array_free(&My_Listeners);
332 } /* Conn_ExitListeners */
335 /* return new listening port file descriptor or -1 on failure */
337 NewListener( const UINT16 Port )
339 /* Create new listening socket on specified port */
341 struct sockaddr_in addr;
342 struct in_addr inaddr;
345 char name[CLIENT_ID_LEN], *info;
348 /* Server-"Listen"-Socket initialisieren */
349 memset( &addr, 0, sizeof( addr ));
350 memset( &inaddr, 0, sizeof( inaddr ));
351 addr.sin_family = (sa_family_t)AF_INET;
352 addr.sin_port = htons( Port );
353 if( Conf_ListenAddress[0] )
355 #ifdef HAVE_INET_ATON
356 if( inet_aton( Conf_ListenAddress, &inaddr ) == 0 )
358 inaddr.s_addr = inet_addr( Conf_ListenAddress );
359 if( inaddr.s_addr == (unsigned)-1 )
362 Log( LOG_CRIT, "Can't listen on %s:%u: can't convert ip address %s!",
363 Conf_ListenAddress, Port, Conf_ListenAddress );
367 else inaddr.s_addr = htonl( INADDR_ANY );
368 addr.sin_addr = inaddr;
370 sock = socket( PF_INET, SOCK_STREAM, 0);
372 Log( LOG_CRIT, "Can't create socket: %s!", strerror( errno ));
376 if( ! Init_Socket( sock )) return -1;
378 if (bind(sock, (struct sockaddr *)&addr, (socklen_t)sizeof(addr)) != 0) {
379 Log( LOG_CRIT, "Can't bind socket (port %d) : %s!", Port, strerror( errno ));
384 if( listen( sock, 10 ) != 0 ) {
385 Log( LOG_CRIT, "Can't listen on socket: %s!", strerror( errno ));
390 /* keep fd in list so we can close it when ngircd restarts/shuts down */
391 if (!array_catb( &My_Listeners,(char*) &sock, sizeof(int) )) {
392 Log( LOG_CRIT, "Can't add socket to My_Listeners array: %s!", strerror( errno ));
397 if( Conf_ListenAddress[0]) Log( LOG_INFO, "Now listening on %s:%d (socket %d).", Conf_ListenAddress, Port, sock );
398 else Log( LOG_INFO, "Now listening on 0.0.0.0:%d (socket %d).", Port, sock );
401 /* Get best server description text */
402 if( ! Conf_ServerInfo[0] ) info = Conf_ServerName;
405 /* Use server info string */
407 if( Conf_ServerInfo[0] == '[' )
409 /* Cut off leading hostname part in "[]" */
410 info = strchr( Conf_ServerInfo, ']' );
414 while( *info == ' ' ) info++;
417 if( ! info ) info = Conf_ServerInfo;
420 /* Add port number to description if non-standard */
422 snprintf(name, sizeof name, "%s (port %u)", info,
425 strlcpy(name, info, sizeof name);
427 /* Register service */
428 Rendezvous_Register( name, MDNS_TYPE, Port );
437 /* "Main Loop.": Loop until a signal (for shutdown or restart) arrives.
438 * Call io_dispatch() to check for read/writeable sockets every second
439 * Wait for status change on pending connections (e.g: when the hostname has been resolved)
440 * check for penalty/timeouts
441 * handle input buffers
444 unsigned int wdatalen;
449 while(( ! NGIRCd_SignalQuit ) && ( ! NGIRCd_SignalRestart )) {
453 Rendezvous_Handler( );
456 /* Should the configuration be reloaded? */
457 if (NGIRCd_SignalRehash) {
461 /* Check configured servers and established links */
463 Check_Connections( );
467 /* noch volle Lese-Buffer suchen */
468 for( i = 0; i < Pool_Size; i++ ) {
469 if(( My_Connections[i].sock > NONE ) && ( array_bytes(&My_Connections[i].rbuf) > 0 ) &&
470 ( My_Connections[i].delaytime < t ))
472 /* Kann aus dem Buffer noch ein Befehl extrahiert werden? */
473 if (Handle_Buffer( i )) timeout = false;
477 /* noch volle Schreib-Puffer suchen */
478 for( i = 0; i < Pool_Size; i++ ) {
479 if ( My_Connections[i].sock <= NONE )
482 wdatalen = (unsigned int)array_bytes(&My_Connections[i].wbuf);
485 if (( wdatalen > 0 ) || ( array_bytes(&My_Connections[i].zip.wbuf)> 0 ))
490 /* Socket der Verbindung in Set aufnehmen */
491 io_event_add( My_Connections[i].sock, IO_WANTWRITE );
495 /* von welchen Sockets koennte gelesen werden? */
496 for (i = 0; i < Pool_Size; i++ ) {
497 if ( My_Connections[i].sock <= NONE )
500 if (Resolve_INPROGRESS(&My_Connections[i].res_stat)) {
501 /* wait for completion of Resolver Sub-Process */
502 io_event_del( My_Connections[i].sock, IO_WANTREAD );
506 if ( Conn_OPTION_ISSET( &My_Connections[i], CONN_ISCONNECTING ))
507 continue; /* wait for completion of connect() */
509 if( My_Connections[i].delaytime > t ) {
510 /* Fuer die Verbindung ist eine "Penalty-Zeit" gesetzt */
511 io_event_del( My_Connections[i].sock, IO_WANTREAD );
514 io_event_add( My_Connections[i].sock, IO_WANTREAD );
517 /* (re-)set timeout - tv_sec/usec are undefined after io_dispatch() returns */
519 tv.tv_sec = timeout ? 1 : 0;
521 /* wait for activity */
522 i = io_dispatch( &tv );
523 if (i == -1 && errno != EINTR ) {
524 Log(LOG_EMERG, "Conn_Handler(): io_dispatch(): %s!", strerror(errno));
525 Log(LOG_ALERT, "%s exiting due to fatal errors!", PACKAGE_NAME);
530 if( NGIRCd_SignalQuit ) Log( LOG_NOTICE|LOG_snotice, "Server going down NOW!" );
531 else if( NGIRCd_SignalRestart ) Log( LOG_NOTICE|LOG_snotice, "Server restarting NOW!" );
536 * Write a text string into the socket of a connection.
537 * This function automatically appends CR+LF to the string and validates that
538 * the result is a valid IRC message (oversized messages are shortened, for
539 * example). Then it calls the Conn_Write() function to do the actual sending.
540 * @param Idx Index fo the connection.
541 * @param Format Format string, see printf().
542 * @return true on success, false otherwise.
546 Conn_WriteStr( CONN_ID Idx, char *Format, ... )
549 Conn_WriteStr( Idx, Format, va_alist )
555 char buffer[COMMAND_LEN];
560 assert( Idx > NONE );
561 assert( Format != NULL );
564 va_start( ap, Format );
568 if (vsnprintf( buffer, COMMAND_LEN - 2, Format, ap ) >= COMMAND_LEN - 2 ) {
570 * The string that should be written to the socket is longer
571 * than the allowed size of COMMAND_LEN bytes (including both
572 * the CR and LF characters). This can be caused by the
573 * IRC_WriteXXX() functions when the prefix of this server had
574 * to be added to an already "quite long" command line which
575 * has been received from a regular IRC client, for example.
577 * We are not allowed to send such "oversized" messages to
578 * other servers and clients, see RFC 2812 2.3 and 2813 3.3
579 * ("these messages SHALL NOT exceed 512 characters in length,
580 * counting all characters including the trailing CR-LF").
582 * So we have a big problem here: we should send more bytes
583 * to the network than we are allowed to and we don't know
584 * the originator (any more). The "old" behaviour of blaming
585 * the receiver ("next hop") is a bad idea (it could be just
586 * an other server only routing the message!), so the only
587 * option left is to shorten the string and to hope that the
588 * result is still somewhat useful ...
592 strcpy (buffer + sizeof(buffer) - strlen(CUT_TXTSUFFIX) - 2 - 1,
598 Log(LOG_DEBUG, " -> connection %d: '%s'.", Idx, buffer);
601 len = strlcat( buffer, "\r\n", sizeof( buffer ));
602 ok = Conn_Write(Idx, buffer, len);
603 My_Connections[Idx].msg_out++;
607 } /* Conn_WriteStr */
611 Conn_Write( CONN_ID Idx, char *Data, size_t Len )
613 /* Daten in Socket schreiben. Bei "fatalen" Fehlern wird
614 * der Client disconnectiert und false geliefert. */
616 assert( Idx > NONE );
617 assert( Data != NULL );
620 /* Ist der entsprechende Socket ueberhaupt noch offen? In einem
621 * "Handler-Durchlauf" kann es passieren, dass dem nicht mehr so
622 * ist, wenn einer von mehreren Conn_Write()'s fehlgeschlagen ist.
623 * In diesem Fall wird hier einfach ein Fehler geliefert. */
624 if( My_Connections[Idx].sock <= NONE ) {
625 LogDebug("Skipped write on closed socket (connection %d).", Idx );
629 /* Pruefen, ob im Schreibpuffer genuegend Platz ist. Ziel ist es,
630 * moeglichts viel im Puffer zu haben und _nicht_ gleich alles auf den
631 * Socket zu schreiben (u.a. wg. Komprimierung). */
632 if( array_bytes(&My_Connections[Idx].wbuf) >= WRITEBUFFER_LEN) {
633 /* Der Puffer ist dummerweise voll. Jetzt versuchen, den Puffer
634 * zu schreiben, wenn das nicht klappt, haben wir ein Problem ... */
635 if( ! Handle_Write( Idx )) return false;
637 /* check again: if our writebuf is twice als large as the initial limit: Kill connection */
638 if( array_bytes(&My_Connections[Idx].wbuf) >= (WRITEBUFFER_LEN*2)) {
639 Log( LOG_NOTICE, "Write buffer overflow (connection %d)!", Idx );
640 Conn_Close( Idx, "Write buffer overflow!", NULL, false );
646 if ( Conn_OPTION_ISSET( &My_Connections[Idx], CONN_ZIP )) {
647 /* Daten komprimieren und in Puffer kopieren */
648 if( ! Zip_Buffer( Idx, Data, Len )) return false;
653 /* Daten in Puffer kopieren */
654 if (!array_catb( &My_Connections[Idx].wbuf, Data, Len ))
657 My_Connections[Idx].bytes_out += Len;
660 /* Adjust global write counter */
668 Conn_Close( CONN_ID Idx, char *LogMsg, char *FwdMsg, bool InformClient )
670 /* Close connection. Open pipes of asyncronous resolver
671 * sub-processes are closed down. */
677 double in_z_k, out_z_k;
681 assert( Idx > NONE );
683 /* Is this link already shutting down? */
684 if( Conn_OPTION_ISSET( &My_Connections[Idx], CONN_ISCLOSING )) {
685 /* Conn_Close() has been called recursively for this link;
686 * probabe reason: Handle_Write() failed -- see below. */
687 LogDebug("Recursive request to close connection: %d", Idx );
691 assert( My_Connections[Idx].sock > NONE );
693 /* Mark link as "closing" */
694 Conn_OPTION_ADD( &My_Connections[Idx], CONN_ISCLOSING );
701 txt = "Reason unknown";
703 Log(LOG_INFO, "Shutting down connection %d (%s) with %s:%d ...", Idx,
704 LogMsg ? LogMsg : FwdMsg, My_Connections[Idx].host,
705 ntohs(My_Connections[Idx].addr.sin_port));
707 /* Search client, if any */
708 c = Conn_GetClient( Idx );
710 /* Should the client be informed? */
713 /* Send statistics to client if registered as user: */
714 if ((c != NULL) && (Client_Type(c) == CLIENT_USER)) {
716 ":%s NOTICE %s :%sConnection statistics: client %.1f kb, server %.1f kb.",
717 Client_ID(Client_ThisServer()), Client_ID(c),
719 (double)My_Connections[Idx].bytes_in / 1024,
720 (double)My_Connections[Idx].bytes_out / 1024);
723 /* Send ERROR to client (see RFC!) */
725 Conn_WriteStr(Idx, "ERROR :%s", FwdMsg);
727 Conn_WriteStr(Idx, "ERROR :Closing connection.");
730 /* Try to write out the write buffer. Note: Handle_Write() eventually
731 * removes the CLIENT structure associated with this connection if an
732 * error occurs! So we have to re-check if there is still an valid
733 * CLIENT structure after calling Handle_Write() ...*/
734 (void)Handle_Write( Idx );
736 /* Search client, if any (re-check!) */
737 c = Conn_GetClient( Idx );
739 /* Shut down socket */
740 if (! io_close(My_Connections[Idx].sock)) {
741 /* Oops, we can't close the socket!? This is ... ugly! */
743 "Error closing connection %d (socket %d) with %s:%d - %s! (ignored)",
744 Idx, My_Connections[Idx].sock, My_Connections[Idx].host,
745 ntohs(My_Connections[Idx].addr.sin_port), strerror(errno));
748 /* Mark socket as invalid: */
749 My_Connections[Idx].sock = NONE;
751 /* If there is still a client, unregister it now */
753 Client_Destroy(c, LogMsg, FwdMsg, true);
755 /* Calculate statistics and log information */
756 in_k = (double)My_Connections[Idx].bytes_in / 1024;
757 out_k = (double)My_Connections[Idx].bytes_out / 1024;
759 if (Conn_OPTION_ISSET( &My_Connections[Idx], CONN_ZIP)) {
760 in_z_k = (double)My_Connections[Idx].zip.bytes_in / 1024;
761 out_z_k = (double)My_Connections[Idx].zip.bytes_out / 1024;
762 /* Make sure that no division by zero can occur during
763 * the calculation of in_p and out_p: in_z_k and out_z_k
764 * are non-zero, that's guaranteed by the protocol until
765 * compression can be enabled. */
770 in_p = (int)(( in_k * 100 ) / in_z_k );
771 out_p = (int)(( out_k * 100 ) / out_z_k );
773 "Connection %d with %s:%d closed (in: %.1fk/%.1fk/%d%%, out: %.1fk/%.1fk/%d%%).",
774 Idx, My_Connections[Idx].host,
775 ntohs(My_Connections[Idx].addr.sin_port),
776 in_k, in_z_k, in_p, out_k, out_z_k, out_p);
782 "Connection %d with %s:%d closed (in: %.1fk, out: %.1fk).",
783 Idx, My_Connections[Idx].host,
784 ntohs(My_Connections[Idx].addr.sin_port),
788 /* cancel running resolver */
789 if (Resolve_INPROGRESS(&My_Connections[Idx].res_stat))
790 Resolve_Shutdown(&My_Connections[Idx].res_stat);
792 /* Servers: Modify time of next connect attempt? */
793 Conf_UnsetServer( Idx );
796 /* Clean up zlib, if link was compressed */
797 if ( Conn_OPTION_ISSET( &My_Connections[Idx], CONN_ZIP )) {
798 inflateEnd( &My_Connections[Idx].zip.in );
799 deflateEnd( &My_Connections[Idx].zip.out );
800 array_free(&My_Connections[Idx].zip.rbuf);
801 array_free(&My_Connections[Idx].zip.wbuf);
805 array_free(&My_Connections[Idx].rbuf);
806 array_free(&My_Connections[Idx].wbuf);
808 /* Clean up connection structure (=free it) */
809 Init_Conn_Struct( Idx );
811 LogDebug("Shutdown of connection %d completed.", Idx );
816 Conn_SyncServerStruct( void )
818 /* Synchronize server structures (connection IDs):
819 * connections <-> configuration */
825 for( i = 0; i < Pool_Size; i++ ) {
826 /* Established connection? */
827 if (My_Connections[i].sock < 0)
830 /* Server connection? */
831 client = Conn_GetClient( i );
832 if(( ! client ) || ( Client_Type( client ) != CLIENT_SERVER )) continue;
834 for( c = 0; c < MAX_SERVERS; c++ )
836 /* Configured server? */
837 if( ! Conf_Server[c].host[0] ) continue;
840 if( strcmp( Conf_Server[c].name, Client_ID( client )) == 0 )
841 Conf_Server[c].conn_id = i;
844 } /* SyncServerStruct */
848 * Send out data of write buffer; connect new sockets.
851 Handle_Write( CONN_ID Idx )
856 assert( Idx > NONE );
857 if ( My_Connections[Idx].sock < 0 ) {
858 LogDebug("Handle_Write() on closed socket, connection %d", Idx);
861 assert( My_Connections[Idx].sock > NONE );
863 wdatalen = array_bytes(&My_Connections[Idx].wbuf );
866 if (wdatalen == 0 && !array_bytes(&My_Connections[Idx].zip.wbuf)) {
867 io_event_del(My_Connections[Idx].sock, IO_WANTWRITE );
871 /* write buffer empty, but not compression buffer?
872 * -> flush compression buffer! */
877 io_event_del(My_Connections[Idx].sock, IO_WANTWRITE );
882 /* Zip_Flush() may have changed the write buffer ... */
883 wdatalen = array_bytes(&My_Connections[Idx].wbuf);
885 ("Handle_Write() called for connection %d, %ld bytes pending ...",
888 len = write(My_Connections[Idx].sock,
889 array_start(&My_Connections[Idx].wbuf), wdatalen );
892 if (errno == EAGAIN || errno == EINTR)
895 Log(LOG_ERR, "Write error on connection %d (socket %d): %s!",
896 Idx, My_Connections[Idx].sock, strerror(errno));
897 Conn_Close(Idx, "Write error!", NULL, false);
901 /* move any data not yet written to beginning */
902 array_moveleft(&My_Connections[Idx].wbuf, 1, (size_t)len);
909 New_Connection( int Sock )
911 /* Neue Client-Verbindung von Listen-Socket annehmen und
912 * CLIENT-Struktur anlegen. */
915 struct request_info req;
917 struct sockaddr_in new_addr;
918 int new_sock, new_sock_len, new_Pool_Size;
922 assert( Sock > NONE );
923 /* Connection auf Listen-Socket annehmen */
924 new_sock_len = (int)sizeof new_addr;
925 new_sock = accept(Sock, (struct sockaddr *)&new_addr,
926 (socklen_t *)&new_sock_len);
928 Log(LOG_CRIT, "Can't accept connection: %s!", strerror(errno));
933 /* Validate socket using TCP Wrappers */
934 request_init( &req, RQ_DAEMON, PACKAGE_NAME, RQ_FILE, new_sock, RQ_CLIENT_SIN, &new_addr, NULL );
936 if( ! hosts_access( &req ))
939 Log( deny_severity, "Refused connection from %s (by TCP Wrappers)!", inet_ntoa( new_addr.sin_addr ));
940 Simple_Message( new_sock, "ERROR :Connection refused" );
946 /* Socket initialisieren */
947 if (!Init_Socket( new_sock ))
950 /* Check IP-based connection limit */
951 cnt = Count_Connections( new_addr );
952 if(( Conf_MaxConnectionsIP > 0 ) && ( cnt >= Conf_MaxConnectionsIP ))
954 /* Access denied, too many connections from this IP address! */
955 Log( LOG_ERR, "Refused connection from %s: too may connections (%ld) from this IP address!", inet_ntoa( new_addr.sin_addr ), cnt);
956 Simple_Message( new_sock, "ERROR :Connection refused, too many connections from your IP address!" );
961 if( new_sock >= Pool_Size ) {
962 new_Pool_Size = new_sock + 1;
963 /* No free Connection Structures, check if we may accept further connections */
964 if ((( Conf_MaxConnections > 0) && Pool_Size >= Conf_MaxConnections) ||
965 (new_Pool_Size < Pool_Size))
967 Log( LOG_ALERT, "Can't accept connection: limit (%d) reached!", Pool_Size );
968 Simple_Message( new_sock, "ERROR :Connection limit reached" );
973 if (!array_alloc(&My_ConnArray, sizeof(CONNECTION),
975 Log( LOG_EMERG, "Can't allocate memory! [New_Connection]" );
976 Simple_Message( new_sock, "ERROR: Internal error" );
980 LogDebug("Bumped connection pool to %ld items (internal: %ld items, %ld bytes)",
981 new_sock, array_length(&My_ConnArray, sizeof(CONNECTION)), array_bytes(&My_ConnArray));
983 /* Adjust pointer to new block */
984 My_Connections = array_start(&My_ConnArray);
985 while (Pool_Size < new_Pool_Size)
986 Init_Conn_Struct(Pool_Size++);
989 /* register callback */
990 if (!io_event_create( new_sock, IO_WANTREAD, cb_clientserver)) {
991 Log(LOG_ALERT, "Can't accept connection: io_event_create failed!");
992 Simple_Message(new_sock, "ERROR :Internal error");
997 c = Client_NewLocal( new_sock, inet_ntoa( new_addr.sin_addr ), CLIENT_UNKNOWN, false );
999 Log(LOG_ALERT, "Can't accept connection: can't create client structure!");
1000 Simple_Message(new_sock, "ERROR :Internal error");
1005 Init_Conn_Struct( new_sock );
1006 My_Connections[new_sock].sock = new_sock;
1007 My_Connections[new_sock].addr = new_addr;
1008 My_Connections[new_sock].client = c;
1010 Log( LOG_INFO, "Accepted connection %d from %s:%d on socket %d.", new_sock,
1011 inet_ntoa( new_addr.sin_addr ), ntohs( new_addr.sin_port), Sock );
1013 /* Hostnamen ermitteln */
1014 strlcpy( My_Connections[new_sock].host, inet_ntoa( new_addr.sin_addr ),
1015 sizeof( My_Connections[new_sock].host ));
1017 Client_SetHostname( c, My_Connections[new_sock].host );
1019 Resolve_Addr(&My_Connections[new_sock].res_stat, &new_addr,
1020 My_Connections[new_sock].sock, cb_Read_Resolver_Result);
1022 /* Penalty-Zeit setzen */
1023 Conn_SetPenalty( new_sock, 4 );
1025 } /* New_Connection */
1029 Socket2Index( int Sock )
1031 /* zum Socket passende Connection suchen */
1033 assert( Sock >= 0 );
1035 if( Sock >= Pool_Size || My_Connections[Sock].sock != Sock ) {
1036 /* die Connection wurde vermutlich (wegen eines
1037 * Fehlers) bereits wieder abgebaut ... */
1038 LogDebug("Socket2Index: can't get connection for socket %d!", Sock);
1042 } /* Socket2Index */
1046 Read_Request( CONN_ID Idx )
1048 /* Daten von Socket einlesen und entsprechend behandeln.
1049 * Tritt ein Fehler auf, so wird der Socket geschlossen. */
1055 assert( Idx > NONE );
1056 assert( My_Connections[Idx].sock > NONE );
1059 if (( array_bytes(&My_Connections[Idx].rbuf) >= READBUFFER_LEN ) ||
1060 ( array_bytes(&My_Connections[Idx].zip.rbuf) >= ZREADBUFFER_LEN ))
1062 if ( array_bytes(&My_Connections[Idx].rbuf) >= READBUFFER_LEN )
1065 /* Der Lesepuffer ist voll */
1066 Log( LOG_ERR, "Receive buffer overflow (connection %d): %d bytes!", Idx,
1067 array_bytes(&My_Connections[Idx].rbuf));
1068 Conn_Close( Idx, "Receive buffer overflow!", NULL, false );
1072 len = read( My_Connections[Idx].sock, readbuf, sizeof readbuf -1 );
1074 Log( LOG_INFO, "%s:%d (%s) is closing the connection ...",
1075 My_Connections[Idx].host, ntohs( My_Connections[Idx].addr.sin_port),
1076 inet_ntoa( My_Connections[Idx].addr.sin_addr ));
1077 Conn_Close( Idx, "Socket closed!", "Client closed connection", false );
1082 if( errno == EAGAIN ) return;
1083 Log( LOG_ERR, "Read error on connection %d (socket %d): %s!", Idx,
1084 My_Connections[Idx].sock, strerror( errno ));
1085 Conn_Close( Idx, "Read error!", "Client closed connection", false );
1089 if (Conn_OPTION_ISSET(&My_Connections[Idx], CONN_ZIP)) {
1090 if (!array_catb(&My_Connections[Idx].zip.rbuf, readbuf,
1093 "Could not append recieved data to zip input buffer (connn %d): %d bytes!",
1095 Conn_Close(Idx, "Receive buffer overflow!", NULL,
1103 if (!array_cats( &My_Connections[Idx].rbuf, readbuf )) {
1104 Log( LOG_ERR, "Could not append recieved data to input buffer (connn %d): %d bytes!", Idx, len );
1105 Conn_Close( Idx, "Receive buffer overflow!", NULL, false );
1109 /* Update connection statistics */
1110 My_Connections[Idx].bytes_in += len;
1112 /* Update timestamp of last data received if this connection is
1113 * registered as a user, server or service connection. Don't update
1114 * otherwise, so users have at least Conf_PongTimeout seconds time to
1115 * register with the IRC server -- see Check_Connections().
1116 * Set "lastping", too, so we can handle time shifts backwards ... */
1117 c = Conn_GetClient(Idx);
1118 if (c && (Client_Type(c) == CLIENT_USER
1119 || Client_Type(c) == CLIENT_SERVER
1120 || Client_Type(c) == CLIENT_SERVICE)) {
1121 My_Connections[Idx].lastdata = time(NULL);
1122 My_Connections[Idx].lastping = My_Connections[Idx].lastdata;
1125 /* Look at the data in the (read-) buffer of this connection */
1127 } /* Read_Request */
1131 Handle_Buffer( CONN_ID Idx )
1133 /* Handle Data in Connections Read-Buffer.
1134 * Return true if a reuqest was handled, false otherwise (also returned on errors). */
1146 starttime = time(NULL);
1150 if( My_Connections[Idx].delaytime > starttime) return result;
1152 /* unpack compressed data */
1153 if ( Conn_OPTION_ISSET( &My_Connections[Idx], CONN_ZIP ))
1154 if( ! Unzip_Buffer( Idx )) return false;
1157 if (0 == array_bytes(&My_Connections[Idx].rbuf))
1160 if (!array_cat0_temporary(&My_Connections[Idx].rbuf)) /* make sure buf is NULL terminated */
1163 /* A Complete Request end with CR+LF, see RFC 2812. */
1164 ptr = strstr( array_start(&My_Connections[Idx].rbuf), "\r\n" );
1166 if( ptr ) delta = 2; /* complete request */
1169 /* Check for non-RFC-compliant request (only CR or LF)? Unfortunately,
1170 * there are quite a few clients that do this (incl. "mIRC" :-( */
1171 ptr1 = strchr( array_start(&My_Connections[Idx].rbuf), '\r' );
1172 ptr2 = strchr( array_start(&My_Connections[Idx].rbuf), '\n' );
1174 if( ptr1 && ptr2 ) ptr = ptr1 > ptr2 ? ptr2 : ptr1;
1175 else if( ptr1 ) ptr = ptr1;
1176 else if( ptr2 ) ptr = ptr2;
1183 /* End of request found */
1186 len = ( ptr - (char*) array_start(&My_Connections[Idx].rbuf)) + delta;
1188 if( len > ( COMMAND_LEN - 1 )) {
1189 /* Request must not exceed 512 chars (incl. CR+LF!), see
1190 * RFC 2812. Disconnect Client if this happens. */
1191 Log( LOG_ERR, "Request too long (connection %d): %d bytes (max. %d expected)!",
1192 Idx, array_bytes(&My_Connections[Idx].rbuf), COMMAND_LEN - 1 );
1193 Conn_Close( Idx, NULL, "Request too long", true );
1197 if (len <= 2) { /* request was empty (only '\r\n') */
1198 array_moveleft(&My_Connections[Idx].rbuf, 1, delta); /* delta is either 1 or 2 */
1202 /* remember if stream is already compressed */
1203 old_z = My_Connections[Idx].options & CONN_ZIP;
1206 My_Connections[Idx].msg_in++;
1207 if (!Parse_Request(Idx, (char*)array_start(&My_Connections[Idx].rbuf) ))
1212 array_moveleft(&My_Connections[Idx].rbuf, 1, len);
1213 LogDebug("Connection %d: %d bytes left in read buffer.",
1214 Idx, array_bytes(&My_Connections[Idx].rbuf));
1216 if(( ! old_z ) && ( My_Connections[Idx].options & CONN_ZIP ) &&
1217 ( array_bytes(&My_Connections[Idx].rbuf) > 0 ))
1219 /* The last Command activated Socket-Compression.
1220 * Data that was read after that needs to be copied to Unzip-buf
1221 * for decompression */
1222 if( array_bytes(&My_Connections[Idx].rbuf)> ZREADBUFFER_LEN ) {
1223 Log( LOG_ALERT, "Connection %d: No space left in unzip buf (need %u bytes)!",
1224 Idx, array_bytes(&My_Connections[Idx].rbuf ));
1227 if (!array_copy( &My_Connections[Idx].zip.rbuf, &My_Connections[Idx].rbuf ))
1230 array_trunc(&My_Connections[Idx].rbuf);
1231 LogDebug("Moved already received data (%u bytes) to uncompression buffer.",
1232 array_bytes(&My_Connections[Idx].zip.rbuf));
1237 } /* Handle_Buffer */
1241 Check_Connections(void)
1243 /* check if connections are alive. if not, play PING-PONG first.
1244 * if this doesn't help either, disconnect client. */
1248 for (i = 0; i < Pool_Size; i++) {
1249 if (My_Connections[i].sock < 0)
1252 c = Conn_GetClient(i);
1253 if (c && ((Client_Type(c) == CLIENT_USER)
1254 || (Client_Type(c) == CLIENT_SERVER)
1255 || (Client_Type(c) == CLIENT_SERVICE))) {
1256 /* connected User, Server or Service */
1257 if (My_Connections[i].lastping >
1258 My_Connections[i].lastdata) {
1259 /* We already sent a ping */
1260 if (My_Connections[i].lastping <
1261 time(NULL) - Conf_PongTimeout) {
1264 ("Connection %d: Ping timeout: %d seconds.",
1265 i, Conf_PongTimeout);
1266 Conn_Close(i, NULL, "Ping timeout",
1269 } else if (My_Connections[i].lastdata <
1270 time(NULL) - Conf_PingTimeout) {
1271 /* We need to send a PING ... */
1272 LogDebug("Connection %d: sending PING ...", i);
1273 My_Connections[i].lastping = time(NULL);
1274 Conn_WriteStr(i, "PING :%s",
1275 Client_ID(Client_ThisServer()));
1278 /* The connection is not fully established yet, so
1279 * we don't do the PING-PONG game here but instead
1280 * disconnect the client after "a short time" if it's
1281 * still not registered. */
1283 if (My_Connections[i].lastdata <
1284 time(NULL) - Conf_PongTimeout) {
1286 ("Unregistered connection %d timed out ...",
1288 Conn_Close(i, NULL, "Timeout", false);
1292 } /* Check_Connections */
1296 Check_Servers( void )
1298 /* Check if we can establish further server links */
1303 /* Check all configured servers */
1304 for( i = 0; i < MAX_SERVERS; i++ ) {
1305 /* Valid outgoing server which isn't already connected or disabled? */
1306 if(( ! Conf_Server[i].host[0] ) || ( ! Conf_Server[i].port > 0 ) ||
1307 ( Conf_Server[i].conn_id > NONE ) || ( Conf_Server[i].flags & CONF_SFLAG_DISABLED ))
1310 /* Is there already a connection in this group? */
1311 if( Conf_Server[i].group > NONE ) {
1312 for (n = 0; n < MAX_SERVERS; n++) {
1313 if (n == i) continue;
1314 if ((Conf_Server[n].conn_id > NONE) &&
1315 (Conf_Server[n].group == Conf_Server[i].group))
1318 if (n < MAX_SERVERS) continue;
1321 /* Check last connect attempt? */
1322 time_now = time(NULL);
1323 if( Conf_Server[i].lasttry > (time_now - Conf_ConnectRetry))
1326 /* Okay, try to connect now */
1327 Conf_Server[i].lasttry = time_now;
1328 assert(Resolve_Getfd(&Conf_Server[i].res_stat) < 0);
1329 Resolve_Name(&Conf_Server[i].res_stat, Conf_Server[i].host, cb_Connect_to_Server);
1331 } /* Check_Servers */
1335 New_Server( int Server )
1337 /* Establish new server link */
1339 struct sockaddr_in new_addr;
1340 struct in_addr inaddr;
1344 assert( Server > NONE );
1346 Log( LOG_INFO, "Establishing connection to \"%s\", %s, port %d ... ", Conf_Server[Server].host,
1347 Conf_Server[Server].ip, Conf_Server[Server].port );
1349 #ifdef HAVE_INET_ATON
1350 if( inet_aton( Conf_Server[Server].ip, &inaddr ) == 0 )
1352 memset( &inaddr, 0, sizeof( inaddr ));
1353 inaddr.s_addr = inet_addr( Conf_Server[Server].ip );
1354 if( inaddr.s_addr == (unsigned)-1 )
1357 Log( LOG_ERR, "Can't connect to \"%s\": can't convert ip address %s!",
1358 Conf_Server[Server].host, Conf_Server[Server].ip );
1362 memset( &new_addr, 0, sizeof( new_addr ));
1363 new_addr.sin_family = (sa_family_t)AF_INET;
1364 new_addr.sin_addr = inaddr;
1365 new_addr.sin_port = htons( Conf_Server[Server].port );
1367 new_sock = socket( PF_INET, SOCK_STREAM, 0 );
1368 if ( new_sock < 0 ) {
1369 Log( LOG_CRIT, "Can't create socket: %s!", strerror( errno ));
1373 if( ! Init_Socket( new_sock )) return;
1375 res = connect(new_sock, (struct sockaddr *)&new_addr,
1376 (socklen_t)sizeof(new_addr));
1377 if(( res != 0 ) && ( errno != EINPROGRESS )) {
1378 Log( LOG_CRIT, "Can't connect socket: %s!", strerror( errno ));
1383 if (!array_alloc(&My_ConnArray, sizeof(CONNECTION), (size_t)new_sock)) {
1385 "Cannot allocate memory for server connection (socket %d)",
1391 My_Connections = array_start(&My_ConnArray);
1393 assert(My_Connections[new_sock].sock <= 0);
1395 Init_Conn_Struct(new_sock);
1397 c = Client_NewLocal( new_sock, inet_ntoa( new_addr.sin_addr ), CLIENT_UNKNOWNSERVER, false );
1399 Log( LOG_ALERT, "Can't establish connection: can't create client structure!" );
1404 Client_SetIntroducer( c, c );
1405 Client_SetToken( c, TOKEN_OUTBOUND );
1407 /* Register connection */
1408 Conf_Server[Server].conn_id = new_sock;
1409 My_Connections[new_sock].sock = new_sock;
1410 My_Connections[new_sock].addr = new_addr;
1411 My_Connections[new_sock].client = c;
1412 strlcpy( My_Connections[new_sock].host, Conf_Server[Server].host,
1413 sizeof(My_Connections[new_sock].host ));
1415 /* Register new socket */
1416 if (!io_event_create( new_sock, IO_WANTWRITE, cb_connserver)) {
1417 Log( LOG_ALERT, "io_event_create(): could not add fd %d", strerror(errno));
1418 Conn_Close( new_sock, "io_event_create() failed", NULL, false );
1419 Init_Conn_Struct( new_sock );
1420 Conf_Server[Server].conn_id = NONE;
1423 LogDebug("Registered new connection %d on socket %d.",
1424 new_sock, My_Connections[new_sock].sock );
1425 Conn_OPTION_ADD( &My_Connections[new_sock], CONN_ISCONNECTING );
1430 Init_Conn_Struct( CONN_ID Idx )
1432 time_t now = time( NULL );
1433 /* Connection-Struktur initialisieren */
1435 memset( &My_Connections[Idx], 0, sizeof ( CONNECTION ));
1436 My_Connections[Idx].sock = -1;
1437 My_Connections[Idx].lastdata = now;
1438 My_Connections[Idx].lastprivmsg = now;
1439 Resolve_Init(&My_Connections[Idx].res_stat);
1440 } /* Init_Conn_Struct */
1444 Init_Socket( int Sock )
1446 /* Initialize socket (set options) */
1450 if (!io_setnonblock(Sock)) {
1451 Log( LOG_CRIT, "Can't enable non-blocking mode for socket: %s!", strerror( errno ));
1456 /* Don't block this port after socket shutdown */
1458 if( setsockopt( Sock, SOL_SOCKET, SO_REUSEADDR, &value, (socklen_t)sizeof( value )) != 0 )
1460 Log( LOG_ERR, "Can't set socket option SO_REUSEADDR: %s!", strerror( errno ));
1461 /* ignore this error */
1464 /* Set type of service (TOS) */
1465 #if defined(IP_TOS) && defined(IPTOS_LOWDELAY)
1466 value = IPTOS_LOWDELAY;
1467 LogDebug("Setting option IP_TOS on socket %d to IPTOS_LOWDELAY (%d).", Sock, value );
1468 if( setsockopt( Sock, SOL_IP, IP_TOS, &value, (socklen_t)sizeof( value )) != 0 )
1470 Log( LOG_ERR, "Can't set socket option IP_TOS: %s!", strerror( errno ));
1471 /* ignore this error */
1481 cb_Connect_to_Server(int fd, UNUSED short events)
1483 /* Read result of resolver sub-process from pipe and start connection */
1486 char readbuf[HOST_LEN + 1];
1488 LogDebug("Resolver: Got forward lookup callback on fd %d, events %d", fd, events);
1490 for (i=0; i < MAX_SERVERS; i++) {
1491 if (Resolve_Getfd(&Conf_Server[i].res_stat) == fd )
1495 if( i >= MAX_SERVERS) {
1496 /* Ops, no matching server found?! */
1498 LogDebug("Resolver: Got Forward Lookup callback for unknown server!?");
1502 /* Read result from pipe */
1503 len = Resolve_Read(&Conf_Server[i].res_stat, readbuf, sizeof readbuf -1);
1507 readbuf[len] = '\0';
1508 LogDebug("Got result from resolver: \"%s\" (%u bytes read).", readbuf, len);
1509 strlcpy( Conf_Server[i].ip, readbuf, sizeof( Conf_Server[i].ip ));
1513 } /* cb_Read_Forward_Lookup */
1517 cb_Read_Resolver_Result( int r_fd, UNUSED short events )
1519 /* Read result of resolver sub-process from pipe and update the
1520 * apropriate connection/client structure(s): hostname and/or
1521 * IDENT user name.*/
1528 char readbuf[HOST_LEN + 2 + CLIENT_USER_LEN];
1530 char readbuf[HOST_LEN + 1];
1533 LogDebug("Resolver: Got callback on fd %d, events %d", r_fd, events );
1535 /* Search associated connection ... */
1536 for( i = 0; i < Pool_Size; i++ ) {
1537 if(( My_Connections[i].sock != NONE )
1538 && ( Resolve_Getfd(&My_Connections[i].res_stat) == r_fd ))
1541 if( i >= Pool_Size ) {
1542 /* Ops, none found? Probably the connection has already
1543 * been closed!? We'll ignore that ... */
1545 LogDebug("Resolver: Got callback for unknown connection!?");
1549 /* Read result from pipe */
1550 len = Resolve_Read(&My_Connections[i].res_stat, readbuf, sizeof readbuf -1);
1554 readbuf[len] = '\0';
1555 identptr = strchr(readbuf, '\n');
1556 assert(identptr != NULL);
1558 Log( LOG_CRIT, "Resolver: Got malformed result!");
1563 LogDebug("Got result from resolver: \"%s\" (%u bytes read).", readbuf, len);
1564 /* Okay, we got a complete result: this is a host name for outgoing
1565 * connections and a host name and IDENT user name (if enabled) for
1566 * incoming connections.*/
1567 assert ( My_Connections[i].sock >= 0 );
1568 /* Incoming connection. Search client ... */
1569 c = Conn_GetClient( i );
1570 assert( c != NULL );
1572 /* Only update client information of unregistered clients */
1573 if( Client_Type( c ) == CLIENT_UNKNOWN ) {
1574 strlcpy(My_Connections[i].host, readbuf, sizeof( My_Connections[i].host));
1575 Client_SetHostname( c, readbuf);
1579 Log( LOG_INFO, "IDENT lookup for connection %ld: \"%s\".", i, identptr);
1580 Client_SetUser( c, identptr, true );
1582 Log( LOG_INFO, "IDENT lookup for connection %ld: no result.", i );
1587 else Log( LOG_DEBUG, "Resolver: discarding result for already registered connection %d.", i );
1589 /* Reset penalty time */
1590 Conn_ResetPenalty( i );
1591 } /* cb_Read_Resolver_Result */
1595 Simple_Message( int Sock, const char *Msg )
1597 char buf[COMMAND_LEN];
1599 /* Write "simple" message to socket, without using compression
1600 * or even the connection write buffers. Used e.g. for error
1601 * messages by New_Connection(). */
1602 assert( Sock > NONE );
1603 assert( Msg != NULL );
1605 strlcpy( buf, Msg, sizeof buf - 2);
1606 len = strlcat( buf, "\r\n", sizeof buf);
1607 (void)write(Sock, buf, len);
1608 } /* Simple_Error */
1612 Count_Connections( struct sockaddr_in addr_in )
1617 for( i = 0; i < Pool_Size; i++ ) {
1618 if(( My_Connections[i].sock > NONE ) && ( My_Connections[i].addr.sin_addr.s_addr == addr_in.sin_addr.s_addr )) cnt++;
1621 } /* Count_Connections */
1625 Conn_GetClient( CONN_ID Idx )
1627 /* return Client-Structure that belongs to the local Connection Idx.
1628 * If none is found, return NULL.
1633 c = array_get(&My_ConnArray, sizeof (CONNECTION), (size_t)Idx);
1637 return c ? c->client : NULL;