llnet.cpp 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604
  1. /**
  2. * @file llnet.cpp
  3. * @brief OS-specific implementation of cross-platform utility functions.
  4. *
  5. * $LicenseInfo:firstyear=2000&license=viewergpl$
  6. *
  7. * Copyright (c) 2000-2009, Linden Research, Inc.
  8. *
  9. * Second Life Viewer Source Code
  10. * The source code in this file ("Source Code") is provided by Linden Lab
  11. * to you under the terms of the GNU General Public License, version 2.0
  12. * ("GPL"), unless you have obtained a separate licensing agreement
  13. * ("Other License"), formally executed by you and Linden Lab. Terms of
  14. * the GPL can be found in doc/GPL-license.txt in this distribution, or
  15. * online at http://secondlifegrid.net/programs/open_source/licensing/gplv2
  16. *
  17. * There are special exceptions to the terms and conditions of the GPL as
  18. * it is applied to this Source Code. View the full text of the exception
  19. * in the file doc/FLOSS-exception.txt in this software distribution, or
  20. * online at
  21. * http://secondlifegrid.net/programs/open_source/licensing/flossexception
  22. *
  23. * By copying, modifying or distributing this software, you acknowledge
  24. * that you have read and understood your obligations described above,
  25. * and agree to abide by those obligations.
  26. *
  27. * ALL LINDEN LAB SOURCE CODE IS PROVIDED "AS IS." LINDEN LAB MAKES NO
  28. * WARRANTIES, EXPRESS, IMPLIED OR OTHERWISE, REGARDING ITS ACCURACY,
  29. * COMPLETENESS OR PERFORMANCE.
  30. * $/LicenseInfo$
  31. */
  32. #include "linden_common.h"
  33. #include <stdexcept>
  34. #if !LL_WINDOWS
  35. # include <sys/types.h>
  36. # include <sys/socket.h>
  37. # include <netinet/in.h>
  38. # include <arpa/inet.h>
  39. # include <fcntl.h>
  40. # include <unistd.h>
  41. # include <errno.h>
  42. #endif
  43. #include "llnet.h"
  44. #include "indra_constants.h"
  45. // Globals
  46. #if LL_WINDOWS
  47. SOCKADDR_IN stDstAddr;
  48. SOCKADDR_IN stSrcAddr;
  49. SOCKADDR_IN stLclAddr;
  50. static WSADATA stWSAData;
  51. #else
  52. struct sockaddr_in stDstAddr;
  53. struct sockaddr_in stSrcAddr;
  54. struct sockaddr_in stLclAddr;
  55. # if LL_DARWIN && !defined(_SOCKLEN_T)
  56. # define _SOCKLEN_T
  57. typedef int socklen_t;
  58. # endif
  59. #endif
  60. // Address to which datagram was sent:
  61. static U32 gsnReceivingIFAddr = INVALID_HOST_IP_ADDRESS;
  62. #if LL_DARWIN
  63. // Mac OS X returns an error when trying to set these to 400000. Smaller values
  64. // succeed.
  65. const int SEND_BUFFER_SIZE = 200000;
  66. const int RECEIVE_BUFFER_SIZE = 200000;
  67. #else // LL_DARWIN
  68. const int SEND_BUFFER_SIZE = 400000;
  69. const int RECEIVE_BUFFER_SIZE = 400000;
  70. #endif // LL_DARWIN
  71. // Universal functions (cross-platform)
  72. LLHost get_sender()
  73. {
  74. return LLHost(stSrcAddr.sin_addr.s_addr, ntohs(stSrcAddr.sin_port));
  75. }
  76. U32 get_sender_ip()
  77. {
  78. return stSrcAddr.sin_addr.s_addr;
  79. }
  80. U32 get_sender_port()
  81. {
  82. return ntohs(stSrcAddr.sin_port);
  83. }
  84. LLHost get_receiving_interface()
  85. {
  86. return LLHost(gsnReceivingIFAddr, INVALID_PORT);
  87. }
  88. U32 get_receiving_interface_ip()
  89. {
  90. return gsnReceivingIFAddr;
  91. }
  92. #if LL_WINDOWS
  93. ///////////////////////////////////////////////////////////////////////////////
  94. // Windows Versions
  95. ///////////////////////////////////////////////////////////////////////////////
  96. S32 start_net(S32& socket_out, int& port_num)
  97. {
  98. // Create socket, make non-blocking
  99. // Init WinSock
  100. int nret;
  101. // Initialize windows specific stuff
  102. if (WSAStartup(0x0202, &stWSAData))
  103. {
  104. S32 err = WSAGetLastError();
  105. llwarns << "Windows sockets initialization failed, with error "
  106. << err << llendl;
  107. WSACleanup();
  108. return 1;
  109. }
  110. // Get a datagram socket
  111. int sock_num = (int)socket(AF_INET, SOCK_DGRAM, 0);
  112. if (sock_num == INVALID_SOCKET)
  113. {
  114. S32 err = WSAGetLastError();
  115. llwarns << "socket() failedwith error " << err << llendl;
  116. WSACleanup();
  117. return 2;
  118. }
  119. // Name the socket (assign the local port number to receive on)
  120. stLclAddr.sin_family = AF_INET;
  121. stLclAddr.sin_addr.s_addr = htonl(INADDR_ANY);
  122. stLclAddr.sin_port = htons(port_num);
  123. S32 attempt_port = port_num;
  124. LL_DEBUGS("AppInit") << "Attempting to connect on port " << attempt_port
  125. << LL_ENDL;
  126. nret = bind(sock_num, (struct sockaddr*) &stLclAddr, sizeof(stLclAddr));
  127. if (nret == SOCKET_ERROR)
  128. {
  129. // If we got an address in use error...
  130. if (WSAGetLastError() == WSAEADDRINUSE)
  131. {
  132. // Try all ports from PORT_DISCOVERY_RANGE_MIN to
  133. // PORT_DISCOVERY_RANGE_MAX
  134. for (attempt_port = PORT_DISCOVERY_RANGE_MIN;
  135. attempt_port <= PORT_DISCOVERY_RANGE_MAX; ++attempt_port)
  136. {
  137. stLclAddr.sin_port = htons(attempt_port);
  138. LL_DEBUGS("AppInit") << "Trying port " << attempt_port
  139. << LL_ENDL;
  140. nret = bind(sock_num, (struct sockaddr*) &stLclAddr,
  141. sizeof(stLclAddr));
  142. if (!(nret == SOCKET_ERROR &&
  143. WSAGetLastError() == WSAEADDRINUSE))
  144. {
  145. break;
  146. }
  147. }
  148. if (nret == SOCKET_ERROR)
  149. {
  150. llwarns << "Network port " << port_num << " not available."
  151. << llendl;
  152. WSACleanup();
  153. return 3;
  154. }
  155. }
  156. else // Some other socket error
  157. {
  158. S32 err = WSAGetLastError();
  159. llwarns << "bind() to port " << port_num << " failed with error: "
  160. << err << llendl;
  161. WSACleanup();
  162. return 4;
  163. }
  164. }
  165. sockaddr_in socket_address;
  166. S32 socket_address_size = sizeof(socket_address);
  167. getsockname(sock_num, (SOCKADDR*)&socket_address, &socket_address_size);
  168. attempt_port = ntohs(socket_address.sin_port);
  169. llinfos << "Connected on port " << attempt_port << llendl;
  170. port_num = attempt_port;
  171. // Set socket to be non-blocking
  172. unsigned long argp = 1;
  173. nret = ioctlsocket(sock_num, FIONBIO, &argp);
  174. if (nret == SOCKET_ERROR)
  175. {
  176. S32 err = WSAGetLastError();
  177. llwarns << "Failed to set socket non-blocking with error: " << err
  178. << llendl;
  179. }
  180. // Set a large receive buffer
  181. int rec_size = RECEIVE_BUFFER_SIZE;
  182. int buff_size = 4;
  183. nret = setsockopt(sock_num, SOL_SOCKET, SO_RCVBUF, (char*)&rec_size,
  184. buff_size);
  185. if (nret)
  186. {
  187. llinfos << "Cannot set receive buffer size !" << llendl;
  188. }
  189. int snd_size = SEND_BUFFER_SIZE;
  190. nret = setsockopt(sock_num, SOL_SOCKET, SO_SNDBUF, (char*)&snd_size,
  191. buff_size);
  192. if (nret)
  193. {
  194. llinfos << "Cannot set send buffer size !" << llendl;
  195. }
  196. getsockopt(sock_num, SOL_SOCKET, SO_RCVBUF, (char*)&rec_size, &buff_size);
  197. getsockopt(sock_num, SOL_SOCKET, SO_SNDBUF, (char*)&snd_size, &buff_size);
  198. llinfos << "Receive buffer size: " << rec_size << " - Send buffer size: "
  199. << snd_size << llendl;
  200. // Setup a destination address
  201. stDstAddr.sin_family = AF_INET;
  202. stDstAddr.sin_addr.s_addr = INVALID_HOST_IP_ADDRESS;
  203. stDstAddr.sin_port = htons(port_num);
  204. socket_out = sock_num;
  205. return 0;
  206. }
  207. void end_net(S32& socket_out)
  208. {
  209. if (socket_out >= 0)
  210. {
  211. shutdown(socket_out, SD_BOTH);
  212. closesocket(socket_out);
  213. }
  214. WSACleanup();
  215. }
  216. // Receives data asynchronously from the socket set by initNet(). Returns the
  217. // number of bytes received into dataReceived, or zero if there is no data
  218. // received.
  219. S32 receive_packet(int sock_num, char* recv_buffer)
  220. {
  221. int nret;
  222. int addr_size = sizeof(struct sockaddr_in);
  223. nret = recvfrom(sock_num, recv_buffer, NET_BUFFER_SIZE, 0,
  224. (struct sockaddr*)&stSrcAddr, &addr_size);
  225. if (nret == SOCKET_ERROR)
  226. {
  227. if (WSAEWOULDBLOCK == WSAGetLastError() ||
  228. WSAECONNRESET == WSAGetLastError())
  229. {
  230. return 0;
  231. }
  232. llinfos << "Failed with error: " << WSAGetLastError() << llendl;
  233. }
  234. return nret;
  235. }
  236. // Sends a packet to the address set in initNet. Returns true on success.
  237. bool send_packet(int sock_num, const char* send_buffer, int size,
  238. U32 recipient, int port_num)
  239. {
  240. int nret = 0;
  241. U32 last_error = 0;
  242. stDstAddr.sin_addr.s_addr = recipient;
  243. stDstAddr.sin_port = htons(port_num);
  244. do
  245. {
  246. nret = sendto(sock_num, send_buffer, size, 0,
  247. (struct sockaddr*)&stDstAddr, sizeof(stDstAddr));
  248. if (nret == SOCKET_ERROR)
  249. {
  250. last_error = WSAGetLastError();
  251. if (last_error != WSAEWOULDBLOCK)
  252. {
  253. // WSAECONNRESET - I think this is caused by an ICMP
  254. // "connection refused" message being sent back from a Linux
  255. // box... I'm not finding helpful documentation or web pages on
  256. // this. The question is whether the packet actually got sent
  257. // or not. Based on the structure of this code, I would assume
  258. // it is. JNC 2002.01.18
  259. if (WSAECONNRESET == WSAGetLastError())
  260. {
  261. return true;
  262. }
  263. llinfos << "sendto() failed to " << u32_to_ip_string(recipient)
  264. << ":" << port_num << " - Error: " << last_error
  265. << llendl;
  266. }
  267. }
  268. }
  269. while (nret == SOCKET_ERROR && last_error == WSAEWOULDBLOCK);
  270. return nret != SOCKET_ERROR;
  271. }
  272. #else
  273. ///////////////////////////////////////////////////////////////////////////////
  274. // Linux Versions
  275. ///////////////////////////////////////////////////////////////////////////////
  276. // Create socket, make non-blocking
  277. S32 start_net(S32& socket_out, int& port_num)
  278. {
  279. int nret;
  280. // Create socket
  281. int sock_num = socket(AF_INET, SOCK_DGRAM, 0);
  282. if (sock_num < 0)
  283. {
  284. llwarns << "socket() failed" << llendl;
  285. return 1;
  286. }
  287. if (port_num == NET_USE_OS_ASSIGNED_PORT)
  288. {
  289. // Although bind is not required it will tell us which port we were
  290. // assigned to.
  291. stLclAddr.sin_family = AF_INET;
  292. stLclAddr.sin_addr.s_addr = htonl(INADDR_ANY);
  293. stLclAddr.sin_port = htons(0);
  294. llinfos << "attempting to connect on OS assigned port" << llendl;
  295. nret = bind(sock_num, (struct sockaddr*) &stLclAddr,
  296. sizeof(stLclAddr));
  297. if (nret < 0)
  298. {
  299. llwarns << "Failed to bind on an OS assigned port error: "
  300. << nret << llendl;
  301. }
  302. else
  303. {
  304. sockaddr_in socket_info;
  305. socklen_t len = sizeof(sockaddr_in);
  306. int err = getsockname(sock_num, (sockaddr*)&socket_info, &len);
  307. llinfos << "Get socket returned: " << err << " length " << len
  308. << llendl;
  309. port_num = ntohs(socket_info.sin_port);
  310. llinfos << "Assigned port: " << port_num << llendl;
  311. }
  312. }
  313. else
  314. {
  315. // Name the socket (assign the local port number to receive on)
  316. stLclAddr.sin_family = AF_INET;
  317. stLclAddr.sin_addr.s_addr = htonl(INADDR_ANY);
  318. stLclAddr.sin_port = htons(port_num);
  319. U32 attempt_port = port_num;
  320. llinfos << "Attempting to connect on port " << attempt_port << llendl;
  321. nret = bind(sock_num, (struct sockaddr*)&stLclAddr, sizeof(stLclAddr));
  322. if (nret < 0)
  323. {
  324. // If we got an address in use error...
  325. if (errno == EADDRINUSE)
  326. {
  327. // Try all ports from PORT_DISCOVERY_RANGE_MIN to
  328. // PORT_DISCOVERY_RANGE_MAX
  329. for (attempt_port = PORT_DISCOVERY_RANGE_MIN;
  330. attempt_port <= PORT_DISCOVERY_RANGE_MAX;
  331. attempt_port++)
  332. {
  333. stLclAddr.sin_port = htons(attempt_port);
  334. llinfos << "trying port " << attempt_port << llendl;
  335. nret = bind(sock_num, (struct sockaddr*)&stLclAddr,
  336. sizeof(stLclAddr));
  337. if (!((nret < 0) && (errno == EADDRINUSE)))
  338. {
  339. break;
  340. }
  341. }
  342. if (nret < 0)
  343. {
  344. llwarns << "Network port " << port_num << " not available."
  345. << llendl;
  346. close(sock_num);
  347. return 3;
  348. }
  349. }
  350. // Some other socket error
  351. else
  352. {
  353. llwarns << "bind() to port " << port_num
  354. << " failed with error: " << strerror(errno) << llendl;
  355. close(sock_num);
  356. return 4;
  357. }
  358. }
  359. llinfos << "Connected on port " << attempt_port << llendl;
  360. port_num = attempt_port;
  361. }
  362. // Set socket to be non-blocking
  363. fcntl(sock_num, F_SETFL, O_NONBLOCK);
  364. // Set a large receive buffer
  365. int rec_size = RECEIVE_BUFFER_SIZE;
  366. socklen_t buff_size = 4;
  367. nret = setsockopt(sock_num, SOL_SOCKET, SO_RCVBUF, (char*)&rec_size,
  368. buff_size);
  369. if (nret)
  370. {
  371. llinfos << "Cannot set receive size !" << llendl;
  372. }
  373. int snd_size = SEND_BUFFER_SIZE;
  374. nret = setsockopt(sock_num, SOL_SOCKET, SO_SNDBUF, (char*)&snd_size,
  375. buff_size);
  376. if (nret)
  377. {
  378. llinfos << "Cannot set send size !" << llendl;
  379. }
  380. getsockopt(sock_num, SOL_SOCKET, SO_RCVBUF, (char*)&rec_size, &buff_size);
  381. getsockopt(sock_num, SOL_SOCKET, SO_SNDBUF, (char*)&snd_size, &buff_size);
  382. llinfos << "Receive buffer size: " << rec_size << " - Send buffer size: "
  383. << snd_size << llendl;
  384. #if LL_LINUX
  385. // Turn on recipient address tracking
  386. {
  387. int use_pktinfo = 1;
  388. if (setsockopt(sock_num, SOL_IP, IP_PKTINFO, &use_pktinfo,
  389. sizeof(use_pktinfo)) == -1)
  390. {
  391. llwarns << "No IP_PKTINFO available" << llendl;
  392. }
  393. else
  394. {
  395. llinfos << "IP_PKKTINFO enabled" << llendl;
  396. }
  397. }
  398. #endif
  399. // Setup a destination address
  400. char achMCAddr[MAXADDRSTR] = "127.0.0.1";
  401. stDstAddr.sin_family = AF_INET;
  402. stDstAddr.sin_addr.s_addr = ip_string_to_u32(achMCAddr);
  403. stDstAddr.sin_port = htons(port_num);
  404. socket_out = sock_num;
  405. return 0;
  406. }
  407. void end_net(S32& socket_out)
  408. {
  409. if (socket_out >= 0)
  410. {
  411. close(socket_out);
  412. }
  413. }
  414. #if LL_LINUX
  415. static int recvfrom_destip(int sock_num, void* buf, int len,
  416. struct sockaddr* from, socklen_t* fromlen,
  417. U32* dstip)
  418. {
  419. int size;
  420. struct iovec iov[1];
  421. char cmsg[CMSG_SPACE(sizeof(struct in_pktinfo))];
  422. struct cmsghdr* cmsgptr;
  423. struct msghdr msg = { 0 };
  424. iov[0].iov_base = buf;
  425. iov[0].iov_len = len;
  426. memset(&msg, 0, sizeof msg);
  427. msg.msg_name = from;
  428. msg.msg_namelen = *fromlen;
  429. msg.msg_iov = iov;
  430. msg.msg_iovlen = 1;
  431. msg.msg_control = &cmsg;
  432. msg.msg_controllen = sizeof(cmsg);
  433. size = recvmsg(sock_num, &msg, 0);
  434. if (size == -1)
  435. {
  436. return -1;
  437. }
  438. for (cmsgptr = CMSG_FIRSTHDR(&msg); cmsgptr != NULL;
  439. cmsgptr = CMSG_NXTHDR(&msg, cmsgptr))
  440. {
  441. if (cmsgptr->cmsg_level == SOL_IP && cmsgptr->cmsg_type == IP_PKTINFO)
  442. {
  443. in_pktinfo* pktinfo = (in_pktinfo*)CMSG_DATA(cmsgptr);
  444. if (pktinfo)
  445. {
  446. // Two choices. routed and specified. ipi_addr is routed,
  447. // ipi_spec_dst is routed. We should stay with specified until
  448. // we go to multiple interfaces
  449. *dstip = pktinfo->ipi_spec_dst.s_addr;
  450. }
  451. }
  452. }
  453. return size;
  454. }
  455. #endif
  456. // Receives data asynchronously from the socket set by initNet(). Returns the
  457. // number of bytes received into dataReceived, or zero if there is no data
  458. // received.
  459. int receive_packet(int sock_num, char* recv_buffer)
  460. {
  461. int nret;
  462. socklen_t addr_size = sizeof(struct sockaddr_in);
  463. gsnReceivingIFAddr = INVALID_HOST_IP_ADDRESS;
  464. #if LL_LINUX
  465. nret = recvfrom_destip(sock_num, recv_buffer, NET_BUFFER_SIZE,
  466. (struct sockaddr*)&stSrcAddr, &addr_size,
  467. &gsnReceivingIFAddr);
  468. #else
  469. int recv_flags = 0;
  470. nret = recvfrom(sock_num, recv_buffer, NET_BUFFER_SIZE, recv_flags,
  471. (struct sockaddr*)&stSrcAddr, &addr_size);
  472. #endif
  473. if (nret == -1)
  474. {
  475. // To maintain consistency with the Windows implementation, return a
  476. // zero for size on error.
  477. return 0;
  478. }
  479. return nret;
  480. }
  481. bool send_packet(int sock_num, const char* send_buffer, int size,
  482. U32 recipient, int port_num)
  483. {
  484. stDstAddr.sin_addr.s_addr = recipient;
  485. stDstAddr.sin_port = htons(port_num);
  486. bool success = false;
  487. S32 send_attempts = 0;
  488. while (true)
  489. {
  490. if (++send_attempts > 3)
  491. {
  492. llinfos << "Bailing out of send after 3 failed attempts" << llendl;
  493. break;
  494. }
  495. success = sendto(sock_num, send_buffer, size, 0,
  496. (struct sockaddr*)&stDstAddr, sizeof(stDstAddr)) >= 0;
  497. if (success)
  498. {
  499. break;
  500. }
  501. // send failed, check to see if we should resend
  502. if (errno == EAGAIN)
  503. {
  504. // Say nothing, just repeat send
  505. llinfos << "sendto() reported buffer full, resending (attempt "
  506. << send_attempts << ") to "
  507. << inet_ntoa(stDstAddr.sin_addr) << ":" << port_num
  508. << llendl;
  509. }
  510. else if (errno == ECONNREFUSED)
  511. {
  512. // Response to ICMP connection refused message on earlier send
  513. llinfos << "sendto() reported connection refused, resending (attempt "
  514. << send_attempts << ") to "
  515. << inet_ntoa(stDstAddr.sin_addr) << ":" << port_num
  516. << llendl;
  517. }
  518. else
  519. {
  520. // Some other error, abort !
  521. llinfos << "sendto() failed: " << errno << ", "
  522. << strerror(errno) << ". Aborted sending to "
  523. << inet_ntoa(stDstAddr.sin_addr) << ":" << port_num
  524. << llendl;
  525. break;
  526. }
  527. }
  528. return success;
  529. }
  530. #endif