]> rtime.felk.cvut.cz Git - can-utils.git/blob - candump.c
Fixed contradiction in Sourcecode discalimer.
[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 MAXDEV 6 /* change sscanf()'s manually if changed here */
71 #define ANYDEV "any"
72 #define ANL "\r\n" /* newline in ASC mode */
73
74 #define BOLD    ATTBOLD
75 #define RED     ATTBOLD FGRED
76 #define GREEN   ATTBOLD FGGREEN
77 #define YELLOW  ATTBOLD FGYELLOW
78 #define BLUE    ATTBOLD FGBLUE
79 #define MAGENTA ATTBOLD FGMAGENTA
80 #define CYAN    ATTBOLD FGCYAN
81
82 const char col_on [MAXDEV][19] = {BOLD, MAGENTA, GREEN, BLUE, CYAN, RED};
83 const char col_off [] = ATTRESET;
84
85 static char devname[MAXDEV][IFNAMSIZ+1];
86 static int  dindex[MAXDEV];
87 static int  max_devname_len;
88
89 #define MAXANI 8
90 const char anichar[MAXANI] = {'|', '/', '-', '\\', '|', '/', '-', '\\'};
91
92 extern int optind, opterr, optopt;
93
94 static volatile int running = 1;
95
96 void print_usage(char *prg)
97 {
98     fprintf(stderr, "Usage: %s [can-interfaces]\n", prg);
99     fprintf(stderr, "  (use CTRL-C to terminate %s)\n", prg);
100     fprintf(stderr, "Options: -m <mask>   (default 0x00000000)\n");
101     fprintf(stderr, "         -v <value>  (default 0x00000000)\n");
102     fprintf(stderr, "         -i <0|1>    (inv_filter)\n");
103     fprintf(stderr, "         -e <emask>  (mask for error frames)\n");
104     fprintf(stderr, "         -t <type>   (timestamp: Absolute/Delta/Zero)\n");
105     fprintf(stderr, "         -c          (color mode)\n");
106     fprintf(stderr, "         -a          (enable additional ASCII output)\n");
107     fprintf(stderr, "         -s <level>  (silent mode - 1: animation 2: nothing)\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, "When using more than one CAN interface the options\n");
114     fprintf(stderr, "m/v/i/e have comma seperated values e.g. '-m 0,7FF,0'\n");
115     fprintf(stderr, "Use interface name '%s' to receive from all can-interfaces\n", ANYDEV);
116 }
117
118 void sigterm(int signo)
119 {
120     running = 0;
121 }
122
123 int idx2dindex(int ifidx, int socket) {
124
125     int i;
126     struct ifreq ifr;
127
128     for (i=0; i<MAXDEV; i++) {
129         if (dindex[i] == ifidx)
130             return i;
131     }
132
133     /* create new interface index cache entry */
134
135     for (i=0; i < MAXDEV; i++)
136         if (!dindex[i]) /* free entry */
137             break;
138
139     if (i == MAXDEV) {
140         printf("BUG in interface index cache! MAXDEV?\n");
141         exit(1);
142     }
143
144     dindex[i] = ifidx;
145
146     ifr.ifr_ifindex = ifidx;
147     if (ioctl(socket, SIOCGIFNAME, &ifr) < 0)
148         perror("SIOCGIFNAME");
149
150     if (max_devname_len < strlen(ifr.ifr_name))
151         max_devname_len = strlen(ifr.ifr_name);
152
153     strcpy(devname[i], ifr.ifr_name);
154
155 #ifdef DEBUG
156     printf("new index %d (%s)\n", i, devname[i]);
157 #endif
158
159     return i;
160 }
161
162 int main(int argc, char **argv)
163 {
164     fd_set rdfs;
165     int s[MAXDEV];
166     int bridge = 0;
167     canid_t mask[MAXDEV] = {0};
168     canid_t value[MAXDEV] = {0};
169     int inv_filter[MAXDEV] = {0};
170     can_err_mask_t err_mask[MAXDEV] = {0};
171     unsigned char timestamp = 0;
172     unsigned char silent = 0;
173     unsigned char silentani = 0;
174     unsigned char color = 0;
175     unsigned char ascii = 0;
176     unsigned char log = 0;
177     unsigned char logfrmt = 0;
178     int opt, ret;
179     int currmax = 1; /* we assume at least one can bus ;-) */
180     struct sockaddr_can addr;
181     struct can_filter rfilter;
182     struct can_frame frame;
183     int nbytes, i, j;
184     struct ifreq ifr;
185     struct timeval tv, last_tv;
186     FILE *logfile = NULL;
187
188     signal(SIGTERM, sigterm);
189     signal(SIGHUP, sigterm);
190     signal(SIGINT, sigterm);
191
192     last_tv.tv_sec  = 0;
193     last_tv.tv_usec = 0;
194
195     while ((opt = getopt(argc, argv, "m:v:i:e:t:cas:b:B:lL")) != -1) {
196         switch (opt) {
197         case 'm':
198             i = sscanf(optarg, "%x,%x,%x,%x,%x,%x",
199                        &mask[0], &mask[1], &mask[2],
200                        &mask[3], &mask[4], &mask[5]);
201             if (i > currmax)
202                 currmax = i;
203             break;
204
205         case 'v':
206             i = sscanf(optarg, "%x,%x,%x,%x,%x,%x",
207                        &value[0], &value[1], &value[2],
208                        &value[3], &value[4], &value[5]);
209             if (i > currmax)
210                 currmax = i;
211             break;
212
213         case 'i':
214             i = sscanf(optarg, "%d,%d,%d,%d,%d,%d",
215                        &inv_filter[0], &inv_filter[1], &inv_filter[2],
216                        &inv_filter[3], &inv_filter[4], &inv_filter[5]);
217             if (i > currmax)
218                 currmax = i;
219             break;
220
221         case 'e':
222             i = sscanf(optarg, "%x,%x,%x,%x,%x,%x",
223                        &err_mask[0], &err_mask[1], &err_mask[2],
224                        &err_mask[3], &err_mask[4], &err_mask[5]);
225             if (i > currmax)
226                 currmax = i;
227             break;
228
229         case 't':
230             timestamp = optarg[0];
231             if ((timestamp != 'a') && (timestamp != 'A') &&
232                 (timestamp != 'd') && (timestamp != 'z')) {
233                 printf("%s: unknown timestamp mode '%c' - ignored\n",
234                        basename(argv[0]), optarg[0]);
235                 timestamp = 0;
236             }
237             break;
238
239         case 'c':
240             color++;
241             break;
242
243         case 'a':
244             ascii = 1;
245             break;
246
247         case 's':
248             silent = atoi(optarg);
249             break;
250
251         case 'b':
252         case 'B':
253             if (strlen(optarg) >= IFNAMSIZ) {
254                 printf("Name of CAN device '%s' is too long!\n\n", optarg);
255                 return 1;
256             }
257             else {
258                 if ((bridge = socket(PF_CAN, SOCK_RAW, CAN_RAW)) < 0) {
259                     perror("bridge socket");
260                     return 1;
261                 }
262                 addr.can_family = AF_CAN;
263                 strcpy(ifr.ifr_name, optarg);
264                 if (ioctl(bridge, SIOCGIFINDEX, &ifr) < 0)
265                     perror("SIOCGIFINDEX");
266                 addr.can_ifindex = ifr.ifr_ifindex;
267                 
268                 if (!addr.can_ifindex) {
269                     perror("invalid bridge interface");
270                     return 1;
271                 }
272
273                 if (opt == 'B') {
274                     int loopback = 0;
275
276                     setsockopt(bridge, SOL_CAN_RAW, CAN_RAW_LOOPBACK, &loopback, sizeof(loopback));
277                 }
278
279                 if (bind(bridge, (struct sockaddr *)&addr, sizeof(addr)) < 0) {
280                     perror("bridge bind");
281                     return 1;
282                 }
283             }
284             break;
285             
286         case 'l':
287             log = 1;
288             break;
289
290         case 'L':
291             logfrmt = 1;
292             break;
293
294         default:
295             fprintf(stderr, "Unknown option %c\n", opt);
296             print_usage(basename(argv[0]));
297             exit(1);
298             break;
299         }
300     }
301
302     if (optind == argc) {
303         print_usage(basename(argv[0]));
304         exit(0);
305     }
306         
307     /* count in options higher than device count ? */
308     if (optind + currmax > argc) {
309         printf("low count of CAN devices!\n");
310         return 1;
311     }
312
313     currmax = argc - optind; /* find real number of CAN devices */
314
315     if (currmax > MAXDEV) {
316         printf("More than %d CAN devices!\n", MAXDEV);
317         return 1;
318     }
319
320     for (i=0; i<currmax; i++) {
321
322 #ifdef DEBUG
323         printf("open %d '%s' m%08X v%08X i%d e%d.\n",
324                i, argv[optind+i], mask[i], value[i],
325                inv_filter[i], err_mask[i]);
326 #endif
327
328         if ((s[i] = socket(PF_CAN, SOCK_RAW, CAN_RAW)) < 0) {
329             perror("socket");
330             return 1;
331         }
332
333         if (mask[i] || value[i]) {
334
335             printf("CAN ID filter[%d] for %s set to "
336                    "mask = %08X, value = %08X %s\n",
337                    i, argv[optind+i], mask[i], value[i],
338                    (inv_filter[i]) ? "(inv_filter)" : "");
339
340             rfilter.can_id   = value[i];
341             rfilter.can_mask = mask[i];
342             if (inv_filter[i])
343                 rfilter.can_id |= CAN_INV_FILTER;
344
345             setsockopt(s[i], SOL_CAN_RAW, CAN_RAW_FILTER,
346                        &rfilter, sizeof(rfilter));
347         }
348
349         if (err_mask[i])
350             setsockopt(s[i], SOL_CAN_RAW, CAN_RAW_ERR_FILTER,
351                        &err_mask[i], sizeof(err_mask[i]));
352
353         j = strlen(argv[optind+i]);
354
355         if (!(j < IFNAMSIZ)) {
356             printf("name of CAN device '%s' is too long!\n", argv[optind+i]);
357             return 1;
358         }
359
360         if (j > max_devname_len)
361             max_devname_len = j; /* for nice printing */
362
363         addr.can_family = AF_CAN;
364
365         if (strcmp(ANYDEV, argv[optind+i])) {
366             strcpy(ifr.ifr_name, argv[optind+i]);
367             if (ioctl(s[i], SIOCGIFINDEX, &ifr) < 0) {
368                 perror("SIOCGIFINDEX");
369                 exit(1);
370             }
371             addr.can_ifindex = ifr.ifr_ifindex;
372         }
373         else
374             addr.can_ifindex = 0; /* any can interface */
375
376         if (bind(s[i], (struct sockaddr *)&addr, sizeof(addr)) < 0) {
377             perror("bind");
378             return 1;
379         }
380     }
381
382     if (log) {
383         time_t currtime;
384         struct tm now;
385         char fname[sizeof("candump-2006-11-20_202026.log")+1];
386
387         if (time(&currtime) == (time_t)-1) {
388             perror("time");
389             return 1;
390         }
391
392         localtime_r(&currtime, &now);
393
394         sprintf(fname, "candump-%04d-%02d-%02d_%02d%02d%02d.log",
395                now.tm_year + 1900,
396                now.tm_mon + 1,
397                now.tm_mday,
398                now.tm_hour,
399                now.tm_min,
400                now.tm_sec);
401
402         printf("\nEnabling Logfile '%s'\n\n", fname);
403
404         logfile = fopen(fname, "w");
405         if (!logfile) {
406             perror("logfile");
407             return 1;
408         }
409     }
410
411     while (running) {
412
413         FD_ZERO(&rdfs);
414         for (i=0; i<currmax; i++)
415             FD_SET(s[i], &rdfs);
416
417         if ((ret = select(s[currmax-1]+1, &rdfs, NULL, NULL, NULL)) < 0) {
418             //perror("select");
419             running = 0;
420             continue;
421         }
422
423         for (i=0; i<currmax; i++) {  /* check all CAN RAW sockets */
424
425             if (FD_ISSET(s[i], &rdfs)) {
426
427                 socklen_t len = sizeof(addr);
428                 int idx;
429
430                 if ((nbytes = recvfrom(s[i], &frame,
431                                        sizeof(struct can_frame), 0,
432                                        (struct sockaddr*)&addr, &len)) < 0) {
433                     perror("read");
434                     return 1;
435                 }
436
437                 if (nbytes < sizeof(struct can_frame)) {
438                     fprintf(stderr, "read: incomplete CAN frame\n");
439                     return 1;
440                 }
441
442                 if (bridge) {
443                     if ((nbytes = write(bridge, &frame,
444                                         sizeof(struct can_frame))) < 0) {
445                         perror("bridge write");
446                         return 1;
447                     } else if (nbytes < sizeof(struct can_frame)) {
448                         fprintf(stderr,"bridge write: incomplete CAN frame\n");
449                         return 1;
450                     }
451                 }
452                     
453                 if (timestamp || log || logfrmt)
454                     if (ioctl(s[i], SIOCGSTAMP, &tv) < 0)
455                         perror("SIOCGSTAMP");
456
457
458                 idx = idx2dindex(addr.can_ifindex, s[i]);
459
460                 if (log) {
461                     /* log CAN frame with absolute timestamp & device */
462                     fprintf(logfile, "(%ld.%06ld) ", tv.tv_sec, tv.tv_usec);
463                     fprintf(logfile, "%*s ", max_devname_len, devname[idx]);
464                     /* without seperator as logfile use-case is parsing */
465                     fprint_canframe(logfile, &frame, "\n", 0);
466                 }
467
468                 if (logfrmt) {
469                     /* print CAN frame in log file style to stdout */
470                     printf("(%ld.%06ld) ", tv.tv_sec, tv.tv_usec);
471                     printf("%*s ", max_devname_len, devname[idx]);
472                     fprint_canframe(stdout, &frame, "\n", 0);
473                     goto out_fflush; /* no other output to stdout */
474                 }
475
476                 if (silent){
477                     if (silent == 1) {
478                         printf("%c\b", anichar[silentani%=MAXANI]);
479                         silentani++;
480                     }
481                     goto out_fflush; /* no other output to stdout */
482                 }
483                       
484                 printf(" %s", (color>2)?col_on[idx]:"");
485
486                 switch (timestamp) {
487
488                 case 'a': /* absolute with timestamp */
489                     printf("(%ld.%06ld) ", tv.tv_sec, tv.tv_usec);
490                     break;
491
492                 case 'A': /* absolute with date */
493                     {
494                         struct tm tm;
495                         char timestring[25];
496
497                         tm = *localtime(&tv.tv_sec);
498                         strftime(timestring, 24, "%Y-%m-%d %H:%M:%S", &tm);
499                         printf("(%s.%06ld) ", timestring, tv.tv_usec);
500                     }
501                     break;
502
503                 case 'd': /* delta */
504                 case 'z': /* starting with zero */
505                     {
506                         struct timeval diff;
507
508                         if (last_tv.tv_sec == 0)   /* first init */
509                             last_tv = tv;
510                         diff.tv_sec  = tv.tv_sec  - last_tv.tv_sec;
511                         diff.tv_usec = tv.tv_usec - last_tv.tv_usec;
512                         if (diff.tv_usec < 0)
513                             diff.tv_sec--, diff.tv_usec += 1000000;
514                         if (diff.tv_sec < 0)
515                             diff.tv_sec = diff.tv_usec = 0;
516                         printf("(%ld.%06ld) ", diff.tv_sec, diff.tv_usec);
517                                 
518                         if (timestamp == 'd')
519                             last_tv = tv; /* update for delta calculation */
520                     }
521                     break;
522
523                 default: /* no timestamp output */
524                     break;
525                 }
526
527                 printf(" %s", (color && (color<3))?col_on[idx]:"");
528                 printf("%*s", max_devname_len, devname[idx]);
529                 printf("%s  ", (color==1)?col_off:"");
530
531                 fprint_long_canframe(stdout, &frame, NULL, ascii);
532
533                 printf("%s", (color>1)?col_off:"");
534                 printf("\n");
535             }
536
537 out_fflush:
538             fflush(stdout);
539         }
540     }
541
542     for (i=0; i<currmax; i++)
543         close(s[i]);
544
545     if (bridge)
546       close(bridge);
547
548     if (log)
549         fclose(logfile);
550
551     return 0;
552 }