]> rtime.felk.cvut.cz Git - can-utils.git/blob - candump.c
Do not allow to create error frame filters via standard filter sets.
[can-utils.git] / candump.c
1 /*
2  *  $Id$
3  */
4
5 /*
6  * candump.c
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 <socketcan-users@lists.berlios.de>
45  *
46  */
47
48 #include <stdio.h>
49 #include <stdlib.h>
50 #include <unistd.h>
51 #include <string.h>
52 #include <signal.h>
53 #include <ctype.h>
54 #include <libgen.h>
55 #include <time.h>
56
57 #include <sys/time.h>
58 #include <sys/types.h>
59 #include <sys/socket.h>
60 #include <sys/ioctl.h>
61 #include <sys/uio.h>
62 #include <net/if.h>
63
64 #include <linux/can.h>
65 #include <linux/can/raw.h>
66
67 #include "terminal.h"
68 #include "lib.h"
69
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 */
76
77 #define BOLD    ATTBOLD
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
84
85 const char col_on [MAXCOL][19] = {BLUE, RED, GREEN, BOLD, MAGENTA, CYAN};
86 const char col_off [] = ATTRESET;
87
88 static char devname[MAXIFNAMES][IFNAMSIZ+1];
89 static int  dindex[MAXIFNAMES];
90 static int  max_devname_len; /* to prevent frazzled device name output */ 
91
92 #define MAXANI 4
93 const char anichar[MAXANI] = {'|', '/', '-', '\\'};
94
95 extern int optind, opterr, optopt;
96
97 static volatile int running = 1;
98
99 void print_usage(char *prg)
100 {
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, "\nCAN IDs, masks and data content are given and expected in hexadecimal values.\n");
120         fprintf(stderr, "When can_id and can_mask are both 8 digits, they are assumed to be 29 bit EFF.\n");
121         fprintf(stderr, "Without any given filter all data frames are received ('0:0' default filter).\n");
122         fprintf(stderr, "\nUse interface name '%s' to receive from all CAN interfaces.\n", ANYDEV);
123         fprintf(stderr, "\nExamples:\n");
124         fprintf(stderr, "%s -c -c -ta can0,123:7FF,400:700,#000000FF can2,400~7F0 can3 can8\n", prg);
125         fprintf(stderr, "%s -l any,0~0,#FFFFFFFF    (log only error frames but no(!) data frames)\n", prg);
126         fprintf(stderr, "%s -l any,0:0,#FFFFFFFF    (log error frames and also all data frames)\n", prg);
127         fprintf(stderr, "%s vcan2,92345678:9FFFFFFF (match only for extended CAN ID 12345678)\n", prg);
128         fprintf(stderr, "%s vcan2,12345678:1FFFFFFF (analog to above due to 8 digit value length)\n", prg);
129         fprintf(stderr, "\n");
130 }
131
132 void sigterm(int signo)
133 {
134         running = 0;
135 }
136
137 int idx2dindex(int ifidx, int socket) {
138
139         int i;
140         struct ifreq ifr;
141
142         for (i=0; i < MAXIFNAMES; i++) {
143                 if (dindex[i] == ifidx)
144                         return i;
145         }
146
147         /* create new interface index cache entry */
148
149         /* remove index cache zombies first */
150         for (i=0; i < MAXIFNAMES; i++) {
151                 if (dindex[i]) {
152                         ifr.ifr_ifindex = dindex[i];
153                         if (ioctl(socket, SIOCGIFNAME, &ifr) < 0)
154                                 dindex[i] = 0;
155                 }
156         }
157
158         for (i=0; i < MAXIFNAMES; i++)
159                 if (!dindex[i]) /* free entry */
160                         break;
161
162         if (i == MAXIFNAMES) {
163                 printf("Interface index cache only supports %d interfaces.\n",
164                        MAXIFNAMES);
165                 exit(1);
166         }
167
168         dindex[i] = ifidx;
169
170         ifr.ifr_ifindex = ifidx;
171         if (ioctl(socket, SIOCGIFNAME, &ifr) < 0)
172                 perror("SIOCGIFNAME");
173
174         if (max_devname_len < strlen(ifr.ifr_name))
175                 max_devname_len = strlen(ifr.ifr_name);
176
177         strcpy(devname[i], ifr.ifr_name);
178
179 #ifdef DEBUG
180         printf("new index %d (%s)\n", i, devname[i]);
181 #endif
182
183         return i;
184 }
185
186 canid_t checkeff(char *ptr, char *nptr)
187 {
188         int len;
189
190         if (nptr)
191                 len = nptr - ptr;
192         else
193                 len = strlen(ptr);
194
195         if (len == 17 && (ptr[8] == ':' || ptr[8] == '~'))
196                 return CAN_EFF_FLAG;
197         else
198                 return 0;
199 }
200
201 int main(int argc, char **argv)
202 {
203         fd_set rdfs;
204         int s[MAXSOCK];
205         int bridge = 0;
206         unsigned char timestamp = 0;
207         unsigned char silent = 0;
208         unsigned char silentani = 0;
209         unsigned char color = 0;
210         unsigned char view = 0;
211         unsigned char log = 0;
212         unsigned char logfrmt = 0;
213         int opt, ret;
214         int currmax, numfilter;
215         char *ptr, *nptr;
216         canid_t eff;
217         struct sockaddr_can addr;
218         struct can_filter rfilter[MAXFILTER];
219         can_err_mask_t err_mask;
220         struct can_frame frame;
221         int nbytes, i;
222         struct ifreq ifr;
223         struct timeval tv, last_tv;
224         FILE *logfile = NULL;
225
226         signal(SIGTERM, sigterm);
227         signal(SIGHUP, sigterm);
228         signal(SIGINT, sigterm);
229
230         last_tv.tv_sec  = 0;
231         last_tv.tv_usec = 0;
232
233         while ((opt = getopt(argc, argv, "t:cias:b:B:lLh?")) != -1) {
234                 switch (opt) {
235                 case 't':
236                         timestamp = optarg[0];
237                         if ((timestamp != 'a') && (timestamp != 'A') &&
238                             (timestamp != 'd') && (timestamp != 'z')) {
239                                 printf("%s: unknown timestamp mode '%c' - ignored\n",
240                                        basename(argv[0]), optarg[0]);
241                                 timestamp = 0;
242                         }
243                         break;
244
245                 case 'c':
246                         color++;
247                         break;
248
249                 case 'i':
250                         view |= CANLIB_VIEW_BINARY;
251                         break;
252
253                 case 'a':
254                         view |= CANLIB_VIEW_ASCII;
255                         break;
256
257                 case 's':
258                         silent = atoi(optarg);
259                         break;
260
261                 case 'b':
262                 case 'B':
263                         if (strlen(optarg) >= IFNAMSIZ) {
264                                 printf("Name of CAN device '%s' is too long!\n\n", optarg);
265                                 return 1;
266                         } else {
267                                 bridge = socket(PF_CAN, SOCK_RAW, CAN_RAW);
268                                 if (bridge < 0) {
269                                         perror("bridge socket");
270                                         return 1;
271                                 }
272                                 addr.can_family = AF_CAN;
273                                 strcpy(ifr.ifr_name, optarg);
274                                 if (ioctl(bridge, SIOCGIFINDEX, &ifr) < 0)
275                                         perror("SIOCGIFINDEX");
276                                 addr.can_ifindex = ifr.ifr_ifindex;
277                 
278                                 if (!addr.can_ifindex) {
279                                         perror("invalid bridge interface");
280                                         return 1;
281                                 }
282
283                                 if (opt == 'B') {
284                                         int loopback = 0;
285
286                                         setsockopt(bridge, SOL_CAN_RAW, CAN_RAW_LOOPBACK,
287                                                    &loopback, sizeof(loopback));
288                                 }
289
290                                 if (bind(bridge, (struct sockaddr *)&addr, sizeof(addr)) < 0) {
291                                         perror("bridge bind");
292                                         return 1;
293                                 }
294                         }
295                         break;
296             
297                 case 'l':
298                         log = 1;
299                         break;
300
301                 case 'L':
302                         logfrmt = 1;
303                         break;
304
305                 default:
306                         print_usage(basename(argv[0]));
307                         exit(1);
308                         break;
309                 }
310         }
311
312         if (optind == argc) {
313                 print_usage(basename(argv[0]));
314                 exit(0);
315         }
316         
317         currmax = argc - optind; /* find real number of CAN devices */
318
319         if (currmax > MAXSOCK) {
320                 printf("More than %d CAN devices given on commandline!\n", MAXSOCK);
321                 return 1;
322         }
323
324         for (i=0; i < currmax; i++) {
325
326                 ptr = argv[optind+i];
327                 nptr = strchr(ptr, ',');
328
329 #ifdef DEBUG
330                 printf("open %d '%s'.\n", i, ptr);
331 #endif
332
333                 s[i] = socket(PF_CAN, SOCK_RAW, CAN_RAW);
334                 if (s[i] < 0) {
335                         perror("socket");
336                         return 1;
337                 }
338
339                 if (nptr)
340                         nbytes = nptr - ptr;  /* interface name is up the first ',' */
341                 else
342                         nbytes = strlen(ptr); /* no ',' found => no filter definitions */
343
344                 if (nbytes >= IFNAMSIZ) {
345                         printf("name of CAN device '%s' is too long!\n", ptr);
346                         return 1;
347                 }
348
349                 if (nbytes > max_devname_len)
350                         max_devname_len = nbytes; /* for nice printing */
351
352                 addr.can_family = AF_CAN;
353
354                 memset(&ifr.ifr_name, 0, sizeof(ifr.ifr_name));
355                 strncpy(ifr.ifr_name, ptr, nbytes);
356
357 #ifdef DEBUG
358                 printf("using interface name '%s'.\n", ifr.ifr_name);
359 #endif
360
361                 if (strcmp(ANYDEV, ifr.ifr_name)) {
362                         if (ioctl(s[i], SIOCGIFINDEX, &ifr) < 0) {
363                                 perror("SIOCGIFINDEX");
364                                 exit(1);
365                         }
366                         addr.can_ifindex = ifr.ifr_ifindex;
367                 } else
368                         addr.can_ifindex = 0; /* any can interface */
369
370                 if (nptr) {
371
372                         /* found a ',' after the interface name => check for filters */
373
374                         numfilter = 0;
375                         err_mask = 0;
376
377                         while (nptr) {
378
379                                 ptr = nptr+1; /* hop behind the ',' */
380                                 nptr = strchr(ptr, ','); /* update exit condition */
381
382                                 if (sscanf(ptr, "%lx:%lx",
383                                            (long unsigned int *)
384                                            &rfilter[numfilter].can_id, 
385                                            (long unsigned int *)
386                                            &rfilter[numfilter].can_mask) == 2) {
387                                         eff = checkeff(ptr, nptr);
388                                         rfilter[numfilter].can_id |= eff;
389                                         rfilter[numfilter].can_mask |= eff;
390                                         rfilter[numfilter].can_mask &= ~CAN_ERR_FLAG;
391                                         numfilter++;
392                                 } else if (sscanf(ptr, "%lx~%lx",
393                                                   (long unsigned int *)
394                                                   &rfilter[numfilter].can_id, 
395                                                   (long unsigned int *)
396                                                   &rfilter[numfilter].can_mask) == 2) {
397                                         rfilter[numfilter].can_id |= CAN_INV_FILTER;
398                                         eff = checkeff(ptr, nptr);
399                                         rfilter[numfilter].can_id |= eff;
400                                         rfilter[numfilter].can_mask |= eff;
401                                         rfilter[numfilter].can_mask &= ~CAN_ERR_FLAG;
402                                         numfilter++;
403                                 } else if (sscanf(ptr, "#%lx",
404                                                   (long unsigned int *)&err_mask) != 1) { 
405                                         printf("Error in filter option parsing: '%s'\n", ptr);
406                                         exit(1);
407                                 }
408
409                                 if (numfilter > MAXFILTER) {
410                                         printf("Too many filters specified for '%s'.\n",
411                                                ifr.ifr_name);
412                                         exit(1);
413                                 }
414                         }
415
416                         if (err_mask)
417                                 setsockopt(s[i], SOL_CAN_RAW, CAN_RAW_ERR_FILTER,
418                                            &err_mask, sizeof(err_mask));
419
420                         if (numfilter)
421                                 setsockopt(s[i], SOL_CAN_RAW, CAN_RAW_FILTER,
422                                            &rfilter, numfilter * sizeof(struct can_filter));
423                 } /* if (nptr) */
424
425                 if (bind(s[i], (struct sockaddr *)&addr, sizeof(addr)) < 0) {
426                         perror("bind");
427                         return 1;
428                 }
429         }
430
431         if (log) {
432                 time_t currtime;
433                 struct tm now;
434                 char fname[sizeof("candump-2006-11-20_202026.log")+1];
435
436                 if (time(&currtime) == (time_t)-1) {
437                         perror("time");
438                         return 1;
439                 }
440
441                 localtime_r(&currtime, &now);
442
443                 sprintf(fname, "candump-%04d-%02d-%02d_%02d%02d%02d.log",
444                         now.tm_year + 1900,
445                         now.tm_mon + 1,
446                         now.tm_mday,
447                         now.tm_hour,
448                         now.tm_min,
449                         now.tm_sec);
450
451                 printf("\nEnabling Logfile '%s'\n\n", fname);
452
453                 logfile = fopen(fname, "w");
454                 if (!logfile) {
455                         perror("logfile");
456                         return 1;
457                 }
458         }
459
460         while (running) {
461
462                 FD_ZERO(&rdfs);
463                 for (i=0; i<currmax; i++)
464                         FD_SET(s[i], &rdfs);
465
466                 if ((ret = select(s[currmax-1]+1, &rdfs, NULL, NULL, NULL)) < 0) {
467                         //perror("select");
468                         running = 0;
469                         continue;
470                 }
471
472                 for (i=0; i<currmax; i++) {  /* check all CAN RAW sockets */
473
474                         if (FD_ISSET(s[i], &rdfs)) {
475
476                                 socklen_t len = sizeof(addr);
477                                 int idx;
478
479                                 nbytes = recvfrom(s[i], &frame, sizeof(struct can_frame), 0,
480                                                   (struct sockaddr*)&addr, &len);
481                                 if (nbytes < 0) {
482                                         perror("read");
483                                         return 1;
484                                 }
485
486                                 if (nbytes < sizeof(struct can_frame)) {
487                                         fprintf(stderr, "read: incomplete CAN frame\n");
488                                         return 1;
489                                 }
490
491                                 if (bridge) {
492                                         nbytes = write(bridge, &frame, sizeof(struct can_frame));
493                                         if (nbytes < 0) {
494                                                 perror("bridge write");
495                                                 return 1;
496                                         } else if (nbytes < sizeof(struct can_frame)) {
497                                                 fprintf(stderr,"bridge write: incomplete CAN frame\n");
498                                                 return 1;
499                                         }
500                                 }
501                     
502                                 if (timestamp || log || logfrmt)
503                                         if (ioctl(s[i], SIOCGSTAMP, &tv) < 0)
504                                                 perror("SIOCGSTAMP");
505
506
507                                 idx = idx2dindex(addr.can_ifindex, s[i]);
508
509                                 if (log) {
510                                         /* log CAN frame with absolute timestamp & device */
511                                         fprintf(logfile, "(%ld.%06ld) ", tv.tv_sec, tv.tv_usec);
512                                         fprintf(logfile, "%*s ", max_devname_len, devname[idx]);
513                                         /* without seperator as logfile use-case is parsing */
514                                         fprint_canframe(logfile, &frame, "\n", 0);
515                                 }
516
517                                 if (logfrmt) {
518                                         /* print CAN frame in log file style to stdout */
519                                         printf("(%ld.%06ld) ", tv.tv_sec, tv.tv_usec);
520                                         printf("%*s ", max_devname_len, devname[idx]);
521                                         fprint_canframe(stdout, &frame, "\n", 0);
522                                         goto out_fflush; /* no other output to stdout */
523                                 }
524
525                                 if (silent){
526                                         if (silent == 1) {
527                                                 printf("%c\b", anichar[silentani%=MAXANI]);
528                                                 silentani++;
529                                         }
530                                         goto out_fflush; /* no other output to stdout */
531                                 }
532                       
533                                 printf(" %s", (color>2)?col_on[idx%MAXCOL]:"");
534
535                                 switch (timestamp) {
536
537                                 case 'a': /* absolute with timestamp */
538                                         printf("(%ld.%06ld) ", tv.tv_sec, tv.tv_usec);
539                                         break;
540
541                                 case 'A': /* absolute with date */
542                                 {
543                                         struct tm tm;
544                                         char timestring[25];
545
546                                         tm = *localtime(&tv.tv_sec);
547                                         strftime(timestring, 24, "%Y-%m-%d %H:%M:%S", &tm);
548                                         printf("(%s.%06ld) ", timestring, tv.tv_usec);
549                                 }
550                                 break;
551
552                                 case 'd': /* delta */
553                                 case 'z': /* starting with zero */
554                                 {
555                                         struct timeval diff;
556
557                                         if (last_tv.tv_sec == 0)   /* first init */
558                                                 last_tv = tv;
559                                         diff.tv_sec  = tv.tv_sec  - last_tv.tv_sec;
560                                         diff.tv_usec = tv.tv_usec - last_tv.tv_usec;
561                                         if (diff.tv_usec < 0)
562                                                 diff.tv_sec--, diff.tv_usec += 1000000;
563                                         if (diff.tv_sec < 0)
564                                                 diff.tv_sec = diff.tv_usec = 0;
565                                         printf("(%ld.%06ld) ", diff.tv_sec, diff.tv_usec);
566                                 
567                                         if (timestamp == 'd')
568                                                 last_tv = tv; /* update for delta calculation */
569                                 }
570                                 break;
571
572                                 default: /* no timestamp output */
573                                         break;
574                                 }
575
576                                 printf(" %s", (color && (color<3))?col_on[idx%MAXCOL]:"");
577                                 printf("%*s", max_devname_len, devname[idx]);
578                                 printf("%s  ", (color==1)?col_off:"");
579
580                                 fprint_long_canframe(stdout, &frame, NULL, view);
581
582                                 printf("%s", (color>1)?col_off:"");
583                                 printf("\n");
584                         }
585
586                 out_fflush:
587                         fflush(stdout);
588                 }
589         }
590
591         for (i=0; i<currmax; i++)
592                 close(s[i]);
593
594         if (bridge)
595                 close(bridge);
596
597         if (log)
598                 fclose(logfile);
599
600         return 0;
601 }