conn.c 71 KB

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