conn.c 64 KB

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