net.c 43 KB

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