conn.c 46 KB

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