]> rtime.felk.cvut.cz Git - sojka/can-utils.git/blob - candump.c
Add functionality to
[sojka/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 SILENT_INI 42 /* detect user setting on commandline */
78 #define SILENT_OFF 0  /* no silent mode */
79 #define SILENT_ANI 1  /* silent mode with animation */
80 #define SILENT_ON  2  /* silent mode (completely silent) */
81
82 #define BOLD    ATTBOLD
83 #define RED     ATTBOLD FGRED
84 #define GREEN   ATTBOLD FGGREEN
85 #define YELLOW  ATTBOLD FGYELLOW
86 #define BLUE    ATTBOLD FGBLUE
87 #define MAGENTA ATTBOLD FGMAGENTA
88 #define CYAN    ATTBOLD FGCYAN
89
90 const char col_on [MAXCOL][19] = {BLUE, RED, GREEN, BOLD, MAGENTA, CYAN};
91 const char col_off [] = ATTRESET;
92
93 static char devname[MAXIFNAMES][IFNAMSIZ+1];
94 static int  dindex[MAXIFNAMES];
95 static int  max_devname_len; /* to prevent frazzled device name output */ 
96
97 #define MAXANI 4
98 const char anichar[MAXANI] = {'|', '/', '-', '\\'};
99
100 extern int optind, opterr, optopt;
101
102 static volatile int running = 1;
103
104 void print_usage(char *prg)
105 {
106         fprintf(stderr, "\nUsage: %s [options] <CAN interface>+\n", prg);
107         fprintf(stderr, "  (use CTRL-C to terminate %s)\n\n", prg);
108         fprintf(stderr, "Options: -t <type>   (timestamp: (a)bsolute/(d)elta/(z)ero/(A)bsolute w date)\n");
109         fprintf(stderr, "         -c          (increment color mode level)\n");
110         fprintf(stderr, "         -i          (binary output - may exceed 80 chars/line)\n");
111         fprintf(stderr, "         -a          (enable additional ASCII output)\n");
112         fprintf(stderr, "         -S          (swap byte order in printed CAN data[] - marked with '%c' )\n", SWAP_DELIMITER);
113         fprintf(stderr, "         -s <level>  (silent mode - %d: off (default) %d: animation %d: silent)\n", SILENT_OFF, SILENT_ANI, SILENT_ON);
114         fprintf(stderr, "         -b <can>    (bridge mode - send received frames to <can>)\n");
115         fprintf(stderr, "         -B <can>    (bridge mode - like '-b' with disabled loopback)\n");
116         fprintf(stderr, "         -l          (log CAN-frames into file. Sets '-s %d' by default)\n", SILENT_ON);
117         fprintf(stderr, "         -L          (use log file format on stdout)\n");
118         fprintf(stderr, "         -n <count>  (terminate after receiption of <count> CAN frames)\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, "\nUp to %d comma separated filters can be specified for each given CAN interface:\n", MAXFILTER);
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");
138 }
139
140 void sigterm(int signo)
141 {
142         running = 0;
143 }
144
145 int idx2dindex(int ifidx, int socket) {
146
147         int i;
148         struct ifreq ifr;
149
150         for (i=0; i < MAXIFNAMES; i++) {
151                 if (dindex[i] == ifidx)
152                         return i;
153         }
154
155         /* create new interface index cache entry */
156
157         /* remove index cache zombies first */
158         for (i=0; i < MAXIFNAMES; i++) {
159                 if (dindex[i]) {
160                         ifr.ifr_ifindex = dindex[i];
161                         if (ioctl(socket, SIOCGIFNAME, &ifr) < 0)
162                                 dindex[i] = 0;
163                 }
164         }
165
166         for (i=0; i < MAXIFNAMES; i++)
167                 if (!dindex[i]) /* free entry */
168                         break;
169
170         if (i == MAXIFNAMES) {
171                 fprintf(stderr, "Interface index cache only supports %d interfaces.\n",
172                        MAXIFNAMES);
173                 exit(1);
174         }
175
176         dindex[i] = ifidx;
177
178         ifr.ifr_ifindex = ifidx;
179         if (ioctl(socket, SIOCGIFNAME, &ifr) < 0)
180                 perror("SIOCGIFNAME");
181
182         if (max_devname_len < strlen(ifr.ifr_name))
183                 max_devname_len = strlen(ifr.ifr_name);
184
185         strcpy(devname[i], ifr.ifr_name);
186
187 #ifdef DEBUG
188         printf("new index %d (%s)\n", i, devname[i]);
189 #endif
190
191         return i;
192 }
193
194 int main(int argc, char **argv)
195 {
196         fd_set rdfs;
197         int s[MAXSOCK];
198         int bridge = 0;
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;
206         int count = 0;
207         int opt, ret;
208         int currmax, numfilter;
209         char *ptr, *nptr;
210         struct sockaddr_can addr;
211         struct can_filter rfilter[MAXFILTER];
212         can_err_mask_t err_mask;
213         struct can_frame frame;
214         int nbytes, i;
215         struct ifreq ifr;
216         struct timeval tv, last_tv;
217         FILE *logfile = NULL;
218
219         signal(SIGTERM, sigterm);
220         signal(SIGHUP, sigterm);
221         signal(SIGINT, sigterm);
222
223         last_tv.tv_sec  = 0;
224         last_tv.tv_usec = 0;
225
226         while ((opt = getopt(argc, argv, "t:ciaSs:b:B:lLn:h?")) != -1) {
227                 switch (opt) {
228                 case 't':
229                         timestamp = optarg[0];
230                         if ((timestamp != 'a') && (timestamp != 'A') &&
231                             (timestamp != 'd') && (timestamp != 'z')) {
232                                 fprintf(stderr, "%s: unknown timestamp mode '%c' - ignored\n",
233                                        basename(argv[0]), optarg[0]);
234                                 timestamp = 0;
235                         }
236                         break;
237
238                 case 'c':
239                         color++;
240                         break;
241
242                 case 'i':
243                         view |= CANLIB_VIEW_BINARY;
244                         break;
245
246                 case 'a':
247                         view |= CANLIB_VIEW_ASCII;
248                         break;
249
250                 case 'S':
251                         view |= CANLIB_VIEW_SWAP;
252                         break;
253
254                 case 's':
255                         silent = atoi(optarg);
256                         if (silent > SILENT_ON) {
257                                 print_usage(basename(argv[0]));
258                                 exit(1);
259                         }
260                         break;
261
262                 case 'b':
263                 case 'B':
264                         if (strlen(optarg) >= IFNAMSIZ) {
265                                 fprintf(stderr, "Name of CAN device '%s' is too long!\n\n", optarg);
266                                 return 1;
267                         } else {
268                                 bridge = socket(PF_CAN, SOCK_RAW, CAN_RAW);
269                                 if (bridge < 0) {
270                                         perror("bridge socket");
271                                         return 1;
272                                 }
273                                 addr.can_family = AF_CAN;
274                                 strcpy(ifr.ifr_name, optarg);
275                                 if (ioctl(bridge, SIOCGIFINDEX, &ifr) < 0)
276                                         perror("SIOCGIFINDEX");
277                                 addr.can_ifindex = ifr.ifr_ifindex;
278                 
279                                 if (!addr.can_ifindex) {
280                                         perror("invalid bridge interface");
281                                         return 1;
282                                 }
283
284                                 /* disable default receive filter on this write-only RAW socket */
285                                 setsockopt(bridge, SOL_CAN_RAW, CAN_RAW_FILTER, NULL, 0);
286
287                                 if (opt == 'B') {
288                                         int loopback = 0;
289
290                                         setsockopt(bridge, SOL_CAN_RAW, CAN_RAW_LOOPBACK,
291                                                    &loopback, sizeof(loopback));
292                                 }
293
294                                 if (bind(bridge, (struct sockaddr *)&addr, sizeof(addr)) < 0) {
295                                         perror("bridge bind");
296                                         return 1;
297                                 }
298                         }
299                         break;
300             
301                 case 'l':
302                         log = 1;
303                         break;
304
305                 case 'L':
306                         logfrmt = 1;
307                         break;
308
309                 case 'n':
310                         count = atoi(optarg);
311                         if (count < 1) {
312                                 print_usage(basename(argv[0]));
313                                 exit(1);
314                         }
315                         break;
316
317                 default:
318                         print_usage(basename(argv[0]));
319                         exit(1);
320                         break;
321                 }
322         }
323
324         if (optind == argc) {
325                 print_usage(basename(argv[0]));
326                 exit(0);
327         }
328         
329         if (logfrmt && view) {
330                 fprintf(stderr, "Log file format selected: Please disable ASCII/BINARY/SWAP options!\n");
331                 exit(0);
332         }
333
334         if (silent == SILENT_INI) {
335                 if (log) {
336                         fprintf(stderr, "\nDisabled standard output while logging.");
337                         silent = SILENT_ON; /* disable output on stdout */
338                 } else
339                         silent = SILENT_OFF; /* default output */
340         }
341
342         currmax = argc - optind; /* find real number of CAN devices */
343
344         if (currmax > MAXSOCK) {
345                 fprintf(stderr, "More than %d CAN devices given on commandline!\n", MAXSOCK);
346                 return 1;
347         }
348
349         for (i=0; i < currmax; i++) {
350
351                 ptr = argv[optind+i];
352                 nptr = strchr(ptr, ',');
353
354 #ifdef DEBUG
355                 printf("open %d '%s'.\n", i, ptr);
356 #endif
357
358                 s[i] = socket(PF_CAN, SOCK_RAW, CAN_RAW);
359                 if (s[i] < 0) {
360                         perror("socket");
361                         return 1;
362                 }
363
364                 if (nptr)
365                         nbytes = nptr - ptr;  /* interface name is up the first ',' */
366                 else
367                         nbytes = strlen(ptr); /* no ',' found => no filter definitions */
368
369                 if (nbytes >= IFNAMSIZ) {
370                         fprintf(stderr, "name of CAN device '%s' is too long!\n", ptr);
371                         return 1;
372                 }
373
374                 if (nbytes > max_devname_len)
375                         max_devname_len = nbytes; /* for nice printing */
376
377                 addr.can_family = AF_CAN;
378
379                 memset(&ifr.ifr_name, 0, sizeof(ifr.ifr_name));
380                 strncpy(ifr.ifr_name, ptr, nbytes);
381
382 #ifdef DEBUG
383                 printf("using interface name '%s'.\n", ifr.ifr_name);
384 #endif
385
386                 if (strcmp(ANYDEV, ifr.ifr_name)) {
387                         if (ioctl(s[i], SIOCGIFINDEX, &ifr) < 0) {
388                                 perror("SIOCGIFINDEX");
389                                 exit(1);
390                         }
391                         addr.can_ifindex = ifr.ifr_ifindex;
392                 } else
393                         addr.can_ifindex = 0; /* any can interface */
394
395                 if (nptr) {
396
397                         /* found a ',' after the interface name => check for filters */
398
399                         numfilter = 0;
400                         err_mask = 0;
401
402                         while (nptr) {
403
404                                 ptr = nptr+1; /* hop behind the ',' */
405                                 nptr = strchr(ptr, ','); /* update exit condition */
406
407                                 if (sscanf(ptr, "%lx:%lx",
408                                            (long unsigned int *)
409                                            &rfilter[numfilter].can_id, 
410                                            (long unsigned int *)
411                                            &rfilter[numfilter].can_mask) == 2) {
412                                         rfilter[numfilter].can_mask &= ~CAN_ERR_FLAG;
413                                         numfilter++;
414                                 } else if (sscanf(ptr, "%lx~%lx",
415                                                   (long unsigned int *)
416                                                   &rfilter[numfilter].can_id, 
417                                                   (long unsigned int *)
418                                                   &rfilter[numfilter].can_mask) == 2) {
419                                         rfilter[numfilter].can_id |= CAN_INV_FILTER;
420                                         rfilter[numfilter].can_mask &= ~CAN_ERR_FLAG;
421                                         numfilter++;
422                                 } else if (sscanf(ptr, "#%lx",
423                                                   (long unsigned int *)&err_mask) != 1) { 
424                                         fprintf(stderr, "Error in filter option parsing: '%s'\n", ptr);
425                                         exit(1);
426                                 }
427
428                                 if (numfilter > MAXFILTER) {
429                                         fprintf(stderr, "Too many filters specified for '%s'.\n",
430                                                ifr.ifr_name);
431                                         exit(1);
432                                 }
433                         }
434
435                         if (err_mask)
436                                 setsockopt(s[i], SOL_CAN_RAW, CAN_RAW_ERR_FILTER,
437                                            &err_mask, sizeof(err_mask));
438
439                         if (numfilter)
440                                 setsockopt(s[i], SOL_CAN_RAW, CAN_RAW_FILTER,
441                                            &rfilter, numfilter * sizeof(struct can_filter));
442                 } /* if (nptr) */
443
444                 if (bind(s[i], (struct sockaddr *)&addr, sizeof(addr)) < 0) {
445                         perror("bind");
446                         return 1;
447                 }
448         }
449
450         if (log) {
451                 time_t currtime;
452                 struct tm now;
453                 char fname[sizeof("candump-2006-11-20_202026.log")+1];
454
455                 if (time(&currtime) == (time_t)-1) {
456                         perror("time");
457                         return 1;
458                 }
459
460                 localtime_r(&currtime, &now);
461
462                 sprintf(fname, "candump-%04d-%02d-%02d_%02d%02d%02d.log",
463                         now.tm_year + 1900,
464                         now.tm_mon + 1,
465                         now.tm_mday,
466                         now.tm_hour,
467                         now.tm_min,
468                         now.tm_sec);
469
470                 if (silent != SILENT_ON)
471                         printf("\nWarning: console output active while logging!");
472
473                 fprintf(stderr, "\nEnabling Logfile '%s'\n\n", fname);
474
475                 logfile = fopen(fname, "w");
476                 if (!logfile) {
477                         perror("logfile");
478                         return 1;
479                 }
480         }
481
482         while (running) {
483
484                 FD_ZERO(&rdfs);
485                 for (i=0; i<currmax; i++)
486                         FD_SET(s[i], &rdfs);
487
488                 if ((ret = select(s[currmax-1]+1, &rdfs, NULL, NULL, NULL)) < 0) {
489                         //perror("select");
490                         running = 0;
491                         continue;
492                 }
493
494                 for (i=0; i<currmax; i++) {  /* check all CAN RAW sockets */
495
496                         if (FD_ISSET(s[i], &rdfs)) {
497
498                                 socklen_t len = sizeof(addr);
499                                 int idx;
500
501                                 nbytes = recvfrom(s[i], &frame, sizeof(struct can_frame), 0,
502                                                   (struct sockaddr*)&addr, &len);
503                                 if (nbytes < 0) {
504                                         perror("read");
505                                         return 1;
506                                 }
507
508                                 if (nbytes < sizeof(struct can_frame)) {
509                                         fprintf(stderr, "read: incomplete CAN frame\n");
510                                         return 1;
511                                 }
512
513                                 if (count && (--count == 0))
514                                         running = 0;
515
516                                 if (bridge) {
517                                         nbytes = write(bridge, &frame, sizeof(struct can_frame));
518                                         if (nbytes < 0) {
519                                                 perror("bridge write");
520                                                 return 1;
521                                         } else if (nbytes < sizeof(struct can_frame)) {
522                                                 fprintf(stderr,"bridge write: incomplete CAN frame\n");
523                                                 return 1;
524                                         }
525                                 }
526                     
527                                 if (timestamp || log || logfrmt)
528                                         if (ioctl(s[i], SIOCGSTAMP, &tv) < 0)
529                                                 perror("SIOCGSTAMP");
530
531
532                                 idx = idx2dindex(addr.can_ifindex, s[i]);
533
534                                 if (log) {
535                                         /* log CAN frame with absolute timestamp & device */
536                                         fprintf(logfile, "(%ld.%06ld) ", tv.tv_sec, tv.tv_usec);
537                                         fprintf(logfile, "%*s ", max_devname_len, devname[idx]);
538                                         /* without seperator as logfile use-case is parsing */
539                                         fprint_canframe(logfile, &frame, "\n", 0);
540                                 }
541
542                                 if (logfrmt) {
543                                         /* print CAN frame in log file style to stdout */
544                                         printf("(%ld.%06ld) ", tv.tv_sec, tv.tv_usec);
545                                         printf("%*s ", max_devname_len, devname[idx]);
546                                         fprint_canframe(stdout, &frame, "\n", 0);
547                                         goto out_fflush; /* no other output to stdout */
548                                 }
549
550                                 if (silent != SILENT_OFF){
551                                         if (silent == SILENT_ANI) {
552                                                 printf("%c\b", anichar[silentani%=MAXANI]);
553                                                 silentani++;
554                                         }
555                                         goto out_fflush; /* no other output to stdout */
556                                 }
557                       
558                                 printf(" %s", (color>2)?col_on[idx%MAXCOL]:"");
559
560                                 switch (timestamp) {
561
562                                 case 'a': /* absolute with timestamp */
563                                         printf("(%ld.%06ld) ", tv.tv_sec, tv.tv_usec);
564                                         break;
565
566                                 case 'A': /* absolute with date */
567                                 {
568                                         struct tm tm;
569                                         char timestring[25];
570
571                                         tm = *localtime(&tv.tv_sec);
572                                         strftime(timestring, 24, "%Y-%m-%d %H:%M:%S", &tm);
573                                         printf("(%s.%06ld) ", timestring, tv.tv_usec);
574                                 }
575                                 break;
576
577                                 case 'd': /* delta */
578                                 case 'z': /* starting with zero */
579                                 {
580                                         struct timeval diff;
581
582                                         if (last_tv.tv_sec == 0)   /* first init */
583                                                 last_tv = tv;
584                                         diff.tv_sec  = tv.tv_sec  - last_tv.tv_sec;
585                                         diff.tv_usec = tv.tv_usec - last_tv.tv_usec;
586                                         if (diff.tv_usec < 0)
587                                                 diff.tv_sec--, diff.tv_usec += 1000000;
588                                         if (diff.tv_sec < 0)
589                                                 diff.tv_sec = diff.tv_usec = 0;
590                                         printf("(%ld.%06ld) ", diff.tv_sec, diff.tv_usec);
591                                 
592                                         if (timestamp == 'd')
593                                                 last_tv = tv; /* update for delta calculation */
594                                 }
595                                 break;
596
597                                 default: /* no timestamp output */
598                                         break;
599                                 }
600
601                                 printf(" %s", (color && (color<3))?col_on[idx%MAXCOL]:"");
602                                 printf("%*s", max_devname_len, devname[idx]);
603                                 printf("%s  ", (color==1)?col_off:"");
604
605                                 fprint_long_canframe(stdout, &frame, NULL, view);
606
607                                 printf("%s", (color>1)?col_off:"");
608                                 printf("\n");
609                         }
610
611                 out_fflush:
612                         fflush(stdout);
613                 }
614         }
615
616         for (i=0; i<currmax; i++)
617                 close(s[i]);
618
619         if (bridge)
620                 close(bridge);
621
622         if (log)
623                 fclose(logfile);
624
625         return 0;
626 }