]> rtime.felk.cvut.cz Git - can-utils.git/blob - candump.c
Start candump in silent mode, when logging into a file.
[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 MAXSOCK 16    /* max. number of CAN interfaces given on the cmdline */
71 #define MAXFILTER 30  /* max. number of possible filters for each socket */
72 #define MAXIFNAMES 30 /* size of receive name index to omit ioctls */
73 #define MAXCOL 6      /* number of different colors for colorized output */
74 #define ANYDEV "any"  /* name of interface to receive from any CAN interface */
75 #define ANL "\r\n"    /* newline in ASC mode */
76
77 #define SILENT_INI 42 /* detect user setting on commandline */
78 #define SILENT_OFF 0  /* no silent mode */
79 #define SILENT_ANI 1  /* silent mode with animation */
80 #define SILENT_ON  2  /* silent mode (completely silent) */
81
82 #define BOLD    ATTBOLD
83 #define RED     ATTBOLD FGRED
84 #define GREEN   ATTBOLD FGGREEN
85 #define YELLOW  ATTBOLD FGYELLOW
86 #define BLUE    ATTBOLD FGBLUE
87 #define MAGENTA ATTBOLD FGMAGENTA
88 #define CYAN    ATTBOLD FGCYAN
89
90 const char col_on [MAXCOL][19] = {BLUE, RED, GREEN, BOLD, MAGENTA, CYAN};
91 const char col_off [] = ATTRESET;
92
93 static char devname[MAXIFNAMES][IFNAMSIZ+1];
94 static int  dindex[MAXIFNAMES];
95 static int  max_devname_len; /* to prevent frazzled device name output */ 
96
97 #define MAXANI 4
98 const char anichar[MAXANI] = {'|', '/', '-', '\\'};
99
100 extern int optind, opterr, optopt;
101
102 static volatile int running = 1;
103
104 void print_usage(char *prg)
105 {
106         fprintf(stderr, "\nUsage: %s [options] <CAN interface>+\n", prg);
107         fprintf(stderr, "  (use CTRL-C to terminate %s)\n\n", prg);
108         fprintf(stderr, "Options: -t <type>   (timestamp: (a)bsolute/(d)elta/(z)ero/(A)bsolute w date)\n");
109         fprintf(stderr, "         -c          (increment color mode level)\n");
110         fprintf(stderr, "         -i          (binary output - may exceed 80 chars/line)\n");
111         fprintf(stderr, "         -a          (enable additional ASCII output)\n");
112         fprintf(stderr, "         -s <level>  (silent mode - %d: off (default) %d: animation %d: silent)\n", SILENT_OFF, SILENT_ANI, SILENT_ON);
113         fprintf(stderr, "         -b <can>    (bridge mode - send received frames to <can>)\n");
114         fprintf(stderr, "         -B <can>    (bridge mode - like '-b' with disabled loopback)\n");
115         fprintf(stderr, "         -l          (log CAN-frames into file. Sets '-s %d' by default)\n", SILENT_ON);
116         fprintf(stderr, "         -L          (use log file format on stdout)\n");
117         fprintf(stderr, "\n");
118         fprintf(stderr, "Up to %d CAN interfaces with optional filter sets can be specified\n", MAXSOCK);
119         fprintf(stderr, "on the commandline in the form: <ifname>[,filter]*\n");
120         fprintf(stderr, "\nUp to %d comma separated filters can be specified for each given CAN interface:\n", MAXFILTER);
121         fprintf(stderr, " <can_id>:<can_mask> (matches when <received_can_id> & mask == can_id & mask)\n");
122         fprintf(stderr, " <can_id>~<can_mask> (matches when <received_can_id> & mask != can_id & mask)\n");
123         fprintf(stderr, " #<error_mask>       (set error frame filter, see include/linux/can/error.h)\n");
124         fprintf(stderr, "\nCAN IDs, masks and data content are given and expected in hexadecimal values.\n");
125         fprintf(stderr, "When can_id and can_mask are both 8 digits, they are assumed to be 29 bit EFF.\n");
126         fprintf(stderr, "Without any given filter all data frames are received ('0:0' default filter).\n");
127         fprintf(stderr, "\nUse interface name '%s' to receive from all CAN interfaces.\n", ANYDEV);
128         fprintf(stderr, "\nExamples:\n");
129         fprintf(stderr, "%s -c -c -ta can0,123:7FF,400:700,#000000FF can2,400~7F0 can3 can8\n", prg);
130         fprintf(stderr, "%s -l any,0~0,#FFFFFFFF    (log only error frames but no(!) data frames)\n", prg);
131         fprintf(stderr, "%s -l any,0:0,#FFFFFFFF    (log error frames and also all data frames)\n", prg);
132         fprintf(stderr, "%s vcan2,92345678:9FFFFFFF (match only for extended CAN ID 12345678)\n", prg);
133         fprintf(stderr, "%s vcan2,12345678:1FFFFFFF (analog to above due to 8 digit value length)\n", prg);
134         fprintf(stderr, "\n");
135 }
136
137 void sigterm(int signo)
138 {
139         running = 0;
140 }
141
142 int idx2dindex(int ifidx, int socket) {
143
144         int i;
145         struct ifreq ifr;
146
147         for (i=0; i < MAXIFNAMES; i++) {
148                 if (dindex[i] == ifidx)
149                         return i;
150         }
151
152         /* create new interface index cache entry */
153
154         /* remove index cache zombies first */
155         for (i=0; i < MAXIFNAMES; i++) {
156                 if (dindex[i]) {
157                         ifr.ifr_ifindex = dindex[i];
158                         if (ioctl(socket, SIOCGIFNAME, &ifr) < 0)
159                                 dindex[i] = 0;
160                 }
161         }
162
163         for (i=0; i < MAXIFNAMES; i++)
164                 if (!dindex[i]) /* free entry */
165                         break;
166
167         if (i == MAXIFNAMES) {
168                 printf("Interface index cache only supports %d interfaces.\n",
169                        MAXIFNAMES);
170                 exit(1);
171         }
172
173         dindex[i] = ifidx;
174
175         ifr.ifr_ifindex = ifidx;
176         if (ioctl(socket, SIOCGIFNAME, &ifr) < 0)
177                 perror("SIOCGIFNAME");
178
179         if (max_devname_len < strlen(ifr.ifr_name))
180                 max_devname_len = strlen(ifr.ifr_name);
181
182         strcpy(devname[i], ifr.ifr_name);
183
184 #ifdef DEBUG
185         printf("new index %d (%s)\n", i, devname[i]);
186 #endif
187
188         return i;
189 }
190
191 canid_t checkeff(char *ptr, char *nptr)
192 {
193         int len;
194
195         if (nptr)
196                 len = nptr - ptr;
197         else
198                 len = strlen(ptr);
199
200         if (len == 17 && (ptr[8] == ':' || ptr[8] == '~'))
201                 return CAN_EFF_FLAG;
202         else
203                 return 0;
204 }
205
206 int main(int argc, char **argv)
207 {
208         fd_set rdfs;
209         int s[MAXSOCK];
210         int bridge = 0;
211         unsigned char timestamp = 0;
212         unsigned char silent = SILENT_INI;
213         unsigned char silentani = 0;
214         unsigned char color = 0;
215         unsigned char view = 0;
216         unsigned char log = 0;
217         unsigned char logfrmt = 0;
218         int opt, ret;
219         int currmax, numfilter;
220         char *ptr, *nptr;
221         canid_t eff;
222         struct sockaddr_can addr;
223         struct can_filter rfilter[MAXFILTER];
224         can_err_mask_t err_mask;
225         struct can_frame frame;
226         int nbytes, i;
227         struct ifreq ifr;
228         struct timeval tv, last_tv;
229         FILE *logfile = NULL;
230
231         signal(SIGTERM, sigterm);
232         signal(SIGHUP, sigterm);
233         signal(SIGINT, sigterm);
234
235         last_tv.tv_sec  = 0;
236         last_tv.tv_usec = 0;
237
238         while ((opt = getopt(argc, argv, "t:cias:b:B:lLh?")) != -1) {
239                 switch (opt) {
240                 case 't':
241                         timestamp = optarg[0];
242                         if ((timestamp != 'a') && (timestamp != 'A') &&
243                             (timestamp != 'd') && (timestamp != 'z')) {
244                                 printf("%s: unknown timestamp mode '%c' - ignored\n",
245                                        basename(argv[0]), optarg[0]);
246                                 timestamp = 0;
247                         }
248                         break;
249
250                 case 'c':
251                         color++;
252                         break;
253
254                 case 'i':
255                         view |= CANLIB_VIEW_BINARY;
256                         break;
257
258                 case 'a':
259                         view |= CANLIB_VIEW_ASCII;
260                         break;
261
262                 case 's':
263                         silent = atoi(optarg);
264                         if (silent > SILENT_ON) {
265                                 print_usage(basename(argv[0]));
266                                 exit(1);
267                         }
268                         break;
269
270                 case 'b':
271                 case 'B':
272                         if (strlen(optarg) >= IFNAMSIZ) {
273                                 printf("Name of CAN device '%s' is too long!\n\n", optarg);
274                                 return 1;
275                         } else {
276                                 bridge = socket(PF_CAN, SOCK_RAW, CAN_RAW);
277                                 if (bridge < 0) {
278                                         perror("bridge socket");
279                                         return 1;
280                                 }
281                                 addr.can_family = AF_CAN;
282                                 strcpy(ifr.ifr_name, optarg);
283                                 if (ioctl(bridge, SIOCGIFINDEX, &ifr) < 0)
284                                         perror("SIOCGIFINDEX");
285                                 addr.can_ifindex = ifr.ifr_ifindex;
286                 
287                                 if (!addr.can_ifindex) {
288                                         perror("invalid bridge interface");
289                                         return 1;
290                                 }
291
292                                 if (opt == 'B') {
293                                         int loopback = 0;
294
295                                         setsockopt(bridge, SOL_CAN_RAW, CAN_RAW_LOOPBACK,
296                                                    &loopback, sizeof(loopback));
297                                 }
298
299                                 if (bind(bridge, (struct sockaddr *)&addr, sizeof(addr)) < 0) {
300                                         perror("bridge bind");
301                                         return 1;
302                                 }
303                         }
304                         break;
305             
306                 case 'l':
307                         log = 1;
308                         break;
309
310                 case 'L':
311                         logfrmt = 1;
312                         break;
313
314                 default:
315                         print_usage(basename(argv[0]));
316                         exit(1);
317                         break;
318                 }
319         }
320
321         if (optind == argc) {
322                 print_usage(basename(argv[0]));
323                 exit(0);
324         }
325         
326         if (silent == SILENT_INI) {
327                 if (log) {
328                         printf("\nDisabled standard output while logging.");
329                         silent = SILENT_ON; /* disable output on stdout */
330                 } else
331                         silent = SILENT_OFF; /* default output */
332         }
333
334         currmax = argc - optind; /* find real number of CAN devices */
335
336         if (currmax > MAXSOCK) {
337                 printf("More than %d CAN devices given on commandline!\n", MAXSOCK);
338                 return 1;
339         }
340
341         for (i=0; i < currmax; i++) {
342
343                 ptr = argv[optind+i];
344                 nptr = strchr(ptr, ',');
345
346 #ifdef DEBUG
347                 printf("open %d '%s'.\n", i, ptr);
348 #endif
349
350                 s[i] = socket(PF_CAN, SOCK_RAW, CAN_RAW);
351                 if (s[i] < 0) {
352                         perror("socket");
353                         return 1;
354                 }
355
356                 if (nptr)
357                         nbytes = nptr - ptr;  /* interface name is up the first ',' */
358                 else
359                         nbytes = strlen(ptr); /* no ',' found => no filter definitions */
360
361                 if (nbytes >= IFNAMSIZ) {
362                         printf("name of CAN device '%s' is too long!\n", ptr);
363                         return 1;
364                 }
365
366                 if (nbytes > max_devname_len)
367                         max_devname_len = nbytes; /* for nice printing */
368
369                 addr.can_family = AF_CAN;
370
371                 memset(&ifr.ifr_name, 0, sizeof(ifr.ifr_name));
372                 strncpy(ifr.ifr_name, ptr, nbytes);
373
374 #ifdef DEBUG
375                 printf("using interface name '%s'.\n", ifr.ifr_name);
376 #endif
377
378                 if (strcmp(ANYDEV, ifr.ifr_name)) {
379                         if (ioctl(s[i], SIOCGIFINDEX, &ifr) < 0) {
380                                 perror("SIOCGIFINDEX");
381                                 exit(1);
382                         }
383                         addr.can_ifindex = ifr.ifr_ifindex;
384                 } else
385                         addr.can_ifindex = 0; /* any can interface */
386
387                 if (nptr) {
388
389                         /* found a ',' after the interface name => check for filters */
390
391                         numfilter = 0;
392                         err_mask = 0;
393
394                         while (nptr) {
395
396                                 ptr = nptr+1; /* hop behind the ',' */
397                                 nptr = strchr(ptr, ','); /* update exit condition */
398
399                                 if (sscanf(ptr, "%lx:%lx",
400                                            (long unsigned int *)
401                                            &rfilter[numfilter].can_id, 
402                                            (long unsigned int *)
403                                            &rfilter[numfilter].can_mask) == 2) {
404                                         eff = checkeff(ptr, nptr);
405                                         rfilter[numfilter].can_id |= eff;
406                                         rfilter[numfilter].can_mask |= eff;
407                                         rfilter[numfilter].can_mask &= ~CAN_ERR_FLAG;
408                                         numfilter++;
409                                 } else if (sscanf(ptr, "%lx~%lx",
410                                                   (long unsigned int *)
411                                                   &rfilter[numfilter].can_id, 
412                                                   (long unsigned int *)
413                                                   &rfilter[numfilter].can_mask) == 2) {
414                                         rfilter[numfilter].can_id |= CAN_INV_FILTER;
415                                         eff = checkeff(ptr, nptr);
416                                         rfilter[numfilter].can_id |= eff;
417                                         rfilter[numfilter].can_mask |= eff;
418                                         rfilter[numfilter].can_mask &= ~CAN_ERR_FLAG;
419                                         numfilter++;
420                                 } else if (sscanf(ptr, "#%lx",
421                                                   (long unsigned int *)&err_mask) != 1) { 
422                                         printf("Error in filter option parsing: '%s'\n", ptr);
423                                         exit(1);
424                                 }
425
426                                 if (numfilter > MAXFILTER) {
427                                         printf("Too many filters specified for '%s'.\n",
428                                                ifr.ifr_name);
429                                         exit(1);
430                                 }
431                         }
432
433                         if (err_mask)
434                                 setsockopt(s[i], SOL_CAN_RAW, CAN_RAW_ERR_FILTER,
435                                            &err_mask, sizeof(err_mask));
436
437                         if (numfilter)
438                                 setsockopt(s[i], SOL_CAN_RAW, CAN_RAW_FILTER,
439                                            &rfilter, numfilter * sizeof(struct can_filter));
440                 } /* if (nptr) */
441
442                 if (bind(s[i], (struct sockaddr *)&addr, sizeof(addr)) < 0) {
443                         perror("bind");
444                         return 1;
445                 }
446         }
447
448         if (log) {
449                 time_t currtime;
450                 struct tm now;
451                 char fname[sizeof("candump-2006-11-20_202026.log")+1];
452
453                 if (time(&currtime) == (time_t)-1) {
454                         perror("time");
455                         return 1;
456                 }
457
458                 localtime_r(&currtime, &now);
459
460                 sprintf(fname, "candump-%04d-%02d-%02d_%02d%02d%02d.log",
461                         now.tm_year + 1900,
462                         now.tm_mon + 1,
463                         now.tm_mday,
464                         now.tm_hour,
465                         now.tm_min,
466                         now.tm_sec);
467
468                 if (silent != SILENT_ON)
469                         printf("\nWarning: console output active while logging!");
470
471                 printf("\nEnabling Logfile '%s'\n\n", fname);
472
473                 logfile = fopen(fname, "w");
474                 if (!logfile) {
475                         perror("logfile");
476                         return 1;
477                 }
478         }
479
480         while (running) {
481
482                 FD_ZERO(&rdfs);
483                 for (i=0; i<currmax; i++)
484                         FD_SET(s[i], &rdfs);
485
486                 if ((ret = select(s[currmax-1]+1, &rdfs, NULL, NULL, NULL)) < 0) {
487                         //perror("select");
488                         running = 0;
489                         continue;
490                 }
491
492                 for (i=0; i<currmax; i++) {  /* check all CAN RAW sockets */
493
494                         if (FD_ISSET(s[i], &rdfs)) {
495
496                                 socklen_t len = sizeof(addr);
497                                 int idx;
498
499                                 nbytes = recvfrom(s[i], &frame, sizeof(struct can_frame), 0,
500                                                   (struct sockaddr*)&addr, &len);
501                                 if (nbytes < 0) {
502                                         perror("read");
503                                         return 1;
504                                 }
505
506                                 if (nbytes < sizeof(struct can_frame)) {
507                                         fprintf(stderr, "read: incomplete CAN frame\n");
508                                         return 1;
509                                 }
510
511                                 if (bridge) {
512                                         nbytes = write(bridge, &frame, sizeof(struct can_frame));
513                                         if (nbytes < 0) {
514                                                 perror("bridge write");
515                                                 return 1;
516                                         } else if (nbytes < sizeof(struct can_frame)) {
517                                                 fprintf(stderr,"bridge write: incomplete CAN frame\n");
518                                                 return 1;
519                                         }
520                                 }
521                     
522                                 if (timestamp || log || logfrmt)
523                                         if (ioctl(s[i], SIOCGSTAMP, &tv) < 0)
524                                                 perror("SIOCGSTAMP");
525
526
527                                 idx = idx2dindex(addr.can_ifindex, s[i]);
528
529                                 if (log) {
530                                         /* log CAN frame with absolute timestamp & device */
531                                         fprintf(logfile, "(%ld.%06ld) ", tv.tv_sec, tv.tv_usec);
532                                         fprintf(logfile, "%*s ", max_devname_len, devname[idx]);
533                                         /* without seperator as logfile use-case is parsing */
534                                         fprint_canframe(logfile, &frame, "\n", 0);
535                                 }
536
537                                 if (logfrmt) {
538                                         /* print CAN frame in log file style to stdout */
539                                         printf("(%ld.%06ld) ", tv.tv_sec, tv.tv_usec);
540                                         printf("%*s ", max_devname_len, devname[idx]);
541                                         fprint_canframe(stdout, &frame, "\n", 0);
542                                         goto out_fflush; /* no other output to stdout */
543                                 }
544
545                                 if (silent != SILENT_OFF){
546                                         if (silent == SILENT_ANI) {
547                                                 printf("%c\b", anichar[silentani%=MAXANI]);
548                                                 silentani++;
549                                         }
550                                         goto out_fflush; /* no other output to stdout */
551                                 }
552                       
553                                 printf(" %s", (color>2)?col_on[idx%MAXCOL]:"");
554
555                                 switch (timestamp) {
556
557                                 case 'a': /* absolute with timestamp */
558                                         printf("(%ld.%06ld) ", tv.tv_sec, tv.tv_usec);
559                                         break;
560
561                                 case 'A': /* absolute with date */
562                                 {
563                                         struct tm tm;
564                                         char timestring[25];
565
566                                         tm = *localtime(&tv.tv_sec);
567                                         strftime(timestring, 24, "%Y-%m-%d %H:%M:%S", &tm);
568                                         printf("(%s.%06ld) ", timestring, tv.tv_usec);
569                                 }
570                                 break;
571
572                                 case 'd': /* delta */
573                                 case 'z': /* starting with zero */
574                                 {
575                                         struct timeval diff;
576
577                                         if (last_tv.tv_sec == 0)   /* first init */
578                                                 last_tv = tv;
579                                         diff.tv_sec  = tv.tv_sec  - last_tv.tv_sec;
580                                         diff.tv_usec = tv.tv_usec - last_tv.tv_usec;
581                                         if (diff.tv_usec < 0)
582                                                 diff.tv_sec--, diff.tv_usec += 1000000;
583                                         if (diff.tv_sec < 0)
584                                                 diff.tv_sec = diff.tv_usec = 0;
585                                         printf("(%ld.%06ld) ", diff.tv_sec, diff.tv_usec);
586                                 
587                                         if (timestamp == 'd')
588                                                 last_tv = tv; /* update for delta calculation */
589                                 }
590                                 break;
591
592                                 default: /* no timestamp output */
593                                         break;
594                                 }
595
596                                 printf(" %s", (color && (color<3))?col_on[idx%MAXCOL]:"");
597                                 printf("%*s", max_devname_len, devname[idx]);
598                                 printf("%s  ", (color==1)?col_off:"");
599
600                                 fprint_long_canframe(stdout, &frame, NULL, view);
601
602                                 printf("%s", (color>1)?col_off:"");
603                                 printf("\n");
604                         }
605
606                 out_fflush:
607                         fflush(stdout);
608                 }
609         }
610
611         for (i=0; i<currmax; i++)
612                 close(s[i]);
613
614         if (bridge)
615                 close(bridge);
616
617         if (log)
618                 fclose(logfile);
619
620         return 0;
621 }