conn.c 63 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390
  1. /*
  2. * ngIRCd -- The Next Generation IRC Daemon
  3. * Copyright (c)2001-2010 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. #define CONN_MODULE
  12. #include "portab.h"
  13. #include "conf-ssl.h"
  14. #include "io.h"
  15. /**
  16. * @file
  17. * Connection management
  18. */
  19. #include "imp.h"
  20. #include <assert.h>
  21. #ifdef PROTOTYPES
  22. # include <stdarg.h>
  23. #else
  24. # include <varargs.h>
  25. #endif
  26. #include <stdio.h>
  27. #include <stdlib.h>
  28. #include <unistd.h>
  29. #include <errno.h>
  30. #include <string.h>
  31. #include <sys/socket.h>
  32. #include <sys/time.h>
  33. #include <sys/types.h>
  34. #include <time.h>
  35. #include <netinet/in.h>
  36. #ifdef HAVE_NETINET_IP_H
  37. # ifdef HAVE_NETINET_IN_SYSTM_H
  38. # include <netinet/in_systm.h>
  39. # endif
  40. # include <netinet/ip.h>
  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 "exp.h"
  51. #include "conn.h"
  52. #include "imp.h"
  53. #include "ngircd.h"
  54. #include "array.h"
  55. #include "client.h"
  56. #include "conf.h"
  57. #include "conn-ssl.h"
  58. #include "conn-zip.h"
  59. #include "conn-func.h"
  60. #include "log.h"
  61. #include "ng_ipaddr.h"
  62. #include "parse.h"
  63. #include "resolve.h"
  64. #include "tool.h"
  65. #include "exp.h"
  66. #define SERVER_WAIT (NONE - 1)
  67. #define MAX_COMMANDS 3
  68. #define MAX_COMMANDS_SERVER 10
  69. #define MAX_COMMANDS_SERVICE MAX_COMMANDS_SERVER
  70. static bool Handle_Write PARAMS(( CONN_ID Idx ));
  71. static bool Conn_Write PARAMS(( CONN_ID Idx, char *Data, size_t Len ));
  72. static int New_Connection PARAMS(( int Sock ));
  73. static CONN_ID Socket2Index PARAMS(( int Sock ));
  74. static void Read_Request PARAMS(( CONN_ID Idx ));
  75. static unsigned int Handle_Buffer PARAMS(( CONN_ID Idx ));
  76. static void Check_Connections PARAMS(( void ));
  77. static void Check_Servers PARAMS(( void ));
  78. static void Init_Conn_Struct PARAMS(( CONN_ID Idx ));
  79. static bool Init_Socket PARAMS(( int Sock ));
  80. static void New_Server PARAMS(( int Server, ng_ipaddr_t *dest ));
  81. static void Simple_Message PARAMS(( int Sock, const char *Msg ));
  82. static int NewListener PARAMS(( const char *listen_addr, UINT16 Port ));
  83. static void Account_Connection PARAMS((void));
  84. static array My_Listeners;
  85. static array My_ConnArray;
  86. static size_t NumConnections, NumConnectionsMax, NumConnectionsAccepted;
  87. #ifdef TCPWRAP
  88. int allow_severity = LOG_INFO;
  89. int deny_severity = LOG_ERR;
  90. #endif
  91. static void server_login PARAMS((CONN_ID idx));
  92. #ifdef SSL_SUPPORT
  93. extern struct SSLOptions Conf_SSLOptions;
  94. static void cb_connserver_login_ssl PARAMS((int sock, short what));
  95. static void cb_clientserver_ssl PARAMS((int sock, short what));
  96. #endif
  97. static void cb_Read_Resolver_Result PARAMS((int sock, UNUSED short what));
  98. static void cb_Connect_to_Server PARAMS((int sock, UNUSED short what));
  99. static void cb_clientserver PARAMS((int sock, short what));
  100. /**
  101. * IO callback for listening sockets: handle new connections. This callback
  102. * gets called when a new non-SSL connection should be accepted.
  103. *
  104. * @param sock Socket descriptor.
  105. * @param irrelevant (ignored IO specification)
  106. */
  107. static void
  108. cb_listen(int sock, short irrelevant)
  109. {
  110. (void) irrelevant;
  111. (void) New_Connection(sock);
  112. }
  113. #ifdef SSL_SUPPORT
  114. /**
  115. * IO callback for listening SSL sockets: handle new connections. This callback
  116. * gets called when a new SSL-enabled connection should be accepted.
  117. *
  118. * @param sock Socket descriptor.
  119. * @param irrelevant (ignored IO specification)
  120. */
  121. static void
  122. cb_listen_ssl(int sock, short irrelevant)
  123. {
  124. int fd;
  125. (void) irrelevant;
  126. fd = New_Connection(sock);
  127. if (fd < 0)
  128. return;
  129. io_event_setcb(My_Connections[fd].sock, cb_clientserver_ssl);
  130. }
  131. #endif
  132. /**
  133. * IO callback for new outgoing non-SSL server connections.
  134. *
  135. * @param sock Socket descriptor.
  136. * @param what IO specification (IO_WANTREAD/IO_WANTWRITE/...).
  137. */
  138. static void
  139. cb_connserver(int sock, UNUSED short what)
  140. {
  141. int res, err, server;
  142. socklen_t sock_len;
  143. CONN_ID idx = Socket2Index( sock );
  144. if (idx <= NONE) {
  145. LogDebug("cb_connserver wants to write on unknown socket?!");
  146. io_close(sock);
  147. return;
  148. }
  149. assert(what & IO_WANTWRITE);
  150. /* Make sure that the server is still configured; it could have been
  151. * removed in the meantime! */
  152. server = Conf_GetServer(idx);
  153. if (server < 0) {
  154. Log(LOG_ERR, "Connection on socket %d to \"%s\" aborted!",
  155. sock, My_Connections[idx].host);
  156. Conn_Close(idx, "Connection aborted!", NULL, false);
  157. return;
  158. }
  159. /* connect() finished, get result. */
  160. sock_len = (socklen_t)sizeof(err);
  161. res = getsockopt(My_Connections[idx].sock, SOL_SOCKET, SO_ERROR,
  162. &err, &sock_len );
  163. assert(sock_len == sizeof(err));
  164. /* Error while connecting? */
  165. if ((res != 0) || (err != 0)) {
  166. if (res != 0)
  167. Log(LOG_CRIT, "getsockopt (connection %d): %s!",
  168. idx, strerror(errno));
  169. else
  170. Log(LOG_CRIT,
  171. "Can't connect socket to \"%s:%d\" (connection %d): %s!",
  172. My_Connections[idx].host, Conf_Server[server].port,
  173. idx, strerror(err));
  174. Conn_Close(idx, "Can't connect!", NULL, false);
  175. if (ng_ipaddr_af(&Conf_Server[server].dst_addr[0])) {
  176. /* more addresses to try... */
  177. New_Server(server, &Conf_Server[server].dst_addr[0]);
  178. /* connection to dst_addr[0] is now in progress, so
  179. * remove this address... */
  180. Conf_Server[server].dst_addr[0] =
  181. Conf_Server[server].dst_addr[1];
  182. memset(&Conf_Server[server].dst_addr[1], 0,
  183. sizeof(Conf_Server[server].dst_addr[1]));
  184. }
  185. return;
  186. }
  187. /* connect() succeeded, remove all additional addresses */
  188. memset(&Conf_Server[server].dst_addr, 0,
  189. sizeof(Conf_Server[server].dst_addr));
  190. Conn_OPTION_DEL( &My_Connections[idx], CONN_ISCONNECTING );
  191. #ifdef SSL_SUPPORT
  192. if ( Conn_OPTION_ISSET( &My_Connections[idx], CONN_SSL_CONNECT )) {
  193. io_event_setcb( sock, cb_connserver_login_ssl );
  194. io_event_add( sock, IO_WANTWRITE|IO_WANTREAD );
  195. return;
  196. }
  197. #endif
  198. server_login(idx);
  199. }
  200. /**
  201. * Login to a remote server.
  202. *
  203. * @param idx Connection index.
  204. */
  205. static void
  206. server_login(CONN_ID idx)
  207. {
  208. Log(LOG_INFO,
  209. "Connection %d (socket %d) with \"%s:%d\" established. Now logging in ...",
  210. idx, My_Connections[idx].sock, My_Connections[idx].host,
  211. Conf_Server[Conf_GetServer(idx)].port);
  212. io_event_setcb( My_Connections[idx].sock, cb_clientserver);
  213. io_event_add( My_Connections[idx].sock, IO_WANTREAD|IO_WANTWRITE);
  214. /* Send PASS and SERVER command to peer */
  215. Conn_WriteStr( idx, "PASS %s %s", Conf_Server[Conf_GetServer( idx )].pwd_out, NGIRCd_ProtoID );
  216. Conn_WriteStr( idx, "SERVER %s :%s", Conf_ServerName, Conf_ServerInfo );
  217. }
  218. #ifdef SSL_SUPPORT
  219. /**
  220. * IO callback for new outgoing SSL-enabled server connections.
  221. *
  222. * @param sock Socket descriptor.
  223. * @param unused (ignored IO specification)
  224. */
  225. static void
  226. cb_connserver_login_ssl(int sock, short unused)
  227. {
  228. CONN_ID idx = Socket2Index(sock);
  229. assert(idx >= 0);
  230. if (idx < 0) {
  231. io_close(sock);
  232. return;
  233. }
  234. (void) unused;
  235. switch (ConnSSL_Connect( &My_Connections[idx])) {
  236. case 1: break;
  237. case 0: LogDebug("ConnSSL_Connect: not ready");
  238. return;
  239. case -1:
  240. Log(LOG_ERR, "SSL connection on socket %d failed!", sock);
  241. Conn_Close(idx, "Can't connect!", NULL, false);
  242. return;
  243. }
  244. Log( LOG_INFO, "SSL connection %d with \"%s:%d\" established.", idx,
  245. My_Connections[idx].host, Conf_Server[Conf_GetServer( idx )].port );
  246. server_login(idx);
  247. }
  248. #endif
  249. /**
  250. * IO callback for established non-SSL client and server connections.
  251. *
  252. * @param sock Socket descriptor.
  253. * @param what IO specification (IO_WANTREAD/IO_WANTWRITE/...).
  254. */
  255. static void
  256. cb_clientserver(int sock, short what)
  257. {
  258. CONN_ID idx = Socket2Index(sock);
  259. assert(idx >= 0);
  260. if (idx < 0) {
  261. io_close(sock);
  262. return;
  263. }
  264. #ifdef SSL_SUPPORT
  265. if (what & IO_WANTREAD
  266. || (Conn_OPTION_ISSET(&My_Connections[idx], CONN_SSL_WANT_WRITE))) {
  267. /* if TLS layer needs to write additional data, call
  268. * Read_Request() instead so that SSL/TLS can continue */
  269. Read_Request(idx);
  270. }
  271. #else
  272. if (what & IO_WANTREAD)
  273. Read_Request(idx);
  274. #endif
  275. if (what & IO_WANTWRITE)
  276. Handle_Write(idx);
  277. }
  278. #ifdef SSL_SUPPORT
  279. /**
  280. * IO callback for established SSL-enabled client and server connections.
  281. *
  282. * @param sock Socket descriptor.
  283. * @param what IO specification (IO_WANTREAD/IO_WANTWRITE/...).
  284. */
  285. static void
  286. cb_clientserver_ssl(int sock, short what)
  287. {
  288. CONN_ID idx = Socket2Index(sock);
  289. assert(idx >= 0);
  290. if (idx < 0) {
  291. io_close(sock);
  292. return;
  293. }
  294. switch (ConnSSL_Accept(&My_Connections[idx])) {
  295. case 1:
  296. break; /* OK */
  297. case 0:
  298. return; /* EAGAIN: callback will be invoked again by IO layer */
  299. default:
  300. Conn_Close(idx, "SSL accept error, closing socket", "SSL accept error", false);
  301. return;
  302. }
  303. if (what & IO_WANTREAD)
  304. Read_Request(idx);
  305. if (what & IO_WANTWRITE)
  306. Handle_Write(idx);
  307. io_event_setcb(sock, cb_clientserver); /* SSL handshake completed */
  308. }
  309. #endif
  310. /**
  311. * Initialite connecion module.
  312. */
  313. GLOBAL void
  314. Conn_Init( void )
  315. {
  316. CONN_ID i;
  317. /* Speicher fuer Verbindungs-Pool anfordern */
  318. Pool_Size = CONNECTION_POOL;
  319. if ((Conf_MaxConnections > 0) &&
  320. (Pool_Size > Conf_MaxConnections))
  321. Pool_Size = Conf_MaxConnections;
  322. if (!array_alloc(&My_ConnArray, sizeof(CONNECTION), (size_t)Pool_Size)) {
  323. Log(LOG_EMERG, "Can't allocate memory! [Conn_Init]");
  324. exit(1);
  325. }
  326. /* FIXME: My_Connetions/Pool_Size is needed by other parts of the
  327. * code; remove them! */
  328. My_Connections = (CONNECTION*) array_start(&My_ConnArray);
  329. LogDebug("Allocated connection pool for %d items (%ld bytes).",
  330. array_length(&My_ConnArray, sizeof(CONNECTION)),
  331. array_bytes(&My_ConnArray));
  332. assert(array_length(&My_ConnArray, sizeof(CONNECTION)) >= (size_t)Pool_Size);
  333. array_free( &My_Listeners );
  334. for (i = 0; i < Pool_Size; i++)
  335. Init_Conn_Struct(i);
  336. } /* Conn_Init */
  337. /**
  338. * Clean up connection module.
  339. */
  340. GLOBAL void
  341. Conn_Exit( void )
  342. {
  343. CONN_ID idx;
  344. Conn_ExitListeners();
  345. LogDebug("Shutting down all connections ..." );
  346. for( idx = 0; idx < Pool_Size; idx++ ) {
  347. if( My_Connections[idx].sock > NONE ) {
  348. Conn_Close( idx, NULL, NGIRCd_SignalRestart ?
  349. "Server going down (restarting)":"Server going down", true );
  350. }
  351. }
  352. array_free(&My_ConnArray);
  353. My_Connections = NULL;
  354. Pool_Size = 0;
  355. io_library_shutdown();
  356. } /* Conn_Exit */
  357. /**
  358. * Close all sockets (file descriptors) of open connections.
  359. * This is useful in forked child processes, for example, to make sure that
  360. * they don't hold connections open that the main process wants to close.
  361. */
  362. GLOBAL void
  363. Conn_CloseAllSockets(void)
  364. {
  365. CONN_ID idx;
  366. for(idx = 0; idx < Pool_Size; idx++) {
  367. if(My_Connections[idx].sock > NONE)
  368. close(My_Connections[idx].sock);
  369. }
  370. }
  371. /**
  372. * Initialize listening ports.
  373. *
  374. * @param a Array containing the ports the daemon should listen on.
  375. * @param listen_addr Address the socket should listen on (can be "0.0.0.0").
  376. * @param func IO callback function to register.
  377. * @returns Number of listening sockets created.
  378. */
  379. static unsigned int
  380. ports_initlisteners(array *a, const char *listen_addr, void (*func)(int,short))
  381. {
  382. unsigned int created = 0;
  383. size_t len;
  384. int fd;
  385. UINT16 *port;
  386. len = array_length(a, sizeof (UINT16));
  387. port = array_start(a);
  388. while (len--) {
  389. fd = NewListener(listen_addr, *port);
  390. if (fd < 0) {
  391. port++;
  392. continue;
  393. }
  394. if (!io_event_create( fd, IO_WANTREAD, func )) {
  395. Log( LOG_ERR, "io_event_create(): Could not add listening fd %d (port %u): %s!",
  396. fd, (unsigned int) *port, strerror(errno));
  397. close(fd);
  398. port++;
  399. continue;
  400. }
  401. created++;
  402. port++;
  403. }
  404. return created;
  405. }
  406. /**
  407. * Initialize all listening sockets.
  408. *
  409. * @returns Number of created listening sockets
  410. */
  411. GLOBAL unsigned int
  412. Conn_InitListeners( void )
  413. {
  414. /* Initialize ports on which the server should accept connections */
  415. unsigned int created = 0;
  416. char *copy, *listen_addr;
  417. assert(Conf_ListenAddress);
  418. /* can't use Conf_ListenAddress directly, see below */
  419. copy = strdup(Conf_ListenAddress);
  420. if (!copy) {
  421. Log(LOG_CRIT, "Cannot copy %s: %s", Conf_ListenAddress, strerror(errno));
  422. return 0;
  423. }
  424. listen_addr = strtok(copy, ",");
  425. while (listen_addr) {
  426. ngt_TrimStr(listen_addr);
  427. if (*listen_addr) {
  428. created += ports_initlisteners(&Conf_ListenPorts, listen_addr, cb_listen);
  429. #ifdef SSL_SUPPORT
  430. created += ports_initlisteners(&Conf_SSLOptions.ListenPorts, listen_addr, cb_listen_ssl);
  431. #endif
  432. }
  433. listen_addr = strtok(NULL, ",");
  434. }
  435. /* Can't free() Conf_ListenAddress here: on REHASH, if the config file
  436. * cannot be re-loaded, we'd end up with a NULL Conf_ListenAddress.
  437. * Instead, free() takes place in conf.c, before the config file
  438. * is being parsed. */
  439. free(copy);
  440. return created;
  441. } /* Conn_InitListeners */
  442. /**
  443. * Shut down all listening sockets.
  444. */
  445. GLOBAL void
  446. Conn_ExitListeners( void )
  447. {
  448. /* Close down all listening sockets */
  449. int *fd;
  450. size_t arraylen;
  451. arraylen = array_length(&My_Listeners, sizeof (int));
  452. Log(LOG_INFO,
  453. "Shutting down all listening sockets (%d total) ...", arraylen);
  454. fd = array_start(&My_Listeners);
  455. while(arraylen--) {
  456. assert(fd != NULL);
  457. assert(*fd >= 0);
  458. io_close(*fd);
  459. LogDebug("Listening socket %d closed.", *fd );
  460. fd++;
  461. }
  462. array_free(&My_Listeners);
  463. } /* Conn_ExitListeners */
  464. /**
  465. * Bind a socket to a specific (source) address.
  466. *
  467. * @param addr Address structure.
  468. * @param listen_addrstr Source address as string.
  469. * @param Port Port number.
  470. * @returns true on success, false otherwise.
  471. */
  472. static bool
  473. InitSinaddrListenAddr(ng_ipaddr_t *addr, const char *listen_addrstr, UINT16 Port)
  474. {
  475. bool ret;
  476. ret = ng_ipaddr_init(addr, listen_addrstr, Port);
  477. if (!ret) {
  478. assert(listen_addrstr);
  479. Log(LOG_CRIT, "Can't bind to [%s]:%u: can't convert ip address \"%s\"",
  480. listen_addrstr, Port, listen_addrstr);
  481. }
  482. return ret;
  483. }
  484. /**
  485. * Set a socket to "IPv6 only". If the given socket doesn't belong to the
  486. * AF_INET6 family, or the operating system doesn't support this functionality,
  487. * this function retruns silently.
  488. *
  489. * @param af Address family of the socket.
  490. * @param sock Socket handle.
  491. */
  492. static void
  493. set_v6_only(int af, int sock)
  494. {
  495. #if defined(IPV6_V6ONLY) && defined(WANT_IPV6)
  496. int on = 1;
  497. if (af != AF_INET6)
  498. return;
  499. if (setsockopt(sock, IPPROTO_IPV6, IPV6_V6ONLY, &on, (socklen_t)sizeof(on)))
  500. Log(LOG_ERR, "Could not set IPV6_V6ONLY: %s", strerror(errno));
  501. #else
  502. (void)af;
  503. (void)sock;
  504. #endif
  505. }
  506. /**
  507. * Initialize new listening port.
  508. *
  509. * @param listen_addr Local address to bind the socet to (can be 0.0.0.0).
  510. * @param Port Port number on which the new socket should be listening.
  511. * @returns file descriptor of the socket or -1 on failure.
  512. */
  513. static int
  514. NewListener(const char *listen_addr, UINT16 Port)
  515. {
  516. /* Create new listening socket on specified port */
  517. ng_ipaddr_t addr;
  518. int sock, af;
  519. if (!InitSinaddrListenAddr(&addr, listen_addr, Port))
  520. return -1;
  521. af = ng_ipaddr_af(&addr);
  522. sock = socket(af, SOCK_STREAM, 0);
  523. if( sock < 0 ) {
  524. Log(LOG_CRIT, "Can't create socket (af %d) : %s!", af, strerror(errno));
  525. return -1;
  526. }
  527. set_v6_only(af, sock);
  528. if (!Init_Socket(sock))
  529. return -1;
  530. if (bind(sock, (struct sockaddr *)&addr, ng_ipaddr_salen(&addr)) != 0) {
  531. Log(LOG_CRIT, "Can't bind socket to address %s:%d - %s",
  532. ng_ipaddr_tostr(&addr), Port, strerror(errno));
  533. close(sock);
  534. return -1;
  535. }
  536. if( listen( sock, 10 ) != 0 ) {
  537. Log( LOG_CRIT, "Can't listen on socket: %s!", strerror( errno ));
  538. close( sock );
  539. return -1;
  540. }
  541. /* keep fd in list so we can close it when ngircd restarts/shuts down */
  542. if (!array_catb( &My_Listeners,(char*) &sock, sizeof(int) )) {
  543. Log( LOG_CRIT, "Can't add socket to My_Listeners array: %s!", strerror( errno ));
  544. close( sock );
  545. return -1;
  546. }
  547. Log(LOG_INFO, "Now listening on [%s]:%d (socket %d).",
  548. ng_ipaddr_tostr(&addr), Port, sock);
  549. return sock;
  550. } /* NewListener */
  551. #ifdef SSL_SUPPORT
  552. /**
  553. * Check if SSL library needs to read SSL-protocol related data.
  554. *
  555. * SSL/TLS connections require extra treatment:
  556. * When either CONN_SSL_WANT_WRITE or CONN_SSL_WANT_READ is set, we
  557. * need to take care of that first, before checking read/write buffers.
  558. * For instance, while we might have data in our write buffer, the
  559. * TLS/SSL protocol might need to read internal data first for TLS/SSL
  560. * writes to succeed.
  561. *
  562. * If this function returns true, such a condition is met and we have
  563. * to reverse the condition (check for read even if we've data to write,
  564. * do not check for read but writeability even if write-buffer is empty).
  565. *
  566. * @param c Connection to check.
  567. * @returns true if SSL-library has to read protocol data.
  568. */
  569. static bool
  570. SSL_WantRead(const CONNECTION *c)
  571. {
  572. if (Conn_OPTION_ISSET(c, CONN_SSL_WANT_READ)) {
  573. io_event_add(c->sock, IO_WANTREAD);
  574. return true;
  575. }
  576. return false;
  577. }
  578. /**
  579. * Check if SSL library needs to write SSL-protocol related data.
  580. *
  581. * Please see description of SSL_WantRead() for full description!
  582. *
  583. * @param c Connection to check.
  584. * @returns true if SSL-library has to write protocol data.
  585. */
  586. static bool
  587. SSL_WantWrite(const CONNECTION *c)
  588. {
  589. if (Conn_OPTION_ISSET(c, CONN_SSL_WANT_WRITE)) {
  590. io_event_add(c->sock, IO_WANTWRITE);
  591. return true;
  592. }
  593. return false;
  594. }
  595. #else
  596. static inline bool
  597. SSL_WantRead(UNUSED const CONNECTION *c)
  598. { return false; }
  599. static inline bool
  600. SSL_WantWrite(UNUSED const CONNECTION *c)
  601. { return false; }
  602. #endif
  603. /**
  604. * "Main Loop": Loop until shutdown or restart is signalled.
  605. *
  606. * This function loops until a shutdown or restart of ngIRCd is signalled and
  607. * calls io_dispatch() to check for readable and writable sockets every second.
  608. * It checks for status changes on pending connections (e. g. when a hostname
  609. * has been resolved), checks for "penalties" and timeouts, and handles the
  610. * input buffers.
  611. */
  612. GLOBAL void
  613. Conn_Handler(void)
  614. {
  615. int i;
  616. unsigned int wdatalen, bytes_processed;
  617. struct timeval tv;
  618. time_t t;
  619. while (!NGIRCd_SignalQuit && !NGIRCd_SignalRestart) {
  620. t = time(NULL);
  621. /* Check configured servers and established links */
  622. Check_Servers();
  623. Check_Connections();
  624. /* Look for non-empty read buffers ... */
  625. for (i = 0; i < Pool_Size; i++) {
  626. if ((My_Connections[i].sock > NONE)
  627. && (array_bytes(&My_Connections[i].rbuf) > 0)
  628. && (My_Connections[i].delaytime <= t)) {
  629. /* ... and try to handle the received data */
  630. bytes_processed = Handle_Buffer(i);
  631. /* if we processed data, and there might be
  632. * more commands in the input buffer, do not
  633. * try to read any more data now */
  634. if (bytes_processed &&
  635. array_bytes(&My_Connections[i].rbuf) > 2) {
  636. LogDebug
  637. ("Throttling connection %d: command limit reached!",
  638. i);
  639. Conn_SetPenalty(i, 1);
  640. }
  641. }
  642. }
  643. /* Look for non-empty write buffers ... */
  644. for (i = 0; i < Pool_Size; i++) {
  645. if (My_Connections[i].sock <= NONE)
  646. continue;
  647. wdatalen = (unsigned int)array_bytes(&My_Connections[i].wbuf);
  648. #ifdef ZLIB
  649. if (wdatalen > 0 ||
  650. array_bytes(&My_Connections[i].zip.wbuf) > 0)
  651. #else
  652. if (wdatalen > 0)
  653. #endif
  654. {
  655. if (SSL_WantRead(&My_Connections[i]))
  656. continue;
  657. io_event_add(My_Connections[i].sock,
  658. IO_WANTWRITE);
  659. }
  660. }
  661. /* Check from which sockets we possibly could read ... */
  662. for (i = 0; i < Pool_Size; i++) {
  663. if (My_Connections[i].sock <= NONE)
  664. continue;
  665. #ifdef SSL_SUPPORT
  666. if (SSL_WantWrite(&My_Connections[i]))
  667. continue; /* TLS/SSL layer needs to write data; deal with this first */
  668. #endif
  669. if (Proc_InProgress(&My_Connections[i].proc_stat)) {
  670. /* Wait for completion of forked subprocess
  671. * and ignore the socket in the meantime ... */
  672. io_event_del(My_Connections[i].sock,
  673. IO_WANTREAD);
  674. continue;
  675. }
  676. if (Conn_OPTION_ISSET(&My_Connections[i], CONN_ISCONNECTING))
  677. /* Wait for completion of connect() ... */
  678. continue;
  679. if (My_Connections[i].delaytime > t) {
  680. /* There is a "penalty time" set: ignore socket! */
  681. io_event_del(My_Connections[i].sock,
  682. IO_WANTREAD);
  683. continue;
  684. }
  685. io_event_add(My_Connections[i].sock, IO_WANTREAD);
  686. }
  687. /* Set the timeout for reading from the network to 1 second,
  688. * which is the granularity with witch we handle "penalty
  689. * times" for example.
  690. * Note: tv_sec/usec are undefined(!) after io_dispatch()
  691. * returns, so we have to set it beforce each call to it! */
  692. tv.tv_usec = 0;
  693. tv.tv_sec = 1;
  694. /* Wait for activity ... */
  695. i = io_dispatch(&tv);
  696. if (i == -1 && errno != EINTR) {
  697. Log(LOG_EMERG, "Conn_Handler(): io_dispatch(): %s!",
  698. strerror(errno));
  699. Log(LOG_ALERT, "%s exiting due to fatal errors!",
  700. PACKAGE_NAME);
  701. exit(1);
  702. }
  703. }
  704. if (NGIRCd_SignalQuit)
  705. Log(LOG_NOTICE | LOG_snotice, "Server going down NOW!");
  706. else if (NGIRCd_SignalRestart)
  707. Log(LOG_NOTICE | LOG_snotice, "Server restarting NOW!");
  708. } /* Conn_Handler */
  709. /**
  710. * Write a text string into the socket of a connection.
  711. *
  712. * This function automatically appends CR+LF to the string and validates that
  713. * the result is a valid IRC message (oversized messages are shortened, for
  714. * example). Then it calls the Conn_Write() function to do the actual sending.
  715. *
  716. * @param Idx Index fo the connection.
  717. * @param Format Format string, see printf().
  718. * @returns true on success, false otherwise.
  719. */
  720. #ifdef PROTOTYPES
  721. GLOBAL bool
  722. Conn_WriteStr(CONN_ID Idx, const char *Format, ...)
  723. #else
  724. GLOBAL bool
  725. Conn_WriteStr(Idx, Format, va_alist)
  726. CONN_ID Idx;
  727. const char *Format;
  728. va_dcl
  729. #endif
  730. {
  731. char buffer[COMMAND_LEN];
  732. size_t len;
  733. bool ok;
  734. va_list ap;
  735. assert( Idx > NONE );
  736. assert( Format != NULL );
  737. #ifdef PROTOTYPES
  738. va_start( ap, Format );
  739. #else
  740. va_start( ap );
  741. #endif
  742. if (vsnprintf( buffer, COMMAND_LEN - 2, Format, ap ) >= COMMAND_LEN - 2 ) {
  743. /*
  744. * The string that should be written to the socket is longer
  745. * than the allowed size of COMMAND_LEN bytes (including both
  746. * the CR and LF characters). This can be caused by the
  747. * IRC_WriteXXX() functions when the prefix of this server had
  748. * to be added to an already "quite long" command line which
  749. * has been received from a regular IRC client, for example.
  750. *
  751. * We are not allowed to send such "oversized" messages to
  752. * other servers and clients, see RFC 2812 2.3 and 2813 3.3
  753. * ("these messages SHALL NOT exceed 512 characters in length,
  754. * counting all characters including the trailing CR-LF").
  755. *
  756. * So we have a big problem here: we should send more bytes
  757. * to the network than we are allowed to and we don't know
  758. * the originator (any more). The "old" behaviour of blaming
  759. * the receiver ("next hop") is a bad idea (it could be just
  760. * an other server only routing the message!), so the only
  761. * option left is to shorten the string and to hope that the
  762. * result is still somewhat useful ...
  763. * -alex-
  764. */
  765. strcpy (buffer + sizeof(buffer) - strlen(CUT_TXTSUFFIX) - 2 - 1,
  766. CUT_TXTSUFFIX);
  767. }
  768. #ifdef SNIFFER
  769. if (NGIRCd_Sniffer)
  770. Log(LOG_DEBUG, " -> connection %d: '%s'.", Idx, buffer);
  771. #endif
  772. len = strlcat( buffer, "\r\n", sizeof( buffer ));
  773. ok = Conn_Write(Idx, buffer, len);
  774. My_Connections[Idx].msg_out++;
  775. va_end( ap );
  776. return ok;
  777. } /* Conn_WriteStr */
  778. /**
  779. * Append Data to the outbound write buffer of a connection.
  780. *
  781. * @param Idx Index of the connection.
  782. * @param Data pointer to the data.
  783. * @param Len length of Data.
  784. * @returns true on success, false otherwise.
  785. */
  786. static bool
  787. Conn_Write( CONN_ID Idx, char *Data, size_t Len )
  788. {
  789. CLIENT *c;
  790. size_t writebuf_limit = WRITEBUFFER_MAX_LEN;
  791. assert( Idx > NONE );
  792. assert( Data != NULL );
  793. assert( Len > 0 );
  794. c = Conn_GetClient(Idx);
  795. assert( c != NULL);
  796. /* Servers do get special write buffer limits, so they can generate
  797. * all the messages that are required while peering. */
  798. if (Client_Type(c) == CLIENT_SERVER)
  799. writebuf_limit = WRITEBUFFER_SLINK_LEN;
  800. /* Is the socket still open? A previous call to Conn_Write()
  801. * may have closed the connection due to a fatal error.
  802. * In this case it is sufficient to return an error, as well. */
  803. if( My_Connections[Idx].sock <= NONE ) {
  804. LogDebug("Skipped write on closed socket (connection %d).", Idx);
  805. return false;
  806. }
  807. #ifdef ZLIB
  808. if ( Conn_OPTION_ISSET( &My_Connections[Idx], CONN_ZIP )) {
  809. /* Compressed link:
  810. * Zip_Buffer() does all the dirty work for us: it flushes
  811. * the (pre-)compression buffers if required and handles
  812. * all error conditions. */
  813. if (!Zip_Buffer(Idx, Data, Len))
  814. return false;
  815. }
  816. else
  817. #endif
  818. {
  819. /* Uncompressed link:
  820. * Check if outbound buffer has enough space for the data. */
  821. if (array_bytes(&My_Connections[Idx].wbuf) + Len >=
  822. WRITEBUFFER_FLUSH_LEN) {
  823. /* Buffer is full, flush it. Handle_Write deals with
  824. * low-level errors, if any. */
  825. if (!Handle_Write(Idx))
  826. return false;
  827. }
  828. /* When the write buffer is still too big after flushing it,
  829. * the connection will be killed. */
  830. if (array_bytes(&My_Connections[Idx].wbuf) + Len >=
  831. writebuf_limit) {
  832. Log(LOG_NOTICE,
  833. "Write buffer space exhausted (connection %d, limit is %lu bytes, %lu bytes new, %lu bytes pending)",
  834. Idx, writebuf_limit, Len,
  835. (unsigned long)array_bytes(&My_Connections[Idx].wbuf));
  836. Conn_Close(Idx, "Write buffer space exhausted", NULL, false);
  837. return false;
  838. }
  839. /* Copy data to write buffer */
  840. if (!array_catb(&My_Connections[Idx].wbuf, Data, Len))
  841. return false;
  842. My_Connections[Idx].bytes_out += Len;
  843. }
  844. /* Adjust global write counter */
  845. WCounter += Len;
  846. return true;
  847. } /* Conn_Write */
  848. /**
  849. * Shut down a connection.
  850. *
  851. * @param Idx Connection index.
  852. * @param LogMsg Message to write to the log or NULL. If no LogMsg
  853. * is given, the FwdMsg is logged.
  854. * @param FwdMsg Message to forward to remote servers.
  855. * @param InformClient If true, inform the client on the connection which is
  856. * to be shut down of the reason (FwdMsg) and send
  857. * connection statistics before disconnecting it.
  858. */
  859. GLOBAL void
  860. Conn_Close( CONN_ID Idx, const char *LogMsg, const char *FwdMsg, bool InformClient )
  861. {
  862. /* Close connection. Open pipes of asyncronous resolver
  863. * sub-processes are closed down. */
  864. CLIENT *c;
  865. double in_k, out_k;
  866. UINT16 port;
  867. #ifdef ZLIB
  868. double in_z_k, out_z_k;
  869. int in_p, out_p;
  870. #endif
  871. assert( Idx > NONE );
  872. /* Is this link already shutting down? */
  873. if( Conn_OPTION_ISSET( &My_Connections[Idx], CONN_ISCLOSING )) {
  874. /* Conn_Close() has been called recursively for this link;
  875. * probabe reason: Handle_Write() failed -- see below. */
  876. LogDebug("Recursive request to close connection: %d", Idx );
  877. return;
  878. }
  879. assert( My_Connections[Idx].sock > NONE );
  880. /* Mark link as "closing" */
  881. Conn_OPTION_ADD( &My_Connections[Idx], CONN_ISCLOSING );
  882. port = ng_ipaddr_getport(&My_Connections[Idx].addr);
  883. Log(LOG_INFO, "Shutting down connection %d (%s) with %s:%d ...", Idx,
  884. LogMsg ? LogMsg : FwdMsg, My_Connections[Idx].host, port);
  885. /* Search client, if any */
  886. c = Conn_GetClient( Idx );
  887. /* Should the client be informed? */
  888. if (InformClient) {
  889. #ifndef STRICT_RFC
  890. /* Send statistics to client if registered as user: */
  891. if ((c != NULL) && (Client_Type(c) == CLIENT_USER)) {
  892. Conn_WriteStr( Idx,
  893. ":%s NOTICE %s :%sConnection statistics: client %.1f kb, server %.1f kb.",
  894. Client_ID(Client_ThisServer()), Client_ID(c),
  895. NOTICE_TXTPREFIX,
  896. (double)My_Connections[Idx].bytes_in / 1024,
  897. (double)My_Connections[Idx].bytes_out / 1024);
  898. }
  899. #endif
  900. /* Send ERROR to client (see RFC 2812, section 3.1.7) */
  901. if (FwdMsg)
  902. Conn_WriteStr(Idx, "ERROR :%s", FwdMsg);
  903. else
  904. Conn_WriteStr(Idx, "ERROR :Closing connection");
  905. }
  906. /* Try to write out the write buffer. Note: Handle_Write() eventually
  907. * removes the CLIENT structure associated with this connection if an
  908. * error occurs! So we have to re-check if there is still an valid
  909. * CLIENT structure after calling Handle_Write() ...*/
  910. (void)Handle_Write( Idx );
  911. /* Search client, if any (re-check!) */
  912. c = Conn_GetClient( Idx );
  913. #ifdef SSL_SUPPORT
  914. if ( Conn_OPTION_ISSET( &My_Connections[Idx], CONN_SSL )) {
  915. Log(LOG_INFO, "SSL connection %d shutting down ...", Idx);
  916. ConnSSL_Free(&My_Connections[Idx]);
  917. }
  918. #endif
  919. /* Shut down socket */
  920. if (! io_close(My_Connections[Idx].sock)) {
  921. /* Oops, we can't close the socket!? This is ... ugly! */
  922. Log(LOG_CRIT,
  923. "Error closing connection %d (socket %d) with %s:%d - %s! (ignored)",
  924. Idx, My_Connections[Idx].sock, My_Connections[Idx].host,
  925. port, strerror(errno));
  926. }
  927. /* Mark socket as invalid: */
  928. My_Connections[Idx].sock = NONE;
  929. /* If there is still a client, unregister it now */
  930. if (c)
  931. Client_Destroy(c, LogMsg, FwdMsg, true);
  932. /* Calculate statistics and log information */
  933. in_k = (double)My_Connections[Idx].bytes_in / 1024;
  934. out_k = (double)My_Connections[Idx].bytes_out / 1024;
  935. #ifdef ZLIB
  936. if (Conn_OPTION_ISSET( &My_Connections[Idx], CONN_ZIP)) {
  937. in_z_k = (double)My_Connections[Idx].zip.bytes_in / 1024;
  938. out_z_k = (double)My_Connections[Idx].zip.bytes_out / 1024;
  939. /* Make sure that no division by zero can occur during
  940. * the calculation of in_p and out_p: in_z_k and out_z_k
  941. * are non-zero, that's guaranteed by the protocol until
  942. * compression can be enabled. */
  943. if (! in_z_k)
  944. in_z_k = in_k;
  945. if (! out_z_k)
  946. out_z_k = out_k;
  947. in_p = (int)(( in_k * 100 ) / in_z_k );
  948. out_p = (int)(( out_k * 100 ) / out_z_k );
  949. Log(LOG_INFO,
  950. "Connection %d with %s:%d closed (in: %.1fk/%.1fk/%d%%, out: %.1fk/%.1fk/%d%%).",
  951. Idx, My_Connections[Idx].host, port,
  952. in_k, in_z_k, in_p, out_k, out_z_k, out_p);
  953. }
  954. else
  955. #endif
  956. {
  957. Log(LOG_INFO,
  958. "Connection %d with %s:%d closed (in: %.1fk, out: %.1fk).",
  959. Idx, My_Connections[Idx].host, port,
  960. in_k, out_k);
  961. }
  962. /* Servers: Modify time of next connect attempt? */
  963. Conf_UnsetServer( Idx );
  964. #ifdef ZLIB
  965. /* Clean up zlib, if link was compressed */
  966. if ( Conn_OPTION_ISSET( &My_Connections[Idx], CONN_ZIP )) {
  967. inflateEnd( &My_Connections[Idx].zip.in );
  968. deflateEnd( &My_Connections[Idx].zip.out );
  969. array_free(&My_Connections[Idx].zip.rbuf);
  970. array_free(&My_Connections[Idx].zip.wbuf);
  971. }
  972. #endif
  973. array_free(&My_Connections[Idx].rbuf);
  974. array_free(&My_Connections[Idx].wbuf);
  975. /* Clean up connection structure (=free it) */
  976. Init_Conn_Struct( Idx );
  977. assert(NumConnections > 0);
  978. if (NumConnections)
  979. NumConnections--;
  980. LogDebug("Shutdown of connection %d completed, %ld connection%s left.",
  981. Idx, NumConnections, NumConnections != 1 ? "s" : "");
  982. } /* Conn_Close */
  983. /**
  984. * Get current number of connections.
  985. *
  986. * @returns Number of current connections.
  987. */
  988. GLOBAL long
  989. Conn_Count(void)
  990. {
  991. return NumConnections;
  992. } /* Conn_Count */
  993. /**
  994. * Get number of maximum simultaneous connections.
  995. *
  996. * @returns Number of maximum simultaneous connections.
  997. */
  998. GLOBAL long
  999. Conn_CountMax(void)
  1000. {
  1001. return NumConnectionsMax;
  1002. } /* Conn_CountMax */
  1003. /**
  1004. * Get number of connections accepted since the daemon startet.
  1005. *
  1006. * @returns Number of connections accepted.
  1007. */
  1008. GLOBAL long
  1009. Conn_CountAccepted(void)
  1010. {
  1011. return NumConnectionsAccepted;
  1012. } /* Conn_CountAccepted */
  1013. /**
  1014. * Synchronize established connections and configured server structures
  1015. * after a configuration update and store the correct connection IDs, if any.
  1016. */
  1017. GLOBAL void
  1018. Conn_SyncServerStruct(void)
  1019. {
  1020. CLIENT *client;
  1021. CONN_ID i;
  1022. int c;
  1023. for (i = 0; i < Pool_Size; i++) {
  1024. if (My_Connections[i].sock == NONE)
  1025. continue;
  1026. /* Server link? */
  1027. client = Conn_GetClient(i);
  1028. if (!client || Client_Type(client) != CLIENT_SERVER)
  1029. continue;
  1030. for (c = 0; c < MAX_SERVERS; c++) {
  1031. /* Configured server? */
  1032. if (!Conf_Server[c].host[0])
  1033. continue;
  1034. if (strcasecmp(Conf_Server[c].name, Client_ID(client)) == 0)
  1035. Conf_Server[c].conn_id = i;
  1036. }
  1037. }
  1038. } /* SyncServerStruct */
  1039. /**
  1040. * Send out data of write buffer; connect new sockets.
  1041. *
  1042. * @param Idx Connection index.
  1043. * @returns true on success, false otherwise.
  1044. */
  1045. static bool
  1046. Handle_Write( CONN_ID Idx )
  1047. {
  1048. ssize_t len;
  1049. size_t wdatalen;
  1050. assert( Idx > NONE );
  1051. if ( My_Connections[Idx].sock < 0 ) {
  1052. LogDebug("Handle_Write() on closed socket, connection %d", Idx);
  1053. return false;
  1054. }
  1055. assert( My_Connections[Idx].sock > NONE );
  1056. wdatalen = array_bytes(&My_Connections[Idx].wbuf );
  1057. #ifdef ZLIB
  1058. if (wdatalen == 0) {
  1059. /* Write buffer is empty, so we try to flush the compression
  1060. * buffer and get some data to work with from there :-) */
  1061. if (!Zip_Flush(Idx))
  1062. return false;
  1063. /* Now the write buffer most probably has changed: */
  1064. wdatalen = array_bytes(&My_Connections[Idx].wbuf);
  1065. }
  1066. #endif
  1067. if (wdatalen == 0) {
  1068. /* Still no data, fine. */
  1069. io_event_del(My_Connections[Idx].sock, IO_WANTWRITE );
  1070. return true;
  1071. }
  1072. LogDebug
  1073. ("Handle_Write() called for connection %d, %ld bytes pending ...",
  1074. Idx, wdatalen);
  1075. #ifdef SSL_SUPPORT
  1076. if ( Conn_OPTION_ISSET( &My_Connections[Idx], CONN_SSL )) {
  1077. len = ConnSSL_Write(&My_Connections[Idx], array_start(&My_Connections[Idx].wbuf), wdatalen);
  1078. } else
  1079. #endif
  1080. {
  1081. len = write(My_Connections[Idx].sock,
  1082. array_start(&My_Connections[Idx].wbuf), wdatalen );
  1083. }
  1084. if( len < 0 ) {
  1085. if (errno == EAGAIN || errno == EINTR)
  1086. return true;
  1087. Log(LOG_ERR, "Write error on connection %d (socket %d): %s!",
  1088. Idx, My_Connections[Idx].sock, strerror(errno));
  1089. Conn_Close(Idx, "Write error!", NULL, false);
  1090. return false;
  1091. }
  1092. /* move any data not yet written to beginning */
  1093. array_moveleft(&My_Connections[Idx].wbuf, 1, (size_t)len);
  1094. return true;
  1095. } /* Handle_Write */
  1096. /**
  1097. * Count established connections to a specific IP address.
  1098. *
  1099. * @returns Number of established connections.
  1100. */
  1101. static int
  1102. Count_Connections(ng_ipaddr_t *a)
  1103. {
  1104. int i, cnt;
  1105. cnt = 0;
  1106. for (i = 0; i < Pool_Size; i++) {
  1107. if (My_Connections[i].sock <= NONE)
  1108. continue;
  1109. if (ng_ipaddr_ipequal(&My_Connections[i].addr, a))
  1110. cnt++;
  1111. }
  1112. return cnt;
  1113. } /* Count_Connections */
  1114. /**
  1115. * Initialize new client connection on a listening socket.
  1116. *
  1117. * @param Sock Listening socket descriptor.
  1118. * @returns Accepted socket descriptor or -1 on error.
  1119. */
  1120. static int
  1121. New_Connection(int Sock)
  1122. {
  1123. #ifdef TCPWRAP
  1124. struct request_info req;
  1125. #endif
  1126. ng_ipaddr_t new_addr;
  1127. char ip_str[NG_INET_ADDRSTRLEN];
  1128. int new_sock, new_sock_len, identsock;
  1129. CLIENT *c;
  1130. long cnt;
  1131. assert(Sock > NONE);
  1132. new_sock_len = (int)sizeof(new_addr);
  1133. new_sock = accept(Sock, (struct sockaddr *)&new_addr,
  1134. (socklen_t *)&new_sock_len);
  1135. if (new_sock < 0) {
  1136. Log(LOG_CRIT, "Can't accept connection: %s!", strerror(errno));
  1137. return -1;
  1138. }
  1139. NumConnectionsAccepted++;
  1140. if (!ng_ipaddr_tostr_r(&new_addr, ip_str)) {
  1141. Log(LOG_CRIT, "fd %d: Can't convert IP address!", new_sock);
  1142. Simple_Message(new_sock, "ERROR :Internal Server Error");
  1143. close(new_sock);
  1144. return -1;
  1145. }
  1146. #ifdef TCPWRAP
  1147. /* Validate socket using TCP Wrappers */
  1148. request_init(&req, RQ_DAEMON, PACKAGE_NAME, RQ_FILE, new_sock,
  1149. RQ_CLIENT_SIN, &new_addr, NULL);
  1150. fromhost(&req);
  1151. if (!hosts_access(&req)) {
  1152. Log(deny_severity,
  1153. "Refused connection from %s (by TCP Wrappers)!", ip_str);
  1154. Simple_Message(new_sock, "ERROR :Connection refused");
  1155. close(new_sock);
  1156. return -1;
  1157. }
  1158. #endif
  1159. if (!Init_Socket(new_sock))
  1160. return -1;
  1161. /* Check global connection limit */
  1162. if ((Conf_MaxConnections > 0) &&
  1163. (NumConnections >= (size_t) Conf_MaxConnections)) {
  1164. Log(LOG_ALERT, "Can't accept connection: limit (%d) reached!",
  1165. Conf_MaxConnections);
  1166. Simple_Message(new_sock, "ERROR :Connection limit reached");
  1167. close(new_sock);
  1168. return -1;
  1169. }
  1170. /* Check IP-based connection limit */
  1171. cnt = Count_Connections(&new_addr);
  1172. if ((Conf_MaxConnectionsIP > 0) && (cnt >= Conf_MaxConnectionsIP)) {
  1173. /* Access denied, too many connections from this IP address! */
  1174. Log(LOG_ERR,
  1175. "Refused connection from %s: too may connections (%ld) from this IP address!",
  1176. ip_str, cnt);
  1177. Simple_Message(new_sock,
  1178. "ERROR :Connection refused, too many connections from your IP address");
  1179. close(new_sock);
  1180. return -1;
  1181. }
  1182. if (new_sock >= Pool_Size) {
  1183. if (!array_alloc(&My_ConnArray, sizeof(CONNECTION),
  1184. (size_t) new_sock)) {
  1185. Log(LOG_EMERG,
  1186. "Can't allocate memory! [New_Connection]");
  1187. Simple_Message(new_sock, "ERROR: Internal error");
  1188. close(new_sock);
  1189. return -1;
  1190. }
  1191. LogDebug("Bumped connection pool to %ld items (internal: %ld items, %ld bytes)",
  1192. new_sock, array_length(&My_ConnArray,
  1193. sizeof(CONNECTION)), array_bytes(&My_ConnArray));
  1194. /* Adjust pointer to new block */
  1195. My_Connections = array_start(&My_ConnArray);
  1196. while (Pool_Size <= new_sock)
  1197. Init_Conn_Struct(Pool_Size++);
  1198. }
  1199. /* register callback */
  1200. if (!io_event_create(new_sock, IO_WANTREAD, cb_clientserver)) {
  1201. Log(LOG_ALERT,
  1202. "Can't accept connection: io_event_create failed!");
  1203. Simple_Message(new_sock, "ERROR :Internal error");
  1204. close(new_sock);
  1205. return -1;
  1206. }
  1207. c = Client_NewLocal(new_sock, ip_str, CLIENT_UNKNOWN, false);
  1208. if (!c) {
  1209. Log(LOG_ALERT,
  1210. "Can't accept connection: can't create client structure!");
  1211. Simple_Message(new_sock, "ERROR :Internal error");
  1212. io_close(new_sock);
  1213. return -1;
  1214. }
  1215. Init_Conn_Struct(new_sock);
  1216. My_Connections[new_sock].sock = new_sock;
  1217. My_Connections[new_sock].addr = new_addr;
  1218. My_Connections[new_sock].client = c;
  1219. /* Set initial hostname to IP address. This becomes overwritten when
  1220. * the DNS lookup is enabled and succeeds, but is used otherwise. */
  1221. if (ng_ipaddr_af(&new_addr) != AF_INET)
  1222. snprintf(My_Connections[new_sock].host,
  1223. sizeof(My_Connections[new_sock].host), "[%s]", ip_str);
  1224. else
  1225. strlcpy(My_Connections[new_sock].host, ip_str,
  1226. sizeof(My_Connections[new_sock].host));
  1227. Client_SetHostname(c, My_Connections[new_sock].host);
  1228. Log(LOG_INFO, "Accepted connection %d from %s:%d on socket %d.",
  1229. new_sock, My_Connections[new_sock].host,
  1230. ng_ipaddr_getport(&new_addr), Sock);
  1231. identsock = new_sock;
  1232. #ifdef IDENTAUTH
  1233. if (!Conf_Ident)
  1234. identsock = -1;
  1235. #endif
  1236. if (Conf_DNS) {
  1237. if (Conf_NoticeAuth) {
  1238. #ifdef IDENTAUTH
  1239. if (Conf_Ident)
  1240. (void)Conn_WriteStr(new_sock,
  1241. "NOTICE AUTH :*** Looking up your hostname and checking ident");
  1242. else
  1243. #endif
  1244. (void)Conn_WriteStr(new_sock,
  1245. "NOTICE AUTH :*** Looking up your hostname");
  1246. }
  1247. Resolve_Addr(&My_Connections[new_sock].proc_stat, &new_addr,
  1248. identsock, cb_Read_Resolver_Result);
  1249. }
  1250. Account_Connection();
  1251. return new_sock;
  1252. } /* New_Connection */
  1253. /**
  1254. * Update global connection counters.
  1255. */
  1256. static void
  1257. Account_Connection(void)
  1258. {
  1259. NumConnections++;
  1260. if (NumConnections > NumConnectionsMax)
  1261. NumConnectionsMax = NumConnections;
  1262. LogDebug("Total number of connections now %lu (max %lu).",
  1263. NumConnections, NumConnectionsMax);
  1264. } /* Account_Connection */
  1265. /**
  1266. * Translate socket handle into connection index.
  1267. *
  1268. * @param Sock Socket handle.
  1269. * @returns Connecion index or NONE, if no connection could be found.
  1270. */
  1271. static CONN_ID
  1272. Socket2Index( int Sock )
  1273. {
  1274. assert( Sock >= 0 );
  1275. if( Sock >= Pool_Size || My_Connections[Sock].sock != Sock ) {
  1276. /* the Connection was already closed again, likely due to
  1277. * an error. */
  1278. LogDebug("Socket2Index: can't get connection for socket %d!", Sock);
  1279. return NONE;
  1280. }
  1281. return Sock;
  1282. } /* Socket2Index */
  1283. /**
  1284. * Read data from the network to the read buffer. If an error occures,
  1285. * the socket of this connection will be shut down.
  1286. *
  1287. * @param Idx Connection index.
  1288. */
  1289. static void
  1290. Read_Request( CONN_ID Idx )
  1291. {
  1292. ssize_t len;
  1293. static const unsigned int maxbps = COMMAND_LEN / 2;
  1294. char readbuf[READBUFFER_LEN];
  1295. time_t t;
  1296. CLIENT *c;
  1297. assert( Idx > NONE );
  1298. assert( My_Connections[Idx].sock > NONE );
  1299. #ifdef ZLIB
  1300. if ((array_bytes(&My_Connections[Idx].rbuf) >= READBUFFER_LEN) ||
  1301. (array_bytes(&My_Connections[Idx].zip.rbuf) >= READBUFFER_LEN))
  1302. #else
  1303. if (array_bytes(&My_Connections[Idx].rbuf) >= READBUFFER_LEN)
  1304. #endif
  1305. {
  1306. /* Read buffer is full */
  1307. Log(LOG_ERR,
  1308. "Receive buffer space exhausted (connection %d): %d bytes",
  1309. Idx, array_bytes(&My_Connections[Idx].rbuf));
  1310. Conn_Close(Idx, "Receive buffer space exhausted", NULL, false);
  1311. return;
  1312. }
  1313. #ifdef SSL_SUPPORT
  1314. if (Conn_OPTION_ISSET(&My_Connections[Idx], CONN_SSL))
  1315. len = ConnSSL_Read( &My_Connections[Idx], readbuf, sizeof(readbuf));
  1316. else
  1317. #endif
  1318. len = read(My_Connections[Idx].sock, readbuf, sizeof(readbuf));
  1319. if (len == 0) {
  1320. Log(LOG_INFO, "%s:%u (%s) is closing the connection ...",
  1321. My_Connections[Idx].host,
  1322. (unsigned int) ng_ipaddr_getport(&My_Connections[Idx].addr),
  1323. ng_ipaddr_tostr(&My_Connections[Idx].addr));
  1324. Conn_Close(Idx,
  1325. "Socket closed!", "Client closed connection",
  1326. false);
  1327. return;
  1328. }
  1329. if (len < 0) {
  1330. if( errno == EAGAIN ) return;
  1331. Log(LOG_ERR, "Read error on connection %d (socket %d): %s!",
  1332. Idx, My_Connections[Idx].sock, strerror(errno));
  1333. Conn_Close(Idx, "Read error!", "Client closed connection",
  1334. false);
  1335. return;
  1336. }
  1337. #ifdef ZLIB
  1338. if (Conn_OPTION_ISSET(&My_Connections[Idx], CONN_ZIP)) {
  1339. if (!array_catb(&My_Connections[Idx].zip.rbuf, readbuf,
  1340. (size_t) len)) {
  1341. Log(LOG_ERR,
  1342. "Could not append recieved data to zip input buffer (connn %d): %d bytes!",
  1343. Idx, len);
  1344. Conn_Close(Idx, "Receive buffer space exhausted", NULL,
  1345. false);
  1346. return;
  1347. }
  1348. } else
  1349. #endif
  1350. {
  1351. if (!array_catb( &My_Connections[Idx].rbuf, readbuf, len)) {
  1352. Log( LOG_ERR, "Could not append recieved data to input buffer (connn %d): %d bytes!", Idx, len );
  1353. Conn_Close(Idx, "Receive buffer space exhausted", NULL, false );
  1354. }
  1355. }
  1356. /* Update connection statistics */
  1357. My_Connections[Idx].bytes_in += len;
  1358. My_Connections[Idx].bps += Handle_Buffer(Idx);
  1359. /* Make sure that there is still a valid client registered */
  1360. c = Conn_GetClient(Idx);
  1361. if (!c)
  1362. return;
  1363. /* Update timestamp of last data received if this connection is
  1364. * registered as a user, server or service connection. Don't update
  1365. * otherwise, so users have at least Conf_PongTimeout seconds time to
  1366. * register with the IRC server -- see Check_Connections().
  1367. * Update "lastping", too, if time shifted backwards ... */
  1368. if (Client_Type(c) == CLIENT_USER
  1369. || Client_Type(c) == CLIENT_SERVER
  1370. || Client_Type(c) == CLIENT_SERVICE) {
  1371. t = time(NULL);
  1372. if (My_Connections[Idx].lastdata != t)
  1373. My_Connections[Idx].bps = 0;
  1374. My_Connections[Idx].lastdata = t;
  1375. if (My_Connections[Idx].lastping > t)
  1376. My_Connections[Idx].lastping = t;
  1377. }
  1378. /* Look at the data in the (read-) buffer of this connection */
  1379. if (Client_Type(c) != CLIENT_SERVER
  1380. && Client_Type(c) != CLIENT_UNKNOWNSERVER
  1381. && Client_Type(c) != CLIENT_SERVICE
  1382. && My_Connections[Idx].bps >= maxbps) {
  1383. LogDebug("Throttling connection %d: BPS exceeded! (%u >= %u)",
  1384. Idx, My_Connections[Idx].bps, maxbps);
  1385. Conn_SetPenalty(Idx, 1);
  1386. }
  1387. } /* Read_Request */
  1388. /**
  1389. * Handle all data in the connection read-buffer.
  1390. *
  1391. * Data is processed until no complete command is left in the read buffer,
  1392. * or MAX_COMMANDS[_SERVER|_SERVICE] commands were processed.
  1393. * When a fatal error occurs, the connection is shut down.
  1394. *
  1395. * @param Idx Index of the connection.
  1396. * @returns Number of bytes processed.
  1397. */
  1398. static unsigned int
  1399. Handle_Buffer(CONN_ID Idx)
  1400. {
  1401. #ifndef STRICT_RFC
  1402. char *ptr1, *ptr2, *first_eol;
  1403. #endif
  1404. char *ptr;
  1405. size_t len, delta;
  1406. time_t starttime;
  1407. #ifdef ZLIB
  1408. bool old_z;
  1409. #endif
  1410. unsigned int i, maxcmd = MAX_COMMANDS, len_processed = 0;
  1411. CLIENT *c;
  1412. c = Conn_GetClient(Idx);
  1413. starttime = time(NULL);
  1414. assert(c != NULL);
  1415. /* Servers do get special command limits, so they can process
  1416. * all the messages that are required while peering. */
  1417. switch (Client_Type(c)) {
  1418. case CLIENT_SERVER:
  1419. /* Allow servers to send more commands in the first 10 secods
  1420. * to speed up server login and network synchronisation. */
  1421. if (starttime - Client_StartTime(c) < 10)
  1422. maxcmd = MAX_COMMANDS_SERVER * 5;
  1423. else
  1424. maxcmd = MAX_COMMANDS_SERVER;
  1425. break;
  1426. case CLIENT_SERVICE:
  1427. maxcmd = MAX_COMMANDS_SERVICE; break;
  1428. }
  1429. for (i=0; i < maxcmd; i++) {
  1430. /* Check penalty */
  1431. if (My_Connections[Idx].delaytime > starttime)
  1432. return 0;
  1433. #ifdef ZLIB
  1434. /* Unpack compressed data, if compression is in use */
  1435. if (Conn_OPTION_ISSET(&My_Connections[Idx], CONN_ZIP)) {
  1436. /* When unzipping fails, Unzip_Buffer() shuts
  1437. * down the connection itself */
  1438. if (!Unzip_Buffer(Idx))
  1439. return 0;
  1440. }
  1441. #endif
  1442. if (0 == array_bytes(&My_Connections[Idx].rbuf))
  1443. break;
  1444. /* Make sure that the buffer is NULL terminated */
  1445. if (!array_cat0_temporary(&My_Connections[Idx].rbuf)) {
  1446. Conn_Close(Idx, NULL,
  1447. "Can't allocate memory [Handle_Buffer]",
  1448. true);
  1449. return 0;
  1450. }
  1451. /* RFC 2812, section "2.3 Messages", 5th paragraph:
  1452. * "IRC messages are always lines of characters terminated
  1453. * with a CR-LF (Carriage Return - Line Feed) pair [...]". */
  1454. delta = 2;
  1455. ptr = strstr(array_start(&My_Connections[Idx].rbuf), "\r\n");
  1456. #ifndef STRICT_RFC
  1457. /* Check for non-RFC-compliant request (only CR or LF)?
  1458. * Unfortunately, there are quite a few clients out there
  1459. * that do this -- e. g. mIRC, BitchX, and Trillian :-( */
  1460. ptr1 = strchr(array_start(&My_Connections[Idx].rbuf), '\r');
  1461. ptr2 = strchr(array_start(&My_Connections[Idx].rbuf), '\n');
  1462. if (ptr) {
  1463. /* Check if there is a single CR or LF _before_ the
  1464. * corerct CR+LF line terminator: */
  1465. first_eol = ptr1 < ptr2 ? ptr1 : ptr2;
  1466. if (first_eol < ptr) {
  1467. /* Single CR or LF before CR+LF found */
  1468. ptr = first_eol;
  1469. delta = 1;
  1470. }
  1471. } else if (ptr1 || ptr2) {
  1472. /* No CR+LF terminated command found, but single
  1473. * CR or LF found ... */
  1474. if (ptr1 && ptr2)
  1475. ptr = ptr1 < ptr2 ? ptr1 : ptr2;
  1476. else
  1477. ptr = ptr1 ? ptr1 : ptr2;
  1478. delta = 1;
  1479. }
  1480. #endif
  1481. if (!ptr)
  1482. break;
  1483. /* Complete (=line terminated) request found, handle it! */
  1484. *ptr = '\0';
  1485. len = ptr - (char *)array_start(&My_Connections[Idx].rbuf) + delta;
  1486. if (len > (COMMAND_LEN - 1)) {
  1487. /* Request must not exceed 512 chars (incl. CR+LF!),
  1488. * see RFC 2812. Disconnect Client if this happens. */
  1489. Log(LOG_ERR,
  1490. "Request too long (connection %d): %d bytes (max. %d expected)!",
  1491. Idx, array_bytes(&My_Connections[Idx].rbuf),
  1492. COMMAND_LEN - 1);
  1493. Conn_Close(Idx, NULL, "Request too long", true);
  1494. return 0;
  1495. }
  1496. len_processed += (unsigned int)len;
  1497. if (len <= delta) {
  1498. /* Request is empty (only '\r\n', '\r' or '\n');
  1499. * delta is 2 ('\r\n') or 1 ('\r' or '\n'), see above */
  1500. array_moveleft(&My_Connections[Idx].rbuf, 1, len);
  1501. continue;
  1502. }
  1503. #ifdef ZLIB
  1504. /* remember if stream is already compressed */
  1505. old_z = My_Connections[Idx].options & CONN_ZIP;
  1506. #endif
  1507. My_Connections[Idx].msg_in++;
  1508. if (!Parse_Request
  1509. (Idx, (char *)array_start(&My_Connections[Idx].rbuf)))
  1510. return 0; /* error -> connection has been closed */
  1511. array_moveleft(&My_Connections[Idx].rbuf, 1, len);
  1512. LogDebug("Connection %d: %d bytes left in read buffer.",
  1513. Idx, array_bytes(&My_Connections[Idx].rbuf));
  1514. #ifdef ZLIB
  1515. if ((!old_z) && (My_Connections[Idx].options & CONN_ZIP) &&
  1516. (array_bytes(&My_Connections[Idx].rbuf) > 0)) {
  1517. /* The last command activated socket compression.
  1518. * Data that was read after that needs to be copied
  1519. * to the unzip buffer for decompression: */
  1520. if (!array_copy
  1521. (&My_Connections[Idx].zip.rbuf,
  1522. &My_Connections[Idx].rbuf)) {
  1523. Conn_Close(Idx, NULL,
  1524. "Can't allocate memory [Handle_Buffer]",
  1525. true);
  1526. return 0;
  1527. }
  1528. array_trunc(&My_Connections[Idx].rbuf);
  1529. LogDebug
  1530. ("Moved already received data (%u bytes) to uncompression buffer.",
  1531. array_bytes(&My_Connections[Idx].zip.rbuf));
  1532. }
  1533. #endif
  1534. }
  1535. return len_processed;
  1536. } /* Handle_Buffer */
  1537. /**
  1538. * Check whether established connections are still alive or not.
  1539. * If not, play PING-PONG first; and if that doesn't help either,
  1540. * disconnect the respective peer.
  1541. */
  1542. static void
  1543. Check_Connections(void)
  1544. {
  1545. CLIENT *c;
  1546. CONN_ID i;
  1547. char msg[64];
  1548. for (i = 0; i < Pool_Size; i++) {
  1549. if (My_Connections[i].sock < 0)
  1550. continue;
  1551. c = Conn_GetClient(i);
  1552. if (c && ((Client_Type(c) == CLIENT_USER)
  1553. || (Client_Type(c) == CLIENT_SERVER)
  1554. || (Client_Type(c) == CLIENT_SERVICE))) {
  1555. /* connected User, Server or Service */
  1556. if (My_Connections[i].lastping >
  1557. My_Connections[i].lastdata) {
  1558. /* We already sent a ping */
  1559. if (My_Connections[i].lastping <
  1560. time(NULL) - Conf_PongTimeout) {
  1561. /* Timeout */
  1562. LogDebug
  1563. ("Connection %d: Ping timeout: %d seconds.",
  1564. i, Conf_PongTimeout);
  1565. snprintf(msg, sizeof(msg), "Ping timeout: %d seconds", Conf_PongTimeout);
  1566. Conn_Close(i, NULL, msg, true);
  1567. }
  1568. } else if (My_Connections[i].lastdata <
  1569. time(NULL) - Conf_PingTimeout) {
  1570. /* We need to send a PING ... */
  1571. LogDebug("Connection %d: sending PING ...", i);
  1572. My_Connections[i].lastping = time(NULL);
  1573. Conn_WriteStr(i, "PING :%s",
  1574. Client_ID(Client_ThisServer()));
  1575. }
  1576. } else {
  1577. /* The connection is not fully established yet, so
  1578. * we don't do the PING-PONG game here but instead
  1579. * disconnect the client after "a short time" if it's
  1580. * still not registered. */
  1581. if (My_Connections[i].lastdata <
  1582. time(NULL) - Conf_PongTimeout) {
  1583. LogDebug
  1584. ("Unregistered connection %d timed out ...",
  1585. i);
  1586. Conn_Close(i, NULL, "Timeout", false);
  1587. }
  1588. }
  1589. }
  1590. } /* Check_Connections */
  1591. /**
  1592. * Check if further server links should be established.
  1593. */
  1594. static void
  1595. Check_Servers(void)
  1596. {
  1597. int i, n;
  1598. time_t time_now;
  1599. time_now = time(NULL);
  1600. /* Check all configured servers */
  1601. for (i = 0; i < MAX_SERVERS; i++) {
  1602. if (Conf_Server[i].conn_id != NONE)
  1603. continue; /* Already establishing or connected */
  1604. if (!Conf_Server[i].host[0] || !Conf_Server[i].port > 0)
  1605. continue; /* No host and/or port configured */
  1606. if (Conf_Server[i].flags & CONF_SFLAG_DISABLED)
  1607. continue; /* Disabled configuration entry */
  1608. if (Conf_Server[i].lasttry > (time_now - Conf_ConnectRetry))
  1609. continue; /* We have to wait a little bit ... */
  1610. /* Is there already a connection in this group? */
  1611. if (Conf_Server[i].group > NONE) {
  1612. for (n = 0; n < MAX_SERVERS; n++) {
  1613. if (n == i)
  1614. continue;
  1615. if ((Conf_Server[n].conn_id != NONE) &&
  1616. (Conf_Server[n].group == Conf_Server[i].group))
  1617. break;
  1618. }
  1619. if (n < MAX_SERVERS)
  1620. continue;
  1621. }
  1622. /* Okay, try to connect now */
  1623. Log(LOG_NOTICE,
  1624. "Preparing to establish a new server link for \"%s\" ...",
  1625. Conf_Server[i].name);
  1626. Conf_Server[i].lasttry = time_now;
  1627. Conf_Server[i].conn_id = SERVER_WAIT;
  1628. assert(Proc_GetPipeFd(&Conf_Server[i].res_stat) < 0);
  1629. Resolve_Name(&Conf_Server[i].res_stat, Conf_Server[i].host,
  1630. cb_Connect_to_Server);
  1631. }
  1632. } /* Check_Servers */
  1633. /**
  1634. * Establish a new outgoing server connection.
  1635. *
  1636. * @param Server Configuration index of the server.
  1637. * @param dest Destination IP address to connect to.
  1638. */
  1639. static void
  1640. New_Server( int Server , ng_ipaddr_t *dest)
  1641. {
  1642. /* Establish new server link */
  1643. char ip_str[NG_INET_ADDRSTRLEN];
  1644. int af_dest, res, new_sock;
  1645. CLIENT *c;
  1646. assert( Server > NONE );
  1647. if (!ng_ipaddr_tostr_r(dest, ip_str)) {
  1648. Log(LOG_WARNING, "New_Server: Could not convert IP to string");
  1649. return;
  1650. }
  1651. af_dest = ng_ipaddr_af(dest);
  1652. new_sock = socket(af_dest, SOCK_STREAM, 0);
  1653. Log(LOG_INFO,
  1654. "Establishing connection for \"%s\" to \"%s:%d\" (%s), socket %d ...",
  1655. Conf_Server[Server].name, Conf_Server[Server].host,
  1656. Conf_Server[Server].port, ip_str, new_sock);
  1657. if (new_sock < 0) {
  1658. Log(LOG_CRIT, "Can't create socket (af %d): %s!",
  1659. af_dest, strerror(errno));
  1660. return;
  1661. }
  1662. if (!Init_Socket(new_sock))
  1663. return;
  1664. /* is a bind address configured? */
  1665. res = ng_ipaddr_af(&Conf_Server[Server].bind_addr);
  1666. /* if yes, bind now. If it fails, warn and let connect() pick a source address */
  1667. if (res && bind(new_sock, (struct sockaddr *) &Conf_Server[Server].bind_addr,
  1668. ng_ipaddr_salen(&Conf_Server[Server].bind_addr)))
  1669. {
  1670. ng_ipaddr_tostr_r(&Conf_Server[Server].bind_addr, ip_str);
  1671. Log(LOG_WARNING, "Can't bind socket to %s: %s!", ip_str, strerror(errno));
  1672. }
  1673. ng_ipaddr_setport(dest, Conf_Server[Server].port);
  1674. res = connect(new_sock, (struct sockaddr *) dest, ng_ipaddr_salen(dest));
  1675. if(( res != 0 ) && ( errno != EINPROGRESS )) {
  1676. Log( LOG_CRIT, "Can't connect socket: %s!", strerror( errno ));
  1677. close( new_sock );
  1678. return;
  1679. }
  1680. if (!array_alloc(&My_ConnArray, sizeof(CONNECTION), (size_t)new_sock)) {
  1681. Log(LOG_ALERT,
  1682. "Cannot allocate memory for server connection (socket %d)",
  1683. new_sock);
  1684. close( new_sock );
  1685. return;
  1686. }
  1687. if (!io_event_create( new_sock, IO_WANTWRITE, cb_connserver)) {
  1688. Log(LOG_ALERT, "io_event_create(): could not add fd %d", strerror(errno));
  1689. close(new_sock);
  1690. return;
  1691. }
  1692. My_Connections = array_start(&My_ConnArray);
  1693. assert(My_Connections[new_sock].sock <= 0);
  1694. Init_Conn_Struct(new_sock);
  1695. ng_ipaddr_tostr_r(dest, ip_str);
  1696. c = Client_NewLocal(new_sock, ip_str, CLIENT_UNKNOWNSERVER, false);
  1697. if (!c) {
  1698. Log( LOG_ALERT, "Can't establish connection: can't create client structure!" );
  1699. io_close(new_sock);
  1700. return;
  1701. }
  1702. /* Conn_Close() decrements this counter again */
  1703. Account_Connection();
  1704. Client_SetIntroducer( c, c );
  1705. Client_SetToken( c, TOKEN_OUTBOUND );
  1706. /* Register connection */
  1707. Conf_Server[Server].conn_id = new_sock;
  1708. My_Connections[new_sock].sock = new_sock;
  1709. My_Connections[new_sock].addr = *dest;
  1710. My_Connections[new_sock].client = c;
  1711. strlcpy( My_Connections[new_sock].host, Conf_Server[Server].host,
  1712. sizeof(My_Connections[new_sock].host ));
  1713. #ifdef SSL_SUPPORT
  1714. if (Conf_Server[Server].SSLConnect && !ConnSSL_PrepareConnect( &My_Connections[new_sock],
  1715. &Conf_Server[Server] ))
  1716. {
  1717. Log(LOG_ALERT, "Could not initialize SSL for outgoing connection");
  1718. Conn_Close( new_sock, "Could not initialize SSL for outgoing connection", NULL, false );
  1719. Init_Conn_Struct( new_sock );
  1720. Conf_Server[Server].conn_id = NONE;
  1721. return;
  1722. }
  1723. #endif
  1724. LogDebug("Registered new connection %d on socket %d (%ld in total).",
  1725. new_sock, My_Connections[new_sock].sock, NumConnections);
  1726. Conn_OPTION_ADD( &My_Connections[new_sock], CONN_ISCONNECTING );
  1727. } /* New_Server */
  1728. /**
  1729. * Initialize connection structure.
  1730. *
  1731. * @param Idx Connection index.
  1732. */
  1733. static void
  1734. Init_Conn_Struct(CONN_ID Idx)
  1735. {
  1736. time_t now = time(NULL);
  1737. memset(&My_Connections[Idx], 0, sizeof(CONNECTION));
  1738. My_Connections[Idx].sock = -1;
  1739. My_Connections[Idx].signon = now;
  1740. My_Connections[Idx].lastdata = now;
  1741. My_Connections[Idx].lastprivmsg = now;
  1742. Proc_InitStruct(&My_Connections[Idx].proc_stat);
  1743. } /* Init_Conn_Struct */
  1744. /**
  1745. * Initialize options of a new socket.
  1746. *
  1747. * For example, we try to set socket options SO_REUSEADDR and IPTOS_LOWDELAY.
  1748. * The socket is automatically closed if a fatal error is encountered.
  1749. *
  1750. * @param Sock Socket handle.
  1751. * @returns false if socket was closed due to fatal error.
  1752. */
  1753. static bool
  1754. Init_Socket( int Sock )
  1755. {
  1756. int value;
  1757. if (!io_setnonblock(Sock)) {
  1758. Log( LOG_CRIT, "Can't enable non-blocking mode for socket: %s!", strerror( errno ));
  1759. close( Sock );
  1760. return false;
  1761. }
  1762. /* Don't block this port after socket shutdown */
  1763. value = 1;
  1764. if( setsockopt( Sock, SOL_SOCKET, SO_REUSEADDR, &value, (socklen_t)sizeof( value )) != 0 )
  1765. {
  1766. Log( LOG_ERR, "Can't set socket option SO_REUSEADDR: %s!", strerror( errno ));
  1767. /* ignore this error */
  1768. }
  1769. /* Set type of service (TOS) */
  1770. #if defined(IPPROTO_IP) && defined(IPTOS_LOWDELAY)
  1771. value = IPTOS_LOWDELAY;
  1772. LogDebug("Setting IP_TOS on socket %d to IPTOS_LOWDELAY.", Sock);
  1773. if (setsockopt(Sock, IPPROTO_IP, IP_TOS, &value,
  1774. (socklen_t) sizeof(value))) {
  1775. LogDebug("Can't set socket option IP_TOS: %s!",
  1776. strerror(errno));
  1777. /* ignore this error */
  1778. }
  1779. #endif
  1780. return true;
  1781. } /* Init_Socket */
  1782. /**
  1783. * Read results of a resolver sub-process and try to initiate a new server
  1784. * connection.
  1785. *
  1786. * @param fd File descriptor of the pipe to the sub-process.
  1787. * @param events (ignored IO specification)
  1788. */
  1789. static void
  1790. cb_Connect_to_Server(int fd, UNUSED short events)
  1791. {
  1792. /* Read result of resolver sub-process from pipe and start connection */
  1793. int i;
  1794. size_t len;
  1795. ng_ipaddr_t dest_addrs[4]; /* we can handle at most 3; but we read up to
  1796. four so we can log the 'more than we can handle'
  1797. condition. First result is tried immediately, rest
  1798. is saved for later if needed. */
  1799. LogDebug("Resolver: Got forward lookup callback on fd %d, events %d", fd, events);
  1800. for (i=0; i < MAX_SERVERS; i++) {
  1801. if (Proc_GetPipeFd(&Conf_Server[i].res_stat) == fd )
  1802. break;
  1803. }
  1804. if( i >= MAX_SERVERS) {
  1805. /* Ops, no matching server found?! */
  1806. io_close( fd );
  1807. LogDebug("Resolver: Got Forward Lookup callback for unknown server!?");
  1808. return;
  1809. }
  1810. /* Read result from pipe */
  1811. len = Proc_Read(&Conf_Server[i].res_stat, dest_addrs, sizeof(dest_addrs));
  1812. if (len == 0) {
  1813. /* Error resolving hostname: reset server structure */
  1814. Conf_Server[i].conn_id = NONE;
  1815. return;
  1816. }
  1817. assert((len % sizeof(ng_ipaddr_t)) == 0);
  1818. LogDebug("Got result from resolver: %u structs (%u bytes).", len/sizeof(ng_ipaddr_t), len);
  1819. memset(&Conf_Server[i].dst_addr, 0, sizeof(Conf_Server[i].dst_addr));
  1820. if (len > sizeof(ng_ipaddr_t)) {
  1821. /* more than one address for this hostname, remember them
  1822. * in case first address is unreachable/not available */
  1823. len -= sizeof(ng_ipaddr_t);
  1824. if (len > sizeof(Conf_Server[i].dst_addr)) {
  1825. len = sizeof(Conf_Server[i].dst_addr);
  1826. Log(LOG_NOTICE,
  1827. "Notice: Resolver returned more IP Addresses for host than we can handle, additional addresses dropped.");
  1828. }
  1829. memcpy(&Conf_Server[i].dst_addr, &dest_addrs[1], len);
  1830. }
  1831. /* connect() */
  1832. New_Server(i, dest_addrs);
  1833. } /* cb_Read_Forward_Lookup */
  1834. /**
  1835. * Read results of a resolver sub-process from the pipe and update the
  1836. * apropriate connection/client structure(s): hostname and/or IDENT user name.
  1837. *
  1838. * @param r_fd File descriptor of the pipe to the sub-process.
  1839. * @param events (ignored IO specification)
  1840. */
  1841. static void
  1842. cb_Read_Resolver_Result( int r_fd, UNUSED short events )
  1843. {
  1844. CLIENT *c;
  1845. CONN_ID i;
  1846. size_t len;
  1847. char *identptr;
  1848. #ifdef IDENTAUTH
  1849. char readbuf[HOST_LEN + 2 + CLIENT_USER_LEN];
  1850. #else
  1851. char readbuf[HOST_LEN + 1];
  1852. #endif
  1853. LogDebug("Resolver: Got callback on fd %d, events %d", r_fd, events );
  1854. i = Conn_GetFromProc(r_fd);
  1855. if (i == NONE) {
  1856. /* Ops, none found? Probably the connection has already
  1857. * been closed!? We'll ignore that ... */
  1858. io_close( r_fd );
  1859. LogDebug("Resolver: Got callback for unknown connection!?");
  1860. return;
  1861. }
  1862. /* Read result from pipe */
  1863. len = Proc_Read(&My_Connections[i].proc_stat, readbuf, sizeof readbuf -1);
  1864. if (len == 0)
  1865. return;
  1866. readbuf[len] = '\0';
  1867. identptr = strchr(readbuf, '\n');
  1868. assert(identptr != NULL);
  1869. if (!identptr) {
  1870. Log( LOG_CRIT, "Resolver: Got malformed result!");
  1871. return;
  1872. }
  1873. *identptr = '\0';
  1874. LogDebug("Got result from resolver: \"%s\" (%u bytes read).", readbuf, len);
  1875. /* Okay, we got a complete result: this is a host name for outgoing
  1876. * connections and a host name and IDENT user name (if enabled) for
  1877. * incoming connections.*/
  1878. assert ( My_Connections[i].sock >= 0 );
  1879. /* Incoming connection. Search client ... */
  1880. c = Conn_GetClient( i );
  1881. assert( c != NULL );
  1882. /* Only update client information of unregistered clients.
  1883. * Note: user commands (e. g. WEBIRC) are always read _after_ reading
  1884. * the resolver results, so we don't have to worry to override settings
  1885. * from these commands here. */
  1886. if(Client_Type(c) == CLIENT_UNKNOWN) {
  1887. strlcpy(My_Connections[i].host, readbuf,
  1888. sizeof(My_Connections[i].host));
  1889. Client_SetHostname(c, readbuf);
  1890. if (Conf_NoticeAuth)
  1891. (void)Conn_WriteStr(i,
  1892. "NOTICE AUTH :*** Found your hostname");
  1893. #ifdef IDENTAUTH
  1894. ++identptr;
  1895. if (*identptr) {
  1896. Log(LOG_INFO, "IDENT lookup for connection %d: \"%s\".", i, identptr);
  1897. Client_SetUser(c, identptr, true);
  1898. if (Conf_NoticeAuth)
  1899. (void)Conn_WriteStr(i,
  1900. "NOTICE AUTH :*** Got ident response");
  1901. } else {
  1902. Log(LOG_INFO, "IDENT lookup for connection %d: no result.", i);
  1903. if (Conf_NoticeAuth && Conf_Ident)
  1904. (void)Conn_WriteStr(i,
  1905. "NOTICE AUTH :*** No ident response");
  1906. }
  1907. #endif
  1908. }
  1909. #ifdef DEBUG
  1910. else Log( LOG_DEBUG, "Resolver: discarding result for already registered connection %d.", i );
  1911. #endif
  1912. } /* cb_Read_Resolver_Result */
  1913. /**
  1914. * Write a "simple" (error) message to a socket.
  1915. *
  1916. * The message is sent without using the connection write buffers, without
  1917. * compression/encryption, and even without any error reporting. It is
  1918. * designed for error messages of e.g. New_Connection().
  1919. *
  1920. * @param Sock Socket handle.
  1921. * @param Msg Message string to send.
  1922. */
  1923. static void
  1924. Simple_Message(int Sock, const char *Msg)
  1925. {
  1926. char buf[COMMAND_LEN];
  1927. size_t len;
  1928. assert(Sock > NONE);
  1929. assert(Msg != NULL);
  1930. strlcpy(buf, Msg, sizeof buf - 2);
  1931. len = strlcat(buf, "\r\n", sizeof buf);
  1932. if (write(Sock, buf, len) < 0) {
  1933. /* Because this function most probably got called to log
  1934. * an error message, any write error is ignored here to
  1935. * avoid an endless loop. But casting the result of write()
  1936. * to "void" doesn't satisfy the GNU C code attribute
  1937. * "warn_unused_result" which is used by some versions of
  1938. * glibc (e.g. 2.11.1), therefore this silly error
  1939. * "handling" code here :-( */
  1940. return;
  1941. }
  1942. } /* Simple_Error */
  1943. /**
  1944. * Get CLIENT structure that belongs to a local connection identified by its
  1945. * index number. Each connection belongs to a client by definition, so it is
  1946. * not required that the caller checks for NULL return values.
  1947. *
  1948. * @param Idx Connection index number.
  1949. * @returns Pointer to CLIENT structure.
  1950. */
  1951. GLOBAL CLIENT *
  1952. Conn_GetClient( CONN_ID Idx )
  1953. {
  1954. CONNECTION *c;
  1955. assert(Idx >= 0);
  1956. c = array_get(&My_ConnArray, sizeof (CONNECTION), (size_t)Idx);
  1957. assert(c != NULL);
  1958. return c ? c->client : NULL;
  1959. }
  1960. /**
  1961. * Get PROC_STAT sub-process structure of a connection.
  1962. *
  1963. * @param Idx Connection index number.
  1964. * @returns PROC_STAT structure.
  1965. */
  1966. GLOBAL PROC_STAT *
  1967. Conn_GetProcStat(CONN_ID Idx)
  1968. {
  1969. CONNECTION *c;
  1970. assert(Idx >= 0);
  1971. c = array_get(&My_ConnArray, sizeof (CONNECTION), (size_t)Idx);
  1972. assert(c != NULL);
  1973. return &c->proc_stat;
  1974. } /* Conn_GetProcStat */
  1975. /**
  1976. * Get CONN_ID from file descriptor associated to a subprocess structure.
  1977. *
  1978. * @param fd File descriptor.
  1979. * @returns CONN_ID or NONE (-1).
  1980. */
  1981. GLOBAL CONN_ID
  1982. Conn_GetFromProc(int fd)
  1983. {
  1984. int i;
  1985. assert(fd > 0);
  1986. for (i = 0; i < Pool_Size; i++) {
  1987. if ((My_Connections[i].sock != NONE)
  1988. && (Proc_GetPipeFd(&My_Connections[i].proc_stat) == fd))
  1989. return i;
  1990. }
  1991. return NONE;
  1992. } /* Conn_GetFromProc */
  1993. #ifndef STRICT_RFC
  1994. GLOBAL long
  1995. Conn_GetAuthPing(CONN_ID Idx)
  1996. {
  1997. assert (Idx != NONE);
  1998. return My_Connections[Idx].auth_ping;
  1999. } /* Conn_GetAuthPing */
  2000. GLOBAL void
  2001. Conn_SetAuthPing(CONN_ID Idx, long ID)
  2002. {
  2003. assert (Idx != NONE);
  2004. My_Connections[Idx].auth_ping = ID;
  2005. } /* Conn_SetAuthPing */
  2006. #endif
  2007. #ifdef SSL_SUPPORT
  2008. /**
  2009. * Get information about used SSL chiper.
  2010. *
  2011. * @param Idx Connection index number.
  2012. * @param buf Buffer for returned information text.
  2013. * @param len Size of return buffer "buf".
  2014. * @returns true on success, false otherwise.
  2015. */
  2016. GLOBAL bool
  2017. Conn_GetCipherInfo(CONN_ID Idx, char *buf, size_t len)
  2018. {
  2019. if (Idx < 0)
  2020. return false;
  2021. assert(Idx < (int) array_length(&My_ConnArray, sizeof(CONNECTION)));
  2022. return ConnSSL_GetCipherInfo(&My_Connections[Idx], buf, len);
  2023. }
  2024. /**
  2025. * Check if a connection is SSL-enabled or not.
  2026. *
  2027. * @param Idx Connection index number.
  2028. * @return true if connection is SSL-enabled, false otherwise.
  2029. */
  2030. GLOBAL bool
  2031. Conn_UsesSSL(CONN_ID Idx)
  2032. {
  2033. if (Idx < 0)
  2034. return false;
  2035. assert(Idx < (int) array_length(&My_ConnArray, sizeof(CONNECTION)));
  2036. return Conn_OPTION_ISSET(&My_Connections[Idx], CONN_SSL);
  2037. }
  2038. #endif
  2039. #ifdef DEBUG
  2040. /**
  2041. * Dump internal state of the "connection module".
  2042. */
  2043. GLOBAL void
  2044. Conn_DebugDump(void)
  2045. {
  2046. int i;
  2047. Log(LOG_DEBUG, "Connection status:");
  2048. for (i = 0; i < Pool_Size; i++) {
  2049. if (My_Connections[i].sock == NONE)
  2050. continue;
  2051. Log(LOG_DEBUG,
  2052. " - %d: host=%s, lastdata=%ld, lastping=%ld, delaytime=%ld, flag=%d, options=%d, bps=%d, client=%s",
  2053. My_Connections[i].sock, My_Connections[i].host,
  2054. My_Connections[i].lastdata, My_Connections[i].lastping,
  2055. My_Connections[i].delaytime, My_Connections[i].flag,
  2056. My_Connections[i].options, My_Connections[i].bps,
  2057. My_Connections[i].client ? Client_ID(My_Connections[i].client) : "-");
  2058. }
  2059. } /* Conn_DumpClients */
  2060. #endif
  2061. /* -eof- */