sockutils.c 49 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489
  1. /*
  2. * Copyright (c) 2002 - 2003
  3. * NetGroup, Politecnico di Torino (Italy)
  4. * All rights reserved.
  5. *
  6. * Redistribution and use in source and binary forms, with or without
  7. * modification, are permitted provided that the following conditions
  8. * are met:
  9. *
  10. * 1. Redistributions of source code must retain the above copyright
  11. * notice, this list of conditions and the following disclaimer.
  12. * 2. Redistributions in binary form must reproduce the above copyright
  13. * notice, this list of conditions and the following disclaimer in the
  14. * documentation and/or other materials provided with the distribution.
  15. * 3. Neither the name of the Politecnico di Torino nor the names of its
  16. * contributors may be used to endorse or promote products derived from
  17. * this software without specific prior written permission.
  18. *
  19. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  20. * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  21. * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  22. * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  23. * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  24. * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  25. * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  26. * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  27. * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  28. * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  29. * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  30. *
  31. */
  32. #ifdef HAVE_CONFIG_H
  33. #include <config.h>
  34. #endif
  35. /*
  36. * \file sockutils.c
  37. *
  38. * The goal of this file is to provide a common set of primitives for socket
  39. * manipulation.
  40. *
  41. * Although the socket interface defined in the RFC 2553 (and its updates)
  42. * is excellent, there are still differences between the behavior of those
  43. * routines on UN*X and Windows, and between UN*Xes.
  44. *
  45. * These calls provide an interface similar to the socket interface, but
  46. * that hides the differences between operating systems. It does not
  47. * attempt to significantly improve on the socket interface in other
  48. * ways.
  49. */
  50. #include "ftmacros.h"
  51. #include <string.h>
  52. #include <errno.h> /* for the errno variable */
  53. #include <stdio.h> /* for the stderr file */
  54. #include <stdlib.h> /* for malloc() and free() */
  55. #ifdef HAVE_LIMITS_H
  56. #include <limits.h>
  57. #else
  58. #define INT_MAX 2147483647
  59. #endif
  60. #include "pcap-int.h"
  61. #include "sockutils.h"
  62. #include "portability.h"
  63. #ifdef _WIN32
  64. /*
  65. * Winsock initialization.
  66. *
  67. * Ask for WinSock 2.2.
  68. */
  69. #define WINSOCK_MAJOR_VERSION 2
  70. #define WINSOCK_MINOR_VERSION 2
  71. static int sockcount = 0; /*!< Variable that allows calling the WSAStartup() only one time */
  72. #endif
  73. /* Some minor differences between UNIX and Win32 */
  74. #ifdef _WIN32
  75. #define SHUT_WR SD_SEND /* The control code for shutdown() is different in Win32 */
  76. #endif
  77. /* Size of the buffer that has to keep error messages */
  78. #define SOCK_ERRBUF_SIZE 1024
  79. /* Constants; used in order to keep strings here */
  80. #define SOCKET_NO_NAME_AVAILABLE "No name available"
  81. #define SOCKET_NO_PORT_AVAILABLE "No port available"
  82. #define SOCKET_NAME_NULL_DAD "Null address (possibly DAD Phase)"
  83. /*
  84. * On UN*X, send() and recv() return ssize_t.
  85. *
  86. * On Windows, send() and recv() return an int.
  87. *
  88. * Wth MSVC, there *is* no ssize_t.
  89. *
  90. * With MinGW, there is an ssize_t type; it is either an int (32 bit)
  91. * or a long long (64 bit).
  92. *
  93. * So, on Windows, if we don't have ssize_t defined, define it as an
  94. * int, so we can use it, on all platforms, as the type of variables
  95. * that hold the return values from send() and recv().
  96. */
  97. #if defined(_WIN32) && !defined(_SSIZE_T_DEFINED)
  98. typedef int ssize_t;
  99. #endif
  100. /****************************************************
  101. * *
  102. * Locally defined functions *
  103. * *
  104. ****************************************************/
  105. static int sock_ismcastaddr(const struct sockaddr *saddr);
  106. /****************************************************
  107. * *
  108. * Function bodies *
  109. * *
  110. ****************************************************/
  111. /*
  112. * Format an error message given an errno value (UN*X) or a WinSock error
  113. * (Windows).
  114. */
  115. void sock_fmterror(const char *caller, int errcode, char *errbuf, int errbuflen)
  116. {
  117. #ifdef _WIN32
  118. int retval;
  119. char message[SOCK_ERRBUF_SIZE]; /* We're forcing "ANSI" */
  120. if (errbuf == NULL)
  121. return;
  122. retval = FormatMessageA(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS |
  123. FORMAT_MESSAGE_MAX_WIDTH_MASK,
  124. NULL, errcode, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
  125. message, sizeof(message) / sizeof(TCHAR), NULL);
  126. if (retval == 0)
  127. {
  128. if ((caller) && (*caller))
  129. pcap_snprintf(errbuf, errbuflen, "%sUnable to get the exact error message", caller);
  130. else
  131. pcap_snprintf(errbuf, errbuflen, "Unable to get the exact error message");
  132. }
  133. else
  134. {
  135. if ((caller) && (*caller))
  136. pcap_snprintf(errbuf, errbuflen, "%s%s (code %d)", caller, message, errcode);
  137. else
  138. pcap_snprintf(errbuf, errbuflen, "%s (code %d)", message, errcode);
  139. }
  140. #else
  141. char *message;
  142. if (errbuf == NULL)
  143. return;
  144. message = strerror(errcode);
  145. if ((caller) && (*caller))
  146. pcap_snprintf(errbuf, errbuflen, "%s%s (code %d)", caller, message, errcode);
  147. else
  148. pcap_snprintf(errbuf, errbuflen, "%s (code %d)", message, errcode);
  149. #endif
  150. }
  151. /*
  152. * \brief It retrieves the error message after an error occurred in the socket interface.
  153. *
  154. * This function is defined because of the different way errors are returned in UNIX
  155. * and Win32. This function provides a consistent way to retrieve the error message
  156. * (after a socket error occurred) on all the platforms.
  157. *
  158. * \param caller: a pointer to a user-allocated string which contains a message that has
  159. * to be printed *before* the true error message. It could be, for example, 'this error
  160. * comes from the recv() call at line 31'. It may be NULL.
  161. *
  162. * \param errbuf: a pointer to an user-allocated buffer that will contain the complete
  163. * error message. This buffer has to be at least 'errbuflen' in length.
  164. * It can be NULL; in this case the error cannot be printed.
  165. *
  166. * \param errbuflen: length of the buffer that will contains the error. The error message cannot be
  167. * larger than 'errbuflen - 1' because the last char is reserved for the string terminator.
  168. *
  169. * \return No return values. The error message is returned in the 'string' parameter.
  170. */
  171. void sock_geterror(const char *caller, char *errbuf, int errbuflen)
  172. {
  173. #ifdef _WIN32
  174. if (errbuf == NULL)
  175. return;
  176. sock_fmterror(caller, GetLastError(), errbuf, errbuflen);
  177. #else
  178. if (errbuf == NULL)
  179. return;
  180. sock_fmterror(caller, errno, errbuf, errbuflen);
  181. #endif
  182. }
  183. /*
  184. * \brief It initializes sockets.
  185. *
  186. * This function is pretty useless on UNIX, since socket initialization is not required.
  187. * However it is required on Win32. In UNIX, this function appears to be completely empty.
  188. *
  189. * \param errbuf: a pointer to an user-allocated buffer that will contain the complete
  190. * error message. This buffer has to be at least 'errbuflen' in length.
  191. * It can be NULL; in this case the error cannot be printed.
  192. *
  193. * \param errbuflen: length of the buffer that will contains the error. The error message cannot be
  194. * larger than 'errbuflen - 1' because the last char is reserved for the string terminator.
  195. *
  196. * \return '0' if everything is fine, '-1' if some errors occurred. The error message is returned
  197. * in the 'errbuf' variable.
  198. */
  199. #ifdef _WIN32
  200. int sock_init(char *errbuf, int errbuflen)
  201. {
  202. if (sockcount == 0)
  203. {
  204. WSADATA wsaData; /* helper variable needed to initialize Winsock */
  205. if (WSAStartup(MAKEWORD(WINSOCK_MAJOR_VERSION,
  206. WINSOCK_MINOR_VERSION), &wsaData) != 0)
  207. {
  208. if (errbuf)
  209. pcap_snprintf(errbuf, errbuflen, "Failed to initialize Winsock\n");
  210. WSACleanup();
  211. return -1;
  212. }
  213. }
  214. sockcount++;
  215. #else
  216. int sock_init(char *errbuf _U_, int errbuflen _U_)
  217. {
  218. #endif
  219. return 0;
  220. }
  221. /*
  222. * \brief It deallocates sockets.
  223. *
  224. * This function is pretty useless on UNIX, since socket deallocation is not required.
  225. * However it is required on Win32. In UNIX, this function appears to be completely empty.
  226. *
  227. * \return No error values.
  228. */
  229. void sock_cleanup(void)
  230. {
  231. #ifdef _WIN32
  232. sockcount--;
  233. if (sockcount == 0)
  234. WSACleanup();
  235. #endif
  236. }
  237. /*
  238. * \brief It checks if the sockaddr variable contains a multicast address.
  239. *
  240. * \return '0' if the address is multicast, '-1' if it is not.
  241. */
  242. static int sock_ismcastaddr(const struct sockaddr *saddr)
  243. {
  244. if (saddr->sa_family == PF_INET)
  245. {
  246. struct sockaddr_in *saddr4 = (struct sockaddr_in *) saddr;
  247. if (IN_MULTICAST(ntohl(saddr4->sin_addr.s_addr))) return 0;
  248. else return -1;
  249. }
  250. else
  251. {
  252. struct sockaddr_in6 *saddr6 = (struct sockaddr_in6 *) saddr;
  253. if (IN6_IS_ADDR_MULTICAST(&saddr6->sin6_addr)) return 0;
  254. else return -1;
  255. }
  256. }
  257. /*
  258. * \brief It initializes a network connection both from the client and the server side.
  259. *
  260. * In case of a client socket, this function calls socket() and connect().
  261. * In the meanwhile, it checks for any socket error.
  262. * If an error occurs, it writes the error message into 'errbuf'.
  263. *
  264. * In case of a server socket, the function calls socket(), bind() and listen().
  265. *
  266. * This function is usually preceeded by the sock_initaddress().
  267. *
  268. * \param addrinfo: pointer to an addrinfo variable which will be used to
  269. * open the socket and such. This variable is the one returned by the previous call to
  270. * sock_initaddress().
  271. *
  272. * \param server: '1' if this is a server socket, '0' otherwise.
  273. *
  274. * \param nconn: number of the connections that are allowed to wait into the listen() call.
  275. * This value has no meanings in case of a client socket.
  276. *
  277. * \param errbuf: a pointer to an user-allocated buffer that will contain the complete
  278. * error message. This buffer has to be at least 'errbuflen' in length.
  279. * It can be NULL; in this case the error cannot be printed.
  280. *
  281. * \param errbuflen: length of the buffer that will contains the error. The error message cannot be
  282. * larger than 'errbuflen - 1' because the last char is reserved for the string terminator.
  283. *
  284. * \return the socket that has been opened (that has to be used in the following sockets calls)
  285. * if everything is fine, INVALID_SOCKET if some errors occurred. The error message is returned
  286. * in the 'errbuf' variable.
  287. */
  288. SOCKET sock_open(struct addrinfo *addrinfo, int server, int nconn, char *errbuf, int errbuflen)
  289. {
  290. SOCKET sock;
  291. #if defined(SO_NOSIGPIPE) || defined(IPV6_V6ONLY) || defined(IPV6_BINDV6ONLY)
  292. int on = 1;
  293. #endif
  294. sock = socket(addrinfo->ai_family, addrinfo->ai_socktype, addrinfo->ai_protocol);
  295. if (sock == INVALID_SOCKET)
  296. {
  297. sock_geterror("socket(): ", errbuf, errbuflen);
  298. return INVALID_SOCKET;
  299. }
  300. /*
  301. * Disable SIGPIPE, if we have SO_NOSIGPIPE. We don't want to
  302. * have to deal with signals if the peer closes the connection,
  303. * especially in client programs, which may not even be aware that
  304. * they're sending to sockets.
  305. */
  306. #ifdef SO_NOSIGPIPE
  307. if (setsockopt(sock, SOL_SOCKET, SO_NOSIGPIPE, (char *)&on,
  308. sizeof (int)) == -1)
  309. {
  310. sock_geterror("setsockopt(SO_NOSIGPIPE)", errbuf, errbuflen);
  311. closesocket(sock);
  312. return INVALID_SOCKET;
  313. }
  314. #endif
  315. /* This is a server socket */
  316. if (server)
  317. {
  318. #if defined(IPV6_V6ONLY) || defined(IPV6_BINDV6ONLY)
  319. /*
  320. * Force the use of IPv6-only addresses.
  321. *
  322. * RFC 3493 indicates that you can support IPv4 on an
  323. * IPv6 socket:
  324. *
  325. * https://tools.ietf.org/html/rfc3493#section-3.7
  326. *
  327. * and that this is the default behavior. This means
  328. * that if we first create an IPv6 socket bound to the
  329. * "any" address, it is, in effect, also bound to the
  330. * IPv4 "any" address, so when we create an IPv4 socket
  331. * and try to bind it to the IPv4 "any" address, it gets
  332. * EADDRINUSE.
  333. *
  334. * Not all network stacks support IPv4 on IPv6 sockets;
  335. * pre-NT 6 Windows stacks don't support it, and the
  336. * OpenBSD stack doesn't support it for security reasons
  337. * (see the OpenBSD inet6(4) man page). Therefore, we
  338. * don't want to rely on this behavior.
  339. *
  340. * So we try to disable it, using either the IPV6_V6ONLY
  341. * option from RFC 3493:
  342. *
  343. * https://tools.ietf.org/html/rfc3493#section-5.3
  344. *
  345. * or the IPV6_BINDV6ONLY option from older UN*Xes.
  346. */
  347. #ifndef IPV6_V6ONLY
  348. /* For older systems */
  349. #define IPV6_V6ONLY IPV6_BINDV6ONLY
  350. #endif /* IPV6_V6ONLY */
  351. if (addrinfo->ai_family == PF_INET6)
  352. {
  353. if (setsockopt(sock, IPPROTO_IPV6, IPV6_V6ONLY,
  354. (char *)&on, sizeof (int)) == -1)
  355. {
  356. if (errbuf)
  357. pcap_snprintf(errbuf, errbuflen, "setsockopt(IPV6_V6ONLY)");
  358. closesocket(sock);
  359. return INVALID_SOCKET;
  360. }
  361. }
  362. #endif /* defined(IPV6_V6ONLY) || defined(IPV6_BINDV6ONLY) */
  363. /* WARNING: if the address is a mcast one, I should place the proper Win32 code here */
  364. if (bind(sock, addrinfo->ai_addr, (int) addrinfo->ai_addrlen) != 0)
  365. {
  366. sock_geterror("bind(): ", errbuf, errbuflen);
  367. closesocket(sock);
  368. return INVALID_SOCKET;
  369. }
  370. if (addrinfo->ai_socktype == SOCK_STREAM)
  371. if (listen(sock, nconn) == -1)
  372. {
  373. sock_geterror("listen(): ", errbuf, errbuflen);
  374. closesocket(sock);
  375. return INVALID_SOCKET;
  376. }
  377. /* server side ended */
  378. return sock;
  379. }
  380. else /* we're the client */
  381. {
  382. struct addrinfo *tempaddrinfo;
  383. char *errbufptr;
  384. size_t bufspaceleft;
  385. tempaddrinfo = addrinfo;
  386. errbufptr = errbuf;
  387. bufspaceleft = errbuflen;
  388. *errbufptr = 0;
  389. /*
  390. * We have to loop though all the addinfo returned.
  391. * For instance, we can have both IPv6 and IPv4 addresses, but the service we're trying
  392. * to connect to is unavailable in IPv6, so we have to try in IPv4 as well
  393. */
  394. while (tempaddrinfo)
  395. {
  396. if (connect(sock, tempaddrinfo->ai_addr, (int) tempaddrinfo->ai_addrlen) == -1)
  397. {
  398. size_t msglen;
  399. char TmpBuffer[100];
  400. char SocketErrorMessage[SOCK_ERRBUF_SIZE];
  401. /*
  402. * We have to retrieve the error message before any other socket call completes, otherwise
  403. * the error message is lost
  404. */
  405. sock_geterror(NULL, SocketErrorMessage, sizeof(SocketErrorMessage));
  406. /* Returns the numeric address of the host that triggered the error */
  407. sock_getascii_addrport((struct sockaddr_storage *) tempaddrinfo->ai_addr, TmpBuffer, sizeof(TmpBuffer), NULL, 0, NI_NUMERICHOST, TmpBuffer, sizeof(TmpBuffer));
  408. pcap_snprintf(errbufptr, bufspaceleft,
  409. "Is the server properly installed on %s? connect() failed: %s", TmpBuffer, SocketErrorMessage);
  410. /* In case more then one 'connect' fails, we manage to keep all the error messages */
  411. msglen = strlen(errbufptr);
  412. errbufptr[msglen] = ' ';
  413. errbufptr[msglen + 1] = 0;
  414. bufspaceleft = bufspaceleft - (msglen + 1);
  415. errbufptr += (msglen + 1);
  416. tempaddrinfo = tempaddrinfo->ai_next;
  417. }
  418. else
  419. break;
  420. }
  421. /*
  422. * Check how we exit from the previous loop
  423. * If tempaddrinfo is equal to NULL, it means that all the connect() failed.
  424. */
  425. if (tempaddrinfo == NULL)
  426. {
  427. closesocket(sock);
  428. return INVALID_SOCKET;
  429. }
  430. else
  431. return sock;
  432. }
  433. }
  434. /*
  435. * \brief Closes the present (TCP and UDP) socket connection.
  436. *
  437. * This function sends a shutdown() on the socket in order to disable send() calls
  438. * (while recv() ones are still allowed). Then, it closes the socket.
  439. *
  440. * \param sock: the socket identifier of the connection that has to be closed.
  441. *
  442. * \param errbuf: a pointer to an user-allocated buffer that will contain the complete
  443. * error message. This buffer has to be at least 'errbuflen' in length.
  444. * It can be NULL; in this case the error cannot be printed.
  445. *
  446. * \param errbuflen: length of the buffer that will contains the error. The error message cannot be
  447. * larger than 'errbuflen - 1' because the last char is reserved for the string terminator.
  448. *
  449. * \return '0' if everything is fine, '-1' if some errors occurred. The error message is returned
  450. * in the 'errbuf' variable.
  451. */
  452. int sock_close(SOCKET sock, char *errbuf, int errbuflen)
  453. {
  454. /*
  455. * SHUT_WR: subsequent calls to the send function are disallowed.
  456. * For TCP sockets, a FIN will be sent after all data is sent and
  457. * acknowledged by the Server.
  458. */
  459. if (shutdown(sock, SHUT_WR))
  460. {
  461. sock_geterror("shutdown(): ", errbuf, errbuflen);
  462. /* close the socket anyway */
  463. closesocket(sock);
  464. return -1;
  465. }
  466. closesocket(sock);
  467. return 0;
  468. }
  469. /*
  470. * \brief Checks that the address, port and flags given are valids and it returns an 'addrinfo' structure.
  471. *
  472. * This function basically calls the getaddrinfo() calls, and it performs a set of sanity checks
  473. * to control that everything is fine (e.g. a TCP socket cannot have a mcast address, and such).
  474. * If an error occurs, it writes the error message into 'errbuf'.
  475. *
  476. * \param host: a pointer to a string identifying the host. It can be
  477. * a host name, a numeric literal address, or NULL or "" (useful
  478. * in case of a server socket which has to bind to all addresses).
  479. *
  480. * \param port: a pointer to a user-allocated buffer containing the network port to use.
  481. *
  482. * \param hints: an addrinfo variable (passed by reference) containing the flags needed to create the
  483. * addrinfo structure appropriately.
  484. *
  485. * \param addrinfo: it represents the true returning value. This is a pointer to an addrinfo variable
  486. * (passed by reference), which will be allocated by this function and returned back to the caller.
  487. * This variable will be used in the next sockets calls.
  488. *
  489. * \param errbuf: a pointer to an user-allocated buffer that will contain the complete
  490. * error message. This buffer has to be at least 'errbuflen' in length.
  491. * It can be NULL; in this case the error cannot be printed.
  492. *
  493. * \param errbuflen: length of the buffer that will contains the error. The error message cannot be
  494. * larger than 'errbuflen - 1' because the last char is reserved for the string terminator.
  495. *
  496. * \return '0' if everything is fine, '-1' if some errors occurred. The error message is returned
  497. * in the 'errbuf' variable. The addrinfo variable that has to be used in the following sockets calls is
  498. * returned into the addrinfo parameter.
  499. *
  500. * \warning The 'addrinfo' variable has to be deleted by the programmer by calling freeaddrinfo() when
  501. * it is no longer needed.
  502. *
  503. * \warning This function requires the 'hints' variable as parameter. The semantic of this variable is the same
  504. * of the one of the corresponding variable used into the standard getaddrinfo() socket function. We suggest
  505. * the programmer to look at that function in order to set the 'hints' variable appropriately.
  506. */
  507. int sock_initaddress(const char *host, const char *port,
  508. struct addrinfo *hints, struct addrinfo **addrinfo, char *errbuf, int errbuflen)
  509. {
  510. int retval;
  511. retval = getaddrinfo(host, port, hints, addrinfo);
  512. if (retval != 0)
  513. {
  514. /*
  515. * if the getaddrinfo() fails, you have to use gai_strerror(), instead of using the standard
  516. * error routines (errno) in UNIX; Winsock suggests using the GetLastError() instead.
  517. */
  518. if (errbuf)
  519. {
  520. #ifdef _WIN32
  521. sock_geterror("getaddrinfo(): ", errbuf, errbuflen);
  522. #else
  523. pcap_snprintf(errbuf, errbuflen, "getaddrinfo() %s", gai_strerror(retval));
  524. #endif
  525. }
  526. return -1;
  527. }
  528. /*
  529. * \warning SOCKET: I should check all the accept() in order to bind to all addresses in case
  530. * addrinfo has more han one pointers
  531. */
  532. /*
  533. * This software only supports PF_INET and PF_INET6.
  534. *
  535. * XXX - should we just check that at least *one* address is
  536. * either PF_INET or PF_INET6, and, when using the list,
  537. * ignore all addresses that are neither? (What, no IPX
  538. * support? :-))
  539. */
  540. if (((*addrinfo)->ai_family != PF_INET) &&
  541. ((*addrinfo)->ai_family != PF_INET6))
  542. {
  543. if (errbuf)
  544. pcap_snprintf(errbuf, errbuflen, "getaddrinfo(): socket type not supported");
  545. freeaddrinfo(*addrinfo);
  546. *addrinfo = NULL;
  547. return -1;
  548. }
  549. /*
  550. * You can't do multicast (or broadcast) TCP.
  551. */
  552. if (((*addrinfo)->ai_socktype == SOCK_STREAM) &&
  553. (sock_ismcastaddr((*addrinfo)->ai_addr) == 0))
  554. {
  555. if (errbuf)
  556. pcap_snprintf(errbuf, errbuflen, "getaddrinfo(): multicast addresses are not valid when using TCP streams");
  557. freeaddrinfo(*addrinfo);
  558. *addrinfo = NULL;
  559. return -1;
  560. }
  561. return 0;
  562. }
  563. /*
  564. * \brief It sends the amount of data contained into 'buffer' on the given socket.
  565. *
  566. * This function basically calls the send() socket function and it checks that all
  567. * the data specified in 'buffer' (of size 'size') will be sent. If an error occurs,
  568. * it writes the error message into 'errbuf'.
  569. * In case the socket buffer does not have enough space, it loops until all data
  570. * has been sent.
  571. *
  572. * \param socket: the connected socket currently opened.
  573. *
  574. * \param buffer: a char pointer to a user-allocated buffer in which data is contained.
  575. *
  576. * \param size: number of bytes that have to be sent.
  577. *
  578. * \param errbuf: a pointer to an user-allocated buffer that will contain the complete
  579. * error message. This buffer has to be at least 'errbuflen' in length.
  580. * It can be NULL; in this case the error cannot be printed.
  581. *
  582. * \param errbuflen: length of the buffer that will contains the error. The error message cannot be
  583. * larger than 'errbuflen - 1' because the last char is reserved for the string terminator.
  584. *
  585. * \return '0' if everything is fine, '-1' if an error other than
  586. * "connection reset" or "peer has closed the receive side" occurred,
  587. * '-2' if we got one of those errors.
  588. * For errors, an error message is returned in the 'errbuf' variable.
  589. */
  590. int sock_send(SOCKET sock, const char *buffer, size_t size,
  591. char *errbuf, int errbuflen)
  592. {
  593. int remaining;
  594. ssize_t nsent;
  595. if (size > INT_MAX)
  596. {
  597. if (errbuf)
  598. {
  599. pcap_snprintf(errbuf, errbuflen,
  600. "Can't send more than %u bytes with sock_recv",
  601. INT_MAX);
  602. }
  603. return -1;
  604. }
  605. remaining = (int)size;
  606. do {
  607. #ifdef MSG_NOSIGNAL
  608. /*
  609. * Send with MSG_NOSIGNAL, so that we don't get SIGPIPE
  610. * on errors on stream-oriented sockets when the other
  611. * end breaks the connection.
  612. * The EPIPE error is still returned.
  613. */
  614. nsent = send(sock, buffer, remaining, MSG_NOSIGNAL);
  615. #else
  616. nsent = send(sock, buffer, remaining, 0);
  617. #endif
  618. if (nsent == -1)
  619. {
  620. /*
  621. * If the client closed the connection out from
  622. * under us, there's no need to log that as an
  623. * error.
  624. */
  625. int errcode;
  626. #ifdef _WIN32
  627. errcode = GetLastError();
  628. if (errcode == WSAECONNRESET ||
  629. errcode == WSAECONNABORTED)
  630. {
  631. /*
  632. * WSAECONNABORTED appears to be the error
  633. * returned in Winsock when you try to send
  634. * on a connection where the peer has closed
  635. * the receive side.
  636. */
  637. return -2;
  638. }
  639. sock_fmterror("send(): ", errcode, errbuf, errbuflen);
  640. #else
  641. errcode = errno;
  642. if (errcode == ECONNRESET || errcode == EPIPE)
  643. {
  644. /*
  645. * EPIPE is what's returned on UN*X when
  646. * you try to send on a connection when
  647. * the peer has closed the receive side.
  648. */
  649. return -2;
  650. }
  651. sock_fmterror("send(): ", errcode, errbuf, errbuflen);
  652. #endif
  653. return -1;
  654. }
  655. remaining -= nsent;
  656. buffer += nsent;
  657. } while (remaining != 0);
  658. return 0;
  659. }
  660. /*
  661. * \brief It copies the amount of data contained into 'buffer' into 'tempbuf'.
  662. * and it checks for buffer overflows.
  663. *
  664. * This function basically copies 'size' bytes of data contained into 'buffer'
  665. * into 'tempbuf', starting at offset 'offset'. Before that, it checks that the
  666. * resulting buffer will not be larger than 'totsize'. Finally, it updates
  667. * the 'offset' variable in order to point to the first empty location of the buffer.
  668. *
  669. * In case the function is called with 'checkonly' equal to 1, it does not copy
  670. * the data into the buffer. It only checks for buffer overflows and it updates the
  671. * 'offset' variable. This mode can be useful when the buffer already contains the
  672. * data (maybe because the producer writes directly into the target buffer), so
  673. * only the buffer overflow check has to be made.
  674. * In this case, both 'buffer' and 'tempbuf' can be NULL values.
  675. *
  676. * This function is useful in case the userland application does not know immediately
  677. * all the data it has to write into the socket. This function provides a way to create
  678. * the "stream" step by step, appending the new data to the old one. Then, when all the
  679. * data has been bufferized, the application can call the sock_send() function.
  680. *
  681. * \param buffer: a char pointer to a user-allocated buffer that keeps the data
  682. * that has to be copied.
  683. *
  684. * \param size: number of bytes that have to be copied.
  685. *
  686. * \param tempbuf: user-allocated buffer (of size 'totsize') in which data
  687. * has to be copied.
  688. *
  689. * \param offset: an index into 'tempbuf' which keeps the location of its first
  690. * empty location.
  691. *
  692. * \param totsize: total size of the buffer in which data is being copied.
  693. *
  694. * \param checkonly: '1' if we do not want to copy data into the buffer and we
  695. * want just do a buffer ovreflow control, '0' if data has to be copied as well.
  696. *
  697. * \param errbuf: a pointer to an user-allocated buffer that will contain the complete
  698. * error message. This buffer has to be at least 'errbuflen' in length.
  699. * It can be NULL; in this case the error cannot be printed.
  700. *
  701. * \param errbuflen: length of the buffer that will contains the error. The error message cannot be
  702. * larger than 'errbuflen - 1' because the last char is reserved for the string terminator.
  703. *
  704. * \return '0' if everything is fine, '-1' if some errors occurred. The error message
  705. * is returned in the 'errbuf' variable. When the function returns, 'tempbuf' will
  706. * have the new string appended, and 'offset' will keep the length of that buffer.
  707. * In case of 'checkonly == 1', data is not copied, but 'offset' is updated in any case.
  708. *
  709. * \warning This function assumes that the buffer in which data has to be stored is
  710. * large 'totbuf' bytes.
  711. *
  712. * \warning In case of 'checkonly', be carefully to call this function *before* copying
  713. * the data into the buffer. Otherwise, the control about the buffer overflow is useless.
  714. */
  715. int sock_bufferize(const char *buffer, int size, char *tempbuf, int *offset, int totsize, int checkonly, char *errbuf, int errbuflen)
  716. {
  717. if ((*offset + size) > totsize)
  718. {
  719. if (errbuf)
  720. pcap_snprintf(errbuf, errbuflen, "Not enough space in the temporary send buffer.");
  721. return -1;
  722. }
  723. if (!checkonly)
  724. memcpy(tempbuf + (*offset), buffer, size);
  725. (*offset) += size;
  726. return 0;
  727. }
  728. /*
  729. * \brief It waits on a connected socket and it manages to receive data.
  730. *
  731. * This function basically calls the recv() socket function and it checks that no
  732. * error occurred. If that happens, it writes the error message into 'errbuf'.
  733. *
  734. * This function changes its behavior according to the 'receiveall' flag: if we
  735. * want to receive exactly 'size' byte, it loops on the recv() until all the requested
  736. * data is arrived. Otherwise, it returns the data currently available.
  737. *
  738. * In case the socket does not have enough data available, it cycles on the recv()
  739. * until the requested data (of size 'size') is arrived.
  740. * In this case, it blocks until the number of bytes read is equal to 'size'.
  741. *
  742. * \param sock: the connected socket currently opened.
  743. *
  744. * \param buffer: a char pointer to a user-allocated buffer in which data has to be stored
  745. *
  746. * \param size: size of the allocated buffer. WARNING: this indicates the number of bytes
  747. * that we are expecting to be read.
  748. *
  749. * \param flags:
  750. *
  751. * SOCK_RECEIVALL_XXX:
  752. *
  753. * if SOCK_RECEIVEALL_NO, return as soon as some data is ready
  754. * if SOCK_RECEIVALL_YES, wait until 'size' data has been
  755. * received (in case the socket does not have enough data available).
  756. *
  757. * SOCK_EOF_XXX:
  758. *
  759. * if SOCK_EOF_ISNT_ERROR, if the first read returns 0, just return 0,
  760. * and return an error on any subsequent read that returns 0;
  761. * if SOCK_EOF_IS_ERROR, if any read returns 0, return an error.
  762. *
  763. * \param errbuf: a pointer to an user-allocated buffer that will contain the complete
  764. * error message. This buffer has to be at least 'errbuflen' in length.
  765. * It can be NULL; in this case the error cannot be printed.
  766. *
  767. * \param errbuflen: length of the buffer that will contains the error. The error message cannot be
  768. * larger than 'errbuflen - 1' because the last char is reserved for the string terminator.
  769. *
  770. * \return the number of bytes read if everything is fine, '-1' if some errors occurred.
  771. * The error message is returned in the 'errbuf' variable.
  772. */
  773. int sock_recv(SOCKET sock, void *buffer, size_t size, int flags,
  774. char *errbuf, int errbuflen)
  775. {
  776. char *bufp = buffer;
  777. int remaining;
  778. ssize_t nread;
  779. if (size == 0)
  780. {
  781. SOCK_DEBUG_MESSAGE("I have been requested to read zero bytes");
  782. return 0;
  783. }
  784. if (size > INT_MAX)
  785. {
  786. if (errbuf)
  787. {
  788. pcap_snprintf(errbuf, errbuflen,
  789. "Can't read more than %u bytes with sock_recv",
  790. INT_MAX);
  791. }
  792. return -1;
  793. }
  794. bufp = (char *) buffer;
  795. remaining = (int) size;
  796. /*
  797. * We don't use MSG_WAITALL because it's not supported in
  798. * Win32.
  799. */
  800. for (;;) {
  801. nread = recv(sock, bufp, remaining, 0);
  802. if (nread == -1)
  803. {
  804. #ifndef _WIN32
  805. if (errno == EINTR)
  806. return -3;
  807. #endif
  808. sock_geterror("recv(): ", errbuf, errbuflen);
  809. return -1;
  810. }
  811. if (nread == 0)
  812. {
  813. if ((flags & SOCK_EOF_IS_ERROR) ||
  814. (remaining != (int) size))
  815. {
  816. /*
  817. * Either we've already read some data,
  818. * or we're always supposed to return
  819. * an error on EOF.
  820. */
  821. if (errbuf)
  822. {
  823. pcap_snprintf(errbuf, errbuflen,
  824. "The other host terminated the connection.");
  825. }
  826. return -1;
  827. }
  828. else
  829. return 0;
  830. }
  831. /*
  832. * Do we want to read the amount requested, or just return
  833. * what we got?
  834. */
  835. if (!(flags & SOCK_RECEIVEALL_YES))
  836. {
  837. /*
  838. * Just return what we got.
  839. */
  840. return (int) nread;
  841. }
  842. bufp += nread;
  843. remaining -= nread;
  844. if (remaining == 0)
  845. return (int) size;
  846. }
  847. }
  848. /*
  849. * Receives a datagram from a socket.
  850. *
  851. * Returns the size of the datagram on success or -1 on error.
  852. */
  853. int sock_recv_dgram(SOCKET sock, void *buffer, size_t size,
  854. char *errbuf, int errbuflen)
  855. {
  856. ssize_t nread;
  857. #ifndef _WIN32
  858. struct msghdr message;
  859. struct iovec iov;
  860. #endif
  861. if (size == 0)
  862. {
  863. SOCK_DEBUG_MESSAGE("I have been requested to read zero bytes");
  864. return 0;
  865. }
  866. if (size > INT_MAX)
  867. {
  868. if (errbuf)
  869. {
  870. pcap_snprintf(errbuf, errbuflen,
  871. "Can't read more than %u bytes with sock_recv_dgram",
  872. INT_MAX);
  873. }
  874. return -1;
  875. }
  876. /*
  877. * This should be a datagram socket, so we should get the
  878. * entire datagram in one recv() or recvmsg() call, and
  879. * don't need to loop.
  880. */
  881. #ifdef _WIN32
  882. nread = recv(sock, buffer, size, 0);
  883. if (nread == SOCKET_ERROR)
  884. {
  885. /*
  886. * To quote the MSDN documentation for recv(),
  887. * "If the datagram or message is larger than
  888. * the buffer specified, the buffer is filled
  889. * with the first part of the datagram, and recv
  890. * generates the error WSAEMSGSIZE. For unreliable
  891. * protocols (for example, UDP) the excess data is
  892. * lost..."
  893. *
  894. * So if the message is bigger than the buffer
  895. * supplied to us, the excess data is discarded,
  896. * and we'll report an error.
  897. */
  898. sock_geterror("recv(): ", errbuf, errbuflen);
  899. return -1;
  900. }
  901. #else /* _WIN32 */
  902. /*
  903. * The Single UNIX Specification says that a recv() on
  904. * a socket for a message-oriented protocol will discard
  905. * the excess data. It does *not* indicate that the
  906. * receive will fail with, for example, EMSGSIZE.
  907. *
  908. * Therefore, we use recvmsg(), which appears to be
  909. * the only way to get a "message truncated" indication
  910. * when receiving a message for a message-oriented
  911. * protocol.
  912. */
  913. message.msg_name = NULL; /* we don't care who it's from */
  914. message.msg_namelen = 0;
  915. iov.iov_base = buffer;
  916. iov.iov_len = size;
  917. message.msg_iov = &iov;
  918. message.msg_iovlen = 1;
  919. #ifdef HAVE_STRUCT_MSGHDR_MSG_CONTROL
  920. message.msg_control = NULL; /* we don't care about control information */
  921. message.msg_controllen = 0;
  922. #endif
  923. #ifdef HAVE_STRUCT_MSGHDR_MSG_FLAGS
  924. message.msg_flags = 0;
  925. #endif
  926. nread = recvmsg(sock, &message, 0);
  927. if (nread == -1)
  928. {
  929. if (errno == EINTR)
  930. return -3;
  931. sock_geterror("recv(): ", errbuf, errbuflen);
  932. return -1;
  933. }
  934. #ifdef HAVE_STRUCT_MSGHDR_MSG_FLAGS
  935. /*
  936. * XXX - Solaris supports this, but only if you ask for the
  937. * X/Open version of recvmsg(); should we use that, or will
  938. * that cause other problems?
  939. */
  940. if (message.msg_flags & MSG_TRUNC)
  941. {
  942. /*
  943. * Message was bigger than the specified buffer size.
  944. *
  945. * Report this as an error, as the Microsoft documentation
  946. * implies we'd do in a similar case on Windows.
  947. */
  948. pcap_snprintf(errbuf, errbuflen, "recv(): Message too long");
  949. return -1;
  950. }
  951. #endif /* HAVE_STRUCT_MSGHDR_MSG_FLAGS */
  952. #endif /* _WIN32 */
  953. /*
  954. * The size we're reading fits in an int, so the return value
  955. * will fit in an int.
  956. */
  957. return (int)nread;
  958. }
  959. /*
  960. * \brief It discards N bytes that are currently waiting to be read on the current socket.
  961. *
  962. * This function is useful in case we receive a message we cannot understand (e.g.
  963. * wrong version number when receiving a network packet), so that we have to discard all
  964. * data before reading a new message.
  965. *
  966. * This function will read 'size' bytes from the socket and discard them.
  967. * It defines an internal buffer in which data will be copied; however, in case
  968. * this buffer is not large enough, it will cycle in order to read everything as well.
  969. *
  970. * \param sock: the connected socket currently opened.
  971. *
  972. * \param size: number of bytes that have to be discarded.
  973. *
  974. * \param errbuf: a pointer to an user-allocated buffer that will contain the complete
  975. * error message. This buffer has to be at least 'errbuflen' in length.
  976. * It can be NULL; in this case the error cannot be printed.
  977. *
  978. * \param errbuflen: length of the buffer that will contains the error. The error message cannot be
  979. * larger than 'errbuflen - 1' because the last char is reserved for the string terminator.
  980. *
  981. * \return '0' if everything is fine, '-1' if some errors occurred.
  982. * The error message is returned in the 'errbuf' variable.
  983. */
  984. int sock_discard(SOCKET sock, int size, char *errbuf, int errbuflen)
  985. {
  986. #define TEMP_BUF_SIZE 32768
  987. char buffer[TEMP_BUF_SIZE]; /* network buffer, to be used when the message is discarded */
  988. /*
  989. * A static allocation avoids the need of a 'malloc()' each time we want to discard a message
  990. * Our feeling is that a buffer if 32KB is enough for most of the application;
  991. * in case this is not enough, the "while" loop discards the message by calling the
  992. * sockrecv() several times.
  993. * We do not want to create a bigger variable because this causes the program to exit on
  994. * some platforms (e.g. BSD)
  995. */
  996. while (size > TEMP_BUF_SIZE)
  997. {
  998. if (sock_recv(sock, buffer, TEMP_BUF_SIZE, SOCK_RECEIVEALL_YES, errbuf, errbuflen) == -1)
  999. return -1;
  1000. size -= TEMP_BUF_SIZE;
  1001. }
  1002. /*
  1003. * If there is still data to be discarded
  1004. * In this case, the data can fit into the temporary buffer
  1005. */
  1006. if (size)
  1007. {
  1008. if (sock_recv(sock, buffer, size, SOCK_RECEIVEALL_YES, errbuf, errbuflen) == -1)
  1009. return -1;
  1010. }
  1011. SOCK_DEBUG_MESSAGE("I'm currently discarding data\n");
  1012. return 0;
  1013. }
  1014. /*
  1015. * \brief Checks that one host (identified by the sockaddr_storage structure) belongs to an 'allowed list'.
  1016. *
  1017. * This function is useful after an accept() call in order to check if the connecting
  1018. * host is allowed to connect to me. To do that, we have a buffer that keeps the list of the
  1019. * allowed host; this function checks the sockaddr_storage structure of the connecting host
  1020. * against this host list, and it returns '0' is the host is included in this list.
  1021. *
  1022. * \param hostlist: pointer to a string that contains the list of the allowed host.
  1023. *
  1024. * \param sep: a string that keeps the separators used between the hosts (for example the
  1025. * space character) in the host list.
  1026. *
  1027. * \param from: a sockaddr_storage structure, as it is returned by the accept() call.
  1028. *
  1029. * \param errbuf: a pointer to an user-allocated buffer that will contain the complete
  1030. * error message. This buffer has to be at least 'errbuflen' in length.
  1031. * It can be NULL; in this case the error cannot be printed.
  1032. *
  1033. * \param errbuflen: length of the buffer that will contains the error. The error message cannot be
  1034. * larger than 'errbuflen - 1' because the last char is reserved for the string terminator.
  1035. *
  1036. * \return It returns:
  1037. * - '1' if the host list is empty
  1038. * - '0' if the host belongs to the host list (and therefore it is allowed to connect)
  1039. * - '-1' in case the host does not belong to the host list (and therefore it is not allowed to connect
  1040. * - '-2' in case or error. The error message is returned in the 'errbuf' variable.
  1041. */
  1042. int sock_check_hostlist(char *hostlist, const char *sep, struct sockaddr_storage *from, char *errbuf, int errbuflen)
  1043. {
  1044. /* checks if the connecting host is among the ones allowed */
  1045. if ((hostlist) && (hostlist[0]))
  1046. {
  1047. char *token; /* temp, needed to separate items into the hostlist */
  1048. struct addrinfo *addrinfo, *ai_next;
  1049. char *temphostlist;
  1050. char *lasts;
  1051. /*
  1052. * The problem is that strtok modifies the original variable by putting '0' at the end of each token
  1053. * So, we have to create a new temporary string in which the original content is kept
  1054. */
  1055. temphostlist = strdup(hostlist);
  1056. if (temphostlist == NULL)
  1057. {
  1058. sock_geterror("sock_check_hostlist(), malloc() failed", errbuf, errbuflen);
  1059. return -2;
  1060. }
  1061. token = pcap_strtok_r(temphostlist, sep, &lasts);
  1062. /* it avoids a warning in the compilation ('addrinfo used but not initialized') */
  1063. addrinfo = NULL;
  1064. while (token != NULL)
  1065. {
  1066. struct addrinfo hints;
  1067. int retval;
  1068. addrinfo = NULL;
  1069. memset(&hints, 0, sizeof(struct addrinfo));
  1070. hints.ai_family = PF_UNSPEC;
  1071. hints.ai_socktype = SOCK_STREAM;
  1072. retval = getaddrinfo(token, "0", &hints, &addrinfo);
  1073. if (retval != 0)
  1074. {
  1075. if (errbuf)
  1076. pcap_snprintf(errbuf, errbuflen, "getaddrinfo() %s", gai_strerror(retval));
  1077. SOCK_DEBUG_MESSAGE(errbuf);
  1078. /* Get next token */
  1079. token = pcap_strtok_r(NULL, sep, &lasts);
  1080. continue;
  1081. }
  1082. /* ai_next is required to preserve the content of addrinfo, in order to deallocate it properly */
  1083. ai_next = addrinfo;
  1084. while (ai_next)
  1085. {
  1086. if (sock_cmpaddr(from, (struct sockaddr_storage *) ai_next->ai_addr) == 0)
  1087. {
  1088. free(temphostlist);
  1089. freeaddrinfo(addrinfo);
  1090. return 0;
  1091. }
  1092. /*
  1093. * If we are here, it means that the current address does not matches
  1094. * Let's try with the next one in the header chain
  1095. */
  1096. ai_next = ai_next->ai_next;
  1097. }
  1098. freeaddrinfo(addrinfo);
  1099. addrinfo = NULL;
  1100. /* Get next token */
  1101. token = pcap_strtok_r(NULL, sep, &lasts);
  1102. }
  1103. if (addrinfo)
  1104. {
  1105. freeaddrinfo(addrinfo);
  1106. addrinfo = NULL;
  1107. }
  1108. if (errbuf)
  1109. pcap_snprintf(errbuf, errbuflen, "The host is not in the allowed host list. Connection refused.");
  1110. free(temphostlist);
  1111. return -1;
  1112. }
  1113. /* No hostlist, so we have to return 'empty list' */
  1114. return 1;
  1115. }
  1116. /*
  1117. * \brief Compares two addresses contained into two sockaddr_storage structures.
  1118. *
  1119. * This function is useful to compare two addresses, given their internal representation,
  1120. * i.e. an sockaddr_storage structure.
  1121. *
  1122. * The two structures do not need to be sockaddr_storage; you can have both 'sockaddr_in' and
  1123. * sockaddr_in6, properly acsted in order to be compliant to the function interface.
  1124. *
  1125. * This function will return '0' if the two addresses matches, '-1' if not.
  1126. *
  1127. * \param first: a sockaddr_storage structure, (for example the one that is returned by an
  1128. * accept() call), containing the first address to compare.
  1129. *
  1130. * \param second: a sockaddr_storage structure containing the second address to compare.
  1131. *
  1132. * \return '0' if the addresses are equal, '-1' if they are different.
  1133. */
  1134. int sock_cmpaddr(struct sockaddr_storage *first, struct sockaddr_storage *second)
  1135. {
  1136. if (first->ss_family == second->ss_family)
  1137. {
  1138. if (first->ss_family == AF_INET)
  1139. {
  1140. if (memcmp(&(((struct sockaddr_in *) first)->sin_addr),
  1141. &(((struct sockaddr_in *) second)->sin_addr),
  1142. sizeof(struct in_addr)) == 0)
  1143. return 0;
  1144. }
  1145. else /* address family is AF_INET6 */
  1146. {
  1147. if (memcmp(&(((struct sockaddr_in6 *) first)->sin6_addr),
  1148. &(((struct sockaddr_in6 *) second)->sin6_addr),
  1149. sizeof(struct in6_addr)) == 0)
  1150. return 0;
  1151. }
  1152. }
  1153. return -1;
  1154. }
  1155. /*
  1156. * \brief It gets the address/port the system picked for this socket (on connected sockets).
  1157. *
  1158. * It is used to return the address and port the server picked for our socket on the local machine.
  1159. * It works only on:
  1160. * - connected sockets
  1161. * - server sockets
  1162. *
  1163. * On unconnected client sockets it does not work because the system dynamically chooses a port
  1164. * only when the socket calls a send() call.
  1165. *
  1166. * \param sock: the connected socket currently opened.
  1167. *
  1168. * \param address: it contains the address that will be returned by the function. This buffer
  1169. * must be properly allocated by the user. The address can be either literal or numeric depending
  1170. * on the value of 'Flags'.
  1171. *
  1172. * \param addrlen: the length of the 'address' buffer.
  1173. *
  1174. * \param port: it contains the port that will be returned by the function. This buffer
  1175. * must be properly allocated by the user.
  1176. *
  1177. * \param portlen: the length of the 'port' buffer.
  1178. *
  1179. * \param flags: a set of flags (the ones defined into the getnameinfo() standard socket function)
  1180. * that determine if the resulting address must be in numeric / literal form, and so on.
  1181. *
  1182. * \param errbuf: a pointer to an user-allocated buffer that will contain the complete
  1183. * error message. This buffer has to be at least 'errbuflen' in length.
  1184. * It can be NULL; in this case the error cannot be printed.
  1185. *
  1186. * \param errbuflen: length of the buffer that will contains the error. The error message cannot be
  1187. * larger than 'errbuflen - 1' because the last char is reserved for the string terminator.
  1188. *
  1189. * \return It returns '-1' if this function succeeds, '0' otherwise.
  1190. * The address and port corresponding are returned back in the buffers 'address' and 'port'.
  1191. * In any case, the returned strings are '0' terminated.
  1192. *
  1193. * \warning If the socket is using a connectionless protocol, the address may not be available
  1194. * until I/O occurs on the socket.
  1195. */
  1196. int sock_getmyinfo(SOCKET sock, char *address, int addrlen, char *port, int portlen, int flags, char *errbuf, int errbuflen)
  1197. {
  1198. struct sockaddr_storage mysockaddr;
  1199. socklen_t sockaddrlen;
  1200. sockaddrlen = sizeof(struct sockaddr_storage);
  1201. if (getsockname(sock, (struct sockaddr *) &mysockaddr, &sockaddrlen) == -1)
  1202. {
  1203. sock_geterror("getsockname(): ", errbuf, errbuflen);
  1204. return 0;
  1205. }
  1206. /* Returns the numeric address of the host that triggered the error */
  1207. return sock_getascii_addrport(&mysockaddr, address, addrlen, port, portlen, flags, errbuf, errbuflen);
  1208. }
  1209. /*
  1210. * \brief It retrieves two strings containing the address and the port of a given 'sockaddr' variable.
  1211. *
  1212. * This function is basically an extended version of the inet_ntop(), which does not exist in
  1213. * Winsock because the same result can be obtained by using the getnameinfo().
  1214. * However, differently from inet_ntop(), this function is able to return also literal names
  1215. * (e.g. 'localhost') dependently from the 'Flags' parameter.
  1216. *
  1217. * The function accepts a sockaddr_storage variable (which can be returned by several functions
  1218. * like bind(), connect(), accept(), and more) and it transforms its content into a 'human'
  1219. * form. So, for instance, it is able to translate an hex address (stored in binary form) into
  1220. * a standard IPv6 address like "::1".
  1221. *
  1222. * The behavior of this function depends on the parameters we have in the 'Flags' variable, which
  1223. * are the ones allowed in the standard getnameinfo() socket function.
  1224. *
  1225. * \param sockaddr: a 'sockaddr_in' or 'sockaddr_in6' structure containing the address that
  1226. * need to be translated from network form into the presentation form. This structure must be
  1227. * zero-ed prior using it, and the address family field must be filled with the proper value.
  1228. * The user must cast any 'sockaddr_in' or 'sockaddr_in6' structures to 'sockaddr_storage' before
  1229. * calling this function.
  1230. *
  1231. * \param address: it contains the address that will be returned by the function. This buffer
  1232. * must be properly allocated by the user. The address can be either literal or numeric depending
  1233. * on the value of 'Flags'.
  1234. *
  1235. * \param addrlen: the length of the 'address' buffer.
  1236. *
  1237. * \param port: it contains the port that will be returned by the function. This buffer
  1238. * must be properly allocated by the user.
  1239. *
  1240. * \param portlen: the length of the 'port' buffer.
  1241. *
  1242. * \param flags: a set of flags (the ones defined into the getnameinfo() standard socket function)
  1243. * that determine if the resulting address must be in numeric / literal form, and so on.
  1244. *
  1245. * \param errbuf: a pointer to an user-allocated buffer that will contain the complete
  1246. * error message. This buffer has to be at least 'errbuflen' in length.
  1247. * It can be NULL; in this case the error cannot be printed.
  1248. *
  1249. * \param errbuflen: length of the buffer that will contains the error. The error message cannot be
  1250. * larger than 'errbuflen - 1' because the last char is reserved for the string terminator.
  1251. *
  1252. * \return It returns '-1' if this function succeeds, '0' otherwise.
  1253. * The address and port corresponding to the given SockAddr are returned back in the buffers 'address'
  1254. * and 'port'.
  1255. * In any case, the returned strings are '0' terminated.
  1256. */
  1257. int sock_getascii_addrport(const struct sockaddr_storage *sockaddr, char *address, int addrlen, char *port, int portlen, int flags, char *errbuf, int errbuflen)
  1258. {
  1259. socklen_t sockaddrlen;
  1260. int retval; /* Variable that keeps the return value; */
  1261. retval = -1;
  1262. #ifdef _WIN32
  1263. if (sockaddr->ss_family == AF_INET)
  1264. sockaddrlen = sizeof(struct sockaddr_in);
  1265. else
  1266. sockaddrlen = sizeof(struct sockaddr_in6);
  1267. #else
  1268. sockaddrlen = sizeof(struct sockaddr_storage);
  1269. #endif
  1270. if ((flags & NI_NUMERICHOST) == 0) /* Check that we want literal names */
  1271. {
  1272. if ((sockaddr->ss_family == AF_INET6) &&
  1273. (memcmp(&((struct sockaddr_in6 *) sockaddr)->sin6_addr, "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0", sizeof(struct in6_addr)) == 0))
  1274. {
  1275. if (address)
  1276. strlcpy(address, SOCKET_NAME_NULL_DAD, addrlen);
  1277. return retval;
  1278. }
  1279. }
  1280. if (getnameinfo((struct sockaddr *) sockaddr, sockaddrlen, address, addrlen, port, portlen, flags) != 0)
  1281. {
  1282. /* If the user wants to receive an error message */
  1283. if (errbuf)
  1284. {
  1285. sock_geterror("getnameinfo(): ", errbuf, errbuflen);
  1286. errbuf[errbuflen - 1] = 0;
  1287. }
  1288. if (address)
  1289. {
  1290. strlcpy(address, SOCKET_NO_NAME_AVAILABLE, addrlen);
  1291. address[addrlen - 1] = 0;
  1292. }
  1293. if (port)
  1294. {
  1295. strlcpy(port, SOCKET_NO_PORT_AVAILABLE, portlen);
  1296. port[portlen - 1] = 0;
  1297. }
  1298. retval = 0;
  1299. }
  1300. return retval;
  1301. }
  1302. /*
  1303. * \brief It translates an address from the 'presentation' form into the 'network' form.
  1304. *
  1305. * This function basically replaces inet_pton(), which does not exist in Winsock because
  1306. * the same result can be obtained by using the getaddrinfo().
  1307. * An additional advantage is that 'Address' can be both a numeric address (e.g. '127.0.0.1',
  1308. * like in inet_pton() ) and a literal name (e.g. 'localhost').
  1309. *
  1310. * This function does the reverse job of sock_getascii_addrport().
  1311. *
  1312. * \param address: a zero-terminated string which contains the name you have to
  1313. * translate. The name can be either literal (e.g. 'localhost') or numeric (e.g. '::1').
  1314. *
  1315. * \param sockaddr: a user-allocated sockaddr_storage structure which will contains the
  1316. * 'network' form of the requested address.
  1317. *
  1318. * \param addr_family: a constant which can assume the following values:
  1319. * - 'AF_INET' if we want to ping an IPv4 host
  1320. * - 'AF_INET6' if we want to ping an IPv6 host
  1321. * - 'AF_UNSPEC' if we do not have preferences about the protocol used to ping the host
  1322. *
  1323. * \param errbuf: a pointer to an user-allocated buffer that will contain the complete
  1324. * error message. This buffer has to be at least 'errbuflen' in length.
  1325. * It can be NULL; in this case the error cannot be printed.
  1326. *
  1327. * \param errbuflen: length of the buffer that will contains the error. The error message cannot be
  1328. * larger than 'errbuflen - 1' because the last char is reserved for the string terminator.
  1329. *
  1330. * \return '-1' if the translation succeeded, '-2' if there was some non critical error, '0'
  1331. * otherwise. In case it fails, the content of the SockAddr variable remains unchanged.
  1332. * A 'non critical error' can occur in case the 'Address' is a literal name, which can be mapped
  1333. * to several network addresses (e.g. 'foo.bar.com' => '10.2.2.2' and '10.2.2.3'). In this case
  1334. * the content of the SockAddr parameter will be the address corresponding to the first mapping.
  1335. *
  1336. * \warning The sockaddr_storage structure MUST be allocated by the user.
  1337. */
  1338. int sock_present2network(const char *address, struct sockaddr_storage *sockaddr, int addr_family, char *errbuf, int errbuflen)
  1339. {
  1340. int retval;
  1341. struct addrinfo *addrinfo;
  1342. struct addrinfo hints;
  1343. memset(&hints, 0, sizeof(hints));
  1344. hints.ai_family = addr_family;
  1345. if ((retval = sock_initaddress(address, "22222" /* fake port */, &hints, &addrinfo, errbuf, errbuflen)) == -1)
  1346. return 0;
  1347. if (addrinfo->ai_family == PF_INET)
  1348. memcpy(sockaddr, addrinfo->ai_addr, sizeof(struct sockaddr_in));
  1349. else
  1350. memcpy(sockaddr, addrinfo->ai_addr, sizeof(struct sockaddr_in6));
  1351. if (addrinfo->ai_next != NULL)
  1352. {
  1353. freeaddrinfo(addrinfo);
  1354. if (errbuf)
  1355. pcap_snprintf(errbuf, errbuflen, "More than one socket requested; using the first one returned");
  1356. return -2;
  1357. }
  1358. freeaddrinfo(addrinfo);
  1359. return -1;
  1360. }