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