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