2 * ngIRCd -- The Next Generation IRC Daemon
3 * Copyright (c)2001,2002 by 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
17 static char UNUSED id[] = "$Id: conn.c,v 1.111 2002/12/30 00:01:45 alex Exp $";
28 #include <sys/socket.h>
30 #include <sys/types.h>
32 #include <netinet/in.h>
34 #ifdef HAVE_ARPA_INET_H
35 #include <arpa/inet.h>
37 #define PF_INET AF_INET
41 #include <stdint.h> /* u.a. fuer Mac OS X */
63 #define SERVER_WAIT (NONE - 1)
67 typedef struct _ZipData
69 z_stream in; /* "Handle" for input stream */
70 z_stream out; /* "Handle" for output stream */
71 CHAR rbuf[READBUFFER_LEN]; /* Read buffer */
72 INT rdatalen; /* Length of data in read buffer (compressed) */
73 CHAR wbuf[WRITEBUFFER_LEN]; /* Write buffer */
74 INT wdatalen; /* Length of data in write buffer (uncompressed) */
75 LONG bytes_in, bytes_out; /* Counter for statistics (uncompressed!) */
80 typedef struct _Connection
82 INT sock; /* Socket handle */
83 struct sockaddr_in addr; /* Client address */
84 RES_STAT *res_stat; /* Status of resolver process, if any */
85 CHAR host[HOST_LEN]; /* Hostname */
86 CHAR rbuf[READBUFFER_LEN]; /* Read buffer */
87 INT rdatalen; /* Length of data in read buffer */
88 CHAR wbuf[WRITEBUFFER_LEN]; /* Write buffer */
89 INT wdatalen; /* Length of data in write buffer */
90 time_t starttime; /* Start time of link */
91 time_t lastdata; /* Last activity */
92 time_t lastping; /* Last PING */
93 time_t lastprivmsg; /* Last PRIVMSG */
94 time_t delaytime; /* Ignore link ("penalty") */
95 LONG bytes_in, bytes_out; /* Received and sent bytes */
96 LONG msg_in, msg_out; /* Received and sent IRC messages */
97 INT flag; /* Flag (see "irc-write" module) */
98 INT options; /* Link options */
100 ZIPDATA zip; /* Compression information */
105 LOCAL VOID Handle_Read PARAMS(( INT sock ));
106 LOCAL BOOLEAN Handle_Write PARAMS(( CONN_ID Idx ));
107 LOCAL VOID New_Connection PARAMS(( INT Sock ));
108 LOCAL CONN_ID Socket2Index PARAMS(( INT Sock ));
109 LOCAL VOID Read_Request PARAMS(( CONN_ID Idx ));
110 LOCAL BOOLEAN Try_Write PARAMS(( CONN_ID Idx ));
111 LOCAL BOOLEAN Handle_Buffer PARAMS(( CONN_ID Idx ));
112 LOCAL VOID Check_Connections PARAMS(( VOID ));
113 LOCAL VOID Check_Servers PARAMS(( VOID ));
114 LOCAL VOID Init_Conn_Struct PARAMS(( LONG Idx ));
115 LOCAL BOOLEAN Init_Socket PARAMS(( INT Sock ));
116 LOCAL VOID New_Server PARAMS(( INT Server, CONN_ID Idx ));
117 LOCAL VOID Read_Resolver_Result PARAMS(( INT r_fd ));
120 LOCAL BOOLEAN Zip_Buffer PARAMS(( CONN_ID Idx, CHAR *Data, INT Len ));
121 LOCAL BOOLEAN Zip_Flush PARAMS(( CONN_ID Idx ));
122 LOCAL BOOLEAN Unzip_Buffer PARAMS(( CONN_ID Idx ));
126 LOCAL fd_set My_Listeners;
127 LOCAL fd_set My_Sockets;
128 LOCAL fd_set My_Connects;
130 LOCAL CONNECTION *My_Connections;
131 LOCAL LONG Pool_Size, WCounter;
137 /* Modul initialisieren: statische Strukturen "ausnullen". */
141 /* Speicher fuer Verbindungs-Pool anfordern */
142 Pool_Size = CONNECTION_POOL;
143 if( Conf_MaxConnections > 0 )
145 /* konfiguriertes Limit beachten */
146 if( Pool_Size > Conf_MaxConnections ) Pool_Size = Conf_MaxConnections;
148 My_Connections = malloc( sizeof( CONNECTION ) * Pool_Size );
149 if( ! My_Connections )
151 /* Speicher konnte nicht alloziert werden! */
152 Log( LOG_EMERG, "Can't allocate memory! [Conn_Init]" );
155 Log( LOG_DEBUG, "Allocted connection pool for %ld items (%ld bytes).", Pool_Size, sizeof( CONNECTION ) * Pool_Size );
157 /* zu Beginn haben wir keine Verbindungen */
158 FD_ZERO( &My_Listeners );
159 FD_ZERO( &My_Sockets );
160 FD_ZERO( &My_Connects );
162 /* Groesster File-Descriptor fuer select() */
165 /* Connection-Struktur initialisieren */
166 for( i = 0; i < Pool_Size; i++ ) Init_Conn_Struct( i );
168 /* Global write counter */
176 /* Modul abmelden: alle noch offenen Connections
177 * schliessen und freigeben. */
182 /* Sockets schliessen */
183 Log( LOG_DEBUG, "Shutting down all connections ..." );
184 for( i = 0; i < Conn_MaxFD + 1; i++ )
186 if( FD_ISSET( i, &My_Sockets ))
188 for( idx = 0; idx < Pool_Size; idx++ )
190 if( My_Connections[idx].sock == i ) break;
192 if( FD_ISSET( i, &My_Listeners ))
195 Log( LOG_DEBUG, "Listening socket %d closed.", i );
197 else if( FD_ISSET( i, &My_Connects ))
200 Log( LOG_DEBUG, "Connection %d closed during creation (socket %d).", idx, i );
202 else if( idx < Pool_Size )
204 if( NGIRCd_SignalRestart ) Conn_Close( idx, NULL, "Server going down (restarting)", TRUE );
205 else Conn_Close( idx, NULL, "Server going down", TRUE );
209 Log( LOG_WARNING, "Closing unknown connection %d ...", i );
215 free( My_Connections );
216 My_Connections = NULL;
222 Conn_InitListeners( VOID )
224 /* Ports, auf denen der Server Verbindungen entgegennehmen
225 * soll, initialisieren */
230 for( i = 0; i < Conf_ListenPorts_Count; i++ )
232 if( Conn_NewListener( Conf_ListenPorts[i] )) created++;
233 else Log( LOG_ERR, "Can't listen on port %u!", Conf_ListenPorts[i] );
236 } /* Conn_InitListeners */
240 Conn_ExitListeners( VOID )
242 /* Alle "Listen-Sockets" schliessen */
246 Log( LOG_INFO, "Shutting down all listening sockets ..." );
247 for( i = 0; i < Conn_MaxFD + 1; i++ )
249 if( FD_ISSET( i, &My_Sockets ) && FD_ISSET( i, &My_Listeners ))
252 Log( LOG_DEBUG, "Listening socket %d closed.", i );
255 } /* Conn_ExitListeners */
259 Conn_NewListener( CONST UINT Port )
261 /* Neuen Listen-Socket erzeugen: der Server wartet dann auf
262 * dem angegebenen Port auf Verbindungen. Kann der Listen-
263 * Socket nicht erteugt werden, so wird NULL geliefert.*/
265 struct sockaddr_in addr;
268 /* Server-"Listen"-Socket initialisieren */
269 memset( &addr, 0, sizeof( addr ));
270 addr.sin_family = AF_INET;
271 addr.sin_port = htons( Port );
272 addr.sin_addr.s_addr = htonl( INADDR_ANY );
274 /* Socket erzeugen */
275 sock = socket( PF_INET, SOCK_STREAM, 0);
278 Log( LOG_CRIT, "Can't create socket: %s!", strerror( errno ));
282 if( ! Init_Socket( sock )) return FALSE;
285 if( bind( sock, (struct sockaddr *)&addr, (socklen_t)sizeof( addr )) != 0 )
287 Log( LOG_CRIT, "Can't bind socket: %s!", strerror( errno ));
292 /* in "listen mode" gehen :-) */
293 if( listen( sock, 10 ) != 0 )
295 Log( LOG_CRIT, "Can't listen on soecket: %s!", strerror( errno ));
300 /* Neuen Listener in Strukturen einfuegen */
301 FD_SET( sock, &My_Listeners );
302 FD_SET( sock, &My_Sockets );
304 if( sock > Conn_MaxFD ) Conn_MaxFD = sock;
306 Log( LOG_INFO, "Now listening on port %d (socket %d).", Port, sock );
309 } /* Conn_NewListener */
315 /* "Hauptschleife": Aktive Verbindungen ueberwachen. Folgende Aktionen
316 * werden dabei durchgefuehrt, bis der Server terminieren oder neu
319 * - neue Verbindungen annehmen,
320 * - Server-Verbindungen aufbauen,
321 * - geschlossene Verbindungen loeschen,
322 * - volle Schreibpuffer versuchen zu schreiben,
323 * - volle Lesepuffer versuchen zu verarbeiten,
324 * - Antworten von Resolver Sub-Prozessen annehmen.
327 fd_set read_sockets, write_sockets;
333 start = time( NULL );
334 while(( ! NGIRCd_SignalQuit ) && ( ! NGIRCd_SignalRestart ))
338 /* Should the configuration be reloaded? */
339 if( NGIRCd_SignalRehash ) NGIRCd_Rehash( );
341 /* Check configured servers and established links */
343 Check_Connections( );
345 /* noch volle Lese-Buffer suchen */
346 for( i = 0; i < Pool_Size; i++ )
348 if(( My_Connections[i].sock > NONE ) && ( My_Connections[i].rdatalen > 0 ))
350 /* Kann aus dem Buffer noch ein Befehl extrahiert werden? */
351 if( Handle_Buffer( i )) timeout = FALSE;
355 /* noch volle Schreib-Puffer suchen */
356 FD_ZERO( &write_sockets );
357 for( i = 0; i < Pool_Size; i++ )
360 if(( My_Connections[i].sock > NONE ) && (( My_Connections[i].wdatalen > 0 ) || ( My_Connections[i].zip.wdatalen > 0 )))
362 if(( My_Connections[i].sock > NONE ) && ( My_Connections[i].wdatalen > 0 ))
365 /* Socket der Verbindung in Set aufnehmen */
366 FD_SET( My_Connections[i].sock, &write_sockets );
369 /* Sockets mit im Aufbau befindlichen ausgehenden Verbindungen suchen */
370 for( i = 0; i < Pool_Size; i++ )
372 if(( My_Connections[i].sock > NONE ) && ( FD_ISSET( My_Connections[i].sock, &My_Connects ))) FD_SET( My_Connections[i].sock, &write_sockets );
375 /* von welchen Sockets koennte gelesen werden? */
377 read_sockets = My_Sockets;
378 for( i = 0; i < Pool_Size; i++ )
380 if(( My_Connections[i].sock > NONE ) && ( My_Connections[i].host[0] == '\0' ))
382 /* Hier muss noch auf den Resolver Sub-Prozess gewartet werden */
383 FD_CLR( My_Connections[i].sock, &read_sockets );
385 if(( My_Connections[i].sock > NONE ) && ( FD_ISSET( My_Connections[i].sock, &My_Connects )))
387 /* Hier laeuft noch ein asyncrones connect() */
388 FD_CLR( My_Connections[i].sock, &read_sockets );
390 if( My_Connections[i].delaytime > t )
392 /* Fuer die Verbindung ist eine "Penalty-Zeit" gesetzt */
393 FD_CLR( My_Connections[i].sock, &read_sockets );
394 FD_CLR( My_Connections[i].sock, &write_sockets );
397 for( i = 0; i < Conn_MaxFD + 1; i++ )
399 /* Pipes von Resolver Sub-Prozessen aufnehmen */
400 if( FD_ISSET( i, &Resolver_FDs ))
402 FD_SET( i, &read_sockets );
406 /* Timeout initialisieren */
408 if( timeout ) tv.tv_sec = TIME_RES;
411 /* Auf Aktivitaet warten */
412 i = select( Conn_MaxFD + 1, &read_sockets, &write_sockets, NULL, &tv );
415 /* keine Veraenderung an den Sockets */
420 /* Fehler (z.B. Interrupt) */
423 Log( LOG_EMERG, "Conn_Handler(): select(): %s!", strerror( errno ));
424 Log( LOG_ALERT, "%s exiting due to fatal errors!", PACKAGE );
430 /* Koennen Daten geschrieben werden? */
431 for( i = 0; i < Conn_MaxFD + 1; i++ )
433 if( ! FD_ISSET( i, &write_sockets )) continue;
435 /* Es kann geschrieben werden ... */
436 idx = Socket2Index( i );
437 if( idx == NONE ) continue;
439 if( ! Handle_Write( idx ))
441 /* Fehler beim Schreiben! Diesen Socket nun
442 * auch aus dem Read-Set entfernen: */
443 FD_CLR( i, &read_sockets );
447 /* Daten zum Lesen vorhanden? */
448 for( i = 0; i < Conn_MaxFD + 1; i++ )
450 if( FD_ISSET( i, &read_sockets )) Handle_Read( i );
454 if( NGIRCd_SignalQuit ) Log( LOG_NOTICE|LOG_snotice, "Server going down NOW!" );
455 else if( NGIRCd_SignalRestart ) Log( LOG_NOTICE|LOG_snotice, "Server restarting NOW!" );
461 Conn_WriteStr( CONN_ID Idx, CHAR *Format, ... )
464 Conn_WriteStr( Idx, Format, va_alist )
470 /* String in Socket schreiben. CR+LF wird von dieser Funktion
471 * automatisch angehaengt. Im Fehlerfall wird dir Verbindung
472 * getrennt und FALSE geliefert. */
474 CHAR buffer[COMMAND_LEN];
478 assert( Idx > NONE );
479 assert( Format != NULL );
482 va_start( ap, Format );
486 if( vsnprintf( buffer, COMMAND_LEN - 2, Format, ap ) == COMMAND_LEN - 2 )
488 Log( LOG_CRIT, "Text too long to send (connection %d)!", Idx );
489 Conn_Close( Idx, "Text too long to send!", NULL, FALSE );
494 if( NGIRCd_Sniffer ) Log( LOG_DEBUG, " -> connection %d: '%s'.", Idx, buffer );
497 strlcat( buffer, "\r\n", sizeof( buffer ));
498 ok = Conn_Write( Idx, buffer, strlen( buffer ));
499 My_Connections[Idx].msg_out++;
503 } /* Conn_WriteStr */
507 Conn_Write( CONN_ID Idx, CHAR *Data, INT Len )
509 /* Daten in Socket schreiben. Bei "fatalen" Fehlern wird
510 * der Client disconnectiert und FALSE geliefert. */
512 assert( Idx > NONE );
513 assert( Data != NULL );
516 /* Ist der entsprechende Socket ueberhaupt noch offen? In einem
517 * "Handler-Durchlauf" kann es passieren, dass dem nicht mehr so
518 * ist, wenn einer von mehreren Conn_Write()'s fehlgeschlagen ist.
519 * In diesem Fall wird hier einfach ein Fehler geliefert. */
520 if( My_Connections[Idx].sock <= NONE )
522 Log( LOG_DEBUG, "Skipped write on closed socket (connection %d).", Idx );
526 /* Pruefen, ob im Schreibpuffer genuegend Platz ist. Ziel ist es,
527 * moeglichts viel im Puffer zu haben und _nicht_ gleich alles auf den
528 * Socket zu schreiben (u.a. wg. Komprimierung). */
529 if( WRITEBUFFER_LEN - My_Connections[Idx].wdatalen - Len <= 0 )
531 /* Der Puffer ist dummerweise voll. Jetzt versuchen, den Puffer
532 * zu schreiben, wenn das nicht klappt, haben wir ein Problem ... */
533 if( ! Try_Write( Idx )) return FALSE;
535 /* nun neu pruefen: */
536 if( WRITEBUFFER_LEN - My_Connections[Idx].wdatalen - Len <= 0 )
538 Log( LOG_NOTICE, "Write buffer overflow (connection %d)!", Idx );
539 Conn_Close( Idx, "Write buffer overflow!", NULL, FALSE );
545 if( My_Connections[Idx].options & CONN_ZIP )
547 /* Daten komprimieren und in Puffer kopieren */
548 if( ! Zip_Buffer( Idx, Data, Len )) return FALSE;
553 /* Daten in Puffer kopieren */
554 memcpy( My_Connections[Idx].wbuf + My_Connections[Idx].wdatalen, Data, Len );
555 My_Connections[Idx].wdatalen += Len;
556 My_Connections[Idx].bytes_out += Len;
559 /* Adjust global write counter */
567 Conn_Close( CONN_ID Idx, CHAR *LogMsg, CHAR *FwdMsg, BOOLEAN InformClient )
569 /* Close connection. Open pipes of asyncronous resolver
570 * sub-processes are closed down. */
575 DOUBLE in_z_k, out_z_k;
579 assert( Idx > NONE );
580 assert( My_Connections[Idx].sock > NONE );
582 /* Search client, if any */
583 c = Client_GetFromConn( Idx );
585 /* Should the client be informed? */
589 /* Send statistics to client if registered as user: */
590 if(( c != NULL ) && ( Client_Type( c ) == CLIENT_USER ))
592 Conn_WriteStr( Idx, "NOTICE %s :%sConnection statistics: client %.1f kb, server %.1f kb.", Client_ThisServer( ), NOTICE_TXTPREFIX, (DOUBLE)My_Connections[Idx].bytes_in / 1024, (DOUBLE)My_Connections[Idx].bytes_out / 1024 );
596 /* Send ERROR to client (see RFC!) */
597 if( FwdMsg ) Conn_WriteStr( Idx, "ERROR :%s", FwdMsg );
598 else Conn_WriteStr( Idx, "ERROR :Closing connection." );
599 if( My_Connections[Idx].sock == NONE ) return;
602 /* Try to write out the write buffer */
605 /* Shut down socket */
606 if( close( My_Connections[Idx].sock ) != 0 )
608 /* Oops, we can't close the socket!? This is fatal! */
609 Log( LOG_EMERG, "Error closing connection %d (socket %d) with %s:%d - %s!", Idx, My_Connections[Idx].sock, My_Connections[Idx].host, ntohs( My_Connections[Idx].addr.sin_port), strerror( errno ));
610 Log( LOG_ALERT, "%s exiting due to fatal errors!", PACKAGE );
614 /* Mark socket as invalid: */
615 FD_CLR( My_Connections[Idx].sock, &My_Sockets );
616 FD_CLR( My_Connections[Idx].sock, &My_Connects );
617 My_Connections[Idx].sock = NONE;
619 /* If there is still a client, unregister it now */
620 if( c ) Client_Destroy( c, LogMsg, FwdMsg, TRUE );
622 /* Calculate statistics and log information */
623 in_k = (DOUBLE)My_Connections[Idx].bytes_in / 1024;
624 out_k = (DOUBLE)My_Connections[Idx].bytes_out / 1024;
626 if( My_Connections[Idx].options & CONN_ZIP )
628 in_z_k = (DOUBLE)My_Connections[Idx].zip.bytes_in / 1024;
629 out_z_k = (DOUBLE)My_Connections[Idx].zip.bytes_out / 1024;
630 in_p = (INT)(( in_k * 100 ) / in_z_k );
631 out_p = (INT)(( out_k * 100 ) / out_z_k );
632 Log( LOG_INFO, "Connection %d with %s:%d closed (in: %.1fk/%.1fk/%d%%, out: %.1fk/%.1fk/%d%%).", Idx, My_Connections[Idx].host, ntohs( My_Connections[Idx].addr.sin_port ), in_k, in_z_k, in_p, out_k, out_z_k, out_p );
637 Log( LOG_INFO, "Connection %d with %s:%d closed (in: %.1fk, out: %.1fk).", Idx, My_Connections[Idx].host, ntohs( My_Connections[Idx].addr.sin_port ), in_k, out_k );
640 /* Is there a resolver sub-process running? */
641 if( My_Connections[Idx].res_stat )
643 /* Free resolver structures */
644 FD_CLR( My_Connections[Idx].res_stat->pipe[0], &Resolver_FDs );
645 close( My_Connections[Idx].res_stat->pipe[0] );
646 close( My_Connections[Idx].res_stat->pipe[1] );
647 free( My_Connections[Idx].res_stat );
650 /* Servers: Modify time of next connect attempt? */
651 Conf_UnsetServer( Idx );
654 /* Clean up zlib, if link was compressed */
655 if( Conn_Options( Idx ) & CONN_ZIP )
657 inflateEnd( &My_Connections[Idx].zip.in );
658 deflateEnd( &My_Connections[Idx].zip.out );
662 /* Clean up connection structure (=free it) */
663 Init_Conn_Struct( Idx );
668 Conn_UpdateIdle( CONN_ID Idx )
670 /* Idle-Timer zuruecksetzen */
672 assert( Idx > NONE );
673 My_Connections[Idx].lastprivmsg = time( NULL );
678 Conn_GetIdle( CONN_ID Idx )
680 /* Idle-Time einer Verbindung liefern (in Sekunden) */
682 assert( Idx > NONE );
683 return time( NULL ) - My_Connections[Idx].lastprivmsg;
688 Conn_LastPing( CONN_ID Idx )
690 /* Zeitpunkt des letzten PING liefern */
692 assert( Idx > NONE );
693 return My_Connections[Idx].lastping;
694 } /* Conn_LastPing */
698 Conn_SetPenalty( CONN_ID Idx, time_t Seconds )
700 /* Penalty-Delay fuer eine Verbindung (in Sekunden) setzen;
701 * waehrend dieser Zeit wird der entsprechende Socket vom Server
702 * bei Lese-Operationen komplett ignoriert. Der Delay kann mit
703 * dieser Funktion nur erhoeht, nicht aber verringert werden. */
707 assert( Idx > NONE );
708 assert( Seconds >= 0 );
710 t = time( NULL ) + Seconds;
711 if( t > My_Connections[Idx].delaytime ) My_Connections[Idx].delaytime = t;
712 } /* Conn_SetPenalty */
716 Conn_ResetPenalty( CONN_ID Idx )
718 assert( Idx > NONE );
719 My_Connections[Idx].delaytime = 0;
720 } /* Conn_ResetPenalty */
724 Conn_ClearFlags( VOID )
726 /* Alle Connection auf "nicht-markiert" setzen */
730 for( i = 0; i < Pool_Size; i++ ) My_Connections[i].flag = 0;
731 } /* Conn_ClearFlags */
735 Conn_Flag( CONN_ID Idx )
737 /* Ist eine Connection markiert (TRUE) oder nicht? */
739 assert( Idx > NONE );
740 return My_Connections[Idx].flag;
745 Conn_SetFlag( CONN_ID Idx, INT Flag )
747 /* Connection markieren */
749 assert( Idx > NONE );
750 My_Connections[Idx].flag = Flag;
757 /* Connection-Struktur der ersten Verbindung liefern;
758 * Ist keine Verbindung vorhanden, wird NONE geliefert. */
762 for( i = 0; i < Pool_Size; i++ )
764 if( My_Connections[i].sock != NONE ) return i;
771 Conn_Next( CONN_ID Idx )
773 /* Naechste Verbindungs-Struktur liefern; existiert keine
774 * weitere, so wird NONE geliefert. */
778 assert( Idx > NONE );
780 for( i = Idx + 1; i < Pool_Size; i++ )
782 if( My_Connections[i].sock != NONE ) return i;
789 Conn_SetOption( CONN_ID Idx, INT Option )
791 /* Option fuer Verbindung setzen.
792 * Initial sind alle Optionen _nicht_ gesetzt. */
794 assert( Idx > NONE );
795 assert( Option != 0 );
797 My_Connections[Idx].options |= Option;
798 } /* Conn_SetOption */
802 Conn_UnsetOption( CONN_ID Idx, INT Option )
804 /* Option fuer Verbindung loeschen */
806 assert( Idx > NONE );
807 assert( Option != 0 );
809 My_Connections[Idx].options &= ~Option;
810 } /* Conn_UnsetOption */
814 Conn_Options( CONN_ID Idx )
816 assert( Idx > NONE );
817 return My_Connections[Idx].options;
824 Conn_InitZip( CONN_ID Idx )
826 /* Kompression fuer Link initialisieren */
828 assert( Idx > NONE );
830 My_Connections[Idx].zip.in.avail_in = 0;
831 My_Connections[Idx].zip.in.total_in = 0;
832 My_Connections[Idx].zip.in.total_out = 0;
833 My_Connections[Idx].zip.in.zalloc = NULL;
834 My_Connections[Idx].zip.in.zfree = NULL;
835 My_Connections[Idx].zip.in.data_type = Z_ASCII;
837 if( inflateInit( &My_Connections[Idx].zip.in ) != Z_OK )
840 Log( LOG_ALERT, "Can't initialize compression on connection %d (zlib inflate)!", Idx );
844 My_Connections[Idx].zip.out.total_in = 0;
845 My_Connections[Idx].zip.out.total_in = 0;
846 My_Connections[Idx].zip.out.zalloc = NULL;
847 My_Connections[Idx].zip.out.zfree = NULL;
848 My_Connections[Idx].zip.out.data_type = Z_ASCII;
850 if( deflateInit( &My_Connections[Idx].zip.out, Z_DEFAULT_COMPRESSION ) != Z_OK )
853 Log( LOG_ALERT, "Can't initialize compression on connection %d (zlib deflate)!", Idx );
857 My_Connections[Idx].zip.bytes_in = My_Connections[Idx].bytes_in;
858 My_Connections[Idx].zip.bytes_out = My_Connections[Idx].bytes_out;
860 Log( LOG_INFO, "Enabled link compression (zlib) on connection %d.", Idx );
861 Conn_SetOption( Idx, CONN_ZIP );
868 Conn_SendBytesZip( CONN_ID Idx )
870 /* Anzahl gesendeter Bytes (komprimiert!) liefern */
872 assert( Idx > NONE );
873 return My_Connections[Idx].zip.bytes_out;
874 } /* Conn_SendBytesZip */
878 Conn_RecvBytesZip( CONN_ID Idx )
880 /* Anzahl gesendeter Bytes (komprimiert!) liefern */
882 assert( Idx > NONE );
883 return My_Connections[Idx].zip.bytes_in;
884 } /* Conn_RecvBytesZip */
890 Conn_StartTime( CONN_ID Idx )
892 /* Zeitpunkt des Link-Starts liefern (in Sekunden) */
894 assert( Idx > NONE );
895 return My_Connections[Idx].starttime;
900 Conn_SendQ( CONN_ID Idx )
902 /* Laenge der Daten im Schreibbuffer liefern */
904 assert( Idx > NONE );
906 if( My_Connections[Idx].options & CONN_ZIP ) return My_Connections[Idx].zip.wdatalen;
909 return My_Connections[Idx].wdatalen;
914 Conn_SendMsg( CONN_ID Idx )
916 /* Anzahl gesendeter Nachrichten liefern */
918 assert( Idx > NONE );
919 return My_Connections[Idx].msg_out;
924 Conn_SendBytes( CONN_ID Idx )
926 /* Anzahl gesendeter Bytes (unkomprimiert) liefern */
928 assert( Idx > NONE );
929 return My_Connections[Idx].bytes_out;
930 } /* Conn_SendBytes */
934 Conn_RecvQ( CONN_ID Idx )
936 /* Laenge der Daten im Lesebuffer liefern */
938 assert( Idx > NONE );
940 if( My_Connections[Idx].options & CONN_ZIP ) return My_Connections[Idx].zip.rdatalen;
943 return My_Connections[Idx].rdatalen;
948 Conn_RecvMsg( CONN_ID Idx )
950 /* Anzahl empfangener Nachrichten liefern */
952 assert( Idx > NONE );
953 return My_Connections[Idx].msg_in;
958 Conn_RecvBytes( CONN_ID Idx )
960 /* Anzahl empfangener Bytes (unkomprimiert) liefern */
962 assert( Idx > NONE );
963 return My_Connections[Idx].bytes_in;
964 } /* Conn_RecvBytes */
968 Conn_ResetWCounter( VOID )
971 } /* Conn_ResetWCounter */
975 Conn_WCounter( VOID )
978 } /* Conn_WCounter */
982 Try_Write( CONN_ID Idx )
984 /* Versuchen, Daten aus dem Schreib-Puffer in den Socket zu
985 * schreiben. TRUE wird geliefert, wenn entweder keine Daten
986 * zum Versenden vorhanden sind oder erfolgreich bearbeitet
987 * werden konnten. Im Fehlerfall wird FALSE geliefert und
988 * die Verbindung geschlossen. */
993 assert( Idx > NONE );
994 assert( My_Connections[Idx].sock > NONE );
996 /* sind ueberhaupt Daten vorhanden? */
998 if(( ! My_Connections[Idx].wdatalen > 0 ) && ( ! My_Connections[Idx].zip.wdatalen )) return TRUE;
1000 if( ! My_Connections[Idx].wdatalen > 0 ) return TRUE;
1003 /* Timeout initialisieren: 0 Sekunden, also nicht blockieren */
1004 tv.tv_sec = 0; tv.tv_usec = 0;
1006 FD_ZERO( &write_socket );
1007 FD_SET( My_Connections[Idx].sock, &write_socket );
1008 if( select( My_Connections[Idx].sock + 1, NULL, &write_socket, NULL, &tv ) == -1 )
1011 if( errno != EINTR )
1013 Log( LOG_ALERT, "Try_Write(): select() failed: %s (con=%d, sock=%d)!", strerror( errno ), Idx, My_Connections[Idx].sock );
1014 Conn_Close( Idx, "Server error!", NULL, FALSE );
1019 if( FD_ISSET( My_Connections[Idx].sock, &write_socket )) return Handle_Write( Idx );
1025 Handle_Read( INT Sock )
1027 /* Aktivitaet auf einem Socket verarbeiten:
1028 * - neue Clients annehmen,
1029 * - Daten von Clients verarbeiten,
1030 * - Resolver-Rueckmeldungen annehmen. */
1034 assert( Sock > NONE );
1036 if( FD_ISSET( Sock, &My_Listeners ))
1038 /* es ist einer unserer Listener-Sockets: es soll
1039 * also eine neue Verbindung aufgebaut werden. */
1041 New_Connection( Sock );
1043 else if( FD_ISSET( Sock, &Resolver_FDs ))
1045 /* Rueckmeldung von einem Resolver Sub-Prozess */
1047 Read_Resolver_Result( Sock );
1051 /* Ein Client Socket: entweder ein User oder Server */
1053 idx = Socket2Index( Sock );
1054 if( idx > NONE ) Read_Request( idx );
1060 Handle_Write( CONN_ID Idx )
1062 /* Daten aus Schreibpuffer versenden bzw. Connection aufbauen */
1066 assert( Idx > NONE );
1067 assert( My_Connections[Idx].sock > NONE );
1069 if( FD_ISSET( My_Connections[Idx].sock, &My_Connects ))
1071 /* es soll nichts geschrieben werden, sondern ein
1072 * connect() hat ein Ergebnis geliefert */
1074 FD_CLR( My_Connections[Idx].sock, &My_Connects );
1076 /* Ergebnis des connect() ermitteln */
1077 len = sizeof( err );
1078 res = getsockopt( My_Connections[Idx].sock, SOL_SOCKET, SO_ERROR, &err, &len );
1079 assert( len == sizeof( err ));
1081 /* Fehler aufgetreten? */
1082 if(( res != 0 ) || ( err != 0 ))
1085 if( res != 0 ) Log( LOG_CRIT, "getsockopt (connection %d): %s!", Idx, strerror( errno ));
1086 else Log( LOG_CRIT, "Can't connect socket to \"%s:%d\" (connection %d): %s!", My_Connections[Idx].host, Conf_Server[Conf_GetServer( Idx )].port, Idx, strerror( err ));
1088 /* Socket etc. pp. aufraeumen */
1089 FD_CLR( My_Connections[Idx].sock, &My_Sockets );
1090 close( My_Connections[Idx].sock );
1091 Init_Conn_Struct( Idx );
1093 /* Bei Server-Verbindungen lasttry-Zeitpunkt auf "jetzt" setzen */
1094 Conf_Server[Conf_GetServer( Idx )].lasttry = time( NULL );
1095 Conf_UnsetServer( Idx );
1099 Log( LOG_DEBUG, "Connection %d with \"%s:%d\" established, now sendig PASS and SERVER ...", Idx, My_Connections[Idx].host, Conf_Server[Conf_GetServer( Idx )].port );
1101 /* PASS und SERVER verschicken */
1102 Conn_WriteStr( Idx, "PASS %s %s", Conf_Server[Conf_GetServer( Idx )].pwd_out, NGIRCd_ProtoID );
1103 return Conn_WriteStr( Idx, "SERVER %s :%s", Conf_ServerName, Conf_ServerInfo );
1107 /* Schreibpuffer leer, aber noch Daten im Kompressionsbuffer?
1108 * Dann muss dieser nun geflushed werden! */
1109 if( My_Connections[Idx].wdatalen == 0 ) Zip_Flush( Idx );
1112 assert( My_Connections[Idx].wdatalen > 0 );
1114 /* Daten schreiben */
1115 len = send( My_Connections[Idx].sock, My_Connections[Idx].wbuf, My_Connections[Idx].wdatalen, 0 );
1118 /* Operation haette Socket "nur" blockiert ... */
1119 if( errno == EAGAIN ) return TRUE;
1121 /* Oops, ein Fehler! */
1122 Log( LOG_ERR, "Write error on connection %d (socket %d): %s!", Idx, My_Connections[Idx].sock, strerror( errno ));
1123 Conn_Close( Idx, "Write error!", NULL, FALSE );
1127 /* Puffer anpassen */
1128 My_Connections[Idx].wdatalen -= len;
1129 memmove( My_Connections[Idx].wbuf, My_Connections[Idx].wbuf + len, My_Connections[Idx].wdatalen );
1132 } /* Handle_Write */
1136 New_Connection( INT Sock )
1138 /* Neue Client-Verbindung von Listen-Socket annehmen und
1139 * CLIENT-Struktur anlegen. */
1141 struct sockaddr_in new_addr;
1142 INT new_sock, new_sock_len;
1149 assert( Sock > NONE );
1151 /* Connection auf Listen-Socket annehmen */
1152 new_sock_len = sizeof( new_addr );
1153 new_sock = accept( Sock, (struct sockaddr *)&new_addr, (socklen_t *)&new_sock_len );
1156 Log( LOG_CRIT, "Can't accept connection: %s!", strerror( errno ));
1160 /* Socket initialisieren */
1161 Init_Socket( new_sock );
1163 /* Freie Connection-Struktur suchen */
1164 for( idx = 0; idx < Pool_Size; idx++ ) if( My_Connections[idx].sock == NONE ) break;
1165 if( idx >= Pool_Size )
1167 new_size = Pool_Size + CONNECTION_POOL;
1169 /* Im bisherigen Pool wurde keine freie Connection-Struktur mehr gefunden.
1170 * Wenn erlaubt und moeglich muss nun der Pool vergroessert werden: */
1172 if( Conf_MaxConnections > 0 )
1174 /* Es ist ein Limit konfiguriert */
1175 if( Pool_Size >= Conf_MaxConnections )
1177 /* Mehr Verbindungen duerfen wir leider nicht mehr annehmen ... */
1178 Log( LOG_ALERT, "Can't accept connection: limit (%d) reached!", Pool_Size );
1182 if( new_size > Conf_MaxConnections ) new_size = Conf_MaxConnections;
1185 /* zunaechst realloc() versuchen; wenn das scheitert, malloc() versuchen
1186 * und Daten ggf. "haendisch" umkopieren. (Haesslich! Eine wirklich
1187 * dynamische Verwaltung waere wohl _deutlich_ besser ...) */
1188 ptr = realloc( My_Connections, sizeof( CONNECTION ) * new_size );
1191 /* realloc() ist fehlgeschlagen. Nun malloc() probieren: */
1192 ptr = malloc( sizeof( CONNECTION ) * new_size );
1195 /* Offenbar steht kein weiterer Sepeicher zur Verfuegung :-( */
1196 Log( LOG_EMERG, "Can't allocate memory! [New_Connection]" );
1201 /* Struktur umkopieren ... */
1202 memcpy( ptr, My_Connections, sizeof( CONNECTION ) * Pool_Size );
1204 Log( LOG_DEBUG, "Allocated new connection pool for %ld items (%ld bytes). [malloc()/memcpy()]", new_size, sizeof( CONNECTION ) * new_size );
1206 else Log( LOG_DEBUG, "Allocated new connection pool for %ld items (%ld bytes). [realloc()]", new_size, sizeof( CONNECTION ) * new_size );
1208 /* Adjust pointer to new block */
1209 My_Connections = ptr;
1211 /* Initialize new items */
1212 for( idx = Pool_Size; idx < new_size; idx++ ) Init_Conn_Struct( idx );
1215 /* Adjust new pool size */
1216 Pool_Size = new_size;
1219 /* Client-Struktur initialisieren */
1220 c = Client_NewLocal( idx, inet_ntoa( new_addr.sin_addr ), CLIENT_UNKNOWN, FALSE );
1223 Log( LOG_ALERT, "Can't accept connection: can't create client structure!" );
1228 /* Verbindung registrieren */
1229 Init_Conn_Struct( idx );
1230 My_Connections[idx].sock = new_sock;
1231 My_Connections[idx].addr = new_addr;
1233 /* Neuen Socket registrieren */
1234 FD_SET( new_sock, &My_Sockets );
1235 if( new_sock > Conn_MaxFD ) Conn_MaxFD = new_sock;
1237 Log( LOG_INFO, "Accepted connection %d from %s:%d on socket %d.", idx, inet_ntoa( new_addr.sin_addr ), ntohs( new_addr.sin_port), Sock );
1239 /* Hostnamen ermitteln */
1240 strlcpy( My_Connections[idx].host, inet_ntoa( new_addr.sin_addr ), sizeof( My_Connections[idx].host ));
1241 Client_SetHostname( c, My_Connections[idx].host );
1242 s = Resolve_Addr( &new_addr );
1245 /* Sub-Prozess wurde asyncron gestartet */
1246 My_Connections[idx].res_stat = s;
1249 /* Penalty-Zeit setzen */
1250 Conn_SetPenalty( idx, 4 );
1251 } /* New_Connection */
1255 Socket2Index( INT Sock )
1257 /* zum Socket passende Connection suchen */
1261 assert( Sock > NONE );
1263 for( idx = 0; idx < Pool_Size; idx++ ) if( My_Connections[idx].sock == Sock ) break;
1265 if( idx >= Pool_Size )
1267 /* die Connection wurde vermutlich (wegen eines
1268 * Fehlers) bereits wieder abgebaut ... */
1269 Log( LOG_DEBUG, "Socket2Index: can't get connection for socket %d!", Sock );
1273 } /* Socket2Index */
1277 Read_Request( CONN_ID Idx )
1279 /* Daten von Socket einlesen und entsprechend behandeln.
1280 * Tritt ein Fehler auf, so wird der Socket geschlossen. */
1287 assert( Idx > NONE );
1288 assert( My_Connections[Idx].sock > NONE );
1290 /* wenn noch nicht registriert: maximal mit ZREADBUFFER_LEN arbeiten,
1291 * ansonsten koennen Daten ggf. nicht umkopiert werden. */
1292 bsize = READBUFFER_LEN;
1294 c = Client_GetFromConn( Idx );
1295 if(( Client_Type( c ) != CLIENT_USER ) && ( Client_Type( c ) != CLIENT_SERVER ) && ( Client_Type( c ) != CLIENT_SERVICE ) && ( bsize > ZREADBUFFER_LEN )) bsize = ZREADBUFFER_LEN;
1299 if(( bsize - My_Connections[Idx].rdatalen - 1 < 1 ) || ( ZREADBUFFER_LEN - My_Connections[Idx].zip.rdatalen < 1 ))
1301 if( bsize - My_Connections[Idx].rdatalen - 1 < 1 )
1304 /* Der Lesepuffer ist voll */
1305 Log( LOG_ERR, "Read buffer overflow (connection %d): %d bytes!", Idx, My_Connections[Idx].rdatalen );
1306 Conn_Close( Idx, "Read buffer overflow!", NULL, FALSE );
1311 if( My_Connections[Idx].options & CONN_ZIP )
1313 len = recv( My_Connections[Idx].sock, My_Connections[Idx].zip.rbuf + My_Connections[Idx].zip.rdatalen, ( ZREADBUFFER_LEN - My_Connections[Idx].zip.rdatalen ), 0 );
1314 if( len > 0 ) My_Connections[Idx].zip.rdatalen += len;
1319 len = recv( My_Connections[Idx].sock, My_Connections[Idx].rbuf + My_Connections[Idx].rdatalen, bsize - My_Connections[Idx].rdatalen - 1, 0 );
1320 if( len > 0 ) My_Connections[Idx].rdatalen += len;
1325 /* Socket wurde geschlossen */
1326 Log( LOG_INFO, "%s:%d (%s) is closing the connection ...", My_Connections[Idx].host, ntohs( My_Connections[Idx].addr.sin_port), inet_ntoa( My_Connections[Idx].addr.sin_addr ));
1327 Conn_Close( Idx, "Socket closed!", "Client closed connection", FALSE );
1333 /* Operation haette Socket "nur" blockiert ... */
1334 if( errno == EAGAIN ) return;
1336 /* Fehler beim Lesen */
1337 Log( LOG_ERR, "Read error on connection %d (socket %d): %s!", Idx, My_Connections[Idx].sock, strerror( errno ));
1338 Conn_Close( Idx, "Read error!", "Client closed connection", FALSE );
1342 /* Connection-Statistik aktualisieren */
1343 My_Connections[Idx].bytes_in += len;
1345 /* Timestamp aktualisieren */
1346 My_Connections[Idx].lastdata = time( NULL );
1348 Handle_Buffer( Idx );
1349 } /* Read_Request */
1353 Handle_Buffer( CONN_ID Idx )
1355 /* Daten im Lese-Puffer einer Verbindung verarbeiten.
1356 * Wurde ein Request verarbeitet, so wird TRUE geliefert,
1357 * ansonsten FALSE (auch bei Fehlern). */
1364 BOOLEAN action, result;
1373 /* ggf. noch unkomprimiete Daten weiter entpacken */
1374 if( My_Connections[Idx].options & CONN_ZIP )
1376 if( ! Unzip_Buffer( Idx )) return FALSE;
1380 if( My_Connections[Idx].rdatalen < 1 ) break;
1382 /* Eine komplette Anfrage muss mit CR+LF enden, vgl.
1383 * RFC 2812. Haben wir eine? */
1384 My_Connections[Idx].rbuf[My_Connections[Idx].rdatalen] = '\0';
1385 ptr = strstr( My_Connections[Idx].rbuf, "\r\n" );
1387 if( ptr ) delta = 2;
1391 /* Nicht RFC-konforme Anfrage mit nur CR oder LF? Leider
1392 * machen soetwas viele Clients, u.a. "mIRC" :-( */
1393 ptr1 = strchr( My_Connections[Idx].rbuf, '\r' );
1394 ptr2 = strchr( My_Connections[Idx].rbuf, '\n' );
1396 if( ptr1 && ptr2 ) ptr = ptr1 > ptr2 ? ptr2 : ptr1;
1397 else if( ptr1 ) ptr = ptr1;
1398 else if( ptr2 ) ptr = ptr2;
1405 /* Ende der Anfrage wurde gefunden */
1407 len = ( ptr - My_Connections[Idx].rbuf ) + delta;
1408 if( len > ( COMMAND_LEN - 1 ))
1410 /* Eine Anfrage darf(!) nicht laenger als 512 Zeichen
1411 * (incl. CR+LF!) werden; vgl. RFC 2812. Wenn soetwas
1412 * empfangen wird, wird der Client disconnectiert. */
1413 Log( LOG_ERR, "Request too long (connection %d): %d bytes (max. %d expected)!", Idx, My_Connections[Idx].rdatalen, COMMAND_LEN - 1 );
1414 Conn_Close( Idx, NULL, "Request too long", TRUE );
1419 /* merken, ob Stream bereits komprimiert wird */
1420 old_z = My_Connections[Idx].options & CONN_ZIP;
1425 /* Es wurde ein Request gelesen */
1426 My_Connections[Idx].msg_in++;
1427 if( ! Parse_Request( Idx, My_Connections[Idx].rbuf )) return FALSE;
1431 /* Puffer anpassen */
1432 My_Connections[Idx].rdatalen -= len;
1433 memmove( My_Connections[Idx].rbuf, My_Connections[Idx].rbuf + len, My_Connections[Idx].rdatalen );
1436 if(( ! old_z ) && ( My_Connections[Idx].options & CONN_ZIP ) && ( My_Connections[Idx].rdatalen > 0 ))
1438 /* Mit dem letzten Befehl wurde Socket-Kompression aktiviert.
1439 * Evtl. schon vom Socket gelesene Daten in den Unzip-Puffer
1440 * umkopieren, damit diese nun zunaechst entkomprimiert werden */
1442 if( My_Connections[Idx].rdatalen > ZREADBUFFER_LEN )
1444 /* Hupsa! Soviel Platz haben wir aber gar nicht! */
1445 Log( LOG_ALERT, "Can't move read buffer: No space left in unzip buffer (need %d bytes)!", My_Connections[Idx].rdatalen );
1448 memcpy( My_Connections[Idx].zip.rbuf, My_Connections[Idx].rbuf, My_Connections[Idx].rdatalen );
1449 My_Connections[Idx].zip.rdatalen = My_Connections[Idx].rdatalen;
1450 My_Connections[Idx].rdatalen = 0;
1451 Log( LOG_DEBUG, "Moved already received data (%d bytes) to uncompression buffer.", My_Connections[Idx].zip.rdatalen );
1457 if( action ) result = TRUE;
1461 } /* Handle_Buffer */
1465 Check_Connections( VOID )
1467 /* Pruefen, ob Verbindungen noch "alive" sind. Ist dies
1468 * nicht der Fall, zunaechst PING-PONG spielen und, wenn
1469 * auch das nicht "hilft", Client disconnectieren. */
1474 for( i = 0; i < Pool_Size; i++ )
1476 if( My_Connections[i].sock == NONE ) continue;
1478 c = Client_GetFromConn( i );
1479 if( c && (( Client_Type( c ) == CLIENT_USER ) || ( Client_Type( c ) == CLIENT_SERVER ) || ( Client_Type( c ) == CLIENT_SERVICE )))
1481 /* verbundener User, Server oder Service */
1482 if( My_Connections[i].lastping > My_Connections[i].lastdata )
1484 /* es wurde bereits ein PING gesendet */
1485 if( My_Connections[i].lastping < time( NULL ) - Conf_PongTimeout )
1488 Log( LOG_DEBUG, "Connection %d: Ping timeout: %d seconds.", i, Conf_PongTimeout );
1489 Conn_Close( i, NULL, "Ping timeout", TRUE );
1492 else if( My_Connections[i].lastdata < time( NULL ) - Conf_PingTimeout )
1494 /* es muss ein PING gesendet werden */
1495 Log( LOG_DEBUG, "Connection %d: sending PING ...", i );
1496 My_Connections[i].lastping = time( NULL );
1497 Conn_WriteStr( i, "PING :%s", Client_ID( Client_ThisServer( )));
1502 /* noch nicht vollstaendig aufgebaute Verbindung */
1503 if( My_Connections[i].lastdata < time( NULL ) - Conf_PingTimeout )
1506 Log( LOG_DEBUG, "Connection %d timed out ...", i );
1507 Conn_Close( i, NULL, "Timeout", FALSE );
1511 } /* Check_Connections */
1515 Check_Servers( VOID )
1517 /* Check if we can establish further server links */
1523 /* Don't connect in "passive mode" */
1524 if( NGIRCd_Passive ) return;
1526 /* Serach all connections, are there results from the resolver? */
1527 for( idx = 0; idx < Pool_Size; idx++ )
1529 if( My_Connections[idx].sock != SERVER_WAIT ) continue;
1532 if( My_Connections[idx].res_stat == NULL ) New_Server( Conf_GetServer( idx ), idx );
1535 /* Check all configured servers */
1536 for( i = 0; i < MAX_SERVERS; i++ )
1538 /* Valid outgoing server which isn't already connected? */
1539 if(( ! Conf_Server[i].host[0] ) || ( ! Conf_Server[i].port > 0 ) || ( Conf_Server[i].conn_id > NONE )) continue;
1541 /* Is there already a connection in this group? */
1542 if( Conf_Server[i].group > NONE )
1544 for( n = 0; n < MAX_SERVERS; n++ )
1546 if( n == i ) continue;
1547 if(( Conf_Server[n].conn_id > NONE ) && ( Conf_Server[n].group == Conf_Server[i].group )) break;
1549 if( n < MAX_SERVERS ) continue;
1552 /* Check last connect attempt? */
1553 if( Conf_Server[i].lasttry > time( NULL ) - Conf_ConnectRetry ) continue;
1555 /* Okay, try to connect now */
1556 Conf_Server[i].lasttry = time( NULL );
1558 /* Search free connection structure */
1559 for( idx = 0; idx < Pool_Size; idx++ ) if( My_Connections[idx].sock == NONE ) break;
1560 if( idx >= Pool_Size )
1562 Log( LOG_ALERT, "Can't establist server connection: connection limit reached (%d)!", Pool_Size );
1565 Log( LOG_DEBUG, "Preparing connection %d for \"%s\" ...", idx, Conf_Server[i].host );
1567 /* Verbindungs-Struktur initialisieren */
1568 Init_Conn_Struct( idx );
1569 My_Connections[idx].sock = SERVER_WAIT;
1570 Conf_Server[i].conn_id = idx;
1572 /* Resolve Hostname. If this fails, try to use it as an IP address */
1573 strlcpy( Conf_Server[i].ip, Conf_Server[i].host, sizeof( Conf_Server[i].ip ));
1574 strlcpy( My_Connections[idx].host, Conf_Server[i].host, sizeof( My_Connections[idx].host ));
1575 s = Resolve_Name( Conf_Server[i].host );
1578 /* Sub-Prozess wurde asyncron gestartet */
1579 My_Connections[idx].res_stat = s;
1582 } /* Check_Servers */
1586 New_Server( INT Server, CONN_ID Idx )
1588 /* Neue Server-Verbindung aufbauen */
1590 struct sockaddr_in new_addr;
1591 struct in_addr inaddr;
1595 assert( Server > NONE );
1596 assert( Idx > NONE );
1598 /* Wurde eine gueltige IP-Adresse gefunden? */
1599 if( ! Conf_Server[Server].ip[0] )
1601 /* Nein. Verbindung wieder freigeben: */
1602 Init_Conn_Struct( Idx );
1603 Log( LOG_ERR, "Can't connect to \"%s\" (connection %d): ip address unknown!", Conf_Server[Server].host, Idx );
1607 Log( LOG_INFO, "Establishing connection to \"%s\", %s, port %d (connection %d) ... ", Conf_Server[Server].host, Conf_Server[Server].ip, Conf_Server[Server].port, Idx );
1609 #ifdef HAVE_INET_ATON
1610 if( inet_aton( Conf_Server[Server].ip, &inaddr ) == 0 )
1612 memset( &inaddr, 0, sizeof( inaddr ));
1613 inaddr.s_addr = inet_addr( Conf_Server[Server].ip );
1614 if( inaddr.s_addr == (unsigned)-1 )
1617 /* Konnte Adresse nicht konvertieren */
1618 Init_Conn_Struct( Idx );
1619 Log( LOG_ERR, "Can't connect to \"%s\" (connection %d): can't convert ip address %s!", Conf_Server[Server].host, Idx, Conf_Server[Server].ip );
1623 memset( &new_addr, 0, sizeof( new_addr ));
1624 new_addr.sin_family = AF_INET;
1625 new_addr.sin_addr = inaddr;
1626 new_addr.sin_port = htons( Conf_Server[Server].port );
1628 new_sock = socket( PF_INET, SOCK_STREAM, 0 );
1631 Init_Conn_Struct( Idx );
1632 Log( LOG_CRIT, "Can't create socket: %s!", strerror( errno ));
1636 if( ! Init_Socket( new_sock )) return;
1638 res = connect( new_sock, (struct sockaddr *)&new_addr, sizeof( new_addr ));
1639 if(( res != 0 ) && ( errno != EINPROGRESS ))
1641 Log( LOG_CRIT, "Can't connect socket: %s!", strerror( errno ));
1643 Init_Conn_Struct( Idx );
1647 /* Client-Struktur initialisieren */
1648 c = Client_NewLocal( Idx, inet_ntoa( new_addr.sin_addr ), CLIENT_UNKNOWNSERVER, FALSE );
1652 Init_Conn_Struct( Idx );
1653 Log( LOG_ALERT, "Can't establish connection: can't create client structure!" );
1656 Client_SetIntroducer( c, c );
1657 Client_SetToken( c, TOKEN_OUTBOUND );
1659 /* Verbindung registrieren */
1660 My_Connections[Idx].sock = new_sock;
1661 My_Connections[Idx].addr = new_addr;
1662 strlcpy( My_Connections[Idx].host, Conf_Server[Server].host, sizeof( My_Connections[Idx].host ));
1664 /* Neuen Socket registrieren */
1665 FD_SET( new_sock, &My_Sockets );
1666 FD_SET( new_sock, &My_Connects );
1667 if( new_sock > Conn_MaxFD ) Conn_MaxFD = new_sock;
1669 Log( LOG_DEBUG, "Registered new connection %d on socket %d.", Idx, My_Connections[Idx].sock );
1674 Init_Conn_Struct( LONG Idx )
1676 /* Connection-Struktur initialisieren */
1678 My_Connections[Idx].sock = NONE;
1679 My_Connections[Idx].res_stat = NULL;
1680 My_Connections[Idx].host[0] = '\0';
1681 My_Connections[Idx].rbuf[0] = '\0';
1682 My_Connections[Idx].rdatalen = 0;
1683 My_Connections[Idx].wbuf[0] = '\0';
1684 My_Connections[Idx].wdatalen = 0;
1685 My_Connections[Idx].starttime = time( NULL );
1686 My_Connections[Idx].lastdata = time( NULL );
1687 My_Connections[Idx].lastping = 0;
1688 My_Connections[Idx].lastprivmsg = time( NULL );
1689 My_Connections[Idx].delaytime = 0;
1690 My_Connections[Idx].bytes_in = 0;
1691 My_Connections[Idx].bytes_out = 0;
1692 My_Connections[Idx].msg_in = 0;
1693 My_Connections[Idx].msg_out = 0;
1694 My_Connections[Idx].flag = 0;
1695 My_Connections[Idx].options = 0;
1698 My_Connections[Idx].zip.rbuf[0] = '\0';
1699 My_Connections[Idx].zip.rdatalen = 0;
1700 My_Connections[Idx].zip.wbuf[0] = '\0';
1701 My_Connections[Idx].zip.wdatalen = 0;
1702 My_Connections[Idx].zip.bytes_in = 0;
1703 My_Connections[Idx].zip.bytes_out = 0;
1705 } /* Init_Conn_Struct */
1709 Init_Socket( INT Sock )
1711 /* Socket-Optionen setzen */
1715 #ifdef O_NONBLOCK /* A/UX kennt das nicht? */
1716 if( fcntl( Sock, F_SETFL, O_NONBLOCK ) != 0 )
1718 Log( LOG_CRIT, "Can't enable non-blocking mode: %s!", strerror( errno ));
1723 if( setsockopt( Sock, SOL_SOCKET, SO_REUSEADDR, &on, (socklen_t)sizeof( on )) != 0)
1725 Log( LOG_ERR, "Can't set socket options: %s!", strerror( errno ));
1726 /* dieser Fehler kann ignoriert werden. */
1734 Read_Resolver_Result( INT r_fd )
1736 /* Ergebnis von Resolver Sub-Prozess aus Pipe lesen
1737 * und entsprechende Connection aktualisieren */
1739 CHAR result[HOST_LEN];
1743 FD_CLR( r_fd, &Resolver_FDs );
1745 /* Anfrage vom Parent lesen */
1746 len = read( r_fd, result, HOST_LEN - 1 );
1749 /* Fehler beim Lesen aus der Pipe */
1751 Log( LOG_CRIT, "Resolver: Can't read result: %s!", strerror( errno ));
1756 /* zugehoerige Connection suchen */
1757 for( i = 0; i < Pool_Size; i++ )
1759 if(( My_Connections[i].sock != NONE ) && ( My_Connections[i].res_stat ) && ( My_Connections[i].res_stat->pipe[0] == r_fd )) break;
1761 if( i >= Pool_Size )
1763 /* Opsa! Keine passende Connection gefunden!? Vermutlich
1764 * wurde sie schon wieder geschlossen. */
1766 Log( LOG_DEBUG, "Resolver: Got result for unknown connection!?" );
1770 Log( LOG_DEBUG, "Resolver: %s is \"%s\".", My_Connections[i].host, result );
1773 close( My_Connections[i].res_stat->pipe[0] );
1774 close( My_Connections[i].res_stat->pipe[1] );
1775 free( My_Connections[i].res_stat );
1776 My_Connections[i].res_stat = NULL;
1778 if( My_Connections[i].sock > NONE )
1780 /* Eingehende Verbindung: Hostnamen setzen */
1781 c = Client_GetFromConn( i );
1782 assert( c != NULL );
1783 strlcpy( My_Connections[i].host, result, sizeof( My_Connections[i].host ));
1784 Client_SetHostname( c, result );
1788 /* Ausgehende Verbindung (=Server): IP setzen */
1789 n = Conf_GetServer( i );
1790 if( n > NONE ) strlcpy( Conf_Server[n].ip, result, sizeof( Conf_Server[n].ip ));
1791 else Log( LOG_ERR, "Got resolver result for non-configured server!?" );
1794 /* Penalty-Zeit zurueck setzen */
1795 Conn_ResetPenalty( i );
1796 } /* Read_Resolver_Result */
1802 Zip_Buffer( CONN_ID Idx, CHAR *Data, INT Len )
1804 /* Daten zum Komprimieren im "Kompressions-Puffer" sammeln.
1805 * Es wird TRUE bei Erfolg, sonst FALSE geliefert. */
1807 assert( Idx > NONE );
1808 assert( Data != NULL );
1811 /* Ist noch Platz im Kompressions-Puffer? */
1812 if( ZWRITEBUFFER_LEN - My_Connections[Idx].zip.wdatalen < Len + 50 )
1814 /* Nein! Puffer zunaechst leeren ...*/
1815 if( ! Zip_Flush( Idx )) return FALSE;
1818 /* Daten kopieren */
1819 memmove( My_Connections[Idx].zip.wbuf + My_Connections[Idx].zip.wdatalen, Data, Len );
1820 My_Connections[Idx].zip.wdatalen += Len;
1827 Zip_Flush( CONN_ID Idx )
1829 /* Daten komprimieren und in Schreibpuffer kopieren.
1830 * Es wird TRUE bei Erfolg, sonst FALSE geliefert. */
1832 INT result, out_len;
1835 out = &My_Connections[Idx].zip.out;
1837 out->next_in = My_Connections[Idx].zip.wbuf;
1838 out->avail_in = My_Connections[Idx].zip.wdatalen;
1839 out->next_out = My_Connections[Idx].wbuf + My_Connections[Idx].wdatalen;
1840 out->avail_out = WRITEBUFFER_LEN - My_Connections[Idx].wdatalen;
1842 result = deflate( out, Z_SYNC_FLUSH );
1843 if(( result != Z_OK ) || ( out->avail_in > 0 ))
1845 Log( LOG_ALERT, "Compression error: code %d!?", result );
1846 Conn_Close( Idx, "Compression error!", NULL, FALSE );
1850 out_len = WRITEBUFFER_LEN - My_Connections[Idx].wdatalen - out->avail_out;
1851 My_Connections[Idx].wdatalen += out_len;
1852 My_Connections[Idx].bytes_out += out_len;
1853 My_Connections[Idx].zip.bytes_out += My_Connections[Idx].zip.wdatalen;
1854 My_Connections[Idx].zip.wdatalen = 0;
1861 Unzip_Buffer( CONN_ID Idx )
1863 /* Daten entpacken und in Lesepuffer kopieren. Bei Fehlern
1864 * wird FALSE geliefert, ansonsten TRUE. Der Fall, dass keine
1865 * Daten mehr zu entpacken sind, ist _kein_ Fehler! */
1867 INT result, in_len, out_len;
1870 assert( Idx > NONE );
1872 if( My_Connections[Idx].zip.rdatalen <= 0 ) return TRUE;
1874 in = &My_Connections[Idx].zip.in;
1876 in->next_in = My_Connections[Idx].zip.rbuf;
1877 in->avail_in = My_Connections[Idx].zip.rdatalen;
1878 in->next_out = My_Connections[Idx].rbuf + My_Connections[Idx].rdatalen;
1879 in->avail_out = READBUFFER_LEN - My_Connections[Idx].rdatalen - 1;
1881 result = inflate( in, Z_SYNC_FLUSH );
1882 if( result != Z_OK )
1884 Log( LOG_ALERT, "Decompression error: code %d (ni=%d, ai=%d, no=%d, ao=%d)!?", result, in->next_in, in->avail_in, in->next_out, in->avail_out );
1885 Conn_Close( Idx, "Decompression error!", NULL, FALSE );
1889 in_len = My_Connections[Idx].zip.rdatalen - in->avail_in;
1890 out_len = READBUFFER_LEN - My_Connections[Idx].rdatalen - 1 - in->avail_out;
1891 My_Connections[Idx].rdatalen += out_len;
1893 if( in->avail_in > 0 )
1895 /* es konnten nicht alle Daten entpackt werden, vermutlich war
1896 * im Ziel-Puffer kein Platz mehr. Umkopieren ... */
1897 My_Connections[Idx].zip.rdatalen -= in_len;
1898 memmove( My_Connections[Idx].zip.rbuf, My_Connections[Idx].zip.rbuf + in_len, My_Connections[Idx].zip.rdatalen );
1900 else My_Connections[Idx].zip.rdatalen = 0;
1901 My_Connections[Idx].zip.bytes_in += out_len;
1904 } /* Unzip_Buffer */