net.c 49 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709
  1. /*
  2. * Copyright (C) 1997 Robey Pointer
  3. * Copyright (C) 1999 - 2002 Eggheads Development Team
  4. * Copyright (C) 2002 - 2010 Bryan Drewery
  5. *
  6. * This program is free software; you can redistribute it and/or
  7. * modify it under the terms of the GNU General Public License
  8. * as published by the Free Software Foundation; either version 2
  9. * of the License, or (at your option) any later version.
  10. *
  11. * This program is distributed in the hope that it will be useful,
  12. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  14. * GNU General Public License for more details.
  15. *
  16. * You should have received a copy of the GNU General Public License
  17. * along with this program; if not, write to the Free Software
  18. * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
  19. */
  20. /*
  21. * net.c -- handles:
  22. * all raw network i/o
  23. *
  24. */
  25. #include <fcntl.h>
  26. #include "common.h"
  27. #include "net.h"
  28. #include "socket.h"
  29. #include "misc.h"
  30. #include "main.h"
  31. #include "debug.h"
  32. #include "dccutil.h"
  33. #include "enclink.h"
  34. #include "egg_timer.h"
  35. #include "traffic.h"
  36. #include "adns.h"
  37. #include <bdlib/src/String.h>
  38. #include <bdlib/src/Stream.h>
  39. #include <limits.h>
  40. #include <string.h>
  41. #include <netdb.h>
  42. #include <signal.h>
  43. #include <sys/types.h>
  44. #include <sys/socket.h>
  45. #include <setjmp.h>
  46. #if HAVE_SYS_SELECT_H
  47. # include <sys/select.h>
  48. #endif /* HAVE_SYS_SELECT_H */
  49. #include <netinet/in.h>
  50. #include <arpa/inet.h>
  51. #include <errno.h>
  52. #include <sys/stat.h>
  53. #if HAVE_UNISTD_H
  54. # include <unistd.h>
  55. #endif /* HAVE_UNITSTD_H */
  56. extern egg_traffic_t traffic;
  57. union sockaddr_union cached_myip4_so;
  58. #ifdef USE_IPV6
  59. union sockaddr_union cached_myip6_so;
  60. #endif /* USE_IPV6 */
  61. bool cached_ip = 0; /* Set to 1 after cache_my_ip is called */
  62. bool identd_hack = 0; /* identd_open() won't work on most servers, dont even bother warning. */
  63. char botuser[21] = ""; /* Username of the user running the bot */
  64. int socks_total = 0; /* total number of sockets */
  65. sock_list *socklist = NULL; /* Enough to be safe */
  66. int MAXSOCKS = 0;
  67. jmp_buf alarmret; /* Env buffer for alarm() returns */
  68. /* This *MUST* be an ip */
  69. char firewall[121] = ""; /* Socks server for firewall */
  70. in_port_t firewallport = 1080; /* Default port of Sock4/5 firewalls */
  71. /* Types of proxy */
  72. #define PROXY_SOCKS 1
  73. #define PROXY_SUN 2
  74. #define PROXY_HTTP 3
  75. /* I need an UNSIGNED long for dcc type stuff
  76. */
  77. unsigned long my_atoul(const char *s)
  78. {
  79. unsigned long ret = 0;
  80. while ((*s >= '0') && (*s <= '9')) {
  81. ret *= 10;
  82. ret += ((*s) - '0');
  83. ++s;
  84. }
  85. return ret;
  86. }
  87. /* get the protocol used on a socket */
  88. int sockprotocol(int sock)
  89. {
  90. struct sockaddr sa;
  91. socklen_t socklen = sizeof(sa);
  92. bzero(&sa, socklen);
  93. if (getsockname(sock, &sa, &socklen))
  94. return -1;
  95. else
  96. return sa.sa_family;
  97. }
  98. /* AF_INET-independent resolving routine */
  99. static int get_ip(char *hostname, union sockaddr_union *so, int dns_type)
  100. {
  101. if (!hostname || (hostname && !hostname[0]))
  102. return 1;
  103. memset(so, 0, sizeof(union sockaddr_union));
  104. debug1("get_ip(%s)", hostname);
  105. bd::Array<bd::String> hosts = dns_lookup_block(hostname, 10, dns_type);
  106. if (hosts.length() == 0)
  107. return -1;
  108. my_addr_t addr;
  109. get_addr(bd::String(hosts[0]).c_str(), &addr);
  110. if (addr.family == AF_INET) {
  111. so->sin.sin_family = AF_INET;
  112. memcpy(&so->sin.sin_addr, &addr.u.addr, sizeof(addr.u.addr));
  113. #ifdef USE_IPV6
  114. } else if (addr.family == AF_INET6) {
  115. so->sin6.sin6_family = AF_INET6;
  116. memcpy(&so->sin6.sin6_addr, &addr.u.addr6, sizeof(addr.u.addr6));
  117. #endif
  118. }
  119. return 0;
  120. }
  121. /* Initialize the socklist
  122. */
  123. void init_net()
  124. {
  125. MAXSOCKS = max_dcc + 10;
  126. if (socklist)
  127. socklist = (sock_list *) my_realloc((void *) socklist, sizeof(sock_list) * MAXSOCKS);
  128. else
  129. socklist = (sock_list *) my_calloc(1, sizeof(sock_list) * MAXSOCKS);
  130. for (int i = 0; i < MAXSOCKS; i++) {
  131. bzero(&socklist[i], sizeof(socklist[i]));
  132. socklist[i].flags = SOCK_UNUSED;
  133. #ifdef EGG_SSL_EXT
  134. socklist[i].ssl = NULL;
  135. #endif
  136. socklist[i].sock = -1;
  137. }
  138. }
  139. /* Get my ipv? ip
  140. */
  141. char *myipstr(int af_type)
  142. {
  143. if (cached_ip) {
  144. #ifdef USE_IPV6
  145. if (af_type == AF_INET6) {
  146. static char s[UHOSTLEN + 1] = "";
  147. inet_ntop(AF_INET6, &cached_myip6_so.sin6.sin6_addr, s, 119);
  148. s[120] = 0;
  149. return s;
  150. } else
  151. #endif /* USE_IPV6 */
  152. if (af_type == AF_INET) {
  153. static char s[UHOSTLEN + 1] = "";
  154. inet_ntop(AF_INET, &cached_myip4_so.sin.sin_addr, s, 119);
  155. s[120] = 0;
  156. return s;
  157. }
  158. }
  159. return "";
  160. }
  161. /* Get my ip number
  162. */
  163. in_addr_t getmyip() {
  164. return cached_myip4_so.sin.sin_addr.s_addr;
  165. }
  166. /* see if it's necessary to set inaddr_any... because if we can't resolve, we die anyway */
  167. void cache_my_ip()
  168. {
  169. #ifdef no
  170. cached_myip6_so.sin6.sin6_family = AF_INET6;
  171. cached_myip6_so.sin6.sin6_addr = in6addr_any;
  172. cached_myip4_so.sin.sin_family = AF_INET;
  173. cached_myip4_so.sin.sin_addr.s_addr = INADDR_ANY;
  174. #endif
  175. int error = 0;
  176. debug0("cache_my_ip()");
  177. memset(&cached_myip4_so, 0, sizeof(union sockaddr_union));
  178. #ifdef USE_IPV6
  179. bool any = 0;
  180. memset(&cached_myip6_so, 0, sizeof(union sockaddr_union));
  181. if (conf.bot->net.ip6) {
  182. if (get_ip(conf.bot->net.ip6, &cached_myip6_so, DNS_LOOKUP_AAAA))
  183. any = 1;
  184. } else if (conf.bot->net.host6) {
  185. if (get_ip(conf.bot->net.host6, &cached_myip6_so, DNS_LOOKUP_AAAA))
  186. any = 1;
  187. } else
  188. any = 1;
  189. if (any) {
  190. cached_myip6_so.sin6.sin6_family = AF_INET6;
  191. cached_myip6_so.sin6.sin6_addr = in6addr_any;
  192. }
  193. #endif /* USE_IPV6 */
  194. if (conf.bot->net.ip) {
  195. if (get_ip(conf.bot->net.ip, &cached_myip4_so, DNS_LOOKUP_A))
  196. error = 1;
  197. } else if (conf.bot->net.host) {
  198. if (get_ip(conf.bot->net.host, &cached_myip4_so, DNS_LOOKUP_A))
  199. error = 2;
  200. } else {
  201. /*
  202. char s[121] = "";
  203. gethostname(s, sizeof(s));
  204. if (get_ip(s, &cached_myip4_so)) {
  205. */
  206. /* error = 3; */
  207. cached_myip4_so.sin.sin_family = AF_INET;
  208. cached_myip4_so.sin.sin_addr.s_addr = INADDR_ANY;
  209. // }
  210. }
  211. if (error) {
  212. putlog(LOG_DEBUG, "*", "Hostname self-lookup error: %d", error);
  213. fatal("Hostname self-lookup failed.", 0);
  214. }
  215. cached_ip = 1;
  216. }
  217. /* Sets/Unsets options for a specific socket.
  218. *
  219. * Returns: 0 - on success
  220. * -1 - socket not found
  221. * -2 - illegal operation
  222. */
  223. int sockoptions(int sock, int operation, int sock_options)
  224. {
  225. int i = -1;
  226. if ((i = findanysnum(sock)) != -1) {
  227. if (operation == EGG_OPTION_SET)
  228. socklist[i].flags |= sock_options;
  229. else if (operation == EGG_OPTION_UNSET)
  230. socklist[i].flags &= ~sock_options;
  231. else
  232. return -2;
  233. return 0;
  234. }
  235. return -1;
  236. }
  237. int
  238. sock_read(bd::Stream& stream)
  239. {
  240. int fd = -1;
  241. bd::String buf, type;
  242. while (stream.tell() < stream.length()) {
  243. buf = stream.getline().chomp();
  244. if (buf == STR("+sock"))
  245. return fd;
  246. type = newsplit(buf);
  247. if (type == STR("sock")) {
  248. int sock = atoi(newsplit(buf).c_str()), options = atoi(newsplit(buf).c_str());
  249. fd = allocsock(sock, options);
  250. }
  251. if (fd >= 0) {
  252. #ifdef USE_IPV6
  253. if (type == STR("af"))
  254. socklist[fd].af = atoi(buf.c_str());
  255. #endif
  256. if (type == STR("host"))
  257. socklist[fd].host = strdup(buf.c_str());
  258. if (type == STR("port"))
  259. socklist[fd].port = atoi(buf.c_str());
  260. }
  261. }
  262. return -1;
  263. }
  264. void
  265. sock_write(bd::Stream &stream, int fd)
  266. {
  267. if (socklist[fd].sock > 0) {
  268. bd::String buf;
  269. stream << bd::String::printf(STR("-sock\n"));
  270. stream << bd::String::printf(STR("sock %d %d\n"), socklist[fd].sock, socklist[fd].flags);
  271. #ifdef USE_IPV6
  272. stream << bd::String::printf(STR("af %u\n"), socklist[fd].af);
  273. #endif
  274. if (socklist[fd].host)
  275. stream << bd::String::printf(STR("host %s\n"), socklist[fd].host);
  276. if (socklist[fd].port)
  277. stream << bd::String::printf(STR("port %d\n"), socklist[fd].port);
  278. stream << bd::String::printf(STR("+sock\n"));
  279. }
  280. }
  281. /* Return a free entry in the socket entry
  282. */
  283. int allocsock(int sock, int options)
  284. {
  285. for (int i = 0; i < MAXSOCKS; i++) {
  286. if (socklist[i].flags & SOCK_UNUSED) {
  287. /* yay! there is table space */
  288. socklist[i].inbuf = NULL;
  289. socklist[i].outbuf = NULL;
  290. socklist[i].flags = options;
  291. socklist[i].sock = sock;
  292. socklist[i].encstatus = 0;
  293. socklist[i].enclink = -1;
  294. socklist[i].gz = 0;
  295. bzero(&(socklist[i].okey), ENC_KEY_LEN + 1);
  296. bzero(&(socklist[i].ikey), ENC_KEY_LEN + 1);
  297. socks_total++;
  298. sdprintf("allocsock(%d) = %d", i, sock);
  299. return i;
  300. }
  301. }
  302. fatal("Socket table is full!", 0);
  303. return -1; /* Never reached */
  304. }
  305. /* Request a normal socket for i/o
  306. */
  307. void setsock(int sock, int options)
  308. {
  309. int i = allocsock(sock, options);
  310. bool parm;
  311. if (((sock != STDOUT) || backgrd) && !(socklist[i].flags & SOCK_NONSOCK)) {
  312. parm = 1;
  313. setsockopt(sock, SOL_SOCKET, SO_KEEPALIVE, (void *) &parm, sizeof(int));
  314. parm = 0;
  315. setsockopt(sock, SOL_SOCKET, SO_LINGER, (void *) &parm, sizeof(int));
  316. }
  317. if (options & SOCK_LISTEN) {
  318. /* Tris says this lets us grab the same port again next time */
  319. parm = 1;
  320. setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, (void *) &parm, sizeof(int));
  321. }
  322. /* Yay async i/o ! */
  323. fcntl(sock, F_SETFL, O_NONBLOCK);
  324. }
  325. #ifdef USE_IPV6
  326. int real_getsock(int options, int af_def, const char *fname, int line)
  327. {
  328. #else
  329. int real_getsock(int options, const char *fname, int line)
  330. {
  331. int af_def = AF_INET;
  332. #endif /* USE_IPV6 */
  333. int sock = -1;
  334. if (!af_def)
  335. af_def = AF_INET;
  336. sock = socket(af_def, SOCK_STREAM, 0);
  337. if (sock >= 0)
  338. setsock(sock, options);
  339. else if (!identd_hack)
  340. putlog(LOG_WARNING, "*", "Warning: Can't create new socket! (%s:%d): %s", fname, line, strerror(errno));
  341. else if (identd_hack)
  342. identd_hack = 0;
  343. return sock;
  344. }
  345. /* Done with a socket
  346. */
  347. void real_killsock(register int sock, const char *file, int line)
  348. {
  349. if (sock < 0) {
  350. putlog(LOG_ERRORS, "*", "Attempt to kill socket -1 %s:%d", file, line);
  351. return;
  352. }
  353. int i = -1;
  354. if ((i = findanysnum(sock)) != -1) {
  355. #ifdef EGG_SSL_EXT
  356. if (socklist[i].ssl) {
  357. SSL_shutdown(socklist[i].ssl);
  358. SSL_free(socklist[i].ssl);
  359. socklist[i].ssl = NULL;
  360. }
  361. #endif
  362. close(socklist[i].sock);
  363. if (socklist[i].inbuf != NULL) {
  364. delete socklist[i].inbuf;
  365. socklist[i].inbuf = NULL;
  366. }
  367. if (socklist[i].outbuf != NULL) {
  368. delete socklist[i].outbuf;
  369. socklist[i].outbuf = NULL;
  370. }
  371. if (socklist[i].host)
  372. free(socklist[i].host);
  373. bzero(&socklist[i], sizeof(socklist[i]));
  374. socklist[i].flags = SOCK_UNUSED;
  375. socks_total--;
  376. sdprintf("killsock(%d, %s, %d) (socklist: %d)", sock, file, line, i);
  377. return;
  378. }
  379. putlog(LOG_MISC, "*", "Attempt to kill un-allocated socket %d %s:%d !!", sock, file, line);
  380. }
  381. /* Send connection request to proxy
  382. */
  383. static int proxy_connect(int sock, const char *ip, in_port_t port, int proxy_type)
  384. {
  385. sdprintf("proxy_connect(%d, %s, %d, %d)", sock, ip, port, proxy_type);
  386. #ifdef USE_IPV6
  387. unsigned char x[32] = "";
  388. int af_ty = sockprotocol(sock);
  389. #else
  390. unsigned char x[10] = "";
  391. #endif /* USE_IPV6 */
  392. char s[256] = "";
  393. /* socks proxy */
  394. if (proxy_type == PROXY_SOCKS) {
  395. /* numeric IP? */
  396. if (is_dotted_ip(ip)) {
  397. in_addr_t ipaddr = ((in_addr_t) inet_addr(ip));
  398. memcpy(x, &ipaddr, 4);
  399. } else { /* if not resolved, resolve it with blocking calls.. (shouldn't happen ever) */
  400. return -1;
  401. }
  402. int i = -1;
  403. if ((i = findanysnum(sock)) != -1)
  404. socklist[i].flags |= SOCK_PROXYWAIT;
  405. #ifdef USE_IPV6
  406. if (af_ty == AF_INET6)
  407. simple_snprintf(s, sizeof s,
  408. "\004\001%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%s",
  409. (port >> 8) % 256, (port % 256), x[0], x[1], x[2], x[3],
  410. x[4], x[5], x[6], x[7], x[9], x[9], x[10], x[11], x[12],
  411. x[13], x[14], x[15], botuser);
  412. else
  413. #endif /* USE_IPV6 */
  414. simple_snprintf(s, sizeof s, "\004\001%c%c%c%c%c%c%s", (port >> 8) % 256,
  415. (port % 256), x[0], x[1], x[2], x[3], botuser);
  416. tputs(sock, s, strlen(botuser) + 9);
  417. } else if (proxy_type == PROXY_SUN) {
  418. size_t len = simple_snprintf(s, sizeof s, "%s %d\n", ip, port);
  419. tputs(sock, s, len);
  420. } else if (proxy_type == PROXY_HTTP) {
  421. size_t len = simple_snprintf(s, sizeof s, "CONNECT %s:%d\n\n", ip, port);
  422. tputs(sock, s, len);
  423. }
  424. return sock;
  425. }
  426. /* FIXME: REPLACE WITH SOCK_NAME() */
  427. void initialize_sockaddr(int af_type, const char *host, in_port_t port, union sockaddr_union *so)
  428. {
  429. bzero(so, sizeof(*so));
  430. so->sa.sa_family = af_type;
  431. if (af_type == AF_INET) {
  432. so->sin.sin_family = AF_INET;
  433. if (host) {
  434. inet_pton(AF_INET, host, &so->sin.sin_addr);
  435. so->sin.sin_port = htons(port);
  436. } else {
  437. so->sin.sin_addr.s_addr = getmyip();
  438. }
  439. #ifdef USE_IPV6
  440. } else {
  441. so->sin6.sin6_family = AF_INET6;
  442. if (host) {
  443. inet_pton(AF_INET6, host, &so->sin6.sin6_addr);
  444. so->sin6.sin6_port = htons(port);
  445. } else {
  446. memcpy(&so->sin6.sin6_addr, &cached_myip6_so.sin6.sin6_addr, 16);
  447. }
  448. #endif /* USE_IPV6 */
  449. }
  450. }
  451. /* Starts a connection attempt to a socket
  452. *
  453. * If given a normal hostname, this will be resolved to the corresponding
  454. * IP address first. PLEASE try to use the non-blocking dns functions
  455. * instead and then call this function with the IP address to avoid blocking.
  456. *
  457. * returns <0 if connection refused:
  458. * -1 strerror()/errno type error
  459. * -2 can't resolve hostname
  460. */
  461. int open_telnet_raw(int sock, const char *ipIn, in_port_t sport, bool proxy_on, int identd)
  462. {
  463. static in_port_t port = 0;
  464. union sockaddr_union so;
  465. char ip[121] = "";
  466. int is_resolved = 0;
  467. volatile int proxy_type = 0, proxy = proxy_on;
  468. /* firewall? use socks */
  469. if (proxy) {
  470. switch (firewall[0]) {
  471. case '!':
  472. proxy_type = PROXY_SUN;
  473. strlcpy(ip, &firewall[1], sizeof(ip));
  474. break;
  475. case '@':
  476. proxy_type = PROXY_HTTP;
  477. strlcpy(ip, &firewall[1], sizeof(ip));
  478. break;
  479. default:
  480. proxy_type = PROXY_SOCKS;
  481. strlcpy(ip, firewall, sizeof(ip));
  482. break;
  483. }
  484. port = firewallport;
  485. } else {
  486. proxy_type = 0;
  487. strlcpy(ip, ipIn, sizeof(ip));
  488. port = sport;
  489. }
  490. socklen_t socklen;
  491. if (sport) {
  492. /* figure out which ip to bind to locally (v4 or v6) based on what the host ip is .. */
  493. if ((is_resolved = is_dotted_ip(ip))) { /* already resolved */
  494. /* bind to our cached ip for v4/v6 depending on what the ip is */
  495. initialize_sockaddr(is_resolved, NULL, 0, &so);
  496. if (bind(sock, &so.sa, SIZEOF_SOCKADDR(so)) < 0) {
  497. putlog(LOG_DEBUG, "*", "Failed to bind to socket %d: %s", sock, strerror(errno));
  498. killsock(sock);
  499. return -1;
  500. }
  501. /* initialize so for connect using the host/port */
  502. initialize_sockaddr(is_resolved, ip, port, &so);
  503. } else { /* if not resolved, resolve it with blocking calls.. (shouldn't happen ever) */
  504. sdprintf("WARNING: open_telnet_raw(%s,%d) was passed an unresolved hostname.", ip, port);
  505. killsock(sock);
  506. return -1;
  507. }
  508. socklen = SIZEOF_SOCKADDR(so);
  509. } else { // Unix domain socket
  510. so.sock_un.sun_family = AF_UNIX;
  511. strcpy(so.sock_un.sun_path, ip);
  512. socklen = SUN_LEN(&so.sock_un);
  513. }
  514. int i = -1;
  515. if ((i = findanysnum(sock)) != -1) {
  516. socklist[i].flags = (socklist[i].flags & ~SOCK_VIRTUAL) | SOCK_CONNECT;
  517. socklist[i].host = strdup(ipIn);
  518. socklist[i].port = port;
  519. }
  520. if (identd && sport) //Only open identd if not a unix domain socket
  521. identd_open(myipstr(is_resolved), ipIn, identd);
  522. int rc = -1;
  523. /* make the connect attempt */
  524. rc = connect(sock, (struct sockaddr *)&so.sa, socklen);
  525. if (rc < 0) {
  526. if (errno == EINPROGRESS) {
  527. debug3("net: connect(%d, %s, %d)", sock, ipIn, sport);
  528. /* Firewall? announce connect attempt to proxy */
  529. if (proxy)
  530. return proxy_connect(sock, ipIn, sport, proxy_type);
  531. return sock; /* async success! */
  532. } else {
  533. sdprintf("connect(%d, %s, %d) failed: %s", sock, ip, sport, strerror(errno));
  534. killsock(sock);
  535. return -1;
  536. }
  537. }
  538. /* Synchronous? :/ */
  539. debug3("net: (BLOCKING) connect(%d, %s, %d)", sock, ipIn, sport);
  540. if (proxy)
  541. return proxy_connect(sock, ipIn, sport, proxy_type);
  542. return sock;
  543. }
  544. #ifdef EGG_SSL_EXT
  545. int net_switch_to_ssl(int sock) {
  546. int i = 0;
  547. debug0("net_switch_to_ssl()");
  548. sleep(3); // Give some time to let the connect() go through.
  549. i = findanysnum(sock);
  550. if (i == MAXSOCKS) {
  551. debug0("Error while swithing to SSL - sock not found in list");
  552. return 0;
  553. }
  554. if (socklist[i].ssl) {
  555. debug0("Error while swithing to SSL - already in ssl");
  556. return 0;
  557. }
  558. socklist[i].ssl = SSL_new(ssl_ctx);
  559. if (!socklist[i].ssl) {
  560. debug0("Error while swithing to SSL - SSL_new() error");
  561. return 0;
  562. }
  563. SSL_set_fd(socklist[i].ssl, socklist[i].sock);
  564. int err = 0, timeout = 0;
  565. while ((err = SSL_connect(socklist[i].ssl)) <= 0) {
  566. if (timeout++ > 500) {
  567. err = 0;
  568. break;
  569. }
  570. int errs = SSL_get_error(socklist[i].ssl,err);
  571. if ((errs != SSL_ERROR_WANT_READ) && (errs != SSL_ERROR_WANT_WRITE) && (errs != SSL_ERROR_WANT_X509_LOOKUP)) {
  572. putlog(LOG_DEBUG, "*", "SSL_connect() = %d, %s", err, (char *)ERR_error_string(ERR_get_error(), NULL));
  573. goto error;
  574. }
  575. usleep(1000);
  576. }
  577. if (err == 1) {
  578. debug0("SSL_connect() success");
  579. return 1;
  580. }
  581. error:
  582. debug0("Error while SSL_connect()");
  583. SSL_shutdown(socklist[i].ssl);
  584. SSL_free(socklist[i].ssl);
  585. socklist[i].ssl = NULL;
  586. return 0;
  587. }
  588. #endif
  589. /* Ordinary non-binary connection attempt */
  590. int open_telnet(const char *ip, in_port_t port, bool proxy, int identd)
  591. {
  592. int sock = -1;
  593. #ifdef USE_IPV6
  594. sock = getsock(0, is_dotted_ip(ip));
  595. #else
  596. sock = getsock(0);
  597. #endif /* USE_IPV6 */
  598. if (sock >= 0)
  599. return open_telnet_raw(sock, ip, port, proxy, identd);
  600. return -1;
  601. }
  602. /* Returns a socket number for a listening socket that will accept any
  603. * connection on a certain address -- port # is returned in port
  604. *
  605. * 'addr' is ignored if af_def is AF_INET6 -poptix (02/03/03)
  606. */
  607. #ifdef USE_IPV6
  608. int open_address_listen(const char* ip, int af_def, in_port_t *port) {
  609. #else
  610. int open_address_listen(const char* ip, in_port_t *port) {
  611. int af_def = AF_INET;
  612. #endif /* USE_IPV6 */
  613. // if (firewall[0]) {
  614. // /* FIXME: can't do listen port thru firewall yet */
  615. // putlog(LOG_MISC, "*", "!! Cant open a listen port (you are using a firewall)");
  616. // return -1;
  617. // }
  618. int sock = 0;
  619. socklen_t addrlen;
  620. union sockaddr_union name;
  621. #ifdef USE_IPV6
  622. if (af_def == AF_INET6) {
  623. struct sockaddr_in6 name6;
  624. sock = getsock(SOCK_LISTEN, af_def);
  625. if (sock < 0)
  626. return -1;
  627. debug2("Opening listen socket on port %d with AF_INET6, sock: %d", *port, sock);
  628. bzero((char *) &name6, sizeof(name6));
  629. name6.sin6_family = af_def;
  630. name6.sin6_port = htons(*port); /* 0 = just assign us a port */
  631. /* memcpy(&name6.sin6_addr, &in6addr_any, 16); */ /* this is the only way to get ipv6+ipv4 in 1 socket */
  632. memcpy(&name6.sin6_addr, &cached_myip6_so.sin6.sin6_addr, 16);
  633. if (bind(sock, (struct sockaddr *) &name6, sizeof(name6)) < 0) {
  634. if (!(identd_hack && *port == 113))
  635. putlog(LOG_DEBUG, "*", "Failed to bind to socket %d for listen on port %d: %s", sock, *port, strerror(errno));
  636. killsock(sock);
  637. return -1;
  638. }
  639. addrlen = sizeof(name6);
  640. if (getsockname(sock, (struct sockaddr *) &name6, &addrlen) < 0) {
  641. if (!(identd_hack && *port == 113))
  642. putlog(LOG_DEBUG, "*", "Failed to getsockname on socket %d for listen on port %d: %s", sock, *port, strerror(errno));
  643. killsock(sock);
  644. return -1;
  645. }
  646. *port = ntohs(name6.sin6_port);
  647. if (listen(sock, 1) < 0) {
  648. if (!(identd_hack && *port == 113))
  649. putlog(LOG_DEBUG, "*", "Failed to listen on socket %d for listen on port %d: %s", sock, *port, strerror(errno));
  650. killsock(sock);
  651. return -1;
  652. }
  653. } else {
  654. sock = getsock(SOCK_LISTEN, af_def);
  655. #else
  656. sock = getsock(SOCK_LISTEN);
  657. #endif /* USE_IPV6 */
  658. if (sock < 0)
  659. return -1;
  660. if (af_def == AF_UNIX)
  661. debug2("Opening listen socket on %s, sock: %d", ip, sock);
  662. else
  663. debug3("Opening listen socket on %s:%d with AF_INET, sock: %d", ip, *port, sock);
  664. bzero((char *) &name, sizeof(struct sockaddr *));
  665. if (af_def == AF_UNIX) {
  666. name.sock_un.sun_family = AF_UNIX;
  667. strcpy(name.sock_un.sun_path, ip);
  668. unlink(name.sock_un.sun_path);
  669. addrlen = SUN_LEN(&name.sock_un);
  670. } else {
  671. name.sin.sin_family = af_def;
  672. name.sin.sin_port = htons(*port); /* 0 = just assign us a port */
  673. name.sin.sin_addr.s_addr = inet_addr(ip);
  674. addrlen = sizeof(struct sockaddr_in);
  675. }
  676. if (bind(sock, (struct sockaddr *) &name, addrlen) < 0) {
  677. if (!(identd_hack && *port == 113)) {
  678. if (af_def == AF_UNIX)
  679. putlog(LOG_DEBUG, "*", "Failed to bind to socket %d for listen on %s: %s", sock, ip, strerror(errno));
  680. else
  681. putlog(LOG_DEBUG, "*", "Failed to bind to socket %d for listen on %s:%d: %s", sock, ip, *port, strerror(errno));
  682. }
  683. killsock(sock);
  684. return -1;
  685. }
  686. if (af_def != AF_UNIX) {
  687. /* what port are we on? */
  688. if (getsockname(sock, (struct sockaddr *) &name, &addrlen) < 0) {
  689. if (!(identd_hack && *port == 113))
  690. putlog(LOG_DEBUG, "*", "Failed to getsockname on socket %d for listen on port %d: %s", sock, *port, strerror(errno));
  691. killsock(sock);
  692. return -1;
  693. }
  694. *port = ntohs(name.sin.sin_port);
  695. }
  696. if (listen(sock, 1) < 0) {
  697. if (!(identd_hack && *port == 113) && af_def != AF_UNIX)
  698. putlog(LOG_DEBUG, "*", "Failed to listen on socket %d for on port %d: %s", sock, *port, strerror(errno));
  699. killsock(sock);
  700. return -1;
  701. }
  702. #ifdef USE_IPV6
  703. }
  704. #endif /* USE_IPV6 */
  705. if (af_def == AF_UNIX)
  706. debug2("Opened listen socket on %s, sock: %d", ip, sock);
  707. else
  708. debug3("Opened listen socket on %s:%d with AF_INET, sock: %d", ip, *port, sock);
  709. return sock;
  710. }
  711. /* Returns a socket number for a listening socket that will accept any
  712. * connection -- port # is returned in port
  713. */
  714. int open_listen(in_port_t *port)
  715. {
  716. #ifdef USE_IPV6
  717. return open_address_listen(iptostr(getmyip()), AF_INET, port);
  718. #else
  719. return open_address_listen(iptostr(getmyip()), port);
  720. #endif /* USE_IPV6 */
  721. }
  722. /* Same as above, except this one can be called with an AF_ type
  723. * the above is being left in for compatibility, and should NOT LONGER BE USED IN THE CORE CODE.
  724. */
  725. int open_listen_by_af(in_port_t *port, int af_def)
  726. {
  727. #ifdef USE_IPV6
  728. return open_address_listen(iptostr(getmyip()), af_def, port);
  729. #else
  730. return -1;
  731. #endif /* USE_IPV6 */
  732. }
  733. int open_listen_addr_by_af(const char *ip, in_port_t *port, int af_def)
  734. {
  735. if (!ip)
  736. ip = iptostr(getmyip());
  737. #ifdef USE_IPV6
  738. return open_address_listen(ip, af_def, port);
  739. #else
  740. return -1;
  741. #endif /* USE_IPV6 */
  742. }
  743. /* Returns the given network byte order IP address in the
  744. * dotted format - "##.##.##.##"
  745. */
  746. char *iptostr(in_addr_t ip)
  747. {
  748. static char ipbuf[32];
  749. struct in_addr a;
  750. a.s_addr = ip;
  751. return (char *) inet_ntop(AF_INET, &a, ipbuf, sizeof(ipbuf));
  752. }
  753. /* Short routine to answer a connect received on a socket made previously
  754. * by open_listen ... returns hostname of the caller & the new socket
  755. * does NOT dispose of old "public" socket!
  756. */
  757. int answer(int sock, char *caller, in_addr_t *ip, in_port_t *port, int binary)
  758. {
  759. int new_sock;
  760. socklen_t addrlen;
  761. struct sockaddr_in from;
  762. int af_ty = sockprotocol(sock);
  763. #ifdef USE_IPV6
  764. struct sockaddr_in6 from6;
  765. bzero(&from6, sizeof(struct sockaddr_in6));
  766. if (af_ty == AF_INET6) {
  767. addrlen = sizeof(from6);
  768. new_sock = accept(sock, (struct sockaddr *) &from6, &addrlen);
  769. } else {
  770. #endif /* USE_IPV6 */
  771. addrlen = sizeof(struct sockaddr);
  772. new_sock = accept(sock, (struct sockaddr *) &from, &addrlen);
  773. #ifdef USE_IPV6
  774. }
  775. #endif /* USE_IPV6 */
  776. if (new_sock < 0)
  777. return -1;
  778. if (ip != NULL) {
  779. #ifdef USE_IPV6
  780. /* Detect IPv4 in IPv6 mapped address .... */
  781. if (af_ty == AF_INET6 && (!IN6_IS_ADDR_V4MAPPED(&from6.sin6_addr))) {
  782. inet_ntop(AF_INET6, &from6.sin6_addr, caller, 119);
  783. caller[120] = 0;
  784. *ip = 0L;
  785. } else if (IN6_IS_ADDR_V4MAPPED(&from6.sin6_addr)) { /* ...and convert it to plain (AF_INET) IPv4 address (openssh) */
  786. struct sockaddr_in *from4 = (struct sockaddr_in *)&from6;
  787. struct in_addr addr;
  788. memcpy(&addr, ((char *)&from6.sin6_addr) + 12, sizeof(addr));
  789. memset(&from, 0, sizeof(from));
  790. from4->sin_family = AF_INET;
  791. addrlen = sizeof(*from4);
  792. memcpy(&from4->sin_addr, &addr, sizeof(addr));
  793. *ip = from4->sin_addr.s_addr;
  794. strlcpy(caller, iptostr(*ip), 121);
  795. *ip = ntohl(*ip);
  796. } else {
  797. #endif /* USE_IPV6 */
  798. if (af_ty == AF_UNIX) {
  799. struct sockaddr_un sock_un;
  800. socklen_t socklen = sizeof(sock_un);
  801. bzero(&sock_un, socklen);
  802. getsockname(sock, (struct sockaddr*) &sock_un, &socklen);
  803. strcpy(caller, sock_un.sun_path);
  804. *port = 0;
  805. } else {
  806. *ip = from.sin_addr.s_addr;
  807. strlcpy(caller, iptostr(*ip), 121);
  808. *ip = ntohl(*ip);
  809. }
  810. #ifdef USE_IPV6
  811. }
  812. #endif /* USE_IPV6 */
  813. }
  814. if (port != NULL) {
  815. #ifdef USE_IPV6
  816. if (af_ty == AF_INET6)
  817. *port = ntohs(from6.sin6_port);
  818. else if (af_ty == AF_INET)
  819. #endif /* USE_IPV6 */
  820. *port = ntohs(from.sin_port);
  821. }
  822. /* Set up all the normal socket crap */
  823. setsock(new_sock, (binary ? SOCK_BINARY : 0));
  824. sdprintf("Answered socket %d: %s", new_sock, caller);
  825. return new_sock;
  826. }
  827. /* Like open_telnet, but uses ip & port specifications of dcc
  828. Take a longip and make into dotted form
  829. */
  830. int open_telnet_dcc(int sock, char *ip, char *port)
  831. {
  832. in_port_t p;
  833. unsigned long addr;
  834. char sv[100] = "";
  835. unsigned char c[4] = "";
  836. #ifdef DEBUG_IPV6
  837. debug1("open_telnet_dcc %s", ip);
  838. #endif /* DEBUG_IPV6 */
  839. if (port != NULL)
  840. p = atoi(port);
  841. else
  842. p = 2000;
  843. #ifdef USE_IPV6
  844. if (sockprotocol(sock) == AF_INET6) {
  845. # ifdef DEBUG_IPV6
  846. debug0("open_telnet_dcc, af_inet6!");
  847. # endif /* DEBUG_IPV6 */
  848. strlcpy(sv, ip, sizeof(sv));
  849. } else {
  850. #endif /* USE_IPV6 */
  851. if (ip != NULL)
  852. addr = my_atoul(ip);
  853. else
  854. addr = 0L;
  855. if (addr < (1 << 24))
  856. return -3; /* fake address */
  857. c[0] = (addr >> 24) & 0xff;
  858. c[1] = (addr >> 16) & 0xff;
  859. c[2] = (addr >> 8) & 0xff;
  860. c[3] = addr & 0xff;
  861. simple_snprintf(sv, sizeof(sv), "%u.%u.%u.%u", c[0], c[1], c[2], c[3]);
  862. #ifdef USE_IPV6
  863. }
  864. /* strcpy(sv,hostnamefromip(addr)); */
  865. # ifdef DEBUG_IPV6
  866. debug3("open_telnet_raw %s %d %d", sv, sock, p);
  867. # endif /* DEBUG_IPV6 */
  868. #endif /* USE_IPV6 */
  869. return open_telnet_raw(sock, sv, p, 0);
  870. }
  871. /* Attempts to read from all the sockets in socklist
  872. * fills s with up to 511 bytes if available, and returns the array index
  873. *
  874. * on EOF: returns -1, with socket in len
  875. * on socket error: returns -2
  876. * if nothing is ready: returns -3
  877. */
  878. static int sockread(char *s, int *len)
  879. {
  880. fd_set fd;
  881. int fds = 0, i, fdtmp, x;
  882. struct timeval t;
  883. int grab = SGRAB + 1;
  884. egg_timeval_t howlong;
  885. if (unlikely(timer_get_shortest(&howlong))) {
  886. /* No timer, default to 1 second. */
  887. t.tv_sec = 1;
  888. t.tv_usec = 0;
  889. }
  890. else {
  891. t.tv_sec = howlong.sec;
  892. t.tv_usec = howlong.usec;
  893. }
  894. FD_ZERO(&fd);
  895. for (i = 0; i < MAXSOCKS; i++) {
  896. if (!(socklist[i].flags & (SOCK_UNUSED | SOCK_VIRTUAL))) {
  897. if (unlikely((socklist[i].sock == STDOUT) && !backgrd))
  898. fdtmp = STDIN;
  899. else
  900. fdtmp = socklist[i].sock;
  901. if (fdtmp > fds)
  902. fds = fdtmp;
  903. FD_SET(fdtmp, &fd);
  904. }
  905. }
  906. fds++;
  907. x = select(fds, &fd, NULL, NULL, &t);
  908. if (x > 0) {
  909. /* Something happened */
  910. for (i = 0; i < MAXSOCKS; i++) {
  911. if ((!(socklist[i].flags & SOCK_UNUSED)) && ((FD_ISSET(socklist[i].sock, &fd)) ||
  912. #ifdef EGG_SSL_EXT
  913. ((socklist[i].ssl) && (SSL_pending(socklist[i].ssl))) ||
  914. #endif
  915. ((socklist[i].sock == STDOUT) && (!backgrd) && (FD_ISSET(STDIN, &fd))))) {
  916. if (socklist[i].flags & (SOCK_LISTEN | SOCK_CONNECT)) {
  917. /* Listening socket -- don't read, just return activity */
  918. /* Same for connection attempt */
  919. /* (for strong connections, require a read to succeed first) */
  920. if (socklist[i].flags & SOCK_PROXYWAIT) { /* drummer */
  921. /* Hang around to get the return code from proxy */
  922. grab = 10;
  923. } else if (!(socklist[i].flags & SOCK_STRONGCONN)) {
  924. debug1("net: connect! sock %d", socklist[i].sock);
  925. s[0] = 0;
  926. *len = 0;
  927. return i;
  928. }
  929. } else if (socklist[i].flags & SOCK_PASS) {
  930. s[0] = 0;
  931. *len = 0;
  932. return i;
  933. }
  934. errno = 0;
  935. if (unlikely((socklist[i].sock == STDOUT) && !backgrd)) {
  936. x = read(STDIN, s, grab);
  937. #ifdef EGG_SSL_EXT
  938. } else if (socklist[i].ssl) {
  939. x = SSL_read(socklist[i].ssl,s,grab);
  940. if (x <= 0) {
  941. int err = SSL_get_error(socklist[i].ssl, x);
  942. x = -1;
  943. switch (err) {
  944. case SSL_ERROR_WANT_READ:
  945. case SSL_ERROR_WANT_WRITE:
  946. case SSL_ERROR_WANT_X509_LOOKUP:
  947. errno = EAGAIN;
  948. break;
  949. case SSL_ERROR_SYSCALL:
  950. switch (ERR_get_error()) {
  951. case 0:
  952. // EOF
  953. break;
  954. case -1:
  955. // I/O error
  956. putlog(LOG_DEBUG, "*", "SSL_read() [IO] = %d, %s", err, (char *)ERR_error_string(ERR_get_error(), NULL));
  957. break;
  958. default:
  959. putlog(LOG_DEBUG, "*", "SSL_read() unknown error: %s", strerror(errno));
  960. break;
  961. }
  962. break;
  963. case SSL_ERROR_SSL:
  964. putlog(LOG_DEBUG, "*", "SSL_read() = %d, %s", err, (char *)ERR_error_string(ERR_get_error(), NULL));
  965. break;
  966. }
  967. }
  968. #endif
  969. } else
  970. x = read(socklist[i].sock, s, grab);
  971. if (x <= 0) { /* eof */
  972. if (errno != EAGAIN) { /* EAGAIN happens when the operation would block
  973. on a non-blocking socket, if the socket is going
  974. to die, it will die later, otherwise it will connect */
  975. *len = socklist[i].sock;
  976. socklist[i].flags &= ~SOCK_CONNECT;
  977. debug1("net: eof!(read) socket %d", socklist[i].sock);
  978. return -1;
  979. } else {
  980. debug3("sockread EAGAIN: %d %d (%s)", socklist[i].sock, errno, strerror(errno));
  981. continue; /* EAGAIN */
  982. }
  983. }
  984. s[x] = 0;
  985. *len = x;
  986. if (socklist[i].flags & SOCK_PROXYWAIT) {
  987. debug2("net: socket: %d proxy errno: %d", socklist[i].sock, s[1]);
  988. socklist[i].flags &= ~(SOCK_CONNECT | SOCK_PROXYWAIT);
  989. switch (s[1]) {
  990. case 90: /* Success */
  991. s[0] = 0;
  992. *len = 0;
  993. return i;
  994. case 91: /* Failed */
  995. errno = ECONNREFUSED;
  996. break;
  997. case 92: /* No identd */
  998. case 93: /* Identd said wrong username */
  999. /* A better error message would be "socks misconfigured"
  1000. * or "identd not working" but this is simplest.
  1001. */
  1002. errno = ENETUNREACH;
  1003. break;
  1004. }
  1005. *len = socklist[i].sock;
  1006. return -1;
  1007. }
  1008. return i;
  1009. }
  1010. }
  1011. } else if (x == -1)
  1012. return -2; /* socket error */
  1013. else {
  1014. s[0] = 0;
  1015. *len = 0;
  1016. }
  1017. return -3;
  1018. }
  1019. /* sockgets: buffer and read from sockets
  1020. *
  1021. * Attempts to read from all registered sockets for up to one second. if
  1022. * after one second, no complete data has been received from any of the
  1023. * sockets, 's' will be empty, 'len' will be 0, and sockgets will return -3.
  1024. * if there is returnable data received from a socket, the data will be
  1025. * in 's' (null-terminated if non-binary), the length will be returned
  1026. * in len, and the socket number will be returned.
  1027. * normal sockets have their input buffered, and each call to sockgets
  1028. * will return one line terminated with a '\n'. binary sockets are not
  1029. * buffered and return whatever coems in as soon as it arrives.
  1030. * listening sockets will return an empty string when a connection comes in.
  1031. * connecting sockets will return an empty string on a successful connect,
  1032. * or EOF on a failed connect.
  1033. * if an EOF is detected from any of the sockets, that socket number will be
  1034. * put in len, and -1 will be returned.
  1035. * the maximum length of the string returned is 512 (including null)
  1036. *
  1037. * Returns -4 if we handled something that shouldn't be handled by the
  1038. * dcc functions. Simply ignore it.
  1039. */
  1040. int sockgets(char *s, int *len)
  1041. {
  1042. char xx[SGRAB + 4] = "", *p = NULL;
  1043. int ret;
  1044. size_t newline_index = size_t(-1);
  1045. bool was_crlf = 0;
  1046. for (int i = 0; i < MAXSOCKS; i++) {
  1047. /* Check for stored-up data waiting to be processed */
  1048. if (!(socklist[i].flags & SOCK_UNUSED) && !(socklist[i].flags & SOCK_BUFFER) && (socklist[i].inbuf != NULL)) {
  1049. if (!(socklist[i].flags & SOCK_BINARY)) {
  1050. /* Find EOL */
  1051. newline_index = socklist[i].inbuf->find('\n');
  1052. if (newline_index != size_t(-1) && newline_index != 0 && socklist[i].inbuf->charAt(newline_index - 1) == '\r') {
  1053. --newline_index;
  1054. was_crlf = 1;
  1055. }
  1056. if (newline_index != size_t(-1)) {
  1057. // Split off a line
  1058. bd::String line(socklist[i].inbuf->substring(0, newline_index));
  1059. strlcpy(s, line.c_str(), SGRAB + 1);
  1060. *(socklist[i].inbuf) += newline_index + 1;
  1061. if (was_crlf)
  1062. *(socklist[i].inbuf) += static_cast<size_t>(1);
  1063. if (s[0] && socklist[i].encstatus)
  1064. link_read(i, s, (size_t *) len);
  1065. *len = strlen(s);
  1066. return socklist[i].sock;
  1067. }
  1068. } else {
  1069. if (!socklist[i].inbuf)
  1070. socklist[i].inbuf = new bd::String();
  1071. /* i dont think any of this is *ever* called */
  1072. /* Handling buffered binary data (must have been SOCK_BUFFER before). */
  1073. if (socklist[i].inbuf->length() <= SGRAB) {
  1074. *len = socklist[i].inbuf->length();
  1075. memcpy(s, socklist[i].inbuf->data(), socklist[i].inbuf->length());
  1076. delete socklist[i].inbuf;
  1077. socklist[i].inbuf = NULL;
  1078. } else {
  1079. /* Split up into chunks of SGRAB bytes. */
  1080. *len = SGRAB;
  1081. memcpy(s, socklist[i].inbuf->data(), *len);
  1082. *(socklist[i].inbuf) += static_cast<size_t>(*len);
  1083. }
  1084. return socklist[i].sock;
  1085. }
  1086. }
  1087. /* Also check any sockets that might have EOF'd during write */
  1088. if (!(socklist[i].flags & SOCK_UNUSED)
  1089. && (socklist[i].flags & SOCK_EOFD)) {
  1090. s[0] = 0;
  1091. *len = socklist[i].sock;
  1092. return -1;
  1093. }
  1094. }
  1095. /* No pent-up data of any worth -- down to business */
  1096. *len = 0;
  1097. ret = sockread(xx, len);
  1098. if (ret < 0) {
  1099. s[0] = 0;
  1100. return ret;
  1101. }
  1102. /* Binary, listening and passed on sockets don't get buffered. */
  1103. if (socklist[ret].flags & SOCK_CONNECT) {
  1104. if (socklist[ret].flags & SOCK_STRONGCONN) {
  1105. socklist[ret].flags &= ~SOCK_STRONGCONN;
  1106. /* Buffer any data that came in, for future read. */
  1107. socklist[ret].inbuf = new bd::String(xx, *len);
  1108. }
  1109. socklist[ret].flags &= ~SOCK_CONNECT;
  1110. s[0] = 0;
  1111. return socklist[ret].sock;
  1112. }
  1113. if (socklist[ret].flags & SOCK_BINARY) {
  1114. memcpy(s, xx, *len);
  1115. return socklist[ret].sock;
  1116. }
  1117. if ((socklist[ret].flags & SOCK_LISTEN) || (socklist[ret].flags & SOCK_PASS))
  1118. return socklist[ret].sock;
  1119. if (socklist[ret].flags & SOCK_BUFFER) {
  1120. if (!socklist[ret].inbuf)
  1121. socklist[ret].inbuf = new bd::String(xx, *len);
  1122. else
  1123. *(socklist[ret].inbuf) += bd::String(xx, *len);
  1124. return -4; /* Ignore this one. */
  1125. }
  1126. /* Might be necessary to prepend stored-up data! */
  1127. if (socklist[ret].inbuf != NULL) {
  1128. *(socklist[ret].inbuf) += bd::String(xx);
  1129. if (socklist[ret].inbuf->length() < (SGRAB + 2)) {
  1130. strlcpy(xx, socklist[ret].inbuf->c_str(), sizeof(xx));
  1131. delete socklist[ret].inbuf;
  1132. socklist[ret].inbuf = NULL;
  1133. } else {
  1134. // Take out an SGRAB sized chunk and advance the buffer
  1135. strlcpy(xx, socklist[ret].inbuf->c_str(), SGRAB + 1);
  1136. *(socklist[ret].inbuf) += static_cast<size_t>(SGRAB);
  1137. /* (leave the rest to be post-pended later) */
  1138. }
  1139. }
  1140. bool data = 0;
  1141. /* Look for EOL marker; if it's there, i have something to show */
  1142. p = strchr(xx, '\n');
  1143. if (p == NULL)
  1144. p = strchr(xx, '\r');
  1145. if (p != NULL) {
  1146. *p = 0;
  1147. strlcpy(s, xx, SGRAB + 10); //buf@main.c
  1148. memmove(xx, p + 1, strlen(p + 1) + 1);
  1149. /* if (s[0] && strlen(s) && (s[strlen(s) - 1] == '\r')) */
  1150. if (strlen(s) && s[strlen(s) - 1] == '\r')
  1151. s[strlen(s) - 1] = 0;
  1152. data = 1; /* DCC_CHAT may now need to process a blank line */
  1153. /* NO! */
  1154. /* if (!s[0]) strcpy(s," "); */
  1155. } else {
  1156. s[0] = 0;
  1157. if (strlen(xx) >= SGRAB) {
  1158. /* String is too long, so just insert fake \n */
  1159. strlcpy(s, xx, SGRAB + 10); //buf@main.c
  1160. xx[0] = 0;
  1161. data = 1;
  1162. }
  1163. }
  1164. if (s[0] && socklist[ret].encstatus)
  1165. link_read(ret, s, (size_t *) len);
  1166. *len = strlen(s);
  1167. /* Anything left that needs to be saved? */
  1168. if (!xx[0]) {
  1169. if (data)
  1170. return socklist[ret].sock;
  1171. else
  1172. return -3;
  1173. }
  1174. /* Prepend old data back */
  1175. if (socklist[ret].inbuf != NULL) {
  1176. socklist[ret].inbuf->insert(0, xx);
  1177. } else {
  1178. socklist[ret].inbuf = new bd::String(xx);
  1179. }
  1180. if (data) {
  1181. return socklist[ret].sock;
  1182. } else {
  1183. return -3;
  1184. }
  1185. }
  1186. /* Dump something to a socket
  1187. *
  1188. * NOTE: Do NOT put Contexts in here if you want DEBUG to be meaningful!!
  1189. */
  1190. void tputs(register int z, const char *s, size_t len)
  1191. {
  1192. if (z < 0) /* um... HELLO?! sanity check please! */
  1193. return;
  1194. if (((z == STDOUT) || (z == STDERR)) && (!backgrd || use_stderr)) {
  1195. if (write(z, s, len) == -1) {
  1196. ;
  1197. }
  1198. return;
  1199. }
  1200. register int x, idx;
  1201. int i = -1;
  1202. if ((i = findanysnum(z)) != -1) {
  1203. if ((idx = findanyidx(z)) != -1 && dcc[idx].type->name) {
  1204. if (!strncmp(dcc[idx].type->name, "BOT", 3))
  1205. traffic.out_today.bn += len;
  1206. else if (!strcmp(dcc[idx].type->name, "SERVER"))
  1207. traffic.out_today.irc += len;
  1208. else if (!strncmp(dcc[idx].type->name, "CHAT", 4))
  1209. traffic.out_today.dcc += len;
  1210. else if (!strncmp(dcc[idx].type->name, "FILES", 5))
  1211. traffic.out_today.filesys += len;
  1212. else if (!strcmp(dcc[idx].type->name, "SEND"))
  1213. traffic.out_today.trans += len;
  1214. else if (!strncmp(dcc[idx].type->name, "GET", 3))
  1215. traffic.out_today.trans += len;
  1216. else
  1217. traffic.out_today.unknown += len;
  1218. }
  1219. if (len && socklist[i].encstatus)
  1220. s = link_write(i, s, &len);
  1221. #ifdef HAVE_ZLIB_H
  1222. /*
  1223. if (socklist[i].gz) {
  1224. FILE *fp;
  1225. fp = gzdopen(z, "wb0");
  1226. x = gzwrite(fp, s, len);
  1227. } else
  1228. */
  1229. #endif /* HAVE_ZLIB_H */
  1230. if (socklist[i].outbuf != NULL) {
  1231. /* Already queueing: just add it */
  1232. *(socklist[i].outbuf) += bd::String(s, len);
  1233. return;
  1234. }
  1235. #ifdef EGG_SSL_EXT
  1236. if (socklist[i].ssl) {
  1237. x = SSL_write(socklist[i].ssl,s,len);
  1238. if (x <= 0) {
  1239. int err = SSL_get_error(socklist[i].ssl, x);
  1240. x = -1;
  1241. switch (err) {
  1242. case SSL_ERROR_WANT_READ:
  1243. case SSL_ERROR_WANT_WRITE:
  1244. case SSL_ERROR_WANT_X509_LOOKUP:
  1245. errno = EAGAIN;
  1246. break;
  1247. case SSL_ERROR_SYSCALL:
  1248. switch (ERR_get_error()) {
  1249. case 0:
  1250. // EOF
  1251. break;
  1252. case -1:
  1253. // I/O error
  1254. putlog(LOG_DEBUG, "*", "SSL_write() [IO] = %d, %s", err, (char *)ERR_error_string(ERR_get_error(), NULL));
  1255. break;
  1256. default:
  1257. putlog(LOG_DEBUG, "*", "SSL_write() unknown error: %s", strerror(errno));
  1258. break;
  1259. }
  1260. break;
  1261. case SSL_ERROR_SSL:
  1262. putlog(LOG_DEBUG, "*", "SSL_write() = %d, %s", err, (char *)ERR_error_string(ERR_get_error(), NULL));
  1263. break;
  1264. }
  1265. }
  1266. } else
  1267. #endif
  1268. /* Try. */
  1269. x = write(z, s, len);
  1270. if (x == -1)
  1271. x = 0;
  1272. if ((size_t) x < len) {
  1273. /* Socket is full, queue it */
  1274. socklist[i].outbuf = new bd::String(&s[x], len - x);
  1275. }
  1276. // if (socklist[i].encstatus && s)
  1277. // free(s);
  1278. return;
  1279. }
  1280. /* Make sure we don't cause a crash by looping here */
  1281. static int inhere = 0;
  1282. if (unlikely(!inhere)) {
  1283. inhere = 1;
  1284. putlog(LOG_MISC, "*", "!!! writing to nonexistent socket: %d", z);
  1285. if (strlen(s)) {
  1286. char *tmp = strdup(s); /* To null-terminate */
  1287. putlog(LOG_MISC, "*", "!-> '%s'", tmp);
  1288. free(tmp);
  1289. }
  1290. inhere = 0;
  1291. }
  1292. /* if (socklist[i].encstatus > 0)
  1293. free(s);
  1294. */
  1295. }
  1296. int findanysnum(register int sock)
  1297. {
  1298. register int i = 0;
  1299. if (sock != -1)
  1300. for (i = 0; i < MAXSOCKS; i++)
  1301. if ((socklist[i].sock == sock) && !(socklist[i].flags & SOCK_UNUSED))
  1302. return i;
  1303. return -1;
  1304. }
  1305. int findanyidx(int sock)
  1306. {
  1307. if (sock != -1)
  1308. for (int idx = 0; idx < dcc_total; ++idx)
  1309. if (dcc[idx].type && dcc[idx].sock == sock)
  1310. return idx;
  1311. return -1;
  1312. }
  1313. /* tputs might queue data for sockets, let's dump as much of it as
  1314. * possible.
  1315. */
  1316. void dequeue_sockets()
  1317. {
  1318. int i, x, z = 0, fds = 0;
  1319. fd_set wfds;
  1320. struct timeval tv;
  1321. /* ^-- start poptix test code, this should avoid writes to sockets not ready to be written to. */
  1322. FD_ZERO(&wfds);
  1323. tv.tv_sec = 0;
  1324. tv.tv_usec = 0; /* we only want to see if it's ready for writing, no need to actually wait.. */
  1325. for (i = 0; i < MAXSOCKS; i++) {
  1326. if (!(socklist[i].flags & SOCK_UNUSED) && socklist[i].outbuf != NULL) {
  1327. FD_SET(socklist[i].sock, &wfds);
  1328. if (socklist[i].sock > fds)
  1329. fds = socklist[i].sock;
  1330. z = 1;
  1331. }
  1332. }
  1333. if (!z)
  1334. return; /* nothing to write */
  1335. fds++;
  1336. select(fds, NULL, &wfds, NULL, &tv);
  1337. /* end poptix */
  1338. for (i = 0; i < MAXSOCKS; i++) {
  1339. if (!(socklist[i].flags & SOCK_UNUSED) &&
  1340. (socklist[i].outbuf != NULL) && (FD_ISSET(socklist[i].sock, &wfds))) {
  1341. /* Trick tputs into doing the work */
  1342. errno = 0;
  1343. #ifdef EGG_SSL_EXT
  1344. if (socklist[i].ssl) {
  1345. x = SSL_write(socklist[i].ssl, socklist[i].outbuf->data(), socklist[i].outbuf->length());
  1346. if (x <= 0) {
  1347. int err = SSL_get_error(socklist[i].ssl, x);
  1348. x = -1;
  1349. switch (err) {
  1350. case SSL_ERROR_WANT_READ:
  1351. case SSL_ERROR_WANT_WRITE:
  1352. case SSL_ERROR_WANT_X509_LOOKUP:
  1353. errno = EAGAIN;
  1354. break;
  1355. case SSL_ERROR_SYSCALL:
  1356. switch (ERR_get_error()) {
  1357. case 0:
  1358. // EOF
  1359. break;
  1360. case -1:
  1361. // I/O error
  1362. putlog(LOG_DEBUG, "*", "SSL_write()/dequeue_sockets() [IO] = %d, %s", err, (char *)ERR_error_string(ERR_get_error(), NULL));
  1363. break;
  1364. default:
  1365. putlog(LOG_DEBUG, "*", "SSL_write() unknown error: %s", strerror(errno));
  1366. break;
  1367. }
  1368. break;
  1369. case SSL_ERROR_SSL:
  1370. putlog(LOG_DEBUG, "*", "SSL_write()/dequeue_sockets() = %d, %s", err, (char *)ERR_error_string(ERR_get_error(), NULL));
  1371. break;
  1372. }
  1373. }
  1374. } else
  1375. #endif
  1376. x = write(socklist[i].sock, socklist[i].outbuf->data(), socklist[i].outbuf->length());
  1377. if ((x < 0) && (errno != EAGAIN)
  1378. #ifdef EBADSLT
  1379. && (errno != EBADSLT)
  1380. #endif /* EBADSLT */
  1381. #ifdef ENOTCONN
  1382. && (errno != ENOTCONN)
  1383. #endif /* EBADSLT */
  1384. ) {
  1385. /* This detects an EOF during writing */
  1386. debug3("net: eof!(write) socket %d (%s,%d)", socklist[i].sock, strerror(errno), errno);
  1387. socklist[i].flags |= SOCK_EOFD;
  1388. } else if ((size_t) x == socklist[i].outbuf->length()) {
  1389. /* If the whole buffer was sent, nuke it */
  1390. delete socklist[i].outbuf;
  1391. socklist[i].outbuf = NULL;
  1392. } else if (x > 0) {
  1393. *(socklist[i].outbuf) += static_cast<size_t>(x);
  1394. } else {
  1395. debug3("dequeue_sockets(): errno = %d (%s) on %d", errno, strerror(errno), socklist[i].sock);
  1396. }
  1397. /* All queued data was sent. Call handler if one exists and the
  1398. * dcc entry wants it.
  1399. */
  1400. if (!socklist[i].outbuf) {
  1401. int idx = findanyidx(socklist[i].sock);
  1402. if (idx >= 0 && dcc[idx].type && dcc[idx].type->outdone)
  1403. dcc[idx].type->outdone(idx);
  1404. }
  1405. }
  1406. }
  1407. }
  1408. /*
  1409. * Debugging stuff
  1410. */
  1411. void tell_netdebug(int idx)
  1412. {
  1413. char s[80] = "";
  1414. dprintf(idx, "Open sockets:");
  1415. for (int i = 0; i < MAXSOCKS; i++) {
  1416. if (!(socklist[i].flags & SOCK_UNUSED)) {
  1417. simple_snprintf(s, sizeof(s), " %d", socklist[i].sock);
  1418. if (socklist[i].flags & SOCK_BINARY)
  1419. strlcat(s, " (binary)", sizeof(s));
  1420. if (socklist[i].flags & SOCK_LISTEN)
  1421. strlcat(s, " (listen)", sizeof(s));
  1422. if (socklist[i].flags & SOCK_PASS)
  1423. strlcat(s, " (passed on)", sizeof(s));
  1424. if (socklist[i].flags & SOCK_CONNECT)
  1425. strlcat(s, " (connecting)", sizeof(s));
  1426. if (socklist[i].flags & SOCK_STRONGCONN)
  1427. strlcat(s, " (strong)", sizeof(s));
  1428. if (socklist[i].flags & SOCK_NONSOCK)
  1429. strlcat(s, " (file)", sizeof(s));
  1430. if (socklist[i].inbuf != NULL)
  1431. simple_sprintf(&s[strlen(s)], " (inbuf: %zu)", socklist[i].inbuf ? socklist[i].inbuf->length() : 0);
  1432. if (socklist[i].outbuf != NULL)
  1433. simple_sprintf(&s[strlen(s)], " (outbuf: %zu)", socklist[i].outbuf ? socklist[i].outbuf->length() : 0);
  1434. if (socklist[i].host)
  1435. simple_sprintf(&s[strlen(s)], " (%s:%d)", socklist[i].host, socklist[i].port);
  1436. strlcat(s, ",", sizeof(s));
  1437. dprintf(idx, "%s", s);
  1438. }
  1439. }
  1440. dprintf(idx, " done.\n");
  1441. }
  1442. /* Checks wether the referenced socket has data queued.
  1443. *
  1444. * Returns true if the incoming/outgoing (depending on 'type') queues
  1445. * contain data, otherwise false.
  1446. */
  1447. bool sock_has_data(int type, int sock)
  1448. {
  1449. bool ret = 0;
  1450. int i = -1;
  1451. if ((i = findanysnum(sock)) != -1) {
  1452. switch (type) {
  1453. case SOCK_DATA_OUTGOING:
  1454. ret = (socklist[i].outbuf != NULL);
  1455. break;
  1456. case SOCK_DATA_INCOMING:
  1457. ret = (socklist[i].inbuf != NULL);
  1458. break;
  1459. }
  1460. } else
  1461. debug1("sock_has_data: could not find socket #%d, returning false.", sock);
  1462. return ret;
  1463. }
  1464. bool socket_run() {
  1465. static int socket_cleanup = 0;
  1466. char buf[SGRAB + 10] = "";
  1467. int i = 0, idx = 0;
  1468. /* Only do this every so often. */
  1469. if (!socket_cleanup) {
  1470. socket_cleanup = 5;
  1471. /* Check for server or dcc activity. */
  1472. dequeue_sockets();
  1473. } else
  1474. --socket_cleanup;
  1475. int xx = sockgets(buf, &i);
  1476. if (xx >= 0) { /* Non-error */
  1477. if ((idx = findanyidx(xx)) != -1) {
  1478. if (likely(dcc[idx].type->activity)) {
  1479. /* Traffic stats */
  1480. if (dcc[idx].type->name) {
  1481. ContextNote(dcc[idx].type->name, buf);
  1482. if (!strncmp(dcc[idx].type->name, "BOT", 3))
  1483. traffic.in_today.bn += i + 1;
  1484. else if (!strcmp(dcc[idx].type->name, "SERVER"))
  1485. traffic.in_today.irc += i + 1;
  1486. else if (!strncmp(dcc[idx].type->name, "CHAT", 4))
  1487. traffic.in_today.dcc += i + 1;
  1488. else if (!strncmp(dcc[idx].type->name, "FILES", 5))
  1489. traffic.in_today.dcc += i + 1;
  1490. else if (!strcmp(dcc[idx].type->name, "SEND"))
  1491. traffic.in_today.trans += i + 1;
  1492. else if (!strncmp(dcc[idx].type->name, "GET", 3))
  1493. traffic.in_today.trans += i + 1;
  1494. else
  1495. traffic.in_today.unknown += i + 1;
  1496. }
  1497. dcc[idx].type->activity(idx, buf, (size_t) i);
  1498. } else
  1499. putlog(LOG_MISC, "*",
  1500. STR("!!! untrapped dcc activity: type %s, sock %d"),
  1501. dcc[idx].type->name, dcc[idx].sock);
  1502. }
  1503. } else if (unlikely(xx == -1)) { /* EOF from someone */
  1504. if (unlikely(i == STDOUT && !backgrd))
  1505. fatal(STR("END OF FILE ON TERMINAL"), 0);
  1506. if ((idx = findanyidx(i)) != -1) {
  1507. sdprintf(STR("EOF on '%s' idx: %d"), dcc[idx].type ? dcc[idx].type->name : "unknown", idx);
  1508. if (likely(dcc[idx].type->eof))
  1509. dcc[idx].type->eof(idx);
  1510. else {
  1511. putlog(LOG_MISC, "*",
  1512. STR("*** ATTENTION: DEAD SOCKET (%d) OF TYPE %s UNTRAPPED"),
  1513. i, dcc[idx].type ? dcc[idx].type->name : "*UNKNOWN*");
  1514. killsock(i);
  1515. lostdcc(idx);
  1516. }
  1517. } else if (unlikely(idx == -1)) {
  1518. putlog(LOG_MISC, "*", STR("(@) EOF socket %d, not a dcc socket, not anything."), i);
  1519. close(i);
  1520. killsock(i);
  1521. }
  1522. } else if (unlikely(xx == -2 && errno != EINTR)) { /* select() error */
  1523. putlog(LOG_MISC, "*", STR("* Socket error #%d; recovering."), errno);
  1524. for (i = 0; i < dcc_total; i++) {
  1525. if (dcc[i].type && dcc[i].sock != -1 && (fcntl(dcc[i].sock, F_GETFD, 0) == -1) && (errno = EBADF)) {
  1526. putlog(LOG_MISC, "*",
  1527. STR("DCC socket %d (type %s, name '%s') expired -- pfft"),
  1528. dcc[i].sock, dcc[i].type->name, dcc[i].nick);
  1529. killsock(dcc[i].sock);
  1530. lostdcc(i);
  1531. i--;
  1532. }
  1533. }
  1534. } else if (xx == -3) { /* Idle */
  1535. socket_cleanup = 0; /* If we've been idle, cleanup & flush */
  1536. return 1;
  1537. }
  1538. return 0;
  1539. }