]> rtime.felk.cvut.cz Git - socketcan-devel.git/blob - can-utils/cansniffer.c
Renamed can-sniffer to cansniffer.
[socketcan-devel.git] / can-utils / cansniffer.c
1 /*
2  *  $Id$
3  */
4
5 /*
6  * can-sniffer.c
7  *
8  * Copyright (c) 2002-2005 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, the following disclaimer and
16  *    the referenced file 'COPYING'.
17  * 2. Redistributions in binary form must reproduce the above copyright
18  *    notice, this list of conditions and the following disclaimer in the
19  *    documentation and/or other materials provided with the distribution.
20  * 3. Neither the name of Volkswagen nor the names of its contributors
21  *    may be used to endorse or promote products derived from this software
22  *    without specific prior written permission.
23  *
24  * Alternatively, provided that this notice is retained in full, this
25  * software may be distributed under the terms of the GNU General
26  * Public License ("GPL") version 2 as distributed in the 'COPYING'
27  * file from the main directory of the linux kernel source.
28  *
29  * The provided data structures and external interfaces from this code
30  * are not restricted to be used by modules with a GPL compatible license.
31  *
32  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
33  * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
34  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
35  * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
36  * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
37  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
38  * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
39  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
40  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
41  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
42  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
43  * DAMAGE.
44  *
45  * Send feedback to <socketcan-users@lists.berlios.de>
46  *
47  */
48
49 #include <stdio.h>
50 #include <stdlib.h>
51 #include <unistd.h>
52 #include <string.h>
53 #include <fcntl.h>
54 #include <signal.h>
55 #include <ctype.h>
56 #include <libgen.h>
57 #include <time.h>
58
59 #include <sys/time.h>
60 #include <sys/types.h>
61 #include <sys/stat.h>
62 #include <sys/socket.h>
63 #include <sys/ioctl.h>
64 #include <sys/uio.h>
65 #include <net/if.h>
66
67 #include <linux/can.h>
68 #include <linux/can/bcm.h>
69
70 #include "terminal.h"
71
72 #define U64_DATA(p) (*(unsigned long long*)(p)->data)
73
74 #define SETFNAME "sniffset."
75
76 /* flags */
77
78 #define ENABLE  1 /* by filter or user */
79 #define DISPLAY 2 /* is on the screen */
80 #define UPDATE  4 /* needs to be printed on the screen */
81 #define CLRSCR  8 /* clear screen in next loop */
82
83 /* flags testing & setting */
84
85 #define is_set(id, flag) (sniftab[id].flags & flag)
86 #define is_clr(id, flag) (!(sniftab[id].flags & flag))
87
88 #define do_set(id, flag) (sniftab[id].flags |= flag)
89 #define do_clr(id, flag) (sniftab[id].flags &= ~flag)
90
91 /* time defaults */
92
93 #define TIMEOUT 50 /* in 100ms */
94 #define HOLD    10 /* in 100ms */
95 #define LOOP     2 /* in 100ms */
96
97 #define MAXANI 8
98 const char anichar[MAXANI] = {'|', '/', '-', '\\', '|', '/', '-', '\\'};
99
100 #define ATTCOLOR ATTBOLD FGRED
101
102 #define STARTLINESTR "X  time    ID  data ... "
103
104 struct snif {
105     int flags;
106     long hold;
107     long timeout;
108     struct timeval laststamp;
109     struct timeval currstamp;
110     struct can_frame last;
111     struct can_frame current;
112     struct can_frame marker;
113     struct can_frame notch;
114 } sniftab[2048];
115
116
117 extern int optind, opterr, optopt;
118
119 static int running = 1;
120 static int clearscreen = 1;
121 static int notch = 0;
122 static long timeout = TIMEOUT;
123 static long hold = HOLD;
124 static long loop = LOOP;
125 static unsigned char binary = 0;
126 static unsigned char color  = 0;
127
128 void rx_setup (int fd, int id);
129 void rx_delete (int fd, int id);
130 void print_snifline(int id);
131 int handle_keyb(int fd);
132 int handle_bcm(int fd, long currcms);
133 int handle_timeo(int fd, long currcms);
134 void writesettings(char* name);
135 void readsettings(char* name, int sockfd);
136
137 void print_usage(char *prg)
138 {
139     const char manual [] = {
140         "commands that can be entered at runtime:\n"
141         "\n"
142         "q<ENTER>       - quit\n"
143         "b<ENTER>       - toggle binary / HEX-ASCII output\n"
144         "c<ENTER>       - toggle color mode\n"
145         "#<ENTER>       - notch currently marked/changed bits (can be used repeatedly)\n"
146         "*<ENTER>       - clear notched marked\n"
147         "rMYNAME<ENTER> - read settings file (filter/notch)\n"
148         "wMYNAME<ENTER> - write settings file (filter/notch)\n"
149         "+FILTER<ENTER> - add CAN-IDs to sniff\n"
150         "-FILTER<ENTER> - remove CAN-IDs to sniff\n"
151         "\n"
152         "FILTER can be a single CAN-ID or a CAN-ID/Bitmask:\n"
153         "+1F5<ENTER>    - add CAN-ID 0x1F5\n"
154         "-42E<ENTER>    - remove CAN-ID 0x42E\n"
155         "-42E7FF<ENTER> - remove CAN-ID 0x42E (using Bitmask)\n"
156         "-500700<ENTER> - remove CAN-IDs 0x500 - 0x5FF\n"
157         "+400600<ENTER> - add CAN-IDs 0x400 - 0x5FF\n"
158         "+000000<ENTER> - add all CAN-IDs\n"
159         "-000000<ENTER> - remove all CAN-IDs\n"
160         "\n"
161         "if (id & filter) == (sniff-id & filter) the action (+/-) is performed,\n"
162         "which is quite easy when the filter is 000\n"
163         "\n"
164     };
165
166     fprintf(stderr, "\nUsage: %s [can-interface]\n", prg);
167     fprintf(stderr, "Options: -m <mask>  (initial FILTER default 0x00000000)\n");
168     fprintf(stderr, "         -v <value> (initial FILTER default 0x00000000)\n");
169     fprintf(stderr, "         -q         (quiet - all IDs deactivated)\n");
170     fprintf(stderr, "         -r <name>  (read %sname from file)\n", SETFNAME);
171     fprintf(stderr, "         -b         (start with binary mode)\n");
172     fprintf(stderr, "         -c         (color changes)\n");
173     fprintf(stderr, "         -t <time>  (timeout for ID display [x100ms] default: %d)\n", TIMEOUT);
174     fprintf(stderr, "         -h <time>  (hold marker on changes [x100ms] default: %d)\n", HOLD);
175     fprintf(stderr, "         -l <time>  (loop time (display) [x100ms] default: %d)\n", LOOP);
176     fprintf(stderr, "\n");
177     fprintf(stderr, "%s", manual);
178 }
179
180 void sigterm(int signo)
181 {
182     running = 0;
183 }
184
185 int main(int argc, char **argv)
186 {
187     fd_set rdfs;
188     int s;
189     canid_t mask = 0;
190     canid_t value = 0;
191     long currcms = 0;
192     long lastcms = 0;
193     unsigned char quiet = 0;
194
195     int opt, ret;
196     struct timeval timeo, start_tv, tv;
197     struct sockaddr_can addr;
198     struct ifreq ifr;
199     int i;
200
201
202     signal(SIGTERM, sigterm);
203     signal(SIGHUP, sigterm);
204     signal(SIGINT, sigterm);
205
206     for (i=0; i < 2048 ;i++) /* default: check all CAN-IDs */
207         do_set(i, ENABLE);
208
209     while ((opt = getopt(argc, argv, "m:v:r:t:h:l:qbc")) != -1) {
210         switch (opt) {
211         case 'm':
212             sscanf(optarg, "%x", &mask);
213             break;
214
215         case 'v':
216             sscanf(optarg, "%x", &value);
217             break;
218
219         case 'r':
220             readsettings(optarg, 0); /* no BCM-setting here */
221             break;
222
223         case 't':
224             sscanf(optarg, "%ld", &timeout);
225             break;
226
227         case 'h':
228             sscanf(optarg, "%ld", &hold);
229             break;
230
231         case 'l':
232             sscanf(optarg, "%ld", &loop);
233             break;
234
235         case 'q':
236             quiet = 1;
237             break;
238
239         case 'b':
240             binary = 1;
241             break;
242
243         case 'c':
244             color = 1;
245             break;
246
247         case '?':
248             break;
249
250         default:
251             fprintf(stderr, "Unknown option %c\n", opt);
252             break;
253         }
254     }
255
256     if (optind == argc) {
257         print_usage(basename(argv[0]));
258         exit(0);
259     }
260         
261     if (mask || value) {
262         for (i=0; i < 2048 ;i++) {
263             if ((i & mask) ==  (value & mask))
264                 do_set(i, ENABLE);
265             else
266                 do_clr(i, ENABLE);
267         }
268     }
269
270     if (quiet)
271         for (i=0; i < 2048 ;i++)
272             do_clr(i, ENABLE);
273
274     if (strlen(argv[optind]) >= IFNAMSIZ) {
275         printf("name of CAN device '%s' is too long!\n", argv[optind]);
276         return 1;
277     }
278
279     if ((s = socket(PF_CAN, SOCK_DGRAM, CAN_BCM)) < 0) {
280         perror("socket");
281         return 1;
282     }
283
284     addr.can_family = AF_CAN;
285     strcpy(ifr.ifr_name, argv[optind]);
286     ioctl(s, SIOCGIFINDEX, &ifr);
287     addr.can_ifindex = ifr.ifr_ifindex;
288
289     if (connect(s, (struct sockaddr *)&addr, sizeof(addr)) < 0) {
290         perror("bind");
291         return 1;
292     }
293
294     for (i=0; i < 2048 ;i++) /* initial BCM setup */
295         if (is_set(i, ENABLE))
296             rx_setup(s, i);
297
298     gettimeofday(&start_tv, NULL);
299     tv.tv_sec = tv.tv_usec = 0;
300
301     printf("%s", CSR_HIDE); /* hide cursor */
302
303     while (running) {
304
305         FD_ZERO(&rdfs);
306         FD_SET(0, &rdfs);
307         FD_SET(s, &rdfs);
308
309         timeo.tv_sec  = 0;
310         timeo.tv_usec = 100000 * loop;
311
312         if ((ret = select(s+1, &rdfs, NULL, NULL, &timeo)) < 0) {
313             //perror("select");
314             running = 0;
315             continue;
316         }
317
318         gettimeofday(&tv, NULL);
319         currcms = (tv.tv_sec - start_tv.tv_sec) * 10 + (tv.tv_usec / 100000);
320
321         if (FD_ISSET(0, &rdfs))
322             running &= handle_keyb(s);
323
324         if (FD_ISSET(s, &rdfs))
325             running &= handle_bcm(s, currcms);
326
327         if (currcms - lastcms >= loop) {
328                 running &= handle_timeo(s, currcms);
329                 lastcms = currcms;
330         }
331     }
332
333     printf("%s", CSR_SHOW); /* show cursor */
334
335     close(s);
336     return 0;
337 }
338
339 void rx_setup (int fd, int id){
340
341     struct {
342         struct bcm_msg_head msg_head;
343         struct can_frame frame;
344     } txmsg;
345
346     txmsg.msg_head.opcode  = RX_SETUP;
347     txmsg.msg_head.can_id  = id;
348     txmsg.msg_head.flags   = RX_CHECK_DLC;
349     txmsg.msg_head.ival1.tv_sec  = 0;
350     txmsg.msg_head.ival1.tv_usec = 0;
351     txmsg.msg_head.ival2.tv_sec  = 0;
352     txmsg.msg_head.ival2.tv_usec = 0;
353     txmsg.msg_head.nframes = 1;
354     U64_DATA(&txmsg.frame) = (__u64) 0xFFFFFFFFFFFFFFFFULL;
355
356     if (write(fd, &txmsg, sizeof(txmsg)) < 0)
357       perror("write");
358 };
359
360 void rx_delete (int fd, int id){
361
362     struct bcm_msg_head msg_head;
363
364     msg_head.opcode  = RX_DELETE;
365     msg_head.can_id  = id;
366     msg_head.nframes = 0;
367
368     if (write(fd, &msg_head, sizeof(msg_head)) < 0)
369       perror("write");
370 }
371
372 int handle_keyb(int fd){
373
374     char cmd [20] = {0};
375     int i;
376     unsigned int mask;
377     unsigned int value;
378
379     if (read(0, cmd, 19) > strlen("+123456\n"))
380         return 1; /* ignore */
381
382     if (strlen(cmd) > 0)
383         cmd[strlen(cmd)-1] = 0; /* chop off trailing newline */
384
385     switch (cmd[0]) {
386
387     case '+':
388     case '-':
389         sscanf(&cmd[1], "%x", &value);
390         if (strlen(&cmd[1]) > 3) {
391             mask = value & 0xFFF;
392             value >>= 12;
393         }
394         else
395             mask = 0x7FF;
396
397         if (cmd[0] == '+') {
398             for (i=0; i < 2048 ;i++) {
399                 if (((i & mask) == (value & mask)) && (is_clr(i, ENABLE))) {
400                     do_set(i, ENABLE);
401                     rx_setup(fd, i);
402                 }
403             }
404         }
405         else { /* '-' */
406             for (i=0; i < 2048 ;i++) {
407                 if (((i & mask) == (value & mask)) && (is_set(i, ENABLE))) {
408                     do_clr(i, ENABLE);
409                     rx_delete(fd, i);
410                 }
411             }
412         }
413         break;
414
415     case 'w' :
416         writesettings(&cmd[1]);
417         break;
418
419     case 'r' :
420         readsettings(&cmd[1], fd);
421         break;
422
423     case 'q' :
424         running = 0;
425         break;
426
427     case 'b' :
428         if (binary)
429             binary = 0;
430         else
431             binary = 1;
432
433         break;
434
435     case 'c' :
436         if (color)
437             color = 0;
438         else
439             color = 1;
440
441         break;
442
443     case '#' :
444         notch = 1;
445         break;
446
447     case '*' :
448         for (i=0; i < 2048; i++)
449             U64_DATA(&sniftab[i].notch) = (__u64) 0;
450         break;
451
452     default:
453         break;
454     }
455
456     clearscreen = 1;
457
458     return 1; /* ok */
459 };
460
461 int handle_bcm(int fd, long currcms){
462
463     int nbytes, id;
464
465     struct {
466         struct bcm_msg_head msg_head;
467         struct can_frame frame;
468     } bmsg;
469
470     if ((nbytes = read(fd, &bmsg, sizeof(bmsg))) < 0) {
471         perror("bcm read");
472         return 0; /* quit */
473     }
474
475     id = bmsg.msg_head.can_id;
476     ioctl(fd, SIOCGSTAMP, &sniftab[id].currstamp);
477
478     if (bmsg.msg_head.opcode != RX_CHANGED) {
479         printf("received strange BCM opcode %d!\n", bmsg.msg_head.opcode);
480         return 0; /* quit */
481     }
482
483     if (nbytes != sizeof(bmsg)) {
484         printf("received strange BCM data length %d!\n", nbytes);
485         return 0; /* quit */
486     }
487
488     sniftab[id].current = bmsg.frame;
489     U64_DATA(&sniftab[id].marker) |= 
490         U64_DATA(&sniftab[id].current) ^ U64_DATA(&sniftab[id].last);
491     sniftab[id].timeout = currcms + timeout;
492
493     if (is_clr(id, DISPLAY))
494         clearscreen = 1; /* new entry -> new drawing */
495
496     do_set(id, DISPLAY);
497     do_set(id, UPDATE);
498         
499     return 1; /* ok */
500 };
501
502 int handle_timeo(int fd, long currcms){
503
504     int i;
505     int force_redraw = 0;
506
507     if (clearscreen) {
508         char startline[80];
509         printf("%s%s", CLR_SCREEN, CSR_HOME);
510         snprintf(startline, 79, "< can-sniffer parameters: l=%ld h=%ld t=%ld >", loop, hold, timeout);
511         printf("%s%*s",STARTLINESTR, 79-strlen(STARTLINESTR), startline); 
512         force_redraw = 1;
513         clearscreen = 0;
514     }
515
516     if (notch) {
517         for (i=0; i < 2048; i++)
518             U64_DATA(&sniftab[i].notch) |= U64_DATA(&sniftab[i].marker);
519         notch = 0;
520     }
521
522     printf("%s", CSR_HOME);
523     printf("%c\n", anichar[currcms % MAXANI]); /* funny animation */
524
525     for (i=0; i < 2048; i++) {
526
527         if is_set(i, ENABLE) {
528
529             if is_set(i, DISPLAY) {
530
531                 if (is_set(i, UPDATE) || (force_redraw)){
532                     print_snifline(i);
533                     sniftab[i].hold = currcms + hold;
534                     do_clr(i, UPDATE);
535                 }
536                 else
537                     if ((sniftab[i].hold) && (sniftab[i].hold < currcms)) {
538                         U64_DATA(&sniftab[i].marker) = (__u64) 0;
539                         print_snifline(i);
540                         sniftab[i].hold = 0; /* disable update by hold */
541                     }
542                     else
543                         printf("%s", CSR_DOWN); /* skip my line */
544
545                 if (sniftab[i].timeout < currcms) {
546                     do_clr(i, DISPLAY);
547                     do_clr(i, UPDATE);
548                     clearscreen = 1; /* removed entry -> new drawing next time */
549                 }
550             }
551             sniftab[i].last      = sniftab[i].current;
552             sniftab[i].laststamp = sniftab[i].currstamp;
553         }
554     }
555
556     return 1; /* ok */
557
558 };
559
560 void print_snifline(int id){
561
562     long diffsec  = sniftab[id].currstamp.tv_sec  - sniftab[id].laststamp.tv_sec;
563     long diffusec = sniftab[id].currstamp.tv_usec - sniftab[id].laststamp.tv_usec;
564     int i,j;
565
566     if (diffusec < 0)
567         diffsec--, diffusec += 1000000;
568
569     if (diffsec < 0)
570         diffsec = diffusec = 0;
571
572     if (diffsec > 10)
573         diffsec = 9, diffusec = 999999;
574
575     printf("%ld.%06ld  %3x  ", diffsec, diffusec, id);
576
577     if (binary) {
578
579         for (i=0; i<sniftab[id].current.can_dlc; i++)
580             for (j=7; j>=0; j--)
581                 if ((color) && (sniftab[id].marker.data[i] & 1<<j) &&
582                     (!(sniftab[id].notch.data[i] & 1<<j)))
583                     if (sniftab[id].current.data[i] & 1<<j)
584                         printf("%s1%s", ATTCOLOR, ATTRESET);
585                     else
586                         printf("%s0%s", ATTCOLOR, ATTRESET);
587                 else
588                     if (sniftab[id].current.data[i] & 1<<j)
589                         putchar('1');
590                     else
591                         putchar('0');
592     }
593     else {
594
595         for (i=0; i<sniftab[id].current.can_dlc; i++)
596             if ((color) && (sniftab[id].marker.data[i]) && (!(sniftab[id].notch.data[i])))
597                 printf("%s%02X%s ", ATTCOLOR, sniftab[id].current.data[i], ATTRESET);
598             else
599                 printf("%02X ", sniftab[id].current.data[i]);
600
601         if (sniftab[id].current.can_dlc < 8)
602             printf("%*s", (8 - sniftab[id].current.can_dlc) * 3, "");
603
604         for (i=0; i<sniftab[id].current.can_dlc; i++)
605             if ((sniftab[id].current.data[i] > 0x1F) && 
606                 (sniftab[id].current.data[i] < 0x7F))
607                 if ((color) && (sniftab[id].marker.data[i]) && (!(sniftab[id].notch.data[i])))
608                     printf("%s%c%s", ATTCOLOR, sniftab[id].current.data[i], ATTRESET);
609                 else
610                     putchar(sniftab[id].current.data[i]);
611             else
612                 putchar('.');
613     }
614
615     putchar('\n');
616
617     U64_DATA(&sniftab[id].marker) = (__u64) 0;
618
619 };
620
621
622 void writesettings(char* name){
623
624     int fd;
625     char fname[30] = SETFNAME;
626     int i,j;
627     char buf[8]= {0};
628
629     strncat(fname, name, 29 - strlen(fname)); 
630     fd = open(fname,  O_WRONLY|O_CREAT, S_IRUSR|S_IWUSR|S_IRGRP|S_IROTH);
631     
632     if (fd > 0) {
633
634         for (i=0; i < 2048 ;i++) {
635             sprintf(buf, "<%03X>%c.", i, (is_set(i, ENABLE))?'1':'0');
636             write(fd, buf, 7);
637             for (j=0; j<8 ; j++){
638                 sprintf(buf, "%02X", sniftab[i].notch.data[j]);
639                 write(fd, buf, 2);
640             }
641             write(fd, "\n", 1);
642             /* 7 + 16 + 1 = 24 bytes per entry */ 
643         }
644         close(fd);
645     }
646     else
647         printf("unable to write setting file '%s'!\n", fname);
648 };
649
650 void readsettings(char* name, int sockfd){
651
652     int fd;
653     char fname[30] = SETFNAME;
654     char buf[25] = {0};
655     int i,j;
656
657     strncat(fname, name, 29 - strlen(fname)); 
658     fd = open(fname, O_RDONLY);
659     
660     if (fd > 0) {
661         if (!sockfd)
662             printf("reading setting file '%s' ... ", fname);
663
664         for (i=0; i < 2048 ;i++) {
665             if (read(fd, &buf, 24) == 24) {
666                 if (buf[5] & 1) {
667                     if (is_clr(i, ENABLE)) {
668                         do_set(i, ENABLE);
669                         if (sockfd)
670                             rx_setup(sockfd, i);
671                     }
672                 }
673                 else
674                     if (is_set(i, ENABLE)) {
675                         do_clr(i, ENABLE);
676                         if (sockfd)
677                             rx_delete(sockfd, i);
678                     }
679                 for (j=7; j>=0 ; j--){
680                     sniftab[i].notch.data[j] =
681                         (__u8) strtoul(&buf[2*j+7], (char **)NULL, 16) & 0xFF;
682                     buf[2*j+7] = 0; /* cut off each time */
683                 }
684             }
685             else {
686                 if (!sockfd)
687                     printf("was only able to read until index %d from setting file '%s'!\n",
688                            i, fname);
689             }
690         }
691     
692         if (!sockfd)
693             printf("done\n");
694
695         close(fd);
696     }
697     else
698         printf("unable to read setting file '%s'!\n", fname);
699 };