PageRenderTime 41ms CodeModel.GetById 12ms RepoModel.GetById 0ms app.codeStats 0ms

/nbase/nbase_misc.c

https://gitlab.com/g10h4ck/nmap-gsoc2015
C | 954 lines | 536 code | 117 blank | 301 comment | 165 complexity | bb265814ada6d52e8dcd5947875f3dea MD5 | raw file
Possible License(s): BSD-3-Clause, GPL-2.0, Apache-2.0, LGPL-2.0, LGPL-2.1, MIT
  1. /***************************************************************************
  2. * nbase_misc.c -- Some small miscellaneous utility/compatibility *
  3. * functions. *
  4. * *
  5. ***********************IMPORTANT NMAP LICENSE TERMS************************
  6. * *
  7. * The Nmap Security Scanner is (C) 1996-2015 Insecure.Com LLC. Nmap is *
  8. * also a registered trademark of Insecure.Com LLC. This program is free *
  9. * software; you may redistribute and/or modify it under the terms of the *
  10. * GNU General Public License as published by the Free Software *
  11. * Foundation; Version 2 ("GPL"), BUT ONLY WITH ALL OF THE CLARIFICATIONS *
  12. * AND EXCEPTIONS DESCRIBED HEREIN. This guarantees your right to use, *
  13. * modify, and redistribute this software under certain conditions. If *
  14. * you wish to embed Nmap technology into proprietary software, we sell *
  15. * alternative licenses (contact sales@nmap.com). Dozens of software *
  16. * vendors already license Nmap technology such as host discovery, port *
  17. * scanning, OS detection, version detection, and the Nmap Scripting *
  18. * Engine. *
  19. * *
  20. * Note that the GPL places important restrictions on "derivative works", *
  21. * yet it does not provide a detailed definition of that term. To avoid *
  22. * misunderstandings, we interpret that term as broadly as copyright law *
  23. * allows. For example, we consider an application to constitute a *
  24. * derivative work for the purpose of this license if it does any of the *
  25. * following with any software or content covered by this license *
  26. * ("Covered Software"): *
  27. * *
  28. * o Integrates source code from Covered Software. *
  29. * *
  30. * o Reads or includes copyrighted data files, such as Nmap's nmap-os-db *
  31. * or nmap-service-probes. *
  32. * *
  33. * o Is designed specifically to execute Covered Software and parse the *
  34. * results (as opposed to typical shell or execution-menu apps, which will *
  35. * execute anything you tell them to). *
  36. * *
  37. * o Includes Covered Software in a proprietary executable installer. The *
  38. * installers produced by InstallShield are an example of this. Including *
  39. * Nmap with other software in compressed or archival form does not *
  40. * trigger this provision, provided appropriate open source decompression *
  41. * or de-archiving software is widely available for no charge. For the *
  42. * purposes of this license, an installer is considered to include Covered *
  43. * Software even if it actually retrieves a copy of Covered Software from *
  44. * another source during runtime (such as by downloading it from the *
  45. * Internet). *
  46. * *
  47. * o Links (statically or dynamically) to a library which does any of the *
  48. * above. *
  49. * *
  50. * o Executes a helper program, module, or script to do any of the above. *
  51. * *
  52. * This list is not exclusive, but is meant to clarify our interpretation *
  53. * of derived works with some common examples. Other people may interpret *
  54. * the plain GPL differently, so we consider this a special exception to *
  55. * the GPL that we apply to Covered Software. Works which meet any of *
  56. * these conditions must conform to all of the terms of this license, *
  57. * particularly including the GPL Section 3 requirements of providing *
  58. * source code and allowing free redistribution of the work as a whole. *
  59. * *
  60. * As another special exception to the GPL terms, Insecure.Com LLC grants *
  61. * permission to link the code of this program with any version of the *
  62. * OpenSSL library which is distributed under a license identical to that *
  63. * listed in the included docs/licenses/OpenSSL.txt file, and distribute *
  64. * linked combinations including the two. *
  65. * *
  66. * Any redistribution of Covered Software, including any derived works, *
  67. * must obey and carry forward all of the terms of this license, including *
  68. * obeying all GPL rules and restrictions. For example, source code of *
  69. * the whole work must be provided and free redistribution must be *
  70. * allowed. All GPL references to "this License", are to be treated as *
  71. * including the terms and conditions of this license text as well. *
  72. * *
  73. * Because this license imposes special exceptions to the GPL, Covered *
  74. * Work may not be combined (even as part of a larger work) with plain GPL *
  75. * software. The terms, conditions, and exceptions of this license must *
  76. * be included as well. This license is incompatible with some other open *
  77. * source licenses as well. In some cases we can relicense portions of *
  78. * Nmap or grant special permissions to use it in other open source *
  79. * software. Please contact fyodor@nmap.org with any such requests. *
  80. * Similarly, we don't incorporate incompatible open source software into *
  81. * Covered Software without special permission from the copyright holders. *
  82. * *
  83. * If you have any questions about the licensing restrictions on using *
  84. * Nmap in other works, are happy to help. As mentioned above, we also *
  85. * offer alternative license to integrate Nmap into proprietary *
  86. * applications and appliances. These contracts have been sold to dozens *
  87. * of software vendors, and generally include a perpetual license as well *
  88. * as providing for priority support and updates. They also fund the *
  89. * continued development of Nmap. Please email sales@nmap.com for further *
  90. * information. *
  91. * *
  92. * If you have received a written license agreement or contract for *
  93. * Covered Software stating terms other than these, you may choose to use *
  94. * and redistribute Covered Software under those terms instead of these. *
  95. * *
  96. * Source is provided to this software because we believe users have a *
  97. * right to know exactly what a program is going to do before they run it. *
  98. * This also allows you to audit the software for security holes. *
  99. * *
  100. * Source code also allows you to port Nmap to new platforms, fix bugs, *
  101. * and add new features. You are highly encouraged to send your changes *
  102. * to the dev@nmap.org mailing list for possible incorporation into the *
  103. * main distribution. By sending these changes to Fyodor or one of the *
  104. * Insecure.Org development mailing lists, or checking them into the Nmap *
  105. * source code repository, it is understood (unless you specify otherwise) *
  106. * that you are offering the Nmap Project (Insecure.Com LLC) the *
  107. * unlimited, non-exclusive right to reuse, modify, and relicense the *
  108. * code. Nmap will always be available Open Source, but this is important *
  109. * because the inability to relicense code has caused devastating problems *
  110. * for other Free Software projects (such as KDE and NASM). We also *
  111. * occasionally relicense the code to third parties as discussed above. *
  112. * If you wish to specify special license conditions of your *
  113. * contributions, just say so when you send them. *
  114. * *
  115. * This program is distributed in the hope that it will be useful, but *
  116. * WITHOUT ANY WARRANTY; without even the implied warranty of *
  117. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the Nmap *
  118. * license file for more details (it's in a COPYING file included with *
  119. * Nmap, and also available from https://svn.nmap.org/nmap/COPYING) *
  120. * *
  121. ***************************************************************************/
  122. /* $Id$ */
  123. #include "nbase.h"
  124. #ifndef WIN32
  125. #include <errno.h>
  126. #ifndef errno
  127. extern int errno;
  128. #endif
  129. #else
  130. #include <winsock2.h>
  131. #endif
  132. #include <limits.h>
  133. #include <stdio.h>
  134. #include "nbase_ipv6.h"
  135. #include "nbase_crc32ct.h"
  136. #include <assert.h>
  137. #include <fcntl.h>
  138. #ifdef WIN32
  139. #include <conio.h>
  140. #endif
  141. #ifndef INET6_ADDRSTRLEN
  142. #define INET6_ADDRSTRLEN 46
  143. #endif
  144. /* Returns the UNIX/Windows errno-equivalent. Note that the Windows
  145. call is socket/networking specific. The windows error number
  146. returned is like WSAMSGSIZE, but nbase.h includes #defines to
  147. correlate many of the common UNIX errors with their closest Windows
  148. equivalents. So you can use EMSGSIZE or EINTR. */
  149. int socket_errno() {
  150. #ifdef WIN32
  151. return WSAGetLastError();
  152. #else
  153. return errno;
  154. #endif
  155. }
  156. /* We can't just use strerror to get socket errors on Windows because it has
  157. its own set of error codes: WSACONNRESET not ECONNRESET for example. This
  158. function will do the right thing on Windows. Call it like
  159. socket_strerror(socket_errno())
  160. */
  161. char *socket_strerror(int errnum) {
  162. #ifdef WIN32
  163. static char buffer[128];
  164. FormatMessageA(FORMAT_MESSAGE_FROM_SYSTEM |
  165. FORMAT_MESSAGE_IGNORE_INSERTS |
  166. FORMAT_MESSAGE_MAX_WIDTH_MASK,
  167. 0, errnum, 0, buffer, sizeof(buffer), NULL);
  168. return buffer;
  169. #else
  170. return strerror(errnum);
  171. #endif
  172. }
  173. /* Compares two sockaddr_storage structures with a return value like strcmp.
  174. First the address families are compared, then the addresses if the families
  175. are equal. The structures must be real full-length sockaddr_storage
  176. structures, not something shorter like sockaddr_in. */
  177. int sockaddr_storage_cmp(const struct sockaddr_storage *a,
  178. const struct sockaddr_storage *b) {
  179. if (a->ss_family < b->ss_family)
  180. return -1;
  181. else if (a->ss_family > b->ss_family)
  182. return 1;
  183. if (a->ss_family == AF_INET) {
  184. struct sockaddr_in *sin_a = (struct sockaddr_in *) a;
  185. struct sockaddr_in *sin_b = (struct sockaddr_in *) b;
  186. if (sin_a->sin_addr.s_addr < sin_b->sin_addr.s_addr)
  187. return -1;
  188. else if (sin_a->sin_addr.s_addr > sin_b->sin_addr.s_addr)
  189. return 1;
  190. else
  191. return 0;
  192. } else if (a->ss_family == AF_INET6) {
  193. struct sockaddr_in6 *sin6_a = (struct sockaddr_in6 *) a;
  194. struct sockaddr_in6 *sin6_b = (struct sockaddr_in6 *) b;
  195. return memcmp(sin6_a->sin6_addr.s6_addr, sin6_b->sin6_addr.s6_addr,
  196. sizeof(sin6_a->sin6_addr.s6_addr));
  197. } else {
  198. assert(0);
  199. }
  200. return 0; /* Not reached */
  201. }
  202. int sockaddr_storage_equal(const struct sockaddr_storage *a,
  203. const struct sockaddr_storage *b) {
  204. return sockaddr_storage_cmp(a, b) == 0;
  205. }
  206. /* This function is an easier version of inet_ntop because you don't
  207. need to pass a dest buffer. Instead, it returns a static buffer that
  208. you can use until the function is called again (by the same or another
  209. thread in the process). If there is a weird error (like sslen being
  210. too short) then NULL will be returned. */
  211. const char *inet_ntop_ez(const struct sockaddr_storage *ss, size_t sslen) {
  212. const struct sockaddr_in *sin = (struct sockaddr_in *) ss;
  213. static char str[INET6_ADDRSTRLEN];
  214. #if HAVE_IPV6
  215. const struct sockaddr_in6 *sin6 = (struct sockaddr_in6 *) ss;
  216. #endif
  217. str[0] = '\0';
  218. if (sin->sin_family == AF_INET) {
  219. if (sslen < sizeof(struct sockaddr_in))
  220. return NULL;
  221. return inet_ntop(AF_INET, &sin->sin_addr, str, sizeof(str));
  222. }
  223. #if HAVE_IPV6
  224. else if(sin->sin_family == AF_INET6) {
  225. if (sslen < sizeof(struct sockaddr_in6))
  226. return NULL;
  227. return inet_ntop(AF_INET6, &sin6->sin6_addr, str, sizeof(str));
  228. }
  229. #endif
  230. //Some laptops report the ip and address family of disabled wifi cards as null
  231. //so yes, we will hit this sometimes.
  232. return NULL;
  233. }
  234. /* Create a new socket inheritable by subprocesses. On non-Windows systems it's
  235. just a normal socket. */
  236. int inheritable_socket(int af, int style, int protocol) {
  237. #ifdef WIN32
  238. /* WSASocket is just like socket, except that the sockets it creates are
  239. inheritable by subprocesses (such as are created by CreateProcess), while
  240. those created by socket are not. */
  241. return WSASocket(af, style, protocol, NULL, 0, 0);
  242. #else
  243. return socket(af, style, protocol);
  244. #endif
  245. }
  246. /* The dup function on Windows works only on file descriptors, not socket
  247. handles. This function accomplishes the same thing for sockets. */
  248. int dup_socket(int sd) {
  249. #ifdef WIN32
  250. HANDLE copy;
  251. if (DuplicateHandle(GetCurrentProcess(), (HANDLE) sd,
  252. GetCurrentProcess(), &copy,
  253. 0, FALSE, DUPLICATE_SAME_ACCESS) == 0) {
  254. return -1;
  255. }
  256. return (int) copy;
  257. #else
  258. return dup(sd);
  259. #endif
  260. }
  261. int unblock_socket(int sd) {
  262. #ifdef WIN32
  263. unsigned long one = 1;
  264. if (sd != 501) /* Hack related to WinIP Raw Socket support */
  265. ioctlsocket(sd, FIONBIO, &one);
  266. return 0;
  267. #else
  268. int options;
  269. /* Unblock our socket to prevent recvfrom from blocking forever on certain
  270. * target ports. */
  271. options = fcntl(sd, F_GETFL);
  272. if (options == -1)
  273. return -1;
  274. return fcntl(sd, F_SETFL, O_NONBLOCK | options);
  275. #endif /* WIN32 */
  276. }
  277. /* Convert a socket to blocking mode */
  278. int block_socket(int sd) {
  279. #ifdef WIN32
  280. unsigned long options = 0;
  281. if (sd != 501)
  282. ioctlsocket(sd, FIONBIO, &options);
  283. return 0;
  284. #else
  285. int options;
  286. options = fcntl(sd, F_GETFL);
  287. if (options == -1)
  288. return -1;
  289. return fcntl(sd, F_SETFL, (~O_NONBLOCK) & options);
  290. #endif
  291. }
  292. /* Use the SO_BINDTODEVICE sockopt to bind with a specific interface (Linux
  293. only). Pass NULL or an empty string to remove device binding. */
  294. int socket_bindtodevice(int sd, const char *device) {
  295. char padded[sizeof(int)];
  296. size_t len;
  297. len = strlen(device) + 1;
  298. /* In Linux 2.6.20 and earlier, there is a bug in SO_BINDTODEVICE that causes
  299. EINVAL to be returned if the optlen < sizeof(int); this happens for example
  300. with the interface names "" and "lo". Pad the string with null characters
  301. so it is above this limit if necessary.
  302. http://article.gmane.org/gmane.linux.network/71887
  303. http://article.gmane.org/gmane.linux.network/72216 */
  304. if (len < sizeof(padded)) {
  305. /* We rely on strncpy padding with nulls here. */
  306. strncpy(padded, device, sizeof(padded));
  307. device = padded;
  308. len = sizeof(padded);
  309. }
  310. #ifdef SO_BINDTODEVICE
  311. /* Linux-specific sockopt asking to use a specific interface. See socket(7). */
  312. if (setsockopt(sd, SOL_SOCKET, SO_BINDTODEVICE, device, len) < 0)
  313. return 0;
  314. #endif
  315. return 1;
  316. }
  317. /* Convert a time specification into a count of seconds. A time specification is
  318. * a non-negative real number, possibly followed by a units suffix. The suffixes
  319. * are "ms" for milliseconds, "s" for seconds, "m" for minutes, or "h" for
  320. * hours. Seconds is the default with no suffix. -1 is returned if the string
  321. * can't be parsed. */
  322. double tval2secs(const char *tspec) {
  323. double d;
  324. char *tail;
  325. errno = 0;
  326. d = strtod(tspec, &tail);
  327. if (*tspec == '\0' || errno != 0)
  328. return -1;
  329. if (strcasecmp(tail, "ms") == 0)
  330. return d / 1000.0;
  331. else if (*tail == '\0' || strcasecmp(tail, "s") == 0)
  332. return d;
  333. else if (strcasecmp(tail, "m") == 0)
  334. return d * 60.0;
  335. else if (strcasecmp(tail, "h") == 0)
  336. return d * 60.0 * 60.0;
  337. else
  338. return -1;
  339. }
  340. long tval2msecs(const char *tspec) {
  341. double s, ms;
  342. s = tval2secs(tspec);
  343. if (s == -1)
  344. return -1;
  345. ms = s * 1000.0;
  346. if (ms > LONG_MAX || ms < LONG_MIN)
  347. return -1;
  348. return (long) ms;
  349. }
  350. /* Returns the unit portion of a time specification (such as "ms", "s", "m", or
  351. "h"). Returns NULL if there was a parsing error or no unit is present. */
  352. const char *tval_unit(const char *tspec) {
  353. double d;
  354. char *tail;
  355. errno = 0;
  356. d = strtod(tspec, &tail);
  357. /* Avoid GCC 4.6 error "variable 'd' set but not used
  358. [-Wunused-but-set-variable]". */
  359. (void) d;
  360. if (*tspec == '\0' || errno != 0 || *tail == '\0')
  361. return NULL;
  362. return tail;
  363. }
  364. /* A replacement for select on Windows that allows selecting on stdin
  365. * (file descriptor 0) and selecting on zero file descriptors (just for
  366. * the timeout). Plain Windows select doesn't work on non-sockets like
  367. * stdin and returns an error if no file descriptors were given, because
  368. * they were NULL or empty. This only works for sockets and stdin; if
  369. * you have a descriptor referring to a normal open file in the set,
  370. * Windows will return WSAENOTSOCK. */
  371. int fselect(int s, fd_set *rmaster, fd_set *wmaster, fd_set *emaster, struct timeval *tv)
  372. {
  373. #ifdef WIN32
  374. static int stdin_thread_started = 0;
  375. int fds_ready = 0;
  376. int iter = -1, i;
  377. struct timeval stv;
  378. fd_set rset, wset, eset;
  379. /* Figure out whether there are any FDs in the sets, as @$@!$# Windows
  380. returns WSAINVAL (10022) if you call a select() with no FDs, even though
  381. the Linux man page says that doing so is a good, reasonably portable way
  382. to sleep with subsecond precision. Sigh. */
  383. for(i = s; i > STDIN_FILENO; i--) {
  384. if ((rmaster != NULL && FD_ISSET(i, rmaster))
  385. || (wmaster != NULL && FD_ISSET(i, wmaster))
  386. || (emaster != NULL && FD_ISSET(i, emaster)))
  387. break;
  388. s--;
  389. }
  390. /* Handle the case where stdin is not being read from. */
  391. if (rmaster == NULL || !FD_ISSET(STDIN_FILENO, rmaster)) {
  392. if (s > 0) {
  393. /* Do a normal select. */
  394. return select(s, rmaster, wmaster, emaster, tv);
  395. } else {
  396. /* No file descriptors given. Just sleep. */
  397. if (tv == NULL) {
  398. /* Sleep forever. */
  399. while (1)
  400. sleep(10000);
  401. } else {
  402. usleep(tv->tv_sec * 1000000UL + tv->tv_usec);
  403. return 0;
  404. }
  405. }
  406. }
  407. /* This is a hack for Windows, which doesn't allow select()ing on
  408. * non-sockets (like stdin). We remove stdin from the fd_set and
  409. * loop while select()ing on everything else, with a timeout of
  410. * 125ms. Then we check if stdin is ready and increment fds_ready
  411. * and set stdin in rmaster if it looks good. We just keep looping
  412. * until we have something or it times out.
  413. */
  414. /* nbase_winunix.c has all the nasty details behind checking if
  415. * stdin has input. It involves a background thread, which we start
  416. * now if necessary. */
  417. if (!stdin_thread_started) {
  418. int ret = win_stdin_start_thread();
  419. assert(ret != 0);
  420. stdin_thread_started = 1;
  421. }
  422. FD_CLR(STDIN_FILENO, rmaster);
  423. if (tv) {
  424. int usecs = (tv->tv_sec * 1000000) + tv->tv_usec;
  425. iter = usecs / 125000;
  426. if (usecs % 125000)
  427. iter++;
  428. }
  429. FD_ZERO(&rset);
  430. FD_ZERO(&wset);
  431. FD_ZERO(&eset);
  432. while (!fds_ready && iter) {
  433. stv.tv_sec = 0;
  434. stv.tv_usec = 125000;
  435. if (rmaster)
  436. rset = *rmaster;
  437. if (wmaster)
  438. wset = *wmaster;
  439. if (emaster)
  440. eset = *emaster;
  441. fds_ready = 0;
  442. /* selecting on anything other than stdin? */
  443. if (s > 1)
  444. fds_ready = select(s, &rset, &wset, &eset, &stv);
  445. else
  446. usleep(stv.tv_sec * 1000000UL + stv.tv_usec);
  447. if (fds_ready > -1 && win_stdin_ready()) {
  448. FD_SET(STDIN_FILENO, &rset);
  449. fds_ready++;
  450. }
  451. if (tv)
  452. iter--;
  453. }
  454. if (rmaster)
  455. *rmaster = rset;
  456. if (wmaster)
  457. *wmaster = wset;
  458. if (emaster)
  459. *emaster = eset;
  460. return fds_ready;
  461. #else
  462. return select(s, rmaster, wmaster, emaster, tv);
  463. #endif
  464. }
  465. /*
  466. * CRC32 Cyclic Redundancy Check
  467. *
  468. * From: http://www.ietf.org/rfc/rfc1952.txt
  469. *
  470. * Copyright (c) 1996 L. Peter Deutsch
  471. *
  472. * Permission is granted to copy and distribute this document for any
  473. * purpose and without charge, including translations into other
  474. * languages and incorporation into compilations, provided that the
  475. * copyright notice and this notice are preserved, and that any
  476. * substantive changes or deletions from the original are clearly
  477. * marked.
  478. *
  479. */
  480. /* Table of CRCs of all 8-bit messages. */
  481. static unsigned long crc_table[256];
  482. /* Flag: has the table been computed? Initially false. */
  483. static int crc_table_computed = 0;
  484. /* Make the table for a fast CRC. */
  485. static void make_crc_table(void)
  486. {
  487. unsigned long c;
  488. int n, k;
  489. for (n = 0; n < 256; n++) {
  490. c = (unsigned long) n;
  491. for (k = 0; k < 8; k++) {
  492. if (c & 1) {
  493. c = 0xedb88320L ^ (c >> 1);
  494. } else {
  495. c = c >> 1;
  496. }
  497. }
  498. crc_table[n] = c;
  499. }
  500. crc_table_computed = 1;
  501. }
  502. /*
  503. Update a running crc with the bytes buf[0..len-1] and return
  504. the updated crc. The crc should be initialized to zero. Pre- and
  505. post-conditioning (one's complement) is performed within this
  506. function so it shouldn't be done by the caller. Usage example:
  507. unsigned long crc = 0L;
  508. while (read_buffer(buffer, length) != EOF) {
  509. crc = update_crc(crc, buffer, length);
  510. }
  511. if (crc != original_crc) error();
  512. */
  513. static unsigned long update_crc(unsigned long crc,
  514. unsigned char *buf, int len)
  515. {
  516. unsigned long c = crc ^ 0xffffffffL;
  517. int n;
  518. if (!crc_table_computed)
  519. make_crc_table();
  520. for (n = 0; n < len; n++) {
  521. c = crc_table[(c ^ buf[n]) & 0xff] ^ (c >> 8);
  522. }
  523. return c ^ 0xffffffffL;
  524. }
  525. /* Return the CRC of the bytes buf[0..len-1]. */
  526. unsigned long nbase_crc32(unsigned char *buf, int len)
  527. {
  528. return update_crc(0L, buf, len);
  529. }
  530. /*
  531. * CRC-32C (Castagnoli) Cyclic Redundancy Check.
  532. * Taken straight from Appendix C of RFC 4960 (SCTP), with the difference that
  533. * the remainder register (crc32) is initialized to 0xffffffffL rather than ~0L,
  534. * for correct operation on platforms where unsigned long is longer than 32
  535. * bits.
  536. */
  537. /* Return the CRC-32C of the bytes buf[0..len-1] */
  538. unsigned long nbase_crc32c(unsigned char *buf, int len)
  539. {
  540. int i;
  541. unsigned long crc32 = 0xffffffffL;
  542. unsigned long result;
  543. unsigned char byte0, byte1, byte2, byte3;
  544. for (i = 0; i < len; i++) {
  545. CRC32C(crc32, buf[i]);
  546. }
  547. result = ~crc32;
  548. /* result now holds the negated polynomial remainder;
  549. * since the table and algorithm is "reflected" [williams95].
  550. * That is, result has the same value as if we mapped the message
  551. * to a polynomial, computed the host-bit-order polynomial
  552. * remainder, performed final negation, then did an end-for-end
  553. * bit-reversal.
  554. * Note that a 32-bit bit-reversal is identical to four inplace
  555. * 8-bit reversals followed by an end-for-end byteswap.
  556. * In other words, the bytes of each bit are in the right order,
  557. * but the bytes have been byteswapped. So we now do an explicit
  558. * byteswap. On a little-endian machine, this byteswap and
  559. * the final ntohl cancel out and could be elided.
  560. */
  561. byte0 = result & 0xff;
  562. byte1 = (result >> 8) & 0xff;
  563. byte2 = (result >> 16) & 0xff;
  564. byte3 = (result >> 24) & 0xff;
  565. crc32 = ((byte0 << 24) | (byte1 << 16) | (byte2 << 8) | byte3);
  566. return crc32;
  567. }
  568. /*
  569. * Adler32 Checksum Calculation.
  570. * Taken straight from RFC 2960 (SCTP).
  571. */
  572. #define ADLER32_BASE 65521 /* largest prime smaller than 65536 */
  573. /*
  574. * Update a running Adler-32 checksum with the bytes buf[0..len-1]
  575. * and return the updated checksum. The Adler-32 checksum should
  576. * be initialized to 1.
  577. */
  578. static unsigned long update_adler32(unsigned long adler,
  579. unsigned char *buf, int len)
  580. {
  581. unsigned long s1 = adler & 0xffff;
  582. unsigned long s2 = (adler >> 16) & 0xffff;
  583. int n;
  584. for (n = 0; n < len; n++) {
  585. s1 = (s1 + buf[n]) % ADLER32_BASE;
  586. s2 = (s2 + s1) % ADLER32_BASE;
  587. }
  588. return (s2 << 16) + s1;
  589. }
  590. /* Return the Adler32 of the bytes buf[0..len-1] */
  591. unsigned long nbase_adler32(unsigned char *buf, int len)
  592. {
  593. return update_adler32(1L, buf, len);
  594. }
  595. #undef ADLER32_BASE
  596. /* This function returns a string containing the hexdump of the supplied
  597. * buffer. It uses current locale to determine if a character is printable or
  598. * not. It prints 73char+\n wide lines like these:
  599. 0000 e8 60 65 86 d7 86 6d 30 35 97 54 87 ff 67 05 9e .`e...m05.T..g..
  600. 0010 07 5a 98 c0 ea ad 50 d2 62 4f 7b ff e1 34 f8 fc .Z....P.bO{..4..
  601. 0020 c4 84 0a 6a 39 ad 3c 10 63 b2 22 c4 24 40 f4 b1 ...j9.<.c.".$@..
  602. * The lines look basically like Wireshark's hex dump.
  603. * WARNING: This function returns a pointer to a DYNAMICALLY allocated buffer
  604. * that the caller is supposed to free().
  605. * */
  606. char *hexdump(const u8 *cp, u32 length){
  607. static char asciify[257]; /* Stores character table */
  608. int asc_init=0; /* Flag to generate table only once */
  609. u32 i=0, hex=0, asc=0; /* Array indexes */
  610. u32 line_count=0; /* For byte count at line start */
  611. char *current_line=NULL; /* Current line to write */
  612. char *buffer=NULL; /* Dynamic buffer we return */
  613. #define LINE_LEN 74 /* Length of printed line */
  614. char line2print[LINE_LEN]; /* Stores current line */
  615. char printbyte[16]; /* For byte conversion */
  616. int bytes2alloc; /* For buffer */
  617. memset(line2print, ' ', LINE_LEN); /* We fill the line with spaces */
  618. /* On the first run, generate a list of nice printable characters
  619. * (according to current locale) */
  620. if( asc_init==0){
  621. asc_init=1;
  622. for(i=0; i<256; i++){
  623. if( isalnum(i) || isdigit(i) || ispunct(i) ){ asciify[i]=i; }
  624. else{ asciify[i]='.'; }
  625. }
  626. }
  627. /* Allocate enough space to print the hex dump */
  628. bytes2alloc=(length%16==0)? (1 + LINE_LEN * (length/16)) : (1 + LINE_LEN * (1+(length/16))) ;
  629. buffer=(char *)safe_zalloc(bytes2alloc);
  630. current_line=buffer;
  631. #define HEX_START 7
  632. #define ASC_START 57
  633. /* This is how or line looks like.
  634. 0000 00 01 02 03 04 05 06 07 08 09 0a 0b 0c 0d 0e 0f .`e...m05.T..g..[\n]
  635. 01234567890123456789012345678901234567890123456789012345678901234567890123
  636. 0 1 2 3 4 5 6 7
  637. ^ ^ ^
  638. | | |
  639. HEX_START ASC_START Newline
  640. */
  641. i=0;
  642. while( i < length ){
  643. memset(line2print, ' ', LINE_LEN); /* Fill line with spaces */
  644. snprintf(line2print, sizeof(line2print), "%04x", (16*line_count++) % 0xFFFF); /* Add line No.*/
  645. line2print[4]=' '; /* Replace the '\0' inserted by snprintf() with a space */
  646. hex=HEX_START; asc=ASC_START;
  647. do { /* Print 16 bytes in both hex and ascii */
  648. if (i%16 == 8) hex++; /* Insert space every 8 bytes */
  649. snprintf(printbyte, sizeof(printbyte), "%02x", cp[i]);/* First print the hex number */
  650. line2print[hex++]=printbyte[0];
  651. line2print[hex++]=printbyte[1];
  652. line2print[hex++]=' ';
  653. line2print[asc++]=asciify[ cp[i] ]; /* Then print its ASCII equivalent */
  654. i++;
  655. } while (i < length && i%16 != 0);
  656. /* Copy line to output buffer */
  657. line2print[LINE_LEN-1]='\n';
  658. memcpy(current_line, line2print, LINE_LEN);
  659. current_line += LINE_LEN;
  660. }
  661. buffer[bytes2alloc-1]='\0';
  662. return buffer;
  663. } /* End of hexdump() */
  664. /* This is like strtol or atoi, but it allows digits only. No whitespace, sign,
  665. or radix prefix. */
  666. long parse_long(const char *s, char **tail)
  667. {
  668. if (!isdigit((int) (unsigned char) *s)) {
  669. *tail = (char *) s;
  670. return 0;
  671. }
  672. return strtol(s, (char **) tail, 10);
  673. }
  674. /* This function takes a byte count and stores a short ascii equivalent
  675. in the supplied buffer. Eg: 0.122MB, 10.322Kb or 128B. */
  676. char *format_bytecount(unsigned long long bytes, char *buf, size_t buflen) {
  677. assert(buf != NULL);
  678. if (bytes < 1000)
  679. Snprintf(buf, buflen, "%uB", (unsigned int) bytes);
  680. else if (bytes < 1000000)
  681. Snprintf(buf, buflen, "%.3fKB", bytes / 1000.0);
  682. else
  683. Snprintf(buf, buflen, "%.3fMB", bytes / 1000000.0);
  684. return buf;
  685. }
  686. /* Compare a canonical option name (e.g. "max-scan-delay") with a
  687. user-generated option such as "max_scan_delay" and returns 0 if the
  688. two values are considered equivalent (for example, - and _ are
  689. considered to be the same), nonzero otherwise. */
  690. int optcmp(const char *a, const char *b) {
  691. while(*a && *b) {
  692. if (*a == '_' || *a == '-') {
  693. if (*b != '_' && *b != '-')
  694. return 1;
  695. }
  696. else if (*a != *b)
  697. return 1;
  698. a++; b++;
  699. }
  700. if (*a || *b)
  701. return 1;
  702. return 0;
  703. }
  704. /* Returns one if the file pathname given exists, is not a directory and
  705. * is readable by the executing process. Returns two if it is readable
  706. * and is a directory. Otherwise returns 0. */
  707. int file_is_readable(const char *pathname) {
  708. char *pathname_buf = strdup(pathname);
  709. int status = 0;
  710. struct stat st;
  711. #ifdef WIN32
  712. // stat on windows only works for "dir_name" not for "dir_name/" or "dir_name\\"
  713. int pathname_len = strlen(pathname_buf);
  714. char last_char = pathname_buf[pathname_len - 1];
  715. if( last_char == '/'
  716. || last_char == '\\')
  717. pathname_buf[pathname_len - 1] = '\0';
  718. #endif
  719. if (stat(pathname_buf, &st) == -1)
  720. status = 0;
  721. else if (access(pathname_buf, R_OK) != -1)
  722. status = S_ISDIR(st.st_mode) ? 2 : 1;
  723. free(pathname_buf);
  724. return status;
  725. }
  726. #if HAVE_PROC_SELF_EXE
  727. static char *executable_path_proc_self_exe(void) {
  728. char buf[1024];
  729. char *path;
  730. int n;
  731. n = readlink("/proc/self/exe", buf, sizeof(buf));
  732. if (n < 0 || n >= sizeof(buf))
  733. return NULL;
  734. path = (char *) safe_malloc(n + 1);
  735. /* readlink does not null-terminate. */
  736. memcpy(path, buf, n);
  737. path[n] = '\0';
  738. return path;
  739. }
  740. #endif
  741. #if HAVE_MACH_O_DYLD_H
  742. #include <mach-o/dyld.h>
  743. /* See the dyld(3) man page on OS X. */
  744. static char *executable_path_NSGetExecutablePath(void) {
  745. char buf[1024];
  746. uint32_t size;
  747. size = sizeof(buf);
  748. if (_NSGetExecutablePath(buf, &size) == 0)
  749. return strdup(buf);
  750. else
  751. return NULL;
  752. }
  753. #endif
  754. #if WIN32
  755. static char *executable_path_GetModuleFileName(void) {
  756. char buf[1024];
  757. int n;
  758. n = GetModuleFileName(GetModuleHandle(0), buf, sizeof(buf));
  759. if (n <= 0 || n >= sizeof(buf))
  760. return NULL;
  761. return strdup(buf);
  762. }
  763. #endif
  764. static char *executable_path_argv0(const char *argv0) {
  765. if (argv0 == NULL)
  766. return NULL;
  767. /* We can get the path from argv[0] if it contains a directory separator.
  768. (Otherwise it was looked up in $PATH). */
  769. if (strchr(argv0, '/') != NULL)
  770. return strdup(argv0);
  771. #if WIN32
  772. if (strchr(argv0, '\\') != NULL)
  773. return strdup(argv0);
  774. #endif
  775. return NULL;
  776. }
  777. char *executable_path(const char *argv0) {
  778. char *path;
  779. path = NULL;
  780. #if HAVE_PROC_SELF_EXE
  781. if (path == NULL)
  782. path = executable_path_proc_self_exe();
  783. #endif
  784. #if HAVE_MACH_O_DYLD_H
  785. if (path == NULL)
  786. path = executable_path_NSGetExecutablePath();
  787. #endif
  788. #if WIN32
  789. if (path == NULL)
  790. path = executable_path_GetModuleFileName();
  791. #endif
  792. if (path == NULL)
  793. path = executable_path_argv0(argv0);
  794. return path;
  795. }
  796. int sockaddr_storage_inet_pton(const char * ip_str, struct sockaddr_storage * addr)
  797. {
  798. struct sockaddr_in * addrv4p = (struct sockaddr_in *) addr;
  799. #if HAVE_IPV6
  800. struct sockaddr_in6 * addrv6p = (struct sockaddr_in6 *) addr;
  801. if ( 1 == inet_pton(AF_INET6, ip_str, &(addrv6p->sin6_addr)) )
  802. {
  803. addr->ss_family = AF_INET6;
  804. return 1;
  805. }
  806. #endif // HAVE_IPV6
  807. if ( 1 == inet_pton(AF_INET, ip_str, &(addrv4p->sin_addr)) )
  808. {
  809. addr->ss_family = AF_INET;
  810. return 1;
  811. }
  812. return 0;
  813. }
  814. const char *sockaddr_storage_iptop(const struct sockaddr_storage * addr, char * dst)
  815. {
  816. switch (addr->ss_family){
  817. case AF_INET:
  818. {
  819. const struct sockaddr_in * ipv4_ptr = (const struct sockaddr_in *) addr;
  820. return inet_ntop(addr->ss_family, &(ipv4_ptr->sin_addr), dst, INET_ADDRSTRLEN);
  821. }
  822. #if HAVE_IPV6
  823. case AF_INET6:
  824. {
  825. const struct sockaddr_in6 * addrv6p = (struct sockaddr_in6 *) addr;
  826. return inet_ntop(addr->ss_family, &(addrv6p->sin6_addr), dst, INET6_ADDRSTRLEN);
  827. }
  828. #endif
  829. default:
  830. {
  831. return NULL;
  832. }}
  833. }