• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * gw.c - CAN frame Gateway/Router/Bridge with netlink interface
3  *
4  * Copyright (c) 2011 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  */
41 
42 #include <linux/module.h>
43 #include <linux/init.h>
44 #include <linux/types.h>
45 #include <linux/kernel.h>
46 #include <linux/list.h>
47 #include <linux/spinlock.h>
48 #include <linux/rcupdate.h>
49 #include <linux/rculist.h>
50 #include <linux/net.h>
51 #include <linux/netdevice.h>
52 #include <linux/if_arp.h>
53 #include <linux/skbuff.h>
54 #include <linux/can.h>
55 #include <linux/can/core.h>
56 #include <linux/can/skb.h>
57 #include <linux/can/gw.h>
58 #include <net/rtnetlink.h>
59 #include <net/net_namespace.h>
60 #include <net/sock.h>
61 
62 #define CAN_GW_VERSION "20130117"
63 #define CAN_GW_NAME "can-gw"
64 
65 MODULE_DESCRIPTION("PF_CAN netlink gateway");
66 MODULE_LICENSE("Dual BSD/GPL");
67 MODULE_AUTHOR("Oliver Hartkopp <oliver.hartkopp@volkswagen.de>");
68 MODULE_ALIAS(CAN_GW_NAME);
69 
70 #define CGW_MIN_HOPS 1
71 #define CGW_MAX_HOPS 6
72 #define CGW_DEFAULT_HOPS 1
73 
74 static unsigned int max_hops __read_mostly = CGW_DEFAULT_HOPS;
75 module_param(max_hops, uint, S_IRUGO);
76 MODULE_PARM_DESC(max_hops,
77 		 "maximum " CAN_GW_NAME " routing hops for CAN frames "
78 		 "(valid values: " __stringify(CGW_MIN_HOPS) "-"
79 		 __stringify(CGW_MAX_HOPS) " hops, "
80 		 "default: " __stringify(CGW_DEFAULT_HOPS) ")");
81 
82 static HLIST_HEAD(cgw_list);
83 static struct notifier_block notifier;
84 
85 static struct kmem_cache *cgw_cache __read_mostly;
86 
87 /* structure that contains the (on-the-fly) CAN frame modifications */
88 struct cf_mod {
89 	struct {
90 		struct can_frame and;
91 		struct can_frame or;
92 		struct can_frame xor;
93 		struct can_frame set;
94 	} modframe;
95 	struct {
96 		u8 and;
97 		u8 or;
98 		u8 xor;
99 		u8 set;
100 	} modtype;
101 	void (*modfunc[MAX_MODFUNCTIONS])(struct can_frame *cf,
102 					  struct cf_mod *mod);
103 
104 	/* CAN frame checksum calculation after CAN frame modifications */
105 	struct {
106 		struct cgw_csum_xor xor;
107 		struct cgw_csum_crc8 crc8;
108 	} csum;
109 	struct {
110 		void (*xor)(struct can_frame *cf, struct cgw_csum_xor *xor);
111 		void (*crc8)(struct can_frame *cf, struct cgw_csum_crc8 *crc8);
112 	} csumfunc;
113 	u32 uid;
114 };
115 
116 
117 /*
118  * So far we just support CAN -> CAN routing and frame modifications.
119  *
120  * The internal can_can_gw structure contains data and attributes for
121  * a CAN -> CAN gateway job.
122  */
123 struct can_can_gw {
124 	struct can_filter filter;
125 	int src_idx;
126 	int dst_idx;
127 };
128 
129 /* list entry for CAN gateways jobs */
130 struct cgw_job {
131 	struct hlist_node list;
132 	struct rcu_head rcu;
133 	u32 handled_frames;
134 	u32 dropped_frames;
135 	u32 deleted_frames;
136 	struct cf_mod mod;
137 	union {
138 		/* CAN frame data source */
139 		struct net_device *dev;
140 	} src;
141 	union {
142 		/* CAN frame data destination */
143 		struct net_device *dev;
144 	} dst;
145 	union {
146 		struct can_can_gw ccgw;
147 		/* tbc */
148 	};
149 	u8 gwtype;
150 	u8 limit_hops;
151 	u16 flags;
152 };
153 
154 /* modification functions that are invoked in the hot path in can_can_gw_rcv */
155 
156 #define MODFUNC(func, op) static void func(struct can_frame *cf, \
157 					   struct cf_mod *mod) { op ; }
158 
159 MODFUNC(mod_and_id, cf->can_id &= mod->modframe.and.can_id)
160 MODFUNC(mod_and_dlc, cf->can_dlc &= mod->modframe.and.can_dlc)
161 MODFUNC(mod_and_data, *(u64 *)cf->data &= *(u64 *)mod->modframe.and.data)
162 MODFUNC(mod_or_id, cf->can_id |= mod->modframe.or.can_id)
163 MODFUNC(mod_or_dlc, cf->can_dlc |= mod->modframe.or.can_dlc)
164 MODFUNC(mod_or_data, *(u64 *)cf->data |= *(u64 *)mod->modframe.or.data)
165 MODFUNC(mod_xor_id, cf->can_id ^= mod->modframe.xor.can_id)
166 MODFUNC(mod_xor_dlc, cf->can_dlc ^= mod->modframe.xor.can_dlc)
167 MODFUNC(mod_xor_data, *(u64 *)cf->data ^= *(u64 *)mod->modframe.xor.data)
168 MODFUNC(mod_set_id, cf->can_id = mod->modframe.set.can_id)
169 MODFUNC(mod_set_dlc, cf->can_dlc = mod->modframe.set.can_dlc)
170 MODFUNC(mod_set_data, *(u64 *)cf->data = *(u64 *)mod->modframe.set.data)
171 
canframecpy(struct can_frame * dst,struct can_frame * src)172 static inline void canframecpy(struct can_frame *dst, struct can_frame *src)
173 {
174 	/*
175 	 * Copy the struct members separately to ensure that no uninitialized
176 	 * data are copied in the 3 bytes hole of the struct. This is needed
177 	 * to make easy compares of the data in the struct cf_mod.
178 	 */
179 
180 	dst->can_id = src->can_id;
181 	dst->can_dlc = src->can_dlc;
182 	*(u64 *)dst->data = *(u64 *)src->data;
183 }
184 
cgw_chk_csum_parms(s8 fr,s8 to,s8 re)185 static int cgw_chk_csum_parms(s8 fr, s8 to, s8 re)
186 {
187 	/*
188 	 * absolute dlc values 0 .. 7 => 0 .. 7, e.g. data [0]
189 	 * relative to received dlc -1 .. -8 :
190 	 * e.g. for received dlc = 8
191 	 * -1 => index = 7 (data[7])
192 	 * -3 => index = 5 (data[5])
193 	 * -8 => index = 0 (data[0])
194 	 */
195 
196 	if (fr > -9 && fr < 8 &&
197 	    to > -9 && to < 8 &&
198 	    re > -9 && re < 8)
199 		return 0;
200 	else
201 		return -EINVAL;
202 }
203 
calc_idx(int idx,int rx_dlc)204 static inline int calc_idx(int idx, int rx_dlc)
205 {
206 	if (idx < 0)
207 		return rx_dlc + idx;
208 	else
209 		return idx;
210 }
211 
cgw_csum_xor_rel(struct can_frame * cf,struct cgw_csum_xor * xor)212 static void cgw_csum_xor_rel(struct can_frame *cf, struct cgw_csum_xor *xor)
213 {
214 	int from = calc_idx(xor->from_idx, cf->can_dlc);
215 	int to = calc_idx(xor->to_idx, cf->can_dlc);
216 	int res = calc_idx(xor->result_idx, cf->can_dlc);
217 	u8 val = xor->init_xor_val;
218 	int i;
219 
220 	if (from < 0 || to < 0 || res < 0)
221 		return;
222 
223 	if (from <= to) {
224 		for (i = from; i <= to; i++)
225 			val ^= cf->data[i];
226 	} else {
227 		for (i = from; i >= to; i--)
228 			val ^= cf->data[i];
229 	}
230 
231 	cf->data[res] = val;
232 }
233 
cgw_csum_xor_pos(struct can_frame * cf,struct cgw_csum_xor * xor)234 static void cgw_csum_xor_pos(struct can_frame *cf, struct cgw_csum_xor *xor)
235 {
236 	u8 val = xor->init_xor_val;
237 	int i;
238 
239 	for (i = xor->from_idx; i <= xor->to_idx; i++)
240 		val ^= cf->data[i];
241 
242 	cf->data[xor->result_idx] = val;
243 }
244 
cgw_csum_xor_neg(struct can_frame * cf,struct cgw_csum_xor * xor)245 static void cgw_csum_xor_neg(struct can_frame *cf, struct cgw_csum_xor *xor)
246 {
247 	u8 val = xor->init_xor_val;
248 	int i;
249 
250 	for (i = xor->from_idx; i >= xor->to_idx; i--)
251 		val ^= cf->data[i];
252 
253 	cf->data[xor->result_idx] = val;
254 }
255 
cgw_csum_crc8_rel(struct can_frame * cf,struct cgw_csum_crc8 * crc8)256 static void cgw_csum_crc8_rel(struct can_frame *cf, struct cgw_csum_crc8 *crc8)
257 {
258 	int from = calc_idx(crc8->from_idx, cf->can_dlc);
259 	int to = calc_idx(crc8->to_idx, cf->can_dlc);
260 	int res = calc_idx(crc8->result_idx, cf->can_dlc);
261 	u8 crc = crc8->init_crc_val;
262 	int i;
263 
264 	if (from < 0 || to < 0 || res < 0)
265 		return;
266 
267 	if (from <= to) {
268 		for (i = crc8->from_idx; i <= crc8->to_idx; i++)
269 			crc = crc8->crctab[crc^cf->data[i]];
270 	} else {
271 		for (i = crc8->from_idx; i >= crc8->to_idx; i--)
272 			crc = crc8->crctab[crc^cf->data[i]];
273 	}
274 
275 	switch (crc8->profile) {
276 
277 	case CGW_CRC8PRF_1U8:
278 		crc = crc8->crctab[crc^crc8->profile_data[0]];
279 		break;
280 
281 	case  CGW_CRC8PRF_16U8:
282 		crc = crc8->crctab[crc^crc8->profile_data[cf->data[1] & 0xF]];
283 		break;
284 
285 	case CGW_CRC8PRF_SFFID_XOR:
286 		crc = crc8->crctab[crc^(cf->can_id & 0xFF)^
287 				   (cf->can_id >> 8 & 0xFF)];
288 		break;
289 
290 	}
291 
292 	cf->data[crc8->result_idx] = crc^crc8->final_xor_val;
293 }
294 
cgw_csum_crc8_pos(struct can_frame * cf,struct cgw_csum_crc8 * crc8)295 static void cgw_csum_crc8_pos(struct can_frame *cf, struct cgw_csum_crc8 *crc8)
296 {
297 	u8 crc = crc8->init_crc_val;
298 	int i;
299 
300 	for (i = crc8->from_idx; i <= crc8->to_idx; i++)
301 		crc = crc8->crctab[crc^cf->data[i]];
302 
303 	switch (crc8->profile) {
304 
305 	case CGW_CRC8PRF_1U8:
306 		crc = crc8->crctab[crc^crc8->profile_data[0]];
307 		break;
308 
309 	case  CGW_CRC8PRF_16U8:
310 		crc = crc8->crctab[crc^crc8->profile_data[cf->data[1] & 0xF]];
311 		break;
312 
313 	case CGW_CRC8PRF_SFFID_XOR:
314 		crc = crc8->crctab[crc^(cf->can_id & 0xFF)^
315 				   (cf->can_id >> 8 & 0xFF)];
316 		break;
317 	}
318 
319 	cf->data[crc8->result_idx] = crc^crc8->final_xor_val;
320 }
321 
cgw_csum_crc8_neg(struct can_frame * cf,struct cgw_csum_crc8 * crc8)322 static void cgw_csum_crc8_neg(struct can_frame *cf, struct cgw_csum_crc8 *crc8)
323 {
324 	u8 crc = crc8->init_crc_val;
325 	int i;
326 
327 	for (i = crc8->from_idx; i >= crc8->to_idx; i--)
328 		crc = crc8->crctab[crc^cf->data[i]];
329 
330 	switch (crc8->profile) {
331 
332 	case CGW_CRC8PRF_1U8:
333 		crc = crc8->crctab[crc^crc8->profile_data[0]];
334 		break;
335 
336 	case  CGW_CRC8PRF_16U8:
337 		crc = crc8->crctab[crc^crc8->profile_data[cf->data[1] & 0xF]];
338 		break;
339 
340 	case CGW_CRC8PRF_SFFID_XOR:
341 		crc = crc8->crctab[crc^(cf->can_id & 0xFF)^
342 				   (cf->can_id >> 8 & 0xFF)];
343 		break;
344 	}
345 
346 	cf->data[crc8->result_idx] = crc^crc8->final_xor_val;
347 }
348 
349 /* the receive & process & send function */
can_can_gw_rcv(struct sk_buff * skb,void * data)350 static void can_can_gw_rcv(struct sk_buff *skb, void *data)
351 {
352 	struct cgw_job *gwj = (struct cgw_job *)data;
353 	struct can_frame *cf;
354 	struct sk_buff *nskb;
355 	int modidx = 0;
356 
357 	/*
358 	 * Do not handle CAN frames routed more than 'max_hops' times.
359 	 * In general we should never catch this delimiter which is intended
360 	 * to cover a misconfiguration protection (e.g. circular CAN routes).
361 	 *
362 	 * The Controller Area Network controllers only accept CAN frames with
363 	 * correct CRCs - which are not visible in the controller registers.
364 	 * According to skbuff.h documentation the csum_start element for IP
365 	 * checksums is undefined/unused when ip_summed == CHECKSUM_UNNECESSARY.
366 	 * Only CAN skbs can be processed here which already have this property.
367 	 */
368 
369 #define cgw_hops(skb) ((skb)->csum_start)
370 
371 	BUG_ON(skb->ip_summed != CHECKSUM_UNNECESSARY);
372 
373 	if (cgw_hops(skb) >= max_hops) {
374 		/* indicate deleted frames due to misconfiguration */
375 		gwj->deleted_frames++;
376 		return;
377 	}
378 
379 	if (!(gwj->dst.dev->flags & IFF_UP)) {
380 		gwj->dropped_frames++;
381 		return;
382 	}
383 
384 	/* is sending the skb back to the incoming interface not allowed? */
385 	if (!(gwj->flags & CGW_FLAGS_CAN_IIF_TX_OK) &&
386 	    can_skb_prv(skb)->ifindex == gwj->dst.dev->ifindex)
387 		return;
388 
389 	/*
390 	 * clone the given skb, which has not been done in can_rcv()
391 	 *
392 	 * When there is at least one modification function activated,
393 	 * we need to copy the skb as we want to modify skb->data.
394 	 */
395 	if (gwj->mod.modfunc[0])
396 		nskb = skb_copy(skb, GFP_ATOMIC);
397 	else
398 		nskb = skb_clone(skb, GFP_ATOMIC);
399 
400 	if (!nskb) {
401 		gwj->dropped_frames++;
402 		return;
403 	}
404 
405 	/* put the incremented hop counter in the cloned skb */
406 	cgw_hops(nskb) = cgw_hops(skb) + 1;
407 
408 	/* first processing of this CAN frame -> adjust to private hop limit */
409 	if (gwj->limit_hops && cgw_hops(nskb) == 1)
410 		cgw_hops(nskb) = max_hops - gwj->limit_hops + 1;
411 
412 	nskb->dev = gwj->dst.dev;
413 
414 	/* pointer to modifiable CAN frame */
415 	cf = (struct can_frame *)nskb->data;
416 
417 	/* perform preprocessed modification functions if there are any */
418 	while (modidx < MAX_MODFUNCTIONS && gwj->mod.modfunc[modidx])
419 		(*gwj->mod.modfunc[modidx++])(cf, &gwj->mod);
420 
421 	/* Has the CAN frame been modified? */
422 	if (modidx) {
423 		/* get available space for the processed CAN frame type */
424 		int max_len = nskb->len - offsetof(struct can_frame, data);
425 
426 		/* dlc may have changed, make sure it fits to the CAN frame */
427 		if (cf->can_dlc > max_len)
428 			goto out_delete;
429 
430 		/* check for checksum updates in classic CAN length only */
431 		if (gwj->mod.csumfunc.crc8) {
432 			if (cf->can_dlc > 8)
433 				goto out_delete;
434 
435 			(*gwj->mod.csumfunc.crc8)(cf, &gwj->mod.csum.crc8);
436 		}
437 
438 		if (gwj->mod.csumfunc.xor) {
439 			if (cf->can_dlc > 8)
440 				goto out_delete;
441 
442 			(*gwj->mod.csumfunc.xor)(cf, &gwj->mod.csum.xor);
443 		}
444 	}
445 
446 	/* clear the skb timestamp if not configured the other way */
447 	if (!(gwj->flags & CGW_FLAGS_CAN_SRC_TSTAMP))
448 		nskb->tstamp.tv64 = 0;
449 
450 	/* send to netdevice */
451 	if (can_send(nskb, gwj->flags & CGW_FLAGS_CAN_ECHO))
452 		gwj->dropped_frames++;
453 	else
454 		gwj->handled_frames++;
455 
456 	return;
457 
458  out_delete:
459 	/* delete frame due to misconfiguration */
460 	gwj->deleted_frames++;
461 	kfree_skb(nskb);
462 	return;
463 }
464 
cgw_register_filter(struct cgw_job * gwj)465 static inline int cgw_register_filter(struct cgw_job *gwj)
466 {
467 	return can_rx_register(gwj->src.dev, gwj->ccgw.filter.can_id,
468 			       gwj->ccgw.filter.can_mask, can_can_gw_rcv,
469 			       gwj, "gw", NULL);
470 }
471 
cgw_unregister_filter(struct cgw_job * gwj)472 static inline void cgw_unregister_filter(struct cgw_job *gwj)
473 {
474 	can_rx_unregister(gwj->src.dev, gwj->ccgw.filter.can_id,
475 			  gwj->ccgw.filter.can_mask, can_can_gw_rcv, gwj);
476 }
477 
cgw_notifier(struct notifier_block * nb,unsigned long msg,void * ptr)478 static int cgw_notifier(struct notifier_block *nb,
479 			unsigned long msg, void *ptr)
480 {
481 	struct net_device *dev = netdev_notifier_info_to_dev(ptr);
482 
483 	if (!net_eq(dev_net(dev), &init_net))
484 		return NOTIFY_DONE;
485 	if (dev->type != ARPHRD_CAN)
486 		return NOTIFY_DONE;
487 
488 	if (msg == NETDEV_UNREGISTER) {
489 
490 		struct cgw_job *gwj = NULL;
491 		struct hlist_node *nx;
492 
493 		ASSERT_RTNL();
494 
495 		hlist_for_each_entry_safe(gwj, nx, &cgw_list, list) {
496 
497 			if (gwj->src.dev == dev || gwj->dst.dev == dev) {
498 				hlist_del(&gwj->list);
499 				cgw_unregister_filter(gwj);
500 				synchronize_rcu();
501 				kmem_cache_free(cgw_cache, gwj);
502 			}
503 		}
504 	}
505 
506 	return NOTIFY_DONE;
507 }
508 
cgw_put_job(struct sk_buff * skb,struct cgw_job * gwj,int type,u32 pid,u32 seq,int flags)509 static int cgw_put_job(struct sk_buff *skb, struct cgw_job *gwj, int type,
510 		       u32 pid, u32 seq, int flags)
511 {
512 	struct cgw_frame_mod mb;
513 	struct rtcanmsg *rtcan;
514 	struct nlmsghdr *nlh;
515 
516 	nlh = nlmsg_put(skb, pid, seq, type, sizeof(*rtcan), flags);
517 	if (!nlh)
518 		return -EMSGSIZE;
519 
520 	rtcan = nlmsg_data(nlh);
521 	rtcan->can_family = AF_CAN;
522 	rtcan->gwtype = gwj->gwtype;
523 	rtcan->flags = gwj->flags;
524 
525 	/* add statistics if available */
526 
527 	if (gwj->handled_frames) {
528 		if (nla_put_u32(skb, CGW_HANDLED, gwj->handled_frames) < 0)
529 			goto cancel;
530 	}
531 
532 	if (gwj->dropped_frames) {
533 		if (nla_put_u32(skb, CGW_DROPPED, gwj->dropped_frames) < 0)
534 			goto cancel;
535 	}
536 
537 	if (gwj->deleted_frames) {
538 		if (nla_put_u32(skb, CGW_DELETED, gwj->deleted_frames) < 0)
539 			goto cancel;
540 	}
541 
542 	/* check non default settings of attributes */
543 
544 	if (gwj->limit_hops) {
545 		if (nla_put_u8(skb, CGW_LIM_HOPS, gwj->limit_hops) < 0)
546 			goto cancel;
547 	}
548 
549 	if (gwj->mod.modtype.and) {
550 		memcpy(&mb.cf, &gwj->mod.modframe.and, sizeof(mb.cf));
551 		mb.modtype = gwj->mod.modtype.and;
552 		if (nla_put(skb, CGW_MOD_AND, sizeof(mb), &mb) < 0)
553 			goto cancel;
554 	}
555 
556 	if (gwj->mod.modtype.or) {
557 		memcpy(&mb.cf, &gwj->mod.modframe.or, sizeof(mb.cf));
558 		mb.modtype = gwj->mod.modtype.or;
559 		if (nla_put(skb, CGW_MOD_OR, sizeof(mb), &mb) < 0)
560 			goto cancel;
561 	}
562 
563 	if (gwj->mod.modtype.xor) {
564 		memcpy(&mb.cf, &gwj->mod.modframe.xor, sizeof(mb.cf));
565 		mb.modtype = gwj->mod.modtype.xor;
566 		if (nla_put(skb, CGW_MOD_XOR, sizeof(mb), &mb) < 0)
567 			goto cancel;
568 	}
569 
570 	if (gwj->mod.modtype.set) {
571 		memcpy(&mb.cf, &gwj->mod.modframe.set, sizeof(mb.cf));
572 		mb.modtype = gwj->mod.modtype.set;
573 		if (nla_put(skb, CGW_MOD_SET, sizeof(mb), &mb) < 0)
574 			goto cancel;
575 	}
576 
577 	if (gwj->mod.uid) {
578 		if (nla_put_u32(skb, CGW_MOD_UID, gwj->mod.uid) < 0)
579 			goto cancel;
580 	}
581 
582 	if (gwj->mod.csumfunc.crc8) {
583 		if (nla_put(skb, CGW_CS_CRC8, CGW_CS_CRC8_LEN,
584 			    &gwj->mod.csum.crc8) < 0)
585 			goto cancel;
586 	}
587 
588 	if (gwj->mod.csumfunc.xor) {
589 		if (nla_put(skb, CGW_CS_XOR, CGW_CS_XOR_LEN,
590 			    &gwj->mod.csum.xor) < 0)
591 			goto cancel;
592 	}
593 
594 	if (gwj->gwtype == CGW_TYPE_CAN_CAN) {
595 
596 		if (gwj->ccgw.filter.can_id || gwj->ccgw.filter.can_mask) {
597 			if (nla_put(skb, CGW_FILTER, sizeof(struct can_filter),
598 				    &gwj->ccgw.filter) < 0)
599 				goto cancel;
600 		}
601 
602 		if (nla_put_u32(skb, CGW_SRC_IF, gwj->ccgw.src_idx) < 0)
603 			goto cancel;
604 
605 		if (nla_put_u32(skb, CGW_DST_IF, gwj->ccgw.dst_idx) < 0)
606 			goto cancel;
607 	}
608 
609 	nlmsg_end(skb, nlh);
610 	return 0;
611 
612 cancel:
613 	nlmsg_cancel(skb, nlh);
614 	return -EMSGSIZE;
615 }
616 
617 /* Dump information about all CAN gateway jobs, in response to RTM_GETROUTE */
cgw_dump_jobs(struct sk_buff * skb,struct netlink_callback * cb)618 static int cgw_dump_jobs(struct sk_buff *skb, struct netlink_callback *cb)
619 {
620 	struct cgw_job *gwj = NULL;
621 	int idx = 0;
622 	int s_idx = cb->args[0];
623 
624 	rcu_read_lock();
625 	hlist_for_each_entry_rcu(gwj, &cgw_list, list) {
626 		if (idx < s_idx)
627 			goto cont;
628 
629 		if (cgw_put_job(skb, gwj, RTM_NEWROUTE, NETLINK_CB(cb->skb).portid,
630 		    cb->nlh->nlmsg_seq, NLM_F_MULTI) < 0)
631 			break;
632 cont:
633 		idx++;
634 	}
635 	rcu_read_unlock();
636 
637 	cb->args[0] = idx;
638 
639 	return skb->len;
640 }
641 
642 static const struct nla_policy cgw_policy[CGW_MAX+1] = {
643 	[CGW_MOD_AND]	= { .len = sizeof(struct cgw_frame_mod) },
644 	[CGW_MOD_OR]	= { .len = sizeof(struct cgw_frame_mod) },
645 	[CGW_MOD_XOR]	= { .len = sizeof(struct cgw_frame_mod) },
646 	[CGW_MOD_SET]	= { .len = sizeof(struct cgw_frame_mod) },
647 	[CGW_CS_XOR]	= { .len = sizeof(struct cgw_csum_xor) },
648 	[CGW_CS_CRC8]	= { .len = sizeof(struct cgw_csum_crc8) },
649 	[CGW_SRC_IF]	= { .type = NLA_U32 },
650 	[CGW_DST_IF]	= { .type = NLA_U32 },
651 	[CGW_FILTER]	= { .len = sizeof(struct can_filter) },
652 	[CGW_LIM_HOPS]	= { .type = NLA_U8 },
653 	[CGW_MOD_UID]	= { .type = NLA_U32 },
654 };
655 
656 /* check for common and gwtype specific attributes */
cgw_parse_attr(struct nlmsghdr * nlh,struct cf_mod * mod,u8 gwtype,void * gwtypeattr,u8 * limhops)657 static int cgw_parse_attr(struct nlmsghdr *nlh, struct cf_mod *mod,
658 			  u8 gwtype, void *gwtypeattr, u8 *limhops)
659 {
660 	struct nlattr *tb[CGW_MAX+1];
661 	struct cgw_frame_mod mb;
662 	int modidx = 0;
663 	int err = 0;
664 
665 	/* initialize modification & checksum data space */
666 	memset(mod, 0, sizeof(*mod));
667 
668 	err = nlmsg_parse(nlh, sizeof(struct rtcanmsg), tb, CGW_MAX,
669 			  cgw_policy);
670 	if (err < 0)
671 		return err;
672 
673 	if (tb[CGW_LIM_HOPS]) {
674 		*limhops = nla_get_u8(tb[CGW_LIM_HOPS]);
675 
676 		if (*limhops < 1 || *limhops > max_hops)
677 			return -EINVAL;
678 	}
679 
680 	/* check for AND/OR/XOR/SET modifications */
681 
682 	if (tb[CGW_MOD_AND]) {
683 		nla_memcpy(&mb, tb[CGW_MOD_AND], CGW_MODATTR_LEN);
684 
685 		canframecpy(&mod->modframe.and, &mb.cf);
686 		mod->modtype.and = mb.modtype;
687 
688 		if (mb.modtype & CGW_MOD_ID)
689 			mod->modfunc[modidx++] = mod_and_id;
690 
691 		if (mb.modtype & CGW_MOD_DLC)
692 			mod->modfunc[modidx++] = mod_and_dlc;
693 
694 		if (mb.modtype & CGW_MOD_DATA)
695 			mod->modfunc[modidx++] = mod_and_data;
696 	}
697 
698 	if (tb[CGW_MOD_OR]) {
699 		nla_memcpy(&mb, tb[CGW_MOD_OR], CGW_MODATTR_LEN);
700 
701 		canframecpy(&mod->modframe.or, &mb.cf);
702 		mod->modtype.or = mb.modtype;
703 
704 		if (mb.modtype & CGW_MOD_ID)
705 			mod->modfunc[modidx++] = mod_or_id;
706 
707 		if (mb.modtype & CGW_MOD_DLC)
708 			mod->modfunc[modidx++] = mod_or_dlc;
709 
710 		if (mb.modtype & CGW_MOD_DATA)
711 			mod->modfunc[modidx++] = mod_or_data;
712 	}
713 
714 	if (tb[CGW_MOD_XOR]) {
715 		nla_memcpy(&mb, tb[CGW_MOD_XOR], CGW_MODATTR_LEN);
716 
717 		canframecpy(&mod->modframe.xor, &mb.cf);
718 		mod->modtype.xor = mb.modtype;
719 
720 		if (mb.modtype & CGW_MOD_ID)
721 			mod->modfunc[modidx++] = mod_xor_id;
722 
723 		if (mb.modtype & CGW_MOD_DLC)
724 			mod->modfunc[modidx++] = mod_xor_dlc;
725 
726 		if (mb.modtype & CGW_MOD_DATA)
727 			mod->modfunc[modidx++] = mod_xor_data;
728 	}
729 
730 	if (tb[CGW_MOD_SET]) {
731 		nla_memcpy(&mb, tb[CGW_MOD_SET], CGW_MODATTR_LEN);
732 
733 		canframecpy(&mod->modframe.set, &mb.cf);
734 		mod->modtype.set = mb.modtype;
735 
736 		if (mb.modtype & CGW_MOD_ID)
737 			mod->modfunc[modidx++] = mod_set_id;
738 
739 		if (mb.modtype & CGW_MOD_DLC)
740 			mod->modfunc[modidx++] = mod_set_dlc;
741 
742 		if (mb.modtype & CGW_MOD_DATA)
743 			mod->modfunc[modidx++] = mod_set_data;
744 	}
745 
746 	/* check for checksum operations after CAN frame modifications */
747 	if (modidx) {
748 
749 		if (tb[CGW_CS_CRC8]) {
750 			struct cgw_csum_crc8 *c = nla_data(tb[CGW_CS_CRC8]);
751 
752 			err = cgw_chk_csum_parms(c->from_idx, c->to_idx,
753 						 c->result_idx);
754 			if (err)
755 				return err;
756 
757 			nla_memcpy(&mod->csum.crc8, tb[CGW_CS_CRC8],
758 				   CGW_CS_CRC8_LEN);
759 
760 			/*
761 			 * select dedicated processing function to reduce
762 			 * runtime operations in receive hot path.
763 			 */
764 			if (c->from_idx < 0 || c->to_idx < 0 ||
765 			    c->result_idx < 0)
766 				mod->csumfunc.crc8 = cgw_csum_crc8_rel;
767 			else if (c->from_idx <= c->to_idx)
768 				mod->csumfunc.crc8 = cgw_csum_crc8_pos;
769 			else
770 				mod->csumfunc.crc8 = cgw_csum_crc8_neg;
771 		}
772 
773 		if (tb[CGW_CS_XOR]) {
774 			struct cgw_csum_xor *c = nla_data(tb[CGW_CS_XOR]);
775 
776 			err = cgw_chk_csum_parms(c->from_idx, c->to_idx,
777 						 c->result_idx);
778 			if (err)
779 				return err;
780 
781 			nla_memcpy(&mod->csum.xor, tb[CGW_CS_XOR],
782 				   CGW_CS_XOR_LEN);
783 
784 			/*
785 			 * select dedicated processing function to reduce
786 			 * runtime operations in receive hot path.
787 			 */
788 			if (c->from_idx < 0 || c->to_idx < 0 ||
789 			    c->result_idx < 0)
790 				mod->csumfunc.xor = cgw_csum_xor_rel;
791 			else if (c->from_idx <= c->to_idx)
792 				mod->csumfunc.xor = cgw_csum_xor_pos;
793 			else
794 				mod->csumfunc.xor = cgw_csum_xor_neg;
795 		}
796 
797 		if (tb[CGW_MOD_UID]) {
798 			nla_memcpy(&mod->uid, tb[CGW_MOD_UID], sizeof(u32));
799 		}
800 	}
801 
802 	if (gwtype == CGW_TYPE_CAN_CAN) {
803 
804 		/* check CGW_TYPE_CAN_CAN specific attributes */
805 
806 		struct can_can_gw *ccgw = (struct can_can_gw *)gwtypeattr;
807 		memset(ccgw, 0, sizeof(*ccgw));
808 
809 		/* check for can_filter in attributes */
810 		if (tb[CGW_FILTER])
811 			nla_memcpy(&ccgw->filter, tb[CGW_FILTER],
812 				   sizeof(struct can_filter));
813 
814 		err = -ENODEV;
815 
816 		/* specifying two interfaces is mandatory */
817 		if (!tb[CGW_SRC_IF] || !tb[CGW_DST_IF])
818 			return err;
819 
820 		ccgw->src_idx = nla_get_u32(tb[CGW_SRC_IF]);
821 		ccgw->dst_idx = nla_get_u32(tb[CGW_DST_IF]);
822 
823 		/* both indices set to 0 for flushing all routing entries */
824 		if (!ccgw->src_idx && !ccgw->dst_idx)
825 			return 0;
826 
827 		/* only one index set to 0 is an error */
828 		if (!ccgw->src_idx || !ccgw->dst_idx)
829 			return err;
830 	}
831 
832 	/* add the checks for other gwtypes here */
833 
834 	return 0;
835 }
836 
cgw_create_job(struct sk_buff * skb,struct nlmsghdr * nlh)837 static int cgw_create_job(struct sk_buff *skb,  struct nlmsghdr *nlh)
838 {
839 	struct rtcanmsg *r;
840 	struct cgw_job *gwj;
841 	struct cf_mod mod;
842 	struct can_can_gw ccgw;
843 	u8 limhops = 0;
844 	int err = 0;
845 
846 	if (!netlink_capable(skb, CAP_NET_ADMIN))
847 		return -EPERM;
848 
849 	if (nlmsg_len(nlh) < sizeof(*r))
850 		return -EINVAL;
851 
852 	r = nlmsg_data(nlh);
853 	if (r->can_family != AF_CAN)
854 		return -EPFNOSUPPORT;
855 
856 	/* so far we only support CAN -> CAN routings */
857 	if (r->gwtype != CGW_TYPE_CAN_CAN)
858 		return -EINVAL;
859 
860 	err = cgw_parse_attr(nlh, &mod, CGW_TYPE_CAN_CAN, &ccgw, &limhops);
861 	if (err < 0)
862 		return err;
863 
864 	if (mod.uid) {
865 
866 		ASSERT_RTNL();
867 
868 		/* check for updating an existing job with identical uid */
869 		hlist_for_each_entry(gwj, &cgw_list, list) {
870 
871 			if (gwj->mod.uid != mod.uid)
872 				continue;
873 
874 			/* interfaces & filters must be identical */
875 			if (memcmp(&gwj->ccgw, &ccgw, sizeof(ccgw)))
876 				return -EINVAL;
877 
878 			/* update modifications with disabled softirq & quit */
879 			local_bh_disable();
880 			memcpy(&gwj->mod, &mod, sizeof(mod));
881 			local_bh_enable();
882 			return 0;
883 		}
884 	}
885 
886 	/* ifindex == 0 is not allowed for job creation */
887 	if (!ccgw.src_idx || !ccgw.dst_idx)
888 		return -ENODEV;
889 
890 	gwj = kmem_cache_alloc(cgw_cache, GFP_KERNEL);
891 	if (!gwj)
892 		return -ENOMEM;
893 
894 	gwj->handled_frames = 0;
895 	gwj->dropped_frames = 0;
896 	gwj->deleted_frames = 0;
897 	gwj->flags = r->flags;
898 	gwj->gwtype = r->gwtype;
899 	gwj->limit_hops = limhops;
900 
901 	/* insert already parsed information */
902 	memcpy(&gwj->mod, &mod, sizeof(mod));
903 	memcpy(&gwj->ccgw, &ccgw, sizeof(ccgw));
904 
905 	err = -ENODEV;
906 
907 	gwj->src.dev = __dev_get_by_index(&init_net, gwj->ccgw.src_idx);
908 
909 	if (!gwj->src.dev)
910 		goto out;
911 
912 	if (gwj->src.dev->type != ARPHRD_CAN)
913 		goto out;
914 
915 	gwj->dst.dev = __dev_get_by_index(&init_net, gwj->ccgw.dst_idx);
916 
917 	if (!gwj->dst.dev)
918 		goto out;
919 
920 	if (gwj->dst.dev->type != ARPHRD_CAN)
921 		goto out;
922 
923 	ASSERT_RTNL();
924 
925 	err = cgw_register_filter(gwj);
926 	if (!err)
927 		hlist_add_head_rcu(&gwj->list, &cgw_list);
928 out:
929 	if (err)
930 		kmem_cache_free(cgw_cache, gwj);
931 
932 	return err;
933 }
934 
cgw_remove_all_jobs(void)935 static void cgw_remove_all_jobs(void)
936 {
937 	struct cgw_job *gwj = NULL;
938 	struct hlist_node *nx;
939 
940 	ASSERT_RTNL();
941 
942 	hlist_for_each_entry_safe(gwj, nx, &cgw_list, list) {
943 		hlist_del(&gwj->list);
944 		cgw_unregister_filter(gwj);
945 		synchronize_rcu();
946 		kmem_cache_free(cgw_cache, gwj);
947 	}
948 }
949 
cgw_remove_job(struct sk_buff * skb,struct nlmsghdr * nlh)950 static int cgw_remove_job(struct sk_buff *skb, struct nlmsghdr *nlh)
951 {
952 	struct cgw_job *gwj = NULL;
953 	struct hlist_node *nx;
954 	struct rtcanmsg *r;
955 	struct cf_mod mod;
956 	struct can_can_gw ccgw;
957 	u8 limhops = 0;
958 	int err = 0;
959 
960 	if (!netlink_capable(skb, CAP_NET_ADMIN))
961 		return -EPERM;
962 
963 	if (nlmsg_len(nlh) < sizeof(*r))
964 		return -EINVAL;
965 
966 	r = nlmsg_data(nlh);
967 	if (r->can_family != AF_CAN)
968 		return -EPFNOSUPPORT;
969 
970 	/* so far we only support CAN -> CAN routings */
971 	if (r->gwtype != CGW_TYPE_CAN_CAN)
972 		return -EINVAL;
973 
974 	err = cgw_parse_attr(nlh, &mod, CGW_TYPE_CAN_CAN, &ccgw, &limhops);
975 	if (err < 0)
976 		return err;
977 
978 	/* two interface indices both set to 0 => remove all entries */
979 	if (!ccgw.src_idx && !ccgw.dst_idx) {
980 		cgw_remove_all_jobs();
981 		return 0;
982 	}
983 
984 	err = -EINVAL;
985 
986 	ASSERT_RTNL();
987 
988 	/* remove only the first matching entry */
989 	hlist_for_each_entry_safe(gwj, nx, &cgw_list, list) {
990 
991 		if (gwj->flags != r->flags)
992 			continue;
993 
994 		if (gwj->limit_hops != limhops)
995 			continue;
996 
997 		/* we have a match when uid is enabled and identical */
998 		if (gwj->mod.uid || mod.uid) {
999 			if (gwj->mod.uid != mod.uid)
1000 				continue;
1001 		} else {
1002 			/* no uid => check for identical modifications */
1003 			if (memcmp(&gwj->mod, &mod, sizeof(mod)))
1004 				continue;
1005 		}
1006 
1007 		/* if (r->gwtype == CGW_TYPE_CAN_CAN) - is made sure here */
1008 		if (memcmp(&gwj->ccgw, &ccgw, sizeof(ccgw)))
1009 			continue;
1010 
1011 		hlist_del(&gwj->list);
1012 		cgw_unregister_filter(gwj);
1013 		synchronize_rcu();
1014 		kmem_cache_free(cgw_cache, gwj);
1015 		err = 0;
1016 		break;
1017 	}
1018 
1019 	return err;
1020 }
1021 
cgw_module_init(void)1022 static __init int cgw_module_init(void)
1023 {
1024 	/* sanitize given module parameter */
1025 	max_hops = clamp_t(unsigned int, max_hops, CGW_MIN_HOPS, CGW_MAX_HOPS);
1026 
1027 	pr_info("can: netlink gateway (rev " CAN_GW_VERSION ") max_hops=%d\n",
1028 		max_hops);
1029 
1030 	cgw_cache = kmem_cache_create("can_gw", sizeof(struct cgw_job),
1031 				      0, 0, NULL);
1032 
1033 	if (!cgw_cache)
1034 		return -ENOMEM;
1035 
1036 	/* set notifier */
1037 	notifier.notifier_call = cgw_notifier;
1038 	register_netdevice_notifier(&notifier);
1039 
1040 	if (__rtnl_register(PF_CAN, RTM_GETROUTE, NULL, cgw_dump_jobs, NULL)) {
1041 		unregister_netdevice_notifier(&notifier);
1042 		kmem_cache_destroy(cgw_cache);
1043 		return -ENOBUFS;
1044 	}
1045 
1046 	/* Only the first call to __rtnl_register can fail */
1047 	__rtnl_register(PF_CAN, RTM_NEWROUTE, cgw_create_job, NULL, NULL);
1048 	__rtnl_register(PF_CAN, RTM_DELROUTE, cgw_remove_job, NULL, NULL);
1049 
1050 	return 0;
1051 }
1052 
cgw_module_exit(void)1053 static __exit void cgw_module_exit(void)
1054 {
1055 	rtnl_unregister_all(PF_CAN);
1056 
1057 	unregister_netdevice_notifier(&notifier);
1058 
1059 	rtnl_lock();
1060 	cgw_remove_all_jobs();
1061 	rtnl_unlock();
1062 
1063 	rcu_barrier(); /* Wait for completion of call_rcu()'s */
1064 
1065 	kmem_cache_destroy(cgw_cache);
1066 }
1067 
1068 module_init(cgw_module_init);
1069 module_exit(cgw_module_exit);
1070