8 * Copyright (c) 2002-2007 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 MAXFILTER 30 /* max. number of possible filters for each socket */
72 #define MAXIFNAMES 30 /* size of receive name index to omit ioctls */
73 #define MAXCOL 6 /* number of different colors for colorized output */
74 #define ANYDEV "any" /* name of interface to receive from any CAN interface */
75 #define ANL "\r\n" /* newline in ASC mode */
78 #define RED ATTBOLD FGRED
79 #define GREEN ATTBOLD FGGREEN
80 #define YELLOW ATTBOLD FGYELLOW
81 #define BLUE ATTBOLD FGBLUE
82 #define MAGENTA ATTBOLD FGMAGENTA
83 #define CYAN ATTBOLD FGCYAN
85 const char col_on [MAXCOL][19] = {BLUE, RED, GREEN, BOLD, MAGENTA, CYAN};
86 const char col_off [] = ATTRESET;
88 static char devname[MAXIFNAMES][IFNAMSIZ+1];
89 static int dindex[MAXIFNAMES];
90 static int max_devname_len; /* to prevent frazzled device name output */
93 const char anichar[MAXANI] = {'|', '/', '-', '\\'};
95 extern int optind, opterr, optopt;
97 static volatile int running = 1;
99 void print_usage(char *prg)
101 fprintf(stderr, "\nUsage: %s [options] <CAN interface>+\n", prg);
102 fprintf(stderr, " (use CTRL-C to terminate %s)\n\n", prg);
103 fprintf(stderr, "Options: -t <type> (timestamp: (a)bsolute/(d)elta/(z)ero/(A)bsolute w date)\n");
104 fprintf(stderr, " -c (increment color mode level)\n");
105 fprintf(stderr, " -i (binary output - may exceed 80 chars/line)\n");
106 fprintf(stderr, " -a (enable additional ASCII output)\n");
107 fprintf(stderr, " -s <level> (silent mode - 1: animation 2: completely silent)\n");
108 fprintf(stderr, " -b <can> (bridge mode - send received frames to <can>)\n");
109 fprintf(stderr, " -B <can> (bridge mode - like '-b' with disabled loopback)\n");
110 fprintf(stderr, " -l (log CAN-frames into file)\n");
111 fprintf(stderr, " -L (use log file format on stdout)\n");
112 fprintf(stderr, "\n");
113 fprintf(stderr, "Up to %d CAN interfaces with optional filter sets can be specified\n", MAXSOCK);
114 fprintf(stderr, "on the commandline in the form: <ifname>[,filter]*\n");
115 fprintf(stderr, "\nUp to %d comma separated filters can be specified for each given CAN interface:\n", MAXFILTER);
116 fprintf(stderr, " <can_id>:<can_mask> (matches when <received_can_id> & mask == can_id & mask)\n");
117 fprintf(stderr, " <can_id>~<can_mask> (matches when <received_can_id> & mask != can_id & mask)\n");
118 fprintf(stderr, " #<error_mask> (set error frame filter, see include/linux/can/error.h)\n");
119 fprintf(stderr, "\nUse interface name '%s' to receive from all CAN interfaces.\n", ANYDEV);
120 fprintf(stderr, "CAN IDs, masks and data content are given and expected in hexadecimal values.\n");
121 fprintf(stderr, "\nExamples:\n");
122 fprintf(stderr, "%s -c -c -ta can0,123:7FF,400:700,#000000FF can2,400~7F0 can3 can8\n", prg);
123 fprintf(stderr, "%s -l any,0~0,#FFFFFFFF (log only error frames but no(!) data frames)\n", prg);
124 fprintf(stderr, "%s vcan2,92345678:9FFFFFFF (match only for extended CAN ID 12345678)\n", prg);
125 fprintf(stderr, "\n");
128 void sigterm(int signo)
133 int idx2dindex(int ifidx, int socket) {
138 for (i=0; i < MAXIFNAMES; i++) {
139 if (dindex[i] == ifidx)
143 /* create new interface index cache entry */
145 /* remove index cache zombies first */
146 for (i=0; i < MAXIFNAMES; i++) {
148 ifr.ifr_ifindex = dindex[i];
149 if (ioctl(socket, SIOCGIFNAME, &ifr) < 0)
154 for (i=0; i < MAXIFNAMES; i++)
155 if (!dindex[i]) /* free entry */
158 if (i == MAXIFNAMES) {
159 printf("Interface index cache only supports %d interfaces.\n",
166 ifr.ifr_ifindex = ifidx;
167 if (ioctl(socket, SIOCGIFNAME, &ifr) < 0)
168 perror("SIOCGIFNAME");
170 if (max_devname_len < strlen(ifr.ifr_name))
171 max_devname_len = strlen(ifr.ifr_name);
173 strcpy(devname[i], ifr.ifr_name);
176 printf("new index %d (%s)\n", i, devname[i]);
182 int main(int argc, char **argv)
187 unsigned char timestamp = 0;
188 unsigned char silent = 0;
189 unsigned char silentani = 0;
190 unsigned char color = 0;
191 unsigned char view = 0;
192 unsigned char log = 0;
193 unsigned char logfrmt = 0;
195 int currmax, numfilter;
197 struct sockaddr_can addr;
198 struct can_filter rfilter[MAXFILTER];
199 can_err_mask_t err_mask;
200 struct can_frame frame;
203 struct timeval tv, last_tv;
204 FILE *logfile = NULL;
206 signal(SIGTERM, sigterm);
207 signal(SIGHUP, sigterm);
208 signal(SIGINT, sigterm);
213 while ((opt = getopt(argc, argv, "t:cias:b:B:lLh?")) != -1) {
216 timestamp = optarg[0];
217 if ((timestamp != 'a') && (timestamp != 'A') &&
218 (timestamp != 'd') && (timestamp != 'z')) {
219 printf("%s: unknown timestamp mode '%c' - ignored\n",
220 basename(argv[0]), optarg[0]);
230 view |= CANLIB_VIEW_BINARY;
234 view |= CANLIB_VIEW_ASCII;
238 silent = atoi(optarg);
243 if (strlen(optarg) >= IFNAMSIZ) {
244 printf("Name of CAN device '%s' is too long!\n\n", optarg);
247 bridge = socket(PF_CAN, SOCK_RAW, CAN_RAW);
249 perror("bridge socket");
252 addr.can_family = AF_CAN;
253 strcpy(ifr.ifr_name, optarg);
254 if (ioctl(bridge, SIOCGIFINDEX, &ifr) < 0)
255 perror("SIOCGIFINDEX");
256 addr.can_ifindex = ifr.ifr_ifindex;
258 if (!addr.can_ifindex) {
259 perror("invalid bridge interface");
266 setsockopt(bridge, SOL_CAN_RAW, CAN_RAW_LOOPBACK,
267 &loopback, sizeof(loopback));
270 if (bind(bridge, (struct sockaddr *)&addr, sizeof(addr)) < 0) {
271 perror("bridge bind");
286 print_usage(basename(argv[0]));
292 if (optind == argc) {
293 print_usage(basename(argv[0]));
297 currmax = argc - optind; /* find real number of CAN devices */
299 if (currmax > MAXSOCK) {
300 printf("More than %d CAN devices given on commandline!\n", MAXSOCK);
304 for (i=0; i < currmax; i++) {
306 ptr = argv[optind+i];
307 nptr = strchr(ptr, ',');
310 printf("open %d '%s'.\n", i, ptr);
313 s[i] = socket(PF_CAN, SOCK_RAW, CAN_RAW);
320 nbytes = nptr - ptr; /* interface name is up the first ',' */
322 nbytes = strlen(ptr); /* no ',' found => no filter definitions */
324 if (nbytes >= IFNAMSIZ) {
325 printf("name of CAN device '%s' is too long!\n", ptr);
329 if (nbytes > max_devname_len)
330 max_devname_len = nbytes; /* for nice printing */
332 addr.can_family = AF_CAN;
334 memset(&ifr.ifr_name, 0, sizeof(ifr.ifr_name));
335 strncpy(ifr.ifr_name, ptr, nbytes);
338 printf("using interface name '%s'.\n", ifr.ifr_name);
341 if (strcmp(ANYDEV, ifr.ifr_name)) {
342 if (ioctl(s[i], SIOCGIFINDEX, &ifr) < 0) {
343 perror("SIOCGIFINDEX");
346 addr.can_ifindex = ifr.ifr_ifindex;
348 addr.can_ifindex = 0; /* any can interface */
352 /* found a ',' after the interface name => check for filters */
359 ptr = nptr+1; /* hop behind the ',' */
360 nptr = strchr(ptr, ','); /* update exit condition */
362 if (sscanf(ptr, "%lx:%lx",
363 (long unsigned int *)
364 &rfilter[numfilter].can_id,
365 (long unsigned int *)
366 &rfilter[numfilter].can_mask) == 2) {
368 } else if (sscanf(ptr, "%lx~%lx",
369 (long unsigned int *)
370 &rfilter[numfilter].can_id,
371 (long unsigned int *)
372 &rfilter[numfilter].can_mask) == 2) {
373 rfilter[numfilter].can_id |= CAN_INV_FILTER;
375 } else if (sscanf(ptr, "#%lx",
376 (long unsigned int *)&err_mask) != 1) {
377 printf("Error in filter option parsing: '%s'\n", ptr);
381 if (numfilter > MAXFILTER) {
382 printf("Too many filters specified for '%s'.\n",
389 setsockopt(s[i], SOL_CAN_RAW, CAN_RAW_ERR_FILTER,
390 &err_mask, sizeof(err_mask));
393 setsockopt(s[i], SOL_CAN_RAW, CAN_RAW_FILTER,
394 &rfilter, numfilter * sizeof(struct can_filter));
397 if (bind(s[i], (struct sockaddr *)&addr, sizeof(addr)) < 0) {
406 char fname[sizeof("candump-2006-11-20_202026.log")+1];
408 if (time(&currtime) == (time_t)-1) {
413 localtime_r(&currtime, &now);
415 sprintf(fname, "candump-%04d-%02d-%02d_%02d%02d%02d.log",
423 printf("\nEnabling Logfile '%s'\n\n", fname);
425 logfile = fopen(fname, "w");
435 for (i=0; i<currmax; i++)
438 if ((ret = select(s[currmax-1]+1, &rdfs, NULL, NULL, NULL)) < 0) {
444 for (i=0; i<currmax; i++) { /* check all CAN RAW sockets */
446 if (FD_ISSET(s[i], &rdfs)) {
448 socklen_t len = sizeof(addr);
451 nbytes = recvfrom(s[i], &frame, sizeof(struct can_frame), 0,
452 (struct sockaddr*)&addr, &len);
458 if (nbytes < sizeof(struct can_frame)) {
459 fprintf(stderr, "read: incomplete CAN frame\n");
464 nbytes = write(bridge, &frame, sizeof(struct can_frame));
466 perror("bridge write");
468 } else if (nbytes < sizeof(struct can_frame)) {
469 fprintf(stderr,"bridge write: incomplete CAN frame\n");
474 if (timestamp || log || logfrmt)
475 if (ioctl(s[i], SIOCGSTAMP, &tv) < 0)
476 perror("SIOCGSTAMP");
479 idx = idx2dindex(addr.can_ifindex, s[i]);
482 /* log CAN frame with absolute timestamp & device */
483 fprintf(logfile, "(%ld.%06ld) ", tv.tv_sec, tv.tv_usec);
484 fprintf(logfile, "%*s ", max_devname_len, devname[idx]);
485 /* without seperator as logfile use-case is parsing */
486 fprint_canframe(logfile, &frame, "\n", 0);
490 /* print CAN frame in log file style to stdout */
491 printf("(%ld.%06ld) ", tv.tv_sec, tv.tv_usec);
492 printf("%*s ", max_devname_len, devname[idx]);
493 fprint_canframe(stdout, &frame, "\n", 0);
494 goto out_fflush; /* no other output to stdout */
499 printf("%c\b", anichar[silentani%=MAXANI]);
502 goto out_fflush; /* no other output to stdout */
505 printf(" %s", (color>2)?col_on[idx%MAXCOL]:"");
509 case 'a': /* absolute with timestamp */
510 printf("(%ld.%06ld) ", tv.tv_sec, tv.tv_usec);
513 case 'A': /* absolute with date */
518 tm = *localtime(&tv.tv_sec);
519 strftime(timestring, 24, "%Y-%m-%d %H:%M:%S", &tm);
520 printf("(%s.%06ld) ", timestring, tv.tv_usec);
524 case 'd': /* delta */
525 case 'z': /* starting with zero */
529 if (last_tv.tv_sec == 0) /* first init */
531 diff.tv_sec = tv.tv_sec - last_tv.tv_sec;
532 diff.tv_usec = tv.tv_usec - last_tv.tv_usec;
533 if (diff.tv_usec < 0)
534 diff.tv_sec--, diff.tv_usec += 1000000;
536 diff.tv_sec = diff.tv_usec = 0;
537 printf("(%ld.%06ld) ", diff.tv_sec, diff.tv_usec);
539 if (timestamp == 'd')
540 last_tv = tv; /* update for delta calculation */
544 default: /* no timestamp output */
548 printf(" %s", (color && (color<3))?col_on[idx%MAXCOL]:"");
549 printf("%*s", max_devname_len, devname[idx]);
550 printf("%s ", (color==1)?col_off:"");
552 fprint_long_canframe(stdout, &frame, NULL, view);
554 printf("%s", (color>1)?col_off:"");
563 for (i=0; i<currmax; i++)