conn.c 59 KB

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