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