]> arthur.barton.de Git - ngircd-alex.git/blob - src/ngircd/conn.c
e3f88011b178731f8a2e4c70ab2d82e4dfd09622
[ngircd-alex.git] / src / ngircd / conn.c
1 /*
2  * ngIRCd -- The Next Generation IRC Daemon
3  * Copyright (c)2001-2003 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  */
13
14
15 #define CONN_MODULE
16
17 #include "portab.h"
18
19 static char UNUSED id[] = "$Id: conn.c,v 1.117 2003/02/23 12:04:05 alex Exp $";
20
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>
35
36 #ifdef HAVE_ARPA_INET_H
37 #include <arpa/inet.h>
38 #else
39 #define PF_INET AF_INET
40 #endif
41
42 #ifdef HAVE_STDINT_H
43 #include <stdint.h>                     /* u.a. fuer Mac OS X */
44 #endif
45
46 #include "defines.h"
47 #include "resolve.h"
48
49 #include "exp.h"
50 #include "conn.h"
51
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"
61
62 #ifdef RENDEZVOUS
63 #include "rendezvous.h"
64 #endif
65
66 #include "exp.h"
67
68
69 #define SERVER_WAIT (NONE - 1)
70
71
72 LOCAL VOID Handle_Read PARAMS(( INT sock ));
73 LOCAL BOOLEAN Handle_Write PARAMS(( CONN_ID Idx ));
74 LOCAL VOID New_Connection PARAMS(( INT Sock ));
75 LOCAL CONN_ID Socket2Index PARAMS(( INT Sock ));
76 LOCAL VOID Read_Request PARAMS(( CONN_ID Idx ));
77 LOCAL BOOLEAN Try_Write PARAMS(( CONN_ID Idx ));
78 LOCAL BOOLEAN Handle_Buffer PARAMS(( CONN_ID Idx ));
79 LOCAL VOID Check_Connections PARAMS(( VOID ));
80 LOCAL VOID Check_Servers PARAMS(( VOID ));
81 LOCAL VOID Init_Conn_Struct PARAMS(( CONN_ID Idx ));
82 LOCAL BOOLEAN Init_Socket PARAMS(( INT Sock ));
83 LOCAL VOID New_Server PARAMS(( INT Server, CONN_ID Idx ));
84 LOCAL VOID Read_Resolver_Result PARAMS(( INT r_fd ));
85
86 LOCAL fd_set My_Listeners;
87 LOCAL fd_set My_Sockets;
88 LOCAL fd_set My_Connects;
89
90
91 GLOBAL VOID
92 Conn_Init( VOID )
93 {
94         /* Modul initialisieren: statische Strukturen "ausnullen". */
95
96         CONN_ID i;
97
98         /* Speicher fuer Verbindungs-Pool anfordern */
99         Pool_Size = CONNECTION_POOL;
100         if( Conf_MaxConnections > 0 )
101         {
102                 /* konfiguriertes Limit beachten */
103                 if( Pool_Size > Conf_MaxConnections ) Pool_Size = Conf_MaxConnections;
104         }
105         My_Connections = malloc( sizeof( CONNECTION ) * Pool_Size );
106         if( ! My_Connections )
107         {
108                 /* Speicher konnte nicht alloziert werden! */
109                 Log( LOG_EMERG, "Can't allocate memory! [Conn_Init]" );
110                 exit( 1 );
111         }
112         Log( LOG_DEBUG, "Allocted connection pool for %d items (%ld bytes).", Pool_Size, sizeof( CONNECTION ) * Pool_Size );
113
114         /* zu Beginn haben wir keine Verbindungen */
115         FD_ZERO( &My_Listeners );
116         FD_ZERO( &My_Sockets );
117         FD_ZERO( &My_Connects );
118
119         /* Groesster File-Descriptor fuer select() */
120         Conn_MaxFD = 0;
121
122         /* Connection-Struktur initialisieren */
123         for( i = 0; i < Pool_Size; i++ ) Init_Conn_Struct( i );
124
125         /* Global write counter */
126         WCounter = 0;
127 } /* Conn_Init */
128
129
130 GLOBAL VOID
131 Conn_Exit( VOID )
132 {
133         /* Modul abmelden: alle noch offenen Connections
134          * schliessen und freigeben. */
135
136         CONN_ID idx;
137         INT i;
138
139         Log( LOG_DEBUG, "Shutting down all connections ..." );
140
141 #ifdef RENDEZVOUS
142         Rendezvous_UnregisterListeners( );
143 #endif
144         
145         /* Sockets schliessen */
146         for( i = 0; i < Conn_MaxFD + 1; i++ )
147         {
148                 if( FD_ISSET( i, &My_Sockets ))
149                 {
150                         for( idx = 0; idx < Pool_Size; idx++ )
151                         {
152                                 if( My_Connections[idx].sock == i ) break;
153                         }
154                         if( FD_ISSET( i, &My_Listeners ))
155                         {
156                                 close( i );
157                                 Log( LOG_DEBUG, "Listening socket %d closed.", i );
158                         }
159                         else if( FD_ISSET( i, &My_Connects ))
160                         {
161                                 close( i );
162                                 Log( LOG_DEBUG, "Connection %d closed during creation (socket %d).", idx, i );
163                         }
164                         else if( idx < Pool_Size )
165                         {
166                                 if( NGIRCd_SignalRestart ) Conn_Close( idx, NULL, "Server going down (restarting)", TRUE );
167                                 else Conn_Close( idx, NULL, "Server going down", TRUE );
168                         }
169                         else
170                         {
171                                 Log( LOG_WARNING, "Closing unknown connection %d ...", i );
172                                 close( i );
173                         }
174                 }
175         }
176         
177         free( My_Connections );
178         My_Connections = NULL;
179         Pool_Size = 0;
180 } /* Conn_Exit */
181
182
183 GLOBAL INT
184 Conn_InitListeners( VOID )
185 {
186         /* Initialize ports on which the server should accept connections */
187
188         INT created, i;
189
190         created = 0;
191         for( i = 0; i < Conf_ListenPorts_Count; i++ )
192         {
193                 if( Conn_NewListener( Conf_ListenPorts[i] )) created++;
194                 else Log( LOG_ERR, "Can't listen on port %u!", Conf_ListenPorts[i] );
195         }
196         return created;
197 } /* Conn_InitListeners */
198
199
200 GLOBAL VOID
201 Conn_ExitListeners( VOID )
202 {
203         /* Close down all listening sockets */
204
205         INT i;
206
207 #ifdef RENDEZVOUS
208         Rendezvous_UnregisterListeners( );
209 #endif
210         
211         Log( LOG_INFO, "Shutting down all listening sockets ..." );
212         for( i = 0; i < Conn_MaxFD + 1; i++ )
213         {
214                 if( FD_ISSET( i, &My_Sockets ) && FD_ISSET( i, &My_Listeners ))
215                 {
216                         close( i );
217                         Log( LOG_DEBUG, "Listening socket %d closed.", i );
218                 }
219         }
220 } /* Conn_ExitListeners */
221
222
223 GLOBAL BOOLEAN
224 Conn_NewListener( CONST UINT Port )
225 {
226         /* Create new listening socket on specified port */
227
228         struct sockaddr_in addr;
229         INT sock;
230 #ifdef RENDEZVOUS
231         CHAR name[CLIENT_ID_LEN], *info;
232 #endif
233         
234         /* Server-"Listen"-Socket initialisieren */
235         memset( &addr, 0, sizeof( addr ));
236         addr.sin_family = AF_INET;
237         addr.sin_port = htons( Port );
238         addr.sin_addr.s_addr = htonl( INADDR_ANY );
239
240         /* Socket erzeugen */
241         sock = socket( PF_INET, SOCK_STREAM, 0);
242         if( sock < 0 )
243         {
244                 Log( LOG_CRIT, "Can't create socket: %s!", strerror( errno ));
245                 return FALSE;
246         }
247
248         if( ! Init_Socket( sock )) return FALSE;
249
250         /* an Port binden */
251         if( bind( sock, (struct sockaddr *)&addr, (socklen_t)sizeof( addr )) != 0 )
252         {
253                 Log( LOG_CRIT, "Can't bind socket: %s!", strerror( errno ));
254                 close( sock );
255                 return FALSE;
256         }
257
258         /* in "listen mode" gehen :-) */
259         if( listen( sock, 10 ) != 0 )
260         {
261                 Log( LOG_CRIT, "Can't listen on soecket: %s!", strerror( errno ));
262                 close( sock );
263                 return FALSE;
264         }
265
266         /* Neuen Listener in Strukturen einfuegen */
267         FD_SET( sock, &My_Listeners );
268         FD_SET( sock, &My_Sockets );
269
270         if( sock > Conn_MaxFD ) Conn_MaxFD = sock;
271
272         Log( LOG_INFO, "Now listening on port %d (socket %d).", Port, sock );
273
274 #ifdef RENDEZVOUS
275         /* Get best server description text */
276         if( ! Conf_ServerInfo[0] ) info = Conf_ServerName;
277         else
278         {
279                 /* Use server info string */
280                 info = NULL;
281                 if( Conf_ServerInfo[0] == '[' )
282                 {
283                         /* Cut off leading hostname part in "[]" */
284                         info = strchr( Conf_ServerInfo, ']' );
285                         if( info )
286                         {
287                                 info++;
288                                 while( *info == ' ' ) info++;
289                         }
290                 }
291                 if( ! info ) info = Conf_ServerInfo;
292         }
293
294         /* Add port number to description if non-standard */
295         if( Port != 6667 ) snprintf( name, sizeof( name ), "%s (port %u)", info, Port );
296         else strlcpy( name, info, sizeof( name ));
297
298         /* Register service */
299         Rendezvous_Register( name, RENDEZVOUS_TYPE, Port );
300 #endif
301
302         return TRUE;
303 } /* Conn_NewListener */
304
305
306 GLOBAL VOID
307 Conn_Handler( VOID )
308 {
309         /* "Hauptschleife": Aktive Verbindungen ueberwachen. Folgende Aktionen
310          * werden dabei durchgefuehrt, bis der Server terminieren oder neu
311          * starten soll:
312          *
313          *  - neue Verbindungen annehmen,
314          *  - Server-Verbindungen aufbauen,
315          *  - geschlossene Verbindungen loeschen,
316          *  - volle Schreibpuffer versuchen zu schreiben,
317          *  - volle Lesepuffer versuchen zu verarbeiten,
318          *  - Antworten von Resolver Sub-Prozessen annehmen.
319          */
320
321         fd_set read_sockets, write_sockets;
322         struct timeval tv;
323         time_t start, t;
324         CONN_ID i, idx;
325         BOOLEAN timeout;
326
327         start = time( NULL );
328         while(( ! NGIRCd_SignalQuit ) && ( ! NGIRCd_SignalRestart ))
329         {
330                 timeout = TRUE;
331
332 #ifdef RENDEZVOUS
333                 Rendezvous_Handler( );
334 #endif
335
336                 /* Should the configuration be reloaded? */
337                 if( NGIRCd_SignalRehash ) NGIRCd_Rehash( );
338
339                 /* Check configured servers and established links */
340                 Check_Servers( );
341                 Check_Connections( );
342
343                 /* noch volle Lese-Buffer suchen */
344                 for( i = 0; i < Pool_Size; i++ )
345                 {
346                         if(( My_Connections[i].sock > NONE ) && ( My_Connections[i].rdatalen > 0 ))
347                         {
348                                 /* Kann aus dem Buffer noch ein Befehl extrahiert werden? */
349                                 if( Handle_Buffer( i )) timeout = FALSE;
350                         }
351                 }
352
353                 /* noch volle Schreib-Puffer suchen */
354                 FD_ZERO( &write_sockets );
355                 for( i = 0; i < Pool_Size; i++ )
356                 {
357 #ifdef USE_ZLIB
358                         if(( My_Connections[i].sock > NONE ) && (( My_Connections[i].wdatalen > 0 ) || ( My_Connections[i].zip.wdatalen > 0 )))
359 #else
360                         if(( My_Connections[i].sock > NONE ) && ( My_Connections[i].wdatalen > 0 ))
361 #endif
362                         {
363                                 /* Socket der Verbindung in Set aufnehmen */
364                                 FD_SET( My_Connections[i].sock, &write_sockets );
365                         }
366                 }
367
368                 /* Sockets mit im Aufbau befindlichen ausgehenden Verbindungen suchen */
369                 for( i = 0; i < Pool_Size; i++ )
370                 {
371                         if(( My_Connections[i].sock > NONE ) && ( FD_ISSET( My_Connections[i].sock, &My_Connects ))) FD_SET( My_Connections[i].sock, &write_sockets );
372                 }
373
374                 /* von welchen Sockets koennte gelesen werden? */
375                 t = time( NULL );
376                 read_sockets = My_Sockets;
377                 for( i = 0; i < Pool_Size; i++ )
378                 {
379                         if(( My_Connections[i].sock > NONE ) && ( My_Connections[i].host[0] == '\0' ))
380                         {
381                                 /* Hier muss noch auf den Resolver Sub-Prozess gewartet werden */
382                                 FD_CLR( My_Connections[i].sock, &read_sockets );
383                         }
384                         if(( My_Connections[i].sock > NONE ) && ( FD_ISSET( My_Connections[i].sock, &My_Connects )))
385                         {
386                                 /* Hier laeuft noch ein asyncrones connect() */
387                                 FD_CLR( My_Connections[i].sock, &read_sockets );
388                         }
389                         if( My_Connections[i].delaytime > t )
390                         {
391                                 /* Fuer die Verbindung ist eine "Penalty-Zeit" gesetzt */
392                                 FD_CLR( My_Connections[i].sock, &read_sockets );
393                         }
394                 }
395                 for( i = 0; i < Conn_MaxFD + 1; i++ )
396                 {
397                         /* Pipes von Resolver Sub-Prozessen aufnehmen */
398                         if( FD_ISSET( i, &Resolver_FDs ))
399                         {
400                                 FD_SET( i, &read_sockets );
401                         }
402                 }
403
404                 /* Timeout initialisieren */
405                 tv.tv_usec = 0;
406                 if( timeout ) tv.tv_sec = TIME_RES;
407                 else tv.tv_sec = 0;
408                 
409                 /* Auf Aktivitaet warten */
410                 i = select( Conn_MaxFD + 1, &read_sockets, &write_sockets, NULL, &tv );
411                 if( i == 0 )
412                 {
413                         /* keine Veraenderung an den Sockets */
414                         continue;
415                 }
416                 if( i == -1 )
417                 {
418                         /* Fehler (z.B. Interrupt) */
419                         if( errno != EINTR )
420                         {
421                                 Log( LOG_EMERG, "Conn_Handler(): select(): %s!", strerror( errno ));
422                                 Log( LOG_ALERT, "%s exiting due to fatal errors!", PACKAGE );
423                                 exit( 1 );
424                         }
425                         continue;
426                 }
427
428                 /* Koennen Daten geschrieben werden? */
429                 for( i = 0; i < Conn_MaxFD + 1; i++ )
430                 {
431                         if( ! FD_ISSET( i, &write_sockets )) continue;
432
433                         /* Es kann geschrieben werden ... */
434                         idx = Socket2Index( i );
435                         if( idx == NONE ) continue;
436                         
437                         if( ! Handle_Write( idx ))
438                         {
439                                 /* Fehler beim Schreiben! Diesen Socket nun
440                                  * auch aus dem Read-Set entfernen: */
441                                 FD_CLR( i, &read_sockets );
442                         }
443                 }
444
445                 /* Daten zum Lesen vorhanden? */
446                 for( i = 0; i < Conn_MaxFD + 1; i++ )
447                 {
448                         if( FD_ISSET( i, &read_sockets )) Handle_Read( i );
449                 }
450         }
451
452         if( NGIRCd_SignalQuit ) Log( LOG_NOTICE|LOG_snotice, "Server going down NOW!" );
453         else if( NGIRCd_SignalRestart ) Log( LOG_NOTICE|LOG_snotice, "Server restarting NOW!" );
454 } /* Conn_Handler */
455
456
457 #ifdef PROTOTYPES
458 GLOBAL BOOLEAN
459 Conn_WriteStr( CONN_ID Idx, CHAR *Format, ... )
460 #else
461 GLOBAL BOOLEAN
462 Conn_WriteStr( Idx, Format, va_alist )
463 CONN_ID Idx;
464 CHAR *Format;
465 va_dcl
466 #endif
467 {
468         /* String in Socket schreiben. CR+LF wird von dieser Funktion
469          * automatisch angehaengt. Im Fehlerfall wird dir Verbindung
470          * getrennt und FALSE geliefert. */
471
472         CHAR buffer[COMMAND_LEN];
473         BOOLEAN ok;
474         va_list ap;
475
476         assert( Idx > NONE );
477         assert( Format != NULL );
478
479 #ifdef PROTOTYPES
480         va_start( ap, Format );
481 #else
482         va_start( ap );
483 #endif
484         if( vsnprintf( buffer, COMMAND_LEN - 2, Format, ap ) == COMMAND_LEN - 2 )
485         {
486                 Log( LOG_CRIT, "Text too long to send (connection %d)!", Idx );
487                 Conn_Close( Idx, "Text too long to send!", NULL, FALSE );
488                 return FALSE;
489         }
490
491 #ifdef SNIFFER
492         if( NGIRCd_Sniffer ) Log( LOG_DEBUG, " -> connection %d: '%s'.", Idx, buffer );
493 #endif
494
495         strlcat( buffer, "\r\n", sizeof( buffer ));
496         ok = Conn_Write( Idx, buffer, strlen( buffer ));
497         My_Connections[Idx].msg_out++;
498
499         va_end( ap );
500         return ok;
501 } /* Conn_WriteStr */
502
503
504 GLOBAL BOOLEAN
505 Conn_Write( CONN_ID Idx, CHAR *Data, INT Len )
506 {
507         /* Daten in Socket schreiben. Bei "fatalen" Fehlern wird
508          * der Client disconnectiert und FALSE geliefert. */
509
510         assert( Idx > NONE );
511         assert( Data != NULL );
512         assert( Len > 0 );
513
514         /* Ist der entsprechende Socket ueberhaupt noch offen? In einem
515          * "Handler-Durchlauf" kann es passieren, dass dem nicht mehr so
516          * ist, wenn einer von mehreren Conn_Write()'s fehlgeschlagen ist.
517          * In diesem Fall wird hier einfach ein Fehler geliefert. */
518         if( My_Connections[Idx].sock <= NONE )
519         {
520                 Log( LOG_DEBUG, "Skipped write on closed socket (connection %d).", Idx );
521                 return FALSE;
522         }
523
524         /* Pruefen, ob im Schreibpuffer genuegend Platz ist. Ziel ist es,
525          * moeglichts viel im Puffer zu haben und _nicht_ gleich alles auf den
526          * Socket zu schreiben (u.a. wg. Komprimierung). */
527         if( WRITEBUFFER_LEN - My_Connections[Idx].wdatalen - Len <= 0 )
528         {
529                 /* Der Puffer ist dummerweise voll. Jetzt versuchen, den Puffer
530                  * zu schreiben, wenn das nicht klappt, haben wir ein Problem ... */
531                 if( ! Try_Write( Idx )) return FALSE;
532
533                 /* nun neu pruefen: */
534                 if( WRITEBUFFER_LEN - My_Connections[Idx].wdatalen - Len <= 0 )
535                 {
536                         Log( LOG_NOTICE, "Write buffer overflow (connection %d)!", Idx );
537                         Conn_Close( Idx, "Write buffer overflow!", NULL, FALSE );
538                         return FALSE;
539                 }
540         }
541
542 #ifdef USE_ZLIB
543         if( My_Connections[Idx].options & CONN_ZIP )
544         {
545                 /* Daten komprimieren und in Puffer kopieren */
546                 if( ! Zip_Buffer( Idx, Data, Len )) return FALSE;
547         }
548         else
549 #endif
550         {
551                 /* Daten in Puffer kopieren */
552                 memcpy( My_Connections[Idx].wbuf + My_Connections[Idx].wdatalen, Data, Len );
553                 My_Connections[Idx].wdatalen += Len;
554                 My_Connections[Idx].bytes_out += Len;
555         }
556
557         /* Adjust global write counter */
558         WCounter += Len;
559
560         return TRUE;
561 } /* Conn_Write */
562
563
564 GLOBAL VOID
565 Conn_Close( CONN_ID Idx, CHAR *LogMsg, CHAR *FwdMsg, BOOLEAN InformClient )
566 {
567         /* Close connection. Open pipes of asyncronous resolver
568          * sub-processes are closed down. */
569
570         CLIENT *c;
571         DOUBLE in_k, out_k;
572 #ifdef USE_ZLIB
573         DOUBLE in_z_k, out_z_k;
574         INT in_p, out_p;
575 #endif
576
577         assert( Idx > NONE );
578         assert( My_Connections[Idx].sock > NONE );
579
580         /* Is this link already shutting down? */
581         if( My_Connections[Idx].options & CONN_ISCLOSING )
582         {
583                 /* Conn_Close() has been called recursively for this link;
584                  * probabe reason: Try_Write() failed  -- see below. */
585                 return;
586         }
587
588         /* Mark link as "closing" */
589         My_Connections[Idx].options |= CONN_ISCLOSING;
590
591         /* Search client, if any */
592         c = Client_GetFromConn( Idx );
593
594         /* Should the client be informed? */
595         if( InformClient )
596         {
597 #ifndef STRICT_RFC
598                 /* Send statistics to client if registered as user: */
599                 if(( c != NULL ) && ( Client_Type( c ) == CLIENT_USER ))
600                 {
601                         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 );
602                 }
603 #endif
604
605                 /* Send ERROR to client (see RFC!) */
606                 if( FwdMsg ) Conn_WriteStr( Idx, "ERROR :%s", FwdMsg );
607                 else Conn_WriteStr( Idx, "ERROR :Closing connection." );
608                 if( My_Connections[Idx].sock == NONE ) return;
609         }
610
611         /* Try to write out the write buffer */
612         (VOID)Try_Write( Idx );
613
614         /* Shut down socket */
615         if( close( My_Connections[Idx].sock ) != 0 )
616         {
617                 /* Oops, we can't close the socket!? This is fatal! */
618                 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 ));
619                 Log( LOG_ALERT, "%s exiting due to fatal errors!", PACKAGE );
620                 exit( 1 );
621         }
622
623         /* Mark socket as invalid: */
624         FD_CLR( My_Connections[Idx].sock, &My_Sockets );
625         FD_CLR( My_Connections[Idx].sock, &My_Connects );
626         My_Connections[Idx].sock = NONE;
627
628         /* If there is still a client, unregister it now */
629         if( c ) Client_Destroy( c, LogMsg, FwdMsg, TRUE );
630
631         /* Calculate statistics and log information */
632         in_k = (DOUBLE)My_Connections[Idx].bytes_in / 1024;
633         out_k = (DOUBLE)My_Connections[Idx].bytes_out / 1024;
634 #ifdef USE_ZLIB
635         if( My_Connections[Idx].options & CONN_ZIP )
636         {
637                 in_z_k = (DOUBLE)My_Connections[Idx].zip.bytes_in / 1024;
638                 out_z_k = (DOUBLE)My_Connections[Idx].zip.bytes_out / 1024;
639                 in_p = (INT)(( in_k * 100 ) / in_z_k );
640                 out_p = (INT)(( out_k * 100 ) / out_z_k );
641                 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 );
642         }
643         else
644 #endif
645         {
646                 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 );
647         }
648
649         /* Is there a resolver sub-process running? */
650         if( My_Connections[Idx].res_stat )
651         {
652                 /* Free resolver structures */
653                 FD_CLR( My_Connections[Idx].res_stat->pipe[0], &Resolver_FDs );
654                 close( My_Connections[Idx].res_stat->pipe[0] );
655                 close( My_Connections[Idx].res_stat->pipe[1] );
656                 free( My_Connections[Idx].res_stat );
657         }
658
659         /* Servers: Modify time of next connect attempt? */
660         Conf_UnsetServer( Idx );
661
662 #ifdef USE_ZLIB
663         /* Clean up zlib, if link was compressed */
664         if( Conn_Options( Idx ) & CONN_ZIP )
665         {
666                 inflateEnd( &My_Connections[Idx].zip.in );
667                 deflateEnd( &My_Connections[Idx].zip.out );
668         }
669 #endif
670
671         /* Clean up connection structure (=free it) */
672         Init_Conn_Struct( Idx );
673 } /* Conn_Close */
674
675
676 LOCAL BOOLEAN
677 Try_Write( CONN_ID Idx )
678 {
679         /* Versuchen, Daten aus dem Schreib-Puffer in den Socket zu
680          * schreiben. TRUE wird geliefert, wenn entweder keine Daten
681          * zum Versenden vorhanden sind oder erfolgreich bearbeitet
682          * werden konnten. Im Fehlerfall wird FALSE geliefert und
683          * die Verbindung geschlossen. */
684
685         fd_set write_socket;
686         struct timeval tv;
687
688         assert( Idx > NONE );
689         assert( My_Connections[Idx].sock > NONE );
690
691         /* sind ueberhaupt Daten vorhanden? */
692 #ifdef USE_ZLIB
693         if(( ! My_Connections[Idx].wdatalen > 0 ) && ( ! My_Connections[Idx].zip.wdatalen )) return TRUE;
694 #else
695         if( ! My_Connections[Idx].wdatalen > 0 ) return TRUE;
696 #endif
697
698         /* Timeout initialisieren: 0 Sekunden, also nicht blockieren */
699         tv.tv_sec = 0; tv.tv_usec = 0;
700
701         FD_ZERO( &write_socket );
702         FD_SET( My_Connections[Idx].sock, &write_socket );
703         if( select( My_Connections[Idx].sock + 1, NULL, &write_socket, NULL, &tv ) == -1 )
704         {
705                 /* Fehler! */
706                 if( errno != EINTR )
707                 {
708                         Log( LOG_ALERT, "Try_Write(): select() failed: %s (con=%d, sock=%d)!", strerror( errno ), Idx, My_Connections[Idx].sock );
709                         Conn_Close( Idx, "Server error!", NULL, FALSE );
710                         return FALSE;
711                 }
712         }
713
714         if( FD_ISSET( My_Connections[Idx].sock, &write_socket )) return Handle_Write( Idx );
715         else return TRUE;
716 } /* Try_Write */
717
718
719 LOCAL VOID
720 Handle_Read( INT Sock )
721 {
722         /* Aktivitaet auf einem Socket verarbeiten:
723          *  - neue Clients annehmen,
724          *  - Daten von Clients verarbeiten,
725          *  - Resolver-Rueckmeldungen annehmen. */
726
727         CONN_ID idx;
728
729         assert( Sock > NONE );
730
731         if( FD_ISSET( Sock, &My_Listeners ))
732         {
733                 /* es ist einer unserer Listener-Sockets: es soll
734                  * also eine neue Verbindung aufgebaut werden. */
735
736                 New_Connection( Sock );
737         }
738         else if( FD_ISSET( Sock, &Resolver_FDs ))
739         {
740                 /* Rueckmeldung von einem Resolver Sub-Prozess */
741
742                 Read_Resolver_Result( Sock );
743         }
744         else
745         {
746                 /* Ein Client Socket: entweder ein User oder Server */
747
748                 idx = Socket2Index( Sock );
749                 if( idx > NONE ) Read_Request( idx );
750         }
751 } /* Handle_Read */
752
753
754 LOCAL BOOLEAN
755 Handle_Write( CONN_ID Idx )
756 {
757         /* Daten aus Schreibpuffer versenden bzw. Connection aufbauen */
758
759         INT len, res, err;
760         CLIENT *c;
761
762         assert( Idx > NONE );
763         assert( My_Connections[Idx].sock > NONE );
764
765         if( FD_ISSET( My_Connections[Idx].sock, &My_Connects ))
766         {
767                 /* es soll nichts geschrieben werden, sondern ein
768                  * connect() hat ein Ergebnis geliefert */
769
770                 FD_CLR( My_Connections[Idx].sock, &My_Connects );
771
772                 /* Ergebnis des connect() ermitteln */
773                 len = sizeof( err );
774                 res = getsockopt( My_Connections[Idx].sock, SOL_SOCKET, SO_ERROR, &err, &len );
775                 assert( len == sizeof( err ));
776
777                 /* Fehler aufgetreten? */
778                 if(( res != 0 ) || ( err != 0 ))
779                 {
780                         /* Fehler! */
781                         if( res != 0 ) Log( LOG_CRIT, "getsockopt (connection %d): %s!", Idx, strerror( errno ));
782                         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 ));
783
784                         /* Clean up socket, connection and client structures */
785                         FD_CLR( My_Connections[Idx].sock, &My_Sockets );
786                         c = Client_GetFromConn( Idx );
787                         if( c ) Client_DestroyNow( c );
788                         close( My_Connections[Idx].sock );
789                         Init_Conn_Struct( Idx );
790
791                         /* Bei Server-Verbindungen lasttry-Zeitpunkt auf "jetzt" setzen */
792                         Conf_Server[Conf_GetServer( Idx )].lasttry = time( NULL );
793                         Conf_UnsetServer( Idx );
794
795                         return FALSE;
796                 }
797                 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 );
798
799                 /* PASS und SERVER verschicken */
800                 Conn_WriteStr( Idx, "PASS %s %s", Conf_Server[Conf_GetServer( Idx )].pwd_out, NGIRCd_ProtoID );
801                 return Conn_WriteStr( Idx, "SERVER %s :%s", Conf_ServerName, Conf_ServerInfo );
802         }
803
804 #ifdef USE_ZLIB
805         /* Schreibpuffer leer, aber noch Daten im Kompressionsbuffer?
806          * Dann muss dieser nun geflushed werden! */
807         if( My_Connections[Idx].wdatalen == 0 ) Zip_Flush( Idx );
808 #endif
809
810         assert( My_Connections[Idx].wdatalen > 0 );
811
812         /* Daten schreiben */
813         len = send( My_Connections[Idx].sock, My_Connections[Idx].wbuf, My_Connections[Idx].wdatalen, 0 );
814         if( len < 0 )
815         {
816                 /* Operation haette Socket "nur" blockiert ... */
817                 if( errno == EAGAIN ) return TRUE;
818
819                 /* Oops, ein Fehler! */
820                 Log( LOG_ERR, "Write error on connection %d (socket %d): %s!", Idx, My_Connections[Idx].sock, strerror( errno ));
821                 Conn_Close( Idx, "Write error!", NULL, FALSE );
822                 return FALSE;
823         }
824
825         /* Puffer anpassen */
826         My_Connections[Idx].wdatalen -= len;
827         memmove( My_Connections[Idx].wbuf, My_Connections[Idx].wbuf + len, My_Connections[Idx].wdatalen );
828
829         return TRUE;
830 } /* Handle_Write */
831
832
833 LOCAL VOID
834 New_Connection( INT Sock )
835 {
836         /* Neue Client-Verbindung von Listen-Socket annehmen und
837          * CLIENT-Struktur anlegen. */
838
839         struct sockaddr_in new_addr;
840         INT new_sock, new_sock_len;
841         RES_STAT *s;
842         CONN_ID idx;
843         CLIENT *c;
844         POINTER *ptr;
845         LONG new_size;
846
847         assert( Sock > NONE );
848
849         /* Connection auf Listen-Socket annehmen */
850         new_sock_len = sizeof( new_addr );
851         new_sock = accept( Sock, (struct sockaddr *)&new_addr, (socklen_t *)&new_sock_len );
852         if( new_sock < 0 )
853         {
854                 Log( LOG_CRIT, "Can't accept connection: %s!", strerror( errno ));
855                 return;
856         }
857
858         /* Socket initialisieren */
859         Init_Socket( new_sock );
860
861         /* Freie Connection-Struktur suchen */
862         for( idx = 0; idx < Pool_Size; idx++ ) if( My_Connections[idx].sock == NONE ) break;
863         if( idx >= Pool_Size )
864         {
865                 new_size = Pool_Size + CONNECTION_POOL;
866                 
867                 /* Im bisherigen Pool wurde keine freie Connection-Struktur mehr gefunden.
868                  * Wenn erlaubt und moeglich muss nun der Pool vergroessert werden: */
869                 
870                 if( Conf_MaxConnections > 0 )
871                 {
872                         /* Es ist ein Limit konfiguriert */
873                         if( Pool_Size >= Conf_MaxConnections )
874                         {
875                                 /* Mehr Verbindungen duerfen wir leider nicht mehr annehmen ... */
876                                 Log( LOG_ALERT, "Can't accept connection: limit (%d) reached!", Pool_Size );
877                                 close( new_sock );
878                                 return;
879                         }
880                         if( new_size > Conf_MaxConnections ) new_size = Conf_MaxConnections;
881                 }
882                 if( new_size < Pool_Size )
883                 {
884                         Log( LOG_ALERT, "Can't accespt connection: limit (%d) reached -- overflow!", Pool_Size );
885                         close( new_sock );
886                         return;
887                 }
888                 
889                 /* zunaechst realloc() versuchen; wenn das scheitert, malloc() versuchen
890                  * und Daten ggf. "haendisch" umkopieren. (Haesslich! Eine wirklich
891                  * dynamische Verwaltung waere wohl _deutlich_ besser ...) */
892                 ptr = realloc( My_Connections, sizeof( CONNECTION ) * new_size );
893                 if( ! ptr )
894                 {
895                         /* realloc() ist fehlgeschlagen. Nun malloc() probieren: */
896                         ptr = malloc( sizeof( CONNECTION ) * new_size );
897                         if( ! ptr )
898                         {
899                                 /* Offenbar steht kein weiterer Sepeicher zur Verfuegung :-( */
900                                 Log( LOG_EMERG, "Can't allocate memory! [New_Connection]" );
901                                 close( new_sock );
902                                 return;
903                         }
904                         
905                         /* Struktur umkopieren ... */
906                         memcpy( ptr, My_Connections, sizeof( CONNECTION ) * Pool_Size );
907                         
908                         Log( LOG_DEBUG, "Allocated new connection pool for %ld items (%ld bytes). [malloc()/memcpy()]", new_size, sizeof( CONNECTION ) * new_size );
909                 }
910                 else Log( LOG_DEBUG, "Allocated new connection pool for %ld items (%ld bytes). [realloc()]", new_size, sizeof( CONNECTION ) * new_size );
911                 
912                 /* Adjust pointer to new block */
913                 My_Connections = ptr;
914                 
915                 /* Initialize new items */
916                 for( idx = Pool_Size; idx < new_size; idx++ ) Init_Conn_Struct( idx );
917                 idx = Pool_Size;
918                 
919                 /* Adjust new pool size */
920                 Pool_Size = new_size;
921         }
922
923         /* Client-Struktur initialisieren */
924         c = Client_NewLocal( idx, inet_ntoa( new_addr.sin_addr ), CLIENT_UNKNOWN, FALSE );
925         if( ! c )
926         {
927                 Log( LOG_ALERT, "Can't accept connection: can't create client structure!" );
928                 close( new_sock );
929                 return;
930         }
931
932         /* Verbindung registrieren */
933         Init_Conn_Struct( idx );
934         My_Connections[idx].sock = new_sock;
935         My_Connections[idx].addr = new_addr;
936
937         /* Neuen Socket registrieren */
938         FD_SET( new_sock, &My_Sockets );
939         if( new_sock > Conn_MaxFD ) Conn_MaxFD = new_sock;
940
941         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 );
942
943         /* Hostnamen ermitteln */
944         strlcpy( My_Connections[idx].host, inet_ntoa( new_addr.sin_addr ), sizeof( My_Connections[idx].host ));
945         Client_SetHostname( c, My_Connections[idx].host );
946         s = Resolve_Addr( &new_addr );
947         if( s )
948         {
949                 /* Sub-Prozess wurde asyncron gestartet */
950                 My_Connections[idx].res_stat = s;
951         }
952         
953         /* Penalty-Zeit setzen */
954         Conn_SetPenalty( idx, 4 );
955 } /* New_Connection */
956
957
958 LOCAL CONN_ID
959 Socket2Index( INT Sock )
960 {
961         /* zum Socket passende Connection suchen */
962
963         CONN_ID idx;
964
965         assert( Sock > NONE );
966
967         for( idx = 0; idx < Pool_Size; idx++ ) if( My_Connections[idx].sock == Sock ) break;
968
969         if( idx >= Pool_Size )
970         {
971                 /* die Connection wurde vermutlich (wegen eines
972                  * Fehlers) bereits wieder abgebaut ... */
973                 Log( LOG_DEBUG, "Socket2Index: can't get connection for socket %d!", Sock );
974                 return NONE;
975         }
976         else return idx;
977 } /* Socket2Index */
978
979
980 LOCAL VOID
981 Read_Request( CONN_ID Idx )
982 {
983         /* Daten von Socket einlesen und entsprechend behandeln.
984          * Tritt ein Fehler auf, so wird der Socket geschlossen. */
985
986         INT len, bsize;
987 #ifdef USE_ZLIB
988         CLIENT *c;
989 #endif
990
991         assert( Idx > NONE );
992         assert( My_Connections[Idx].sock > NONE );
993
994         /* wenn noch nicht registriert: maximal mit ZREADBUFFER_LEN arbeiten,
995          * ansonsten koennen Daten ggf. nicht umkopiert werden. */
996         bsize = READBUFFER_LEN;
997 #ifdef USE_ZLIB
998         c = Client_GetFromConn( Idx );
999         if(( Client_Type( c ) != CLIENT_USER ) && ( Client_Type( c ) != CLIENT_SERVER ) && ( Client_Type( c ) != CLIENT_SERVICE ) && ( bsize > ZREADBUFFER_LEN )) bsize = ZREADBUFFER_LEN;
1000 #endif
1001
1002 #ifdef USE_ZLIB
1003         if(( bsize - My_Connections[Idx].rdatalen - 1 < 1 ) || ( ZREADBUFFER_LEN - My_Connections[Idx].zip.rdatalen < 1 ))
1004 #else
1005         if( bsize - My_Connections[Idx].rdatalen - 1 < 1 )
1006 #endif
1007         {
1008                 /* Der Lesepuffer ist voll */
1009                 Log( LOG_ERR, "Read buffer overflow (connection %d): %d bytes!", Idx, My_Connections[Idx].rdatalen );
1010                 Conn_Close( Idx, "Read buffer overflow!", NULL, FALSE );
1011                 return;
1012         }
1013
1014 #ifdef USE_ZLIB
1015         if( My_Connections[Idx].options & CONN_ZIP )
1016         {
1017                 len = recv( My_Connections[Idx].sock, My_Connections[Idx].zip.rbuf + My_Connections[Idx].zip.rdatalen, ( ZREADBUFFER_LEN - My_Connections[Idx].zip.rdatalen ), 0 );
1018                 if( len > 0 ) My_Connections[Idx].zip.rdatalen += len;
1019         }
1020         else
1021 #endif
1022         {
1023                 len = recv( My_Connections[Idx].sock, My_Connections[Idx].rbuf + My_Connections[Idx].rdatalen, bsize - My_Connections[Idx].rdatalen - 1, 0 );
1024                 if( len > 0 ) My_Connections[Idx].rdatalen += len;
1025         }
1026
1027         if( len == 0 )
1028         {
1029                 /* Socket wurde geschlossen */
1030                 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 ));
1031                 Conn_Close( Idx, "Socket closed!", "Client closed connection", FALSE );
1032                 return;
1033         }
1034
1035         if( len < 0 )
1036         {
1037                 /* Operation haette Socket "nur" blockiert ... */
1038                 if( errno == EAGAIN ) return;
1039
1040                 /* Fehler beim Lesen */
1041                 Log( LOG_ERR, "Read error on connection %d (socket %d): %s!", Idx, My_Connections[Idx].sock, strerror( errno ));
1042                 Conn_Close( Idx, "Read error!", "Client closed connection", FALSE );
1043                 return;
1044         }
1045
1046         /* Connection-Statistik aktualisieren */
1047         My_Connections[Idx].bytes_in += len;
1048
1049         /* Timestamp aktualisieren */
1050         My_Connections[Idx].lastdata = time( NULL );
1051
1052         Handle_Buffer( Idx );
1053 } /* Read_Request */
1054
1055
1056 LOCAL BOOLEAN
1057 Handle_Buffer( CONN_ID Idx )
1058 {
1059         /* Daten im Lese-Puffer einer Verbindung verarbeiten.
1060          * Wurde ein Request verarbeitet, so wird TRUE geliefert,
1061          * ansonsten FALSE (auch bei Fehlern). */
1062
1063 #ifndef STRICT_RFC
1064         CHAR *ptr1, *ptr2;
1065 #endif
1066         CHAR *ptr;
1067         INT len, delta;
1068         BOOLEAN action, result;
1069 #ifdef USE_ZLIB
1070         BOOLEAN old_z;
1071 #endif
1072
1073         result = FALSE;
1074         do
1075         {
1076 #ifdef USE_ZLIB
1077                 /* ggf. noch unkomprimiete Daten weiter entpacken */
1078                 if( My_Connections[Idx].options & CONN_ZIP )
1079                 {
1080                         if( ! Unzip_Buffer( Idx )) return FALSE;
1081                 }
1082 #endif
1083         
1084                 if( My_Connections[Idx].rdatalen < 1 ) break;
1085
1086                 /* Eine komplette Anfrage muss mit CR+LF enden, vgl.
1087                  * RFC 2812. Haben wir eine? */
1088                 My_Connections[Idx].rbuf[My_Connections[Idx].rdatalen] = '\0';
1089                 ptr = strstr( My_Connections[Idx].rbuf, "\r\n" );
1090         
1091                 if( ptr ) delta = 2;
1092 #ifndef STRICT_RFC
1093                 else
1094                 {
1095                         /* Nicht RFC-konforme Anfrage mit nur CR oder LF? Leider
1096                          * machen soetwas viele Clients, u.a. "mIRC" :-( */
1097                         ptr1 = strchr( My_Connections[Idx].rbuf, '\r' );
1098                         ptr2 = strchr( My_Connections[Idx].rbuf, '\n' );
1099                         delta = 1;
1100                         if( ptr1 && ptr2 ) ptr = ptr1 > ptr2 ? ptr2 : ptr1;
1101                         else if( ptr1 ) ptr = ptr1;
1102                         else if( ptr2 ) ptr = ptr2;
1103                 }
1104 #endif
1105         
1106                 action = FALSE;
1107                 if( ptr )
1108                 {
1109                         /* Ende der Anfrage wurde gefunden */
1110                         *ptr = '\0';
1111                         len = ( ptr - My_Connections[Idx].rbuf ) + delta;
1112                         if( len > ( COMMAND_LEN - 1 ))
1113                         {
1114                                 /* Eine Anfrage darf(!) nicht laenger als 512 Zeichen
1115                                  * (incl. CR+LF!) werden; vgl. RFC 2812. Wenn soetwas
1116                                  * empfangen wird, wird der Client disconnectiert. */
1117                                 Log( LOG_ERR, "Request too long (connection %d): %d bytes (max. %d expected)!", Idx, My_Connections[Idx].rdatalen, COMMAND_LEN - 1 );
1118                                 Conn_Close( Idx, NULL, "Request too long", TRUE );
1119                                 return FALSE;
1120                         }
1121
1122 #ifdef USE_ZLIB
1123                         /* merken, ob Stream bereits komprimiert wird */
1124                         old_z = My_Connections[Idx].options & CONN_ZIP;
1125 #endif
1126
1127                         if( len > delta )
1128                         {
1129                                 /* Es wurde ein Request gelesen */
1130                                 My_Connections[Idx].msg_in++;
1131                                 if( ! Parse_Request( Idx, My_Connections[Idx].rbuf )) return FALSE;
1132                                 else action = TRUE;
1133                         }
1134
1135                         /* Puffer anpassen */
1136                         My_Connections[Idx].rdatalen -= len;
1137                         memmove( My_Connections[Idx].rbuf, My_Connections[Idx].rbuf + len, My_Connections[Idx].rdatalen );
1138
1139 #ifdef USE_ZLIB
1140                         if(( ! old_z ) && ( My_Connections[Idx].options & CONN_ZIP ) && ( My_Connections[Idx].rdatalen > 0 ))
1141                         {
1142                                 /* Mit dem letzten Befehl wurde Socket-Kompression aktiviert.
1143                                  * Evtl. schon vom Socket gelesene Daten in den Unzip-Puffer
1144                                  * umkopieren, damit diese nun zunaechst entkomprimiert werden */
1145                                 {
1146                                         if( My_Connections[Idx].rdatalen > ZREADBUFFER_LEN )
1147                                         {
1148                                                 /* Hupsa! Soviel Platz haben wir aber gar nicht! */
1149                                                 Log( LOG_ALERT, "Can't move read buffer: No space left in unzip buffer (need %d bytes)!", My_Connections[Idx].rdatalen );
1150                                                 return FALSE;
1151                                         }
1152                                         memcpy( My_Connections[Idx].zip.rbuf, My_Connections[Idx].rbuf, My_Connections[Idx].rdatalen );
1153                                         My_Connections[Idx].zip.rdatalen = My_Connections[Idx].rdatalen;
1154                                         My_Connections[Idx].rdatalen = 0;
1155                                         Log( LOG_DEBUG, "Moved already received data (%d bytes) to uncompression buffer.", My_Connections[Idx].zip.rdatalen );
1156                                 }
1157                         }
1158 #endif
1159                 }
1160                 
1161                 if( action ) result = TRUE;
1162         } while( action );
1163         
1164         return result;
1165 } /* Handle_Buffer */
1166
1167
1168 LOCAL VOID
1169 Check_Connections( VOID )
1170 {
1171         /* Pruefen, ob Verbindungen noch "alive" sind. Ist dies
1172          * nicht der Fall, zunaechst PING-PONG spielen und, wenn
1173          * auch das nicht "hilft", Client disconnectieren. */
1174
1175         CLIENT *c;
1176         CONN_ID i;
1177
1178         for( i = 0; i < Pool_Size; i++ )
1179         {
1180                 if( My_Connections[i].sock == NONE ) continue;
1181
1182                 c = Client_GetFromConn( i );
1183                 if( c && (( Client_Type( c ) == CLIENT_USER ) || ( Client_Type( c ) == CLIENT_SERVER ) || ( Client_Type( c ) == CLIENT_SERVICE )))
1184                 {
1185                         /* verbundener User, Server oder Service */
1186                         if( My_Connections[i].lastping > My_Connections[i].lastdata )
1187                         {
1188                                 /* es wurde bereits ein PING gesendet */
1189                                 if( My_Connections[i].lastping < time( NULL ) - Conf_PongTimeout )
1190                                 {
1191                                         /* Timeout */
1192                                         Log( LOG_DEBUG, "Connection %d: Ping timeout: %d seconds.", i, Conf_PongTimeout );
1193                                         Conn_Close( i, NULL, "Ping timeout", TRUE );
1194                                 }
1195                         }
1196                         else if( My_Connections[i].lastdata < time( NULL ) - Conf_PingTimeout )
1197                         {
1198                                 /* es muss ein PING gesendet werden */
1199                                 Log( LOG_DEBUG, "Connection %d: sending PING ...", i );
1200                                 My_Connections[i].lastping = time( NULL );
1201                                 Conn_WriteStr( i, "PING :%s", Client_ID( Client_ThisServer( )));
1202                         }
1203                 }
1204                 else
1205                 {
1206                         /* noch nicht vollstaendig aufgebaute Verbindung */
1207                         if( My_Connections[i].lastdata < time( NULL ) - Conf_PingTimeout )
1208                         {
1209                                 /* Timeout */
1210                                 Log( LOG_DEBUG, "Connection %d timed out ...", i );
1211                                 Conn_Close( i, NULL, "Timeout", FALSE );
1212                         }
1213                 }
1214         }
1215 } /* Check_Connections */
1216
1217
1218 LOCAL VOID
1219 Check_Servers( VOID )
1220 {
1221         /* Check if we can establish further server links */
1222
1223         RES_STAT *s;
1224         CONN_ID idx;
1225         INT i, n;
1226
1227         /* Serach all connections, are there results from the resolver? */
1228         for( idx = 0; idx < Pool_Size; idx++ )
1229         {
1230                 if( My_Connections[idx].sock != SERVER_WAIT ) continue;
1231
1232                 /* IP resolved? */
1233                 if( My_Connections[idx].res_stat == NULL ) New_Server( Conf_GetServer( idx ), idx );
1234         }
1235
1236         /* Check all configured servers */
1237         for( i = 0; i < MAX_SERVERS; i++ )
1238         {
1239                 /* Valid outgoing server which isn't already connected or disabled? */
1240                 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;
1241
1242                 /* Is there already a connection in this group? */
1243                 if( Conf_Server[i].group > NONE )
1244                 {
1245                         for( n = 0; n < MAX_SERVERS; n++ )
1246                         {
1247                                 if( n == i ) continue;
1248                                 if(( Conf_Server[n].conn_id > NONE ) && ( Conf_Server[n].group == Conf_Server[i].group )) break;
1249                         }
1250                         if( n < MAX_SERVERS ) continue;
1251                 }
1252
1253                 /* Check last connect attempt? */
1254                 if( Conf_Server[i].lasttry > time( NULL ) - Conf_ConnectRetry ) continue;
1255
1256                 /* Okay, try to connect now */
1257                 Conf_Server[i].lasttry = time( NULL );
1258
1259                 /* Search free connection structure */
1260                 for( idx = 0; idx < Pool_Size; idx++ ) if( My_Connections[idx].sock == NONE ) break;
1261                 if( idx >= Pool_Size )
1262                 {
1263                         Log( LOG_ALERT, "Can't establist server connection: connection limit reached (%d)!", Pool_Size );
1264                         return;
1265                 }
1266                 Log( LOG_DEBUG, "Preparing connection %d for \"%s\" ...", idx, Conf_Server[i].host );
1267
1268                 /* Verbindungs-Struktur initialisieren */
1269                 Init_Conn_Struct( idx );
1270                 My_Connections[idx].sock = SERVER_WAIT;
1271                 Conf_Server[i].conn_id = idx;
1272
1273                 /* Resolve Hostname. If this fails, try to use it as an IP address */
1274                 strlcpy( Conf_Server[i].ip, Conf_Server[i].host, sizeof( Conf_Server[i].ip ));
1275                 strlcpy( My_Connections[idx].host, Conf_Server[i].host, sizeof( My_Connections[idx].host ));
1276                 s = Resolve_Name( Conf_Server[i].host );
1277                 if( s )
1278                 {
1279                         /* Sub-Prozess wurde asyncron gestartet */
1280                         My_Connections[idx].res_stat = s;
1281                 }
1282         }
1283 } /* Check_Servers */
1284
1285
1286 LOCAL VOID
1287 New_Server( INT Server, CONN_ID Idx )
1288 {
1289         /* Neue Server-Verbindung aufbauen */
1290
1291         struct sockaddr_in new_addr;
1292         struct in_addr inaddr;
1293         INT res, new_sock;
1294         CLIENT *c;
1295
1296         assert( Server > NONE );
1297         assert( Idx > NONE );
1298
1299         /* Wurde eine gueltige IP-Adresse gefunden? */
1300         if( ! Conf_Server[Server].ip[0] )
1301         {
1302                 /* Nein. Verbindung wieder freigeben: */
1303                 Init_Conn_Struct( Idx );
1304                 Log( LOG_ERR, "Can't connect to \"%s\" (connection %d): ip address unknown!", Conf_Server[Server].host, Idx );
1305                 return;
1306         }
1307
1308         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 );
1309
1310 #ifdef HAVE_INET_ATON
1311         if( inet_aton( Conf_Server[Server].ip, &inaddr ) == 0 )
1312 #else
1313         memset( &inaddr, 0, sizeof( inaddr ));
1314         inaddr.s_addr = inet_addr( Conf_Server[Server].ip );
1315         if( inaddr.s_addr == (unsigned)-1 )
1316 #endif
1317         {
1318                 /* Konnte Adresse nicht konvertieren */
1319                 Init_Conn_Struct( Idx );
1320                 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 );
1321                 return;
1322         }
1323
1324         memset( &new_addr, 0, sizeof( new_addr ));
1325         new_addr.sin_family = AF_INET;
1326         new_addr.sin_addr = inaddr;
1327         new_addr.sin_port = htons( Conf_Server[Server].port );
1328
1329         new_sock = socket( PF_INET, SOCK_STREAM, 0 );
1330         if ( new_sock < 0 )
1331         {
1332                 Init_Conn_Struct( Idx );
1333                 Log( LOG_CRIT, "Can't create socket: %s!", strerror( errno ));
1334                 return;
1335         }
1336
1337         if( ! Init_Socket( new_sock )) return;
1338
1339         res = connect( new_sock, (struct sockaddr *)&new_addr, sizeof( new_addr ));
1340         if(( res != 0 ) && ( errno != EINPROGRESS ))
1341         {
1342                 Log( LOG_CRIT, "Can't connect socket: %s!", strerror( errno ));
1343                 close( new_sock );
1344                 Init_Conn_Struct( Idx );
1345                 return;
1346         }
1347
1348         /* Client-Struktur initialisieren */
1349         c = Client_NewLocal( Idx, inet_ntoa( new_addr.sin_addr ), CLIENT_UNKNOWNSERVER, FALSE );
1350         if( ! c )
1351         {
1352                 close( new_sock );
1353                 Init_Conn_Struct( Idx );
1354                 Log( LOG_ALERT, "Can't establish connection: can't create client structure!" );
1355                 return;
1356         }
1357         Client_SetIntroducer( c, c );
1358         Client_SetToken( c, TOKEN_OUTBOUND );
1359
1360         /* Verbindung registrieren */
1361         My_Connections[Idx].sock = new_sock;
1362         My_Connections[Idx].addr = new_addr;
1363         strlcpy( My_Connections[Idx].host, Conf_Server[Server].host, sizeof( My_Connections[Idx].host ));
1364
1365         /* Neuen Socket registrieren */
1366         FD_SET( new_sock, &My_Sockets );
1367         FD_SET( new_sock, &My_Connects );
1368         if( new_sock > Conn_MaxFD ) Conn_MaxFD = new_sock;
1369         
1370         Log( LOG_DEBUG, "Registered new connection %d on socket %d.", Idx, My_Connections[Idx].sock );
1371 } /* New_Server */
1372
1373
1374 LOCAL VOID
1375 Init_Conn_Struct( CONN_ID Idx )
1376 {
1377         /* Connection-Struktur initialisieren */
1378
1379         My_Connections[Idx].sock = NONE;
1380         My_Connections[Idx].res_stat = NULL;
1381         My_Connections[Idx].host[0] = '\0';
1382         My_Connections[Idx].rbuf[0] = '\0';
1383         My_Connections[Idx].rdatalen = 0;
1384         My_Connections[Idx].wbuf[0] = '\0';
1385         My_Connections[Idx].wdatalen = 0;
1386         My_Connections[Idx].starttime = time( NULL );
1387         My_Connections[Idx].lastdata = time( NULL );
1388         My_Connections[Idx].lastping = 0;
1389         My_Connections[Idx].lastprivmsg = time( NULL );
1390         My_Connections[Idx].delaytime = 0;
1391         My_Connections[Idx].bytes_in = 0;
1392         My_Connections[Idx].bytes_out = 0;
1393         My_Connections[Idx].msg_in = 0;
1394         My_Connections[Idx].msg_out = 0;
1395         My_Connections[Idx].flag = 0;
1396         My_Connections[Idx].options = 0;
1397
1398 #ifdef USE_ZLIB
1399         My_Connections[Idx].zip.rbuf[0] = '\0';
1400         My_Connections[Idx].zip.rdatalen = 0;
1401         My_Connections[Idx].zip.wbuf[0] = '\0';
1402         My_Connections[Idx].zip.wdatalen = 0;
1403         My_Connections[Idx].zip.bytes_in = 0;
1404         My_Connections[Idx].zip.bytes_out = 0;
1405 #endif
1406 } /* Init_Conn_Struct */
1407
1408
1409 LOCAL BOOLEAN
1410 Init_Socket( INT Sock )
1411 {
1412         /* Socket-Optionen setzen */
1413
1414         INT on = 1;
1415
1416 #ifdef O_NONBLOCK       /* A/UX kennt das nicht? */
1417         if( fcntl( Sock, F_SETFL, O_NONBLOCK ) != 0 )
1418         {
1419                 Log( LOG_CRIT, "Can't enable non-blocking mode: %s!", strerror( errno ));
1420                 close( Sock );
1421                 return FALSE;
1422         }
1423 #endif
1424         if( setsockopt( Sock, SOL_SOCKET, SO_REUSEADDR, &on, (socklen_t)sizeof( on )) != 0)
1425         {
1426                 Log( LOG_ERR, "Can't set socket options: %s!", strerror( errno ));
1427                 /* dieser Fehler kann ignoriert werden. */
1428         }
1429
1430         return TRUE;
1431 } /* Init_Socket */
1432
1433
1434 LOCAL VOID
1435 Read_Resolver_Result( INT r_fd )
1436 {
1437         /* Ergebnis von Resolver Sub-Prozess aus Pipe lesen
1438          * und entsprechende Connection aktualisieren */
1439
1440         CHAR result[HOST_LEN];
1441         CLIENT *c;
1442         INT len, i, n;
1443
1444         FD_CLR( r_fd, &Resolver_FDs );
1445
1446         /* Anfrage vom Parent lesen */
1447         len = read( r_fd, result, HOST_LEN - 1 );
1448         if( len < 0 )
1449         {
1450                 /* Fehler beim Lesen aus der Pipe */
1451                 close( r_fd );
1452                 Log( LOG_CRIT, "Resolver: Can't read result: %s!", strerror( errno ));
1453                 return;
1454         }
1455         result[len] = '\0';
1456
1457         /* zugehoerige Connection suchen */
1458         for( i = 0; i < Pool_Size; i++ )
1459         {
1460                 if(( My_Connections[i].sock != NONE ) && ( My_Connections[i].res_stat ) && ( My_Connections[i].res_stat->pipe[0] == r_fd )) break;
1461         }
1462         if( i >= Pool_Size )
1463         {
1464                 /* Opsa! Keine passende Connection gefunden!? Vermutlich
1465                  * wurde sie schon wieder geschlossen. */
1466                 close( r_fd );
1467                 Log( LOG_DEBUG, "Resolver: Got result for unknown connection!?" );
1468                 return;
1469         }
1470
1471         Log( LOG_DEBUG, "Resolver: %s is \"%s\".", My_Connections[i].host, result );
1472         
1473         /* Aufraeumen */
1474         close( My_Connections[i].res_stat->pipe[0] );
1475         close( My_Connections[i].res_stat->pipe[1] );
1476         free( My_Connections[i].res_stat );
1477         My_Connections[i].res_stat = NULL;
1478
1479         if( My_Connections[i].sock > NONE )
1480         {
1481                 /* Eingehende Verbindung: Hostnamen setzen */
1482                 c = Client_GetFromConn( i );
1483                 assert( c != NULL );
1484                 strlcpy( My_Connections[i].host, result, sizeof( My_Connections[i].host ));
1485                 Client_SetHostname( c, result );
1486         }
1487         else
1488         {
1489                 /* Ausgehende Verbindung (=Server): IP setzen */
1490                 n = Conf_GetServer( i );
1491                 if( n > NONE ) strlcpy( Conf_Server[n].ip, result, sizeof( Conf_Server[n].ip ));
1492                 else Log( LOG_ERR, "Got resolver result for non-configured server!?" );
1493         }
1494
1495         /* Penalty-Zeit zurueck setzen */
1496         Conn_ResetPenalty( i );
1497 } /* Read_Resolver_Result */
1498
1499
1500 /* -eof- */