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