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