conn.c 45 KB

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