]> rtime.felk.cvut.cz Git - sojka/can-utils.git/blob - cangw.c
Added cangw netlink gateway configuration tool.
[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 <sys/socket.h>
54 #include <net/if.h>
55 #include <linux/netlink.h>
56 #include <linux/rtnetlink.h>
57 #include <linux/can/gw.h>
58
59 enum {
60         UNSPEC,
61         ADD,
62         DEL,
63         FLUSH,
64         LIST
65 };
66
67 struct modattr {
68         struct can_frame cf;
69         __u8 modtype;
70         __u8 instruction;
71 } __attribute__((packed));
72
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 print_usage(char *prg)
98 {
99         fprintf(stderr, "\nUsage: %s [options]\n\n", prg);
100         fprintf(stderr, "Commands:  -A (add a new rule)\n");
101         fprintf(stderr, "           -D (delete a rule)             [not yet implemented]\n");
102         fprintf(stderr, "           -F (flush - delete all rules)  [not yet implemented]\n");
103         fprintf(stderr, "           -L (list all rules)            [not yet implemented]\n");
104         fprintf(stderr, "Mandatory: -s <src_dev>  (source netdevice)\n");
105         fprintf(stderr, "           -d <dst_dev>  (destination netdevice)\n");
106         fprintf(stderr, "Options:   -t (preserve src_dev rx timestamp)\n");
107         fprintf(stderr, "           -e (echo sent frames - recommended on vcanx)\n");
108         fprintf(stderr, "           -f <filter> (set CAN filter)\n");
109         fprintf(stderr, "           -m <mod> (set frame modifications)\n");
110         fprintf(stderr, "\nValues are given and expected in hexadecimal values. Leading 0s can be omitted.\n");
111         fprintf(stderr, "\n");
112         fprintf(stderr, "<filter> is a <value>:<mask> CAN identifier filter\n");
113         fprintf(stderr, "\n");
114         fprintf(stderr, "<mod> is a CAN frame modification instruction consisting of\n");
115         fprintf(stderr, "<instruction>:<can_frame-elements>:<can_id>.<can_dlc>.<can_data>\n");
116         fprintf(stderr, " - <instruction> is one of 'AND' 'OR' 'XOR' 'SET'\n");
117         fprintf(stderr, " - <can_frame-elements> is _one_ or _more_ of 'I'dentifier 'L'ength 'D'ata\n");
118         fprintf(stderr, " - <can_id> is an u32 value containing the CAN Identifier\n");
119         fprintf(stderr, " - <can_dlc> is an u8 value containing the data length code (0 .. 8)\n");
120         fprintf(stderr, " - <can_data> is always eight(!) u8 values containing the CAN frames data\n");
121         fprintf(stderr, "The instructions are performed in the order 'AND' -> 'OR' -> 'XOR' -> 'SET'\n");
122         fprintf(stderr, "\n");
123         fprintf(stderr, "Example:\n");
124         fprintf(stderr, "%s -A -s can0 -d vcan3 -f 123:C00007FF -m SET:IL:80000333.4.1122334455667788\n", prg);
125         fprintf(stderr, "\n");
126 }
127
128 int parse_mod(char *optarg, struct modattr *modmsg)
129 {
130         char *ptr, *nptr;
131         int i;
132
133         char hexdata[17] = {0};
134
135         ptr = optarg;
136         nptr = strchr(ptr, ':');
137
138         if ((nptr - ptr > 3) || (nptr - ptr == 0))
139                 return 1;
140
141         if (!strncmp(ptr, "AND", 3))
142                 modmsg->instruction = CGW_MOD_AND;
143         else if (!strncmp(ptr, "OR", 2))
144                 modmsg->instruction = CGW_MOD_OR;
145         else if (!strncmp(ptr, "XOR", 3))
146                 modmsg->instruction = CGW_MOD_XOR;
147         else if (!strncmp(ptr, "SET", 3))
148                 modmsg->instruction = CGW_MOD_SET;
149         else
150                 return 2;
151
152         ptr = nptr+1;
153         nptr = strchr(ptr, ':');
154
155         if ((nptr - ptr > 3) || (nptr - ptr == 0))
156                 return 3;
157
158         modmsg->modtype = 0;
159
160         while (*ptr != ':') {
161
162                 switch (*ptr) {
163
164                 case 'I':
165                         modmsg->modtype |= CGW_MOD_ID;
166                         break;
167
168                 case 'L':
169                         modmsg->modtype |= CGW_MOD_DLC;
170                         break;
171
172                 case 'D':
173                         modmsg->modtype |= CGW_MOD_DATA;
174                         break;
175
176                 default:
177                         return 4;
178                 }
179                 ptr++;
180         }
181
182         if ((sscanf(++ptr, "%lx.%hhd.%16s",
183                     (long unsigned int *)&modmsg->cf.can_id,
184                     (unsigned char *)&modmsg->cf.can_dlc, hexdata) != 3) ||
185             (modmsg->cf.can_dlc > 8))
186                 return 5;
187
188         if (strlen(hexdata) != 16)
189                 return 6;
190
191         for (i = 0; i < 8; i++) {
192                 if (!sscanf(&hexdata[i*2], "%2hhx", &modmsg->cf.data[i]))
193                         return 7;       
194         }
195
196         return 0; /* ok */
197 }
198
199 int main(int argc, char **argv)
200 {
201         int s;
202         int err = 0;
203
204         int opt;
205         extern int optind, opterr, optopt;
206
207         int cmd = UNSPEC;
208         int have_filter = 0;
209
210         struct {
211                 struct nlmsghdr n;
212                 struct rtcanmsg r;
213                 char buf[200];
214
215         } req;
216
217         struct can_filter filter;
218         struct sockaddr_nl nladdr;
219
220         struct modattr modmsg[CGW_MOD_FUNCS];
221         int modidx = 0;
222         int i;
223
224         memset(&req, 0, sizeof(req));
225
226         while ((opt = getopt(argc, argv, "ADFLs:d:tef:m:?")) != -1) {
227                 switch (opt) {
228
229                 case 'A':
230                         if (cmd == UNSPEC)
231                                 cmd = ADD;
232                         break;
233
234                 case 'D':
235                         if (cmd == UNSPEC)
236                                 cmd = DEL;
237                         break;
238
239                 case 'F':
240                         if (cmd == UNSPEC)
241                                 cmd = FLUSH;
242                         break;
243
244                 case 'L':
245                         if (cmd == UNSPEC)
246                                 cmd = LIST;
247                         break;
248
249                 case 's':
250                         req.r.src_ifindex = if_nametoindex(optarg);
251                         break;
252
253                 case 'd':
254                         req.r.dst_ifindex = if_nametoindex(optarg);
255                         break;
256
257                 case 't':
258                         req.r.can_txflags |= CAN_GW_TXFLAGS_SRC_TSTAMP;
259                         break;
260
261                 case 'e':
262                         req.r.can_txflags |= CAN_GW_TXFLAGS_ECHO;
263                         break;
264
265                 case 'f':
266                         if (sscanf(optarg, "%lx:%lx",
267                                    (long unsigned int *)&filter.can_id, 
268                                    (long unsigned int *)&filter.can_mask) == 2) {
269                                 have_filter = 1;
270                         } else {
271                                 printf("Bad filter definition '%s'.\n", optarg);
272                                 exit(1);
273                         }
274                         break;
275
276                 case 'm':
277                         /* may be triggered by each of the CGW_MOD_FUNCS functions */
278                         if ((modidx < CGW_MOD_FUNCS) && (err = parse_mod(optarg, &modmsg[modidx++]))) {
279                                 printf("Problem %d with modification definition '%s'.\n", err, optarg);
280                                 exit(1);
281                         }
282                         break;
283
284                 case '?':
285                         print_usage(basename(argv[0]));
286                         exit(0);
287                         break;
288
289                 default:
290                         fprintf(stderr, "Unknown option %c\n", opt);
291                         print_usage(basename(argv[0]));
292                         exit(1);
293                         break;
294                 }
295         }
296
297         if ((argc - optind != 0) || (cmd == UNSPEC) ||
298             (!req.r.src_ifindex) || (!req.r.dst_ifindex)) {
299                 print_usage(basename(argv[0]));
300                 exit(1);
301         }
302
303         s = socket(PF_NETLINK, SOCK_RAW, NETLINK_ROUTE);
304
305         switch (cmd) {
306
307         case ADD:
308                 req.n.nlmsg_flags = NLM_F_REQUEST | NLM_F_CREATE | NLM_F_EXCL;
309                 req.n.nlmsg_type  = RTM_NEWROUTE;
310                 break;
311
312         default:
313                 printf("This function is not yet implemented.\n");
314                 exit(1);
315                 break;
316         }
317
318         req.n.nlmsg_len   = NLMSG_LENGTH(sizeof(struct rtcanmsg));
319         req.n.nlmsg_seq   = 0;
320
321         req.r.can_family  = AF_CAN;
322
323         /* add new attributes here */
324
325         if (have_filter)
326                 addattr_l(&req.n, sizeof(req), CGW_FILTER, &filter, sizeof(filter));
327
328         // a better example code
329         // modmsg.modtype = CGW_MOD_ID;
330         // addattr_l(&req.n, sizeof(req), CGW_MOD_SET, &modmsg, CGW_MODATTR_LEN);
331
332         /* add up to CGW_MOD_FUNCS modification definitions */
333         for (i = 0; i < modidx; i++)
334                 addattr_l(&req.n, sizeof(req), modmsg[i].instruction, &modmsg[i], CGW_MODATTR_LEN);
335
336         memset(&nladdr, 0, sizeof(nladdr));
337         nladdr.nl_family = AF_NETLINK;
338         nladdr.nl_pid    = 0;
339         nladdr.nl_groups = 0;
340
341         err = sendto(s, &req, req.n.nlmsg_len, 0,
342                      (struct sockaddr*)&nladdr, sizeof(nladdr));
343
344         if (err < 0)
345                 perror("PF_CAN netlink gateway answered ");
346
347         close(s);
348
349         return err;
350 }
351