]> rtime.felk.cvut.cz Git - sojka/can-utils.git/blob - candump.c
configure: adjust bug report address
[sojka/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 <unistd.h>
47 #include <string.h>
48 #include <signal.h>
49 #include <ctype.h>
50 #include <libgen.h>
51 #include <time.h>
52
53 #include <sys/time.h>
54 #include <sys/types.h>
55 #include <sys/socket.h>
56 #include <sys/ioctl.h>
57 #include <sys/uio.h>
58 #include <net/if.h>
59
60 #include <linux/can.h>
61 #include <linux/can/raw.h>
62
63 #include "terminal.h"
64 #include "lib.h"
65
66 #define MAXSOCK 16    /* max. number of CAN interfaces given on the cmdline */
67 #define MAXIFNAMES 30 /* size of receive name index to omit ioctls */
68 #define MAXCOL 6      /* number of different colors for colorized output */
69 #define ANYDEV "any"  /* name of interface to receive from any CAN interface */
70 #define ANL "\r\n"    /* newline in ASC mode */
71
72 #define SILENT_INI 42 /* detect user setting on commandline */
73 #define SILENT_OFF 0  /* no silent mode */
74 #define SILENT_ANI 1  /* silent mode with animation */
75 #define SILENT_ON  2  /* silent mode (completely silent) */
76
77 #define BOLD    ATTBOLD
78 #define RED     ATTBOLD FGRED
79 #define GREEN   ATTBOLD FGGREEN
80 #define YELLOW  ATTBOLD FGYELLOW
81 #define BLUE    ATTBOLD FGBLUE
82 #define MAGENTA ATTBOLD FGMAGENTA
83 #define CYAN    ATTBOLD FGCYAN
84
85 const char col_on [MAXCOL][19] = {BLUE, RED, GREEN, BOLD, MAGENTA, CYAN};
86 const char col_off [] = ATTRESET;
87
88 static char *cmdlinename[MAXSOCK];
89 static __u32 dropcnt[MAXSOCK];
90 static __u32 last_dropcnt[MAXSOCK];
91 static char devname[MAXIFNAMES][IFNAMSIZ+1];
92 static int  dindex[MAXIFNAMES];
93 static int  max_devname_len; /* to prevent frazzled device name output */ 
94 const int canfd_on = 1;
95
96 #define MAXANI 4
97 const char anichar[MAXANI] = {'|', '/', '-', '\\'};
98 const char extra_m_info[4][4] = {"- -", "B -", "- E", "B E"};
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          (swap byte order in printed CAN data[] - marked with '%c' )\n", SWAP_DELIMITER);
113         fprintf(stderr, "         -s <level>  (silent mode - %d: off (default) %d: animation %d: silent)\n", SILENT_OFF, SILENT_ANI, SILENT_ON);
114         fprintf(stderr, "         -b <can>    (bridge mode - send received frames to <can>)\n");
115         fprintf(stderr, "         -B <can>    (bridge mode - like '-b' with disabled loopback)\n");
116         fprintf(stderr, "         -u <usecs>  (delay bridge forwarding by <usecs> microseconds)\n");
117         fprintf(stderr, "         -l          (log CAN-frames into file. Sets '-s %d' by default)\n", SILENT_ON);
118         fprintf(stderr, "         -L          (use log file format on stdout)\n");
119         fprintf(stderr, "         -n <count>  (terminate after receiption of <count> CAN frames)\n");
120         fprintf(stderr, "         -r <size>   (set socket receive buffer to <size>)\n");
121         fprintf(stderr, "         -d          (monitor dropped CAN frames)\n");
122         fprintf(stderr, "         -e          (dump CAN error frames in human-readable format)\n");
123         fprintf(stderr, "         -x          (print extra message infos, rx/tx brs esi)\n");
124         fprintf(stderr, "\n");
125         fprintf(stderr, "Up to %d CAN interfaces with optional filter sets can be specified\n", MAXSOCK);
126         fprintf(stderr, "on the commandline in the form: <ifname>[,filter]*\n");
127         fprintf(stderr, "\nComma separated filters can be specified for each given CAN interface:\n");
128         fprintf(stderr, " <can_id>:<can_mask> (matches when <received_can_id> & mask == can_id & mask)\n");
129         fprintf(stderr, " <can_id>~<can_mask> (matches when <received_can_id> & mask != can_id & mask)\n");
130         fprintf(stderr, " #<error_mask>       (set error frame filter, see include/linux/can/error.h)\n");
131         fprintf(stderr, "\nCAN IDs, masks and data content are given and expected in hexadecimal values.\n");
132         fprintf(stderr, "When can_id and can_mask are both 8 digits, they are assumed to be 29 bit EFF.\n");
133         fprintf(stderr, "Without any given filter all data frames are received ('0:0' default filter).\n");
134         fprintf(stderr, "\nUse interface name '%s' to receive from all CAN interfaces.\n", ANYDEV);
135         fprintf(stderr, "\nExamples:\n");
136         fprintf(stderr, "%s -c -c -ta can0,123:7FF,400:700,#000000FF can2,400~7F0 can3 can8\n", prg);
137         fprintf(stderr, "%s -l any,0~0,#FFFFFFFF    (log only error frames but no(!) data frames)\n", prg);
138         fprintf(stderr, "%s -l any,0:0,#FFFFFFFF    (log error frames and also all data frames)\n", prg);
139         fprintf(stderr, "%s vcan2,92345678:DFFFFFFF (match only for extended CAN ID 12345678)\n", prg);
140         fprintf(stderr, "%s vcan2,123:7FF (matches CAN ID 123 - including EFF and RTR frames)\n", prg);
141         fprintf(stderr, "%s vcan2,123:C00007FF (matches CAN ID 123 - only SFF and non-RTR frames)\n", prg);
142         fprintf(stderr, "\n");
143 }
144
145 void sigterm(int signo)
146 {
147         running = 0;
148 }
149
150 int idx2dindex(int ifidx, int socket) {
151
152         int i;
153         struct ifreq ifr;
154
155         for (i=0; i < MAXIFNAMES; i++) {
156                 if (dindex[i] == ifidx)
157                         return i;
158         }
159
160         /* create new interface index cache entry */
161
162         /* remove index cache zombies first */
163         for (i=0; i < MAXIFNAMES; i++) {
164                 if (dindex[i]) {
165                         ifr.ifr_ifindex = dindex[i];
166                         if (ioctl(socket, SIOCGIFNAME, &ifr) < 0)
167                                 dindex[i] = 0;
168                 }
169         }
170
171         for (i=0; i < MAXIFNAMES; i++)
172                 if (!dindex[i]) /* free entry */
173                         break;
174
175         if (i == MAXIFNAMES) {
176                 fprintf(stderr, "Interface index cache only supports %d interfaces.\n",
177                        MAXIFNAMES);
178                 exit(1);
179         }
180
181         dindex[i] = ifidx;
182
183         ifr.ifr_ifindex = ifidx;
184         if (ioctl(socket, SIOCGIFNAME, &ifr) < 0)
185                 perror("SIOCGIFNAME");
186
187         if (max_devname_len < strlen(ifr.ifr_name))
188                 max_devname_len = strlen(ifr.ifr_name);
189
190         strcpy(devname[i], ifr.ifr_name);
191
192 #ifdef DEBUG
193         printf("new index %d (%s)\n", i, devname[i]);
194 #endif
195
196         return i;
197 }
198
199 int main(int argc, char **argv)
200 {
201         fd_set rdfs;
202         int s[MAXSOCK];
203         int bridge = 0;
204         useconds_t bridge_delay = 0;
205         unsigned char timestamp = 0;
206         unsigned char dropmonitor = 0;
207         unsigned char extra_msg_info = 0;
208         unsigned char silent = SILENT_INI;
209         unsigned char silentani = 0;
210         unsigned char color = 0;
211         unsigned char view = 0;
212         unsigned char log = 0;
213         unsigned char logfrmt = 0;
214         int count = 0;
215         int rcvbuf_size = 0;
216         int opt, ret;
217         int currmax, numfilter;
218         char *ptr, *nptr;
219         struct sockaddr_can addr;
220         char ctrlmsg[CMSG_SPACE(sizeof(struct timeval)) + CMSG_SPACE(sizeof(__u32))];
221         struct iovec iov;
222         struct msghdr msg;
223         struct cmsghdr *cmsg;
224         struct can_filter *rfilter;
225         can_err_mask_t err_mask;
226         struct canfd_frame frame;
227         int nbytes, i, maxdlen;
228         struct ifreq ifr;
229         struct timeval tv, last_tv;
230         FILE *logfile = NULL;
231
232         signal(SIGTERM, sigterm);
233         signal(SIGHUP, sigterm);
234         signal(SIGINT, sigterm);
235
236         last_tv.tv_sec  = 0;
237         last_tv.tv_usec = 0;
238
239         while ((opt = getopt(argc, argv, "t:ciaSs:b:B:u:ldxLn:r:he?")) != -1) {
240                 switch (opt) {
241                 case 't':
242                         timestamp = optarg[0];
243                         if ((timestamp != 'a') && (timestamp != 'A') &&
244                             (timestamp != 'd') && (timestamp != 'z')) {
245                                 fprintf(stderr, "%s: unknown timestamp mode '%c' - ignored\n",
246                                        basename(argv[0]), optarg[0]);
247                                 timestamp = 0;
248                         }
249                         break;
250
251                 case 'c':
252                         color++;
253                         break;
254
255                 case 'i':
256                         view |= CANLIB_VIEW_BINARY;
257                         break;
258
259                 case 'a':
260                         view |= CANLIB_VIEW_ASCII;
261                         break;
262
263                 case 'S':
264                         view |= CANLIB_VIEW_SWAP;
265                         break;
266
267                 case 'e':
268                         view |= CANLIB_VIEW_ERROR;
269                         break;
270
271                 case 's':
272                         silent = atoi(optarg);
273                         if (silent > SILENT_ON) {
274                                 print_usage(basename(argv[0]));
275                                 exit(1);
276                         }
277                         break;
278
279                 case 'b':
280                 case 'B':
281                         if (strlen(optarg) >= IFNAMSIZ) {
282                                 fprintf(stderr, "Name of CAN device '%s' is too long!\n\n", optarg);
283                                 return 1;
284                         } else {
285                                 bridge = socket(PF_CAN, SOCK_RAW, CAN_RAW);
286                                 if (bridge < 0) {
287                                         perror("bridge socket");
288                                         return 1;
289                                 }
290                                 addr.can_family = AF_CAN;
291                                 strcpy(ifr.ifr_name, optarg);
292                                 if (ioctl(bridge, SIOCGIFINDEX, &ifr) < 0)
293                                         perror("SIOCGIFINDEX");
294                                 addr.can_ifindex = ifr.ifr_ifindex;
295                 
296                                 if (!addr.can_ifindex) {
297                                         perror("invalid bridge interface");
298                                         return 1;
299                                 }
300
301                                 /* disable default receive filter on this write-only RAW socket */
302                                 setsockopt(bridge, SOL_CAN_RAW, CAN_RAW_FILTER, NULL, 0);
303
304                                 if (opt == 'B') {
305                                         const int loopback = 0;
306
307                                         setsockopt(bridge, SOL_CAN_RAW, CAN_RAW_LOOPBACK,
308                                                    &loopback, sizeof(loopback));
309                                 }
310
311                                 if (bind(bridge, (struct sockaddr *)&addr, sizeof(addr)) < 0) {
312                                         perror("bridge bind");
313                                         return 1;
314                                 }
315                         }
316                         break;
317             
318                 case 'u':
319                         bridge_delay = (useconds_t)strtoul(optarg, (char **)NULL, 10);
320                         break;
321
322                 case 'l':
323                         log = 1;
324                         break;
325
326                 case 'd':
327                         dropmonitor = 1;
328                         break;
329
330                 case 'x':
331                         extra_msg_info = 1;
332                         break;
333
334                 case 'L':
335                         logfrmt = 1;
336                         break;
337
338                 case 'n':
339                         count = atoi(optarg);
340                         if (count < 1) {
341                                 print_usage(basename(argv[0]));
342                                 exit(1);
343                         }
344                         break;
345
346                 case 'r':
347                         rcvbuf_size = atoi(optarg);
348                         if (rcvbuf_size < 1) {
349                                 print_usage(basename(argv[0]));
350                                 exit(1);
351                         }
352                         break;
353
354                 default:
355                         print_usage(basename(argv[0]));
356                         exit(1);
357                         break;
358                 }
359         }
360
361         if (optind == argc) {
362                 print_usage(basename(argv[0]));
363                 exit(0);
364         }
365         
366         if (logfrmt && view) {
367                 fprintf(stderr, "Log file format selected: Please disable ASCII/BINARY/SWAP options!\n");
368                 exit(0);
369         }
370
371         if (silent == SILENT_INI) {
372                 if (log) {
373                         fprintf(stderr, "Disabled standard output while logging.\n");
374                         silent = SILENT_ON; /* disable output on stdout */
375                 } else
376                         silent = SILENT_OFF; /* default output */
377         }
378
379         currmax = argc - optind; /* find real number of CAN devices */
380
381         if (currmax > MAXSOCK) {
382                 fprintf(stderr, "More than %d CAN devices given on commandline!\n", MAXSOCK);
383                 return 1;
384         }
385
386         for (i=0; i < currmax; i++) {
387
388                 ptr = argv[optind+i];
389                 nptr = strchr(ptr, ',');
390
391 #ifdef DEBUG
392                 printf("open %d '%s'.\n", i, ptr);
393 #endif
394
395                 s[i] = socket(PF_CAN, SOCK_RAW, CAN_RAW);
396                 if (s[i] < 0) {
397                         perror("socket");
398                         return 1;
399                 }
400
401                 cmdlinename[i] = ptr; /* save pointer to cmdline name of this socket */
402
403                 if (nptr)
404                         nbytes = nptr - ptr;  /* interface name is up the first ',' */
405                 else
406                         nbytes = strlen(ptr); /* no ',' found => no filter definitions */
407
408                 if (nbytes >= IFNAMSIZ) {
409                         fprintf(stderr, "name of CAN device '%s' is too long!\n", ptr);
410                         return 1;
411                 }
412
413                 if (nbytes > max_devname_len)
414                         max_devname_len = nbytes; /* for nice printing */
415
416                 addr.can_family = AF_CAN;
417
418                 memset(&ifr.ifr_name, 0, sizeof(ifr.ifr_name));
419                 strncpy(ifr.ifr_name, ptr, nbytes);
420
421 #ifdef DEBUG
422                 printf("using interface name '%s'.\n", ifr.ifr_name);
423 #endif
424
425                 if (strcmp(ANYDEV, ifr.ifr_name)) {
426                         if (ioctl(s[i], SIOCGIFINDEX, &ifr) < 0) {
427                                 perror("SIOCGIFINDEX");
428                                 exit(1);
429                         }
430                         addr.can_ifindex = ifr.ifr_ifindex;
431                 } else
432                         addr.can_ifindex = 0; /* any can interface */
433
434                 if (nptr) {
435
436                         /* found a ',' after the interface name => check for filters */
437
438                         /* determine number of filters to alloc the filter space */
439                         numfilter = 0;
440                         ptr = nptr;
441                         while (ptr) {
442                                 numfilter++;
443                                 ptr++; /* hop behind the ',' */
444                                 ptr = strchr(ptr, ','); /* exit condition */
445                         }
446
447                         rfilter = malloc(sizeof(struct can_filter) * numfilter);
448                         if (!rfilter) {
449                                 fprintf(stderr, "Failed to create filter space!\n");
450                                 return 1;
451                         }
452
453                         numfilter = 0;
454                         err_mask = 0;
455
456                         while (nptr) {
457
458                                 ptr = nptr+1; /* hop behind the ',' */
459                                 nptr = strchr(ptr, ','); /* update exit condition */
460
461                                 if (sscanf(ptr, "%x:%x",
462                                            &rfilter[numfilter].can_id, 
463                                            &rfilter[numfilter].can_mask) == 2) {
464                                         rfilter[numfilter].can_mask &= ~CAN_ERR_FLAG;
465                                         numfilter++;
466                                 } else if (sscanf(ptr, "%x~%x",
467                                                   &rfilter[numfilter].can_id, 
468                                                   &rfilter[numfilter].can_mask) == 2) {
469                                         rfilter[numfilter].can_id |= CAN_INV_FILTER;
470                                         rfilter[numfilter].can_mask &= ~CAN_ERR_FLAG;
471                                         numfilter++;
472                                 } else if (sscanf(ptr, "#%x", &err_mask) != 1) { 
473                                         fprintf(stderr, "Error in filter option parsing: '%s'\n", ptr);
474                                         return 1;
475                                 }
476                         }
477
478                         if (err_mask)
479                                 setsockopt(s[i], SOL_CAN_RAW, CAN_RAW_ERR_FILTER,
480                                            &err_mask, sizeof(err_mask));
481
482                         if (numfilter)
483                                 setsockopt(s[i], SOL_CAN_RAW, CAN_RAW_FILTER,
484                                            rfilter, numfilter * sizeof(struct can_filter));
485
486                         free(rfilter);
487
488                 } /* if (nptr) */
489
490                 /* try to switch the socket into CAN FD mode */
491                 setsockopt(s[i], SOL_CAN_RAW, CAN_RAW_FD_FRAMES, &canfd_on, sizeof(canfd_on));
492
493                 if (rcvbuf_size) {
494
495                         int curr_rcvbuf_size;
496                         socklen_t curr_rcvbuf_size_len = sizeof(curr_rcvbuf_size);
497
498                         /* try SO_RCVBUFFORCE first, if we run with CAP_NET_ADMIN */
499                         if (setsockopt(s[i], SOL_SOCKET, SO_RCVBUFFORCE,
500                                        &rcvbuf_size, sizeof(rcvbuf_size)) < 0) {
501 #ifdef DEBUG
502                                 printf("SO_RCVBUFFORCE failed so try SO_RCVBUF ...\n");
503 #endif
504                                 if (setsockopt(s[i], SOL_SOCKET, SO_RCVBUF,
505                                                &rcvbuf_size, sizeof(rcvbuf_size)) < 0) {
506                                         perror("setsockopt SO_RCVBUF");
507                                         return 1;
508                                 }
509
510                                 if (getsockopt(s[i], SOL_SOCKET, SO_RCVBUF,
511                                                &curr_rcvbuf_size, &curr_rcvbuf_size_len) < 0) {
512                                         perror("getsockopt SO_RCVBUF");
513                                         return 1;
514                                 }
515
516                                 /* Only print a warning the first time we detect the adjustment */
517                                 /* n.b.: The wanted size is doubled in Linux in net/sore/sock.c */
518                                 if (!i && curr_rcvbuf_size < rcvbuf_size*2)
519                                         fprintf(stderr, "The socket receive buffer size was "
520                                                 "adjusted due to /proc/sys/net/core/rmem_max.\n");
521                         }
522                 }
523
524                 if (timestamp || log || logfrmt) {
525
526                         const int timestamp_on = 1;
527
528                         if (setsockopt(s[i], SOL_SOCKET, SO_TIMESTAMP,
529                                        &timestamp_on, sizeof(timestamp_on)) < 0) {
530                                 perror("setsockopt SO_TIMESTAMP");
531                                 return 1;
532                         }
533                 }
534
535                 if (dropmonitor) {
536
537                         const int dropmonitor_on = 1;
538
539                         if (setsockopt(s[i], SOL_SOCKET, SO_RXQ_OVFL,
540                                        &dropmonitor_on, sizeof(dropmonitor_on)) < 0) {
541                                 perror("setsockopt SO_RXQ_OVFL not supported by your Linux Kernel");
542                                 return 1;
543                         }
544                 }
545
546                 if (bind(s[i], (struct sockaddr *)&addr, sizeof(addr)) < 0) {
547                         perror("bind");
548                         return 1;
549                 }
550         }
551
552         if (log) {
553                 time_t currtime;
554                 struct tm now;
555                 char fname[sizeof("candump-2006-11-20_202026.log")+1];
556
557                 if (time(&currtime) == (time_t)-1) {
558                         perror("time");
559                         return 1;
560                 }
561
562                 localtime_r(&currtime, &now);
563
564                 sprintf(fname, "candump-%04d-%02d-%02d_%02d%02d%02d.log",
565                         now.tm_year + 1900,
566                         now.tm_mon + 1,
567                         now.tm_mday,
568                         now.tm_hour,
569                         now.tm_min,
570                         now.tm_sec);
571
572                 if (silent != SILENT_ON)
573                         printf("\nWarning: console output active while logging!");
574
575                 fprintf(stderr, "\nEnabling Logfile '%s'\n\n", fname);
576
577                 logfile = fopen(fname, "w");
578                 if (!logfile) {
579                         perror("logfile");
580                         return 1;
581                 }
582         }
583
584         /* these settings are static and can be held out of the hot path */
585         iov.iov_base = &frame;
586         msg.msg_name = &addr;
587         msg.msg_iov = &iov;
588         msg.msg_iovlen = 1;
589         msg.msg_control = &ctrlmsg;
590
591         while (running) {
592
593                 FD_ZERO(&rdfs);
594                 for (i=0; i<currmax; i++)
595                         FD_SET(s[i], &rdfs);
596
597                 if ((ret = select(s[currmax-1]+1, &rdfs, NULL, NULL, NULL)) < 0) {
598                         //perror("select");
599                         running = 0;
600                         continue;
601                 }
602
603                 for (i=0; i<currmax; i++) {  /* check all CAN RAW sockets */
604
605                         if (FD_ISSET(s[i], &rdfs)) {
606
607                                 int idx;
608
609                                 /* these settings may be modified by recvmsg() */
610                                 iov.iov_len = sizeof(frame);
611                                 msg.msg_namelen = sizeof(addr);
612                                 msg.msg_controllen = sizeof(ctrlmsg);  
613                                 msg.msg_flags = 0;
614
615                                 nbytes = recvmsg(s[i], &msg, 0);
616                                 if (nbytes < 0) {
617                                         perror("read");
618                                         return 1;
619                                 }
620
621                                 if ((size_t)nbytes == CAN_MTU)
622                                         maxdlen = CAN_MAX_DLEN;
623                                 else if ((size_t)nbytes == CANFD_MTU)
624                                         maxdlen = CANFD_MAX_DLEN;
625                                 else {
626                                         fprintf(stderr, "read: incomplete CAN frame\n");
627                                         return 1;
628                                 }
629
630                                 if (count && (--count == 0))
631                                         running = 0;
632
633                                 if (bridge) {
634                                         if (bridge_delay)
635                                                 usleep(bridge_delay);
636
637                                         nbytes = write(bridge, &frame, nbytes);
638                                         if (nbytes < 0) {
639                                                 perror("bridge write");
640                                                 return 1;
641                                         } else if ((size_t)nbytes != CAN_MTU && (size_t)nbytes != CANFD_MTU) {
642                                                 fprintf(stderr,"bridge write: incomplete CAN frame\n");
643                                                 return 1;
644                                         }
645                                 }
646                     
647                                 for (cmsg = CMSG_FIRSTHDR(&msg);
648                                      cmsg && (cmsg->cmsg_level == SOL_SOCKET);
649                                      cmsg = CMSG_NXTHDR(&msg,cmsg)) {
650                                         if (cmsg->cmsg_type == SO_TIMESTAMP)
651                                                 tv = *(struct timeval *)CMSG_DATA(cmsg);
652                                         else if (cmsg->cmsg_type == SO_RXQ_OVFL)
653                                                 dropcnt[i] = *(__u32 *)CMSG_DATA(cmsg);
654                                 }
655
656                                 /* check for (unlikely) dropped frames on this specific socket */
657                                 if (dropcnt[i] != last_dropcnt[i]) {
658
659                                         __u32 frames;
660
661                                         if (dropcnt[i] > last_dropcnt[i])
662                                                 frames = dropcnt[i] - last_dropcnt[i];
663                                         else
664                                                 frames = 4294967295U - last_dropcnt[i] + dropcnt[i]; /* 4294967295U == UINT32_MAX */
665
666                                         if (silent != SILENT_ON)
667                                                 printf("DROPCOUNT: dropped %d CAN frame%s on '%s' socket (total drops %d)\n",
668                                                        frames, (frames > 1)?"s":"", cmdlinename[i], dropcnt[i]);
669
670                                         if (log)
671                                                 fprintf(logfile, "DROPCOUNT: dropped %d CAN frame%s on '%s' socket (total drops %d)\n",
672                                                         frames, (frames > 1)?"s":"", cmdlinename[i], dropcnt[i]);
673
674                                         last_dropcnt[i] = dropcnt[i];
675                                 }
676
677                                 idx = idx2dindex(addr.can_ifindex, s[i]);
678
679                                 /* once we detected a EFF frame indent SFF frames accordingly */
680                                 if (frame.can_id & CAN_EFF_FLAG)
681                                         view |= CANLIB_VIEW_INDENT_SFF;
682
683                                 if (log) {
684                                         /* log CAN frame with absolute timestamp & device */
685                                         fprintf(logfile, "(%010ld.%06ld) ", tv.tv_sec, tv.tv_usec);
686                                         fprintf(logfile, "%*s ", max_devname_len, devname[idx]);
687                                         /* without seperator as logfile use-case is parsing */
688                                         fprint_canframe(logfile, &frame, "\n", 0, maxdlen);
689                                 }
690
691                                 if (logfrmt) {
692                                         /* print CAN frame in log file style to stdout */
693                                         printf("(%010ld.%06ld) ", tv.tv_sec, tv.tv_usec);
694                                         printf("%*s ", max_devname_len, devname[idx]);
695                                         fprint_canframe(stdout, &frame, "\n", 0, maxdlen);
696                                         goto out_fflush; /* no other output to stdout */
697                                 }
698
699                                 if (silent != SILENT_OFF){
700                                         if (silent == SILENT_ANI) {
701                                                 printf("%c\b", anichar[silentani%=MAXANI]);
702                                                 silentani++;
703                                         }
704                                         goto out_fflush; /* no other output to stdout */
705                                 }
706                       
707                                 printf(" %s", (color>2)?col_on[idx%MAXCOL]:"");
708
709                                 switch (timestamp) {
710
711                                 case 'a': /* absolute with timestamp */
712                                         printf("(%010ld.%06ld) ", tv.tv_sec, tv.tv_usec);
713                                         break;
714
715                                 case 'A': /* absolute with date */
716                                 {
717                                         struct tm tm;
718                                         char timestring[25];
719
720                                         tm = *localtime(&tv.tv_sec);
721                                         strftime(timestring, 24, "%Y-%m-%d %H:%M:%S", &tm);
722                                         printf("(%s.%06ld) ", timestring, tv.tv_usec);
723                                 }
724                                 break;
725
726                                 case 'd': /* delta */
727                                 case 'z': /* starting with zero */
728                                 {
729                                         struct timeval diff;
730
731                                         if (last_tv.tv_sec == 0)   /* first init */
732                                                 last_tv = tv;
733                                         diff.tv_sec  = tv.tv_sec  - last_tv.tv_sec;
734                                         diff.tv_usec = tv.tv_usec - last_tv.tv_usec;
735                                         if (diff.tv_usec < 0)
736                                                 diff.tv_sec--, diff.tv_usec += 1000000;
737                                         if (diff.tv_sec < 0)
738                                                 diff.tv_sec = diff.tv_usec = 0;
739                                         printf("(%03ld.%06ld) ", diff.tv_sec, diff.tv_usec);
740                                 
741                                         if (timestamp == 'd')
742                                                 last_tv = tv; /* update for delta calculation */
743                                 }
744                                 break;
745
746                                 default: /* no timestamp output */
747                                         break;
748                                 }
749
750                                 printf(" %s", (color && (color<3))?col_on[idx%MAXCOL]:"");
751                                 printf("%*s", max_devname_len, devname[idx]);
752
753                                 if (extra_msg_info) {
754
755                                         if (msg.msg_flags & MSG_DONTROUTE)
756                                                 printf ("  TX %s", extra_m_info[frame.flags & 3]);
757                                         else
758                                                 printf ("  RX %s", extra_m_info[frame.flags & 3]);
759                                 }
760
761                                 printf("%s  ", (color==1)?col_off:"");
762
763                                 fprint_long_canframe(stdout, &frame, NULL, view, maxdlen);
764
765                                 printf("%s", (color>1)?col_off:"");
766                                 printf("\n");
767                         }
768
769                 out_fflush:
770                         fflush(stdout);
771                 }
772         }
773
774         for (i=0; i<currmax; i++)
775                 close(s[i]);
776
777         if (bridge)
778                 close(bridge);
779
780         if (log)
781                 fclose(logfile);
782
783         return 0;
784 }