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