Blob


1 /*
2 * ngIRCd -- The Next Generation IRC Daemon
3 * Copyright (c)2001,2002 by Alexander Barton (alex@barton.de)
4 *
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.
10 *
11 * Connection management
12 */
15 #define CONN_MODULE
17 #include "portab.h"
19 static char UNUSED id[] = "$Id: conn.c,v 1.114 2002/12/31 16:13:29 alex Exp $";
21 #include "imp.h"
22 #include <assert.h>
23 #include <stdarg.h>
24 #include <stdio.h>
25 #include <stdlib.h>
26 #include <unistd.h>
27 #include <errno.h>
28 #include <fcntl.h>
29 #include <string.h>
30 #include <sys/socket.h>
31 #include <sys/time.h>
32 #include <sys/types.h>
33 #include <time.h>
34 #include <netinet/in.h>
36 #ifdef HAVE_ARPA_INET_H
37 #include <arpa/inet.h>
38 #else
39 #define PF_INET AF_INET
40 #endif
42 #ifdef HAVE_STDINT_H
43 #include <stdint.h> /* u.a. fuer Mac OS X */
44 #endif
46 #include "defines.h"
47 #include "resolve.h"
49 #include "exp.h"
50 #include "conn.h"
52 #include "imp.h"
53 #include "ngircd.h"
54 #include "client.h"
55 #include "conf.h"
56 #include "conn-zip.h"
57 #include "conn-func.h"
58 #include "log.h"
59 #include "parse.h"
60 #include "tool.h"
62 #include "exp.h"
65 #define SERVER_WAIT (NONE - 1)
68 LOCAL VOID Handle_Read PARAMS(( INT sock ));
69 LOCAL BOOLEAN Handle_Write PARAMS(( CONN_ID Idx ));
70 LOCAL VOID New_Connection PARAMS(( INT Sock ));
71 LOCAL CONN_ID Socket2Index PARAMS(( INT Sock ));
72 LOCAL VOID Read_Request PARAMS(( CONN_ID Idx ));
73 LOCAL BOOLEAN Try_Write PARAMS(( CONN_ID Idx ));
74 LOCAL BOOLEAN Handle_Buffer PARAMS(( CONN_ID Idx ));
75 LOCAL VOID Check_Connections PARAMS(( VOID ));
76 LOCAL VOID Check_Servers PARAMS(( VOID ));
77 LOCAL VOID Init_Conn_Struct PARAMS(( CONN_ID Idx ));
78 LOCAL BOOLEAN Init_Socket PARAMS(( INT Sock ));
79 LOCAL VOID New_Server PARAMS(( INT Server, CONN_ID Idx ));
80 LOCAL VOID Read_Resolver_Result PARAMS(( INT r_fd ));
82 LOCAL fd_set My_Listeners;
83 LOCAL fd_set My_Sockets;
84 LOCAL fd_set My_Connects;
87 GLOBAL VOID
88 Conn_Init( VOID )
89 {
90 /* Modul initialisieren: statische Strukturen "ausnullen". */
92 CONN_ID i;
94 /* Speicher fuer Verbindungs-Pool anfordern */
95 Pool_Size = CONNECTION_POOL;
96 if( Conf_MaxConnections > 0 )
97 {
98 /* konfiguriertes Limit beachten */
99 if( Pool_Size > Conf_MaxConnections ) Pool_Size = Conf_MaxConnections;
101 My_Connections = malloc( sizeof( CONNECTION ) * Pool_Size );
102 if( ! My_Connections )
104 /* Speicher konnte nicht alloziert werden! */
105 Log( LOG_EMERG, "Can't allocate memory! [Conn_Init]" );
106 exit( 1 );
108 Log( LOG_DEBUG, "Allocted connection pool for %d items (%ld bytes).", Pool_Size, sizeof( CONNECTION ) * Pool_Size );
110 /* zu Beginn haben wir keine Verbindungen */
111 FD_ZERO( &My_Listeners );
112 FD_ZERO( &My_Sockets );
113 FD_ZERO( &My_Connects );
115 /* Groesster File-Descriptor fuer select() */
116 Conn_MaxFD = 0;
118 /* Connection-Struktur initialisieren */
119 for( i = 0; i < Pool_Size; i++ ) Init_Conn_Struct( i );
121 /* Global write counter */
122 WCounter = 0;
123 } /* Conn_Init */
126 GLOBAL VOID
127 Conn_Exit( VOID )
129 /* Modul abmelden: alle noch offenen Connections
130 * schliessen und freigeben. */
132 CONN_ID idx;
133 INT i;
135 /* Sockets schliessen */
136 Log( LOG_DEBUG, "Shutting down all connections ..." );
137 for( i = 0; i < Conn_MaxFD + 1; i++ )
139 if( FD_ISSET( i, &My_Sockets ))
141 for( idx = 0; idx < Pool_Size; idx++ )
143 if( My_Connections[idx].sock == i ) break;
145 if( FD_ISSET( i, &My_Listeners ))
147 close( i );
148 Log( LOG_DEBUG, "Listening socket %d closed.", i );
150 else if( FD_ISSET( i, &My_Connects ))
152 close( i );
153 Log( LOG_DEBUG, "Connection %d closed during creation (socket %d).", idx, i );
155 else if( idx < Pool_Size )
157 if( NGIRCd_SignalRestart ) Conn_Close( idx, NULL, "Server going down (restarting)", TRUE );
158 else Conn_Close( idx, NULL, "Server going down", TRUE );
160 else
162 Log( LOG_WARNING, "Closing unknown connection %d ...", i );
163 close( i );
168 free( My_Connections );
169 My_Connections = NULL;
170 Pool_Size = 0;
171 } /* Conn_Exit */
174 GLOBAL INT
175 Conn_InitListeners( VOID )
177 /* Initialize ports on which the server should accept connections */
179 INT created, i;
181 created = 0;
182 for( i = 0; i < Conf_ListenPorts_Count; i++ )
184 if( Conn_NewListener( Conf_ListenPorts[i] )) created++;
185 else Log( LOG_ERR, "Can't listen on port %u!", Conf_ListenPorts[i] );
187 return created;
188 } /* Conn_InitListeners */
191 GLOBAL VOID
192 Conn_ExitListeners( VOID )
194 /* Close down all listening sockets */
196 INT i;
198 Log( LOG_INFO, "Shutting down all listening sockets ..." );
199 for( i = 0; i < Conn_MaxFD + 1; i++ )
201 if( FD_ISSET( i, &My_Sockets ) && FD_ISSET( i, &My_Listeners ))
203 close( i );
204 Log( LOG_DEBUG, "Listening socket %d closed.", i );
207 } /* Conn_ExitListeners */
210 GLOBAL BOOLEAN
211 Conn_NewListener( CONST UINT Port )
213 /* Create new listening socket on specified port */
215 struct sockaddr_in addr;
216 INT sock;
218 /* Server-"Listen"-Socket initialisieren */
219 memset( &addr, 0, sizeof( addr ));
220 addr.sin_family = AF_INET;
221 addr.sin_port = htons( Port );
222 addr.sin_addr.s_addr = htonl( INADDR_ANY );
224 /* Socket erzeugen */
225 sock = socket( PF_INET, SOCK_STREAM, 0);
226 if( sock < 0 )
228 Log( LOG_CRIT, "Can't create socket: %s!", strerror( errno ));
229 return FALSE;
232 if( ! Init_Socket( sock )) return FALSE;
234 /* an Port binden */
235 if( bind( sock, (struct sockaddr *)&addr, (socklen_t)sizeof( addr )) != 0 )
237 Log( LOG_CRIT, "Can't bind socket: %s!", strerror( errno ));
238 close( sock );
239 return FALSE;
242 /* in "listen mode" gehen :-) */
243 if( listen( sock, 10 ) != 0 )
245 Log( LOG_CRIT, "Can't listen on soecket: %s!", strerror( errno ));
246 close( sock );
247 return FALSE;
250 /* Neuen Listener in Strukturen einfuegen */
251 FD_SET( sock, &My_Listeners );
252 FD_SET( sock, &My_Sockets );
254 if( sock > Conn_MaxFD ) Conn_MaxFD = sock;
256 Log( LOG_INFO, "Now listening on port %d (socket %d).", Port, sock );
258 return TRUE;
259 } /* Conn_NewListener */
262 GLOBAL VOID
263 Conn_Handler( VOID )
265 /* "Hauptschleife": Aktive Verbindungen ueberwachen. Folgende Aktionen
266 * werden dabei durchgefuehrt, bis der Server terminieren oder neu
267 * starten soll:
269 * - neue Verbindungen annehmen,
270 * - Server-Verbindungen aufbauen,
271 * - geschlossene Verbindungen loeschen,
272 * - volle Schreibpuffer versuchen zu schreiben,
273 * - volle Lesepuffer versuchen zu verarbeiten,
274 * - Antworten von Resolver Sub-Prozessen annehmen.
275 */
277 fd_set read_sockets, write_sockets;
278 struct timeval tv;
279 time_t start, t;
280 CONN_ID i, idx;
281 BOOLEAN timeout;
283 start = time( NULL );
284 while(( ! NGIRCd_SignalQuit ) && ( ! NGIRCd_SignalRestart ))
286 timeout = TRUE;
288 /* Should the configuration be reloaded? */
289 if( NGIRCd_SignalRehash ) NGIRCd_Rehash( );
291 /* Check configured servers and established links */
292 Check_Servers( );
293 Check_Connections( );
295 /* noch volle Lese-Buffer suchen */
296 for( i = 0; i < Pool_Size; i++ )
298 if(( My_Connections[i].sock > NONE ) && ( My_Connections[i].rdatalen > 0 ))
300 /* Kann aus dem Buffer noch ein Befehl extrahiert werden? */
301 if( Handle_Buffer( i )) timeout = FALSE;
305 /* noch volle Schreib-Puffer suchen */
306 FD_ZERO( &write_sockets );
307 for( i = 0; i < Pool_Size; i++ )
309 #ifdef USE_ZLIB
310 if(( My_Connections[i].sock > NONE ) && (( My_Connections[i].wdatalen > 0 ) || ( My_Connections[i].zip.wdatalen > 0 )))
311 #else
312 if(( My_Connections[i].sock > NONE ) && ( My_Connections[i].wdatalen > 0 ))
313 #endif
315 /* Socket der Verbindung in Set aufnehmen */
316 FD_SET( My_Connections[i].sock, &write_sockets );
320 /* Sockets mit im Aufbau befindlichen ausgehenden Verbindungen suchen */
321 for( i = 0; i < Pool_Size; i++ )
323 if(( My_Connections[i].sock > NONE ) && ( FD_ISSET( My_Connections[i].sock, &My_Connects ))) FD_SET( My_Connections[i].sock, &write_sockets );
326 /* von welchen Sockets koennte gelesen werden? */
327 t = time( NULL );
328 read_sockets = My_Sockets;
329 for( i = 0; i < Pool_Size; i++ )
331 if(( My_Connections[i].sock > NONE ) && ( My_Connections[i].host[0] == '\0' ))
333 /* Hier muss noch auf den Resolver Sub-Prozess gewartet werden */
334 FD_CLR( My_Connections[i].sock, &read_sockets );
336 if(( My_Connections[i].sock > NONE ) && ( FD_ISSET( My_Connections[i].sock, &My_Connects )))
338 /* Hier laeuft noch ein asyncrones connect() */
339 FD_CLR( My_Connections[i].sock, &read_sockets );
341 if( My_Connections[i].delaytime > t )
343 /* Fuer die Verbindung ist eine "Penalty-Zeit" gesetzt */
344 FD_CLR( My_Connections[i].sock, &read_sockets );
347 for( i = 0; i < Conn_MaxFD + 1; i++ )
349 /* Pipes von Resolver Sub-Prozessen aufnehmen */
350 if( FD_ISSET( i, &Resolver_FDs ))
352 FD_SET( i, &read_sockets );
356 /* Timeout initialisieren */
357 tv.tv_usec = 0;
358 if( timeout ) tv.tv_sec = TIME_RES;
359 else tv.tv_sec = 0;
361 /* Auf Aktivitaet warten */
362 i = select( Conn_MaxFD + 1, &read_sockets, &write_sockets, NULL, &tv );
363 if( i == 0 )
365 /* keine Veraenderung an den Sockets */
366 continue;
368 if( i == -1 )
370 /* Fehler (z.B. Interrupt) */
371 if( errno != EINTR )
373 Log( LOG_EMERG, "Conn_Handler(): select(): %s!", strerror( errno ));
374 Log( LOG_ALERT, "%s exiting due to fatal errors!", PACKAGE );
375 exit( 1 );
377 continue;
380 /* Koennen Daten geschrieben werden? */
381 for( i = 0; i < Conn_MaxFD + 1; i++ )
383 if( ! FD_ISSET( i, &write_sockets )) continue;
385 /* Es kann geschrieben werden ... */
386 idx = Socket2Index( i );
387 if( idx == NONE ) continue;
389 if( ! Handle_Write( idx ))
391 /* Fehler beim Schreiben! Diesen Socket nun
392 * auch aus dem Read-Set entfernen: */
393 FD_CLR( i, &read_sockets );
397 /* Daten zum Lesen vorhanden? */
398 for( i = 0; i < Conn_MaxFD + 1; i++ )
400 if( FD_ISSET( i, &read_sockets )) Handle_Read( i );
404 if( NGIRCd_SignalQuit ) Log( LOG_NOTICE|LOG_snotice, "Server going down NOW!" );
405 else if( NGIRCd_SignalRestart ) Log( LOG_NOTICE|LOG_snotice, "Server restarting NOW!" );
406 } /* Conn_Handler */
409 #ifdef PROTOTYPES
410 GLOBAL BOOLEAN
411 Conn_WriteStr( CONN_ID Idx, CHAR *Format, ... )
412 #else
413 GLOBAL BOOLEAN
414 Conn_WriteStr( Idx, Format, va_alist )
415 CONN_ID Idx;
416 CHAR *Format;
417 va_dcl
418 #endif
420 /* String in Socket schreiben. CR+LF wird von dieser Funktion
421 * automatisch angehaengt. Im Fehlerfall wird dir Verbindung
422 * getrennt und FALSE geliefert. */
424 CHAR buffer[COMMAND_LEN];
425 BOOLEAN ok;
426 va_list ap;
428 assert( Idx > NONE );
429 assert( Format != NULL );
431 #ifdef PROTOTYPES
432 va_start( ap, Format );
433 #else
434 va_start( ap );
435 #endif
436 if( vsnprintf( buffer, COMMAND_LEN - 2, Format, ap ) == COMMAND_LEN - 2 )
438 Log( LOG_CRIT, "Text too long to send (connection %d)!", Idx );
439 Conn_Close( Idx, "Text too long to send!", NULL, FALSE );
440 return FALSE;
443 #ifdef SNIFFER
444 if( NGIRCd_Sniffer ) Log( LOG_DEBUG, " -> connection %d: '%s'.", Idx, buffer );
445 #endif
447 strlcat( buffer, "\r\n", sizeof( buffer ));
448 ok = Conn_Write( Idx, buffer, strlen( buffer ));
449 My_Connections[Idx].msg_out++;
451 va_end( ap );
452 return ok;
453 } /* Conn_WriteStr */
456 GLOBAL BOOLEAN
457 Conn_Write( CONN_ID Idx, CHAR *Data, INT Len )
459 /* Daten in Socket schreiben. Bei "fatalen" Fehlern wird
460 * der Client disconnectiert und FALSE geliefert. */
462 assert( Idx > NONE );
463 assert( Data != NULL );
464 assert( Len > 0 );
466 /* Ist der entsprechende Socket ueberhaupt noch offen? In einem
467 * "Handler-Durchlauf" kann es passieren, dass dem nicht mehr so
468 * ist, wenn einer von mehreren Conn_Write()'s fehlgeschlagen ist.
469 * In diesem Fall wird hier einfach ein Fehler geliefert. */
470 if( My_Connections[Idx].sock <= NONE )
472 Log( LOG_DEBUG, "Skipped write on closed socket (connection %d).", Idx );
473 return FALSE;
476 /* Pruefen, ob im Schreibpuffer genuegend Platz ist. Ziel ist es,
477 * moeglichts viel im Puffer zu haben und _nicht_ gleich alles auf den
478 * Socket zu schreiben (u.a. wg. Komprimierung). */
479 if( WRITEBUFFER_LEN - My_Connections[Idx].wdatalen - Len <= 0 )
481 /* Der Puffer ist dummerweise voll. Jetzt versuchen, den Puffer
482 * zu schreiben, wenn das nicht klappt, haben wir ein Problem ... */
483 if( ! Try_Write( Idx )) return FALSE;
485 /* nun neu pruefen: */
486 if( WRITEBUFFER_LEN - My_Connections[Idx].wdatalen - Len <= 0 )
488 Log( LOG_NOTICE, "Write buffer overflow (connection %d)!", Idx );
489 Conn_Close( Idx, "Write buffer overflow!", NULL, FALSE );
490 return FALSE;
494 #ifdef USE_ZLIB
495 if( My_Connections[Idx].options & CONN_ZIP )
497 /* Daten komprimieren und in Puffer kopieren */
498 if( ! Zip_Buffer( Idx, Data, Len )) return FALSE;
500 else
501 #endif
503 /* Daten in Puffer kopieren */
504 memcpy( My_Connections[Idx].wbuf + My_Connections[Idx].wdatalen, Data, Len );
505 My_Connections[Idx].wdatalen += Len;
506 My_Connections[Idx].bytes_out += Len;
509 /* Adjust global write counter */
510 WCounter += Len;
512 return TRUE;
513 } /* Conn_Write */
516 GLOBAL VOID
517 Conn_Close( CONN_ID Idx, CHAR *LogMsg, CHAR *FwdMsg, BOOLEAN InformClient )
519 /* Close connection. Open pipes of asyncronous resolver
520 * sub-processes are closed down. */
522 CLIENT *c;
523 DOUBLE in_k, out_k;
524 #ifdef USE_ZLIB
525 DOUBLE in_z_k, out_z_k;
526 INT in_p, out_p;
527 #endif
529 assert( Idx > NONE );
530 assert( My_Connections[Idx].sock > NONE );
532 /* Search client, if any */
533 c = Client_GetFromConn( Idx );
535 /* Should the client be informed? */
536 if( InformClient )
538 #ifndef STRICT_RFC
539 /* Send statistics to client if registered as user: */
540 if(( c != NULL ) && ( Client_Type( c ) == CLIENT_USER ))
542 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 );
544 #endif
546 /* Send ERROR to client (see RFC!) */
547 if( FwdMsg ) Conn_WriteStr( Idx, "ERROR :%s", FwdMsg );
548 else Conn_WriteStr( Idx, "ERROR :Closing connection." );
549 if( My_Connections[Idx].sock == NONE ) return;
552 /* Try to write out the write buffer */
553 Try_Write( Idx );
555 /* Shut down socket */
556 if( close( My_Connections[Idx].sock ) != 0 )
558 /* Oops, we can't close the socket!? This is fatal! */
559 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 ));
560 Log( LOG_ALERT, "%s exiting due to fatal errors!", PACKAGE );
561 exit( 1 );
564 /* Mark socket as invalid: */
565 FD_CLR( My_Connections[Idx].sock, &My_Sockets );
566 FD_CLR( My_Connections[Idx].sock, &My_Connects );
567 My_Connections[Idx].sock = NONE;
569 /* If there is still a client, unregister it now */
570 if( c ) Client_Destroy( c, LogMsg, FwdMsg, TRUE );
572 /* Calculate statistics and log information */
573 in_k = (DOUBLE)My_Connections[Idx].bytes_in / 1024;
574 out_k = (DOUBLE)My_Connections[Idx].bytes_out / 1024;
575 #ifdef USE_ZLIB
576 if( My_Connections[Idx].options & CONN_ZIP )
578 in_z_k = (DOUBLE)My_Connections[Idx].zip.bytes_in / 1024;
579 out_z_k = (DOUBLE)My_Connections[Idx].zip.bytes_out / 1024;
580 in_p = (INT)(( in_k * 100 ) / in_z_k );
581 out_p = (INT)(( out_k * 100 ) / out_z_k );
582 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 );
584 else
585 #endif
587 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 );
590 /* Is there a resolver sub-process running? */
591 if( My_Connections[Idx].res_stat )
593 /* Free resolver structures */
594 FD_CLR( My_Connections[Idx].res_stat->pipe[0], &Resolver_FDs );
595 close( My_Connections[Idx].res_stat->pipe[0] );
596 close( My_Connections[Idx].res_stat->pipe[1] );
597 free( My_Connections[Idx].res_stat );
600 /* Servers: Modify time of next connect attempt? */
601 Conf_UnsetServer( Idx );
603 #ifdef USE_ZLIB
604 /* Clean up zlib, if link was compressed */
605 if( Conn_Options( Idx ) & CONN_ZIP )
607 inflateEnd( &My_Connections[Idx].zip.in );
608 deflateEnd( &My_Connections[Idx].zip.out );
610 #endif
612 /* Clean up connection structure (=free it) */
613 Init_Conn_Struct( Idx );
614 } /* Conn_Close */
617 LOCAL BOOLEAN
618 Try_Write( CONN_ID Idx )
620 /* Versuchen, Daten aus dem Schreib-Puffer in den Socket zu
621 * schreiben. TRUE wird geliefert, wenn entweder keine Daten
622 * zum Versenden vorhanden sind oder erfolgreich bearbeitet
623 * werden konnten. Im Fehlerfall wird FALSE geliefert und
624 * die Verbindung geschlossen. */
626 fd_set write_socket;
627 struct timeval tv;
629 assert( Idx > NONE );
630 assert( My_Connections[Idx].sock > NONE );
632 /* sind ueberhaupt Daten vorhanden? */
633 #ifdef USE_ZLIB
634 if(( ! My_Connections[Idx].wdatalen > 0 ) && ( ! My_Connections[Idx].zip.wdatalen )) return TRUE;
635 #else
636 if( ! My_Connections[Idx].wdatalen > 0 ) return TRUE;
637 #endif
639 /* Timeout initialisieren: 0 Sekunden, also nicht blockieren */
640 tv.tv_sec = 0; tv.tv_usec = 0;
642 FD_ZERO( &write_socket );
643 FD_SET( My_Connections[Idx].sock, &write_socket );
644 if( select( My_Connections[Idx].sock + 1, NULL, &write_socket, NULL, &tv ) == -1 )
646 /* Fehler! */
647 if( errno != EINTR )
649 Log( LOG_ALERT, "Try_Write(): select() failed: %s (con=%d, sock=%d)!", strerror( errno ), Idx, My_Connections[Idx].sock );
650 Conn_Close( Idx, "Server error!", NULL, FALSE );
651 return FALSE;
655 if( FD_ISSET( My_Connections[Idx].sock, &write_socket )) return Handle_Write( Idx );
656 else return TRUE;
657 } /* Try_Write */
660 LOCAL VOID
661 Handle_Read( INT Sock )
663 /* Aktivitaet auf einem Socket verarbeiten:
664 * - neue Clients annehmen,
665 * - Daten von Clients verarbeiten,
666 * - Resolver-Rueckmeldungen annehmen. */
668 CONN_ID idx;
670 assert( Sock > NONE );
672 if( FD_ISSET( Sock, &My_Listeners ))
674 /* es ist einer unserer Listener-Sockets: es soll
675 * also eine neue Verbindung aufgebaut werden. */
677 New_Connection( Sock );
679 else if( FD_ISSET( Sock, &Resolver_FDs ))
681 /* Rueckmeldung von einem Resolver Sub-Prozess */
683 Read_Resolver_Result( Sock );
685 else
687 /* Ein Client Socket: entweder ein User oder Server */
689 idx = Socket2Index( Sock );
690 if( idx > NONE ) Read_Request( idx );
692 } /* Handle_Read */
695 LOCAL BOOLEAN
696 Handle_Write( CONN_ID Idx )
698 /* Daten aus Schreibpuffer versenden bzw. Connection aufbauen */
700 INT len, res, err;
702 assert( Idx > NONE );
703 assert( My_Connections[Idx].sock > NONE );
705 if( FD_ISSET( My_Connections[Idx].sock, &My_Connects ))
707 /* es soll nichts geschrieben werden, sondern ein
708 * connect() hat ein Ergebnis geliefert */
710 FD_CLR( My_Connections[Idx].sock, &My_Connects );
712 /* Ergebnis des connect() ermitteln */
713 len = sizeof( err );
714 res = getsockopt( My_Connections[Idx].sock, SOL_SOCKET, SO_ERROR, &err, &len );
715 assert( len == sizeof( err ));
717 /* Fehler aufgetreten? */
718 if(( res != 0 ) || ( err != 0 ))
720 /* Fehler! */
721 if( res != 0 ) Log( LOG_CRIT, "getsockopt (connection %d): %s!", Idx, strerror( errno ));
722 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 ));
724 /* Socket etc. pp. aufraeumen */
725 FD_CLR( My_Connections[Idx].sock, &My_Sockets );
726 close( My_Connections[Idx].sock );
727 Init_Conn_Struct( Idx );
729 /* Bei Server-Verbindungen lasttry-Zeitpunkt auf "jetzt" setzen */
730 Conf_Server[Conf_GetServer( Idx )].lasttry = time( NULL );
731 Conf_UnsetServer( Idx );
733 return FALSE;
735 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 );
737 /* PASS und SERVER verschicken */
738 Conn_WriteStr( Idx, "PASS %s %s", Conf_Server[Conf_GetServer( Idx )].pwd_out, NGIRCd_ProtoID );
739 return Conn_WriteStr( Idx, "SERVER %s :%s", Conf_ServerName, Conf_ServerInfo );
742 #ifdef USE_ZLIB
743 /* Schreibpuffer leer, aber noch Daten im Kompressionsbuffer?
744 * Dann muss dieser nun geflushed werden! */
745 if( My_Connections[Idx].wdatalen == 0 ) Zip_Flush( Idx );
746 #endif
748 assert( My_Connections[Idx].wdatalen > 0 );
750 /* Daten schreiben */
751 len = send( My_Connections[Idx].sock, My_Connections[Idx].wbuf, My_Connections[Idx].wdatalen, 0 );
752 if( len < 0 )
754 /* Operation haette Socket "nur" blockiert ... */
755 if( errno == EAGAIN ) return TRUE;
757 /* Oops, ein Fehler! */
758 Log( LOG_ERR, "Write error on connection %d (socket %d): %s!", Idx, My_Connections[Idx].sock, strerror( errno ));
759 Conn_Close( Idx, "Write error!", NULL, FALSE );
760 return FALSE;
763 /* Puffer anpassen */
764 My_Connections[Idx].wdatalen -= len;
765 memmove( My_Connections[Idx].wbuf, My_Connections[Idx].wbuf + len, My_Connections[Idx].wdatalen );
767 return TRUE;
768 } /* Handle_Write */
771 LOCAL VOID
772 New_Connection( INT Sock )
774 /* Neue Client-Verbindung von Listen-Socket annehmen und
775 * CLIENT-Struktur anlegen. */
777 struct sockaddr_in new_addr;
778 INT new_sock, new_sock_len;
779 RES_STAT *s;
780 CONN_ID idx;
781 CLIENT *c;
782 POINTER *ptr;
783 LONG new_size;
785 assert( Sock > NONE );
787 /* Connection auf Listen-Socket annehmen */
788 new_sock_len = sizeof( new_addr );
789 new_sock = accept( Sock, (struct sockaddr *)&new_addr, (socklen_t *)&new_sock_len );
790 if( new_sock < 0 )
792 Log( LOG_CRIT, "Can't accept connection: %s!", strerror( errno ));
793 return;
796 /* Socket initialisieren */
797 Init_Socket( new_sock );
799 /* Freie Connection-Struktur suchen */
800 for( idx = 0; idx < Pool_Size; idx++ ) if( My_Connections[idx].sock == NONE ) break;
801 if( idx >= Pool_Size )
803 new_size = Pool_Size + CONNECTION_POOL;
805 /* Im bisherigen Pool wurde keine freie Connection-Struktur mehr gefunden.
806 * Wenn erlaubt und moeglich muss nun der Pool vergroessert werden: */
808 if( Conf_MaxConnections > 0 )
810 /* Es ist ein Limit konfiguriert */
811 if( Pool_Size >= Conf_MaxConnections )
813 /* Mehr Verbindungen duerfen wir leider nicht mehr annehmen ... */
814 Log( LOG_ALERT, "Can't accept connection: limit (%d) reached!", Pool_Size );
815 close( new_sock );
816 return;
818 if( new_size > Conf_MaxConnections ) new_size = Conf_MaxConnections;
820 if( new_size < Pool_Size )
822 Log( LOG_ALERT, "Can't accespt connection: limit (%d) reached -- overflow!", Pool_Size );
823 close( new_sock );
824 return;
827 /* zunaechst realloc() versuchen; wenn das scheitert, malloc() versuchen
828 * und Daten ggf. "haendisch" umkopieren. (Haesslich! Eine wirklich
829 * dynamische Verwaltung waere wohl _deutlich_ besser ...) */
830 ptr = realloc( My_Connections, sizeof( CONNECTION ) * new_size );
831 if( ! ptr )
833 /* realloc() ist fehlgeschlagen. Nun malloc() probieren: */
834 ptr = malloc( sizeof( CONNECTION ) * new_size );
835 if( ! ptr )
837 /* Offenbar steht kein weiterer Sepeicher zur Verfuegung :-( */
838 Log( LOG_EMERG, "Can't allocate memory! [New_Connection]" );
839 close( new_sock );
840 return;
843 /* Struktur umkopieren ... */
844 memcpy( ptr, My_Connections, sizeof( CONNECTION ) * Pool_Size );
846 Log( LOG_DEBUG, "Allocated new connection pool for %ld items (%ld bytes). [malloc()/memcpy()]", new_size, sizeof( CONNECTION ) * new_size );
848 else Log( LOG_DEBUG, "Allocated new connection pool for %ld items (%ld bytes). [realloc()]", new_size, sizeof( CONNECTION ) * new_size );
850 /* Adjust pointer to new block */
851 My_Connections = ptr;
853 /* Initialize new items */
854 for( idx = Pool_Size; idx < new_size; idx++ ) Init_Conn_Struct( idx );
855 idx = Pool_Size;
857 /* Adjust new pool size */
858 Pool_Size = new_size;
861 /* Client-Struktur initialisieren */
862 c = Client_NewLocal( idx, inet_ntoa( new_addr.sin_addr ), CLIENT_UNKNOWN, FALSE );
863 if( ! c )
865 Log( LOG_ALERT, "Can't accept connection: can't create client structure!" );
866 close( new_sock );
867 return;
870 /* Verbindung registrieren */
871 Init_Conn_Struct( idx );
872 My_Connections[idx].sock = new_sock;
873 My_Connections[idx].addr = new_addr;
875 /* Neuen Socket registrieren */
876 FD_SET( new_sock, &My_Sockets );
877 if( new_sock > Conn_MaxFD ) Conn_MaxFD = new_sock;
879 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 );
881 /* Hostnamen ermitteln */
882 strlcpy( My_Connections[idx].host, inet_ntoa( new_addr.sin_addr ), sizeof( My_Connections[idx].host ));
883 Client_SetHostname( c, My_Connections[idx].host );
884 s = Resolve_Addr( &new_addr );
885 if( s )
887 /* Sub-Prozess wurde asyncron gestartet */
888 My_Connections[idx].res_stat = s;
891 /* Penalty-Zeit setzen */
892 Conn_SetPenalty( idx, 4 );
893 } /* New_Connection */
896 LOCAL CONN_ID
897 Socket2Index( INT Sock )
899 /* zum Socket passende Connection suchen */
901 CONN_ID idx;
903 assert( Sock > NONE );
905 for( idx = 0; idx < Pool_Size; idx++ ) if( My_Connections[idx].sock == Sock ) break;
907 if( idx >= Pool_Size )
909 /* die Connection wurde vermutlich (wegen eines
910 * Fehlers) bereits wieder abgebaut ... */
911 Log( LOG_DEBUG, "Socket2Index: can't get connection for socket %d!", Sock );
912 return NONE;
914 else return idx;
915 } /* Socket2Index */
918 LOCAL VOID
919 Read_Request( CONN_ID Idx )
921 /* Daten von Socket einlesen und entsprechend behandeln.
922 * Tritt ein Fehler auf, so wird der Socket geschlossen. */
924 INT len, bsize;
925 #ifdef USE_ZLIB
926 CLIENT *c;
927 #endif
929 assert( Idx > NONE );
930 assert( My_Connections[Idx].sock > NONE );
932 /* wenn noch nicht registriert: maximal mit ZREADBUFFER_LEN arbeiten,
933 * ansonsten koennen Daten ggf. nicht umkopiert werden. */
934 bsize = READBUFFER_LEN;
935 #ifdef USE_ZLIB
936 c = Client_GetFromConn( Idx );
937 if(( Client_Type( c ) != CLIENT_USER ) && ( Client_Type( c ) != CLIENT_SERVER ) && ( Client_Type( c ) != CLIENT_SERVICE ) && ( bsize > ZREADBUFFER_LEN )) bsize = ZREADBUFFER_LEN;
938 #endif
940 #ifdef USE_ZLIB
941 if(( bsize - My_Connections[Idx].rdatalen - 1 < 1 ) || ( ZREADBUFFER_LEN - My_Connections[Idx].zip.rdatalen < 1 ))
942 #else
943 if( bsize - My_Connections[Idx].rdatalen - 1 < 1 )
944 #endif
946 /* Der Lesepuffer ist voll */
947 Log( LOG_ERR, "Read buffer overflow (connection %d): %d bytes!", Idx, My_Connections[Idx].rdatalen );
948 Conn_Close( Idx, "Read buffer overflow!", NULL, FALSE );
949 return;
952 #ifdef USE_ZLIB
953 if( My_Connections[Idx].options & CONN_ZIP )
955 len = recv( My_Connections[Idx].sock, My_Connections[Idx].zip.rbuf + My_Connections[Idx].zip.rdatalen, ( ZREADBUFFER_LEN - My_Connections[Idx].zip.rdatalen ), 0 );
956 if( len > 0 ) My_Connections[Idx].zip.rdatalen += len;
958 else
959 #endif
961 len = recv( My_Connections[Idx].sock, My_Connections[Idx].rbuf + My_Connections[Idx].rdatalen, bsize - My_Connections[Idx].rdatalen - 1, 0 );
962 if( len > 0 ) My_Connections[Idx].rdatalen += len;
965 if( len == 0 )
967 /* Socket wurde geschlossen */
968 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 ));
969 Conn_Close( Idx, "Socket closed!", "Client closed connection", FALSE );
970 return;
973 if( len < 0 )
975 /* Operation haette Socket "nur" blockiert ... */
976 if( errno == EAGAIN ) return;
978 /* Fehler beim Lesen */
979 Log( LOG_ERR, "Read error on connection %d (socket %d): %s!", Idx, My_Connections[Idx].sock, strerror( errno ));
980 Conn_Close( Idx, "Read error!", "Client closed connection", FALSE );
981 return;
984 /* Connection-Statistik aktualisieren */
985 My_Connections[Idx].bytes_in += len;
987 /* Timestamp aktualisieren */
988 My_Connections[Idx].lastdata = time( NULL );
990 Handle_Buffer( Idx );
991 } /* Read_Request */
994 LOCAL BOOLEAN
995 Handle_Buffer( CONN_ID Idx )
997 /* Daten im Lese-Puffer einer Verbindung verarbeiten.
998 * Wurde ein Request verarbeitet, so wird TRUE geliefert,
999 * ansonsten FALSE (auch bei Fehlern). */
1001 #ifndef STRICT_RFC
1002 CHAR *ptr1, *ptr2;
1003 #endif
1004 CHAR *ptr;
1005 INT len, delta;
1006 BOOLEAN action, result;
1007 #ifdef USE_ZLIB
1008 BOOLEAN old_z;
1009 #endif
1011 result = FALSE;
1014 #ifdef USE_ZLIB
1015 /* ggf. noch unkomprimiete Daten weiter entpacken */
1016 if( My_Connections[Idx].options & CONN_ZIP )
1018 if( ! Unzip_Buffer( Idx )) return FALSE;
1020 #endif
1022 if( My_Connections[Idx].rdatalen < 1 ) break;
1024 /* Eine komplette Anfrage muss mit CR+LF enden, vgl.
1025 * RFC 2812. Haben wir eine? */
1026 My_Connections[Idx].rbuf[My_Connections[Idx].rdatalen] = '\0';
1027 ptr = strstr( My_Connections[Idx].rbuf, "\r\n" );
1029 if( ptr ) delta = 2;
1030 #ifndef STRICT_RFC
1031 else
1033 /* Nicht RFC-konforme Anfrage mit nur CR oder LF? Leider
1034 * machen soetwas viele Clients, u.a. "mIRC" :-( */
1035 ptr1 = strchr( My_Connections[Idx].rbuf, '\r' );
1036 ptr2 = strchr( My_Connections[Idx].rbuf, '\n' );
1037 delta = 1;
1038 if( ptr1 && ptr2 ) ptr = ptr1 > ptr2 ? ptr2 : ptr1;
1039 else if( ptr1 ) ptr = ptr1;
1040 else if( ptr2 ) ptr = ptr2;
1042 #endif
1044 action = FALSE;
1045 if( ptr )
1047 /* Ende der Anfrage wurde gefunden */
1048 *ptr = '\0';
1049 len = ( ptr - My_Connections[Idx].rbuf ) + delta;
1050 if( len > ( COMMAND_LEN - 1 ))
1052 /* Eine Anfrage darf(!) nicht laenger als 512 Zeichen
1053 * (incl. CR+LF!) werden; vgl. RFC 2812. Wenn soetwas
1054 * empfangen wird, wird der Client disconnectiert. */
1055 Log( LOG_ERR, "Request too long (connection %d): %d bytes (max. %d expected)!", Idx, My_Connections[Idx].rdatalen, COMMAND_LEN - 1 );
1056 Conn_Close( Idx, NULL, "Request too long", TRUE );
1057 return FALSE;
1060 #ifdef USE_ZLIB
1061 /* merken, ob Stream bereits komprimiert wird */
1062 old_z = My_Connections[Idx].options & CONN_ZIP;
1063 #endif
1065 if( len > delta )
1067 /* Es wurde ein Request gelesen */
1068 My_Connections[Idx].msg_in++;
1069 if( ! Parse_Request( Idx, My_Connections[Idx].rbuf )) return FALSE;
1070 else action = TRUE;
1073 /* Puffer anpassen */
1074 My_Connections[Idx].rdatalen -= len;
1075 memmove( My_Connections[Idx].rbuf, My_Connections[Idx].rbuf + len, My_Connections[Idx].rdatalen );
1077 #ifdef USE_ZLIB
1078 if(( ! old_z ) && ( My_Connections[Idx].options & CONN_ZIP ) && ( My_Connections[Idx].rdatalen > 0 ))
1080 /* Mit dem letzten Befehl wurde Socket-Kompression aktiviert.
1081 * Evtl. schon vom Socket gelesene Daten in den Unzip-Puffer
1082 * umkopieren, damit diese nun zunaechst entkomprimiert werden */
1084 if( My_Connections[Idx].rdatalen > ZREADBUFFER_LEN )
1086 /* Hupsa! Soviel Platz haben wir aber gar nicht! */
1087 Log( LOG_ALERT, "Can't move read buffer: No space left in unzip buffer (need %d bytes)!", My_Connections[Idx].rdatalen );
1088 return FALSE;
1090 memcpy( My_Connections[Idx].zip.rbuf, My_Connections[Idx].rbuf, My_Connections[Idx].rdatalen );
1091 My_Connections[Idx].zip.rdatalen = My_Connections[Idx].rdatalen;
1092 My_Connections[Idx].rdatalen = 0;
1093 Log( LOG_DEBUG, "Moved already received data (%d bytes) to uncompression buffer.", My_Connections[Idx].zip.rdatalen );
1096 #endif
1099 if( action ) result = TRUE;
1100 } while( action );
1102 return result;
1103 } /* Handle_Buffer */
1106 LOCAL VOID
1107 Check_Connections( VOID )
1109 /* Pruefen, ob Verbindungen noch "alive" sind. Ist dies
1110 * nicht der Fall, zunaechst PING-PONG spielen und, wenn
1111 * auch das nicht "hilft", Client disconnectieren. */
1113 CLIENT *c;
1114 CONN_ID i;
1116 for( i = 0; i < Pool_Size; i++ )
1118 if( My_Connections[i].sock == NONE ) continue;
1120 c = Client_GetFromConn( i );
1121 if( c && (( Client_Type( c ) == CLIENT_USER ) || ( Client_Type( c ) == CLIENT_SERVER ) || ( Client_Type( c ) == CLIENT_SERVICE )))
1123 /* verbundener User, Server oder Service */
1124 if( My_Connections[i].lastping > My_Connections[i].lastdata )
1126 /* es wurde bereits ein PING gesendet */
1127 if( My_Connections[i].lastping < time( NULL ) - Conf_PongTimeout )
1129 /* Timeout */
1130 Log( LOG_DEBUG, "Connection %d: Ping timeout: %d seconds.", i, Conf_PongTimeout );
1131 Conn_Close( i, NULL, "Ping timeout", TRUE );
1134 else if( My_Connections[i].lastdata < time( NULL ) - Conf_PingTimeout )
1136 /* es muss ein PING gesendet werden */
1137 Log( LOG_DEBUG, "Connection %d: sending PING ...", i );
1138 My_Connections[i].lastping = time( NULL );
1139 Conn_WriteStr( i, "PING :%s", Client_ID( Client_ThisServer( )));
1142 else
1144 /* noch nicht vollstaendig aufgebaute Verbindung */
1145 if( My_Connections[i].lastdata < time( NULL ) - Conf_PingTimeout )
1147 /* Timeout */
1148 Log( LOG_DEBUG, "Connection %d timed out ...", i );
1149 Conn_Close( i, NULL, "Timeout", FALSE );
1153 } /* Check_Connections */
1156 LOCAL VOID
1157 Check_Servers( VOID )
1159 /* Check if we can establish further server links */
1161 RES_STAT *s;
1162 CONN_ID idx;
1163 INT i, n;
1165 /* Serach all connections, are there results from the resolver? */
1166 for( idx = 0; idx < Pool_Size; idx++ )
1168 if( My_Connections[idx].sock != SERVER_WAIT ) continue;
1170 /* IP resolved? */
1171 if( My_Connections[idx].res_stat == NULL ) New_Server( Conf_GetServer( idx ), idx );
1174 /* Check all configured servers */
1175 for( i = 0; i < MAX_SERVERS; i++ )
1177 /* Valid outgoing server which isn't already connected or disabled? */
1178 if(( ! Conf_Server[i].host[0] ) || ( ! Conf_Server[i].port > 0 ) || ( Conf_Server[i].conn_id > NONE ) || ( Conf_Server[i].flags & CONF_SFLAG_DISABLED )) continue;
1180 /* Is there already a connection in this group? */
1181 if( Conf_Server[i].group > NONE )
1183 for( n = 0; n < MAX_SERVERS; n++ )
1185 if( n == i ) continue;
1186 if(( Conf_Server[n].conn_id > NONE ) && ( Conf_Server[n].group == Conf_Server[i].group )) break;
1188 if( n < MAX_SERVERS ) continue;
1191 /* Check last connect attempt? */
1192 if( Conf_Server[i].lasttry > time( NULL ) - Conf_ConnectRetry ) continue;
1194 /* Okay, try to connect now */
1195 Conf_Server[i].lasttry = time( NULL );
1197 /* Search free connection structure */
1198 for( idx = 0; idx < Pool_Size; idx++ ) if( My_Connections[idx].sock == NONE ) break;
1199 if( idx >= Pool_Size )
1201 Log( LOG_ALERT, "Can't establist server connection: connection limit reached (%d)!", Pool_Size );
1202 return;
1204 Log( LOG_DEBUG, "Preparing connection %d for \"%s\" ...", idx, Conf_Server[i].host );
1206 /* Verbindungs-Struktur initialisieren */
1207 Init_Conn_Struct( idx );
1208 My_Connections[idx].sock = SERVER_WAIT;
1209 Conf_Server[i].conn_id = idx;
1211 /* Resolve Hostname. If this fails, try to use it as an IP address */
1212 strlcpy( Conf_Server[i].ip, Conf_Server[i].host, sizeof( Conf_Server[i].ip ));
1213 strlcpy( My_Connections[idx].host, Conf_Server[i].host, sizeof( My_Connections[idx].host ));
1214 s = Resolve_Name( Conf_Server[i].host );
1215 if( s )
1217 /* Sub-Prozess wurde asyncron gestartet */
1218 My_Connections[idx].res_stat = s;
1221 } /* Check_Servers */
1224 LOCAL VOID
1225 New_Server( INT Server, CONN_ID Idx )
1227 /* Neue Server-Verbindung aufbauen */
1229 struct sockaddr_in new_addr;
1230 struct in_addr inaddr;
1231 INT res, new_sock;
1232 CLIENT *c;
1234 assert( Server > NONE );
1235 assert( Idx > NONE );
1237 /* Wurde eine gueltige IP-Adresse gefunden? */
1238 if( ! Conf_Server[Server].ip[0] )
1240 /* Nein. Verbindung wieder freigeben: */
1241 Init_Conn_Struct( Idx );
1242 Log( LOG_ERR, "Can't connect to \"%s\" (connection %d): ip address unknown!", Conf_Server[Server].host, Idx );
1243 return;
1246 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 );
1248 #ifdef HAVE_INET_ATON
1249 if( inet_aton( Conf_Server[Server].ip, &inaddr ) == 0 )
1250 #else
1251 memset( &inaddr, 0, sizeof( inaddr ));
1252 inaddr.s_addr = inet_addr( Conf_Server[Server].ip );
1253 if( inaddr.s_addr == (unsigned)-1 )
1254 #endif
1256 /* Konnte Adresse nicht konvertieren */
1257 Init_Conn_Struct( Idx );
1258 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 );
1259 return;
1262 memset( &new_addr, 0, sizeof( new_addr ));
1263 new_addr.sin_family = AF_INET;
1264 new_addr.sin_addr = inaddr;
1265 new_addr.sin_port = htons( Conf_Server[Server].port );
1267 new_sock = socket( PF_INET, SOCK_STREAM, 0 );
1268 if ( new_sock < 0 )
1270 Init_Conn_Struct( Idx );
1271 Log( LOG_CRIT, "Can't create socket: %s!", strerror( errno ));
1272 return;
1275 if( ! Init_Socket( new_sock )) return;
1277 res = connect( new_sock, (struct sockaddr *)&new_addr, sizeof( new_addr ));
1278 if(( res != 0 ) && ( errno != EINPROGRESS ))
1280 Log( LOG_CRIT, "Can't connect socket: %s!", strerror( errno ));
1281 close( new_sock );
1282 Init_Conn_Struct( Idx );
1283 return;
1286 /* Client-Struktur initialisieren */
1287 c = Client_NewLocal( Idx, inet_ntoa( new_addr.sin_addr ), CLIENT_UNKNOWNSERVER, FALSE );
1288 if( ! c )
1290 close( new_sock );
1291 Init_Conn_Struct( Idx );
1292 Log( LOG_ALERT, "Can't establish connection: can't create client structure!" );
1293 return;
1295 Client_SetIntroducer( c, c );
1296 Client_SetToken( c, TOKEN_OUTBOUND );
1298 /* Verbindung registrieren */
1299 My_Connections[Idx].sock = new_sock;
1300 My_Connections[Idx].addr = new_addr;
1301 strlcpy( My_Connections[Idx].host, Conf_Server[Server].host, sizeof( My_Connections[Idx].host ));
1303 /* Neuen Socket registrieren */
1304 FD_SET( new_sock, &My_Sockets );
1305 FD_SET( new_sock, &My_Connects );
1306 if( new_sock > Conn_MaxFD ) Conn_MaxFD = new_sock;
1308 Log( LOG_DEBUG, "Registered new connection %d on socket %d.", Idx, My_Connections[Idx].sock );
1309 } /* New_Server */
1312 LOCAL VOID
1313 Init_Conn_Struct( CONN_ID Idx )
1315 /* Connection-Struktur initialisieren */
1317 My_Connections[Idx].sock = NONE;
1318 My_Connections[Idx].res_stat = NULL;
1319 My_Connections[Idx].host[0] = '\0';
1320 My_Connections[Idx].rbuf[0] = '\0';
1321 My_Connections[Idx].rdatalen = 0;
1322 My_Connections[Idx].wbuf[0] = '\0';
1323 My_Connections[Idx].wdatalen = 0;
1324 My_Connections[Idx].starttime = time( NULL );
1325 My_Connections[Idx].lastdata = time( NULL );
1326 My_Connections[Idx].lastping = 0;
1327 My_Connections[Idx].lastprivmsg = time( NULL );
1328 My_Connections[Idx].delaytime = 0;
1329 My_Connections[Idx].bytes_in = 0;
1330 My_Connections[Idx].bytes_out = 0;
1331 My_Connections[Idx].msg_in = 0;
1332 My_Connections[Idx].msg_out = 0;
1333 My_Connections[Idx].flag = 0;
1334 My_Connections[Idx].options = 0;
1336 #ifdef USE_ZLIB
1337 My_Connections[Idx].zip.rbuf[0] = '\0';
1338 My_Connections[Idx].zip.rdatalen = 0;
1339 My_Connections[Idx].zip.wbuf[0] = '\0';
1340 My_Connections[Idx].zip.wdatalen = 0;
1341 My_Connections[Idx].zip.bytes_in = 0;
1342 My_Connections[Idx].zip.bytes_out = 0;
1343 #endif
1344 } /* Init_Conn_Struct */
1347 LOCAL BOOLEAN
1348 Init_Socket( INT Sock )
1350 /* Socket-Optionen setzen */
1352 INT on = 1;
1354 #ifdef O_NONBLOCK /* A/UX kennt das nicht? */
1355 if( fcntl( Sock, F_SETFL, O_NONBLOCK ) != 0 )
1357 Log( LOG_CRIT, "Can't enable non-blocking mode: %s!", strerror( errno ));
1358 close( Sock );
1359 return FALSE;
1361 #endif
1362 if( setsockopt( Sock, SOL_SOCKET, SO_REUSEADDR, &on, (socklen_t)sizeof( on )) != 0)
1364 Log( LOG_ERR, "Can't set socket options: %s!", strerror( errno ));
1365 /* dieser Fehler kann ignoriert werden. */
1368 return TRUE;
1369 } /* Init_Socket */
1372 LOCAL VOID
1373 Read_Resolver_Result( INT r_fd )
1375 /* Ergebnis von Resolver Sub-Prozess aus Pipe lesen
1376 * und entsprechende Connection aktualisieren */
1378 CHAR result[HOST_LEN];
1379 CLIENT *c;
1380 INT len, i, n;
1382 FD_CLR( r_fd, &Resolver_FDs );
1384 /* Anfrage vom Parent lesen */
1385 len = read( r_fd, result, HOST_LEN - 1 );
1386 if( len < 0 )
1388 /* Fehler beim Lesen aus der Pipe */
1389 close( r_fd );
1390 Log( LOG_CRIT, "Resolver: Can't read result: %s!", strerror( errno ));
1391 return;
1393 result[len] = '\0';
1395 /* zugehoerige Connection suchen */
1396 for( i = 0; i < Pool_Size; i++ )
1398 if(( My_Connections[i].sock != NONE ) && ( My_Connections[i].res_stat ) && ( My_Connections[i].res_stat->pipe[0] == r_fd )) break;
1400 if( i >= Pool_Size )
1402 /* Opsa! Keine passende Connection gefunden!? Vermutlich
1403 * wurde sie schon wieder geschlossen. */
1404 close( r_fd );
1405 Log( LOG_DEBUG, "Resolver: Got result for unknown connection!?" );
1406 return;
1409 Log( LOG_DEBUG, "Resolver: %s is \"%s\".", My_Connections[i].host, result );
1411 /* Aufraeumen */
1412 close( My_Connections[i].res_stat->pipe[0] );
1413 close( My_Connections[i].res_stat->pipe[1] );
1414 free( My_Connections[i].res_stat );
1415 My_Connections[i].res_stat = NULL;
1417 if( My_Connections[i].sock > NONE )
1419 /* Eingehende Verbindung: Hostnamen setzen */
1420 c = Client_GetFromConn( i );
1421 assert( c != NULL );
1422 strlcpy( My_Connections[i].host, result, sizeof( My_Connections[i].host ));
1423 Client_SetHostname( c, result );
1425 else
1427 /* Ausgehende Verbindung (=Server): IP setzen */
1428 n = Conf_GetServer( i );
1429 if( n > NONE ) strlcpy( Conf_Server[n].ip, result, sizeof( Conf_Server[n].ip ));
1430 else Log( LOG_ERR, "Got resolver result for non-configured server!?" );
1433 /* Penalty-Zeit zurueck setzen */
1434 Conn_ResetPenalty( i );
1435 } /* Read_Resolver_Result */
1438 /* -eof- */