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