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