6 * cangw.c - manage PF_CAN netlink gateway
8 * Copyright (c) 2010 Volkswagen Group Electronic Research
11 * Redistribution and use in source and binary forms, with or without
12 * modification, are permitted provided that the following conditions
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.
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.
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.
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
44 * Send feedback to <socketcan-users@lists.berlios.de>
54 #include <sys/socket.h>
56 #include <linux/netlink.h>
57 #include <linux/rtnetlink.h>
58 #include <linux/can/gw.h>
72 } __attribute__((packed));
75 #define RTCAN_RTA(r) ((struct rtattr*)(((char*)(r)) + NLMSG_ALIGN(sizeof(struct rtcanmsg))))
76 #define RTCAN_PAYLOAD(n) NLMSG_PAYLOAD(n,sizeof(struct rtcanmsg))
78 /* some netlink helpers stolen from iproute2 package */
79 #define NLMSG_TAIL(nmsg) \
80 ((struct rtattr *)(((void *) (nmsg)) + NLMSG_ALIGN((nmsg)->nlmsg_len)))
82 int addattr_l(struct nlmsghdr *n, int maxlen, int type, const void *data,
85 int len = RTA_LENGTH(alen);
88 if (NLMSG_ALIGN(n->nlmsg_len) + RTA_ALIGN(len) > maxlen) {
89 fprintf(stderr, "addattr_l: message exceeded bound of %d\n",
96 memcpy(RTA_DATA(rta), data, alen);
97 n->nlmsg_len = NLMSG_ALIGN(n->nlmsg_len) + RTA_ALIGN(len);
101 void printfilter(const void *data)
103 struct can_filter *filter = (struct can_filter *)data;
105 printf("-f %03X:%X ", filter->can_id, filter->can_mask);
108 void printmod(const char *type, const void *data)
113 memcpy (&mod, data, CGW_MODATTR_LEN);
115 printf("-m %s:", type);
117 if (mod.modtype & CGW_MOD_ID)
120 if (mod.modtype & CGW_MOD_DLC)
123 if (mod.modtype & CGW_MOD_DATA)
126 printf(":%03X.%X.", mod.cf.can_id, mod.cf.can_dlc);
128 for (i = 0; i < 8; i++)
129 printf("%02X", mod.cf.data[i]);
134 void print_cs_xor(struct cgw_csum_xor *cs_xor)
136 printf("-x %d:%d:%d:%02X ",
137 cs_xor->from_idx, cs_xor->to_idx,
138 cs_xor->result_idx, cs_xor->init_xor_val);
141 void print_cs_crc8(struct cgw_csum_crc8 *cs_crc8)
145 printf("-c %d:%d:%d:%02X:%02X:",
146 cs_crc8->from_idx, cs_crc8->to_idx,
147 cs_crc8->result_idx, cs_crc8->init_crc_val,
148 cs_crc8->final_xor_val);
150 for (i = 0; i < 256; i++)
151 printf("%02X", cs_crc8->crctab[i]);
156 void print_usage(char *prg)
158 fprintf(stderr, "\nUsage: %s [options]\n\n", prg);
159 fprintf(stderr, "Commands: -A (add a new rule)\n");
160 fprintf(stderr, " -D (delete a rule)\n");
161 fprintf(stderr, " -F (flush / delete all rules)\n");
162 fprintf(stderr, " -L (list all rules)\n");
163 fprintf(stderr, "Mandatory: -s <src_dev> (source netdevice)\n");
164 fprintf(stderr, " -d <dst_dev> (destination netdevice)\n");
165 fprintf(stderr, "Options: -t (preserve src_dev rx timestamp)\n");
166 fprintf(stderr, " -e (echo sent frames - recommended on vcanx)\n");
167 fprintf(stderr, " -f <filter> (set CAN filter)\n");
168 fprintf(stderr, " -m <mod> (set frame modifications)\n");
169 fprintf(stderr, "\nValues are given and expected in hexadecimal values. Leading 0s can be omitted.\n");
170 fprintf(stderr, "\n");
171 fprintf(stderr, "<filter> is a <value>:<mask> CAN identifier filter\n");
172 fprintf(stderr, "\n");
173 fprintf(stderr, "<mod> is a CAN frame modification instruction consisting of\n");
174 fprintf(stderr, "<instruction>:<can_frame-elements>:<can_id>.<can_dlc>.<can_data>\n");
175 fprintf(stderr, " - <instruction> is one of 'AND' 'OR' 'XOR' 'SET'\n");
176 fprintf(stderr, " - <can_frame-elements> is _one_ or _more_ of 'I'dentifier 'L'ength 'D'ata\n");
177 fprintf(stderr, " - <can_id> is an u32 value containing the CAN Identifier\n");
178 fprintf(stderr, " - <can_dlc> is an u8 value containing the data length code (0 .. 8)\n");
179 fprintf(stderr, " - <can_data> is always eight(!) u8 values containing the CAN frames data\n");
180 fprintf(stderr, "The max. four modifications are performed in the order AND -> OR -> XOR -> SET\n");
181 fprintf(stderr, "\n");
182 fprintf(stderr, "Example:\n");
183 fprintf(stderr, "%s -A -s can0 -d vcan3 -e -f 123:C00007FF -m SET:IL:333.4.1122334455667788\n", prg);
184 fprintf(stderr, "\n");
187 int b64hex(char *asc, unsigned char *bin, int len)
191 for (i = 0; i < len; i++) {
192 if (!sscanf(asc+(i*2), "%2hhx", bin+i))
198 int parse_mod(char *optarg, struct modattr *modmsg)
201 char hexdata[17] = {0};
204 nptr = strchr(ptr, ':');
206 if ((nptr - ptr > 3) || (nptr - ptr == 0))
209 if (!strncmp(ptr, "AND", 3))
210 modmsg->instruction = CGW_MOD_AND;
211 else if (!strncmp(ptr, "OR", 2))
212 modmsg->instruction = CGW_MOD_OR;
213 else if (!strncmp(ptr, "XOR", 3))
214 modmsg->instruction = CGW_MOD_XOR;
215 else if (!strncmp(ptr, "SET", 3))
216 modmsg->instruction = CGW_MOD_SET;
221 nptr = strchr(ptr, ':');
223 if ((nptr - ptr > 3) || (nptr - ptr == 0))
228 while (*ptr != ':') {
233 modmsg->modtype |= CGW_MOD_ID;
237 modmsg->modtype |= CGW_MOD_DLC;
241 modmsg->modtype |= CGW_MOD_DATA;
250 if (sscanf(++ptr, "%lx.%hhx.%16s",
251 (long unsigned int *)&modmsg->cf.can_id,
252 (unsigned char *)&modmsg->cf.can_dlc, hexdata) != 3)
255 /* 4-bit masks can have values from 0 to 0xF */
256 if (modmsg->cf.can_dlc > 0xF)
259 /* but when setting CAN_DLC the value has to be limited to 8 */
260 if (modmsg->instruction == CGW_MOD_SET && modmsg->cf.can_dlc > 8)
263 if (strlen(hexdata) != 16)
266 if (b64hex(hexdata, &modmsg->cf.data[0], 8))
272 int parse_rtlist(char *prgname, unsigned char *rxbuf, int len)
274 char ifname[IF_NAMESIZE]; /* internface name for if_indextoname() */
275 struct rtcanmsg *rtc;
277 struct nlmsghdr *nlh;
278 unsigned int src_ifindex = 0;
279 unsigned int dst_ifindex = 0;
280 __u32 handled, dropped;
284 nlh = (struct nlmsghdr *)rxbuf;
287 if (!NLMSG_OK(nlh, len))
290 if (nlh->nlmsg_type == NLMSG_ERROR) {
291 printf("NLMSG_ERROR\n");
295 if (nlh->nlmsg_type == NLMSG_DONE) {
296 //printf("NLMSG_DONE\n");
300 rtc = (struct rtcanmsg *)NLMSG_DATA(nlh);
301 if (rtc->can_family != AF_CAN) {
302 printf("received msg from unknown family %d\n", rtc->can_family);
306 if (rtc->gwtype != CGW_TYPE_CAN_CAN) {
307 printf("received msg with unknown gwtype %d\n", rtc->gwtype);
312 * print list in a representation that
313 * can be used directly for start scripts.
315 * To order the mandatory and optional parameters in the
316 * output string, the NLMSG is parsed twice.
324 printf("%s -A ", basename(prgname));
326 /* first parse for mandatory options */
327 rta = (struct rtattr *) RTCAN_RTA(rtc);
328 rtlen = RTCAN_PAYLOAD(nlh);
329 for(;RTA_OK(rta, rtlen);rta=RTA_NEXT(rta,rtlen))
331 //printf("(A-%d)", rta->rta_type);
332 switch(rta->rta_type) {
344 src_ifindex = *(__u32 *)RTA_DATA(rta);
348 dst_ifindex = *(__u32 *)RTA_DATA(rta);
352 handled = *(__u32 *)RTA_DATA(rta);
356 dropped = *(__u32 *)RTA_DATA(rta);
360 printf("Unknown attribute %d!", rta->rta_type);
367 printf("-s %s ", if_indextoname(src_ifindex, ifname));
368 printf("-d %s ", if_indextoname(dst_ifindex, ifname));
370 if (rtc->flags & CGW_FLAGS_CAN_ECHO)
373 if (rtc->flags & CGW_FLAGS_CAN_SRC_TSTAMP)
376 /* second parse for mod attributes */
377 rta = (struct rtattr *) RTCAN_RTA(rtc);
378 rtlen = RTCAN_PAYLOAD(nlh);
379 for(;RTA_OK(rta, rtlen);rta=RTA_NEXT(rta,rtlen))
381 //printf("(B-%d)", rta->rta_type);
382 switch(rta->rta_type) {
385 printfilter(RTA_DATA(rta));
389 printmod("AND", RTA_DATA(rta));
393 printmod("OR", RTA_DATA(rta));
397 printmod("XOR", RTA_DATA(rta));
401 printmod("SET", RTA_DATA(rta));
405 print_cs_xor((struct cgw_csum_xor *)RTA_DATA(rta));
409 print_cs_crc8((struct cgw_csum_crc8 *)RTA_DATA(rta));
419 printf("Unknown attribute %d!", rta->rta_type);
425 printf("# %d handled %d dropped\n", handled, dropped); /* end of entry */
427 /* jump to next NLMSG in the given buffer */
428 nlh = NLMSG_NEXT(nlh, len);
432 int main(int argc, char **argv)
438 extern int optind, opterr, optopt;
443 int have_cs_crc8 = 0;
447 struct rtcanmsg rtcan;
452 unsigned char rxbuf[8192]; /* netlink receive buffer */
453 struct nlmsghdr *nlh;
454 struct nlmsgerr *rte;
455 unsigned int src_ifindex = 0;
456 unsigned int dst_ifindex = 0;
460 struct can_filter filter;
461 struct sockaddr_nl nladdr;
463 struct cgw_csum_xor cs_xor;
464 struct cgw_csum_crc8 cs_crc8;
465 char crc8tab[513] = {0};
467 struct modattr modmsg[CGW_MOD_FUNCS];
471 memset(&req, 0, sizeof(req));
473 while ((opt = getopt(argc, argv, "ADFLs:d:tef:c:x:m:?")) != -1) {
497 src_ifindex = if_nametoindex(optarg);
501 dst_ifindex = if_nametoindex(optarg);
505 flags |= CGW_FLAGS_CAN_SRC_TSTAMP;
509 flags |= CGW_FLAGS_CAN_ECHO;
513 if (sscanf(optarg, "%lx:%lx",
514 (long unsigned int *)&filter.can_id,
515 (long unsigned int *)&filter.can_mask) == 2) {
518 printf("Bad filter definition '%s'.\n", optarg);
524 if (sscanf(optarg, "%hhd:%hhd:%hhd:%hhx",
525 &cs_xor.from_idx, &cs_xor.to_idx,
526 &cs_xor.result_idx, &cs_xor.init_xor_val) == 4) {
529 printf("Bad XOR checksum definition '%s'.\n", optarg);
535 if ((sscanf(optarg, "%hhd:%hhd:%hhd:%hhx:%hhx:%512s",
536 &cs_crc8.from_idx, &cs_crc8.to_idx,
537 &cs_crc8.result_idx, &cs_crc8.init_crc_val,
538 &cs_crc8.final_xor_val, crc8tab) == 6) &&
539 (strlen(crc8tab) == 512) &&
540 (b64hex(crc8tab, (unsigned char *)&cs_crc8.crctab, 256) == 0)) {
543 printf("Bad CRC8 checksum definition '%s'.\n", optarg);
549 /* may be triggered by each of the CGW_MOD_FUNCS functions */
550 if ((modidx < CGW_MOD_FUNCS) && (err = parse_mod(optarg, &modmsg[modidx++]))) {
551 printf("Problem %d with modification definition '%s'.\n", err, optarg);
557 print_usage(basename(argv[0]));
562 fprintf(stderr, "Unknown option %c\n", opt);
563 print_usage(basename(argv[0]));
569 if ((argc - optind != 0) || (cmd == UNSPEC)) {
570 print_usage(basename(argv[0]));
574 if ((cmd == ADD || cmd == DEL) &&
575 ((!src_ifindex) || (!dst_ifindex))) {
576 print_usage(basename(argv[0]));
580 s = socket(PF_NETLINK, SOCK_RAW, NETLINK_ROUTE);
585 req.nh.nlmsg_flags = NLM_F_REQUEST | NLM_F_ACK;
586 req.nh.nlmsg_type = RTM_NEWROUTE;
590 req.nh.nlmsg_flags = NLM_F_REQUEST | NLM_F_ACK;
591 req.nh.nlmsg_type = RTM_DELROUTE;
595 req.nh.nlmsg_flags = NLM_F_REQUEST | NLM_F_ACK;
596 req.nh.nlmsg_type = RTM_DELROUTE;
597 /* if_index set to 0 => remove all entries */
603 req.nh.nlmsg_flags = NLM_F_REQUEST | NLM_F_DUMP;
604 req.nh.nlmsg_type = RTM_GETROUTE;
608 printf("This function is not yet implemented.\n");
613 req.nh.nlmsg_len = NLMSG_LENGTH(sizeof(struct rtcanmsg));
614 req.nh.nlmsg_seq = 0;
616 req.rtcan.can_family = AF_CAN;
617 req.rtcan.gwtype = CGW_TYPE_CAN_CAN;
618 req.rtcan.flags = flags;
620 addattr_l(&req.nh, sizeof(req), CGW_SRC_IF, &src_ifindex, sizeof(src_ifindex));
621 addattr_l(&req.nh, sizeof(req), CGW_DST_IF, &dst_ifindex, sizeof(dst_ifindex));
623 /* add new attributes here */
626 addattr_l(&req.nh, sizeof(req), CGW_FILTER, &filter, sizeof(filter));
629 addattr_l(&req.nh, sizeof(req), CGW_CS_CRC8, &cs_crc8, sizeof(cs_crc8));
632 addattr_l(&req.nh, sizeof(req), CGW_CS_XOR, &cs_xor, sizeof(cs_xor));
635 * a better example code
636 * modmsg.modtype = CGW_MOD_ID;
637 * addattr_l(&req.n, sizeof(req), CGW_MOD_SET, &modmsg, CGW_MODATTR_LEN);
640 /* add up to CGW_MOD_FUNCS modification definitions */
641 for (i = 0; i < modidx; i++)
642 addattr_l(&req.nh, sizeof(req), modmsg[i].instruction, &modmsg[i], CGW_MODATTR_LEN);
644 memset(&nladdr, 0, sizeof(nladdr));
645 nladdr.nl_family = AF_NETLINK;
647 nladdr.nl_groups = 0;
649 err = sendto(s, &req, req.nh.nlmsg_len, 0,
650 (struct sockaddr*)&nladdr, sizeof(nladdr));
652 perror("netlink sendto");
656 /* clean netlink receive buffer */
657 bzero(rxbuf, sizeof(rxbuf));
662 * cmd == ADD || cmd == DEL || cmd == FLUSH
664 * Parse the requested netlink acknowledge return values.
667 err = recv(s, &rxbuf, sizeof(rxbuf), 0);
669 perror("netlink recv");
672 nlh = (struct nlmsghdr *)rxbuf;
673 if (nlh->nlmsg_type != NLMSG_ERROR) {
674 fprintf(stderr, "unexpected netlink answer of type %d\n", nlh->nlmsg_type);
677 rte = (struct nlmsgerr *)NLMSG_DATA(nlh);
680 fprintf(stderr, "netlink error %d (%s)\n", err, strerror(abs(err)));
687 len = recv(s, &rxbuf, sizeof(rxbuf), 0);
689 perror("netlink recv");
693 printf("received msg len %d\n", len);
695 for (i = 0; i < len; i++)
696 printf("%02X ", rxbuf[i]);
700 /* leave on errors or NLMSG_DONE */
701 if (parse_rtlist(argv[0], rxbuf, len))