]> rtime.felk.cvut.cz Git - sojka/can-utils.git/blob - cangw.c
Initialize packet counters when printing each routing entry.
[sojka/can-utils.git] / cangw.c
1 /*
2  *  $Id$
3  */
4
5 /*
6  * cangw.c - manage PF_CAN netlink gateway
7  *
8  * Copyright (c) 2010 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 <libgen.h>
51 #include <string.h>
52 #include <unistd.h>
53 #include <errno.h>
54 #include <sys/socket.h>
55 #include <net/if.h>
56 #include <linux/netlink.h>
57 #include <linux/rtnetlink.h>
58 #include <linux/can/gw.h>
59
60 enum {
61         UNSPEC,
62         ADD,
63         DEL,
64         FLUSH,
65         LIST
66 };
67
68 struct modattr {
69         struct can_frame cf;
70         __u8 modtype;
71         __u8 instruction;
72 } __attribute__((packed));
73
74
75 /* some netlink helpers stolen from iproute2 package */
76 #define NLMSG_TAIL(nmsg) \
77         ((struct rtattr *)(((void *) (nmsg)) + NLMSG_ALIGN((nmsg)->nlmsg_len)))
78
79 int addattr_l(struct nlmsghdr *n, int maxlen, int type, const void *data,
80               int alen)
81 {
82         int len = RTA_LENGTH(alen);
83         struct rtattr *rta;
84
85         if (NLMSG_ALIGN(n->nlmsg_len) + RTA_ALIGN(len) > maxlen) {
86                 fprintf(stderr, "addattr_l: message exceeded bound of %d\n",
87                         maxlen);
88                 return -1;
89         }
90         rta = NLMSG_TAIL(n);
91         rta->rta_type = type;
92         rta->rta_len = len;
93         memcpy(RTA_DATA(rta), data, alen);
94         n->nlmsg_len = NLMSG_ALIGN(n->nlmsg_len) + RTA_ALIGN(len);
95         return 0;
96 }
97
98 void printfilter(const void *data)
99 {
100         struct can_filter *filter = (struct can_filter *)data;
101
102         printf("-f %03X:%X ", filter->can_id, filter->can_mask);
103 }
104
105 void printmod(const char *type, const void *data)
106 {
107         struct modattr mod;
108         int i;
109
110         memcpy (&mod, data, CGW_MODATTR_LEN);
111
112         printf("-m %s:", type);
113
114         if (mod.modtype & CGW_MOD_ID)
115                 printf("I");
116
117         if (mod.modtype & CGW_MOD_DLC)
118                 printf("L");
119
120         if (mod.modtype & CGW_MOD_DATA)
121                 printf("D");
122
123         printf(":%03X.%X.", mod.cf.can_id, mod.cf.can_dlc);
124
125         for (i = 0; i < 8; i++)
126                 printf("%02X", mod.cf.data[i]);
127
128         printf(" ");
129 }
130
131
132 void print_usage(char *prg)
133 {
134         fprintf(stderr, "\nUsage: %s [options]\n\n", prg);
135         fprintf(stderr, "Commands:  -A (add a new rule)\n");
136         fprintf(stderr, "           -D (delete a rule)\n");
137         fprintf(stderr, "           -F (flush / delete all rules)\n");
138         fprintf(stderr, "           -L (list all rules)\n");
139         fprintf(stderr, "Mandatory: -s <src_dev>  (source netdevice)\n");
140         fprintf(stderr, "           -d <dst_dev>  (destination netdevice)\n");
141         fprintf(stderr, "Options:   -t (preserve src_dev rx timestamp)\n");
142         fprintf(stderr, "           -e (echo sent frames - recommended on vcanx)\n");
143         fprintf(stderr, "           -f <filter> (set CAN filter)\n");
144         fprintf(stderr, "           -m <mod> (set frame modifications)\n");
145         fprintf(stderr, "\nValues are given and expected in hexadecimal values. Leading 0s can be omitted.\n");
146         fprintf(stderr, "\n");
147         fprintf(stderr, "<filter> is a <value>:<mask> CAN identifier filter\n");
148         fprintf(stderr, "\n");
149         fprintf(stderr, "<mod> is a CAN frame modification instruction consisting of\n");
150         fprintf(stderr, "<instruction>:<can_frame-elements>:<can_id>.<can_dlc>.<can_data>\n");
151         fprintf(stderr, " - <instruction> is one of 'AND' 'OR' 'XOR' 'SET'\n");
152         fprintf(stderr, " - <can_frame-elements> is _one_ or _more_ of 'I'dentifier 'L'ength 'D'ata\n");
153         fprintf(stderr, " - <can_id> is an u32 value containing the CAN Identifier\n");
154         fprintf(stderr, " - <can_dlc> is an u8 value containing the data length code (0 .. 8)\n");
155         fprintf(stderr, " - <can_data> is always eight(!) u8 values containing the CAN frames data\n");
156         fprintf(stderr, "The max. four modifications are performed in the order AND -> OR -> XOR -> SET\n");
157         fprintf(stderr, "\n");
158         fprintf(stderr, "Example:\n");
159         fprintf(stderr, "%s -A -s can0 -d vcan3 -e -f 123:C00007FF -m SET:IL:333.4.1122334455667788\n", prg);
160         fprintf(stderr, "\n");
161 }
162
163 int parse_mod(char *optarg, struct modattr *modmsg)
164 {
165         char *ptr, *nptr;
166         int i;
167
168         char hexdata[17] = {0};
169
170         ptr = optarg;
171         nptr = strchr(ptr, ':');
172
173         if ((nptr - ptr > 3) || (nptr - ptr == 0))
174                 return 1;
175
176         if (!strncmp(ptr, "AND", 3))
177                 modmsg->instruction = CGW_MOD_AND;
178         else if (!strncmp(ptr, "OR", 2))
179                 modmsg->instruction = CGW_MOD_OR;
180         else if (!strncmp(ptr, "XOR", 3))
181                 modmsg->instruction = CGW_MOD_XOR;
182         else if (!strncmp(ptr, "SET", 3))
183                 modmsg->instruction = CGW_MOD_SET;
184         else
185                 return 2;
186
187         ptr = nptr+1;
188         nptr = strchr(ptr, ':');
189
190         if ((nptr - ptr > 3) || (nptr - ptr == 0))
191                 return 3;
192
193         modmsg->modtype = 0;
194
195         while (*ptr != ':') {
196
197                 switch (*ptr) {
198
199                 case 'I':
200                         modmsg->modtype |= CGW_MOD_ID;
201                         break;
202
203                 case 'L':
204                         modmsg->modtype |= CGW_MOD_DLC;
205                         break;
206
207                 case 'D':
208                         modmsg->modtype |= CGW_MOD_DATA;
209                         break;
210
211                 default:
212                         return 4;
213                 }
214                 ptr++;
215         }
216
217         if ((sscanf(++ptr, "%lx.%hhd.%16s",
218                     (long unsigned int *)&modmsg->cf.can_id,
219                     (unsigned char *)&modmsg->cf.can_dlc, hexdata) != 3) ||
220             (modmsg->cf.can_dlc > 8))
221                 return 5;
222
223         if (strlen(hexdata) != 16)
224                 return 6;
225
226         for (i = 0; i < 8; i++) {
227                 if (!sscanf(&hexdata[i*2], "%2hhx", &modmsg->cf.data[i]))
228                         return 7;       
229         }
230
231         return 0; /* ok */
232 }
233
234 int main(int argc, char **argv)
235 {
236         int s;
237         int err = 0;
238
239         int opt;
240         extern int optind, opterr, optopt;
241
242         int cmd = UNSPEC;
243         int have_filter = 0;
244
245         struct {
246                 struct nlmsghdr nh;
247                 struct rtcanmsg rtcan;
248                 char buf[200];
249
250         } req;
251
252         char rxbuf[8192]; /* netlink receive buffer */
253         char ifname[IF_NAMESIZE]; /* internface name for if_indextoname() */
254         struct nlmsghdr *nlh;
255         struct nlmsgerr *rte;
256         struct rtcanmsg *rtc;
257         struct rtattr *rta;
258         __u32 handled, dropped;
259         int rtlen;
260         int len;
261
262         struct can_filter filter;
263         struct sockaddr_nl nladdr;
264
265         struct modattr modmsg[CGW_MOD_FUNCS];
266         int modidx = 0;
267         int i;
268
269         memset(&req, 0, sizeof(req));
270
271         while ((opt = getopt(argc, argv, "ADFLs:d:tef:m:?")) != -1) {
272                 switch (opt) {
273
274                 case 'A':
275                         if (cmd == UNSPEC)
276                                 cmd = ADD;
277                         break;
278
279                 case 'D':
280                         if (cmd == UNSPEC)
281                                 cmd = DEL;
282                         break;
283
284                 case 'F':
285                         if (cmd == UNSPEC)
286                                 cmd = FLUSH;
287                         break;
288
289                 case 'L':
290                         if (cmd == UNSPEC)
291                                 cmd = LIST;
292                         break;
293
294                 case 's':
295                         req.rtcan.src_ifindex = if_nametoindex(optarg);
296                         break;
297
298                 case 'd':
299                         req.rtcan.dst_ifindex = if_nametoindex(optarg);
300                         break;
301
302                 case 't':
303                         req.rtcan.can_txflags |= CAN_GW_TXFLAGS_SRC_TSTAMP;
304                         break;
305
306                 case 'e':
307                         req.rtcan.can_txflags |= CAN_GW_TXFLAGS_ECHO;
308                         break;
309
310                 case 'f':
311                         if (sscanf(optarg, "%lx:%lx",
312                                    (long unsigned int *)&filter.can_id, 
313                                    (long unsigned int *)&filter.can_mask) == 2) {
314                                 have_filter = 1;
315                         } else {
316                                 printf("Bad filter definition '%s'.\n", optarg);
317                                 exit(1);
318                         }
319                         break;
320
321                 case 'm':
322                         /* may be triggered by each of the CGW_MOD_FUNCS functions */
323                         if ((modidx < CGW_MOD_FUNCS) && (err = parse_mod(optarg, &modmsg[modidx++]))) {
324                                 printf("Problem %d with modification definition '%s'.\n", err, optarg);
325                                 exit(1);
326                         }
327                         break;
328
329                 case '?':
330                         print_usage(basename(argv[0]));
331                         exit(0);
332                         break;
333
334                 default:
335                         fprintf(stderr, "Unknown option %c\n", opt);
336                         print_usage(basename(argv[0]));
337                         exit(1);
338                         break;
339                 }
340         }
341
342         if ((argc - optind != 0) || (cmd == UNSPEC)) {
343                 print_usage(basename(argv[0]));
344                 exit(1);
345         }
346
347         if ((cmd == ADD || cmd == DEL) &&
348             ((!req.rtcan.src_ifindex) || (!req.rtcan.dst_ifindex))) {
349                 print_usage(basename(argv[0]));
350                 exit(1);
351         }
352
353         s = socket(PF_NETLINK, SOCK_RAW, NETLINK_ROUTE);
354
355         switch (cmd) {
356
357         case ADD:
358                 req.nh.nlmsg_flags = NLM_F_REQUEST | NLM_F_ACK;
359                 req.nh.nlmsg_type  = RTM_NEWROUTE;
360                 break;
361
362         case DEL:
363                 req.nh.nlmsg_flags = NLM_F_REQUEST | NLM_F_ACK;
364                 req.nh.nlmsg_type  = RTM_DELROUTE;
365                 break;
366
367         case FLUSH:
368                 req.nh.nlmsg_flags = NLM_F_REQUEST | NLM_F_ACK;
369                 req.nh.nlmsg_type  = RTM_DELROUTE;
370                 /* if_index set to 0 => remove all entries */
371                 req.rtcan.src_ifindex  = 0;
372                 req.rtcan.dst_ifindex  = 0;
373                 break;
374
375         case LIST:
376                 req.nh.nlmsg_flags = NLM_F_REQUEST | NLM_F_DUMP;
377                 req.nh.nlmsg_type  = RTM_GETROUTE;
378                 break;
379
380         default:
381                 printf("This function is not yet implemented.\n");
382                 exit(1);
383                 break;
384         }
385
386         req.nh.nlmsg_len   = NLMSG_LENGTH(sizeof(struct rtcanmsg));
387         req.nh.nlmsg_seq   = 0;
388
389         req.rtcan.can_family  = AF_CAN;
390
391         /* add new attributes here */
392
393         if (have_filter)
394                 addattr_l(&req.nh, sizeof(req), CGW_FILTER, &filter, sizeof(filter));
395
396         /*
397          * a better example code
398          * modmsg.modtype = CGW_MOD_ID;
399          * addattr_l(&req.n, sizeof(req), CGW_MOD_SET, &modmsg, CGW_MODATTR_LEN);
400          */
401
402         /* add up to CGW_MOD_FUNCS modification definitions */
403         for (i = 0; i < modidx; i++)
404                 addattr_l(&req.nh, sizeof(req), modmsg[i].instruction, &modmsg[i], CGW_MODATTR_LEN);
405
406         memset(&nladdr, 0, sizeof(nladdr));
407         nladdr.nl_family = AF_NETLINK;
408         nladdr.nl_pid    = 0;
409         nladdr.nl_groups = 0;
410
411         err = sendto(s, &req, req.nh.nlmsg_len, 0,
412                      (struct sockaddr*)&nladdr, sizeof(nladdr));
413         if (err < 0) {
414                 perror("netlink sendto");
415                 return err;
416         }
417
418         /* clean netlink receive buffer */
419         bzero(rxbuf, sizeof(rxbuf));
420
421         if (cmd != LIST) {
422
423                 /*
424                  * cmd == ADD || cmd == DEL || cmd == FLUSH
425                  *
426                  * Parse the requested netlink acknowledge return values.
427                  */
428
429                 err = recv(s, &rxbuf, sizeof(rxbuf), 0);
430                 if (err < 0) {
431                         perror("netlink recv");
432                         return err;
433                 }
434                 nlh = (struct nlmsghdr *)rxbuf;
435                 if (nlh->nlmsg_type != NLMSG_ERROR) {
436                         fprintf(stderr, "unexpected netlink answer of type %d\n", nlh->nlmsg_type);
437                         return -EINVAL;
438                 }
439                 rte = (struct nlmsgerr *)NLMSG_DATA(nlh);
440                 err = rte->error;
441                 if (err < 0)
442                         fprintf(stderr, "netlink error %d (%s)\n", err, strerror(abs(err)));
443
444         } else {
445
446                 /* cmd == LIST */
447
448                 while (1) {
449                         len = recv(s, &rxbuf, sizeof(rxbuf), 0);
450                         if (len < 0) {
451                                 perror("netlink recv");
452                                 return len;
453                         }
454                         nlh = (struct nlmsghdr *)rxbuf;
455                         if (nlh->nlmsg_type == NLMSG_DONE) 
456                                 break;
457
458                         rtc = (struct rtcanmsg *)NLMSG_DATA(nlh);
459                         if (rtc->can_family != AF_CAN) {
460                                 printf("received msg from unknown family %d\n", rtc->can_family);
461                                 return -EINVAL;
462                         }
463
464                         /*
465                          * print list in a representation that
466                          * can be used directly for start scripts
467                          */
468
469                         printf("%s -A ", basename(argv[0]));
470                         printf("-s %s ", if_indextoname(rtc->src_ifindex, ifname));
471                         printf("-d %s ", if_indextoname(rtc->dst_ifindex, ifname));
472
473                         if (rtc->can_txflags & CAN_GW_TXFLAGS_ECHO)
474                                 printf("-e ");
475
476                         if (rtc->can_txflags & CAN_GW_TXFLAGS_SRC_TSTAMP)
477                                 printf("-t ");
478
479                         /* check for attributes */
480
481                         handled = 0;
482                         dropped = 0;
483
484                         rta = (struct rtattr *) RTM_RTA(rtc);
485                         rtlen = RTM_PAYLOAD(nlh);
486                         for(;RTA_OK(rta, rtlen);rta=RTA_NEXT(rta,rtlen))
487                         {
488                                 switch(rta->rta_type) {
489
490                                 case CGW_FILTER:
491                                         printfilter(RTA_DATA(rta));
492                                         break;
493
494                                 case CGW_MOD_AND:
495                                         printmod("AND", RTA_DATA(rta));
496                                         break;
497
498                                 case CGW_MOD_OR:
499                                         printmod("OR", RTA_DATA(rta));
500                                         break;
501
502                                 case CGW_MOD_XOR:
503                                         printmod("XOR", RTA_DATA(rta));
504                                         break;
505
506                                 case CGW_MOD_SET:
507                                         printmod("SET", RTA_DATA(rta));
508                                         break;
509
510                                 case CGW_HANDLED:
511                                         handled = *(__u32 *)RTA_DATA(rta);
512                                         break;
513
514                                 case CGW_DROPPED:
515                                         dropped = *(__u32 *)RTA_DATA(rta);
516                                         break;
517
518                                 default:
519                                         printf("Unknown attribute %d!", rta->rta_type);
520                                         return -EINVAL;
521                                         break;
522                                 }
523                         }
524
525                         printf("# %d handled %d dropped\n", handled, dropped); /* end of entry */
526                 }
527         }
528
529         close(s);
530
531         return err;
532 }
533