conn.c 73 KB

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