canplayer.c 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522
  1. /*
  2. * canplayer.c - replay a compact CAN frame logfile to CAN devices
  3. *
  4. * Copyright (c) 2002-2007 Volkswagen Group Electronic Research
  5. * All rights reserved.
  6. *
  7. * Redistribution and use in source and binary forms, with or without
  8. * modification, are permitted provided that the following conditions
  9. * are met:
  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 Volkswagen nor the names of its contributors
  16. * may be used to endorse or promote products derived from this software
  17. * without specific prior written permission.
  18. *
  19. * Alternatively, provided that this notice is retained in full, this
  20. * software may be distributed under the terms of the GNU General
  21. * Public License ("GPL") version 2, in which case the provisions of the
  22. * GPL apply INSTEAD OF those given above.
  23. *
  24. * The provided data structures and external interfaces from this code
  25. * are not restricted to be used by modules with a GPL compatible license.
  26. *
  27. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  28. * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  29. * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  30. * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  31. * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  32. * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  33. * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  34. * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  35. * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  36. * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  37. * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
  38. * DAMAGE.
  39. *
  40. * Send feedback to <linux-can@vger.kernel.org>
  41. *
  42. */
  43. #include <stdio.h>
  44. #include <string.h>
  45. #include <time.h>
  46. #include <libgen.h>
  47. #include <stdlib.h>
  48. #include <unistd.h>
  49. #include <net/if.h>
  50. #include <sys/socket.h>
  51. #include <sys/ioctl.h>
  52. #include <sys/time.h>
  53. #include <linux/can.h>
  54. #include <linux/can/raw.h>
  55. #include "lib.h"
  56. #define DEFAULT_GAP 1 /* ms */
  57. #define DEFAULT_LOOPS 1 /* only one replay */
  58. #define CHANNELS 20 /* anyone using more than 20 CAN interfaces at a time? */
  59. #define COMMENTSZ 200
  60. #define BUFSZ (sizeof("(1345212884.318850)") + IFNAMSIZ + 4 + CL_CFSZ + COMMENTSZ) /* for one line in the logfile */
  61. #define STDOUTIDX 65536 /* interface index for printing on stdout - bigger than max uint16 */
  62. struct assignment {
  63. char txif[IFNAMSIZ];
  64. int txifidx;
  65. char rxif[IFNAMSIZ];
  66. };
  67. static struct assignment asgn[CHANNELS];
  68. const int canfd_on = 1;
  69. extern int optind, opterr, optopt;
  70. void print_usage(char *prg)
  71. {
  72. fprintf(stderr, "\nUsage: %s <options> [interface assignment]*\n\n", prg);
  73. fprintf(stderr, "Options: -I <infile> (default stdin)\n");
  74. fprintf(stderr, " -l <num> "
  75. "(process input file <num> times)\n"
  76. " "
  77. "(Use 'i' for infinite loop - default: %d)\n", DEFAULT_LOOPS);
  78. fprintf(stderr, " -t (ignore timestamps: "
  79. "send frames immediately)\n");
  80. fprintf(stderr, " -g <ms> (gap in milli "
  81. "seconds - default: %d ms)\n", DEFAULT_GAP);
  82. fprintf(stderr, " -s <s> (skip gaps in "
  83. "timestamps > 's' seconds)\n");
  84. fprintf(stderr, " -x (disable local "
  85. "loopback of sent CAN frames)\n");
  86. fprintf(stderr, " -v (verbose: print "
  87. "sent CAN frames)\n\n");
  88. fprintf(stderr, "Interface assignment: 0..n assignments like "
  89. "<write-if>=<log-if>\n");
  90. fprintf(stderr, "e.g. vcan2=can0 ( send frames received from can0 on "
  91. "vcan2 )\n");
  92. fprintf(stderr, "extra hook: stdout=can0 ( print logfile line marked with can0 on "
  93. "stdout )\n");
  94. fprintf(stderr, "No assignments => send frames to the interface(s) they "
  95. "had been received from.\n\n");
  96. fprintf(stderr, "Lines in the logfile not beginning with '(' (start of "
  97. "timestamp) are ignored.\n\n");
  98. }
  99. /* copied from /usr/src/linux/include/linux/time.h ...
  100. * lhs < rhs: return <0
  101. * lhs == rhs: return 0
  102. * lhs > rhs: return >0
  103. */
  104. static inline int timeval_compare(struct timeval *lhs, struct timeval *rhs)
  105. {
  106. if (lhs->tv_sec < rhs->tv_sec)
  107. return -1;
  108. if (lhs->tv_sec > rhs->tv_sec)
  109. return 1;
  110. return lhs->tv_usec - rhs->tv_usec;
  111. }
  112. static inline void create_diff_tv(struct timeval *today, struct timeval *diff,
  113. struct timeval *log) {
  114. /* create diff_tv so that log_tv + diff_tv = today_tv */
  115. diff->tv_sec = today->tv_sec - log->tv_sec;
  116. diff->tv_usec = today->tv_usec - log->tv_usec;
  117. }
  118. static inline int frames_to_send(struct timeval *today, struct timeval *diff,
  119. struct timeval *log)
  120. {
  121. /* return value <0 when log + diff < today */
  122. struct timeval cmp;
  123. cmp.tv_sec = log->tv_sec + diff->tv_sec;
  124. cmp.tv_usec = log->tv_usec + diff->tv_usec;
  125. if (cmp.tv_usec > 1000000) {
  126. cmp.tv_usec -= 1000000;
  127. cmp.tv_sec++;
  128. }
  129. if (cmp.tv_usec < 0) {
  130. cmp.tv_usec += 1000000;
  131. cmp.tv_sec--;
  132. }
  133. return timeval_compare(&cmp, today);
  134. }
  135. int get_txidx(char *logif_name) {
  136. int i;
  137. for (i=0; i<CHANNELS; i++) {
  138. if (asgn[i].rxif[0] == 0) /* end of table content */
  139. break;
  140. if (strcmp(asgn[i].rxif, logif_name) == 0) /* found device name */
  141. break;
  142. }
  143. if ((i == CHANNELS) || (asgn[i].rxif[0] == 0))
  144. return 0; /* not found */
  145. return asgn[i].txifidx; /* return interface index */
  146. }
  147. char *get_txname(char *logif_name) {
  148. int i;
  149. for (i=0; i<CHANNELS; i++) {
  150. if (asgn[i].rxif[0] == 0) /* end of table content */
  151. break;
  152. if (strcmp(asgn[i].rxif, logif_name) == 0) /* found device name */
  153. break;
  154. }
  155. if ((i == CHANNELS) || (asgn[i].rxif[0] == 0))
  156. return 0; /* not found */
  157. return asgn[i].txif; /* return interface name */
  158. }
  159. int add_assignment(char *mode, int socket, char *txname, char *rxname,
  160. int verbose) {
  161. struct ifreq ifr;
  162. int i;
  163. /* find free entry */
  164. for (i=0; i<CHANNELS; i++) {
  165. if (asgn[i].txif[0] == 0)
  166. break;
  167. }
  168. if (i == CHANNELS) {
  169. fprintf(stderr, "Assignment table exceeded!\n");
  170. return 1;
  171. }
  172. if (strlen(txname) >= IFNAMSIZ) {
  173. fprintf(stderr, "write-if interface name '%s' too long!", txname);
  174. return 1;
  175. }
  176. strcpy(asgn[i].txif, txname);
  177. if (strlen(rxname) >= IFNAMSIZ) {
  178. fprintf(stderr, "log-if interface name '%s' too long!", rxname);
  179. return 1;
  180. }
  181. strcpy(asgn[i].rxif, rxname);
  182. if (strcmp(txname, "stdout")) {
  183. strcpy(ifr.ifr_name, txname);
  184. if (ioctl(socket, SIOCGIFINDEX, &ifr) < 0) {
  185. perror("SIOCGIFINDEX");
  186. fprintf(stderr, "write-if interface name '%s' is wrong!\n", txname);
  187. return 1;
  188. }
  189. asgn[i].txifidx = ifr.ifr_ifindex;
  190. } else
  191. asgn[i].txifidx = STDOUTIDX;
  192. if (verbose > 1) /* use -v -v to see this */
  193. printf("added %s assignment: log-if=%s write-if=%s write-if-idx=%d\n",
  194. mode, asgn[i].rxif, asgn[i].txif, asgn[i].txifidx);
  195. return 0;
  196. }
  197. int main(int argc, char **argv)
  198. {
  199. static char buf[BUFSZ], device[BUFSZ], ascframe[BUFSZ];
  200. struct sockaddr_can addr;
  201. static struct canfd_frame frame;
  202. static struct timeval today_tv, log_tv, last_log_tv, diff_tv;
  203. struct timespec sleep_ts;
  204. int s; /* CAN_RAW socket */
  205. FILE *infile = stdin;
  206. unsigned long gap = DEFAULT_GAP;
  207. int use_timestamps = 1;
  208. static int verbose, opt, delay_loops;
  209. static unsigned long skipgap;
  210. static int loopback_disable = 0;
  211. static int infinite_loops = 0;
  212. static int loops = DEFAULT_LOOPS;
  213. int assignments; /* assignments defined on the commandline */
  214. int txidx; /* sendto() interface index */
  215. int eof, txmtu, i, j;
  216. char *fret;
  217. while ((opt = getopt(argc, argv, "I:l:tg:s:xv?")) != -1) {
  218. switch (opt) {
  219. case 'I':
  220. infile = fopen(optarg, "r");
  221. if (!infile) {
  222. perror("infile");
  223. return 1;
  224. }
  225. break;
  226. case 'l':
  227. if (optarg[0] == 'i')
  228. infinite_loops = 1;
  229. else
  230. if (!(loops = atoi(optarg))) {
  231. fprintf(stderr, "Invalid argument for option -l !\n");
  232. return 1;
  233. }
  234. break;
  235. case 't':
  236. use_timestamps = 0;
  237. break;
  238. case 'g':
  239. gap = strtoul(optarg, NULL, 10);
  240. break;
  241. case 's':
  242. skipgap = strtoul(optarg, NULL, 10);
  243. if (skipgap < 1) {
  244. fprintf(stderr, "Invalid argument for option -s !\n");
  245. return 1;
  246. }
  247. break;
  248. case 'x':
  249. loopback_disable = 1;
  250. break;
  251. case 'v':
  252. verbose++;
  253. break;
  254. case '?':
  255. default:
  256. print_usage(basename(argv[0]));
  257. return 1;
  258. break;
  259. }
  260. }
  261. assignments = argc - optind; /* find real number of user assignments */
  262. if (infile == stdin) { /* no jokes with stdin */
  263. infinite_loops = 0;
  264. loops = 1;
  265. }
  266. if (verbose > 1) { /* use -v -v to see this */
  267. if (infinite_loops)
  268. printf("infinite_loops\n");
  269. else
  270. printf("%d loops\n", loops);
  271. }
  272. sleep_ts.tv_sec = gap / 1000;
  273. sleep_ts.tv_nsec = (gap % 1000) * 1000000;
  274. /* open socket */
  275. if ((s = socket(PF_CAN, SOCK_RAW, CAN_RAW)) < 0) {
  276. perror("socket");
  277. return 1;
  278. }
  279. addr.can_family = AF_CAN;
  280. addr.can_ifindex = 0;
  281. /* disable unneeded default receive filter on this RAW socket */
  282. setsockopt(s, SOL_CAN_RAW, CAN_RAW_FILTER, NULL, 0);
  283. /* try to switch the socket into CAN FD mode */
  284. setsockopt(s, SOL_CAN_RAW, CAN_RAW_FD_FRAMES, &canfd_on, sizeof(canfd_on));
  285. if (loopback_disable) {
  286. int loopback = 0;
  287. setsockopt(s, SOL_CAN_RAW, CAN_RAW_LOOPBACK,
  288. &loopback, sizeof(loopback));
  289. }
  290. if (bind(s, (struct sockaddr *)&addr, sizeof(addr)) < 0) {
  291. perror("bind");
  292. return 1;
  293. }
  294. if (assignments) {
  295. /* add & check user assginments from commandline */
  296. for (i=0; i<assignments; i++) {
  297. if (strlen(argv[optind+i]) >= BUFSZ) {
  298. fprintf(stderr, "Assignment too long!\n");
  299. print_usage(basename(argv[0]));
  300. return 1;
  301. }
  302. strcpy(buf, argv[optind+i]);
  303. for (j=0; j<BUFSZ; j++) { /* find '=' in assignment */
  304. if (buf[j] == '=')
  305. break;
  306. }
  307. if ((j == BUFSZ) || (buf[j] != '=')) {
  308. fprintf(stderr, "'=' missing in assignment!\n");
  309. print_usage(basename(argv[0]));
  310. return 1;
  311. }
  312. buf[j] = 0; /* cut string in two pieces */
  313. if (add_assignment("user", s, &buf[0], &buf[j+1], verbose))
  314. return 1;
  315. }
  316. }
  317. while (infinite_loops || loops--) {
  318. if (infile != stdin)
  319. rewind(infile); /* for each loop */
  320. if (verbose > 1) /* use -v -v to see this */
  321. printf (">>>>>>>>> start reading file. remaining loops = %d\n", loops);
  322. /* read first non-comment frame from logfile */
  323. while ((fret = fgets(buf, BUFSZ-1, infile)) != NULL && buf[0] != '(') {
  324. if (strlen(buf) >= BUFSZ-2) {
  325. fprintf(stderr, "comment line too long for input buffer\n");
  326. return 1;
  327. }
  328. }
  329. if (!fret)
  330. goto out; /* nothing to read */
  331. eof = 0;
  332. if (sscanf(buf, "(%ld.%ld) %s %s", &log_tv.tv_sec, &log_tv.tv_usec,
  333. device, ascframe) != 4) {
  334. fprintf(stderr, "incorrect line format in logfile\n");
  335. return 1;
  336. }
  337. if (use_timestamps) { /* throttle sending due to logfile timestamps */
  338. gettimeofday(&today_tv, NULL);
  339. create_diff_tv(&today_tv, &diff_tv, &log_tv);
  340. last_log_tv = log_tv;
  341. }
  342. while (!eof) {
  343. while ((!use_timestamps) ||
  344. (frames_to_send(&today_tv, &diff_tv, &log_tv) < 0)) {
  345. /* log_tv/device/ascframe are valid here */
  346. if (strlen(device) >= IFNAMSIZ) {
  347. fprintf(stderr, "log interface name '%s' too long!", device);
  348. return 1;
  349. }
  350. txidx = get_txidx(device); /* get ifindex for sending the frame */
  351. if ((!txidx) && (!assignments)) {
  352. /* ifindex not found and no user assignments */
  353. /* => assign this device automatically */
  354. if (add_assignment("auto", s, device, device, verbose))
  355. return 1;
  356. txidx = get_txidx(device);
  357. }
  358. if (txidx == STDOUTIDX) { /* hook to print logfile lines on stdout */
  359. printf("%s", buf); /* print the line AS-IS without extra \n */
  360. fflush(stdout);
  361. } else if (txidx > 0) { /* only send to valid CAN devices */
  362. txmtu = parse_canframe(ascframe, &frame);
  363. if (!txmtu) {
  364. fprintf(stderr, "wrong CAN frame format: '%s'!", ascframe);
  365. return 1;
  366. }
  367. addr.can_family = AF_CAN;
  368. addr.can_ifindex = txidx; /* send via this interface */
  369. if (sendto(s, &frame, txmtu, 0, (struct sockaddr*)&addr, sizeof(addr)) != txmtu) {
  370. perror("sendto");
  371. return 1;
  372. }
  373. if (verbose) {
  374. printf("%s (%s) ", get_txname(device), device);
  375. if (txmtu == CAN_MTU)
  376. fprint_long_canframe(stdout, &frame, "\n", CANLIB_VIEW_INDENT_SFF, CAN_MAX_DLEN);
  377. else
  378. fprint_long_canframe(stdout, &frame, "\n", CANLIB_VIEW_INDENT_SFF, CANFD_MAX_DLEN);
  379. }
  380. }
  381. /* read next non-comment frame from logfile */
  382. while ((fret = fgets(buf, BUFSZ-1, infile)) != NULL && buf[0] != '(') {
  383. if (strlen(buf) >= BUFSZ-2) {
  384. fprintf(stderr, "comment line too long for input buffer\n");
  385. return 1;
  386. }
  387. }
  388. if (!fret) {
  389. eof = 1; /* this file is completely processed */
  390. break;
  391. }
  392. if (sscanf(buf, "(%ld.%ld) %s %s", &log_tv.tv_sec, &log_tv.tv_usec,
  393. device, ascframe) != 4) {
  394. fprintf(stderr, "incorrect line format in logfile\n");
  395. return 1;
  396. }
  397. /*
  398. * ensure the fractions of seconds are 6 decimal places long to catch
  399. * 3rd party or handcrafted logfiles that treat the timestamp as float
  400. */
  401. if (strchr(buf, ')') - strchr(buf, '.') != 7) {
  402. fprintf(stderr, "timestamp format in logfile requires 6 decimal places\n");
  403. return 1;
  404. }
  405. if (use_timestamps) {
  406. gettimeofday(&today_tv, NULL);
  407. /* test for logfile timestamps jumping backwards OR */
  408. /* if the user likes to skip long gaps in the timestamps */
  409. if ((last_log_tv.tv_sec > log_tv.tv_sec) ||
  410. (skipgap && labs(last_log_tv.tv_sec - log_tv.tv_sec) > skipgap))
  411. create_diff_tv(&today_tv, &diff_tv, &log_tv);
  412. last_log_tv = log_tv;
  413. }
  414. } /* while frames_to_send ... */
  415. if (nanosleep(&sleep_ts, NULL))
  416. return 1;
  417. delay_loops++; /* private statistics */
  418. gettimeofday(&today_tv, NULL);
  419. } /* while (!eof) */
  420. } /* while (infinite_loops || loops--) */
  421. out:
  422. close(s);
  423. fclose(infile);
  424. if (verbose > 1) /* use -v -v to see this */
  425. printf("%d delay_loops\n", delay_loops);
  426. return 0;
  427. }