]> rtime.felk.cvut.cz Git - can-utils.git/blob - candump.c
candump: Enable HW timestamping before using it
[can-utils.git] / candump.c
1 /*
2  * candump.c
3  *
4  * Copyright (c) 2002-2009 Volkswagen Group Electronic Research
5  * All rights reserved.
6  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions
9  * are met:
10  * 1. Redistributions of source code must retain the above copyright
11  *    notice, this list of conditions and the following disclaimer.
12  * 2. Redistributions in binary form must reproduce the above copyright
13  *    notice, this list of conditions and the following disclaimer in the
14  *    documentation and/or other materials provided with the distribution.
15  * 3. Neither the name of Volkswagen nor the names of its contributors
16  *    may be used to endorse or promote products derived from this software
17  *    without specific prior written permission.
18  *
19  * Alternatively, provided that this notice is retained in full, this
20  * software may be distributed under the terms of the GNU General
21  * Public License ("GPL") version 2, in which case the provisions of the
22  * GPL apply INSTEAD OF those given above.
23  *
24  * The provided data structures and external interfaces from this code
25  * are not restricted to be used by modules with a GPL compatible license.
26  *
27  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
28  * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
29  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
30  * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
31  * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
32  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
33  * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
34  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
35  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
36  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
37  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
38  * DAMAGE.
39  *
40  * Send feedback to <linux-can@vger.kernel.org>
41  *
42  */
43
44 #include <stdio.h>
45 #include <stdlib.h>
46 #include <stdint.h>
47 #include <unistd.h>
48 #include <string.h>
49 #include <signal.h>
50 #include <ctype.h>
51 #include <libgen.h>
52 #include <time.h>
53 #include <errno.h>
54
55 #include <sys/time.h>
56 #include <sys/types.h>
57 #include <sys/socket.h>
58 #include <sys/ioctl.h>
59 #include <sys/uio.h>
60 #include <net/if.h>
61
62 #include <linux/can.h>
63 #include <linux/can/raw.h>
64 #include <linux/net_tstamp.h>
65
66 #include "terminal.h"
67 #include "lib.h"
68
69 #ifndef SIOCSHWTSTAMP
70 # define SIOCSHWTSTAMP 0x89b0
71 #endif
72
73 #define MAXSOCK 16    /* max. number of CAN interfaces given on the cmdline */
74 #define MAXIFNAMES 30 /* size of receive name index to omit ioctls */
75 #define MAXCOL 6      /* number of different colors for colorized output */
76 #define ANYDEV "any"  /* name of interface to receive from any CAN interface */
77 #define ANL "\r\n"    /* newline in ASC mode */
78
79 #define SILENT_INI 42 /* detect user setting on commandline */
80 #define SILENT_OFF 0  /* no silent mode */
81 #define SILENT_ANI 1  /* silent mode with animation */
82 #define SILENT_ON  2  /* silent mode (completely silent) */
83
84 #define BOLD    ATTBOLD
85 #define RED     ATTBOLD FGRED
86 #define GREEN   ATTBOLD FGGREEN
87 #define YELLOW  ATTBOLD FGYELLOW
88 #define BLUE    ATTBOLD FGBLUE
89 #define MAGENTA ATTBOLD FGMAGENTA
90 #define CYAN    ATTBOLD FGCYAN
91
92 const char col_on [MAXCOL][19] = {BLUE, RED, GREEN, BOLD, MAGENTA, CYAN};
93 const char col_off [] = ATTRESET;
94
95 static char *cmdlinename[MAXSOCK];
96 static __u32 dropcnt[MAXSOCK];
97 static __u32 last_dropcnt[MAXSOCK];
98 static char devname[MAXIFNAMES][IFNAMSIZ+1];
99 static int  dindex[MAXIFNAMES];
100 static int  max_devname_len; /* to prevent frazzled device name output */ 
101 const int canfd_on = 1;
102
103 #define MAXANI 4
104 const char anichar[MAXANI] = {'|', '/', '-', '\\'};
105 const char extra_m_info[4][4] = {"- -", "B -", "- E", "B E"};
106
107 extern int optind, opterr, optopt;
108
109 static volatile int running = 1;
110
111 void print_usage(char *prg)
112 {
113         fprintf(stderr, "\nUsage: %s [options] <CAN interface>+\n", prg);
114         fprintf(stderr, "  (use CTRL-C to terminate %s)\n\n", prg);
115         fprintf(stderr, "Options: -t <type>   (timestamp: (a)bsolute/(d)elta/(z)ero/(A)bsolute w date)\n");
116         fprintf(stderr, "         -H          (use hardware timestamping)\n");
117         fprintf(stderr, "         -c          (increment color mode level)\n");
118         fprintf(stderr, "         -i          (binary output - may exceed 80 chars/line)\n");
119         fprintf(stderr, "         -a          (enable additional ASCII output)\n");
120         fprintf(stderr, "         -S          (swap byte order in printed CAN data[] - marked with '%c' )\n", SWAP_DELIMITER);
121         fprintf(stderr, "         -s <level>  (silent mode - %d: off (default) %d: animation %d: silent)\n", SILENT_OFF, SILENT_ANI, SILENT_ON);
122         fprintf(stderr, "         -b <can>    (bridge mode - send received frames to <can>)\n");
123         fprintf(stderr, "         -B <can>    (bridge mode - like '-b' with disabled loopback)\n");
124         fprintf(stderr, "         -u <usecs>  (delay bridge forwarding by <usecs> microseconds)\n");
125         fprintf(stderr, "         -l          (log CAN-frames into file. Sets '-s %d' by default)\n", SILENT_ON);
126         fprintf(stderr, "         -L          (use log file format on stdout)\n");
127         fprintf(stderr, "         -n <count>  (terminate after receiption of <count> CAN frames)\n");
128         fprintf(stderr, "         -r <size>   (set socket receive buffer to <size>)\n");
129         fprintf(stderr, "         -d          (monitor dropped CAN frames)\n");
130         fprintf(stderr, "         -e          (dump CAN error frames in human-readable format)\n");
131         fprintf(stderr, "         -x          (print extra message infos, rx/tx brs esi)\n");
132         fprintf(stderr, "         -T <msecs>  (terminate after <msecs> without any reception)\n");
133         fprintf(stderr, "\n");
134         fprintf(stderr, "Up to %d CAN interfaces with optional filter sets can be specified\n", MAXSOCK);
135         fprintf(stderr, "on the commandline in the form: <ifname>[,filter]*\n");
136         fprintf(stderr, "\nComma separated filters can be specified for each given CAN interface:\n");
137         fprintf(stderr, " <can_id>:<can_mask> (matches when <received_can_id> & mask == can_id & mask)\n");
138         fprintf(stderr, " <can_id>~<can_mask> (matches when <received_can_id> & mask != can_id & mask)\n");
139         fprintf(stderr, " #<error_mask>       (set error frame filter, see include/linux/can/error.h)\n");
140         fprintf(stderr, " [j|J]               (join the given CAN filters - logical AND semantic)\n");
141         fprintf(stderr, "\nCAN IDs, masks and data content are given and expected in hexadecimal values.\n");
142         fprintf(stderr, "When can_id and can_mask are both 8 digits, they are assumed to be 29 bit EFF.\n");
143         fprintf(stderr, "Without any given filter all data frames are received ('0:0' default filter).\n");
144         fprintf(stderr, "\nUse interface name '%s' to receive from all CAN interfaces.\n", ANYDEV);
145         fprintf(stderr, "\nExamples:\n");
146         fprintf(stderr, "%s -c -c -ta can0,123:7FF,400:700,#000000FF can2,400~7F0 can3 can8\n", prg);
147         fprintf(stderr, "%s -l any,0~0,#FFFFFFFF    (log only error frames but no(!) data frames)\n", prg);
148         fprintf(stderr, "%s -l any,0:0,#FFFFFFFF    (log error frames and also all data frames)\n", prg);
149         fprintf(stderr, "%s vcan2,92345678:DFFFFFFF (match only for extended CAN ID 12345678)\n", prg);
150         fprintf(stderr, "%s vcan2,123:7FF (matches CAN ID 123 - including EFF and RTR frames)\n", prg);
151         fprintf(stderr, "%s vcan2,123:C00007FF (matches CAN ID 123 - only SFF and non-RTR frames)\n", prg);
152         fprintf(stderr, "\n");
153 }
154
155 void sigterm(int signo)
156 {
157         running = 0;
158 }
159
160 int idx2dindex(int ifidx, int socket) {
161
162         int i;
163         struct ifreq ifr;
164
165         for (i=0; i < MAXIFNAMES; i++) {
166                 if (dindex[i] == ifidx)
167                         return i;
168         }
169
170         /* create new interface index cache entry */
171
172         /* remove index cache zombies first */
173         for (i=0; i < MAXIFNAMES; i++) {
174                 if (dindex[i]) {
175                         ifr.ifr_ifindex = dindex[i];
176                         if (ioctl(socket, SIOCGIFNAME, &ifr) < 0)
177                                 dindex[i] = 0;
178                 }
179         }
180
181         for (i=0; i < MAXIFNAMES; i++)
182                 if (!dindex[i]) /* free entry */
183                         break;
184
185         if (i == MAXIFNAMES) {
186                 fprintf(stderr, "Interface index cache only supports %d interfaces.\n",
187                        MAXIFNAMES);
188                 exit(1);
189         }
190
191         dindex[i] = ifidx;
192
193         ifr.ifr_ifindex = ifidx;
194         if (ioctl(socket, SIOCGIFNAME, &ifr) < 0)
195                 perror("SIOCGIFNAME");
196
197         if (max_devname_len < strlen(ifr.ifr_name))
198                 max_devname_len = strlen(ifr.ifr_name);
199
200         strcpy(devname[i], ifr.ifr_name);
201
202 #ifdef DEBUG
203         printf("new index %d (%s)\n", i, devname[i]);
204 #endif
205
206         return i;
207 }
208
209 int main(int argc, char **argv)
210 {
211         fd_set rdfs;
212         int s[MAXSOCK];
213         int bridge = 0;
214         useconds_t bridge_delay = 0;
215         unsigned char timestamp = 0;
216         int hw_timestamp = 0;
217         unsigned char dropmonitor = 0;
218         unsigned char extra_msg_info = 0;
219         unsigned char silent = SILENT_INI;
220         unsigned char silentani = 0;
221         unsigned char color = 0;
222         unsigned char view = 0;
223         unsigned char log = 0;
224         unsigned char logfrmt = 0;
225         int count = 0;
226         int rcvbuf_size = 0;
227         int opt, ret;
228         int currmax, numfilter;
229         int join_filter;
230         char *ptr, *nptr;
231         struct sockaddr_can addr;
232         char ctrlmsg[CMSG_SPACE(sizeof(struct timeval)) + CMSG_SPACE(sizeof(__u32))];
233         struct iovec iov;
234         struct msghdr msg;
235         struct cmsghdr *cmsg;
236         struct can_filter *rfilter;
237         can_err_mask_t err_mask;
238         struct canfd_frame frame;
239         int nbytes, i, maxdlen;
240         struct ifreq ifr;
241         struct timeval tv, last_tv;
242         struct timeval timeout, timeout_config = { 0, 0 }, *timeout_current = NULL;
243         FILE *logfile = NULL;
244
245         signal(SIGTERM, sigterm);
246         signal(SIGHUP, sigterm);
247         signal(SIGINT, sigterm);
248
249         last_tv.tv_sec  = 0;
250         last_tv.tv_usec = 0;
251
252         while ((opt = getopt(argc, argv, "t:ciaSs:b:B:u:ldxLn:r:heT:H?")) != -1) {
253                 switch (opt) {
254                 case 't':
255                         timestamp = optarg[0];
256                         if ((timestamp != 'a') && (timestamp != 'A') &&
257                             (timestamp != 'd') && (timestamp != 'z')) {
258                                 fprintf(stderr, "%s: unknown timestamp mode '%c' - ignored\n",
259                                        basename(argv[0]), optarg[0]);
260                                 timestamp = 0;
261                         }
262                         break;
263
264                 case 'H':
265                         hw_timestamp = 1;
266                         break;
267
268                 case 'c':
269                         color++;
270                         break;
271
272                 case 'i':
273                         view |= CANLIB_VIEW_BINARY;
274                         break;
275
276                 case 'a':
277                         view |= CANLIB_VIEW_ASCII;
278                         break;
279
280                 case 'S':
281                         view |= CANLIB_VIEW_SWAP;
282                         break;
283
284                 case 'e':
285                         view |= CANLIB_VIEW_ERROR;
286                         break;
287
288                 case 's':
289                         silent = atoi(optarg);
290                         if (silent > SILENT_ON) {
291                                 print_usage(basename(argv[0]));
292                                 exit(1);
293                         }
294                         break;
295
296                 case 'b':
297                 case 'B':
298                         if (strlen(optarg) >= IFNAMSIZ) {
299                                 fprintf(stderr, "Name of CAN device '%s' is too long!\n\n", optarg);
300                                 return 1;
301                         } else {
302                                 bridge = socket(PF_CAN, SOCK_RAW, CAN_RAW);
303                                 if (bridge < 0) {
304                                         perror("bridge socket");
305                                         return 1;
306                                 }
307                                 addr.can_family = AF_CAN;
308                                 strcpy(ifr.ifr_name, optarg);
309                                 if (ioctl(bridge, SIOCGIFINDEX, &ifr) < 0)
310                                         perror("SIOCGIFINDEX");
311                                 addr.can_ifindex = ifr.ifr_ifindex;
312                 
313                                 if (!addr.can_ifindex) {
314                                         perror("invalid bridge interface");
315                                         return 1;
316                                 }
317
318                                 /* disable default receive filter on this write-only RAW socket */
319                                 setsockopt(bridge, SOL_CAN_RAW, CAN_RAW_FILTER, NULL, 0);
320
321                                 if (opt == 'B') {
322                                         const int loopback = 0;
323
324                                         setsockopt(bridge, SOL_CAN_RAW, CAN_RAW_LOOPBACK,
325                                                    &loopback, sizeof(loopback));
326                                 }
327
328                                 if (bind(bridge, (struct sockaddr *)&addr, sizeof(addr)) < 0) {
329                                         perror("bridge bind");
330                                         return 1;
331                                 }
332                         }
333                         break;
334             
335                 case 'u':
336                         bridge_delay = (useconds_t)strtoul(optarg, (char **)NULL, 10);
337                         break;
338
339                 case 'l':
340                         log = 1;
341                         break;
342
343                 case 'd':
344                         dropmonitor = 1;
345                         break;
346
347                 case 'x':
348                         extra_msg_info = 1;
349                         break;
350
351                 case 'L':
352                         logfrmt = 1;
353                         break;
354
355                 case 'n':
356                         count = atoi(optarg);
357                         if (count < 1) {
358                                 print_usage(basename(argv[0]));
359                                 exit(1);
360                         }
361                         break;
362
363                 case 'r':
364                         rcvbuf_size = atoi(optarg);
365                         if (rcvbuf_size < 1) {
366                                 print_usage(basename(argv[0]));
367                                 exit(1);
368                         }
369                         break;
370
371                 case 'T':
372                         errno = 0;
373                         timeout_config.tv_usec = strtol(optarg, NULL, 0);
374                         if (errno != 0) {
375                                 print_usage(basename(argv[0]));
376                                 exit(1);
377                         }
378                         timeout_config.tv_sec = timeout_config.tv_usec / 1000;
379                         timeout_config.tv_usec = (timeout_config.tv_usec % 1000) * 1000;
380                         timeout_current = &timeout;
381                         break;
382                 default:
383                         print_usage(basename(argv[0]));
384                         exit(1);
385                         break;
386                 }
387         }
388
389         if (optind == argc) {
390                 print_usage(basename(argv[0]));
391                 exit(0);
392         }
393         
394         if (logfrmt && view) {
395                 fprintf(stderr, "Log file format selected: Please disable ASCII/BINARY/SWAP options!\n");
396                 exit(0);
397         }
398
399         if (silent == SILENT_INI) {
400                 if (log) {
401                         fprintf(stderr, "Disabled standard output while logging.\n");
402                         silent = SILENT_ON; /* disable output on stdout */
403                 } else
404                         silent = SILENT_OFF; /* default output */
405         }
406
407         currmax = argc - optind; /* find real number of CAN devices */
408
409         if (currmax > MAXSOCK) {
410                 fprintf(stderr, "More than %d CAN devices given on commandline!\n", MAXSOCK);
411                 return 1;
412         }
413
414         for (i=0; i < currmax; i++) {
415
416                 ptr = argv[optind+i];
417                 nptr = strchr(ptr, ',');
418
419 #ifdef DEBUG
420                 printf("open %d '%s'.\n", i, ptr);
421 #endif
422
423                 s[i] = socket(PF_CAN, SOCK_RAW, CAN_RAW);
424                 if (s[i] < 0) {
425                         perror("socket");
426                         return 1;
427                 }
428
429                 cmdlinename[i] = ptr; /* save pointer to cmdline name of this socket */
430
431                 if (nptr)
432                         nbytes = nptr - ptr;  /* interface name is up the first ',' */
433                 else
434                         nbytes = strlen(ptr); /* no ',' found => no filter definitions */
435
436                 if (nbytes >= IFNAMSIZ) {
437                         fprintf(stderr, "name of CAN device '%s' is too long!\n", ptr);
438                         return 1;
439                 }
440
441                 if (nbytes > max_devname_len)
442                         max_devname_len = nbytes; /* for nice printing */
443
444                 addr.can_family = AF_CAN;
445
446                 memset(&ifr.ifr_name, 0, sizeof(ifr.ifr_name));
447                 strncpy(ifr.ifr_name, ptr, nbytes);
448
449 #ifdef DEBUG
450                 printf("using interface name '%s'.\n", ifr.ifr_name);
451 #endif
452
453                 if (strcmp(ANYDEV, ifr.ifr_name)) {
454                         if (ioctl(s[i], SIOCGIFINDEX, &ifr) < 0) {
455                                 perror("SIOCGIFINDEX");
456                                 exit(1);
457                         }
458                         addr.can_ifindex = ifr.ifr_ifindex;
459                 } else
460                         addr.can_ifindex = 0; /* any can interface */
461
462                 if (nptr) {
463
464                         /* found a ',' after the interface name => check for filters */
465
466                         /* determine number of filters to alloc the filter space */
467                         numfilter = 0;
468                         ptr = nptr;
469                         while (ptr) {
470                                 numfilter++;
471                                 ptr++; /* hop behind the ',' */
472                                 ptr = strchr(ptr, ','); /* exit condition */
473                         }
474
475                         rfilter = malloc(sizeof(struct can_filter) * numfilter);
476                         if (!rfilter) {
477                                 fprintf(stderr, "Failed to create filter space!\n");
478                                 return 1;
479                         }
480
481                         numfilter = 0;
482                         err_mask = 0;
483                         join_filter = 0;
484
485                         while (nptr) {
486
487                                 ptr = nptr+1; /* hop behind the ',' */
488                                 nptr = strchr(ptr, ','); /* update exit condition */
489
490                                 if (sscanf(ptr, "%x:%x",
491                                            &rfilter[numfilter].can_id, 
492                                            &rfilter[numfilter].can_mask) == 2) {
493                                         rfilter[numfilter].can_mask &= ~CAN_ERR_FLAG;
494                                         numfilter++;
495                                 } else if (sscanf(ptr, "%x~%x",
496                                                   &rfilter[numfilter].can_id, 
497                                                   &rfilter[numfilter].can_mask) == 2) {
498                                         rfilter[numfilter].can_id |= CAN_INV_FILTER;
499                                         rfilter[numfilter].can_mask &= ~CAN_ERR_FLAG;
500                                         numfilter++;
501                                 } else if (*ptr == 'j' || *ptr == 'J') {
502                                         join_filter = 1;
503                                 } else if (sscanf(ptr, "#%x", &err_mask) != 1) { 
504                                         fprintf(stderr, "Error in filter option parsing: '%s'\n", ptr);
505                                         return 1;
506                                 }
507                         }
508
509                         if (err_mask)
510                                 setsockopt(s[i], SOL_CAN_RAW, CAN_RAW_ERR_FILTER,
511                                            &err_mask, sizeof(err_mask));
512
513                         if (join_filter && setsockopt(s[i], SOL_CAN_RAW, CAN_RAW_JOIN_FILTERS,
514                                                       &join_filter, sizeof(join_filter)) < 0) {
515                                 perror("setsockopt CAN_RAW_JOIN_FILTERS not supported by your Linux Kernel");
516                                 return 1;
517                         }
518
519                         if (numfilter)
520                                 setsockopt(s[i], SOL_CAN_RAW, CAN_RAW_FILTER,
521                                            rfilter, numfilter * sizeof(struct can_filter));
522
523                         free(rfilter);
524
525                 } /* if (nptr) */
526
527                 /* try to switch the socket into CAN FD mode */
528                 setsockopt(s[i], SOL_CAN_RAW, CAN_RAW_FD_FRAMES, &canfd_on, sizeof(canfd_on));
529
530                 if (rcvbuf_size) {
531
532                         int curr_rcvbuf_size;
533                         socklen_t curr_rcvbuf_size_len = sizeof(curr_rcvbuf_size);
534
535                         /* try SO_RCVBUFFORCE first, if we run with CAP_NET_ADMIN */
536                         if (setsockopt(s[i], SOL_SOCKET, SO_RCVBUFFORCE,
537                                        &rcvbuf_size, sizeof(rcvbuf_size)) < 0) {
538 #ifdef DEBUG
539                                 printf("SO_RCVBUFFORCE failed so try SO_RCVBUF ...\n");
540 #endif
541                                 if (setsockopt(s[i], SOL_SOCKET, SO_RCVBUF,
542                                                &rcvbuf_size, sizeof(rcvbuf_size)) < 0) {
543                                         perror("setsockopt SO_RCVBUF");
544                                         return 1;
545                                 }
546
547                                 if (getsockopt(s[i], SOL_SOCKET, SO_RCVBUF,
548                                                &curr_rcvbuf_size, &curr_rcvbuf_size_len) < 0) {
549                                         perror("getsockopt SO_RCVBUF");
550                                         return 1;
551                                 }
552
553                                 /* Only print a warning the first time we detect the adjustment */
554                                 /* n.b.: The wanted size is doubled in Linux in net/sore/sock.c */
555                                 if (!i && curr_rcvbuf_size < rcvbuf_size*2)
556                                         fprintf(stderr, "The socket receive buffer size was "
557                                                 "adjusted due to /proc/sys/net/core/rmem_max.\n");
558                         }
559                 }
560
561                 if (timestamp || log || logfrmt) {
562                         if (hw_timestamp == 0) {
563                                 const int timestamp_on = 1;
564
565                                 if (setsockopt(s[i], SOL_SOCKET, SO_TIMESTAMP,
566                                                &timestamp_on, sizeof(timestamp_on)) < 0) {
567                                         perror("setsockopt SO_TIMESTAMP");
568                                         return 1;
569                                 }
570                         } else {
571                                 struct ifreq hwtstamp;
572                                 struct hwtstamp_config hwconfig;
573
574                                 memset(&hwtstamp, 0, sizeof(hwtstamp));
575                                 strncpy(hwtstamp.ifr_name, ifr.ifr_name, sizeof(hwtstamp.ifr_name));
576                                 hwtstamp.ifr_data = (void *)&hwconfig;
577                                 memset(&hwconfig, 0, sizeof(hwconfig));
578                                 hwconfig.tx_type = HWTSTAMP_TX_OFF;
579                                 hwconfig.rx_filter = HWTSTAMP_FILTER_ALL;
580
581                                 if (ioctl(s[i], SIOCSHWTSTAMP, &hwtstamp) < 0) {
582                                         perror("SIOCSHWTSTAMP");
583                                         return 1;
584                                 }
585
586                                 const int so_timestamping_flags = SOF_TIMESTAMPING_RAW_HARDWARE;
587
588                                 if (setsockopt(s[i], SOL_SOCKET, SO_TIMESTAMPING,
589                                                &so_timestamping_flags,
590                                                sizeof(so_timestamping_flags)) < 0)
591                                         perror("setsockopt SO_TIMESTAMPING");
592                         }
593                 }
594
595                 if (dropmonitor) {
596
597                         const int dropmonitor_on = 1;
598
599                         if (setsockopt(s[i], SOL_SOCKET, SO_RXQ_OVFL,
600                                        &dropmonitor_on, sizeof(dropmonitor_on)) < 0) {
601                                 perror("setsockopt SO_RXQ_OVFL not supported by your Linux Kernel");
602                                 return 1;
603                         }
604                 }
605
606                 if (bind(s[i], (struct sockaddr *)&addr, sizeof(addr)) < 0) {
607                         perror("bind");
608                         return 1;
609                 }
610         }
611
612         if (log) {
613                 time_t currtime;
614                 struct tm now;
615                 char fname[sizeof("candump-2006-11-20_202026.log")+1];
616
617                 if (time(&currtime) == (time_t)-1) {
618                         perror("time");
619                         return 1;
620                 }
621
622                 localtime_r(&currtime, &now);
623
624                 sprintf(fname, "candump-%04d-%02d-%02d_%02d%02d%02d.log",
625                         now.tm_year + 1900,
626                         now.tm_mon + 1,
627                         now.tm_mday,
628                         now.tm_hour,
629                         now.tm_min,
630                         now.tm_sec);
631
632                 if (silent != SILENT_ON)
633                         printf("\nWarning: console output active while logging!");
634
635                 fprintf(stderr, "\nEnabling Logfile '%s'\n\n", fname);
636
637                 logfile = fopen(fname, "w");
638                 if (!logfile) {
639                         perror("logfile");
640                         return 1;
641                 }
642         }
643
644         /* these settings are static and can be held out of the hot path */
645         iov.iov_base = &frame;
646         msg.msg_name = &addr;
647         msg.msg_iov = &iov;
648         msg.msg_iovlen = 1;
649         msg.msg_control = &ctrlmsg;
650
651         while (running) {
652
653                 FD_ZERO(&rdfs);
654                 for (i=0; i<currmax; i++)
655                         FD_SET(s[i], &rdfs);
656
657                 if (timeout_current)
658                         *timeout_current = timeout_config;
659
660                 if ((ret = select(s[currmax-1]+1, &rdfs, NULL, NULL, timeout_current)) <= 0) {
661                         //perror("select");
662                         running = 0;
663                         continue;
664                 }
665
666                 for (i=0; i<currmax; i++) {  /* check all CAN RAW sockets */
667
668                         if (FD_ISSET(s[i], &rdfs)) {
669
670                                 int idx;
671
672                                 /* these settings may be modified by recvmsg() */
673                                 iov.iov_len = sizeof(frame);
674                                 msg.msg_namelen = sizeof(addr);
675                                 msg.msg_controllen = sizeof(ctrlmsg);  
676                                 msg.msg_flags = 0;
677
678                                 nbytes = recvmsg(s[i], &msg, 0);
679                                 if (nbytes < 0) {
680                                         perror("read");
681                                         return 1;
682                                 }
683
684                                 if ((size_t)nbytes == CAN_MTU)
685                                         maxdlen = CAN_MAX_DLEN;
686                                 else if ((size_t)nbytes == CANFD_MTU)
687                                         maxdlen = CANFD_MAX_DLEN;
688                                 else {
689                                         fprintf(stderr, "read: incomplete CAN frame\n");
690                                         return 1;
691                                 }
692
693                                 if (count && (--count == 0))
694                                         running = 0;
695
696                                 if (bridge) {
697                                         if (bridge_delay)
698                                                 usleep(bridge_delay);
699
700                                         nbytes = write(bridge, &frame, nbytes);
701                                         if (nbytes < 0) {
702                                                 perror("bridge write");
703                                                 return 1;
704                                         } else if ((size_t)nbytes != CAN_MTU && (size_t)nbytes != CANFD_MTU) {
705                                                 fprintf(stderr,"bridge write: incomplete CAN frame\n");
706                                                 return 1;
707                                         }
708                                 }
709                     
710                                 for (cmsg = CMSG_FIRSTHDR(&msg);
711                                      cmsg && (cmsg->cmsg_level == SOL_SOCKET);
712                                      cmsg = CMSG_NXTHDR(&msg,cmsg)) {
713                                         if (cmsg->cmsg_type == SO_TIMESTAMP)
714                                                 tv = *(struct timeval *)CMSG_DATA(cmsg);
715                                         else if (cmsg->cmsg_type == SO_RXQ_OVFL)
716                                                 dropcnt[i] = *(__u32 *)CMSG_DATA(cmsg);
717                                         else if (cmsg->cmsg_type == SO_TIMESTAMPING) {
718                                                 struct timespec *ts = (struct timespec *) CMSG_DATA(cmsg);
719                                                 tv.tv_sec = ts[2].tv_sec;
720                                                 tv.tv_usec = ts[2].tv_nsec / 1000;
721                                         }
722
723                                 }
724
725                                 /* check for (unlikely) dropped frames on this specific socket */
726                                 if (dropcnt[i] != last_dropcnt[i]) {
727
728                                         __u32 frames = dropcnt[i] - last_dropcnt[i];
729
730                                         if (silent != SILENT_ON)
731                                                 printf("DROPCOUNT: dropped %d CAN frame%s on '%s' socket (total drops %d)\n",
732                                                        frames, (frames > 1)?"s":"", cmdlinename[i], dropcnt[i]);
733
734                                         if (log)
735                                                 fprintf(logfile, "DROPCOUNT: dropped %d CAN frame%s on '%s' socket (total drops %d)\n",
736                                                         frames, (frames > 1)?"s":"", cmdlinename[i], dropcnt[i]);
737
738                                         last_dropcnt[i] = dropcnt[i];
739                                 }
740
741                                 idx = idx2dindex(addr.can_ifindex, s[i]);
742
743                                 /* once we detected a EFF frame indent SFF frames accordingly */
744                                 if (frame.can_id & CAN_EFF_FLAG)
745                                         view |= CANLIB_VIEW_INDENT_SFF;
746
747                                 if (log) {
748                                         char buf[CL_CFSZ]; /* max length */
749
750                                         /* log CAN frame with absolute timestamp & device */
751                                         sprint_canframe(buf, &frame, 0, maxdlen);
752                                         fprintf(logfile, "(%010ld.%06ld) %*s %s\n",
753                                                 tv.tv_sec, tv.tv_usec,
754                                                 max_devname_len, devname[idx], buf);
755                                 }
756
757                                 if (logfrmt) {
758                                         char buf[CL_CFSZ]; /* max length */
759
760                                         /* print CAN frame in log file style to stdout */
761                                         sprint_canframe(buf, &frame, 0, maxdlen);
762                                         printf("(%010ld.%06ld) %*s %s\n",
763                                                tv.tv_sec, tv.tv_usec,
764                                                max_devname_len, devname[idx], buf);
765                                         goto out_fflush; /* no other output to stdout */
766                                 }
767
768                                 if (silent != SILENT_OFF){
769                                         if (silent == SILENT_ANI) {
770                                                 printf("%c\b", anichar[silentani%=MAXANI]);
771                                                 silentani++;
772                                         }
773                                         goto out_fflush; /* no other output to stdout */
774                                 }
775                       
776                                 printf(" %s", (color>2)?col_on[idx%MAXCOL]:"");
777
778                                 switch (timestamp) {
779
780                                 case 'a': /* absolute with timestamp */
781                                         printf("(%010ld.%06ld) ", tv.tv_sec, tv.tv_usec);
782                                         break;
783
784                                 case 'A': /* absolute with date */
785                                 {
786                                         struct tm tm;
787                                         char timestring[25];
788
789                                         tm = *localtime(&tv.tv_sec);
790                                         strftime(timestring, 24, "%Y-%m-%d %H:%M:%S", &tm);
791                                         printf("(%s.%06ld) ", timestring, tv.tv_usec);
792                                 }
793                                 break;
794
795                                 case 'd': /* delta */
796                                 case 'z': /* starting with zero */
797                                 {
798                                         struct timeval diff;
799
800                                         if (last_tv.tv_sec == 0)   /* first init */
801                                                 last_tv = tv;
802                                         diff.tv_sec  = tv.tv_sec  - last_tv.tv_sec;
803                                         diff.tv_usec = tv.tv_usec - last_tv.tv_usec;
804                                         if (diff.tv_usec < 0)
805                                                 diff.tv_sec--, diff.tv_usec += 1000000;
806                                         if (diff.tv_sec < 0)
807                                                 diff.tv_sec = diff.tv_usec = 0;
808                                         printf("(%03ld.%06ld) ", diff.tv_sec, diff.tv_usec);
809                                 
810                                         if (timestamp == 'd')
811                                                 last_tv = tv; /* update for delta calculation */
812                                 }
813                                 break;
814
815                                 default: /* no timestamp output */
816                                         break;
817                                 }
818
819                                 printf(" %s", (color && (color<3))?col_on[idx%MAXCOL]:"");
820                                 printf("%*s", max_devname_len, devname[idx]);
821
822                                 if (extra_msg_info) {
823
824                                         if (msg.msg_flags & MSG_DONTROUTE)
825                                                 printf ("  TX %s", extra_m_info[frame.flags & 3]);
826                                         else
827                                                 printf ("  RX %s", extra_m_info[frame.flags & 3]);
828                                 }
829
830                                 printf("%s  ", (color==1)?col_off:"");
831
832                                 fprint_long_canframe(stdout, &frame, NULL, view, maxdlen);
833
834                                 printf("%s", (color>1)?col_off:"");
835                                 printf("\n");
836                         }
837
838                 out_fflush:
839                         fflush(stdout);
840                 }
841         }
842
843         for (i=0; i<currmax; i++)
844                 close(s[i]);
845
846         if (bridge)
847                 close(bridge);
848
849         if (log)
850                 fclose(logfile);
851
852         return 0;
853 }