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