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