cangw: support new can-gw features for Linux 3.9+
[profile/ivi/can-utils.git] / cangw.c
1 /*
2  * cangw.c - manage PF_CAN netlink gateway
3  *
4  * Copyright (c) 2010 Volkswagen Group Electronic Research
5  * All rights reserved.
6  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions
9  * are met:
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.
18  *
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.
23  *
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.
26  *
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
38  * DAMAGE.
39  *
40  * Send feedback to <linux-can@vger.kernel.org>
41  *
42  */
43
44 #include <stdio.h>
45 #include <stdlib.h>
46 #include <libgen.h>
47 #include <string.h>
48 #include <unistd.h>
49 #include <errno.h>
50 #include <sys/socket.h>
51 #include <net/if.h>
52 #include <linux/netlink.h>
53 #include <linux/rtnetlink.h>
54 #include <linux/can/gw.h>
55
56 enum {
57         UNSPEC,
58         ADD,
59         DEL,
60         FLUSH,
61         LIST
62 };
63
64 struct modattr {
65         struct can_frame cf;
66         __u8 modtype;
67         __u8 instruction;
68 } __attribute__((packed));
69
70
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))
73
74 /* some netlink helpers stolen from iproute2 package */
75 #define NLMSG_TAIL(nmsg) \
76         ((struct rtattr *)(((void *) (nmsg)) + NLMSG_ALIGN((nmsg)->nlmsg_len)))
77
78 int addattr_l(struct nlmsghdr *n, int maxlen, int type, const void *data,
79               int alen)
80 {
81         int len = RTA_LENGTH(alen);
82         struct rtattr *rta;
83
84         if (NLMSG_ALIGN(n->nlmsg_len) + RTA_ALIGN(len) > maxlen) {
85                 fprintf(stderr, "addattr_l: message exceeded bound of %d\n",
86                         maxlen);
87                 return -1;
88         }
89         rta = NLMSG_TAIL(n);
90         rta->rta_type = type;
91         rta->rta_len = len;
92         memcpy(RTA_DATA(rta), data, alen);
93         n->nlmsg_len = NLMSG_ALIGN(n->nlmsg_len) + RTA_ALIGN(len);
94         return 0;
95 }
96
97 void printfilter(const void *data)
98 {
99         struct can_filter *filter = (struct can_filter *)data;
100
101         printf("-f %03X:%X ", filter->can_id, filter->can_mask);
102 }
103
104 void printmod(const char *type, const void *data)
105 {
106         struct modattr mod;
107         int i;
108
109         memcpy (&mod, data, CGW_MODATTR_LEN);
110
111         printf("-m %s:", type);
112
113         if (mod.modtype & CGW_MOD_ID)
114                 printf("I");
115
116         if (mod.modtype & CGW_MOD_DLC)
117                 printf("L");
118
119         if (mod.modtype & CGW_MOD_DATA)
120                 printf("D");
121
122         printf(":%03X.%X.", mod.cf.can_id, mod.cf.can_dlc);
123
124         for (i = 0; i < 8; i++)
125                 printf("%02X", mod.cf.data[i]);
126
127         printf(" ");
128 }
129
130 void print_cs_xor(struct cgw_csum_xor *cs_xor)
131 {
132         printf("-x %d:%d:%d:%02X ",
133                cs_xor->from_idx, cs_xor->to_idx,
134                cs_xor->result_idx, cs_xor->init_xor_val);
135 }
136
137 void print_cs_crc8_profile(struct cgw_csum_crc8 *cs_crc8)
138 {
139         int i;
140
141         printf("-p %d:", cs_crc8->profile);
142
143         switch (cs_crc8->profile) {
144
145         case  CGW_CRC8PRF_1U8:
146
147                 printf("%02X", cs_crc8->profile_data[0]);
148                 break;
149
150         case  CGW_CRC8PRF_16U8:
151
152                 for (i = 0; i < 16; i++)
153                         printf("%02X", cs_crc8->profile_data[i]);
154                 break;
155
156         case  CGW_CRC8PRF_SFFID_XOR:
157                 break;
158
159         default:
160                 printf("<unknown profile #%d>", cs_crc8->profile);
161         }
162
163         printf(" ");
164 }
165
166 void print_cs_crc8(struct cgw_csum_crc8 *cs_crc8)
167 {
168         int i;
169
170         printf("-c %d:%d:%d:%02X:%02X:",
171                cs_crc8->from_idx, cs_crc8->to_idx,
172                cs_crc8->result_idx, cs_crc8->init_crc_val,
173                cs_crc8->final_xor_val);
174
175         for (i = 0; i < 256; i++)
176                 printf("%02X", cs_crc8->crctab[i]);
177
178         printf(" ");
179
180         if (cs_crc8->profile != CGW_CRC8PRF_UNSPEC)
181                 print_cs_crc8_profile(cs_crc8);
182 }
183
184 void print_usage(char *prg)
185 {
186         fprintf(stderr, "\nUsage: %s [options]\n\n", prg);
187         fprintf(stderr, "Commands:  -A (add a new rule)\n");
188         fprintf(stderr, "           -D (delete a rule)\n");
189         fprintf(stderr, "           -F (flush / delete all rules)\n");
190         fprintf(stderr, "           -L (list all rules)\n");
191         fprintf(stderr, "Mandatory: -s <src_dev>  (source netdevice)\n");
192         fprintf(stderr, "           -d <dst_dev>  (destination netdevice)\n");
193         fprintf(stderr, "Options:   -t (preserve src_dev rx timestamp)\n");
194         fprintf(stderr, "           -e (echo sent frames - recommended on vcanx)\n");
195         fprintf(stderr, "           -i (allow to route to incoming interface)\n");
196         fprintf(stderr, "           -f <filter> (set CAN filter)\n");
197         fprintf(stderr, "           -m <mod> (set frame modifications)\n");
198         fprintf(stderr, "           -x <from_idx>:<to_idx>:<result_idx>:<init_xor_val> (XOR checksum)\n");
199         fprintf(stderr, "           -c <from>:<to>:<result>:<init_val>:<xor_val>:<crctab[256]> (CRC8 cs)\n");
200         fprintf(stderr, "           -p <profile>:[<profile_data>] (CRC8 checksum profile & parameters)\n");
201         fprintf(stderr, "\nValues are given and expected in hexadecimal values. Leading 0s can be omitted.\n");
202         fprintf(stderr, "\n");
203         fprintf(stderr, "<filter> is a <value><mask> CAN identifier filter\n");
204         fprintf(stderr, "   <can_id>:<can_mask> (matches when <received_can_id> & mask == can_id & mask)\n");
205         fprintf(stderr, "   <can_id>~<can_mask> (matches when <received_can_id> & mask != can_id & mask)\n");
206         fprintf(stderr, "\n");
207         fprintf(stderr, "<mod> is a CAN frame modification instruction consisting of\n");
208         fprintf(stderr, "<instruction>:<can_frame-elements>:<can_id>.<can_dlc>.<can_data>\n");
209         fprintf(stderr, " - <instruction> is one of 'AND' 'OR' 'XOR' 'SET'\n");
210         fprintf(stderr, " - <can_frame-elements> is _one_ or _more_ of 'I'dentifier 'L'ength 'D'ata\n");
211         fprintf(stderr, " - <can_id> is an u32 value containing the CAN Identifier\n");
212         fprintf(stderr, " - <can_dlc> is an u8 value containing the data length code (0 .. 8)\n");
213         fprintf(stderr, " - <can_data> is always eight(!) u8 values containing the CAN frames data\n");
214         fprintf(stderr, "The max. four modifications are performed in the order AND -> OR -> XOR -> SET\n");
215         fprintf(stderr, "\n");
216         fprintf(stderr, "Example:\n");
217         fprintf(stderr, "%s -A -s can0 -d vcan3 -e -f 123:C00007FF -m SET:IL:333.4.1122334455667788\n", prg);
218         fprintf(stderr, "\n");
219         fprintf(stderr, "Supported CRC 8 profiles:\n");
220         fprintf(stderr, "Profile '%d' (1U8)       - add one additional u8 value\n", CGW_CRC8PRF_1U8);
221         fprintf(stderr, "Profile '%d' (16U8)      - add u8 value from table[16] indexed by (data[1] & 0xF)\n", CGW_CRC8PRF_16U8);
222         fprintf(stderr, "Profile '%d' (SFFID_XOR) - add u8 value (can_id & 0xFF) ^ (can_id >> 8 & 0xFF)\n", CGW_CRC8PRF_SFFID_XOR);
223         fprintf(stderr, "\n");
224 }
225
226 int b64hex(char *asc, unsigned char *bin, int len)
227 {
228         int i;
229
230         for (i = 0; i < len; i++) {
231                 if (!sscanf(asc+(i*2), "%2hhx", bin+i))
232                         return 1;       
233         }
234         return 0;
235 }
236
237 int parse_crc8_profile(char *optarg, struct cgw_csum_crc8 *crc8)
238 {
239         int ret = 1;
240         char *ptr;
241
242         if (sscanf(optarg, "%hhd:", &crc8->profile) != 1)
243                 return ret;
244
245         switch (crc8->profile) {
246
247         case  CGW_CRC8PRF_1U8:
248
249                 if (sscanf(optarg, "%hhd:%2hhx", &crc8->profile, &crc8->profile_data[0]) == 2)
250                         ret = 0;
251
252                 break;
253
254         case  CGW_CRC8PRF_16U8:
255
256                 ptr = strchr(optarg, ':');
257
258                 /* check if length contains 16 base64 hex values */
259                 if (ptr != NULL &&
260                     strlen(ptr) == strlen(":00112233445566778899AABBCCDDEEFF") &&
261                     b64hex(ptr+1, (unsigned char *)&crc8->profile_data[0], 16) == 0)
262                         ret = 0;
263
264                 break;
265
266         case  CGW_CRC8PRF_SFFID_XOR:
267
268                 /* no additional parameters needed */
269                 ret = 0;
270                 break;
271         }
272
273         return ret;
274 }
275
276 int parse_mod(char *optarg, struct modattr *modmsg)
277 {
278         char *ptr, *nptr;
279         char hexdata[17] = {0};
280
281         ptr = optarg;
282         nptr = strchr(ptr, ':');
283
284         if ((nptr - ptr > 3) || (nptr - ptr == 0))
285                 return 1;
286
287         if (!strncmp(ptr, "AND", 3))
288                 modmsg->instruction = CGW_MOD_AND;
289         else if (!strncmp(ptr, "OR", 2))
290                 modmsg->instruction = CGW_MOD_OR;
291         else if (!strncmp(ptr, "XOR", 3))
292                 modmsg->instruction = CGW_MOD_XOR;
293         else if (!strncmp(ptr, "SET", 3))
294                 modmsg->instruction = CGW_MOD_SET;
295         else
296                 return 2;
297
298         ptr = nptr+1;
299         nptr = strchr(ptr, ':');
300
301         if ((nptr - ptr > 3) || (nptr - ptr == 0))
302                 return 3;
303
304         modmsg->modtype = 0;
305
306         while (*ptr != ':') {
307
308                 switch (*ptr) {
309
310                 case 'I':
311                         modmsg->modtype |= CGW_MOD_ID;
312                         break;
313
314                 case 'L':
315                         modmsg->modtype |= CGW_MOD_DLC;
316                         break;
317
318                 case 'D':
319                         modmsg->modtype |= CGW_MOD_DATA;
320                         break;
321
322                 default:
323                         return 4;
324                 }
325                 ptr++;
326         }
327
328         if (sscanf(++ptr, "%x.%hhx.%16s", &modmsg->cf.can_id,
329                    (unsigned char *)&modmsg->cf.can_dlc, hexdata) != 3)
330                 return 5;
331
332         /* 4-bit masks can have values from 0 to 0xF */ 
333         if (modmsg->cf.can_dlc > 0xF)
334                 return 6;
335
336         /* but when setting CAN_DLC the value has to be limited to 8 */
337         if (modmsg->instruction == CGW_MOD_SET && modmsg->cf.can_dlc > 8)
338                 return 7;
339
340         if (strlen(hexdata) != 16)
341                 return 8;
342
343         if (b64hex(hexdata, &modmsg->cf.data[0], 8))
344                 return 9;
345
346         return 0; /* ok */
347 }
348
349 int parse_rtlist(char *prgname, unsigned char *rxbuf, int len)
350 {
351         char ifname[IF_NAMESIZE]; /* internface name for if_indextoname() */
352         struct rtcanmsg *rtc;
353         struct rtattr *rta;
354         struct nlmsghdr *nlh;
355         unsigned int src_ifindex = 0;
356         unsigned int dst_ifindex = 0;
357         __u32 handled, dropped, deleted;
358         int rtlen;
359
360
361         nlh = (struct nlmsghdr *)rxbuf;
362
363         while (1) {
364                 if (!NLMSG_OK(nlh, len))
365                         return 0;
366
367                 if (nlh->nlmsg_type == NLMSG_ERROR) {
368                         printf("NLMSG_ERROR\n");
369                         return 1;
370                 }
371
372                 if (nlh->nlmsg_type == NLMSG_DONE) {
373                         //printf("NLMSG_DONE\n");
374                         return 1;
375                 }
376
377                 rtc = (struct rtcanmsg *)NLMSG_DATA(nlh);
378                 if (rtc->can_family != AF_CAN) {
379                         printf("received msg from unknown family %d\n", rtc->can_family);
380                         return -EINVAL;
381                 }
382
383                 if (rtc->gwtype != CGW_TYPE_CAN_CAN) {
384                         printf("received msg with unknown gwtype %d\n", rtc->gwtype);
385                         return -EINVAL;
386                 }
387
388                 /*
389                  * print list in a representation that
390                  * can be used directly for start scripts.
391                  *
392                  * To order the mandatory and optional parameters in the
393                  * output string, the NLMSG is parsed twice.
394                  */
395
396                 handled = 0;
397                 dropped = 0;
398                 deleted = 0;
399                 src_ifindex = 0;
400                 dst_ifindex = 0;
401
402                 printf("%s -A ", basename(prgname));
403
404                 /* first parse for mandatory options */
405                 rta = (struct rtattr *) RTCAN_RTA(rtc);
406                 rtlen = RTCAN_PAYLOAD(nlh);
407                 for(;RTA_OK(rta, rtlen);rta=RTA_NEXT(rta,rtlen))
408                 {
409                         //printf("(A-%d)", rta->rta_type);
410                         switch(rta->rta_type) {
411
412                         case CGW_FILTER:
413                         case CGW_MOD_AND:
414                         case CGW_MOD_OR:
415                         case CGW_MOD_XOR:
416                         case CGW_MOD_SET:
417                         case CGW_CS_XOR:
418                         case CGW_CS_CRC8:
419                                 break;
420
421                         case CGW_SRC_IF:
422                                 src_ifindex = *(__u32 *)RTA_DATA(rta);
423                                 break;
424
425                         case CGW_DST_IF:
426                                 dst_ifindex = *(__u32 *)RTA_DATA(rta);
427                                 break;
428
429                         case CGW_HANDLED:
430                                 handled = *(__u32 *)RTA_DATA(rta);
431                                 break;
432
433                         case CGW_DROPPED:
434                                 dropped = *(__u32 *)RTA_DATA(rta);
435                                 break;
436
437                         case CGW_DELETED:
438                                 deleted = *(__u32 *)RTA_DATA(rta);
439                                 break;
440
441                         default:
442                                 printf("Unknown attribute %d!", rta->rta_type);
443                                 return -EINVAL;
444                                 break;
445                         }
446                 }
447
448
449                 printf("-s %s ", if_indextoname(src_ifindex, ifname));
450                 printf("-d %s ", if_indextoname(dst_ifindex, ifname));
451
452                 if (rtc->flags & CGW_FLAGS_CAN_ECHO)
453                         printf("-e ");
454
455                 if (rtc->flags & CGW_FLAGS_CAN_SRC_TSTAMP)
456                         printf("-t ");
457
458                 if (rtc->flags & CGW_FLAGS_CAN_IIF_TX_OK)
459                         printf("-i ");
460
461                 /* second parse for mod attributes */
462                 rta = (struct rtattr *) RTCAN_RTA(rtc);
463                 rtlen = RTCAN_PAYLOAD(nlh);
464                 for(;RTA_OK(rta, rtlen);rta=RTA_NEXT(rta,rtlen))
465                 {
466                         //printf("(B-%d)", rta->rta_type);
467                         switch(rta->rta_type) {
468
469                         case CGW_FILTER:
470                                 printfilter(RTA_DATA(rta));
471                                 break;
472
473                         case CGW_MOD_AND:
474                                 printmod("AND", RTA_DATA(rta));
475                                 break;
476
477                         case CGW_MOD_OR:
478                                 printmod("OR", RTA_DATA(rta));
479                                 break;
480
481                         case CGW_MOD_XOR:
482                                 printmod("XOR", RTA_DATA(rta));
483                                 break;
484
485                         case CGW_MOD_SET:
486                                 printmod("SET", RTA_DATA(rta));
487                                 break;
488
489                         case CGW_CS_XOR:
490                                 print_cs_xor((struct cgw_csum_xor *)RTA_DATA(rta));
491                                 break;
492
493                         case CGW_CS_CRC8:
494                                 print_cs_crc8((struct cgw_csum_crc8 *)RTA_DATA(rta));
495                                 break;
496
497                         case CGW_SRC_IF:
498                         case CGW_DST_IF:
499                         case CGW_HANDLED:
500                         case CGW_DROPPED:
501                         case CGW_DELETED:
502                                 break;
503
504                         default:
505                                 printf("Unknown attribute %d!", rta->rta_type);
506                                 return -EINVAL;
507                                 break;
508                         }
509                 }
510
511                 /* end of entry */
512                 printf("# %d handled %d dropped %d deleted\n",
513                        handled, dropped, deleted);
514
515                 /* jump to next NLMSG in the given buffer */
516                 nlh = NLMSG_NEXT(nlh, len);
517         }
518 }
519
520 int main(int argc, char **argv)
521 {
522         int s;
523         int err = 0;
524
525         int opt;
526         extern int optind, opterr, optopt;
527
528         int cmd = UNSPEC;
529         int have_filter = 0;
530         int have_cs_xor = 0;
531         int have_cs_crc8 = 0;
532
533         struct {
534                 struct nlmsghdr nh;
535                 struct rtcanmsg rtcan;
536                 char buf[600];
537
538         } req;
539
540         unsigned char rxbuf[8192]; /* netlink receive buffer */
541         struct nlmsghdr *nlh;
542         struct nlmsgerr *rte;
543         unsigned int src_ifindex = 0;
544         unsigned int dst_ifindex = 0;
545         __u16 flags = 0;
546         int len;
547
548         struct can_filter filter;
549         struct sockaddr_nl nladdr;
550
551         struct cgw_csum_xor cs_xor;
552         struct cgw_csum_crc8 cs_crc8;
553         char crc8tab[513] = {0};
554
555         struct modattr modmsg[CGW_MOD_FUNCS];
556         int modidx = 0;
557         int i;
558
559         memset(&req, 0, sizeof(req));
560         memset(&cs_xor, 0, sizeof(cs_xor));
561         memset(&cs_crc8, 0, sizeof(cs_crc8));
562
563         while ((opt = getopt(argc, argv, "ADFLs:d:teif:c:p:x:m:?")) != -1) {
564                 switch (opt) {
565
566                 case 'A':
567                         if (cmd == UNSPEC)
568                                 cmd = ADD;
569                         break;
570
571                 case 'D':
572                         if (cmd == UNSPEC)
573                                 cmd = DEL;
574                         break;
575
576                 case 'F':
577                         if (cmd == UNSPEC)
578                                 cmd = FLUSH;
579                         break;
580
581                 case 'L':
582                         if (cmd == UNSPEC)
583                                 cmd = LIST;
584                         break;
585
586                 case 's':
587                         src_ifindex = if_nametoindex(optarg);
588                         break;
589
590                 case 'd':
591                         dst_ifindex = if_nametoindex(optarg);
592                         break;
593
594                 case 't':
595                         flags |= CGW_FLAGS_CAN_SRC_TSTAMP;
596                         break;
597
598                 case 'e':
599                         flags |= CGW_FLAGS_CAN_ECHO;
600                         break;
601
602                 case 'i':
603                         flags |= CGW_FLAGS_CAN_IIF_TX_OK;
604                         break;
605
606                 case 'f':
607                         if (sscanf(optarg, "%x:%x", &filter.can_id,
608                                    &filter.can_mask) == 2) {
609                                 have_filter = 1;
610                         } else if (sscanf(optarg, "%x~%x", &filter.can_id,
611                                           &filter.can_mask) == 2) {
612                                 filter.can_id |= CAN_INV_FILTER;
613                                 have_filter = 1;
614                         } else {
615                                 printf("Bad filter definition '%s'.\n", optarg);
616                                 exit(1);
617                         }
618                         break;
619
620                 case 'x':
621                         if (sscanf(optarg, "%hhd:%hhd:%hhd:%hhx",
622                                    &cs_xor.from_idx, &cs_xor.to_idx,
623                                    &cs_xor.result_idx, &cs_xor.init_xor_val) == 4) {
624                                 have_cs_xor = 1;
625                         } else {
626                                 printf("Bad XOR checksum definition '%s'.\n", optarg);
627                                 exit(1);
628                         }
629                         break;
630
631                 case 'c':
632                         if ((sscanf(optarg, "%hhd:%hhd:%hhd:%hhx:%hhx:%512s",
633                                     &cs_crc8.from_idx, &cs_crc8.to_idx,
634                                     &cs_crc8.result_idx, &cs_crc8.init_crc_val,
635                                     &cs_crc8.final_xor_val, crc8tab) == 6) &&
636                             (strlen(crc8tab) == 512) &&
637                             (b64hex(crc8tab, (unsigned char *)&cs_crc8.crctab, 256) == 0)) {
638                                 have_cs_crc8 = 1;
639                         } else {
640                                 printf("Bad CRC8 checksum definition '%s'.\n", optarg);
641                                 exit(1);
642                         }
643                         break;
644
645                 case 'p':
646                         if (parse_crc8_profile(optarg, &cs_crc8)) {
647                                 printf("Bad CRC8 profile definition '%s'.\n", optarg);
648                                 exit(1);
649                         }
650                         break;
651
652                 case 'm':
653                         /* may be triggered by each of the CGW_MOD_FUNCS functions */
654                         if ((modidx < CGW_MOD_FUNCS) && (err = parse_mod(optarg, &modmsg[modidx++]))) {
655                                 printf("Problem %d with modification definition '%s'.\n", err, optarg);
656                                 exit(1);
657                         }
658                         break;
659
660                 case '?':
661                         print_usage(basename(argv[0]));
662                         exit(0);
663                         break;
664
665                 default:
666                         fprintf(stderr, "Unknown option %c\n", opt);
667                         print_usage(basename(argv[0]));
668                         exit(1);
669                         break;
670                 }
671         }
672
673         if ((argc - optind != 0) || (cmd == UNSPEC)) {
674                 print_usage(basename(argv[0]));
675                 exit(1);
676         }
677
678         if ((cmd == ADD || cmd == DEL) &&
679             ((!src_ifindex) || (!dst_ifindex))) {
680                 print_usage(basename(argv[0]));
681                 exit(1);
682         }
683
684         if (!modidx && (have_cs_crc8 || have_cs_xor)) {
685                 printf("-c or -x can only be used in conjunction with -m\n");
686                 exit(1);
687         }
688
689         s = socket(PF_NETLINK, SOCK_RAW, NETLINK_ROUTE);
690
691         switch (cmd) {
692
693         case ADD:
694                 req.nh.nlmsg_flags = NLM_F_REQUEST | NLM_F_ACK;
695                 req.nh.nlmsg_type  = RTM_NEWROUTE;
696                 break;
697
698         case DEL:
699                 req.nh.nlmsg_flags = NLM_F_REQUEST | NLM_F_ACK;
700                 req.nh.nlmsg_type  = RTM_DELROUTE;
701                 break;
702
703         case FLUSH:
704                 req.nh.nlmsg_flags = NLM_F_REQUEST | NLM_F_ACK;
705                 req.nh.nlmsg_type  = RTM_DELROUTE;
706                 /* if_index set to 0 => remove all entries */
707                 src_ifindex  = 0;
708                 dst_ifindex  = 0;
709                 break;
710
711         case LIST:
712                 req.nh.nlmsg_flags = NLM_F_REQUEST | NLM_F_DUMP;
713                 req.nh.nlmsg_type  = RTM_GETROUTE;
714                 break;
715
716         default:
717                 printf("This function is not yet implemented.\n");
718                 exit(1);
719                 break;
720         }
721
722         req.nh.nlmsg_len   = NLMSG_LENGTH(sizeof(struct rtcanmsg));
723         req.nh.nlmsg_seq   = 0;
724
725         req.rtcan.can_family  = AF_CAN;
726         req.rtcan.gwtype = CGW_TYPE_CAN_CAN;
727         req.rtcan.flags = flags;
728
729         addattr_l(&req.nh, sizeof(req), CGW_SRC_IF, &src_ifindex, sizeof(src_ifindex));
730         addattr_l(&req.nh, sizeof(req), CGW_DST_IF, &dst_ifindex, sizeof(dst_ifindex));
731
732         /* add new attributes here */
733
734         if (have_filter)
735                 addattr_l(&req.nh, sizeof(req), CGW_FILTER, &filter, sizeof(filter));
736
737         if (have_cs_crc8)
738                 addattr_l(&req.nh, sizeof(req), CGW_CS_CRC8, &cs_crc8, sizeof(cs_crc8));
739
740         if (have_cs_xor)
741                 addattr_l(&req.nh, sizeof(req), CGW_CS_XOR, &cs_xor, sizeof(cs_xor));
742
743         /*
744          * a better example code
745          * modmsg.modtype = CGW_MOD_ID;
746          * addattr_l(&req.n, sizeof(req), CGW_MOD_SET, &modmsg, CGW_MODATTR_LEN);
747          */
748
749         /* add up to CGW_MOD_FUNCS modification definitions */
750         for (i = 0; i < modidx; i++)
751                 addattr_l(&req.nh, sizeof(req), modmsg[i].instruction, &modmsg[i], CGW_MODATTR_LEN);
752
753         memset(&nladdr, 0, sizeof(nladdr));
754         nladdr.nl_family = AF_NETLINK;
755         nladdr.nl_pid    = 0;
756         nladdr.nl_groups = 0;
757
758         err = sendto(s, &req, req.nh.nlmsg_len, 0,
759                      (struct sockaddr*)&nladdr, sizeof(nladdr));
760         if (err < 0) {
761                 perror("netlink sendto");
762                 return err;
763         }
764
765         /* clean netlink receive buffer */
766         memset(rxbuf, 0x0, sizeof(rxbuf));
767
768         if (cmd != LIST) {
769
770                 /*
771                  * cmd == ADD || cmd == DEL || cmd == FLUSH
772                  *
773                  * Parse the requested netlink acknowledge return values.
774                  */
775
776                 err = recv(s, &rxbuf, sizeof(rxbuf), 0);
777                 if (err < 0) {
778                         perror("netlink recv");
779                         return err;
780                 }
781                 nlh = (struct nlmsghdr *)rxbuf;
782                 if (nlh->nlmsg_type != NLMSG_ERROR) {
783                         fprintf(stderr, "unexpected netlink answer of type %d\n", nlh->nlmsg_type);
784                         return -EINVAL;
785                 }
786                 rte = (struct nlmsgerr *)NLMSG_DATA(nlh);
787                 err = rte->error;
788                 if (err < 0)
789                         fprintf(stderr, "netlink error %d (%s)\n", err, strerror(abs(err)));
790
791         } else {
792
793                 /* cmd == LIST */
794
795                 while (1) {
796                         len = recv(s, &rxbuf, sizeof(rxbuf), 0);
797                         if (len < 0) {
798                                 perror("netlink recv");
799                                 return len;
800                         }
801 #if 0
802                         printf("received msg len %d\n", len);
803
804                         for (i = 0; i < len; i++)
805                                 printf("%02X ", rxbuf[i]);
806
807                         printf("\n");
808 #endif
809                         /* leave on errors or NLMSG_DONE */
810                         if (parse_rtlist(argv[0], rxbuf, len))
811                                 break;
812                 }
813         }
814
815         close(s);
816
817         return err;
818 }
819