8 * Copyright (c) 2002-2009 Volkswagen Group Electronic Research
11 * Redistribution and use in source and binary forms, with or without
12 * modification, are permitted provided that the following conditions
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.
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.
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.
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
44 * Send feedback to <socketcan-users@lists.berlios.de>
58 #include <sys/types.h>
59 #include <sys/socket.h>
60 #include <sys/ioctl.h>
64 #include <linux/can.h>
65 #include <linux/can/raw.h>
70 #define MAXSOCK 16 /* max. number of CAN interfaces given on the cmdline */
71 #define MAXIFNAMES 30 /* size of receive name index to omit ioctls */
72 #define MAXCOL 6 /* number of different colors for colorized output */
73 #define ANYDEV "any" /* name of interface to receive from any CAN interface */
74 #define ANL "\r\n" /* newline in ASC mode */
76 #define SILENT_INI 42 /* detect user setting on commandline */
77 #define SILENT_OFF 0 /* no silent mode */
78 #define SILENT_ANI 1 /* silent mode with animation */
79 #define SILENT_ON 2 /* silent mode (completely silent) */
82 #define RED ATTBOLD FGRED
83 #define GREEN ATTBOLD FGGREEN
84 #define YELLOW ATTBOLD FGYELLOW
85 #define BLUE ATTBOLD FGBLUE
86 #define MAGENTA ATTBOLD FGMAGENTA
87 #define CYAN ATTBOLD FGCYAN
89 const char col_on [MAXCOL][19] = {BLUE, RED, GREEN, BOLD, MAGENTA, CYAN};
90 const char col_off [] = ATTRESET;
92 static char devname[MAXIFNAMES][IFNAMSIZ+1];
93 static int dindex[MAXIFNAMES];
94 static int max_devname_len; /* to prevent frazzled device name output */
97 const char anichar[MAXANI] = {'|', '/', '-', '\\'};
99 extern int optind, opterr, optopt;
101 static volatile int running = 1;
103 void print_usage(char *prg)
105 fprintf(stderr, "\nUsage: %s [options] <CAN interface>+\n", prg);
106 fprintf(stderr, " (use CTRL-C to terminate %s)\n\n", prg);
107 fprintf(stderr, "Options: -t <type> (timestamp: (a)bsolute/(d)elta/(z)ero/(A)bsolute w date)\n");
108 fprintf(stderr, " -c (increment color mode level)\n");
109 fprintf(stderr, " -i (binary output - may exceed 80 chars/line)\n");
110 fprintf(stderr, " -a (enable additional ASCII output)\n");
111 fprintf(stderr, " -S (swap byte order in printed CAN data[] - marked with '%c' )\n", SWAP_DELIMITER);
112 fprintf(stderr, " -s <level> (silent mode - %d: off (default) %d: animation %d: silent)\n", SILENT_OFF, SILENT_ANI, SILENT_ON);
113 fprintf(stderr, " -b <can> (bridge mode - send received frames to <can>)\n");
114 fprintf(stderr, " -B <can> (bridge mode - like '-b' with disabled loopback)\n");
115 fprintf(stderr, " -l (log CAN-frames into file. Sets '-s %d' by default)\n", SILENT_ON);
116 fprintf(stderr, " -L (use log file format on stdout)\n");
117 fprintf(stderr, " -n <count> (terminate after receiption of <count> CAN frames)\n");
118 fprintf(stderr, " -r <size> (set socket receive buffer to <size>)\n");
119 fprintf(stderr, "\n");
120 fprintf(stderr, "Up to %d CAN interfaces with optional filter sets can be specified\n", MAXSOCK);
121 fprintf(stderr, "on the commandline in the form: <ifname>[,filter]*\n");
122 fprintf(stderr, "\nComma separated filters can be specified for each given CAN interface:\n");
123 fprintf(stderr, " <can_id>:<can_mask> (matches when <received_can_id> & mask == can_id & mask)\n");
124 fprintf(stderr, " <can_id>~<can_mask> (matches when <received_can_id> & mask != can_id & mask)\n");
125 fprintf(stderr, " #<error_mask> (set error frame filter, see include/linux/can/error.h)\n");
126 fprintf(stderr, "\nCAN IDs, masks and data content are given and expected in hexadecimal values.\n");
127 fprintf(stderr, "When can_id and can_mask are both 8 digits, they are assumed to be 29 bit EFF.\n");
128 fprintf(stderr, "Without any given filter all data frames are received ('0:0' default filter).\n");
129 fprintf(stderr, "\nUse interface name '%s' to receive from all CAN interfaces.\n", ANYDEV);
130 fprintf(stderr, "\nExamples:\n");
131 fprintf(stderr, "%s -c -c -ta can0,123:7FF,400:700,#000000FF can2,400~7F0 can3 can8\n", prg);
132 fprintf(stderr, "%s -l any,0~0,#FFFFFFFF (log only error frames but no(!) data frames)\n", prg);
133 fprintf(stderr, "%s -l any,0:0,#FFFFFFFF (log error frames and also all data frames)\n", prg);
134 fprintf(stderr, "%s vcan2,92345678:DFFFFFFF (match only for extended CAN ID 12345678)\n", prg);
135 fprintf(stderr, "%s vcan2,123:7FF (matches CAN ID 123 - including EFF and RTR frames)\n", prg);
136 fprintf(stderr, "%s vcan2,123:C00007FF (matches CAN ID 123 - only SFF and non-RTR frames)\n", prg);
137 fprintf(stderr, "\n");
140 void sigterm(int signo)
145 int idx2dindex(int ifidx, int socket) {
150 for (i=0; i < MAXIFNAMES; i++) {
151 if (dindex[i] == ifidx)
155 /* create new interface index cache entry */
157 /* remove index cache zombies first */
158 for (i=0; i < MAXIFNAMES; i++) {
160 ifr.ifr_ifindex = dindex[i];
161 if (ioctl(socket, SIOCGIFNAME, &ifr) < 0)
166 for (i=0; i < MAXIFNAMES; i++)
167 if (!dindex[i]) /* free entry */
170 if (i == MAXIFNAMES) {
171 fprintf(stderr, "Interface index cache only supports %d interfaces.\n",
178 ifr.ifr_ifindex = ifidx;
179 if (ioctl(socket, SIOCGIFNAME, &ifr) < 0)
180 perror("SIOCGIFNAME");
182 if (max_devname_len < strlen(ifr.ifr_name))
183 max_devname_len = strlen(ifr.ifr_name);
185 strcpy(devname[i], ifr.ifr_name);
188 printf("new index %d (%s)\n", i, devname[i]);
194 int main(int argc, char **argv)
199 unsigned char timestamp = 0;
200 unsigned char silent = SILENT_INI;
201 unsigned char silentani = 0;
202 unsigned char color = 0;
203 unsigned char view = 0;
204 unsigned char log = 0;
205 unsigned char logfrmt = 0;
209 int currmax, numfilter;
211 struct sockaddr_can addr;
212 struct can_filter *rfilter;
213 can_err_mask_t err_mask;
214 struct can_frame frame;
217 struct timeval tv, last_tv;
218 FILE *logfile = NULL;
220 signal(SIGTERM, sigterm);
221 signal(SIGHUP, sigterm);
222 signal(SIGINT, sigterm);
227 while ((opt = getopt(argc, argv, "t:ciaSs:b:B:lLn:r:h?")) != -1) {
230 timestamp = optarg[0];
231 if ((timestamp != 'a') && (timestamp != 'A') &&
232 (timestamp != 'd') && (timestamp != 'z')) {
233 fprintf(stderr, "%s: unknown timestamp mode '%c' - ignored\n",
234 basename(argv[0]), optarg[0]);
244 view |= CANLIB_VIEW_BINARY;
248 view |= CANLIB_VIEW_ASCII;
252 view |= CANLIB_VIEW_SWAP;
256 silent = atoi(optarg);
257 if (silent > SILENT_ON) {
258 print_usage(basename(argv[0]));
265 if (strlen(optarg) >= IFNAMSIZ) {
266 fprintf(stderr, "Name of CAN device '%s' is too long!\n\n", optarg);
269 bridge = socket(PF_CAN, SOCK_RAW, CAN_RAW);
271 perror("bridge socket");
274 addr.can_family = AF_CAN;
275 strcpy(ifr.ifr_name, optarg);
276 if (ioctl(bridge, SIOCGIFINDEX, &ifr) < 0)
277 perror("SIOCGIFINDEX");
278 addr.can_ifindex = ifr.ifr_ifindex;
280 if (!addr.can_ifindex) {
281 perror("invalid bridge interface");
285 /* disable default receive filter on this write-only RAW socket */
286 setsockopt(bridge, SOL_CAN_RAW, CAN_RAW_FILTER, NULL, 0);
291 setsockopt(bridge, SOL_CAN_RAW, CAN_RAW_LOOPBACK,
292 &loopback, sizeof(loopback));
295 if (bind(bridge, (struct sockaddr *)&addr, sizeof(addr)) < 0) {
296 perror("bridge bind");
311 count = atoi(optarg);
313 print_usage(basename(argv[0]));
319 rcvbuf_size = atoi(optarg);
320 if (rcvbuf_size < 1) {
321 print_usage(basename(argv[0]));
327 print_usage(basename(argv[0]));
333 if (optind == argc) {
334 print_usage(basename(argv[0]));
338 if (logfrmt && view) {
339 fprintf(stderr, "Log file format selected: Please disable ASCII/BINARY/SWAP options!\n");
343 if (silent == SILENT_INI) {
345 fprintf(stderr, "\nDisabled standard output while logging.");
346 silent = SILENT_ON; /* disable output on stdout */
348 silent = SILENT_OFF; /* default output */
351 currmax = argc - optind; /* find real number of CAN devices */
353 if (currmax > MAXSOCK) {
354 fprintf(stderr, "More than %d CAN devices given on commandline!\n", MAXSOCK);
358 for (i=0; i < currmax; i++) {
360 ptr = argv[optind+i];
361 nptr = strchr(ptr, ',');
364 printf("open %d '%s'.\n", i, ptr);
367 s[i] = socket(PF_CAN, SOCK_RAW, CAN_RAW);
374 nbytes = nptr - ptr; /* interface name is up the first ',' */
376 nbytes = strlen(ptr); /* no ',' found => no filter definitions */
378 if (nbytes >= IFNAMSIZ) {
379 fprintf(stderr, "name of CAN device '%s' is too long!\n", ptr);
383 if (nbytes > max_devname_len)
384 max_devname_len = nbytes; /* for nice printing */
386 addr.can_family = AF_CAN;
388 memset(&ifr.ifr_name, 0, sizeof(ifr.ifr_name));
389 strncpy(ifr.ifr_name, ptr, nbytes);
392 printf("using interface name '%s'.\n", ifr.ifr_name);
395 if (strcmp(ANYDEV, ifr.ifr_name)) {
396 if (ioctl(s[i], SIOCGIFINDEX, &ifr) < 0) {
397 perror("SIOCGIFINDEX");
400 addr.can_ifindex = ifr.ifr_ifindex;
402 addr.can_ifindex = 0; /* any can interface */
406 /* found a ',' after the interface name => check for filters */
408 /* determine number of filters to alloc the filter space */
413 ptr++; /* hop behind the ',' */
414 ptr = strchr(ptr, ','); /* exit condition */
417 rfilter = malloc(sizeof(struct can_filter) * numfilter);
419 fprintf(stderr, "Failed to create filter space!\n");
428 ptr = nptr+1; /* hop behind the ',' */
429 nptr = strchr(ptr, ','); /* update exit condition */
431 if (sscanf(ptr, "%lx:%lx",
432 (long unsigned int *)
433 &rfilter[numfilter].can_id,
434 (long unsigned int *)
435 &rfilter[numfilter].can_mask) == 2) {
436 rfilter[numfilter].can_mask &= ~CAN_ERR_FLAG;
438 } else if (sscanf(ptr, "%lx~%lx",
439 (long unsigned int *)
440 &rfilter[numfilter].can_id,
441 (long unsigned int *)
442 &rfilter[numfilter].can_mask) == 2) {
443 rfilter[numfilter].can_id |= CAN_INV_FILTER;
444 rfilter[numfilter].can_mask &= ~CAN_ERR_FLAG;
446 } else if (sscanf(ptr, "#%lx",
447 (long unsigned int *)&err_mask) != 1) {
448 fprintf(stderr, "Error in filter option parsing: '%s'\n", ptr);
454 setsockopt(s[i], SOL_CAN_RAW, CAN_RAW_ERR_FILTER,
455 &err_mask, sizeof(err_mask));
458 setsockopt(s[i], SOL_CAN_RAW, CAN_RAW_FILTER,
459 rfilter, numfilter * sizeof(struct can_filter));
467 int curr_rcvbuf_size;
468 socklen_t curr_rcvbuf_size_len = sizeof(curr_rcvbuf_size);
470 if (setsockopt(s[i], SOL_SOCKET, SO_RCVBUF,
471 &rcvbuf_size, sizeof(rcvbuf_size)) < 0) {
472 perror("setsockopt SO_RCVBUF");
476 if (getsockopt(s[i], SOL_SOCKET, SO_RCVBUF,
477 &curr_rcvbuf_size, &curr_rcvbuf_size_len) < 0) {
478 perror("getsockopt SO_RCVBUF");
482 /* Only print a warning the first time we detect the adjustment */
483 /* n.b.: The wanted size is doubled in Linux in net/sore/sock.c */
484 if (!i && curr_rcvbuf_size < rcvbuf_size*2)
485 fprintf(stderr, "The socket receive buffer size was "
486 "adjusted due to /proc/sys/net/core/rmem_max.\n");
489 if (bind(s[i], (struct sockaddr *)&addr, sizeof(addr)) < 0) {
498 char fname[sizeof("candump-2006-11-20_202026.log")+1];
500 if (time(&currtime) == (time_t)-1) {
505 localtime_r(&currtime, &now);
507 sprintf(fname, "candump-%04d-%02d-%02d_%02d%02d%02d.log",
515 if (silent != SILENT_ON)
516 printf("\nWarning: console output active while logging!");
518 fprintf(stderr, "\nEnabling Logfile '%s'\n\n", fname);
520 logfile = fopen(fname, "w");
530 for (i=0; i<currmax; i++)
533 if ((ret = select(s[currmax-1]+1, &rdfs, NULL, NULL, NULL)) < 0) {
539 for (i=0; i<currmax; i++) { /* check all CAN RAW sockets */
541 if (FD_ISSET(s[i], &rdfs)) {
543 socklen_t len = sizeof(addr);
546 nbytes = recvfrom(s[i], &frame, sizeof(struct can_frame), 0,
547 (struct sockaddr*)&addr, &len);
553 if (nbytes < sizeof(struct can_frame)) {
554 fprintf(stderr, "read: incomplete CAN frame\n");
558 if (count && (--count == 0))
562 nbytes = write(bridge, &frame, sizeof(struct can_frame));
564 perror("bridge write");
566 } else if (nbytes < sizeof(struct can_frame)) {
567 fprintf(stderr,"bridge write: incomplete CAN frame\n");
572 if (timestamp || log || logfrmt)
573 if (ioctl(s[i], SIOCGSTAMP, &tv) < 0)
574 perror("SIOCGSTAMP");
577 idx = idx2dindex(addr.can_ifindex, s[i]);
580 /* log CAN frame with absolute timestamp & device */
581 fprintf(logfile, "(%ld.%06ld) ", tv.tv_sec, tv.tv_usec);
582 fprintf(logfile, "%*s ", max_devname_len, devname[idx]);
583 /* without seperator as logfile use-case is parsing */
584 fprint_canframe(logfile, &frame, "\n", 0);
588 /* print CAN frame in log file style to stdout */
589 printf("(%ld.%06ld) ", tv.tv_sec, tv.tv_usec);
590 printf("%*s ", max_devname_len, devname[idx]);
591 fprint_canframe(stdout, &frame, "\n", 0);
592 goto out_fflush; /* no other output to stdout */
595 if (silent != SILENT_OFF){
596 if (silent == SILENT_ANI) {
597 printf("%c\b", anichar[silentani%=MAXANI]);
600 goto out_fflush; /* no other output to stdout */
603 printf(" %s", (color>2)?col_on[idx%MAXCOL]:"");
607 case 'a': /* absolute with timestamp */
608 printf("(%ld.%06ld) ", tv.tv_sec, tv.tv_usec);
611 case 'A': /* absolute with date */
616 tm = *localtime(&tv.tv_sec);
617 strftime(timestring, 24, "%Y-%m-%d %H:%M:%S", &tm);
618 printf("(%s.%06ld) ", timestring, tv.tv_usec);
622 case 'd': /* delta */
623 case 'z': /* starting with zero */
627 if (last_tv.tv_sec == 0) /* first init */
629 diff.tv_sec = tv.tv_sec - last_tv.tv_sec;
630 diff.tv_usec = tv.tv_usec - last_tv.tv_usec;
631 if (diff.tv_usec < 0)
632 diff.tv_sec--, diff.tv_usec += 1000000;
634 diff.tv_sec = diff.tv_usec = 0;
635 printf("(%ld.%06ld) ", diff.tv_sec, diff.tv_usec);
637 if (timestamp == 'd')
638 last_tv = tv; /* update for delta calculation */
642 default: /* no timestamp output */
646 printf(" %s", (color && (color<3))?col_on[idx%MAXCOL]:"");
647 printf("%*s", max_devname_len, devname[idx]);
648 printf("%s ", (color==1)?col_off:"");
650 fprint_long_canframe(stdout, &frame, NULL, view);
652 printf("%s", (color>1)?col_off:"");
661 for (i=0; i<currmax; i++)