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