]> rtime.felk.cvut.cz Git - can-utils.git/blob - canplayer.c
candump: Enable HW timestamping before using it
[can-utils.git] / canplayer.c
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
44 #include <stdio.h>
45 #include <string.h>
46 #include <time.h>
47 #include <libgen.h>
48 #include <stdlib.h>
49 #include <unistd.h>
50
51 #include <net/if.h>
52 #include <sys/socket.h>
53 #include <sys/ioctl.h>
54 #include <sys/time.h>
55 #include <linux/can.h>
56 #include <linux/can/raw.h>
57
58 #include "lib.h"
59
60 #define DEFAULT_GAP     1       /* ms */
61 #define DEFAULT_LOOPS   1       /* only one replay */
62 #define CHANNELS        20      /* anyone using more than 20 CAN interfaces at a time? */
63 #define COMMENTSZ 200
64 #define BUFSZ (sizeof("(1345212884.318850)") + IFNAMSIZ + 4 + CL_CFSZ + COMMENTSZ) /* for one line in the logfile */
65 #define STDOUTIDX       65536   /* interface index for printing on stdout - bigger than max uint16 */
66
67 struct assignment {
68         char txif[IFNAMSIZ];
69         int  txifidx;
70         char rxif[IFNAMSIZ];
71 };
72 static struct assignment asgn[CHANNELS];
73 const int canfd_on = 1;
74
75 extern int optind, opterr, optopt;
76
77 void print_usage(char *prg)
78 {
79         fprintf(stderr, "\nUsage: %s <options> [interface assignment]*\n\n", prg);
80         fprintf(stderr, "Options:              -I <infile>  (default stdin)\n");
81         fprintf(stderr, "                      -l <num>     "
82                 "(process input file <num> times)\n"
83                 "                                   "
84                 "(Use 'i' for infinite loop - default: %d)\n", DEFAULT_LOOPS);
85         fprintf(stderr, "                      -t           (ignore timestamps: "
86                 "send frames immediately)\n");
87         fprintf(stderr, "                      -g <ms>      (gap in milli "
88                 "seconds - default: %d ms)\n", DEFAULT_GAP);
89         fprintf(stderr, "                      -s <s>       (skip gaps in "
90                 "timestamps > 's' seconds)\n");
91         fprintf(stderr, "                      -x           (disable local "
92                 "loopback of sent CAN frames)\n");
93         fprintf(stderr, "                      -v           (verbose: print "
94                 "sent CAN frames)\n\n");
95         fprintf(stderr, "Interface assignment:  0..n assignments like "
96                 "<write-if>=<log-if>\n");
97         fprintf(stderr, "e.g. vcan2=can0 ( send frames received from can0 on "
98                 "vcan2 )\n");
99         fprintf(stderr, "extra hook: stdout=can0 ( print logfile line marked with can0 on "
100                 "stdout )\n");
101         fprintf(stderr, "No assignments => send frames to the interface(s) they "
102                 "had been received from.\n\n");
103         fprintf(stderr, "Lines in the logfile not beginning with '(' (start of "
104                 "timestamp) are ignored.\n\n");
105 }
106
107 /* copied from /usr/src/linux/include/linux/time.h ...
108  * lhs < rhs:  return <0
109  * lhs == rhs: return 0
110  * lhs > rhs:  return >0
111  */
112 static inline int timeval_compare(struct timeval *lhs, struct timeval *rhs)
113 {
114         if (lhs->tv_sec < rhs->tv_sec)
115                 return -1;
116         if (lhs->tv_sec > rhs->tv_sec)
117                 return 1;
118         return lhs->tv_usec - rhs->tv_usec;
119 }
120
121 static inline void create_diff_tv(struct timeval *today, struct timeval *diff,
122                                   struct timeval *log) {
123
124         /* create diff_tv so that log_tv + diff_tv = today_tv */
125         diff->tv_sec  = today->tv_sec  - log->tv_sec;
126         diff->tv_usec = today->tv_usec - log->tv_usec;
127 }
128
129 static inline int frames_to_send(struct timeval *today, struct timeval *diff,
130                                  struct timeval *log)
131 {
132         /* return value <0 when log + diff < today */
133
134         struct timeval cmp;
135
136         cmp.tv_sec  = log->tv_sec  + diff->tv_sec;
137         cmp.tv_usec = log->tv_usec + diff->tv_usec;
138
139         if (cmp.tv_usec > 1000000) {
140                 cmp.tv_usec -= 1000000;
141                 cmp.tv_sec++;
142         }
143
144         if (cmp.tv_usec < 0) {
145                 cmp.tv_usec += 1000000;
146                 cmp.tv_sec--;
147         }
148
149         return timeval_compare(&cmp, today);
150 }
151
152 int get_txidx(char *logif_name) {
153
154         int i;
155
156         for (i=0; i<CHANNELS; i++) {
157                 if (asgn[i].rxif[0] == 0) /* end of table content */
158                         break;
159                 if (strcmp(asgn[i].rxif, logif_name) == 0) /* found device name */
160                         break;
161         }
162
163         if ((i == CHANNELS) || (asgn[i].rxif[0] == 0))
164                 return 0; /* not found */
165
166         return asgn[i].txifidx; /* return interface index */
167 }
168
169 char *get_txname(char *logif_name) {
170
171         int i;
172
173         for (i=0; i<CHANNELS; i++) {
174                 if (asgn[i].rxif[0] == 0) /* end of table content */
175                         break;
176                 if (strcmp(asgn[i].rxif, logif_name) == 0) /* found device name */
177                         break;
178         }
179
180         if ((i == CHANNELS) || (asgn[i].rxif[0] == 0))
181                 return 0; /* not found */
182
183         return asgn[i].txif; /* return interface name */
184 }
185
186 int add_assignment(char *mode, int socket, char *txname, char *rxname,
187                    int verbose) {
188
189         struct ifreq ifr;
190         int i;
191
192         /* find free entry */
193         for (i=0; i<CHANNELS; i++) {
194                 if (asgn[i].txif[0] == 0)
195                         break;
196         }
197
198         if (i == CHANNELS) {
199                 fprintf(stderr, "Assignment table exceeded!\n");
200                 return 1;
201         }
202
203         if (strlen(txname) >= IFNAMSIZ) {
204                 fprintf(stderr, "write-if interface name '%s' too long!", txname);
205                 return 1;
206         }
207         strcpy(asgn[i].txif, txname);
208
209         if (strlen(rxname) >= IFNAMSIZ) {
210                 fprintf(stderr, "log-if interface name '%s' too long!", rxname);
211                 return 1;
212         }
213         strcpy(asgn[i].rxif, rxname);
214
215         if (strcmp(txname, "stdout")) {
216                 strcpy(ifr.ifr_name, txname);
217                 if (ioctl(socket, SIOCGIFINDEX, &ifr) < 0) {
218                         perror("SIOCGIFINDEX");
219                         fprintf(stderr, "write-if interface name '%s' is wrong!\n", txname);
220                         return 1;
221                 }
222                 asgn[i].txifidx = ifr.ifr_ifindex;
223         } else
224                 asgn[i].txifidx = STDOUTIDX;
225
226         if (verbose > 1) /* use -v -v to see this */
227                 printf("added %s assignment: log-if=%s write-if=%s write-if-idx=%d\n",
228                        mode, asgn[i].rxif, asgn[i].txif, asgn[i].txifidx);
229
230         return 0;
231 }
232
233 int main(int argc, char **argv)
234 {
235         static char buf[BUFSZ], device[BUFSZ], ascframe[BUFSZ];
236         struct sockaddr_can addr;
237         static struct canfd_frame frame;
238         static struct timeval today_tv, log_tv, last_log_tv, diff_tv;
239         struct timespec sleep_ts;
240         int s; /* CAN_RAW socket */
241         FILE *infile = stdin;
242         unsigned long gap = DEFAULT_GAP; 
243         int use_timestamps = 1;
244         static int verbose, opt, delay_loops;
245         static unsigned long skipgap;
246         static int loopback_disable = 0;
247         static int infinite_loops = 0;
248         static int loops = DEFAULT_LOOPS;
249         int assignments; /* assignments defined on the commandline */
250         int txidx;       /* sendto() interface index */
251         int eof, txmtu, i, j;
252         char *fret;
253
254         while ((opt = getopt(argc, argv, "I:l:tg:s:xv?")) != -1) {
255                 switch (opt) {
256                 case 'I':
257                         infile = fopen(optarg, "r");
258                         if (!infile) {
259                                 perror("infile");
260                                 return 1;
261                         }
262                         break;
263
264                 case 'l':
265                         if (optarg[0] == 'i')
266                                 infinite_loops = 1;
267                         else
268                                 if (!(loops = atoi(optarg))) {
269                                         fprintf(stderr, "Invalid argument for option -l !\n");
270                                         return 1;
271                                 }
272                         break;
273
274                 case 't':
275                         use_timestamps = 0;
276                         break;
277
278                 case 'g':
279                         gap = strtoul(optarg, NULL, 10);
280                         break;
281
282                 case 's':
283                         skipgap = strtoul(optarg, NULL, 10);
284                         if (skipgap < 1) {
285                                 fprintf(stderr, "Invalid argument for option -s !\n");
286                                 return 1;
287                         }
288                         break;
289
290                 case 'x':
291                         loopback_disable = 1;
292                         break;
293
294                 case 'v':
295                         verbose++;
296                         break;
297
298                 case '?':
299                 default:
300                         print_usage(basename(argv[0]));
301                         return 1;
302                         break;
303                 }
304         }
305
306         assignments = argc - optind; /* find real number of user assignments */
307
308         if (infile == stdin) { /* no jokes with stdin */
309                 infinite_loops = 0;
310                 loops = 1;
311         }
312
313         if (verbose > 1) { /* use -v -v to see this */
314                 if (infinite_loops)
315                         printf("infinite_loops\n");
316                 else
317                         printf("%d loops\n", loops);
318         }
319
320         sleep_ts.tv_sec  =  gap / 1000;
321         sleep_ts.tv_nsec = (gap % 1000) * 1000000;
322
323         /* open socket */
324         if ((s = socket(PF_CAN, SOCK_RAW, CAN_RAW)) < 0) {
325                 perror("socket");
326                 return 1;
327         }
328
329         addr.can_family  = AF_CAN;
330         addr.can_ifindex = 0;
331
332         /* disable unneeded default receive filter on this RAW socket */
333         setsockopt(s, SOL_CAN_RAW, CAN_RAW_FILTER, NULL, 0);
334
335         /* try to switch the socket into CAN FD mode */
336         setsockopt(s, SOL_CAN_RAW, CAN_RAW_FD_FRAMES, &canfd_on, sizeof(canfd_on));
337
338         if (loopback_disable) {
339                 int loopback = 0;
340
341                 setsockopt(s, SOL_CAN_RAW, CAN_RAW_LOOPBACK,
342                            &loopback, sizeof(loopback));
343         }
344
345         if (bind(s, (struct sockaddr *)&addr, sizeof(addr)) < 0) {
346                 perror("bind");
347                 return 1;
348         }
349
350         if (assignments) {
351                 /* add & check user assginments from commandline */
352                 for (i=0; i<assignments; i++) {
353                         if (strlen(argv[optind+i]) >= BUFSZ) {
354                                 fprintf(stderr, "Assignment too long!\n");
355                                 print_usage(basename(argv[0]));
356                                 return 1;
357                         }
358                         strcpy(buf, argv[optind+i]);
359                         for (j=0; j<BUFSZ; j++) { /* find '=' in assignment */
360                                 if (buf[j] == '=')
361                                         break;
362                         }
363                         if ((j == BUFSZ) || (buf[j] != '=')) {
364                                 fprintf(stderr, "'=' missing in assignment!\n");
365                                 print_usage(basename(argv[0]));
366                                 return 1;
367                         }
368                         buf[j] = 0; /* cut string in two pieces */
369                         if (add_assignment("user", s, &buf[0], &buf[j+1], verbose))
370                                 return 1;
371                 }
372         }
373
374         while (infinite_loops || loops--) {
375
376                 if (infile != stdin)
377                         rewind(infile); /* for each loop */
378
379                 if (verbose > 1) /* use -v -v to see this */
380                         printf (">>>>>>>>> start reading file. remaining loops = %d\n", loops);
381
382                 /* read first non-comment frame from logfile */
383                 while ((fret = fgets(buf, BUFSZ-1, infile)) != NULL && buf[0] != '(') {
384                         if (strlen(buf) >= BUFSZ-2) {
385                                 fprintf(stderr, "comment line too long for input buffer\n");
386                                 return 1;
387                         }
388                 }
389
390                 if (!fret)
391                         goto out; /* nothing to read */
392
393                 eof = 0;
394
395                 if (sscanf(buf, "(%ld.%ld) %s %s", &log_tv.tv_sec, &log_tv.tv_usec,
396                            device, ascframe) != 4) {
397                         fprintf(stderr, "incorrect line format in logfile\n");
398                         return 1;
399                 }
400
401                 if (use_timestamps) { /* throttle sending due to logfile timestamps */
402
403                         gettimeofday(&today_tv, NULL);
404                         create_diff_tv(&today_tv, &diff_tv, &log_tv);
405                         last_log_tv = log_tv;
406                 }
407
408                 while (!eof) {
409
410                         while ((!use_timestamps) ||
411                                (frames_to_send(&today_tv, &diff_tv, &log_tv) < 0)) {
412
413                                 /* log_tv/device/ascframe are valid here */
414
415                                 if (strlen(device) >= IFNAMSIZ) {
416                                         fprintf(stderr, "log interface name '%s' too long!", device);
417                                         return 1;
418                                 }
419
420                                 txidx = get_txidx(device); /* get ifindex for sending the frame */
421  
422                                 if ((!txidx) && (!assignments)) {
423                                         /* ifindex not found and no user assignments */
424                                         /* => assign this device automatically       */
425                                         if (add_assignment("auto", s, device, device, verbose))
426                                                 return 1;
427                                         txidx = get_txidx(device);
428                                 }
429
430                                 if (txidx == STDOUTIDX) { /* hook to print logfile lines on stdout */
431
432                                         printf("%s", buf); /* print the line AS-IS without extra \n */
433                                         fflush(stdout);
434
435                                 } else if (txidx > 0) { /* only send to valid CAN devices */
436
437                                         txmtu = parse_canframe(ascframe, &frame);
438                                         if (!txmtu) {
439                                                 fprintf(stderr, "wrong CAN frame format: '%s'!", ascframe);
440                                                 return 1;
441                                         }
442
443                                         addr.can_family  = AF_CAN;
444                                         addr.can_ifindex = txidx; /* send via this interface */
445  
446                                         if (sendto(s, &frame, txmtu, 0, (struct sockaddr*)&addr, sizeof(addr)) != txmtu) {
447                                                 perror("sendto");
448                                                 return 1;
449                                         }
450
451                                         if (verbose) {
452                                                 printf("%s (%s) ", get_txname(device), device);
453
454                                                 if (txmtu == CAN_MTU)
455                                                         fprint_long_canframe(stdout, &frame, "\n", CANLIB_VIEW_INDENT_SFF, CAN_MAX_DLEN);
456                                                 else
457                                                         fprint_long_canframe(stdout, &frame, "\n", CANLIB_VIEW_INDENT_SFF, CANFD_MAX_DLEN);
458                                         }
459                                 }
460
461                                 /* read next non-comment frame from logfile */
462                                 while ((fret = fgets(buf, BUFSZ-1, infile)) != NULL && buf[0] != '(') {
463                                         if (strlen(buf) >= BUFSZ-2) {
464                                                 fprintf(stderr, "comment line too long for input buffer\n");
465                                                 return 1;
466                                         }
467                                 }
468
469                                 if (!fret) {
470                                         eof = 1; /* this file is completely processed */
471                                         break;
472                                 }
473
474                                 if (sscanf(buf, "(%ld.%ld) %s %s", &log_tv.tv_sec, &log_tv.tv_usec,
475                                            device, ascframe) != 4) {
476                                         fprintf(stderr, "incorrect line format in logfile\n");
477                                         return 1;
478                                 }
479
480                                 if (use_timestamps) {
481                                         gettimeofday(&today_tv, NULL);
482
483                                         /* test for logfile timestamps jumping backwards OR      */
484                                         /* if the user likes to skip long gaps in the timestamps */
485                                         if ((last_log_tv.tv_sec > log_tv.tv_sec) ||
486                                             (skipgap && labs(last_log_tv.tv_sec - log_tv.tv_sec) > skipgap))
487                                                 create_diff_tv(&today_tv, &diff_tv, &log_tv);
488
489                                         last_log_tv = log_tv;
490                                 }
491
492                         } /* while frames_to_send ... */
493
494                         if (nanosleep(&sleep_ts, NULL))
495                                 return 1;
496
497                         delay_loops++; /* private statistics */
498                         gettimeofday(&today_tv, NULL);
499
500                 } /* while (!eof) */
501
502         } /* while (infinite_loops || loops--) */
503
504 out:
505
506         close(s);
507         fclose(infile);
508
509         if (verbose > 1) /* use -v -v to see this */
510                 printf("%d delay_loops\n", delay_loops);
511
512         return 0;
513 }