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