2 * cangw.c - manage PF_CAN netlink gateway
4 * Copyright (c) 2010 Volkswagen Group Electronic Research
7 * Redistribution and use in source and binary forms, with or without
8 * modification, are permitted provided that the following conditions
10 * 1. Redistributions of source code must retain the above copyright
11 * notice, this list of conditions and the following disclaimer.
12 * 2. Redistributions in binary form must reproduce the above copyright
13 * notice, this list of conditions and the following disclaimer in the
14 * documentation and/or other materials provided with the distribution.
15 * 3. Neither the name of Volkswagen nor the names of its contributors
16 * may be used to endorse or promote products derived from this software
17 * without specific prior written permission.
19 * Alternatively, provided that this notice is retained in full, this
20 * software may be distributed under the terms of the GNU General
21 * Public License ("GPL") version 2, in which case the provisions of the
22 * GPL apply INSTEAD OF those given above.
24 * The provided data structures and external interfaces from this code
25 * are not restricted to be used by modules with a GPL compatible license.
27 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
28 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
29 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
30 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
31 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
32 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
33 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
34 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
35 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
36 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
37 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
40 * Send feedback to <linux-can@vger.kernel.org>
50 #include <sys/socket.h>
52 #include <linux/netlink.h>
53 #include <linux/rtnetlink.h>
54 #include <linux/can/gw.h>
68 } __attribute__((packed));
71 #define RTCAN_RTA(r) ((struct rtattr*)(((char*)(r)) + NLMSG_ALIGN(sizeof(struct rtcanmsg))))
72 #define RTCAN_PAYLOAD(n) NLMSG_PAYLOAD(n,sizeof(struct rtcanmsg))
74 /* some netlink helpers stolen from iproute2 package */
75 #define NLMSG_TAIL(nmsg) \
76 ((struct rtattr *)(((void *) (nmsg)) + NLMSG_ALIGN((nmsg)->nlmsg_len)))
78 int addattr_l(struct nlmsghdr *n, int maxlen, int type, const void *data,
81 int len = RTA_LENGTH(alen);
84 if (NLMSG_ALIGN(n->nlmsg_len) + RTA_ALIGN(len) > maxlen) {
85 fprintf(stderr, "addattr_l: message exceeded bound of %d\n",
92 memcpy(RTA_DATA(rta), data, alen);
93 n->nlmsg_len = NLMSG_ALIGN(n->nlmsg_len) + RTA_ALIGN(len);
97 void printfilter(const void *data)
99 struct can_filter *filter = (struct can_filter *)data;
101 if (filter->can_id & CAN_INV_FILTER)
102 printf("-f %03X~%X ", (filter->can_id & ~CAN_INV_FILTER), filter->can_mask);
104 printf("-f %03X:%X ", filter->can_id, filter->can_mask);
107 void printmod(const char *type, const void *data)
112 memcpy (&mod, data, CGW_MODATTR_LEN);
114 printf("-m %s:", type);
116 if (mod.modtype & CGW_MOD_ID)
119 if (mod.modtype & CGW_MOD_DLC)
122 if (mod.modtype & CGW_MOD_DATA)
125 printf(":%03X.%X.", mod.cf.can_id, mod.cf.can_dlc);
127 for (i = 0; i < 8; i++)
128 printf("%02X", mod.cf.data[i]);
133 void print_cs_xor(struct cgw_csum_xor *cs_xor)
135 printf("-x %d:%d:%d:%02X ",
136 cs_xor->from_idx, cs_xor->to_idx,
137 cs_xor->result_idx, cs_xor->init_xor_val);
140 void print_cs_crc8_profile(struct cgw_csum_crc8 *cs_crc8)
144 printf("-p %d:", cs_crc8->profile);
146 switch (cs_crc8->profile) {
148 case CGW_CRC8PRF_1U8:
150 printf("%02X", cs_crc8->profile_data[0]);
153 case CGW_CRC8PRF_16U8:
155 for (i = 0; i < 16; i++)
156 printf("%02X", cs_crc8->profile_data[i]);
159 case CGW_CRC8PRF_SFFID_XOR:
163 printf("<unknown profile #%d>", cs_crc8->profile);
169 void print_cs_crc8(struct cgw_csum_crc8 *cs_crc8)
173 printf("-c %d:%d:%d:%02X:%02X:",
174 cs_crc8->from_idx, cs_crc8->to_idx,
175 cs_crc8->result_idx, cs_crc8->init_crc_val,
176 cs_crc8->final_xor_val);
178 for (i = 0; i < 256; i++)
179 printf("%02X", cs_crc8->crctab[i]);
183 if (cs_crc8->profile != CGW_CRC8PRF_UNSPEC)
184 print_cs_crc8_profile(cs_crc8);
187 void print_usage(char *prg)
189 fprintf(stderr, "\nUsage: %s [options]\n\n", prg);
190 fprintf(stderr, "Commands: -A (add a new rule)\n");
191 fprintf(stderr, " -D (delete a rule)\n");
192 fprintf(stderr, " -F (flush / delete all rules)\n");
193 fprintf(stderr, " -L (list all rules)\n");
194 fprintf(stderr, "Mandatory: -s <src_dev> (source netdevice)\n");
195 fprintf(stderr, " -d <dst_dev> (destination netdevice)\n");
196 fprintf(stderr, "Options: -t (preserve src_dev rx timestamp)\n");
197 fprintf(stderr, " -e (echo sent frames - recommended on vcanx)\n");
198 fprintf(stderr, " -i (allow to route to incoming interface)\n");
199 fprintf(stderr, " -f <filter> (set CAN filter)\n");
200 fprintf(stderr, " -m <mod> (set frame modifications)\n");
201 fprintf(stderr, " -x <from_idx>:<to_idx>:<result_idx>:<init_xor_val> (XOR checksum)\n");
202 fprintf(stderr, " -c <from>:<to>:<result>:<init_val>:<xor_val>:<crctab[256]> (CRC8 cs)\n");
203 fprintf(stderr, " -p <profile>:[<profile_data>] (CRC8 checksum profile & parameters)\n");
204 fprintf(stderr, "\nValues are given and expected in hexadecimal values. Leading 0s can be omitted.\n");
205 fprintf(stderr, "\n");
206 fprintf(stderr, "<filter> is a <value><mask> CAN identifier filter\n");
207 fprintf(stderr, " <can_id>:<can_mask> (matches when <received_can_id> & mask == can_id & mask)\n");
208 fprintf(stderr, " <can_id>~<can_mask> (matches when <received_can_id> & mask != can_id & mask)\n");
209 fprintf(stderr, "\n");
210 fprintf(stderr, "<mod> is a CAN frame modification instruction consisting of\n");
211 fprintf(stderr, "<instruction>:<can_frame-elements>:<can_id>.<can_dlc>.<can_data>\n");
212 fprintf(stderr, " - <instruction> is one of 'AND' 'OR' 'XOR' 'SET'\n");
213 fprintf(stderr, " - <can_frame-elements> is _one_ or _more_ of 'I'dentifier 'L'ength 'D'ata\n");
214 fprintf(stderr, " - <can_id> is an u32 value containing the CAN Identifier\n");
215 fprintf(stderr, " - <can_dlc> is an u8 value containing the data length code (0 .. 8)\n");
216 fprintf(stderr, " - <can_data> is always eight(!) u8 values containing the CAN frames data\n");
217 fprintf(stderr, "The max. four modifications are performed in the order AND -> OR -> XOR -> SET\n");
218 fprintf(stderr, "\n");
219 fprintf(stderr, "Example:\n");
220 fprintf(stderr, "%s -A -s can0 -d vcan3 -e -f 123:C00007FF -m SET:IL:333.4.1122334455667788\n", prg);
221 fprintf(stderr, "\n");
222 fprintf(stderr, "Supported CRC 8 profiles:\n");
223 fprintf(stderr, "Profile '%d' (1U8) - add one additional u8 value\n", CGW_CRC8PRF_1U8);
224 fprintf(stderr, "Profile '%d' (16U8) - add u8 value from table[16] indexed by (data[1] & 0xF)\n", CGW_CRC8PRF_16U8);
225 fprintf(stderr, "Profile '%d' (SFFID_XOR) - add u8 value (can_id & 0xFF) ^ (can_id >> 8 & 0xFF)\n", CGW_CRC8PRF_SFFID_XOR);
226 fprintf(stderr, "\n");
229 int b64hex(char *asc, unsigned char *bin, int len)
233 for (i = 0; i < len; i++) {
234 if (!sscanf(asc+(i*2), "%2hhx", bin+i))
240 int parse_crc8_profile(char *optarg, struct cgw_csum_crc8 *crc8)
245 if (sscanf(optarg, "%hhd:", &crc8->profile) != 1)
248 switch (crc8->profile) {
250 case CGW_CRC8PRF_1U8:
252 if (sscanf(optarg, "%hhd:%2hhx", &crc8->profile, &crc8->profile_data[0]) == 2)
257 case CGW_CRC8PRF_16U8:
259 ptr = strchr(optarg, ':');
261 /* check if length contains 16 base64 hex values */
263 strlen(ptr) == strlen(":00112233445566778899AABBCCDDEEFF") &&
264 b64hex(ptr+1, (unsigned char *)&crc8->profile_data[0], 16) == 0)
269 case CGW_CRC8PRF_SFFID_XOR:
271 /* no additional parameters needed */
279 int parse_mod(char *optarg, struct modattr *modmsg)
282 char hexdata[17] = {0};
285 nptr = strchr(ptr, ':');
287 if ((nptr - ptr > 3) || (nptr - ptr == 0))
290 if (!strncmp(ptr, "AND", 3))
291 modmsg->instruction = CGW_MOD_AND;
292 else if (!strncmp(ptr, "OR", 2))
293 modmsg->instruction = CGW_MOD_OR;
294 else if (!strncmp(ptr, "XOR", 3))
295 modmsg->instruction = CGW_MOD_XOR;
296 else if (!strncmp(ptr, "SET", 3))
297 modmsg->instruction = CGW_MOD_SET;
302 nptr = strchr(ptr, ':');
304 if ((nptr - ptr > 3) || (nptr - ptr == 0))
309 while (*ptr != ':') {
314 modmsg->modtype |= CGW_MOD_ID;
318 modmsg->modtype |= CGW_MOD_DLC;
322 modmsg->modtype |= CGW_MOD_DATA;
331 if (sscanf(++ptr, "%x.%hhx.%16s", &modmsg->cf.can_id,
332 (unsigned char *)&modmsg->cf.can_dlc, hexdata) != 3)
335 /* 4-bit masks can have values from 0 to 0xF */
336 if (modmsg->cf.can_dlc > 0xF)
339 /* but when setting CAN_DLC the value has to be limited to 8 */
340 if (modmsg->instruction == CGW_MOD_SET && modmsg->cf.can_dlc > 8)
343 if (strlen(hexdata) != 16)
346 if (b64hex(hexdata, &modmsg->cf.data[0], 8))
352 int parse_rtlist(char *prgname, unsigned char *rxbuf, int len)
354 char ifname[IF_NAMESIZE]; /* internface name for if_indextoname() */
355 struct rtcanmsg *rtc;
357 struct nlmsghdr *nlh;
358 unsigned int src_ifindex = 0;
359 unsigned int dst_ifindex = 0;
360 __u32 handled, dropped, deleted;
364 nlh = (struct nlmsghdr *)rxbuf;
367 if (!NLMSG_OK(nlh, len))
370 if (nlh->nlmsg_type == NLMSG_ERROR) {
371 printf("NLMSG_ERROR\n");
375 if (nlh->nlmsg_type == NLMSG_DONE) {
376 //printf("NLMSG_DONE\n");
380 rtc = (struct rtcanmsg *)NLMSG_DATA(nlh);
381 if (rtc->can_family != AF_CAN) {
382 printf("received msg from unknown family %d\n", rtc->can_family);
386 if (rtc->gwtype != CGW_TYPE_CAN_CAN) {
387 printf("received msg with unknown gwtype %d\n", rtc->gwtype);
392 * print list in a representation that
393 * can be used directly for start scripts.
395 * To order the mandatory and optional parameters in the
396 * output string, the NLMSG is parsed twice.
405 printf("%s -A ", basename(prgname));
407 /* first parse for mandatory options */
408 rta = (struct rtattr *) RTCAN_RTA(rtc);
409 rtlen = RTCAN_PAYLOAD(nlh);
410 for(;RTA_OK(rta, rtlen);rta=RTA_NEXT(rta,rtlen))
412 //printf("(A-%d)", rta->rta_type);
413 switch(rta->rta_type) {
425 src_ifindex = *(__u32 *)RTA_DATA(rta);
429 dst_ifindex = *(__u32 *)RTA_DATA(rta);
433 handled = *(__u32 *)RTA_DATA(rta);
437 dropped = *(__u32 *)RTA_DATA(rta);
441 deleted = *(__u32 *)RTA_DATA(rta);
445 printf("Unknown attribute %d!", rta->rta_type);
452 printf("-s %s ", if_indextoname(src_ifindex, ifname));
453 printf("-d %s ", if_indextoname(dst_ifindex, ifname));
455 if (rtc->flags & CGW_FLAGS_CAN_ECHO)
458 if (rtc->flags & CGW_FLAGS_CAN_SRC_TSTAMP)
461 if (rtc->flags & CGW_FLAGS_CAN_IIF_TX_OK)
464 /* second parse for mod attributes */
465 rta = (struct rtattr *) RTCAN_RTA(rtc);
466 rtlen = RTCAN_PAYLOAD(nlh);
467 for(;RTA_OK(rta, rtlen);rta=RTA_NEXT(rta,rtlen))
469 //printf("(B-%d)", rta->rta_type);
470 switch(rta->rta_type) {
473 printfilter(RTA_DATA(rta));
477 printmod("AND", RTA_DATA(rta));
481 printmod("OR", RTA_DATA(rta));
485 printmod("XOR", RTA_DATA(rta));
489 printmod("SET", RTA_DATA(rta));
493 print_cs_xor((struct cgw_csum_xor *)RTA_DATA(rta));
497 print_cs_crc8((struct cgw_csum_crc8 *)RTA_DATA(rta));
508 printf("Unknown attribute %d!", rta->rta_type);
515 printf("# %d handled %d dropped %d deleted\n",
516 handled, dropped, deleted);
518 /* jump to next NLMSG in the given buffer */
519 nlh = NLMSG_NEXT(nlh, len);
523 int main(int argc, char **argv)
529 extern int optind, opterr, optopt;
534 int have_cs_crc8 = 0;
538 struct rtcanmsg rtcan;
543 unsigned char rxbuf[8192]; /* netlink receive buffer */
544 struct nlmsghdr *nlh;
545 struct nlmsgerr *rte;
546 unsigned int src_ifindex = 0;
547 unsigned int dst_ifindex = 0;
551 struct can_filter filter;
552 struct sockaddr_nl nladdr;
554 struct cgw_csum_xor cs_xor;
555 struct cgw_csum_crc8 cs_crc8;
556 char crc8tab[513] = {0};
558 struct modattr modmsg[CGW_MOD_FUNCS];
562 memset(&req, 0, sizeof(req));
563 memset(&cs_xor, 0, sizeof(cs_xor));
564 memset(&cs_crc8, 0, sizeof(cs_crc8));
566 while ((opt = getopt(argc, argv, "ADFLs:d:teif:c:p:x:m:?")) != -1) {
590 src_ifindex = if_nametoindex(optarg);
594 dst_ifindex = if_nametoindex(optarg);
598 flags |= CGW_FLAGS_CAN_SRC_TSTAMP;
602 flags |= CGW_FLAGS_CAN_ECHO;
606 flags |= CGW_FLAGS_CAN_IIF_TX_OK;
610 if (sscanf(optarg, "%x:%x", &filter.can_id,
611 &filter.can_mask) == 2) {
613 } else if (sscanf(optarg, "%x~%x", &filter.can_id,
614 &filter.can_mask) == 2) {
615 filter.can_id |= CAN_INV_FILTER;
618 printf("Bad filter definition '%s'.\n", optarg);
624 if (sscanf(optarg, "%hhd:%hhd:%hhd:%hhx",
625 &cs_xor.from_idx, &cs_xor.to_idx,
626 &cs_xor.result_idx, &cs_xor.init_xor_val) == 4) {
629 printf("Bad XOR checksum definition '%s'.\n", optarg);
635 if ((sscanf(optarg, "%hhd:%hhd:%hhd:%hhx:%hhx:%512s",
636 &cs_crc8.from_idx, &cs_crc8.to_idx,
637 &cs_crc8.result_idx, &cs_crc8.init_crc_val,
638 &cs_crc8.final_xor_val, crc8tab) == 6) &&
639 (strlen(crc8tab) == 512) &&
640 (b64hex(crc8tab, (unsigned char *)&cs_crc8.crctab, 256) == 0)) {
643 printf("Bad CRC8 checksum definition '%s'.\n", optarg);
649 if (parse_crc8_profile(optarg, &cs_crc8)) {
650 printf("Bad CRC8 profile definition '%s'.\n", optarg);
656 /* may be triggered by each of the CGW_MOD_FUNCS functions */
657 if ((modidx < CGW_MOD_FUNCS) && (err = parse_mod(optarg, &modmsg[modidx++]))) {
658 printf("Problem %d with modification definition '%s'.\n", err, optarg);
664 print_usage(basename(argv[0]));
669 fprintf(stderr, "Unknown option %c\n", opt);
670 print_usage(basename(argv[0]));
676 if ((argc - optind != 0) || (cmd == UNSPEC)) {
677 print_usage(basename(argv[0]));
681 if ((cmd == ADD || cmd == DEL) &&
682 ((!src_ifindex) || (!dst_ifindex))) {
683 print_usage(basename(argv[0]));
687 if (!modidx && (have_cs_crc8 || have_cs_xor)) {
688 printf("-c or -x can only be used in conjunction with -m\n");
692 s = socket(PF_NETLINK, SOCK_RAW, NETLINK_ROUTE);
697 req.nh.nlmsg_flags = NLM_F_REQUEST | NLM_F_ACK;
698 req.nh.nlmsg_type = RTM_NEWROUTE;
702 req.nh.nlmsg_flags = NLM_F_REQUEST | NLM_F_ACK;
703 req.nh.nlmsg_type = RTM_DELROUTE;
707 req.nh.nlmsg_flags = NLM_F_REQUEST | NLM_F_ACK;
708 req.nh.nlmsg_type = RTM_DELROUTE;
709 /* if_index set to 0 => remove all entries */
715 req.nh.nlmsg_flags = NLM_F_REQUEST | NLM_F_DUMP;
716 req.nh.nlmsg_type = RTM_GETROUTE;
720 printf("This function is not yet implemented.\n");
725 req.nh.nlmsg_len = NLMSG_LENGTH(sizeof(struct rtcanmsg));
726 req.nh.nlmsg_seq = 0;
728 req.rtcan.can_family = AF_CAN;
729 req.rtcan.gwtype = CGW_TYPE_CAN_CAN;
730 req.rtcan.flags = flags;
732 addattr_l(&req.nh, sizeof(req), CGW_SRC_IF, &src_ifindex, sizeof(src_ifindex));
733 addattr_l(&req.nh, sizeof(req), CGW_DST_IF, &dst_ifindex, sizeof(dst_ifindex));
735 /* add new attributes here */
738 addattr_l(&req.nh, sizeof(req), CGW_FILTER, &filter, sizeof(filter));
741 addattr_l(&req.nh, sizeof(req), CGW_CS_CRC8, &cs_crc8, sizeof(cs_crc8));
744 addattr_l(&req.nh, sizeof(req), CGW_CS_XOR, &cs_xor, sizeof(cs_xor));
747 * a better example code
748 * modmsg.modtype = CGW_MOD_ID;
749 * addattr_l(&req.n, sizeof(req), CGW_MOD_SET, &modmsg, CGW_MODATTR_LEN);
752 /* add up to CGW_MOD_FUNCS modification definitions */
753 for (i = 0; i < modidx; i++)
754 addattr_l(&req.nh, sizeof(req), modmsg[i].instruction, &modmsg[i], CGW_MODATTR_LEN);
756 memset(&nladdr, 0, sizeof(nladdr));
757 nladdr.nl_family = AF_NETLINK;
759 nladdr.nl_groups = 0;
761 err = sendto(s, &req, req.nh.nlmsg_len, 0,
762 (struct sockaddr*)&nladdr, sizeof(nladdr));
764 perror("netlink sendto");
768 /* clean netlink receive buffer */
769 memset(rxbuf, 0x0, sizeof(rxbuf));
774 * cmd == ADD || cmd == DEL || cmd == FLUSH
776 * Parse the requested netlink acknowledge return values.
779 err = recv(s, &rxbuf, sizeof(rxbuf), 0);
781 perror("netlink recv");
784 nlh = (struct nlmsghdr *)rxbuf;
785 if (nlh->nlmsg_type != NLMSG_ERROR) {
786 fprintf(stderr, "unexpected netlink answer of type %d\n", nlh->nlmsg_type);
789 rte = (struct nlmsgerr *)NLMSG_DATA(nlh);
792 fprintf(stderr, "netlink error %d (%s)\n", err, strerror(abs(err)));
799 len = recv(s, &rxbuf, sizeof(rxbuf), 0);
801 perror("netlink recv");
805 printf("received msg len %d\n", len);
807 for (i = 0; i < len; i++)
808 printf("%02X ", rxbuf[i]);
812 /* leave on errors or NLMSG_DONE */
813 if (parse_rtlist(argv[0], rxbuf, len))