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