conn.c 71 KB

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