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