send_packets.c 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500
  1. /* $Id: send_packets.c 1898 2007-08-25 05:10:51Z aturner $ */
  2. /*
  3. * Copyright (c) 2001-2007 Aaron Turner.
  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 names of the copyright owners 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 ``AS IS'' AND ANY EXPRESS OR IMPLIED
  20. * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
  21. * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
  22. * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
  23. * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
  24. * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
  25. * GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
  26. * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER
  27. * IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
  28. * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
  29. * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  30. */
  31. #include "config.h"
  32. #include "defines.h"
  33. #include "common.h"
  34. #include <sys/time.h>
  35. #include <sys/types.h>
  36. #include <signal.h>
  37. #include <string.h>
  38. #include <netinet/in.h>
  39. #include <errno.h>
  40. #include <stdlib.h>
  41. #include <unistd.h>
  42. #include <fcntl.h>
  43. #include "tcpreplay.h"
  44. #ifdef TCPREPLAY
  45. #include "tcpreplay_opts.h"
  46. #ifdef TCPREPLAY_EDIT
  47. #include "tcpedit/tcpedit.h"
  48. extern tcpedit_t *tcpedit;
  49. #endif
  50. #endif /* TCPREPLAY */
  51. #include "send_packets.h"
  52. extern tcpreplay_opt_t options;
  53. extern struct timeval begin, end;
  54. extern COUNTER bytes_sent, failed, pkts_sent;
  55. extern volatile int didsig;
  56. #ifdef DEBUG
  57. extern int debug;
  58. #endif
  59. static void do_sleep(struct timeval *time, struct timeval *last, int len, int accurate,
  60. sendpacket_t *sp, COUNTER counter);
  61. static u_int32_t sleep_loop(struct timeval time);
  62. static u_char *get_next_packet(pcap_t *pcap, struct pcap_pkthdr *pkthdr, int file_idx, packet_cache_t **prev_packet);
  63. /**
  64. * the main loop function for tcpreplay. This is where we figure out
  65. * what to do with each packet
  66. */
  67. void
  68. send_packets(pcap_t *pcap, int cache_file_idx)
  69. {
  70. struct timeval last = { 0, 0 };
  71. COUNTER packetnum = 0;
  72. struct pcap_pkthdr pkthdr;
  73. const u_char *pktdata = NULL;
  74. sendpacket_t *sp = options.intf1;
  75. u_int32_t pktlen;
  76. packet_cache_t *cached_packet = NULL;
  77. packet_cache_t **prev_packet = NULL;
  78. #if defined TCPREPLAY && defined TCPREPLAY_EDIT
  79. struct pcap_pkthdr *pkthdr_ptr;
  80. #endif
  81. /* register signals */
  82. didsig = 0;
  83. if (options.speed.mode != SPEED_ONEATATIME) {
  84. (void)signal(SIGINT, catcher);
  85. } else {
  86. (void)signal(SIGINT, break_now);
  87. }
  88. if (options.enable_file_cache) {
  89. prev_packet = &cached_packet;
  90. } else {
  91. prev_packet = NULL;
  92. }
  93. /* MAIN LOOP
  94. * Keep sending while we have packets or until
  95. * we've sent enough packets
  96. */
  97. while ((pktdata = get_next_packet(pcap, &pkthdr, cache_file_idx, prev_packet)) != NULL) {
  98. /* die? */
  99. if (didsig)
  100. break_now(0);
  101. /* stop sending based on the limit -L? */
  102. if (options.limit_send > 0 && pkts_sent >= options.limit_send)
  103. return;
  104. packetnum++;
  105. #ifdef TCPREPLAY
  106. /* do we use the snaplen (caplen) or the "actual" packet len? */
  107. pktlen = HAVE_OPT(PKTLEN) ? pkthdr.len : pkthdr.caplen;
  108. #elif TCPBRIDGE
  109. pktlen = pkthdr.caplen;
  110. #else
  111. #error WTF??? We should not be here!
  112. #endif
  113. dbgx(2, "packet " COUNTER_SPEC " caplen %d", packetnum, pktlen);
  114. /* Dual nic processing */
  115. if (options.intf2 != NULL) {
  116. sp = (sendpacket_t *) cache_mode(options.cachedata, packetnum);
  117. /* sometimes we should not send the packet */
  118. if (sp == TCPR_DIR_NOSEND)
  119. continue;
  120. }
  121. /* do we need to print the packet via tcpdump? */
  122. #ifdef ENABLE_VERBOSE
  123. if (options.verbose)
  124. tcpdump_print(options.tcpdump, &pkthdr, pktdata);
  125. #endif
  126. #if defined TCPREPLAY && defined TCPREPLAY_EDIT
  127. pkthdr_ptr = &pkthdr;
  128. if (tcpedit_packet(tcpedit, &pkthdr_ptr, &pktdata, sp->cache_dir) == -1) {
  129. errx(1, "Error editing packet #" COUNTER_SPEC ": %s", packetnum, tcpedit_geterr(tcpedit));
  130. }
  131. pktlen = HAVE_OPT(PKTLEN) ? pkthdr_ptr->len : pkthdr_ptr->caplen;
  132. #endif
  133. /*
  134. * we have to cast the ts, since OpenBSD sucks
  135. * had to be special and use bpf_timeval
  136. */
  137. do_sleep((struct timeval *)&pkthdr.ts, &last, pktlen, options.accurate, sp, packetnum);
  138. /* write packet out on network */
  139. if (sendpacket(sp, pktdata, pktlen) < (int)pktlen)
  140. warnx("Unable to send packet: %s", sendpacket_geterr(sp));
  141. /*
  142. * track the time of the "last packet sent". Again, because of OpenBSD
  143. * we have to do a mempcy rather then assignment.
  144. *
  145. * A number of 3rd party tools generate bad timestamps which go backwards
  146. * in time. Hence, don't update the "last" unless pkthdr.ts > last
  147. */
  148. if (timercmp(&last, &pkthdr.ts, <))
  149. memcpy(&last, &pkthdr.ts, sizeof(struct timeval));
  150. pkts_sent ++;
  151. bytes_sent += pktlen;
  152. } /* while */
  153. if (options.enable_file_cache) {
  154. options.file_cache[cache_file_idx].cached = TRUE;
  155. }
  156. }
  157. /**
  158. * Gets the next packet to be sent out. This will either read from the pcap file
  159. * or will retrieve the packet from the internal cache.
  160. *
  161. * The parameter prev_packet is used as the parent of the new entry in the cache list.
  162. * This should be NULL on the first call to this function for each file and
  163. * will be updated as new entries are added (or retrieved) from the cache list.
  164. */
  165. static u_char *
  166. get_next_packet(pcap_t *pcap, struct pcap_pkthdr *pkthdr, int file_idx,
  167. packet_cache_t **prev_packet)
  168. {
  169. u_char *pktdata = NULL;
  170. u_int32_t pktlen;
  171. /* pcap may be null in cache mode! */
  172. /* packet_cache_t may be null in file read mode! */
  173. assert(pkthdr);
  174. /*
  175. * Check if we're caching files
  176. */
  177. if (options.enable_file_cache && (prev_packet != NULL)) {
  178. /*
  179. * Yes we are caching files - has this one been cached?
  180. */
  181. if (options.file_cache[file_idx].cached) {
  182. if (*prev_packet == NULL) {
  183. /*
  184. * Get the first packet in the cache list directly from the file
  185. */
  186. *prev_packet = options.file_cache[file_idx].packet_cache;
  187. } else {
  188. /*
  189. * Get the next packet in the cache list
  190. */
  191. *prev_packet = (*prev_packet)->next;
  192. }
  193. if (*prev_packet != NULL) {
  194. pktdata = (*prev_packet)->pktdata;
  195. memcpy(pkthdr, &((*prev_packet)->pkthdr), sizeof(struct pcap_pkthdr));
  196. }
  197. } else {
  198. /*
  199. * We should read the pcap file, and cache the results
  200. */
  201. pktdata = pcap_next(pcap, pkthdr);
  202. if (pktdata != NULL) {
  203. if (*prev_packet == NULL) {
  204. /*
  205. * Create the first packet in the list
  206. */
  207. *prev_packet = safe_malloc(sizeof(packet_cache_t));
  208. options.file_cache[file_idx].packet_cache = *prev_packet;
  209. } else {
  210. /*
  211. * Add a packet to the end of the list
  212. */
  213. (*prev_packet)->next = safe_malloc(sizeof(packet_cache_t));
  214. *prev_packet = (*prev_packet)->next;
  215. }
  216. if (*prev_packet != NULL) {
  217. (*prev_packet)->next = NULL;
  218. pktlen = pkthdr->len;
  219. (*prev_packet)->pktdata = safe_malloc(pktlen);
  220. memcpy((*prev_packet)->pktdata, pktdata, pktlen);
  221. memcpy(&((*prev_packet)->pkthdr), pkthdr, sizeof(struct pcap_pkthdr));
  222. }
  223. }
  224. }
  225. } else {
  226. /*
  227. * Read pcap file as normal
  228. */
  229. pktdata = pcap_next(pcap, pkthdr);
  230. }
  231. return pktdata;
  232. }
  233. /**
  234. * determines based upon the cachedata which interface the given packet
  235. * should go out. Also rewrites any layer 2 data we might need to adjust.
  236. * Returns a void cased pointer to the options.intfX of the corresponding
  237. * interface.
  238. */
  239. void *
  240. cache_mode(char *cachedata, COUNTER packet_num)
  241. {
  242. void *sp = NULL;
  243. int result;
  244. if (packet_num > options.cache_packets)
  245. err(1, "Exceeded number of packets in cache file.");
  246. result = check_cache(cachedata, packet_num);
  247. if (result == TCPR_DIR_NOSEND) {
  248. dbgx(2, "Cache: Not sending packet " COUNTER_SPEC ".", packet_num);
  249. return TCPR_DIR_NOSEND;
  250. }
  251. else if (result == TCPR_DIR_C2S) {
  252. dbgx(2, "Cache: Sending packet " COUNTER_SPEC " out primary interface.", packet_num);
  253. sp = options.intf1;
  254. }
  255. else if (result == TCPR_DIR_S2C) {
  256. dbgx(2, "Cache: Sending packet " COUNTER_SPEC " out secondary interface.", packet_num);
  257. sp = options.intf2;
  258. }
  259. else {
  260. err(1, "check_cache() returned an error. Aborting...");
  261. }
  262. return sp;
  263. }
  264. /**
  265. * Given the timestamp on the current packet and the last packet sent,
  266. * calculate the appropriate amount of time to sleep and do so.
  267. */
  268. static void
  269. do_sleep(struct timeval *time, struct timeval *last, int len, int accurate, sendpacket_t *sp,
  270. COUNTER counter)
  271. {
  272. static struct timeval didsleep = { 0, 0 };
  273. static struct timeval start = { 0, 0 };
  274. #ifdef DEBUG
  275. static struct timeval totalsleep = { 0, 0 };
  276. #endif
  277. struct timeval nap, now, delta;
  278. struct timespec ignore, sleep;
  279. float n;
  280. struct pollfd poller[1]; /* use poll to read from the keyboard */
  281. char input[EBUF_SIZE];
  282. static u_int32_t send = 0; /* remember # of packets to send btw calls */
  283. u_int32_t loop;
  284. /* just return if topspeed */
  285. if (options.speed.mode == SPEED_TOPSPEED)
  286. return;
  287. dbgx(3, "Last time: " TIMEVAL_FORMAT, last->tv_sec, last->tv_usec);
  288. if (gettimeofday(&now, NULL) < 0) {
  289. errx(1, "Error gettimeofday: %s", strerror(errno));
  290. }
  291. dbgx(3, "Now time: " TIMEVAL_FORMAT, now.tv_sec, now.tv_usec);
  292. /* First time through for this file */
  293. if (pkts_sent == 0 || ((options.speed.mode != SPEED_MBPSRATE) && (counter == 0))) {
  294. start = now;
  295. timerclear(&delta);
  296. timerclear(&didsleep);
  297. }
  298. else {
  299. timersub(&now, &start, &delta);
  300. }
  301. switch(options.speed.mode) {
  302. case SPEED_MULTIPLIER:
  303. /*
  304. * Replay packets a factor of the time they were originally sent.
  305. */
  306. if (timerisset(last) && timercmp(time, last, >)) {
  307. timersub(time, last, &nap);
  308. timerdiv(&nap, options.speed.speed);
  309. }
  310. else {
  311. /*
  312. * Don't sleep if this is our first packet, or if the
  313. * this packet appears to have been sent before the
  314. * last packet.
  315. */
  316. timerclear(&nap);
  317. }
  318. break;
  319. case SPEED_MBPSRATE:
  320. /*
  321. * Ignore the time supplied by the capture file and send data at
  322. * a constant 'rate' (bytes per second).
  323. */
  324. if (pkts_sent != 0) {
  325. n = (float)len / (options.speed.speed * 1024 * 1024 / 8); /* convert Mbps to bps */
  326. nap.tv_sec = n;
  327. nap.tv_usec = (n - nap.tv_sec) * 1000000;
  328. dbgx(3, "packet size %d\t\tequals %f bps\t\tnap " TIMEVAL_FORMAT, len, n,
  329. nap.tv_sec, nap.tv_usec);
  330. }
  331. else {
  332. timerclear(&nap);
  333. }
  334. break;
  335. case SPEED_PACKETRATE:
  336. /* run in packets/sec */
  337. n = 1 / options.speed.speed;
  338. nap.tv_sec = n;
  339. n -= nap.tv_sec;
  340. nap.tv_usec = n * 1000000;
  341. break;
  342. case SPEED_ONEATATIME:
  343. /* do we skip prompting for a key press? */
  344. if (send == 0) {
  345. printf("**** Next packet #" COUNTER_SPEC " out %s. How many packets do you wish to send? ",
  346. counter, (sp == options.intf1 ? options.intf1_name : options.intf2_name));
  347. fflush(NULL);
  348. poller[0].fd = STDIN_FILENO;
  349. poller[0].events = POLLIN | POLLPRI | POLLNVAL;
  350. poller[0].revents = 0;
  351. if (fcntl(0, F_SETFL, fcntl(0, F_GETFL) & ~O_NONBLOCK))
  352. errx(1, "Unable to clear non-blocking flag on stdin: %s", strerror(errno));
  353. /* wait for the input */
  354. if (poll(poller, 1, -1) < 0)
  355. errx(1, "Error reading user input from stdin: %s", strerror(errno));
  356. /*
  357. * read to the end of the line or EBUF_SIZE,
  358. * Note, if people are stupid, and type in more text then EBUF_SIZE
  359. * then the next fgets() will pull in that data, which will have poor
  360. * results. fuck them.
  361. */
  362. if (fgets(input, sizeof(input), stdin) == NULL) {
  363. errx(1, "Unable to process user input for fd %d: %s", fileno(stdin), strerror(errno));
  364. } else if (strlen(input) > 1) {
  365. send = strtoul(input, NULL, 0);
  366. }
  367. /* how many packets should we send? */
  368. if (send == 0) {
  369. dbg(1, "Input was less then 1 or non-numeric, assuming 1");
  370. /* assume send only one packet */
  371. send = 1;
  372. }
  373. }
  374. /* decrement our send counter */
  375. printf("Sending packet " COUNTER_SPEC " out: %s\n", counter,
  376. sp == options.intf1 ? options.intf1_name : options.intf2_name);
  377. send --;
  378. /* leave do_sleep() */
  379. return;
  380. break;
  381. default:
  382. errx(1, "Unknown/supported speed mode: %d", options.speed.mode);
  383. break;
  384. }
  385. if (!accurate) {
  386. timeradd(&didsleep, &nap, &didsleep);
  387. dbgx(4, "I will sleep " TIMEVAL_FORMAT, nap.tv_sec, nap.tv_usec);
  388. if (timercmp(&didsleep, &delta, >)) {
  389. timersub(&didsleep, &delta, &nap);
  390. sleep.tv_sec = nap.tv_sec;
  391. sleep.tv_nsec = nap.tv_usec * 1000; /* convert microsec to ns */
  392. dbgx(4, "Sleeping " TIMEVAL_FORMAT, nap.tv_sec, nap.tv_usec);
  393. #ifdef DEBUG
  394. timeradd(&totalsleep, &nap, &totalsleep);
  395. #endif
  396. if (nanosleep(&sleep, &ignore) == -1) {
  397. warnx("nanosleep error: %s", strerror(errno));
  398. }
  399. }
  400. } else {
  401. timeradd(&now, &nap, &delta);
  402. loop = sleep_loop(delta);
  403. dbgx(3, "sleep_loop looped %u times", loop);
  404. }
  405. #ifdef DEBUG
  406. dbgx(4, "Total sleep time: " TIMEVAL_FORMAT, totalsleep.tv_sec, totalsleep.tv_usec);
  407. #endif
  408. }
  409. /**
  410. * this function will keep calling gettimeofday() until it returns
  411. * >= time. This should be a lot more accurate then using nanosleep(),
  412. * but at the cost of being more CPU intensive.
  413. */
  414. static u_int32_t
  415. sleep_loop(struct timeval time)
  416. {
  417. struct timeval now;
  418. u_int32_t loop = 0;
  419. do {
  420. gettimeofday(&now, NULL);
  421. loop ++;
  422. } while (now.tv_sec < time.tv_sec || now.tv_usec < time.tv_usec);
  423. return loop;
  424. }
  425. /*
  426. Local Variables:
  427. mode:c
  428. indent-tabs-mode:nil
  429. c-basic-offset:4
  430. End:
  431. */