conn.c 54 KB

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