conn.c 72 KB

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