1
0

conn.c 44 KB

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