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