utils.c 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408
  1. /* $Id$ */
  2. /*
  3. * Copyright (c) 2001-2010 Aaron Turner <aturner at synfin dot net>
  4. * Copyright (c) 2013-2018 Fred Klassen <tcpreplay at appneta dot com> - AppNeta
  5. *
  6. * The Tcpreplay Suite of tools is free software: you can redistribute it
  7. * and/or modify it under the terms of the GNU General Public License as
  8. * published by the Free Software Foundation, either version 3 of the
  9. * License, or with the authors permission any later version.
  10. *
  11. * The Tcpreplay Suite is distributed in the hope that it will be useful,
  12. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  14. * GNU General Public License for more details.
  15. *
  16. * You should have received a copy of the GNU General Public License
  17. * along with the Tcpreplay Suite. If not, see <http://www.gnu.org/licenses/>.
  18. */
  19. #include "config.h"
  20. #include "defines.h"
  21. #include "common.h"
  22. #include <string.h>
  23. #include <stdlib.h>
  24. #include <errno.h>
  25. #include <ctype.h>
  26. #include <unistd.h>
  27. #ifdef HAVE_SYS_IOCTL_H
  28. #include <sys/ioctl.h>
  29. #endif
  30. #ifdef DEBUG
  31. extern int debug;
  32. #endif
  33. /**
  34. * this is wrapped up in a #define safe_malloc
  35. * This function, detects failures to malloc memory and zeros out the
  36. * memory before returning
  37. */
  38. void *
  39. _our_safe_malloc(size_t len, const char *funcname, const int line, const char *file)
  40. {
  41. u_char *ptr;
  42. if ((ptr = malloc(len)) == NULL) {
  43. fprintf(stderr, "ERROR in %s:%s() line %d: Unable to malloc() %zu bytes/n",
  44. file, funcname, line, len);
  45. exit(-1);
  46. }
  47. /* zero memory */
  48. memset(ptr, 0, len);
  49. /* wrapped inside an #ifdef for better performance */
  50. dbgx(5, "Malloc'd %zu bytes in %s:%s() line %d", len, file, funcname, line);
  51. return (void *)ptr;
  52. }
  53. /**
  54. * this is wrapped up in a #define safe_realloc
  55. * This function, detects failures to realloc memory and zeros
  56. * out the NEW memory if len > current len. As always, remember
  57. * to use it as:
  58. * ptr = safe_realloc(ptr, size)
  59. */
  60. void *
  61. _our_safe_realloc(void *ptr, size_t len, const char *funcname, const int line, const char *file)
  62. {
  63. if ((ptr = realloc(ptr, len)) == NULL) {
  64. fprintf(stderr, "ERROR: in %s:%s() line %d: Unable to remalloc() buffer to %zu bytes", file, funcname, line, len);
  65. exit(-1);
  66. }
  67. dbgx(5, "Remalloc'd buffer to %zu bytes in %s:%s() line %d", len, file, funcname, line);
  68. return ptr;
  69. }
  70. /**
  71. * this is wrapped up in a #define safe_strdup
  72. * This function, detects failures to realloc memory
  73. */
  74. char *
  75. _our_safe_strdup(const char *str, const char *funcname, const int line, const char *file)
  76. {
  77. char *newstr;
  78. if ((newstr = (char *)malloc(strlen(str) + 1)) == NULL) {
  79. fprintf(stderr, "ERROR in %s:%s() line %d: Unable to strdup() %zu bytes\n", file, funcname, line, strlen(str));
  80. exit(-1);
  81. }
  82. memcpy(newstr, str, strlen(str) + 1);
  83. return newstr;
  84. }
  85. /**
  86. * calls free and sets to NULL.
  87. */
  88. void
  89. _our_safe_free(void *ptr, const char *funcname, const int line, const char *file)
  90. {
  91. assert(funcname);
  92. assert(line);
  93. assert(file);
  94. if (ptr == NULL)
  95. return;
  96. free(ptr);
  97. }
  98. /**
  99. * get next packet in pcap file
  100. */
  101. u_char *_our_safe_pcap_next(pcap_t *pcap, struct pcap_pkthdr *pkthdr,
  102. const char *funcname, const int line, const char *file)
  103. {
  104. u_char *pktdata = (u_char *)pcap_next(pcap, pkthdr);
  105. if (pktdata) {
  106. if (pkthdr->len > MAXPACKET) {
  107. fprintf(stderr, "safe_pcap_next ERROR: Invalid packet length in %s:%s() line %d: %u is greater than maximum %u\n",
  108. file, funcname, line, pkthdr->len, MAXPACKET);
  109. exit(-1);
  110. }
  111. if (!pkthdr->len || pkthdr->len < pkthdr->caplen) {
  112. fprintf(stderr, "safe_pcap_next ERROR: Invalid packet length in %s:%s() line %d: packet length=%u capture length=%u\n",
  113. file, funcname, line, pkthdr->len, pkthdr->caplen);
  114. exit(-1);
  115. }
  116. }
  117. return pktdata;
  118. }
  119. /**
  120. * get next packet in pcap file (extended)
  121. */
  122. int _our_safe_pcap_next_ex(pcap_t *pcap, struct pcap_pkthdr **pkthdr,
  123. const u_char **pktdata, const char *funcname,
  124. const int line, const char *file)
  125. {
  126. int res = pcap_next_ex(pcap, pkthdr, pktdata);
  127. if (*pktdata && *pkthdr) {
  128. if ((*pkthdr)->len > MAXPACKET) {
  129. fprintf(stderr, "safe_pcap_next_ex ERROR: Invalid packet length in %s:%s() line %d: %u is greater than maximum %u\n",
  130. file, funcname, line, (*pkthdr)->len, MAXPACKET);
  131. exit(-1);
  132. }
  133. if (!(*pkthdr)->len || (*pkthdr)->len < (*pkthdr)->caplen) {
  134. fprintf(stderr, "safe_pcap_next_ex ERROR: Invalid packet length in %s:%s() line %d: packet length=%u capture length=%u\n",
  135. file, funcname, line, (*pkthdr)->len, (*pkthdr)->caplen);
  136. exit(-1);
  137. }
  138. }
  139. return res;
  140. }
  141. /**
  142. * Print various packet statistics
  143. */
  144. void
  145. packet_stats(const tcpreplay_stats_t *stats)
  146. {
  147. struct timeval diff;
  148. COUNTER diff_us;
  149. COUNTER bytes_sec = 0;
  150. u_int32_t bytes_sec_10ths = 0;
  151. COUNTER mb_sec = 0;
  152. u_int32_t mb_sec_100ths = 0;
  153. u_int32_t mb_sec_1000ths = 0;
  154. COUNTER pkts_sec = 0;
  155. u_int32_t pkts_sec_100ths = 0;
  156. timersub(&stats->end_time, &stats->start_time, &diff);
  157. diff_us = TIMEVAL_TO_MICROSEC(&diff);
  158. if (diff_us && stats->pkts_sent && stats->bytes_sent) {
  159. COUNTER bytes_sec_X10;
  160. COUNTER pkts_sec_X100;
  161. COUNTER mb_sec_X1000;
  162. COUNTER mb_sec_X100;
  163. if (stats->bytes_sent > 1000 * 1000 * 1000 && diff_us > 1000 * 1000) {
  164. bytes_sec_X10 = (stats->bytes_sent * 10 * 1000) / (diff_us / 1000);
  165. pkts_sec_X100 = (stats->pkts_sent * 100 * 1000) / (diff_us / 1000);
  166. } else {
  167. bytes_sec_X10 = (stats->bytes_sent * 10 * 1000 * 1000) / diff_us;
  168. pkts_sec_X100 = (stats->pkts_sent * 100 * 1000 * 1000) / diff_us;
  169. }
  170. bytes_sec = bytes_sec_X10 / 10;
  171. bytes_sec_10ths = bytes_sec_X10 % 10;
  172. mb_sec_X1000 = (bytes_sec * 8) / 1000;
  173. mb_sec_X100 = mb_sec_X1000 / 10;
  174. mb_sec = mb_sec_X1000 / 1000;
  175. mb_sec_100ths = mb_sec_X100 % 100;
  176. mb_sec_1000ths = mb_sec_X1000 % 1000;
  177. pkts_sec = pkts_sec_X100 / 100;
  178. pkts_sec_100ths = pkts_sec_X100 % 100;
  179. }
  180. if (diff_us >= 1000 * 1000)
  181. printf("Actual: " COUNTER_SPEC " packets (" COUNTER_SPEC " bytes) sent in %zd.%02zd seconds\n",
  182. stats->pkts_sent, stats->bytes_sent, (ssize_t)diff.tv_sec, (ssize_t)(diff.tv_usec / (10 * 1000)));
  183. else
  184. printf("Actual: " COUNTER_SPEC " packets (" COUNTER_SPEC " bytes) sent in %zd.%06zd seconds\n",
  185. stats->pkts_sent, stats->bytes_sent, (ssize_t)diff.tv_sec, (ssize_t)diff.tv_usec);
  186. if (mb_sec >= 1)
  187. printf("Rated: %llu.%1u Bps, %llu.%02u Mbps, %llu.%02u pps\n",
  188. bytes_sec, bytes_sec_10ths, mb_sec, mb_sec_100ths, pkts_sec, pkts_sec_100ths);
  189. else
  190. printf("Rated: %llu.%1u Bps, %llu.%03u Mbps, %llu.%02u pps\n",
  191. bytes_sec, bytes_sec_10ths, mb_sec, mb_sec_1000ths, pkts_sec, pkts_sec_100ths);
  192. fflush(NULL);
  193. if (stats->failed)
  194. printf("Failed write attempts: " COUNTER_SPEC "\n",
  195. stats->failed);
  196. }
  197. /**
  198. * fills a buffer with a string representing the given time
  199. *
  200. * @param when: the time that should be formatted
  201. * @param buf: a buffer to write to
  202. * @param len: length of the buffer
  203. * @return: string containing date, or -1 on error
  204. */
  205. int format_date_time(struct timeval *when, char *buf, size_t len)
  206. {
  207. struct tm *tm;
  208. char tmp[64];
  209. assert(len);
  210. tm = localtime(&when->tv_sec);
  211. if (!tm)
  212. return -1;
  213. strftime(tmp, sizeof tmp, "%Y-%m-%d %H:%M:%S.%%06u", tm);
  214. return snprintf(buf, len, tmp, when->tv_usec);
  215. }
  216. /**
  217. * reads a hexstring in the format of xx,xx,xx,xx spits it back into *hex
  218. * up to hexlen bytes. Returns actual number of bytes returned. On error
  219. * it just calls errx() since all errors are fatal.
  220. */
  221. int
  222. read_hexstring(const char *l2string, u_char *hex, const int hexlen)
  223. {
  224. int numbytes = 0;
  225. unsigned int value;
  226. char *l2byte;
  227. u_char databyte;
  228. char *token = NULL;
  229. char *string;
  230. string = safe_strdup(l2string);
  231. if (hexlen <= 0)
  232. err(-1, "Hex buffer must be > 0");
  233. memset(hex, '\0', hexlen);
  234. /* data is hex, comma separated, byte by byte */
  235. /* get the first byte */
  236. l2byte = strtok_r(string, ",", &token);
  237. sscanf(l2byte, "%x", &value);
  238. if (value > 0xff)
  239. errx(-1, "Invalid hex string byte: %s", l2byte);
  240. databyte = (u_char) value;
  241. memcpy(&hex[numbytes], &databyte, 1);
  242. /* get remaining bytes */
  243. while ((l2byte = strtok_r(NULL, ",", &token)) != NULL) {
  244. numbytes++;
  245. if (numbytes + 1 > hexlen) {
  246. warn("Hex buffer too small for data- skipping data");
  247. goto done;
  248. }
  249. sscanf(l2byte, "%x", &value);
  250. if (value > 0xff)
  251. errx(-1, "Invalid hex string byte: %s", l2byte);
  252. databyte = (u_char) value;
  253. memcpy(&hex[numbytes], &databyte, 1);
  254. }
  255. numbytes++;
  256. done:
  257. safe_free(string);
  258. dbgx(1, "Read %d bytes of hex data", numbytes);
  259. return (numbytes);
  260. }
  261. #ifdef USE_CUSTOM_INET_ATON
  262. int
  263. inet_aton(const char *name, struct in_addr *addr)
  264. {
  265. in_addr_t a = inet_addr(name);
  266. addr->s_addr = a;
  267. return a != (in_addr_t)-1;
  268. }
  269. #endif
  270. #if SIZEOF_LONG == 4
  271. uint32_t __div64_32(uint64_t *n, uint32_t base)
  272. {
  273. uint64_t rem = *n;
  274. uint64_t b = base;
  275. uint64_t res, d = 1;
  276. uint32_t high = rem >> 32;
  277. /* Reduce the thing a bit first */
  278. res = 0;
  279. if (high >= base) {
  280. high /= base;
  281. res = (uint64_t) high << 32;
  282. rem -= (uint64_t) (high*base) << 32;
  283. }
  284. while ((int64_t)b > 0 && b < rem) {
  285. b = b+b;
  286. d = d+d;
  287. }
  288. do {
  289. if (rem >= b) {
  290. rem -= b;
  291. res += d;
  292. }
  293. b >>= 1;
  294. d >>= 1;
  295. } while (d);
  296. *n = res;
  297. return rem;
  298. }
  299. #endif /* SIZEOF_LONG == 4 */
  300. /**
  301. * Implementation of rand_r that is consistent across all platforms
  302. * This algorithm is mentioned in the ISO C standard, here extended
  303. * for 32 bits.
  304. * @param: seed
  305. * @return: random number
  306. */
  307. uint32_t tcpr_random(uint32_t *seed)
  308. {
  309. unsigned int next = *seed;
  310. int result;
  311. next *= 1103515245;
  312. next += 12345;
  313. result = (unsigned int) (next / 65536) % 2048;
  314. next *= 1103515245;
  315. next += 12345;
  316. result <<= 10;
  317. result ^= (unsigned int) (next / 65536) % 1024;
  318. next *= 1103515245;
  319. next += 12345;
  320. result <<= 10;
  321. result ^= (unsigned int) (next / 65536) % 1024;
  322. *seed = next;
  323. return result;
  324. }
  325. /**
  326. * #416 - Ensure STDIN is not left in non-blocking mode after closing
  327. * a program. BSD and Unix derivatives should utilize `FIONBIO` due to known
  328. * issues with reading from tty with a 0 byte read returning -1 opposed to 0.
  329. */
  330. void restore_stdin(void)
  331. {
  332. #ifdef FIONBIO
  333. int nb = 0;
  334. ioctl(0, FIONBIO, &nb);
  335. #else
  336. fcntl(0, F_SETFL, fcntl(0, F_GETFL) | O_NONBLOCK);
  337. #endif /* FIONBIO */
  338. }