]> rtime.felk.cvut.cz Git - sojka/can-utils.git/blob - canplayer.c
can-utils: AOSP build clean up
[sojka/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, skipgap;
245         static int loopback_disable = 0;
246         static int infinite_loops = 0;
247         static int loops = DEFAULT_LOOPS;
248         int assignments; /* assignments defined on the commandline */
249         int txidx;       /* sendto() interface index */
250         int eof, txmtu, i, j;
251         char *fret;
252
253         while ((opt = getopt(argc, argv, "I:l:tg:s:xv?")) != -1) {
254                 switch (opt) {
255                 case 'I':
256                         infile = fopen(optarg, "r");
257                         if (!infile) {
258                                 perror("infile");
259                                 return 1;
260                         }
261                         break;
262
263                 case 'l':
264                         if (optarg[0] == 'i')
265                                 infinite_loops = 1;
266                         else
267                                 if (!(loops = atoi(optarg))) {
268                                         fprintf(stderr, "Invalid argument for option -l !\n");
269                                         return 1;
270                                 }
271                         break;
272
273                 case 't':
274                         use_timestamps = 0;
275                         break;
276
277                 case 'g':
278                         gap = strtoul(optarg, NULL, 10);
279                         break;
280
281                 case 's':
282                         skipgap = strtoul(optarg, NULL, 10);
283                         if (skipgap < 1) {
284                                 fprintf(stderr, "Invalid argument for option -s !\n");
285                                 return 1;
286                         }
287                         break;
288
289                 case 'x':
290                         loopback_disable = 1;
291                         break;
292
293                 case 'v':
294                         verbose++;
295                         break;
296
297                 case '?':
298                 default:
299                         print_usage(basename(argv[0]));
300                         return 1;
301                         break;
302                 }
303         }
304
305         assignments = argc - optind; /* find real number of user assignments */
306
307         if (infile == stdin) { /* no jokes with stdin */
308                 infinite_loops = 0;
309                 loops = 1;
310         }
311
312         if (verbose > 1) { /* use -v -v to see this */
313                 if (infinite_loops)
314                         printf("infinite_loops\n");
315                 else
316                         printf("%d loops\n", loops);
317         }
318
319         sleep_ts.tv_sec  =  gap / 1000;
320         sleep_ts.tv_nsec = (gap % 1000) * 1000000;
321
322         /* open socket */
323         if ((s = socket(PF_CAN, SOCK_RAW, CAN_RAW)) < 0) {
324                 perror("socket");
325                 return 1;
326         }
327
328         addr.can_family  = AF_CAN;
329         addr.can_ifindex = 0;
330
331         /* disable unneeded default receive filter on this RAW socket */
332         setsockopt(s, SOL_CAN_RAW, CAN_RAW_FILTER, NULL, 0);
333
334         /* try to switch the socket into CAN FD mode */
335         setsockopt(s, SOL_CAN_RAW, CAN_RAW_FD_FRAMES, &canfd_on, sizeof(canfd_on));
336
337         if (loopback_disable) {
338                 int loopback = 0;
339
340                 setsockopt(s, SOL_CAN_RAW, CAN_RAW_LOOPBACK,
341                            &loopback, sizeof(loopback));
342         }
343
344         if (bind(s, (struct sockaddr *)&addr, sizeof(addr)) < 0) {
345                 perror("bind");
346                 return 1;
347         }
348
349         if (assignments) {
350                 /* add & check user assginments from commandline */
351                 for (i=0; i<assignments; i++) {
352                         if (strlen(argv[optind+i]) >= BUFSZ) {
353                                 fprintf(stderr, "Assignment too long!\n");
354                                 print_usage(basename(argv[0]));
355                                 return 1;
356                         }
357                         strcpy(buf, argv[optind+i]);
358                         for (j=0; j<BUFSZ; j++) { /* find '=' in assignment */
359                                 if (buf[j] == '=')
360                                         break;
361                         }
362                         if ((j == BUFSZ) || (buf[j] != '=')) {
363                                 fprintf(stderr, "'=' missing in assignment!\n");
364                                 print_usage(basename(argv[0]));
365                                 return 1;
366                         }
367                         buf[j] = 0; /* cut string in two pieces */
368                         if (add_assignment("user", s, &buf[0], &buf[j+1], verbose))
369                                 return 1;
370                 }
371         }
372
373         while (infinite_loops || loops--) {
374
375                 if (infile != stdin)
376                         rewind(infile); /* for each loop */
377
378                 if (verbose > 1) /* use -v -v to see this */
379                         printf (">>>>>>>>> start reading file. remaining loops = %d\n", loops);
380
381                 /* read first 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
389                 if (!fret)
390                         goto out; /* nothing to read */
391
392                 eof = 0;
393
394                 if (sscanf(buf, "(%ld.%ld) %s %s", &log_tv.tv_sec, &log_tv.tv_usec,
395                            device, ascframe) != 4) {
396                         fprintf(stderr, "incorrect line format in logfile\n");
397                         return 1;
398                 }
399
400                 if (use_timestamps) { /* throttle sending due to logfile timestamps */
401
402                         gettimeofday(&today_tv, NULL);
403                         create_diff_tv(&today_tv, &diff_tv, &log_tv);
404                         last_log_tv = log_tv;
405                 }
406
407                 while (!eof) {
408
409                         while ((!use_timestamps) ||
410                                (frames_to_send(&today_tv, &diff_tv, &log_tv) < 0)) {
411
412                                 /* log_tv/device/ascframe are valid here */
413
414                                 if (strlen(device) >= IFNAMSIZ) {
415                                         fprintf(stderr, "log interface name '%s' too long!", device);
416                                         return 1;
417                                 }
418
419                                 txidx = get_txidx(device); /* get ifindex for sending the frame */
420  
421                                 if ((!txidx) && (!assignments)) {
422                                         /* ifindex not found and no user assignments */
423                                         /* => assign this device automatically       */
424                                         if (add_assignment("auto", s, device, device, verbose))
425                                                 return 1;
426                                         txidx = get_txidx(device);
427                                 }
428
429                                 if (txidx == STDOUTIDX) { /* hook to print logfile lines on stdout */
430
431                                         printf("%s", buf); /* print the line AS-IS without extra \n */
432                                         fflush(stdout);
433
434                                 } else if (txidx > 0) { /* only send to valid CAN devices */
435
436                                         txmtu = parse_canframe(ascframe, &frame);
437                                         if (!txmtu) {
438                                                 fprintf(stderr, "wrong CAN frame format: '%s'!", ascframe);
439                                                 return 1;
440                                         }
441
442                                         addr.can_family  = AF_CAN;
443                                         addr.can_ifindex = txidx; /* send via this interface */
444  
445                                         if (sendto(s, &frame, txmtu, 0, (struct sockaddr*)&addr, sizeof(addr)) != txmtu) {
446                                                 perror("sendto");
447                                                 return 1;
448                                         }
449
450                                         if (verbose) {
451                                                 printf("%s (%s) ", get_txname(device), device);
452
453                                                 if (txmtu == CAN_MTU)
454                                                         fprint_long_canframe(stdout, &frame, "\n", CANLIB_VIEW_INDENT_SFF, CAN_MAX_DLEN);
455                                                 else
456                                                         fprint_long_canframe(stdout, &frame, "\n", CANLIB_VIEW_INDENT_SFF, CANFD_MAX_DLEN);
457                                         }
458                                 }
459
460                                 /* read next non-comment frame from logfile */
461                                 while ((fret = fgets(buf, BUFSZ-1, infile)) != NULL && buf[0] != '(') {
462                                         if (strlen(buf) >= BUFSZ-2) {
463                                                 fprintf(stderr, "comment line too long for input buffer\n");
464                                                 return 1;
465                                         }
466                                 }
467
468                                 if (!fret) {
469                                         eof = 1; /* this file is completely processed */
470                                         break;
471                                 }
472
473                                 if (sscanf(buf, "(%ld.%ld) %s %s", &log_tv.tv_sec, &log_tv.tv_usec,
474                                            device, ascframe) != 4) {
475                                         fprintf(stderr, "incorrect line format in logfile\n");
476                                         return 1;
477                                 }
478
479                                 if (use_timestamps) {
480                                         gettimeofday(&today_tv, NULL);
481
482                                         /* test for logfile timestamps jumping backwards OR      */
483                                         /* if the user likes to skip long gaps in the timestamps */
484                                         if ((last_log_tv.tv_sec > log_tv.tv_sec) ||
485                                             (skipgap && abs(last_log_tv.tv_sec - log_tv.tv_sec) > skipgap))
486                                                 create_diff_tv(&today_tv, &diff_tv, &log_tv);
487
488                                         last_log_tv = log_tv;
489                                 }
490
491                         } /* while frames_to_send ... */
492
493                         if (nanosleep(&sleep_ts, NULL))
494                                 return 1;
495
496                         delay_loops++; /* private statistics */
497                         gettimeofday(&today_tv, NULL);
498
499                 } /* while (!eof) */
500
501         } /* while (infinite_loops || loops--) */
502
503 out:
504
505         close(s);
506         fclose(infile);
507
508         if (verbose > 1) /* use -v -v to see this */
509                 printf("%d delay_loops\n", delay_loops);
510
511         return 0;
512 }