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