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