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