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