utils.c 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463
  1. /* $Id$ */
  2. /*
  3. * Copyright (c) 2001-2010 Aaron Turner <aturner at synfin dot net>
  4. * Copyright (c) 2013-2022 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 "defines.h"
  20. #include "config.h"
  21. #include "common.h"
  22. #include <stdlib.h>
  23. #include <string.h>
  24. #ifdef HAVE_SYS_IOCTL_H
  25. #include <sys/ioctl.h>
  26. #endif
  27. /**
  28. * this is wrapped up in a #define safe_malloc
  29. * This function, detects failures to malloc memory and zeros out the
  30. * memory before returning
  31. */
  32. void *
  33. our_safe_malloc(size_t len, const char *funcname, int line, const char *file)
  34. {
  35. u_char *ptr;
  36. if ((ptr = malloc(len)) == NULL) {
  37. fprintf(stderr, "ERROR in %s:%s() line %d: Unable to malloc() %zu bytes/n", file, funcname, line, len);
  38. exit(-1);
  39. }
  40. /* zero memory */
  41. memset(ptr, 0, len);
  42. /* wrapped inside an #ifdef for better performance */
  43. dbgx(5, "Malloc'd %zu bytes in %s:%s() line %d", len, file, funcname, line);
  44. return (void *)ptr;
  45. }
  46. /**
  47. * this is wrapped up in a #define safe_realloc
  48. * This function, detects failures to realloc memory and zeros
  49. * out the NEW memory if len > current len. As always, remember
  50. * to use it as:
  51. * ptr = safe_realloc(ptr, size)
  52. */
  53. void *
  54. our_safe_realloc(void *ptr, size_t len, const char *funcname, int line, const char *file)
  55. {
  56. if ((ptr = realloc(ptr, len)) == NULL) {
  57. fprintf(stderr,
  58. "ERROR: in %s:%s() line %d: Unable to remalloc() buffer to %zu bytes",
  59. file,
  60. funcname,
  61. line,
  62. len);
  63. exit(-1);
  64. }
  65. dbgx(5, "Remalloc'd buffer to %zu bytes in %s:%s() line %d", len, file, funcname, line);
  66. return ptr;
  67. }
  68. /**
  69. * this is wrapped up in a #define safe_strdup
  70. * This function, detects failures to realloc memory
  71. */
  72. char *
  73. our_safe_strdup(const char *str, const char *funcname, int line, const char *file)
  74. {
  75. char *newstr;
  76. if ((newstr = (char *)malloc(strlen(str) + 1)) == NULL) {
  77. fprintf(stderr, "ERROR in %s:%s() line %d: Unable to strdup() %zu bytes\n", file, funcname, line, strlen(str));
  78. exit(-1);
  79. }
  80. memcpy(newstr, str, strlen(str) + 1);
  81. return newstr;
  82. }
  83. /**
  84. * calls free and sets to NULL.
  85. */
  86. void
  87. our_safe_free(void *ptr, const char *funcname, int line, const char *file)
  88. {
  89. assert(funcname);
  90. assert(line);
  91. assert(file);
  92. if (ptr == NULL)
  93. return;
  94. free(ptr);
  95. }
  96. /**
  97. * get next packet in pcap file
  98. */
  99. u_char *
  100. our_safe_pcap_next(pcap_t *pcap, struct pcap_pkthdr *pkthdr, const char *funcname, int line, const char *file)
  101. {
  102. u_char *pktdata = (u_char *)pcap_next(pcap, pkthdr);
  103. if (pktdata) {
  104. if (pkthdr->len > MAX_SNAPLEN) {
  105. fprintf(stderr,
  106. "safe_pcap_next ERROR: Invalid packet length in %s:%s() line %d: %u is greater than maximum %u\n",
  107. file,
  108. funcname,
  109. line,
  110. pkthdr->len,
  111. MAX_SNAPLEN);
  112. exit(-1);
  113. }
  114. if (!pkthdr->len || !pkthdr->caplen) {
  115. fprintf(stderr,
  116. "safe_pcap_next ERROR: Invalid packet length in %s:%s() line %d: packet length=%u capture length=%u\n",
  117. file,
  118. funcname,
  119. line,
  120. pkthdr->len,
  121. pkthdr->caplen);
  122. exit(-1);
  123. }
  124. /* attempt to correct invalid captures */
  125. if (pkthdr->len < pkthdr->caplen) {
  126. dbgx(1, "Correcting invalid packet capture length %d: packet length=%u", pkthdr->caplen, pkthdr->len);
  127. pkthdr->caplen = pkthdr->len;
  128. }
  129. } else {
  130. /* this will be reported as a failed packet in final report */
  131. dbg(1, "No data found in packet");
  132. }
  133. return pktdata;
  134. }
  135. /**
  136. * get next packet in pcap file (extended)
  137. */
  138. int
  139. our_safe_pcap_next_ex(pcap_t *pcap,
  140. struct pcap_pkthdr **pkthdr,
  141. const u_char **pktdata,
  142. const char *funcname,
  143. int line,
  144. const char *file)
  145. {
  146. int res = pcap_next_ex(pcap, pkthdr, pktdata);
  147. if (*pktdata && *pkthdr) {
  148. if ((*pkthdr)->len > MAXPACKET) {
  149. fprintf(stderr,
  150. "safe_pcap_next_ex ERROR: Invalid packet length in %s:%s() line %d: %u is greater than maximum %u\n",
  151. file,
  152. funcname,
  153. line,
  154. (*pkthdr)->len,
  155. MAXPACKET);
  156. exit(-1);
  157. }
  158. if (!(*pkthdr)->len || (*pkthdr)->len < (*pkthdr)->caplen) {
  159. fprintf(stderr,
  160. "safe_pcap_next_ex ERROR: Invalid packet length in %s:%s() line %d: packet length=%u capture length=%u\n",
  161. file,
  162. funcname,
  163. line,
  164. (*pkthdr)->len,
  165. (*pkthdr)->caplen);
  166. exit(-1);
  167. }
  168. if ((*pkthdr)->len < (*pkthdr)->caplen) {
  169. dbgx(1, "Correcting invalid packet capture length %d: packet length=%u", (*pkthdr)->caplen, (*pkthdr)->len);
  170. (*pkthdr)->caplen = (*pkthdr)->len;
  171. }
  172. } else {
  173. /* this will be reported as a failed packet in final report */
  174. dbgx(1, "No data found in packet 0x%p and/or header 0x%p", *pktdata, *pkthdr);
  175. }
  176. return res;
  177. }
  178. /**
  179. * Print various packet statistics
  180. */
  181. void
  182. packet_stats(const tcpreplay_stats_t *stats)
  183. {
  184. struct timeval diff;
  185. COUNTER diff_us;
  186. COUNTER bytes_sec = 0;
  187. u_int32_t bytes_sec_10ths = 0;
  188. COUNTER mb_sec = 0;
  189. u_int32_t mb_sec_100ths = 0;
  190. u_int32_t mb_sec_1000ths = 0;
  191. COUNTER pkts_sec = 0;
  192. u_int32_t pkts_sec_100ths = 0;
  193. timersub(&stats->end_time, &stats->start_time, &diff);
  194. diff_us = TIMEVAL_TO_MICROSEC(&diff);
  195. if (diff_us && stats->pkts_sent && stats->bytes_sent) {
  196. COUNTER bytes_sec_X10;
  197. COUNTER pkts_sec_X100;
  198. COUNTER mb_sec_X1000;
  199. COUNTER mb_sec_X100;
  200. if (stats->bytes_sent > 1000 * 1000 * 1000 && diff_us > 1000 * 1000) {
  201. bytes_sec_X10 = (stats->bytes_sent * 10 * 1000) / (diff_us / 1000);
  202. pkts_sec_X100 = (stats->pkts_sent * 100 * 1000) / (diff_us / 1000);
  203. } else {
  204. bytes_sec_X10 = (stats->bytes_sent * 10 * 1000 * 1000) / diff_us;
  205. pkts_sec_X100 = (stats->pkts_sent * 100 * 1000 * 1000) / diff_us;
  206. }
  207. bytes_sec = bytes_sec_X10 / 10;
  208. bytes_sec_10ths = bytes_sec_X10 % 10;
  209. mb_sec_X1000 = (bytes_sec * 8) / 1000;
  210. mb_sec_X100 = mb_sec_X1000 / 10;
  211. mb_sec = mb_sec_X1000 / 1000;
  212. mb_sec_100ths = mb_sec_X100 % 100;
  213. mb_sec_1000ths = mb_sec_X1000 % 1000;
  214. pkts_sec = pkts_sec_X100 / 100;
  215. pkts_sec_100ths = pkts_sec_X100 % 100;
  216. }
  217. if (diff_us >= 1000 * 1000)
  218. printf("Actual: " COUNTER_SPEC " packets (" COUNTER_SPEC " bytes) sent in %zd.%02zd seconds\n",
  219. stats->pkts_sent,
  220. stats->bytes_sent,
  221. (ssize_t)diff.tv_sec,
  222. (ssize_t)(diff.tv_usec / (10 * 1000)));
  223. else
  224. printf("Actual: " COUNTER_SPEC " packets (" COUNTER_SPEC " bytes) sent in %zd.%06zd seconds\n",
  225. stats->pkts_sent,
  226. stats->bytes_sent,
  227. (ssize_t)diff.tv_sec,
  228. (ssize_t)diff.tv_usec);
  229. if (mb_sec >= 1)
  230. printf("Rated: %llu.%1u Bps, %llu.%02u Mbps, %llu.%02u pps\n",
  231. bytes_sec,
  232. bytes_sec_10ths,
  233. mb_sec,
  234. mb_sec_100ths,
  235. pkts_sec,
  236. pkts_sec_100ths);
  237. else
  238. printf("Rated: %llu.%1u Bps, %llu.%03u Mbps, %llu.%02u pps\n",
  239. bytes_sec,
  240. bytes_sec_10ths,
  241. mb_sec,
  242. mb_sec_1000ths,
  243. pkts_sec,
  244. pkts_sec_100ths);
  245. fflush(NULL);
  246. if (stats->failed)
  247. printf("Failed write attempts: " COUNTER_SPEC "\n", stats->failed);
  248. }
  249. /**
  250. * fills a buffer with a string representing the given time
  251. *
  252. * @param when: the time that should be formatted
  253. * @param buf: a buffer to write to
  254. * @param len: length of the buffer
  255. * @return: string containing date, or -1 on error
  256. */
  257. int
  258. format_date_time(struct timeval *when, char *buf, size_t len)
  259. {
  260. struct tm *tm;
  261. char tmp[64];
  262. assert(len);
  263. tm = localtime(&when->tv_sec);
  264. if (!tm)
  265. return -1;
  266. strftime(tmp, sizeof tmp, "%Y-%m-%d %H:%M:%S.%%06u", tm);
  267. return snprintf(buf, len, tmp, when->tv_usec);
  268. }
  269. /**
  270. * reads a hexstring in the format of xx,xx,xx,xx spits it back into *hex
  271. * up to hexlen bytes. Returns actual number of bytes returned. On error
  272. * it just calls errx() since all errors are fatal.
  273. */
  274. int
  275. read_hexstring(const char *l2string, u_char *hex, int hexlen)
  276. {
  277. int numbytes = 0;
  278. unsigned int value;
  279. char *l2byte;
  280. u_char databyte;
  281. char *token = NULL;
  282. char *string;
  283. string = safe_strdup(l2string);
  284. if (hexlen <= 0)
  285. err(-1, "Hex buffer must be > 0");
  286. memset(hex, '\0', hexlen);
  287. /* data is hex, comma separated, byte by byte */
  288. /* get the first byte */
  289. l2byte = strtok_r(string, ",", &token);
  290. if (l2byte == NULL)
  291. err(-1, "Hex buffer must contain something");
  292. value = strtol(l2byte, NULL, 16);
  293. if (value > 0xff)
  294. errx(-1, "Invalid hex string byte: %s", l2byte);
  295. databyte = (u_char)value;
  296. memcpy(&hex[numbytes], &databyte, 1);
  297. /* get remaining bytes */
  298. while ((l2byte = strtok_r(NULL, ",", &token)) != NULL) {
  299. numbytes++;
  300. if (numbytes + 1 > hexlen) {
  301. warn("Hex buffer too small for data- skipping data");
  302. goto done;
  303. }
  304. value = strtol(l2byte, NULL, 16);
  305. if (value > 0xff)
  306. errx(-1, "Invalid hex string byte: %s", l2byte);
  307. databyte = (u_char)value;
  308. memcpy(&hex[numbytes], &databyte, 1);
  309. }
  310. numbytes++;
  311. done:
  312. safe_free(string);
  313. dbgx(1, "Read %d bytes of hex data", numbytes);
  314. return (numbytes);
  315. }
  316. #ifdef USE_CUSTOM_INET_ATON
  317. int
  318. inet_aton(const char *name, struct in_addr *addr)
  319. {
  320. in_addr_t a = inet_addr(name);
  321. addr->s_addr = a;
  322. return a != (in_addr_t)-1;
  323. }
  324. #endif
  325. #if SIZEOF_LONG == 4
  326. uint32_t
  327. __div64_32(uint64_t *n, uint32_t base)
  328. {
  329. uint64_t rem = *n;
  330. uint64_t b = base;
  331. uint64_t res, d = 1;
  332. uint32_t high = rem >> 32;
  333. /* Reduce the thing a bit first */
  334. res = 0;
  335. if (high >= base) {
  336. high /= base;
  337. res = (uint64_t)high << 32;
  338. rem -= (uint64_t)(high * base) << 32;
  339. }
  340. while ((int64_t)b > 0 && b < rem) {
  341. b = b + b;
  342. d = d + d;
  343. }
  344. do {
  345. if (rem >= b) {
  346. rem -= b;
  347. res += d;
  348. }
  349. b >>= 1;
  350. d >>= 1;
  351. } while (d);
  352. *n = res;
  353. return rem;
  354. }
  355. #endif /* SIZEOF_LONG == 4 */
  356. /**
  357. * Implementation of rand_r that is consistent across all platforms
  358. * This algorithm is mentioned in the ISO C standard, here extended
  359. * for 32 bits.
  360. * @param: seed
  361. * @return: random number
  362. */
  363. uint32_t
  364. tcpr_random(uint32_t *seed)
  365. {
  366. unsigned int next = *seed;
  367. int result;
  368. next *= 1103515245;
  369. next += 12345;
  370. result = (int)(next / 65536) % 2048;
  371. next *= 1103515245;
  372. next += 12345;
  373. result <<= 10;
  374. result ^= (int)(next / 65536) % 1024;
  375. next *= 1103515245;
  376. next += 12345;
  377. result <<= 10;
  378. result ^= (int)(next / 65536) % 1024;
  379. *seed = next;
  380. return result;
  381. }
  382. /**
  383. * #416 - Ensure STDIN is not left in non-blocking mode after closing
  384. * a program. BSD and Unix derivatives should utilize `FIONBIO` due to known
  385. * issues with reading from tty with a 0 byte read returning -1 opposed to 0.
  386. */
  387. void
  388. restore_stdin(void)
  389. {
  390. #ifdef FIONBIO
  391. int nb = 0;
  392. ioctl(0, FIONBIO, &nb);
  393. #else
  394. fcntl(0, F_SETFL, fcntl(0, F_GETFL) | O_NONBLOCK);
  395. #endif /* FIONBIO */
  396. }