]> rtime.felk.cvut.cz Git - can-utils.git/blob - candump.c
isotp: fix copy paste error for isotp padding config
[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, "\nCAN IDs, masks and data content are given and expected in hexadecimal values.\n");
135         fprintf(stderr, "When can_id and can_mask are both 8 digits, they are assumed to be 29 bit EFF.\n");
136         fprintf(stderr, "Without any given filter all data frames are received ('0:0' default filter).\n");
137         fprintf(stderr, "\nUse interface name '%s' to receive from all CAN interfaces.\n", ANYDEV);
138         fprintf(stderr, "\nExamples:\n");
139         fprintf(stderr, "%s -c -c -ta can0,123:7FF,400:700,#000000FF can2,400~7F0 can3 can8\n", prg);
140         fprintf(stderr, "%s -l any,0~0,#FFFFFFFF    (log only error frames but no(!) data frames)\n", prg);
141         fprintf(stderr, "%s -l any,0:0,#FFFFFFFF    (log error frames and also all data frames)\n", prg);
142         fprintf(stderr, "%s vcan2,92345678:DFFFFFFF (match only for extended CAN ID 12345678)\n", prg);
143         fprintf(stderr, "%s vcan2,123:7FF (matches CAN ID 123 - including EFF and RTR frames)\n", prg);
144         fprintf(stderr, "%s vcan2,123:C00007FF (matches CAN ID 123 - only SFF and non-RTR frames)\n", prg);
145         fprintf(stderr, "\n");
146 }
147
148 void sigterm(int signo)
149 {
150         running = 0;
151 }
152
153 int idx2dindex(int ifidx, int socket) {
154
155         int i;
156         struct ifreq ifr;
157
158         for (i=0; i < MAXIFNAMES; i++) {
159                 if (dindex[i] == ifidx)
160                         return i;
161         }
162
163         /* create new interface index cache entry */
164
165         /* remove index cache zombies first */
166         for (i=0; i < MAXIFNAMES; i++) {
167                 if (dindex[i]) {
168                         ifr.ifr_ifindex = dindex[i];
169                         if (ioctl(socket, SIOCGIFNAME, &ifr) < 0)
170                                 dindex[i] = 0;
171                 }
172         }
173
174         for (i=0; i < MAXIFNAMES; i++)
175                 if (!dindex[i]) /* free entry */
176                         break;
177
178         if (i == MAXIFNAMES) {
179                 fprintf(stderr, "Interface index cache only supports %d interfaces.\n",
180                        MAXIFNAMES);
181                 exit(1);
182         }
183
184         dindex[i] = ifidx;
185
186         ifr.ifr_ifindex = ifidx;
187         if (ioctl(socket, SIOCGIFNAME, &ifr) < 0)
188                 perror("SIOCGIFNAME");
189
190         if (max_devname_len < strlen(ifr.ifr_name))
191                 max_devname_len = strlen(ifr.ifr_name);
192
193         strcpy(devname[i], ifr.ifr_name);
194
195 #ifdef DEBUG
196         printf("new index %d (%s)\n", i, devname[i]);
197 #endif
198
199         return i;
200 }
201
202 int main(int argc, char **argv)
203 {
204         fd_set rdfs;
205         int s[MAXSOCK];
206         int bridge = 0;
207         useconds_t bridge_delay = 0;
208         unsigned char timestamp = 0;
209         unsigned char dropmonitor = 0;
210         unsigned char extra_msg_info = 0;
211         unsigned char silent = SILENT_INI;
212         unsigned char silentani = 0;
213         unsigned char color = 0;
214         unsigned char view = 0;
215         unsigned char log = 0;
216         unsigned char logfrmt = 0;
217         int count = 0;
218         int rcvbuf_size = 0;
219         int opt, ret;
220         int currmax, numfilter;
221         char *ptr, *nptr;
222         struct sockaddr_can addr;
223         char ctrlmsg[CMSG_SPACE(sizeof(struct timeval)) + CMSG_SPACE(sizeof(__u32))];
224         struct iovec iov;
225         struct msghdr msg;
226         struct cmsghdr *cmsg;
227         struct can_filter *rfilter;
228         can_err_mask_t err_mask;
229         struct canfd_frame frame;
230         int nbytes, i, maxdlen;
231         struct ifreq ifr;
232         struct timeval tv, last_tv;
233         struct timeval timeout, timeout_config = { 0, 0 }, *timeout_current = NULL;
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:heT:?")) != -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                 case 'T':
359                         errno = 0;
360                         timeout_config.tv_usec = strtol(optarg, NULL, 0);
361                         if (errno != 0) {
362                                 print_usage(basename(argv[0]));
363                                 exit(1);
364                         }
365                         timeout_config.tv_sec = timeout_config.tv_usec / 1000;
366                         timeout_config.tv_usec = (timeout_config.tv_usec % 1000) * 1000;
367                         timeout_current = &timeout;
368                         break;
369                 default:
370                         print_usage(basename(argv[0]));
371                         exit(1);
372                         break;
373                 }
374         }
375
376         if (optind == argc) {
377                 print_usage(basename(argv[0]));
378                 exit(0);
379         }
380         
381         if (logfrmt && view) {
382                 fprintf(stderr, "Log file format selected: Please disable ASCII/BINARY/SWAP options!\n");
383                 exit(0);
384         }
385
386         if (silent == SILENT_INI) {
387                 if (log) {
388                         fprintf(stderr, "Disabled standard output while logging.\n");
389                         silent = SILENT_ON; /* disable output on stdout */
390                 } else
391                         silent = SILENT_OFF; /* default output */
392         }
393
394         currmax = argc - optind; /* find real number of CAN devices */
395
396         if (currmax > MAXSOCK) {
397                 fprintf(stderr, "More than %d CAN devices given on commandline!\n", MAXSOCK);
398                 return 1;
399         }
400
401         for (i=0; i < currmax; i++) {
402
403                 ptr = argv[optind+i];
404                 nptr = strchr(ptr, ',');
405
406 #ifdef DEBUG
407                 printf("open %d '%s'.\n", i, ptr);
408 #endif
409
410                 s[i] = socket(PF_CAN, SOCK_RAW, CAN_RAW);
411                 if (s[i] < 0) {
412                         perror("socket");
413                         return 1;
414                 }
415
416                 cmdlinename[i] = ptr; /* save pointer to cmdline name of this socket */
417
418                 if (nptr)
419                         nbytes = nptr - ptr;  /* interface name is up the first ',' */
420                 else
421                         nbytes = strlen(ptr); /* no ',' found => no filter definitions */
422
423                 if (nbytes >= IFNAMSIZ) {
424                         fprintf(stderr, "name of CAN device '%s' is too long!\n", ptr);
425                         return 1;
426                 }
427
428                 if (nbytes > max_devname_len)
429                         max_devname_len = nbytes; /* for nice printing */
430
431                 addr.can_family = AF_CAN;
432
433                 memset(&ifr.ifr_name, 0, sizeof(ifr.ifr_name));
434                 strncpy(ifr.ifr_name, ptr, nbytes);
435
436 #ifdef DEBUG
437                 printf("using interface name '%s'.\n", ifr.ifr_name);
438 #endif
439
440                 if (strcmp(ANYDEV, ifr.ifr_name)) {
441                         if (ioctl(s[i], SIOCGIFINDEX, &ifr) < 0) {
442                                 perror("SIOCGIFINDEX");
443                                 exit(1);
444                         }
445                         addr.can_ifindex = ifr.ifr_ifindex;
446                 } else
447                         addr.can_ifindex = 0; /* any can interface */
448
449                 if (nptr) {
450
451                         /* found a ',' after the interface name => check for filters */
452
453                         /* determine number of filters to alloc the filter space */
454                         numfilter = 0;
455                         ptr = nptr;
456                         while (ptr) {
457                                 numfilter++;
458                                 ptr++; /* hop behind the ',' */
459                                 ptr = strchr(ptr, ','); /* exit condition */
460                         }
461
462                         rfilter = malloc(sizeof(struct can_filter) * numfilter);
463                         if (!rfilter) {
464                                 fprintf(stderr, "Failed to create filter space!\n");
465                                 return 1;
466                         }
467
468                         numfilter = 0;
469                         err_mask = 0;
470
471                         while (nptr) {
472
473                                 ptr = nptr+1; /* hop behind the ',' */
474                                 nptr = strchr(ptr, ','); /* update exit condition */
475
476                                 if (sscanf(ptr, "%x:%x",
477                                            &rfilter[numfilter].can_id, 
478                                            &rfilter[numfilter].can_mask) == 2) {
479                                         rfilter[numfilter].can_mask &= ~CAN_ERR_FLAG;
480                                         numfilter++;
481                                 } else if (sscanf(ptr, "%x~%x",
482                                                   &rfilter[numfilter].can_id, 
483                                                   &rfilter[numfilter].can_mask) == 2) {
484                                         rfilter[numfilter].can_id |= CAN_INV_FILTER;
485                                         rfilter[numfilter].can_mask &= ~CAN_ERR_FLAG;
486                                         numfilter++;
487                                 } else if (sscanf(ptr, "#%x", &err_mask) != 1) { 
488                                         fprintf(stderr, "Error in filter option parsing: '%s'\n", ptr);
489                                         return 1;
490                                 }
491                         }
492
493                         if (err_mask)
494                                 setsockopt(s[i], SOL_CAN_RAW, CAN_RAW_ERR_FILTER,
495                                            &err_mask, sizeof(err_mask));
496
497                         if (numfilter)
498                                 setsockopt(s[i], SOL_CAN_RAW, CAN_RAW_FILTER,
499                                            rfilter, numfilter * sizeof(struct can_filter));
500
501                         free(rfilter);
502
503                 } /* if (nptr) */
504
505                 /* try to switch the socket into CAN FD mode */
506                 setsockopt(s[i], SOL_CAN_RAW, CAN_RAW_FD_FRAMES, &canfd_on, sizeof(canfd_on));
507
508                 if (rcvbuf_size) {
509
510                         int curr_rcvbuf_size;
511                         socklen_t curr_rcvbuf_size_len = sizeof(curr_rcvbuf_size);
512
513                         /* try SO_RCVBUFFORCE first, if we run with CAP_NET_ADMIN */
514                         if (setsockopt(s[i], SOL_SOCKET, SO_RCVBUFFORCE,
515                                        &rcvbuf_size, sizeof(rcvbuf_size)) < 0) {
516 #ifdef DEBUG
517                                 printf("SO_RCVBUFFORCE failed so try SO_RCVBUF ...\n");
518 #endif
519                                 if (setsockopt(s[i], SOL_SOCKET, SO_RCVBUF,
520                                                &rcvbuf_size, sizeof(rcvbuf_size)) < 0) {
521                                         perror("setsockopt SO_RCVBUF");
522                                         return 1;
523                                 }
524
525                                 if (getsockopt(s[i], SOL_SOCKET, SO_RCVBUF,
526                                                &curr_rcvbuf_size, &curr_rcvbuf_size_len) < 0) {
527                                         perror("getsockopt SO_RCVBUF");
528                                         return 1;
529                                 }
530
531                                 /* Only print a warning the first time we detect the adjustment */
532                                 /* n.b.: The wanted size is doubled in Linux in net/sore/sock.c */
533                                 if (!i && curr_rcvbuf_size < rcvbuf_size*2)
534                                         fprintf(stderr, "The socket receive buffer size was "
535                                                 "adjusted due to /proc/sys/net/core/rmem_max.\n");
536                         }
537                 }
538
539                 if (timestamp || log || logfrmt) {
540
541                         const int timestamp_on = 1;
542
543                         if (setsockopt(s[i], SOL_SOCKET, SO_TIMESTAMP,
544                                        &timestamp_on, sizeof(timestamp_on)) < 0) {
545                                 perror("setsockopt SO_TIMESTAMP");
546                                 return 1;
547                         }
548                 }
549
550                 if (dropmonitor) {
551
552                         const int dropmonitor_on = 1;
553
554                         if (setsockopt(s[i], SOL_SOCKET, SO_RXQ_OVFL,
555                                        &dropmonitor_on, sizeof(dropmonitor_on)) < 0) {
556                                 perror("setsockopt SO_RXQ_OVFL not supported by your Linux Kernel");
557                                 return 1;
558                         }
559                 }
560
561                 if (bind(s[i], (struct sockaddr *)&addr, sizeof(addr)) < 0) {
562                         perror("bind");
563                         return 1;
564                 }
565         }
566
567         if (log) {
568                 time_t currtime;
569                 struct tm now;
570                 char fname[sizeof("candump-2006-11-20_202026.log")+1];
571
572                 if (time(&currtime) == (time_t)-1) {
573                         perror("time");
574                         return 1;
575                 }
576
577                 localtime_r(&currtime, &now);
578
579                 sprintf(fname, "candump-%04d-%02d-%02d_%02d%02d%02d.log",
580                         now.tm_year + 1900,
581                         now.tm_mon + 1,
582                         now.tm_mday,
583                         now.tm_hour,
584                         now.tm_min,
585                         now.tm_sec);
586
587                 if (silent != SILENT_ON)
588                         printf("\nWarning: console output active while logging!");
589
590                 fprintf(stderr, "\nEnabling Logfile '%s'\n\n", fname);
591
592                 logfile = fopen(fname, "w");
593                 if (!logfile) {
594                         perror("logfile");
595                         return 1;
596                 }
597         }
598
599         /* these settings are static and can be held out of the hot path */
600         iov.iov_base = &frame;
601         msg.msg_name = &addr;
602         msg.msg_iov = &iov;
603         msg.msg_iovlen = 1;
604         msg.msg_control = &ctrlmsg;
605
606         while (running) {
607
608                 FD_ZERO(&rdfs);
609                 for (i=0; i<currmax; i++)
610                         FD_SET(s[i], &rdfs);
611
612                 if (timeout_current)
613                         *timeout_current = timeout_config;
614
615                 if ((ret = select(s[currmax-1]+1, &rdfs, NULL, NULL, timeout_current)) <= 0) {
616                         //perror("select");
617                         running = 0;
618                         continue;
619                 }
620
621                 for (i=0; i<currmax; i++) {  /* check all CAN RAW sockets */
622
623                         if (FD_ISSET(s[i], &rdfs)) {
624
625                                 int idx;
626
627                                 /* these settings may be modified by recvmsg() */
628                                 iov.iov_len = sizeof(frame);
629                                 msg.msg_namelen = sizeof(addr);
630                                 msg.msg_controllen = sizeof(ctrlmsg);  
631                                 msg.msg_flags = 0;
632
633                                 nbytes = recvmsg(s[i], &msg, 0);
634                                 if (nbytes < 0) {
635                                         perror("read");
636                                         return 1;
637                                 }
638
639                                 if ((size_t)nbytes == CAN_MTU)
640                                         maxdlen = CAN_MAX_DLEN;
641                                 else if ((size_t)nbytes == CANFD_MTU)
642                                         maxdlen = CANFD_MAX_DLEN;
643                                 else {
644                                         fprintf(stderr, "read: incomplete CAN frame\n");
645                                         return 1;
646                                 }
647
648                                 if (count && (--count == 0))
649                                         running = 0;
650
651                                 if (bridge) {
652                                         if (bridge_delay)
653                                                 usleep(bridge_delay);
654
655                                         nbytes = write(bridge, &frame, nbytes);
656                                         if (nbytes < 0) {
657                                                 perror("bridge write");
658                                                 return 1;
659                                         } else if ((size_t)nbytes != CAN_MTU && (size_t)nbytes != CANFD_MTU) {
660                                                 fprintf(stderr,"bridge write: incomplete CAN frame\n");
661                                                 return 1;
662                                         }
663                                 }
664                     
665                                 for (cmsg = CMSG_FIRSTHDR(&msg);
666                                      cmsg && (cmsg->cmsg_level == SOL_SOCKET);
667                                      cmsg = CMSG_NXTHDR(&msg,cmsg)) {
668                                         if (cmsg->cmsg_type == SO_TIMESTAMP)
669                                                 tv = *(struct timeval *)CMSG_DATA(cmsg);
670                                         else if (cmsg->cmsg_type == SO_RXQ_OVFL)
671                                                 dropcnt[i] = *(__u32 *)CMSG_DATA(cmsg);
672                                 }
673
674                                 /* check for (unlikely) dropped frames on this specific socket */
675                                 if (dropcnt[i] != last_dropcnt[i]) {
676
677                                         __u32 frames;
678
679                                         if (dropcnt[i] > last_dropcnt[i])
680                                                 frames = dropcnt[i] - last_dropcnt[i];
681                                         else
682                                                 frames = UINT32_MAX - last_dropcnt[i] + dropcnt[i];
683
684                                         if (silent != SILENT_ON)
685                                                 printf("DROPCOUNT: dropped %d CAN frame%s on '%s' socket (total drops %d)\n",
686                                                        frames, (frames > 1)?"s":"", cmdlinename[i], dropcnt[i]);
687
688                                         if (log)
689                                                 fprintf(logfile, "DROPCOUNT: dropped %d CAN frame%s on '%s' socket (total drops %d)\n",
690                                                         frames, (frames > 1)?"s":"", cmdlinename[i], dropcnt[i]);
691
692                                         last_dropcnt[i] = dropcnt[i];
693                                 }
694
695                                 idx = idx2dindex(addr.can_ifindex, s[i]);
696
697                                 /* once we detected a EFF frame indent SFF frames accordingly */
698                                 if (frame.can_id & CAN_EFF_FLAG)
699                                         view |= CANLIB_VIEW_INDENT_SFF;
700
701                                 if (log) {
702                                         char buf[CL_CFSZ]; /* max length */
703
704                                         /* log CAN frame with absolute timestamp & device */
705                                         sprint_canframe(buf, &frame, 0, maxdlen);
706                                         fprintf(logfile, "(%010ld.%06ld) %*s %s\n",
707                                                 tv.tv_sec, tv.tv_usec,
708                                                 max_devname_len, devname[idx], buf);
709                                 }
710
711                                 if (logfrmt) {
712                                         char buf[CL_CFSZ]; /* max length */
713
714                                         /* print CAN frame in log file style to stdout */
715                                         sprint_canframe(buf, &frame, 0, maxdlen);
716                                         printf("(%010ld.%06ld) %*s %s\n",
717                                                tv.tv_sec, tv.tv_usec,
718                                                max_devname_len, devname[idx], buf);
719                                         goto out_fflush; /* no other output to stdout */
720                                 }
721
722                                 if (silent != SILENT_OFF){
723                                         if (silent == SILENT_ANI) {
724                                                 printf("%c\b", anichar[silentani%=MAXANI]);
725                                                 silentani++;
726                                         }
727                                         goto out_fflush; /* no other output to stdout */
728                                 }
729                       
730                                 printf(" %s", (color>2)?col_on[idx%MAXCOL]:"");
731
732                                 switch (timestamp) {
733
734                                 case 'a': /* absolute with timestamp */
735                                         printf("(%010ld.%06ld) ", tv.tv_sec, tv.tv_usec);
736                                         break;
737
738                                 case 'A': /* absolute with date */
739                                 {
740                                         struct tm tm;
741                                         char timestring[25];
742
743                                         tm = *localtime(&tv.tv_sec);
744                                         strftime(timestring, 24, "%Y-%m-%d %H:%M:%S", &tm);
745                                         printf("(%s.%06ld) ", timestring, tv.tv_usec);
746                                 }
747                                 break;
748
749                                 case 'd': /* delta */
750                                 case 'z': /* starting with zero */
751                                 {
752                                         struct timeval diff;
753
754                                         if (last_tv.tv_sec == 0)   /* first init */
755                                                 last_tv = tv;
756                                         diff.tv_sec  = tv.tv_sec  - last_tv.tv_sec;
757                                         diff.tv_usec = tv.tv_usec - last_tv.tv_usec;
758                                         if (diff.tv_usec < 0)
759                                                 diff.tv_sec--, diff.tv_usec += 1000000;
760                                         if (diff.tv_sec < 0)
761                                                 diff.tv_sec = diff.tv_usec = 0;
762                                         printf("(%03ld.%06ld) ", diff.tv_sec, diff.tv_usec);
763                                 
764                                         if (timestamp == 'd')
765                                                 last_tv = tv; /* update for delta calculation */
766                                 }
767                                 break;
768
769                                 default: /* no timestamp output */
770                                         break;
771                                 }
772
773                                 printf(" %s", (color && (color<3))?col_on[idx%MAXCOL]:"");
774                                 printf("%*s", max_devname_len, devname[idx]);
775
776                                 if (extra_msg_info) {
777
778                                         if (msg.msg_flags & MSG_DONTROUTE)
779                                                 printf ("  TX %s", extra_m_info[frame.flags & 3]);
780                                         else
781                                                 printf ("  RX %s", extra_m_info[frame.flags & 3]);
782                                 }
783
784                                 printf("%s  ", (color==1)?col_off:"");
785
786                                 fprint_long_canframe(stdout, &frame, NULL, view, maxdlen);
787
788                                 printf("%s", (color>1)?col_off:"");
789                                 printf("\n");
790                         }
791
792                 out_fflush:
793                         fflush(stdout);
794                 }
795         }
796
797         for (i=0; i<currmax; i++)
798                 close(s[i]);
799
800         if (bridge)
801                 close(bridge);
802
803         if (log)
804                 fclose(logfile);
805
806         return 0;
807 }