]> rtime.felk.cvut.cz Git - can-utils.git/blob - candump.c
Added new commandline option '-B' which acts like the bridging option '-b' but
[can-utils.git] / candump.c
1 /*
2  *  $Id$
3  */
4
5 /*
6  * candump.c
7  *
8  * Copyright (c) 2002-2005 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, the following disclaimer and
16  *    the referenced file 'COPYING'.
17  * 2. Redistributions in binary form must reproduce the above copyright
18  *    notice, this list of conditions and the following disclaimer in the
19  *    documentation and/or other materials provided with the distribution.
20  * 3. Neither the name of Volkswagen nor the names of its contributors
21  *    may be used to endorse or promote products derived from this software
22  *    without specific prior written permission.
23  *
24  * Alternatively, provided that this notice is retained in full, this
25  * software may be distributed under the terms of the GNU General
26  * Public License ("GPL") version 2 as distributed in the 'COPYING'
27  * file from the main directory of the linux kernel source.
28  *
29  * The provided data structures and external interfaces from this code
30  * are not restricted to be used by modules with a GPL compatible license.
31  *
32  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
33  * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
34  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
35  * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
36  * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
37  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
38  * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
39  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
40  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
41  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
42  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
43  * DAMAGE.
44  *
45  * Send feedback to <socketcan-users@lists.berlios.de>
46  *
47  */
48
49 #include <stdio.h>
50 #include <stdlib.h>
51 #include <unistd.h>
52 #include <string.h>
53 #include <signal.h>
54 #include <ctype.h>
55 #include <libgen.h>
56 #include <time.h>
57
58 #include <sys/time.h>
59 #include <sys/types.h>
60 #include <sys/socket.h>
61 #include <sys/ioctl.h>
62 #include <sys/uio.h>
63 #include <net/if.h>
64
65 #include <linux/can.h>
66 #include <linux/can/raw.h>
67
68 #include "terminal.h"
69 #include "lib.h"
70
71 #define MAXDEV 6 /* change sscanf()'s manually if changed here */
72 #define ANYDEV "any"
73 #define ANL "\r\n" /* newline in ASC mode */
74
75 #define BOLD    ATTBOLD
76 #define RED     ATTBOLD FGRED
77 #define GREEN   ATTBOLD FGGREEN
78 #define YELLOW  ATTBOLD FGYELLOW
79 #define BLUE    ATTBOLD FGBLUE
80 #define MAGENTA ATTBOLD FGMAGENTA
81 #define CYAN    ATTBOLD FGCYAN
82
83 const char col_on [MAXDEV][19] = {BOLD, MAGENTA, GREEN, BLUE, CYAN, RED};
84 const char col_off [] = ATTRESET;
85
86 static char devname[MAXDEV][IFNAMSIZ+1];
87 static int  dindex[MAXDEV];
88 static int  max_devname_len;
89
90 #define MAXANI 8
91 const char anichar[MAXANI] = {'|', '/', '-', '\\', '|', '/', '-', '\\'};
92
93 extern int optind, opterr, optopt;
94
95 static volatile int running = 1;
96
97 void print_usage(char *prg)
98 {
99     fprintf(stderr, "Usage: %s [can-interfaces]\n", prg);
100     fprintf(stderr, "  (use CTRL-C to terminate %s)\n", prg);
101     fprintf(stderr, "Options: -m <mask>   (default 0x00000000)\n");
102     fprintf(stderr, "         -v <value>  (default 0x00000000)\n");
103     fprintf(stderr, "         -i <0|1>    (inv_filter)\n");
104     fprintf(stderr, "         -e <emask>  (mask for error frames)\n");
105     fprintf(stderr, "         -t <type>   (timestamp: Absolute/Delta/Zero)\n");
106     fprintf(stderr, "         -c          (color mode)\n");
107     fprintf(stderr, "         -a          (enable additional ASCII output)\n");
108     fprintf(stderr, "         -s <level>  (silent mode - 1: animation 2: nothing)\n");
109     fprintf(stderr, "         -b <can>    (bridge mode - send received frames to <can>)\n");
110     fprintf(stderr, "         -B <can>    (bridge mode - like '-b' with disabled loopback)\n");
111     fprintf(stderr, "         -l          (log CAN-frames into file)\n");
112     fprintf(stderr, "         -L          (use log file format on stdout)\n");
113     fprintf(stderr, "\n");
114     fprintf(stderr, "When using more than one CAN interface the options\n");
115     fprintf(stderr, "m/v/i/e have comma seperated values e.g. '-m 0,7FF,0'\n");
116     fprintf(stderr, "Use interface name '%s' to receive from all can-interfaces\n", ANYDEV);
117 }
118
119 void sigterm(int signo)
120 {
121     running = 0;
122 }
123
124 int idx2dindex(int ifidx, int socket) {
125
126     int i;
127     struct ifreq ifr;
128
129     for (i=0; i<MAXDEV; i++) {
130         if (dindex[i] == ifidx)
131             return i;
132     }
133
134     /* create new interface index cache entry */
135
136     for (i=0; i < MAXDEV; i++)
137         if (!dindex[i]) /* free entry */
138             break;
139
140     if (i == MAXDEV) {
141         printf("BUG in interface index cache! MAXDEV?\n");
142         exit(1);
143     }
144
145     dindex[i] = ifidx;
146
147     ifr.ifr_ifindex = ifidx;
148     if (ioctl(socket, SIOCGIFNAME, &ifr) < 0)
149         perror("SIOCGIFNAME");
150
151     if (max_devname_len < strlen(ifr.ifr_name))
152         max_devname_len = strlen(ifr.ifr_name);
153
154     strcpy(devname[i], ifr.ifr_name);
155
156 #ifdef DEBUG
157     printf("new index %d (%s)\n", i, devname[i]);
158 #endif
159
160     return i;
161 }
162
163 int main(int argc, char **argv)
164 {
165     fd_set rdfs;
166     int s[MAXDEV];
167     int bridge = 0;
168     canid_t mask[MAXDEV] = {0};
169     canid_t value[MAXDEV] = {0};
170     int inv_filter[MAXDEV] = {0};
171     can_err_mask_t err_mask[MAXDEV] = {0};
172     unsigned char timestamp = 0;
173     unsigned char silent = 0;
174     unsigned char silentani = 0;
175     unsigned char color = 0;
176     unsigned char ascii = 0;
177     unsigned char log = 0;
178     unsigned char logfrmt = 0;
179     int opt, ret;
180     int currmax = 1; /* we assume at least one can bus ;-) */
181     struct sockaddr_can addr;
182     struct can_filter rfilter;
183     struct can_frame frame;
184     int nbytes, i, j;
185     struct ifreq ifr;
186     struct timeval tv, last_tv;
187     FILE *logfile = NULL;
188
189     signal(SIGTERM, sigterm);
190     signal(SIGHUP, sigterm);
191     signal(SIGINT, sigterm);
192
193     last_tv.tv_sec  = 0;
194     last_tv.tv_usec = 0;
195
196     while ((opt = getopt(argc, argv, "m:v:i:e:t:cas:b:B:lL")) != -1) {
197         switch (opt) {
198         case 'm':
199             i = sscanf(optarg, "%x,%x,%x,%x,%x,%x",
200                        &mask[0], &mask[1], &mask[2],
201                        &mask[3], &mask[4], &mask[5]);
202             if (i > currmax)
203                 currmax = i;
204             break;
205
206         case 'v':
207             i = sscanf(optarg, "%x,%x,%x,%x,%x,%x",
208                        &value[0], &value[1], &value[2],
209                        &value[3], &value[4], &value[5]);
210             if (i > currmax)
211                 currmax = i;
212             break;
213
214         case 'i':
215             i = sscanf(optarg, "%d,%d,%d,%d,%d,%d",
216                        &inv_filter[0], &inv_filter[1], &inv_filter[2],
217                        &inv_filter[3], &inv_filter[4], &inv_filter[5]);
218             if (i > currmax)
219                 currmax = i;
220             break;
221
222         case 'e':
223             i = sscanf(optarg, "%x,%x,%x,%x,%x,%x",
224                        &err_mask[0], &err_mask[1], &err_mask[2],
225                        &err_mask[3], &err_mask[4], &err_mask[5]);
226             if (i > currmax)
227                 currmax = i;
228             break;
229
230         case 't':
231             timestamp = optarg[0];
232             if ((timestamp != 'a') && (timestamp != 'A') &&
233                 (timestamp != 'd') && (timestamp != 'z')) {
234                 printf("%s: unknown timestamp mode '%c' - ignored\n",
235                        basename(argv[0]), optarg[0]);
236                 timestamp = 0;
237             }
238             break;
239
240         case 'c':
241             color++;
242             break;
243
244         case 'a':
245             ascii = 1;
246             break;
247
248         case 's':
249             silent = atoi(optarg);
250             break;
251
252         case 'b':
253         case 'B':
254             if (strlen(optarg) >= IFNAMSIZ) {
255                 printf("Name of CAN device '%s' is too long!\n\n", optarg);
256                 return 1;
257             }
258             else {
259                 if ((bridge = socket(PF_CAN, SOCK_RAW, CAN_RAW)) < 0) {
260                     perror("bridge socket");
261                     return 1;
262                 }
263                 addr.can_family = AF_CAN;
264                 strcpy(ifr.ifr_name, optarg);
265                 if (ioctl(bridge, SIOCGIFINDEX, &ifr) < 0)
266                     perror("SIOCGIFINDEX");
267                 addr.can_ifindex = ifr.ifr_ifindex;
268                 
269                 if (!addr.can_ifindex) {
270                     perror("invalid bridge interface");
271                     return 1;
272                 }
273
274                 if (opt == 'B') {
275                     int loopback = 0;
276
277                     setsockopt(bridge, SOL_CAN_RAW, CAN_RAW_LOOPBACK, &loopback, sizeof(loopback));
278                 }
279
280                 if (bind(bridge, (struct sockaddr *)&addr, sizeof(addr)) < 0) {
281                     perror("bridge bind");
282                     return 1;
283                 }
284             }
285             break;
286             
287         case 'l':
288             log = 1;
289             break;
290
291         case 'L':
292             logfrmt = 1;
293             break;
294
295         default:
296             fprintf(stderr, "Unknown option %c\n", opt);
297             print_usage(basename(argv[0]));
298             exit(1);
299             break;
300         }
301     }
302
303     if (optind == argc) {
304         print_usage(basename(argv[0]));
305         exit(0);
306     }
307         
308     /* count in options higher than device count ? */
309     if (optind + currmax > argc) {
310         printf("low count of CAN devices!\n");
311         return 1;
312     }
313
314     currmax = argc - optind; /* find real number of CAN devices */
315
316     if (currmax > MAXDEV) {
317         printf("More than %d CAN devices!\n", MAXDEV);
318         return 1;
319     }
320
321     for (i=0; i<currmax; i++) {
322
323 #ifdef DEBUG
324         printf("open %d '%s' m%08X v%08X i%d e%d.\n",
325                i, argv[optind+i], mask[i], value[i],
326                inv_filter[i], err_mask[i]);
327 #endif
328
329         if ((s[i] = socket(PF_CAN, SOCK_RAW, CAN_RAW)) < 0) {
330             perror("socket");
331             return 1;
332         }
333
334         if (mask[i] || value[i]) {
335
336             printf("CAN ID filter[%d] for %s set to "
337                    "mask = %08X, value = %08X %s\n",
338                    i, argv[optind+i], mask[i], value[i],
339                    (inv_filter[i]) ? "(inv_filter)" : "");
340
341             rfilter.can_id   = value[i];
342             rfilter.can_mask = mask[i];
343             if (inv_filter[i])
344                 rfilter.can_id |= CAN_INV_FILTER;
345
346             setsockopt(s[i], SOL_CAN_RAW, CAN_RAW_FILTER,
347                        &rfilter, sizeof(rfilter));
348         }
349
350         if (err_mask[i])
351             setsockopt(s[i], SOL_CAN_RAW, CAN_RAW_ERR_FILTER,
352                        &err_mask[i], sizeof(err_mask[i]));
353
354         j = strlen(argv[optind+i]);
355
356         if (!(j < IFNAMSIZ)) {
357             printf("name of CAN device '%s' is too long!\n", argv[optind+i]);
358             return 1;
359         }
360
361         if (j > max_devname_len)
362             max_devname_len = j; /* for nice printing */
363
364         addr.can_family = AF_CAN;
365
366         if (strcmp(ANYDEV, argv[optind+i])) {
367             strcpy(ifr.ifr_name, argv[optind+i]);
368             if (ioctl(s[i], SIOCGIFINDEX, &ifr) < 0) {
369                 perror("SIOCGIFINDEX");
370                 exit(1);
371             }
372             addr.can_ifindex = ifr.ifr_ifindex;
373         }
374         else
375             addr.can_ifindex = 0; /* any can interface */
376
377         if (bind(s[i], (struct sockaddr *)&addr, sizeof(addr)) < 0) {
378             perror("bind");
379             return 1;
380         }
381     }
382
383     if (log) {
384         time_t currtime;
385         struct tm now;
386         char fname[sizeof("candump-2006-11-20_202026.log")+1];
387
388         if (time(&currtime) == (time_t)-1) {
389             perror("time");
390             return 1;
391         }
392
393         localtime_r(&currtime, &now);
394
395         sprintf(fname, "candump-%04d-%02d-%02d_%02d%02d%02d.log",
396                now.tm_year + 1900,
397                now.tm_mon + 1,
398                now.tm_mday,
399                now.tm_hour,
400                now.tm_min,
401                now.tm_sec);
402
403         printf("\nEnabling Logfile '%s'\n\n", fname);
404
405         logfile = fopen(fname, "w");
406         if (!logfile) {
407             perror("logfile");
408             return 1;
409         }
410     }
411
412     while (running) {
413
414         FD_ZERO(&rdfs);
415         for (i=0; i<currmax; i++)
416             FD_SET(s[i], &rdfs);
417
418         if ((ret = select(s[currmax-1]+1, &rdfs, NULL, NULL, NULL)) < 0) {
419             //perror("select");
420             running = 0;
421             continue;
422         }
423
424         for (i=0; i<currmax; i++) {  /* check all CAN RAW sockets */
425
426             if (FD_ISSET(s[i], &rdfs)) {
427
428                 socklen_t len = sizeof(addr);
429                 int idx;
430
431                 if ((nbytes = recvfrom(s[i], &frame,
432                                        sizeof(struct can_frame), 0,
433                                        (struct sockaddr*)&addr, &len)) < 0) {
434                     perror("read");
435                     return 1;
436                 }
437
438                 if (nbytes < sizeof(struct can_frame)) {
439                     fprintf(stderr, "read: incomplete CAN frame\n");
440                     return 1;
441                 }
442
443                 if (bridge) {
444                     if ((nbytes = write(bridge, &frame,
445                                         sizeof(struct can_frame))) < 0) {
446                         perror("bridge write");
447                         return 1;
448                     } else if (nbytes < sizeof(struct can_frame)) {
449                         fprintf(stderr,"bridge write: incomplete CAN frame\n");
450                         return 1;
451                     }
452                 }
453                     
454                 if (timestamp || log || logfrmt)
455                     if (ioctl(s[i], SIOCGSTAMP, &tv) < 0)
456                         perror("SIOCGSTAMP");
457
458
459                 idx = idx2dindex(addr.can_ifindex, s[i]);
460
461                 if (log) {
462                     /* log CAN frame with absolute timestamp & device */
463                     fprintf(logfile, "(%ld.%06ld) ", tv.tv_sec, tv.tv_usec);
464                     fprintf(logfile, "%*s ", max_devname_len, devname[idx]);
465                     /* without seperator as logfile use-case is parsing */
466                     fprint_canframe(logfile, &frame, "\n", 0);
467                 }
468
469                 if (logfrmt) {
470                     /* print CAN frame in log file style to stdout */
471                     printf("(%ld.%06ld) ", tv.tv_sec, tv.tv_usec);
472                     printf("%*s ", max_devname_len, devname[idx]);
473                     fprint_canframe(stdout, &frame, "\n", 0);
474                     goto out_fflush; /* no other output to stdout */
475                 }
476
477                 if (silent){
478                     if (silent == 1) {
479                         printf("%c\b", anichar[silentani%=MAXANI]);
480                         silentani++;
481                     }
482                     goto out_fflush; /* no other output to stdout */
483                 }
484                       
485                 printf(" %s", (color>2)?col_on[idx]:"");
486
487                 switch (timestamp) {
488
489                 case 'a': /* absolute with timestamp */
490                     printf("(%ld.%06ld) ", tv.tv_sec, tv.tv_usec);
491                     break;
492
493                 case 'A': /* absolute with date */
494                     {
495                         struct tm tm;
496                         char timestring[25];
497
498                         tm = *localtime(&tv.tv_sec);
499                         strftime(timestring, 24, "%Y-%m-%d %H:%M:%S", &tm);
500                         printf("(%s.%06ld) ", timestring, tv.tv_usec);
501                     }
502                     break;
503
504                 case 'd': /* delta */
505                 case 'z': /* starting with zero */
506                     {
507                         struct timeval diff;
508
509                         if (last_tv.tv_sec == 0)   /* first init */
510                             last_tv = tv;
511                         diff.tv_sec  = tv.tv_sec  - last_tv.tv_sec;
512                         diff.tv_usec = tv.tv_usec - last_tv.tv_usec;
513                         if (diff.tv_usec < 0)
514                             diff.tv_sec--, diff.tv_usec += 1000000;
515                         if (diff.tv_sec < 0)
516                             diff.tv_sec = diff.tv_usec = 0;
517                         printf("(%ld.%06ld) ", diff.tv_sec, diff.tv_usec);
518                                 
519                         if (timestamp == 'd')
520                             last_tv = tv; /* update for delta calculation */
521                     }
522                     break;
523
524                 default: /* no timestamp output */
525                     break;
526                 }
527
528                 printf(" %s", (color && (color<3))?col_on[idx]:"");
529                 printf("%*s", max_devname_len, devname[idx]);
530                 printf("%s  ", (color==1)?col_off:"");
531
532                 fprint_long_canframe(stdout, &frame, NULL, ascii);
533
534                 printf("%s", (color>1)?col_off:"");
535                 printf("\n");
536             }
537
538 out_fflush:
539             fflush(stdout);
540         }
541     }
542
543     for (i=0; i<currmax; i++)
544         close(s[i]);
545
546     if (bridge)
547       close(bridge);
548
549     if (log)
550         fclose(logfile);
551
552     return 0;
553 }