]> rtime.felk.cvut.cz Git - sojka/can-utils.git/blob - cangw.c
Rework of help text.
[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 = 0;
259         __u32 dropped = 0;
260         int rtlen;
261         int len;
262
263         struct can_filter filter;
264         struct sockaddr_nl nladdr;
265
266         struct modattr modmsg[CGW_MOD_FUNCS];
267         int modidx = 0;
268         int i;
269
270         memset(&req, 0, sizeof(req));
271
272         while ((opt = getopt(argc, argv, "ADFLs:d:tef:m:?")) != -1) {
273                 switch (opt) {
274
275                 case 'A':
276                         if (cmd == UNSPEC)
277                                 cmd = ADD;
278                         break;
279
280                 case 'D':
281                         if (cmd == UNSPEC)
282                                 cmd = DEL;
283                         break;
284
285                 case 'F':
286                         if (cmd == UNSPEC)
287                                 cmd = FLUSH;
288                         break;
289
290                 case 'L':
291                         if (cmd == UNSPEC)
292                                 cmd = LIST;
293                         break;
294
295                 case 's':
296                         req.rtcan.src_ifindex = if_nametoindex(optarg);
297                         break;
298
299                 case 'd':
300                         req.rtcan.dst_ifindex = if_nametoindex(optarg);
301                         break;
302
303                 case 't':
304                         req.rtcan.can_txflags |= CAN_GW_TXFLAGS_SRC_TSTAMP;
305                         break;
306
307                 case 'e':
308                         req.rtcan.can_txflags |= CAN_GW_TXFLAGS_ECHO;
309                         break;
310
311                 case 'f':
312                         if (sscanf(optarg, "%lx:%lx",
313                                    (long unsigned int *)&filter.can_id, 
314                                    (long unsigned int *)&filter.can_mask) == 2) {
315                                 have_filter = 1;
316                         } else {
317                                 printf("Bad filter definition '%s'.\n", optarg);
318                                 exit(1);
319                         }
320                         break;
321
322                 case 'm':
323                         /* may be triggered by each of the CGW_MOD_FUNCS functions */
324                         if ((modidx < CGW_MOD_FUNCS) && (err = parse_mod(optarg, &modmsg[modidx++]))) {
325                                 printf("Problem %d with modification definition '%s'.\n", err, optarg);
326                                 exit(1);
327                         }
328                         break;
329
330                 case '?':
331                         print_usage(basename(argv[0]));
332                         exit(0);
333                         break;
334
335                 default:
336                         fprintf(stderr, "Unknown option %c\n", opt);
337                         print_usage(basename(argv[0]));
338                         exit(1);
339                         break;
340                 }
341         }
342
343         if ((argc - optind != 0) || (cmd == UNSPEC)) {
344                 print_usage(basename(argv[0]));
345                 exit(1);
346         }
347
348         if ((cmd == ADD || cmd == DEL) &&
349             ((!req.rtcan.src_ifindex) || (!req.rtcan.dst_ifindex))) {
350                 print_usage(basename(argv[0]));
351                 exit(1);
352         }
353
354         s = socket(PF_NETLINK, SOCK_RAW, NETLINK_ROUTE);
355
356         switch (cmd) {
357
358         case ADD:
359                 req.nh.nlmsg_flags = NLM_F_REQUEST | NLM_F_ACK;
360                 req.nh.nlmsg_type  = RTM_NEWROUTE;
361                 break;
362
363         case DEL:
364                 req.nh.nlmsg_flags = NLM_F_REQUEST | NLM_F_ACK;
365                 req.nh.nlmsg_type  = RTM_DELROUTE;
366                 break;
367
368         case FLUSH:
369                 req.nh.nlmsg_flags = NLM_F_REQUEST | NLM_F_ACK;
370                 req.nh.nlmsg_type  = RTM_DELROUTE;
371                 /* if_index set to 0 => remove all entries */
372                 req.rtcan.src_ifindex  = 0;
373                 req.rtcan.dst_ifindex  = 0;
374                 break;
375
376         case LIST:
377                 req.nh.nlmsg_flags = NLM_F_REQUEST | NLM_F_DUMP;
378                 req.nh.nlmsg_type  = RTM_GETROUTE;
379                 break;
380
381         default:
382                 printf("This function is not yet implemented.\n");
383                 exit(1);
384                 break;
385         }
386
387         req.nh.nlmsg_len   = NLMSG_LENGTH(sizeof(struct rtcanmsg));
388         req.nh.nlmsg_seq   = 0;
389
390         req.rtcan.can_family  = AF_CAN;
391
392         /* add new attributes here */
393
394         if (have_filter)
395                 addattr_l(&req.nh, sizeof(req), CGW_FILTER, &filter, sizeof(filter));
396
397         /*
398          * a better example code
399          * modmsg.modtype = CGW_MOD_ID;
400          * addattr_l(&req.n, sizeof(req), CGW_MOD_SET, &modmsg, CGW_MODATTR_LEN);
401          */
402
403         /* add up to CGW_MOD_FUNCS modification definitions */
404         for (i = 0; i < modidx; i++)
405                 addattr_l(&req.nh, sizeof(req), modmsg[i].instruction, &modmsg[i], CGW_MODATTR_LEN);
406
407         memset(&nladdr, 0, sizeof(nladdr));
408         nladdr.nl_family = AF_NETLINK;
409         nladdr.nl_pid    = 0;
410         nladdr.nl_groups = 0;
411
412         err = sendto(s, &req, req.nh.nlmsg_len, 0,
413                      (struct sockaddr*)&nladdr, sizeof(nladdr));
414         if (err < 0) {
415                 perror("netlink sendto");
416                 return err;
417         }
418
419         /* clean netlink receive buffer */
420         bzero(rxbuf, sizeof(rxbuf));
421
422         if (cmd != LIST) {
423
424                 /*
425                  * cmd == ADD || cmd == DEL || cmd == FLUSH
426                  *
427                  * Parse the requested netlink acknowledge return values.
428                  */
429
430                 err = recv(s, &rxbuf, sizeof(rxbuf), 0);
431                 if (err < 0) {
432                         perror("netlink recv");
433                         return err;
434                 }
435                 nlh = (struct nlmsghdr *)rxbuf;
436                 if (nlh->nlmsg_type != NLMSG_ERROR) {
437                         fprintf(stderr, "unexpected netlink answer of type %d\n", nlh->nlmsg_type);
438                         return -EINVAL;
439                 }
440                 rte = (struct nlmsgerr *)NLMSG_DATA(nlh);
441                 err = rte->error;
442                 if (err < 0)
443                         fprintf(stderr, "netlink error %d (%s)\n", err, strerror(abs(err)));
444
445         } else {
446
447                 /* cmd == LIST */
448
449                 while (1) {
450                         len = recv(s, &rxbuf, sizeof(rxbuf), 0);
451                         if (len < 0) {
452                                 perror("netlink recv");
453                                 return len;
454                         }
455                         nlh = (struct nlmsghdr *)rxbuf;
456                         if (nlh->nlmsg_type == NLMSG_DONE) 
457                                 break;
458
459                         rtc = (struct rtcanmsg *)NLMSG_DATA(nlh);
460                         if (rtc->can_family != AF_CAN) {
461                                 printf("received msg from unknown family %d\n", rtc->can_family);
462                                 return -EINVAL;
463                         }
464
465                         /*
466                          * print list in a representation that
467                          * can be used directly for start scripts
468                          */
469
470                         printf("%s -A ", basename(argv[0]));
471                         printf("-s %s ", if_indextoname(rtc->src_ifindex, ifname));
472                         printf("-d %s ", if_indextoname(rtc->dst_ifindex, ifname));
473
474                         if (rtc->can_txflags & CAN_GW_TXFLAGS_ECHO)
475                                 printf("-e ");
476
477                         if (rtc->can_txflags & CAN_GW_TXFLAGS_SRC_TSTAMP)
478                                 printf("-t ");
479
480                         /* check for attributes */
481                         rta = (struct rtattr *) RTM_RTA(rtc);
482                         rtlen = RTM_PAYLOAD(nlh);
483                         for(;RTA_OK(rta, rtlen);rta=RTA_NEXT(rta,rtlen))
484                         {
485                                 switch(rta->rta_type) {
486
487                                 case CGW_FILTER:
488                                         printfilter(RTA_DATA(rta));
489                                         break;
490
491                                 case CGW_MOD_AND:
492                                         printmod("AND", RTA_DATA(rta));
493                                         break;
494
495                                 case CGW_MOD_OR:
496                                         printmod("OR", RTA_DATA(rta));
497                                         break;
498
499                                 case CGW_MOD_XOR:
500                                         printmod("XOR", RTA_DATA(rta));
501                                         break;
502
503                                 case CGW_MOD_SET:
504                                         printmod("SET", RTA_DATA(rta));
505                                         break;
506
507                                 case CGW_HANDLED:
508                                         handled = *(__u32 *)RTA_DATA(rta);
509                                         break;
510
511                                 case CGW_DROPPED:
512                                         dropped = *(__u32 *)RTA_DATA(rta);
513                                         break;
514
515                                 default:
516                                         printf("Unknown attribute %d!", rta->rta_type);
517                                         return -EINVAL;
518                                         break;
519                                 }
520                         }
521
522                         printf("# %d handled %d dropped\n", handled, dropped); /* end of entry */
523                 }
524         }
525
526         close(s);
527
528         return err;
529 }
530